Skip to content

Commit c96e647

Browse files
committed
feat: implement the new golang 1.19 atomic types
1 parent c563000 commit c96e647

File tree

2 files changed

+7
-9
lines changed

2 files changed

+7
-9
lines changed

godoc.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,5 @@ Package r9e provides a collection of memory store containers.
55
66
* [MapKeyValue[K comparable, T any]](https://pkg.go.dev/github.com/slashdevops/r9e#MapKeyValue) using sync.RWMutex
77
* [SMapKeyValue[K comparable, T any]](https://pkg.go.dev/github.com/slashdevops/r9e#SMapKeyValue) using sync.Map
8-
98
*/
109
package r9e

smapkeyvalue.go

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ 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.
1212
type SMapKeyValue[K comparable, T any] struct {
13-
count uint64
13+
count atomic.Uint64
1414
data sync.Map
1515
}
1616

@@ -23,14 +23,13 @@ type skv[K comparable, T any] struct {
2323
// NewSMapKeyValue returns a new SMapKeyValue container.
2424
func NewSMapKeyValue[K comparable, T any]() *SMapKeyValue[K, T] {
2525
return &SMapKeyValue[K, T]{
26-
count: 0,
27-
data: sync.Map{},
26+
data: sync.Map{},
2827
}
2928
}
3029

3130
// Set sets the value associated with the key.
3231
func (r *SMapKeyValue[K, T]) Set(key K, value T) {
33-
atomic.AddUint64(&r.count, 1)
32+
r.count.Add(1)
3433
r.data.Store(key, value)
3534
}
3635

@@ -67,7 +66,7 @@ func (r *SMapKeyValue[K, T]) Get(key K) T {
6766
func (r *SMapKeyValue[K, T]) GetAnDelete(key K) (T, bool) {
6867
value, ok := r.data.LoadAndDelete(key)
6968
if ok {
70-
atomic.SwapUint64(&r.count, r.count-1)
69+
r.count.Swap(r.count.Load() - 1)
7170
}
7271

7372
switch value := value.(type) {
@@ -82,19 +81,19 @@ func (r *SMapKeyValue[K, T]) GetAnDelete(key K) (T, bool) {
8281
// Delete deletes the value associated with the key.
8382
func (r *SMapKeyValue[K, T]) Delete(key K) {
8483
if _, ok := r.data.LoadAndDelete(key); ok {
85-
atomic.SwapUint64(&r.count, r.count-1)
84+
r.count.Swap(r.count.Load() - 1)
8685
}
8786
}
8887

8988
// Clear deletes all key-value pairs stored in the container.
9089
func (r *SMapKeyValue[K, T]) Clear() {
9190
r.data = sync.Map{}
92-
atomic.SwapUint64(&r.count, 0)
91+
r.count.Swap(0)
9392
}
9493

9594
// Size returns the number of key-value pairs stored in the container.
9695
func (r *SMapKeyValue[K, T]) Size() int {
97-
return int(r.count)
96+
return int(r.count.Load())
9897
}
9998

10099
// IsEmpty returns true if the container is empty.

0 commit comments

Comments
 (0)