github.com/haraldrudell/parl@v0.4.176/parli/if-map.go (about) 1 /* 2 © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package parli 7 8 const ( 9 MapDeleteWithZeroValue = true 10 MapClearUsingRange = true 11 ) 12 13 // ThreadSafeMap is a one-liner thread-safe mapping. 14 // - pmaps.NewRWMap[K comparable, V any]() 15 type ThreadSafeMap[K comparable, V any] interface { 16 // Get returns the value mapped by key or the V zero-value otherwise. 17 // - the ok return value is true if a mapping was found. 18 // - O(1) 19 Get(key K) (value V, ok bool) 20 // GetOrCreate returns an item from the map if it exists otherwise creates it. 21 // - newV or makeV are invoked in the critical section, ie. these functions 22 // may not access the map or deadlock 23 // - if a key is mapped, its value is returned 24 // - otherwise, if newV and makeV are both nil, nil is returned. 25 // - otherwise, if newV is present, it is invoked to return a pointer ot a value. 26 // A nil return value from newV causes panic. A new mapping is created using 27 // the value pointed to by the newV return value. 28 // - otherwise, a mapping is created using whatever makeV returns 29 // - newV and makeV may not access the map. 30 // The map’s write lock is held during their execution 31 // - GetOrCreate is an atomic, thread-safe operation 32 // - value insert is O(log n) 33 GetOrCreate( 34 key K, 35 newV func() (value *V), 36 makeV func() (value V), 37 ) (value V, ok bool) 38 // Put saves or replaces a mapping 39 Put(key K, value V) 40 // Putif is conditional Put depending on the return value from the putIf function. 41 // - if key does not exist in the map, the put is carried out and wasNewKey is true 42 // - if key exists and putIf is nil or returns true, the put is carried out and wasNewKey is false 43 // - if key exists and putIf returns false, the put is not carried out and wasNewKey is false 44 // - during PutIf, the map cannot be accessed and the map’s write-lock is held 45 // - PutIf is an atomic, thread-safe operation 46 PutIf(key K, value V, putIf func(value V) (doPut bool)) (wasNewKey bool) 47 // Delete removes mapping using key K. 48 // - if key K is not mapped, the map is unchanged. 49 // - O(log n) 50 // - if useZeroValue present and parli.MapDeleteWithZeroValue or true, 51 // the deleted value is fiorst assigned the zero-value 52 Delete(key K, useZeroValue ...bool) 53 // Clear empties the map 54 // - if useRange is present and parli.MapClearUsingRange or true, 55 // delete using range operations setting each item to zero-value 56 // - otherwise, clear by replacing with new map 57 Clear(useRange ...bool) 58 // Length returns the number of mappings 59 Length() (length int) 60 // Clone returns a shallow clone of the map 61 Clone() (clone ThreadSafeMap[K, V]) 62 // List provides the mapped values, undefined ordering 63 // - O(n) 64 List(n ...int) (list []V) 65 }