Skip to content

Commit 5974a31

Browse files
authored
Merge pull request #29 from semihbkgr/json-encoding
add json encoding
2 parents ba78b2b + 03a17fb commit 5974a31

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

map.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package haxmap
22

33
import (
4+
"encoding/json"
45
"reflect"
56
"sort"
67
"strconv"
@@ -344,6 +345,28 @@ func (m *Map[K, V]) Fillrate() uintptr {
344345
return (data.count.Load() * 100) / uintptr(len(data.index))
345346
}
346347

348+
// MarshalJSON implements the json.Marshaler interface.
349+
func (m *Map[K, V]) MarshalJSON() ([]byte, error) {
350+
gomap := make(map[K]V)
351+
for i := m.listHead.next(); i != nil; i = i.next() {
352+
gomap[i.key] = *i.value.Load()
353+
}
354+
return json.Marshal(gomap)
355+
}
356+
357+
// UnmarshalJSON implements the json.Unmarshaler interface.
358+
func (m *Map[K, V]) UnmarshalJSON(i []byte) error {
359+
gomap := make(map[K]V)
360+
err := json.Unmarshal(i, &gomap)
361+
if err != nil {
362+
return err
363+
}
364+
for k, v := range gomap {
365+
m.Set(k, v)
366+
}
367+
return nil
368+
}
369+
347370
// allocate map with the given size
348371
func (m *Map[K, V]) allocate(newSize uintptr) {
349372
if m.resizing.CompareAndSwap(notResizing, resizingInProgress) {

0 commit comments

Comments
 (0)