From 4204f3d06557f53e331c707d565042e41f908494 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Sun, 10 May 2026 10:18:38 -0700 Subject: [PATCH] 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. --- src/sync/map.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/sync/map.go b/src/sync/map.go index 8b5c0cff7..76bdd8380 100644 --- a/src/sync/map.go +++ b/src/sync/map.go @@ -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 +}