Skip to content

Commit 9e446d2

Browse files
committed
sync: add Map.CompareAndSwap and Map.CompareAndDelete
These methods were added in Go 1.20 but were missing from TinyGo's sync.Map implementation, causing compilation failures for code that uses them. The implementation follows the same lock-based approach as the rest of TinyGo's sync.Map.
1 parent 1a1506e commit 9e446d2

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

src/sync/map.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,3 +82,34 @@ func (m *Map) Swap(key, value any) (previous any, loaded bool) {
8282
m.m[key] = value
8383
return
8484
}
85+
86+
// CompareAndSwap swaps the old and new values for an existing key if the value
87+
// stored in the map is equal to old.
88+
func (m *Map) CompareAndSwap(key, old, new any) (swapped bool) {
89+
m.lock.Lock()
90+
defer m.lock.Unlock()
91+
if m.m == nil {
92+
return false
93+
}
94+
value, ok := m.m[key]
95+
if !ok || value != old {
96+
return false
97+
}
98+
m.m[key] = new
99+
return true
100+
}
101+
102+
// CompareAndDelete deletes the entry for key if its value is equal to old.
103+
func (m *Map) CompareAndDelete(key, old any) (deleted bool) {
104+
m.lock.Lock()
105+
defer m.lock.Unlock()
106+
if m.m == nil {
107+
return false
108+
}
109+
value, ok := m.m[key]
110+
if !ok || value != old {
111+
return false
112+
}
113+
delete(m.m, key)
114+
return true
115+
}

0 commit comments

Comments
 (0)