-
Notifications
You must be signed in to change notification settings - Fork 0
/
typedorderedmap.go
74 lines (57 loc) · 1.22 KB
/
typedorderedmap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package orderedmapjson
import (
"bytes"
"encoding/json"
"fmt"
)
type TypedOrderedMap[V any] struct {
*orderedMap[V]
}
func NewTypedOrderedMap[V any]() *TypedOrderedMap[V] {
return &TypedOrderedMap[V]{
orderedMap: newOrderedMap[V](),
}
}
func NewTypedOrderedMapWithCapacity[V any](capacity int) *TypedOrderedMap[V] {
return &TypedOrderedMap[V]{
orderedMap: newOrderedMapWithCapacity[V](capacity),
}
}
func (m *TypedOrderedMap[V]) UnmarshalJSON(b []byte) error {
if m.orderedMap == nil {
m.orderedMap = newOrderedMap[V]()
}
decoder := json.NewDecoder(bytes.NewReader(b))
// Skip '{'
token, err := decoder.Token()
if err != nil {
return err
}
if token != json.Delim('{') {
return fmt.Errorf("expected '{' but got %v", token)
}
for {
token, err := decoder.Token()
if err != nil {
return err
}
// Reached end of map
if token == json.Delim('}') {
return nil
}
key, ok := token.(string)
if !ok {
return fmt.Errorf("unexpected key type: %T", token)
}
var value V
if err := decoder.Decode(&value); err != nil {
return err
}
m.Set(key, value)
}
}
func (m *TypedOrderedMap[V]) Copy() *TypedOrderedMap[V] {
return &TypedOrderedMap[V]{
orderedMap: m.orderedMap.Copy(),
}
}