-
Notifications
You must be signed in to change notification settings - Fork 4
/
collections.go
81 lines (73 loc) · 1.42 KB
/
collections.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
package jsony
// A key-value pair, an object's field.
type Field struct {
K safeString
V Encoder
}
// An object with fixed keys.
type Object []Field
// An object with dynamically set elements.
//
// The order of items is non-deterministic.
//
// Make sure the keys are either [String] or [SafeString].
// JSON doesn't support non-string keys.
type Map map[Encoder]Encoder
// Array of elements of the same type.
type Array[T Encoder] []T
// Array where every element can be of different type.
type MixedArray = Array[Encoder]
// EncodeJSON implements [Encoder].
func (v Object) EncodeJSON(w *Bytes) {
next := byte('{')
for _, f := range v {
w.Append(next)
f.K.EncodeJSON(w)
w.Append(':')
f.V.EncodeJSON(w)
next = ','
}
if next == '{' {
w.Extend([]byte{'{', '}'})
} else {
w.Append('}')
}
}
// EncodeJSON implements [Encoder].
func (v Map) EncodeJSON(w *Bytes) {
if v == nil {
w.Extend([]byte("null"))
return
}
next := byte('{')
for k, v := range v {
w.Append(next)
k.EncodeJSON(w)
w.Append(':')
v.EncodeJSON(w)
next = ','
}
if next == '{' {
w.Extend([]byte{'{', '}'})
} else {
w.Append('}')
}
}
// EncodeJSON implements [Encoder].
func (v Array[T]) EncodeJSON(w *Bytes) {
if v == nil {
w.Extend([]byte("null"))
return
}
next := byte('[')
for _, el := range v {
w.Append(next)
el.EncodeJSON(w)
next = ','
}
if next == '[' {
w.Extend([]byte{'[', ']'})
} else {
w.Append(']')
}
}