Skip to content

Commit

Permalink
feat: add marshal unmarshal json support
Browse files Browse the repository at this point in the history
  • Loading branch information
mhmtszr committed Apr 22, 2024
1 parent 4d04771 commit ee9df32
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
23 changes: 23 additions & 0 deletions concurrent_swiss_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package csmap

import (
"context"
"encoding/json"
"sync"

"github.com/mhmtszr/concurrent-swiss-map/maphash"
Expand Down Expand Up @@ -184,6 +185,28 @@ func (m *CsMap[K, V]) Range(f func(key K, value V) (stop bool)) {
listenCompleted.Wait()
}

func (m *CsMap[K, V]) MarshalJSON() ([]byte, error) {
tmp := make(map[K]V, m.Count())
m.Range(func(key K, value V) (stop bool) {
tmp[key] = value
return false
})
return json.Marshal(tmp)
}

func (m *CsMap[K, V]) UnmarshalJSON(b []byte) error {
tmp := make(map[K]V, m.Count())

if err := json.Unmarshal(b, &tmp); err != nil {
return err
}

for key, val := range tmp {
m.Store(key, val)
}
return nil
}

func (m *CsMap[K, V]) produce(ctx context.Context, ch chan Tuple[K, V]) {
var wg sync.WaitGroup
wg.Add(len(m.shards))
Expand Down
21 changes: 21 additions & 0 deletions concurrent_swiss_map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,27 @@ func TestDeleteFromRange(t *testing.T) {
}
}

func TestMarshal(t *testing.T) {
myMap := csmap.Create[string, int](
csmap.WithSize[string, int](1024),
)

myMap.Store("aaa", 10)
myMap.Store("aab", 11)

b, _ := myMap.MarshalJSON()

newMap := csmap.Create[string, int](
csmap.WithSize[string, int](1024),
)

_ = newMap.UnmarshalJSON(b)

if myMap.Count() != 2 || !myMap.Has("aaa") || !myMap.Has("aab") {
t.Fatal("count should be 2 after unmarshal")
}
}

func TestBasicConcurrentWriteDeleteCount(t *testing.T) {
myMap := csmap.Create[int, string](
csmap.WithShardCount[int, string](32),
Expand Down

0 comments on commit ee9df32

Please sign in to comment.