@@ -10,8 +10,8 @@ import (
1010// SMapKeyValue is a generic key-value store container that is thread-safe.
1111// This use a golang native sync.Map data structure as underlying data structure.
1212type SMapKeyValue [K comparable , T any ] struct {
13- size uint64
14- data sync.Map
13+ count atomic. Uint64
14+ data sync.Map
1515}
1616
1717// skv is a helper struct to sort the values of the SMapKeyValue container.
@@ -23,14 +23,13 @@ type skv[K comparable, T any] struct {
2323// NewSMapKeyValue returns a new SMapKeyValue container.
2424func NewSMapKeyValue [K comparable , T any ]() * SMapKeyValue [K , T ] {
2525 return & SMapKeyValue [K , T ]{
26- size : 0 ,
2726 data : sync.Map {},
2827 }
2928}
3029
3130// Set sets the value associated with the key.
3231func (r * SMapKeyValue [K , T ]) Set (key K , value T ) {
33- atomic . AddUint64 ( & r . size , 1 )
32+ r . count . Add ( 1 )
3433 r .data .Store (key , value )
3534}
3635
@@ -67,7 +66,8 @@ func (r *SMapKeyValue[K, T]) Get(key K) T {
6766func (r * SMapKeyValue [K , T ]) GetAnDelete (key K ) (T , bool ) {
6867 value , ok := r .data .LoadAndDelete (key )
6968 if ok {
70- atomic .SwapUint64 (& r .size , r .size - 1 )
69+ r .count .Swap (r .count .Load () - 1 )
70+
7171 }
7272
7373 switch value := value .(type ) {
@@ -82,19 +82,19 @@ func (r *SMapKeyValue[K, T]) GetAnDelete(key K) (T, bool) {
8282// Delete deletes the value associated with the key.
8383func (r * SMapKeyValue [K , T ]) Delete (key K ) {
8484 if _ , ok := r .data .LoadAndDelete (key ); ok {
85- atomic . SwapUint64 ( & r . size , r . size - 1 )
85+ r . count . Swap ( r . count . Load () - 1 )
8686 }
8787}
8888
8989// Clear deletes all key-value pairs stored in the container.
9090func (r * SMapKeyValue [K , T ]) Clear () {
9191 r .data = sync.Map {}
92- atomic . SwapUint64 ( & r . size , 0 )
92+ r . count . Swap ( 0 )
9393}
9494
9595// Size returns the number of key-value pairs stored in the container.
9696func (r * SMapKeyValue [K , T ]) Size () int {
97- return int (r .size )
97+ return int (r .count . Load () )
9898}
9999
100100// IsEmpty returns true if the container is empty.
0 commit comments