-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathjsony.go
61 lines (51 loc) · 1.08 KB
/
jsony.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
package jsony
import "unsafe"
// One-letter aliases for people living on the edge.
type (
B = Bool
I = Int64
U = UInt
S = String
F = Float64
A = MixedArray
O = Object
M = Map
)
const (
True = Bool(true)
False = Bool(false)
)
// Encoder is an interface describing objects that can be serialized to JSON.
type Encoder interface {
EncodeJSON(*Bytes)
}
// Bytes is a slice of bytes that wraps [append] to require no assignment.
type Bytes struct {
buf []byte
}
func (w *Bytes) Append(b byte) {
w.buf = append(w.buf, b)
}
func (w *Bytes) Extend(b []byte) {
w.buf = append(w.buf, b...)
}
// Marshal JSON as a slice of bytes.
func EncodeBytes(e Encoder) []byte {
b := Bytes{}
e.EncodeJSON(&b)
return b.buf
}
// Marshal JSON into the end of the given slice of bytes.
//
// Useful if you want to reduce allocations by reusing an existing buffer.
func AppendBytes(buf []byte, e Encoder) []byte {
b := Bytes{buf}
e.EncodeJSON(&b)
return b.buf
}
// Marshal JSON as a string.
func EncodeString(e Encoder) string {
b := Bytes{}
e.EncodeJSON(&b)
return unsafe.String(&b.buf[0], len(b.buf))
}