Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/sync/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,34 @@ func (m *Map) Swap(key, value any) (previous any, loaded bool) {
m.m[key] = value
return
}

// CompareAndSwap swaps the old and new values for an existing key if the value
// stored in the map is equal to old.
func (m *Map) CompareAndSwap(key, old, new any) (swapped bool) {
m.lock.Lock()
defer m.lock.Unlock()
if m.m == nil {
return false
}
value, ok := m.m[key]
if !ok || value != old {
return false
}
m.m[key] = new
return true
}

// CompareAndDelete deletes the entry for key if its value is equal to old.
func (m *Map) CompareAndDelete(key, old any) (deleted bool) {
m.lock.Lock()
defer m.lock.Unlock()
if m.m == nil {
return false
}
value, ok := m.m[key]
if !ok || value != old {
return false
}
delete(m.m, key)
return true
}
Loading