github.com/goplusjs/gopherjs@v1.2.6-0.20211206034512-f187917453b8/nosync/map.go (about) 1 package nosync 2 3 // Map is a concurrent map with amortized-constant-time loads, stores, and deletes. 4 // It is safe for multiple goroutines to call a Map's methods concurrently. 5 // 6 // The zero Map is valid and empty. 7 // 8 // A Map must not be copied after first use. 9 type Map struct { 10 m map[interface{}]interface{} 11 } 12 13 // Load returns the value stored in the map for a key, or nil if no 14 // value is present. 15 // The ok result indicates whether value was found in the map. 16 func (m *Map) Load(key interface{}) (value interface{}, ok bool) { 17 value, ok = m.m[key] 18 return value, ok 19 } 20 21 // Store sets the value for a key. 22 func (m *Map) Store(key, value interface{}) { 23 if m.m == nil { 24 m.m = make(map[interface{}]interface{}) 25 } 26 m.m[key] = value 27 } 28 29 // LoadOrStore returns the existing value for the key if present. 30 // Otherwise, it stores and returns the given value. 31 // The loaded result is true if the value was loaded, false if stored. 32 func (m *Map) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool) { 33 if value, ok := m.m[key]; ok { 34 return value, true 35 } 36 if m.m == nil { 37 m.m = make(map[interface{}]interface{}) 38 } 39 m.m[key] = value 40 return value, false 41 } 42 43 // Delete deletes the value for a key. 44 func (m *Map) Delete(key interface{}) { 45 if m.m == nil { 46 return 47 } 48 delete(m.m, key) 49 } 50 51 // Range calls f sequentially for each key and value present in the map. 52 // If f returns false, range stops the iteration. 53 // 54 // Range does not necessarily correspond to any consistent snapshot of the Map's 55 // contents: no key will be visited more than once, but if the value for any key 56 // is stored or deleted concurrently, Range may reflect any mapping for that key 57 // from any point during the Range call. 58 // 59 // Range may be O(N) with the number of elements in the map even if f returns 60 // false after a constant number of calls. 61 func (m *Map) Range(f func(key, value interface{}) bool) { 62 for k, v := range m.m { 63 if !f(k, v) { 64 break 65 } 66 } 67 }