Debian Codegraph @

maps/linkedhashmap/serialization.go

raw symbols SCIP
1 // Copyright (c) 2015, Emir Pasic. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package linkedhashmap
6
7 import (
8 "bytes"
9 "cmp"
10 "encoding/json"
11 "slices"
12
13 "github.com/emirpasic/gods/v2/containers"
14 )
15
16 // Assert Serialization implementation
17 var _ containers.JSONSerializer = (*Map[string, int])(nil)
18 var _ containers.JSONDeserializer = (*Map[string, int])(nil)
19
20 // ToJSON outputs the JSON representation of map.
21 func (m *Map[K, V]) ToJSON() ([]byte, error) {
22 var b []byte
23 buf := bytes.NewBuffer(b)
24
25 buf.WriteRune('{')
26
27 it := m.Iterator()
28 lastIndex := m.Size() - 1
29 index := 0
30
31 for it.Next() {
32 km, err := json.Marshal(it.Key())
33 if err != nil {
34 return nil, err
35 }
36 buf.Write(km)
37
38 buf.WriteRune(':')
39
40 vm, err := json.Marshal(it.Value())
41 if err != nil {
42 return nil, err
43 }
44 buf.Write(vm)
45
46 if index != lastIndex {
47 buf.WriteRune(',')
48 }
49
50 index++
51 }
52
53 buf.WriteRune('}')
54
55 return buf.Bytes(), nil
56 }
57
58 // FromJSON populates map from the input JSON representation.
59 //func (m *Map[K, V]) FromJSON(data []byte) error {
60 // elements := make(map[string]interface{})
61 // err := json.Unmarshal(data, &elements)
62 // if err == nil {
63 // m.Clear()
64 // for key, value := range elements {
65 // m.Put(key, value)
66 // }
67 // }
68 // return err
69 //}
70
71 // FromJSON populates map from the input JSON representation.
72 func (m *Map[K, V]) FromJSON(data []byte) error {
73 elements := make(map[K]V)
74 err := json.Unmarshal(data, &elements)
75 if err != nil {
76 return err
77 }
78
79 index := make(map[K]int)
80 var keys []K
81 for key := range elements {
82 keys = append(keys, key)
83 esc, _ := json.Marshal(key)
84 index[key] = bytes.Index(data, esc)
85 }
86
87 byIndex := func(key1, key2 K) int {
88 return cmp.Compare(index[key1], index[key2])
89 }
90
91 slices.SortFunc(keys, byIndex)
92
93 m.Clear()
94
95 for _, key := range keys {
96 m.Put(key, elements[key])
97 }
98
99 return nil
100 }
101
102 // UnmarshalJSON @implements json.Unmarshaler
103 func (m *Map[K, V]) UnmarshalJSON(bytes []byte) error {
104 return m.FromJSON(bytes)
105 }
106
107 // MarshalJSON @implements json.Marshaler
108 func (m *Map[K, V]) MarshalJSON() ([]byte, error) {
109 return m.ToJSON()
110 }