11package ds
22
3+ import "sync"
4+
35// OrderedMap is a map with a deterministic iteration order
4- // this datastructure is not thread-safe
6+ // this datastructure is thread-safe
57type OrderedMap [T comparable , V any ] struct {
68 len int
79 keys map [T ]int
810 values []V
11+ mtx sync.RWMutex
912}
1013
1114// NewOrderedMap returns a new OrderedMap
@@ -17,6 +20,9 @@ func NewOrderedMap[T comparable, V any]() *OrderedMap[T, V] {
1720
1821// Put adds a key-value pair to the map
1922func (m * OrderedMap [T , V ]) Put (key T , val V ) {
23+ m .mtx .Lock ()
24+ defer m .mtx .Unlock ()
25+
2026 i , ok := m .keys [key ]
2127 if ok {
2228 m .values [i ] = val
@@ -33,6 +39,9 @@ func (m *OrderedMap[T, V]) Put(key T, val V) {
3339
3440// Get returns the value for a given key
3541func (m * OrderedMap [T , V ]) Get (key T ) (V , bool ) {
42+ m .mtx .RLock ()
43+ defer m .mtx .RUnlock ()
44+
3645 i , ok := m .keys [key ]
3746 if ! ok {
3847 var v V
@@ -43,12 +52,18 @@ func (m *OrderedMap[T, V]) Get(key T) (V, bool) {
4352
4453// Has returns true if the map contains the given key
4554func (m * OrderedMap [T , V ]) Has (key T ) bool {
55+ m .mtx .RLock ()
56+ defer m .mtx .RUnlock ()
57+
4658 _ , ok := m .keys [key ]
4759 return ok
4860}
4961
5062// Delete removes a key-value pair from the map
5163func (m * OrderedMap [T , V ]) Delete (key T ) {
64+ m .mtx .Lock ()
65+ defer m .mtx .Unlock ()
66+
5267 i , ok := m .keys [key ]
5368 if ! ok {
5469 return
@@ -63,11 +78,17 @@ func (m *OrderedMap[T, V]) Delete(key T) {
6378
6479// Values returns all values in the map
6580func (m * OrderedMap [T , V ]) Values () []V {
81+ m .mtx .RLock ()
82+ defer m .mtx .RUnlock ()
83+
6684 return append ([]V {}, m .values [0 :m .len ]... )
6785}
6886
6987// Keys returns all keys in the map
7088func (m * OrderedMap [T , V ]) Keys () []T {
89+ m .mtx .RLock ()
90+ defer m .mtx .RUnlock ()
91+
7192 keys := make ([]T , len (m .keys ))
7293 for k , v := range m .keys {
7394 keys [v ] = k
@@ -77,5 +98,8 @@ func (m *OrderedMap[T, V]) Keys() []T {
7798
7899// Len returns a number of the map
79100func (m * OrderedMap [T , V ]) Len () int {
101+ m .mtx .RLock ()
102+ defer m .mtx .RUnlock ()
103+
80104 return m .len
81105}
0 commit comments