Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map: Add .StoreMultiple and .StoreComplete methods #6

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion map.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,14 +111,52 @@ func (tm *Map[K, V]) Load(key K) (value V, ok bool) {
return DeepCopy(ret), true
}

// Store sets a key sets the value for a key. This panics if .Close() has already been called.
// Store sets the value for a key. This panics if .Close() has already been called.
func (tm *Map[K, V]) Store(key K, val V) {
tm.lock.Lock()
defer tm.lock.Unlock()

tm.unlockedStore(key, val)
}

// StoreMultiple sets multiple entries in the map "at once".
//
// This is particularly useful when first initializing the Map, so that a half-initialized state
// cannot be observed. The ordering of the .Updates in the resulting Snapshot is undefined. This
// panics if .Close() has already been called.
//
// Use StoreComplete if you wish for values not in the argument to be deleted.
func (tm *Map[K, V]) StoreMultiple(kvs map[K]V) {
tm.lock.Lock()
defer tm.lock.Unlock()

for k, v := range kvs {
tm.unlockedStore(k, v)
}
}

// StoreComplete completely replaces the map "at once"; storing or deleting entries from the map as
// necessary to have it match the argument.
//
// This is particularly useful when first initializing the Map, so that a half-initialized state
// cannot be observed. The ordering of the .Updates in the resulting Snapshot is undefined. This
// panics if .Close() has already been called.
//
// Use StoreMultiple if you do not wish for values not n the argument to be deleted.
func (tm *Map[K, V]) StoreComplete(kvs map[K]V) {
tm.lock.Lock()
defer tm.lock.Unlock()

for k, v := range kvs {
tm.unlockedStore(k, v)
}
for k := range tm.value {
if _, keep := kvs[k]; !keep {
tm.unlockedDelete(k)
}
}
}

// 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.
//
Expand Down