• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2025 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package syncmap
16
17import "sync"
18
19// SyncMap is a wrapper around sync.Map that provides type safety via generics.
20type SyncMap[K comparable, V any] struct {
21	sync.Map
22}
23
24// Load returns the value stored in the map for a key, or the zero value if no
25// value is present.
26// The ok result indicates whether value was found in the map.
27func (m *SyncMap[K, V]) Load(key K) (value V, ok bool) {
28	v, ok := m.Map.Load(key)
29	if !ok {
30		return *new(V), false
31	}
32	return v.(V), true
33}
34
35// Store sets the value for a key.
36func (m *SyncMap[K, V]) Store(key K, value V) {
37	m.Map.Store(key, value)
38}
39
40// LoadOrStore returns the existing value for the key if present.
41// Otherwise, it stores and returns the given value.
42// The loaded result is true if the value was loaded, false if stored.
43func (m *SyncMap[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) {
44	v, loaded := m.Map.LoadOrStore(key, value)
45	return v.(V), loaded
46}
47
48func (m *SyncMap[K, V]) Range(f func(key K, value V) bool) {
49	m.Map.Range(func(k, v any) bool {
50		return f(k.(K), v.(V))
51	})
52}
53