-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmap.go
103 lines (93 loc) · 1.79 KB
/
map.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package openapi
import (
"bytes"
"encoding/json"
"reflect"
"github.com/chanced/jsonx"
"github.com/tidwall/gjson"
)
type KeyValue[V any] struct {
Key Text
Value V
}
type Map[T any] struct {
Items []KeyValue[T]
}
func (m Map[T]) Get(key Text) (T, bool) {
for _, v := range m.Items {
if v.Key == key {
return v.Value, true
}
}
var t T
return t, false
}
func (m Map[T]) Has(key Text) bool {
for _, v := range m.Items {
if v.Key == key {
return true
}
}
return false
}
func (m *Map[T]) Set(key Text, value T) {
if m == nil {
*m = Map[T]{}
}
for i, v := range m.Items {
if v.Key == key {
m.Items[i].Value = value
return
}
}
m.Items = append(m.Items, KeyValue[T]{Key: key, Value: value})
}
func (m *Map[T]) Del(key Text) {
if m == nil {
return
}
for i, v := range m.Items {
if v.Key == key {
m.Items = append(m.Items[:i], m.Items[i+1:]...)
return
}
}
}
func (m Map[T]) MarshalJSON() ([]byte, error) {
b := bytes.Buffer{}
b.WriteByte('{')
var err error
var s []byte
for _, v := range m.Items {
if b.Len() > 1 {
b.WriteByte(',')
}
jsonx.EncodeAndWriteString(&b, v.Key.String())
b.WriteByte(':')
s, err = json.Marshal(v.Value)
if err != nil {
return nil, err
}
b.Write(s)
}
b.WriteByte('}')
return b.Bytes(), nil
}
func (m *Map[T]) UnmarshalJSON(data []byte) error {
*m = Map[T]{}
var v KeyValue[T]
if !jsonx.IsObject(data) {
return &json.UnmarshalTypeError{Value: jsonx.TypeOf(data).String(), Type: reflect.TypeOf(v), Struct: "Map"}
}
var err error
gjson.ParseBytes(data).ForEach(func(key, value gjson.Result) bool {
var t T
if err = json.Unmarshal([]byte(value.Raw), &t); err != nil {
return false
}
v = KeyValue[T]{Key: Text(key.String()), Value: t}
m.Items = append(m.Items, v)
return true
})
return err
}