fix(coderd/util/syncmap): match sync.Map semantics in the typed wrapper (#27582)

Fixes CODAGT-869
This commit is contained in:
Mathias Fredriksson
2026-07-28 19:05:59 +03:00
committed by GitHub
parent 85984ff142
commit eb905702c8
2 changed files with 317 additions and 29 deletions
+28 -29
View File
@@ -15,42 +15,44 @@ func New[K, V any]() *Map[K, V] {
}
}
// cast converts a value returned by the underlying sync.Map to T. The
// map returns a nil `any` for a missing key, and for a present key whose
// interface-typed value is nil. Neither can be type-asserted, so both
// become the zero T, which is nil for interface types.
func cast[T any](v any) T {
if v == nil {
var empty T
return empty
}
//nolint:forcetypeassert // Only K and V values ever enter the map.
return v.(T)
}
func (m *Map[K, V]) Store(k K, v V) {
m.m.Store(k, v)
}
//nolint:forcetypeassert
func (m *Map[K, V]) Load(key K) (value V, ok bool) {
v, ok := m.m.Load(key)
if !ok {
var empty V
return empty, false
}
return v.(V), ok
return cast[V](v), ok
}
func (m *Map[K, V]) Delete(key K) {
m.m.Delete(key)
}
//nolint:forcetypeassert
func (m *Map[K, V]) LoadAndDelete(key K) (actual V, loaded bool) {
act, loaded := m.m.LoadAndDelete(key)
if !loaded {
var empty V
return empty, loaded
}
return act.(V), loaded
return cast[V](act), loaded
}
//nolint:forcetypeassert
// LoadOrStore returns the existing value for the key if present.
// Otherwise, it stores and returns the given value. The loaded result
// is true if the value was loaded, false if stored. As with sync.Map,
// actual is usable in both cases.
func (m *Map[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) {
act, loaded := m.m.LoadOrStore(key, value)
if !loaded {
var empty V
return empty, loaded
}
return act.(V), loaded
return cast[V](act), loaded
}
func (m *Map[K, V]) CompareAndSwap(key K, old V, newVal V) bool {
@@ -61,19 +63,16 @@ func (m *Map[K, V]) CompareAndDelete(key K, old V) (deleted bool) {
return m.m.CompareAndDelete(key, old)
}
//nolint:forcetypeassert
func (m *Map[K, V]) Swap(key K, value V) (previous any, loaded bool) {
previous, loaded = m.m.Swap(key, value)
if !loaded {
var empty V
return empty, loaded
}
return previous.(V), loaded
// Swap stores the given value for the key and returns the previous
// value if there was one. As with sync.Map, previous is the zero V when
// the key was absent.
func (m *Map[K, V]) Swap(key K, value V) (previous V, loaded bool) {
prev, loaded := m.m.Swap(key, value)
return cast[V](prev), loaded
}
//nolint:forcetypeassert
func (m *Map[K, V]) Range(f func(key K, value V) bool) {
m.m.Range(func(key, value interface{}) bool {
return f(key.(K), value.(V))
m.m.Range(func(key, value any) bool {
return f(cast[K](key), cast[V](value))
})
}