Skip to content

Commit

Permalink
fix: make OrderedMap thread-safe
Browse files Browse the repository at this point in the history
  • Loading branch information
lklimek committed Dec 11, 2023
1 parent 2802490 commit 158727c
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
26 changes: 25 additions & 1 deletion libs/ds/ordered_map.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package ds

import "sync"

// OrderedMap is a map with a deterministic iteration order
// this datastructure is not thread-safe
// this datastructure is thread-safe
type OrderedMap[T comparable, V any] struct {
len int
keys map[T]int
values []V
mtx sync.RWMutex
}

// NewOrderedMap returns a new OrderedMap
Expand All @@ -17,6 +20,9 @@ func NewOrderedMap[T comparable, V any]() *OrderedMap[T, V] {

// Put adds a key-value pair to the map
func (m *OrderedMap[T, V]) Put(key T, val V) {
m.mtx.Lock()
defer m.mtx.Unlock()

i, ok := m.keys[key]
if ok {
m.values[i] = val
Expand All @@ -33,6 +39,9 @@ func (m *OrderedMap[T, V]) Put(key T, val V) {

// Get returns the value for a given key
func (m *OrderedMap[T, V]) Get(key T) (V, bool) {
m.mtx.RLock()
defer m.mtx.RUnlock()

i, ok := m.keys[key]
if !ok {
var v V
Expand All @@ -43,12 +52,18 @@ func (m *OrderedMap[T, V]) Get(key T) (V, bool) {

// Has returns true if the map contains the given key
func (m *OrderedMap[T, V]) Has(key T) bool {
m.mtx.RLock()
defer m.mtx.RUnlock()

_, ok := m.keys[key]
return ok
}

// Delete removes a key-value pair from the map
func (m *OrderedMap[T, V]) Delete(key T) {
m.mtx.Lock()
defer m.mtx.Unlock()

i, ok := m.keys[key]
if !ok {
return
Expand All @@ -63,11 +78,17 @@ func (m *OrderedMap[T, V]) Delete(key T) {

// Values returns all values in the map
func (m *OrderedMap[T, V]) Values() []V {
m.mtx.RLock()
defer m.mtx.RUnlock()

return append([]V{}, m.values[0:m.len]...)
}

// Keys returns all keys in the map
func (m *OrderedMap[T, V]) Keys() []T {
m.mtx.RLock()
defer m.mtx.RUnlock()

keys := make([]T, len(m.keys))
for k, v := range m.keys {
keys[v] = k
Expand All @@ -77,5 +98,8 @@ func (m *OrderedMap[T, V]) Keys() []T {

// Len returns a number of the map
func (m *OrderedMap[T, V]) Len() int {
m.mtx.RLock()
defer m.mtx.RUnlock()

return m.len
}
19 changes: 19 additions & 0 deletions libs/ds/ordered_map_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package ds

import (
"strconv"
"sync"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -40,3 +42,20 @@ func TestOrderedMap(t *testing.T) {
// delete unknown key
om.Delete("c")
}

// / Run TestOrderedMap in parallel
func TestOrderedMapMultithread(t *testing.T) {
threads := 100

wg := sync.WaitGroup{}
wg.Add(threads)

for i := 0; i < threads; i++ {
go func(id int) {
t.Run(strconv.FormatInt(int64(id), 10), TestOrderedMap)
wg.Done()
}(i)
}

wg.Wait()
}

0 comments on commit 158727c

Please sign in to comment.