-
Notifications
You must be signed in to change notification settings - Fork 0
/
append_value.go
132 lines (106 loc) · 1.74 KB
/
append_value.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package jq
import (
"fmt"
"strings"
"nikand.dev/go/cbor"
)
type (
Arr = arr
Obj = obj
Raw = raw
arr []any
obj []any
raw []byte
lab struct {
lab int
val any
}
)
func (b *Buffer) AppendValue(v any) (off Off) {
return b.appendVal(v)
}
func (b *Buffer) appendVal(v any) (off Off) {
e := b.Encoder.CBOR
var a []Off
var tag Tag
var lst []any
off = Off(len(b.B))
switch v := v.(type) {
case Off:
return v
case nil:
return Null
case raw:
b.B = append(b.B, v...)
return off
case bool:
if v {
return True
} else {
return False
}
case int:
switch v {
case 0:
return Zero
case 1:
return One
}
b.B = e.AppendInt(b.B, v)
return off
case string:
b.B = e.AppendString(b.B, v)
return off
case []byte:
b.B = e.AppendBytes(b.B, v)
return off
case float64:
b.B = e.AppendFloat(b.B, v)
return off
case lab:
b.B = e.AppendLabeled(b.B, v.lab)
return b.appendVal(v.val)
case arr:
tag = cbor.Array
lst = []any(v)
case obj:
tag = cbor.Map
lst = []any(v)
default:
panic(v)
}
for _, v := range lst {
off = b.appendVal(v)
a = append(a, off)
}
off = Off(len(b.B))
b.B = b.Encoder.AppendArrayMap(b.B, tag, off, a)
return off
}
func (x arr) String() string {
var b strings.Builder
_ = b.WriteByte('[')
for j, x := range x {
if j != 0 {
_, _ = b.Write([]byte{',', ' '})
}
_, _ = fmt.Fprintf(&b, "%v", x)
}
_ = b.WriteByte(']')
return b.String()
}
func (x obj) String() string {
var b strings.Builder
_ = b.WriteByte('{')
for j := 0; j < len(x); j++ {
if j != 0 {
_, _ = b.Write([]byte{',', ' '})
}
_, _ = fmt.Fprintf(&b, "%v", x[j])
j++
_, _ = b.Write([]byte{':', ' '})
_, _ = fmt.Fprintf(&b, "%v", x[j])
}
_ = b.WriteByte('}')
return b.String()
}