refactored Record.data and Record.expand to be concurrent safe

This commit is contained in:
Gani Georgiev
2023-01-25 22:39:42 +02:00
parent 39df263a03
commit ae371e8481
38 changed files with 313 additions and 88 deletions
+43 -2
View File
@@ -8,9 +8,36 @@ type Store[T any] struct {
data map[string]T
}
// New creates a new Store[T] instance.
// New creates a new Store[T] instance with a shallow copy of the provided data (if any).
func New[T any](data map[string]T) *Store[T] {
return &Store[T]{data: data}
s := &Store[T]{}
s.Reset(data)
return s
}
// Reset clears the store and replaces the store data with a
// shallow copy of the provided newData.
func (s *Store[T]) Reset(newData map[string]T) {
s.mux.Lock()
defer s.mux.Unlock()
var clone = make(map[string]T, len(newData))
for k, v := range newData {
clone[k] = v
}
s.data = clone
}
// Length returns the current number of elements in the store.
func (s *Store[T]) Length() int {
s.mux.RLock()
defer s.mux.RUnlock()
return len(s.data)
}
// RemoveAll removes all the existing store entries.
@@ -51,6 +78,20 @@ func (s *Store[T]) Get(key string) T {
return s.data[key]
}
// GetAll returns a shallow copy of the current store data.
func (s *Store[T]) GetAll() map[string]T {
s.mux.RLock()
defer s.mux.RUnlock()
var clone = make(map[string]T, len(s.data))
for k, v := range s.data {
clone[k] = v
}
return clone
}
// Set sets (or overwrite if already exist) a new value for key.
func (s *Store[T]) Set(key string, value T) {
s.mux.Lock()