forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unmarshal.go
315 lines (289 loc) · 8.14 KB
/
unmarshal.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bson
import (
"bytes"
"fmt"
"io"
"reflect"
"time"
)
// Unmarshaler is the interface that needs to be satisfied
// by types that want to perform custom unmarshaling.
// If kind is EOO, then the type is being unmarshalled
// as a top level object. Otherwise, it's an embedded
// object, and kind will need to be type-checked
// before unmarshaling.
type Unmarshaler interface {
UnmarshalBson(buf *bytes.Buffer, kind byte)
}
func (builder *valueBuilder) canUnMarshal() Unmarshaler {
// Don't use custom unmarshalers for map values.
// It loses symmetry.
if builder.map_.IsValid() {
return nil
}
if builder.val.CanAddr() {
if unmarshaler, ok := builder.val.Addr().Interface().(Unmarshaler); ok {
return unmarshaler
}
}
return nil
}
// Unmarshal unmarshals b into val.
func Unmarshal(b []byte, val interface{}) (err error) {
return UnmarshalFromBuffer(bytes.NewBuffer(b), val)
}
// UnmarshalFromStream unmarshals from reader into val.
func UnmarshalFromStream(reader io.Reader, val interface{}) (err error) {
lenbuf := make([]byte, 4)
var n int
n, err = io.ReadFull(reader, lenbuf)
if err != nil {
return err
}
if n != 4 {
return io.ErrUnexpectedEOF
}
length := Pack.Uint32(lenbuf)
b := make([]byte, length)
Pack.PutUint32(b, length)
n, err = io.ReadFull(reader, b[4:])
if err != nil {
if err == io.EOF {
return io.ErrUnexpectedEOF
}
return err
}
if n != int(length-4) {
return io.ErrUnexpectedEOF
}
return UnmarshalFromBuffer(bytes.NewBuffer(b), val)
}
// UnmarshalFromBuffer unmarshals from buf into val.
func UnmarshalFromBuffer(buf *bytes.Buffer, val interface{}) (err error) {
defer handleError(&err)
if val == nil {
Skip(buf, Object)
return nil
}
if unmarshaler, ok := val.(Unmarshaler); ok {
unmarshaler.UnmarshalBson(buf, EOO)
return nil
}
sb, err := topLevelBuilder(val)
if err != nil {
return err
}
decodeDocument(buf, sb, EOO)
sb.save()
return nil
}
func decodeDocument(buf *bytes.Buffer, builder *valueBuilder, kind byte) {
if kind != EOO && kind != Object && kind != Array {
panic(NewBsonError("unexpected kind: %v", kind))
}
Next(buf, 4)
for kind := NextByte(buf); kind != EOO; kind = NextByte(buf) {
b2 := builder.initField(ReadCString(buf), kind)
if b2 == nil {
Skip(buf, kind)
continue
}
if unmarshaler := b2.canUnMarshal(); unmarshaler != nil {
unmarshaler.UnmarshalBson(buf, kind)
continue
}
switch b2.val.Kind() {
case reflect.String:
b2.setString(DecodeString(buf, kind))
case reflect.Int64:
b2.setInt(DecodeInt64(buf, kind))
case reflect.Int32:
b2.setInt(int64(DecodeInt32(buf, kind)))
case reflect.Int:
b2.setInt(int64(DecodeInt(buf, kind)))
case reflect.Uint64:
b2.setUint(DecodeUint64(buf, kind))
case reflect.Uint32:
b2.setUint(uint64(DecodeUint32(buf, kind)))
case reflect.Uint:
b2.setUint(uint64(DecodeUint(buf, kind)))
case reflect.Float64:
b2.setFloat(DecodeFloat64(buf, kind))
case reflect.Bool:
b2.setBool(DecodeBool(buf, kind))
case reflect.Struct:
if b2.val.Type() == timeType {
b2.setTime(DecodeTime(buf, kind))
} else {
decodeDocument(buf, b2, kind)
}
case reflect.Map, reflect.Array:
decodeDocument(buf, b2, kind)
case reflect.Slice:
if b2.val.Type() == bytesType {
b2.setBytes(DecodeBinary(buf, kind))
} else {
decodeDocument(buf, b2, kind)
}
case reflect.Interface:
b2.setInterface(DecodeInterface(buf, kind))
default:
panic(NewBsonError("cannot unmarshal into %v", b2.val.Kind()))
}
b2.save()
}
}
// Maps & interface values will not give you a reference to their underlying object.
// You can only update them through their Set methods.
type valueBuilder struct {
val reflect.Value
// if map_.IsValid(), write val to map_ using key.
map_ reflect.Value
key reflect.Value
// index tracks current index if val is an array.
index int
}
// topLevelBuilder returns a valid unmarshalable valueBuilder or an error
func topLevelBuilder(val interface{}) (sb *valueBuilder, err error) {
ival := reflect.ValueOf(val)
if ival.Kind() != reflect.Ptr {
return nil, fmt.Errorf("expecting pointer value, received %v", ival.Type())
}
return newValueBuilder(ival.Elem()), nil
}
// newValuebuilder returns a valueBuilder for val. It perorms all
// necessary memory allocations.
func newValueBuilder(val reflect.Value) *valueBuilder {
for val.Kind() == reflect.Ptr {
if val.IsNil() {
val.Set(reflect.New(val.Type().Elem()))
}
val = val.Elem()
}
switch val.Kind() {
case reflect.Map:
if val.IsNil() {
val.Set(reflect.MakeMap(val.Type()))
}
case reflect.Slice:
if val.IsNil() {
val.Set(reflect.MakeSlice(val.Type(), 0, 8))
}
}
return &valueBuilder{val: val}
}
// mapValueBuilder returns a valueBuilder that represents a map value.
// You need to call save after building the value to make sure it gets
// saved to the map.
func mapValueBuilder(typ reflect.Type, map_ reflect.Value, key reflect.Value) *valueBuilder {
if typ.Kind() == reflect.Ptr {
addr := reflect.New(typ.Elem())
map_.SetMapIndex(key, addr)
return newValueBuilder(addr.Elem())
}
builder := newValueBuilder(reflect.New(typ).Elem())
builder.map_ = map_
builder.key = key
return builder
}
// save saves the built value into the map.
func (builder *valueBuilder) save() {
if builder.map_.IsValid() {
builder.map_.SetMapIndex(builder.key, builder.val)
}
}
// initField returns a valueBuilder based on the requested key.
// If the key is a the magic tag _Val_, it returns itself.
// If builder is a struct, it looks for a field of that name.
// If builder is a map, it creates an entry for that key.
// If buider is an array, it ignores the key and returns the next
// element of the array.
// If builder is a slice, it returns a newly appended element.
// If the key cannot be resolved, it returns null.
// If kind is Null, it initializes the field to the zero value.
// Otherwise, it allocates memory as needed.
func (builder *valueBuilder) initField(k string, kind byte) *valueBuilder {
if k == MAGICTAG {
if kind == Null {
setZero(builder.val)
return nil
}
return builder
}
switch builder.val.Kind() {
case reflect.Struct:
t := builder.val.Type()
for i := 0; i < t.NumField(); i++ {
if t.Field(i).Name == k {
if kind == Null {
setZero(builder.val.Field(i))
return nil
}
return newValueBuilder(builder.val.Field(i))
}
}
return nil
case reflect.Map:
t := builder.val.Type()
if t.Key().Kind() != reflect.String {
panic(NewBsonError("map index is not a string: %s", k))
}
key := reflect.ValueOf(k)
if kind == Null {
zero := reflect.Zero(t.Elem())
builder.val.SetMapIndex(key, zero)
return nil
}
return mapValueBuilder(t.Elem(), builder.val, key)
case reflect.Array:
if builder.index >= builder.val.Len() {
panic(NewBsonError("array index %v out of bounds", builder.index))
}
ind := builder.index
builder.index++
if kind == Null {
setZero(builder.val.Index(ind))
return nil
}
return newValueBuilder(builder.val.Index(ind))
case reflect.Slice:
zero := reflect.Zero(builder.val.Type().Elem())
builder.val.Set(reflect.Append(builder.val, zero))
if kind == Null {
return nil
}
return newValueBuilder(builder.val.Index(builder.val.Len() - 1))
}
// Failsafe: this code is actually unreachable.
panic(NewBsonError("internal error: unindexable type %v", builder.val.Type()))
}
func setZero(v reflect.Value) {
v.Set(reflect.Zero(v.Type()))
}
func (builder *valueBuilder) setInt(i int64) {
builder.val.SetInt(i)
}
func (builder *valueBuilder) setUint(u uint64) {
builder.val.SetUint(u)
}
func (builder *valueBuilder) setFloat(f float64) {
builder.val.SetFloat(f)
}
func (builder *valueBuilder) setString(s string) {
builder.val.SetString(s)
}
func (builder *valueBuilder) setBool(tf bool) {
builder.val.SetBool(tf)
}
func (builder *valueBuilder) setTime(t time.Time) {
builder.val.Set(reflect.ValueOf(t))
}
func (builder *valueBuilder) setBytes(b []byte) {
builder.val.Set(reflect.ValueOf(b))
}
func (builder *valueBuilder) setInterface(i interface{}) {
builder.val.Set(reflect.ValueOf(i))
}