forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
marshal.go
381 lines (337 loc) · 9.93 KB
/
marshal.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// 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 (
"io"
"math"
"reflect"
"strconv"
"time"
"github.com/youtube/vitess/go/bytes2"
)
// LenWriter records the current write position on the buffer
// and can later be used to record the number of bytes written
// in conformance to BSON spec
type LenWriter struct {
buf *bytes2.ChunkedWriter
off int
b []byte
}
// NewLenWriter returns a LenWriter that reserves the
// bytes buf so they can store the length later.
func NewLenWriter(buf *bytes2.ChunkedWriter) LenWriter {
off := buf.Len()
b := buf.Reserve(WORD32)
return LenWriter{buf, off, b}
}
// Close closes the current object being encoded by
// writing bson's EOO byte and recording the length.
func (lw LenWriter) Close() {
lw.buf.WriteByte(EOO)
Pack.PutUint32(lw.b, uint32(lw.buf.Len()-lw.off))
}
// Marshaler is the interface that needs to be
// satisfied by types that want to implement a custom
// marshaler.
// When being invoked as a top level object, key will
// be "". In such cases, MarshalBson must not encode
// any prefix.
type Marshaler interface {
MarshalBson(buf *bytes2.ChunkedWriter, key string)
}
func canMarshal(val reflect.Value) Marshaler {
// Check the Marshaler interface on T.
if marshaler, ok := val.Interface().(Marshaler); ok {
// Don't call custom marshaler for nil values.
switch val.Kind() {
case reflect.Ptr, reflect.Interface, reflect.Map, reflect.Slice:
if val.IsNil() {
return nil
}
}
return marshaler
}
// Check the Marshaler interface on *T.
if val.CanAddr() {
if marshaler, ok := val.Addr().Interface().(Marshaler); ok {
return marshaler
}
}
return nil
}
// DefaultBufferSize is the default allocation size for ChunkedWriter.
const DefaultBufferSize = 1024
// MarshalToStream marshals val into writer.
func MarshalToStream(writer io.Writer, val interface{}) (err error) {
buf := bytes2.NewChunkedWriter(DefaultBufferSize)
if err = MarshalToBuffer(buf, val); err != nil {
return err
}
_, err = buf.WriteTo(writer)
return err
}
// Marshal marshals val into encoded.
func Marshal(val interface{}) (encoded []byte, err error) {
buf := bytes2.NewChunkedWriter(DefaultBufferSize)
err = MarshalToBuffer(buf, val)
return buf.Bytes(), err
}
// MarshalToBuffer marshals val into buf. This is the most efficient
// function to use, especially when marshaling large nested objects.
func MarshalToBuffer(buf *bytes2.ChunkedWriter, val interface{}) (err error) {
defer handleError(&err)
if val == nil {
return NewBsonError("cannot marshal nil")
}
v := reflect.Indirect(reflect.ValueOf(val))
if marshaler := canMarshal(v); marshaler != nil {
marshaler.MarshalBson(buf, "")
return
}
switch v.Kind() {
case reflect.String,
reflect.Int64, reflect.Int32, reflect.Int,
reflect.Uint64, reflect.Uint32, reflect.Uint,
reflect.Float64, reflect.Bool:
EncodeSimple(buf, v.Interface())
case reflect.Struct:
if v.Type() == timeType {
EncodeSimple(buf, v.Interface())
} else {
encodeStructContent(buf, v)
}
case reflect.Map:
encodeMapContent(buf, v)
case reflect.Slice, reflect.Array:
if v.Type() == bytesType {
EncodeSimple(buf, v.Interface())
} else {
encodeSliceContent(buf, v)
}
default:
return NewBsonError("unexpected type %v", v.Type())
}
return nil
}
// EncodeSimple marshals simple objects that cannot be
// encoded as a top level bson document.
func EncodeSimple(buf *bytes2.ChunkedWriter, val interface{}) {
lenWriter := NewLenWriter(buf)
EncodeField(buf, MAGICTAG, val)
lenWriter.Close()
}
// EncodeField encodes val using the supplied key as embedded tag.
// Unlike EncodeInterface, EncodeField can handle complex objects
// like structs, pointers, etc. But it is slower.
func EncodeField(buf *bytes2.ChunkedWriter, key string, val interface{}) {
encodeField(buf, key, reflect.ValueOf(val))
}
func encodeField(buf *bytes2.ChunkedWriter, key string, val reflect.Value) {
// nil interfaces show up as invalid
if !val.IsValid() {
EncodePrefix(buf, Null, key)
return
}
if marshaler := canMarshal(val); marshaler != nil {
marshaler.MarshalBson(buf, key)
return
}
switch val.Kind() {
case reflect.String:
EncodeString(buf, key, val.String())
case reflect.Int64:
EncodeInt64(buf, key, val.Int())
case reflect.Int32:
EncodeInt32(buf, key, int32(val.Int()))
case reflect.Int:
EncodeInt(buf, key, int(val.Int()))
case reflect.Uint64:
EncodeUint64(buf, key, uint64(val.Uint()))
case reflect.Uint32:
EncodeUint32(buf, key, uint32(val.Uint()))
case reflect.Uint:
EncodeUint(buf, key, uint(val.Uint()))
case reflect.Float64:
EncodeFloat64(buf, key, val.Float())
case reflect.Bool:
EncodeBool(buf, key, val.Bool())
case reflect.Struct:
if val.Type() == timeType {
EncodeTime(buf, key, val.Interface().(time.Time))
} else {
encodeStruct(buf, key, val)
}
case reflect.Map:
encodeMap(buf, key, val)
case reflect.Slice:
if val.Type() == bytesType {
EncodeBinary(buf, key, val.Interface().([]byte))
} else {
encodeSlice(buf, key, val)
}
case reflect.Ptr, reflect.Interface:
if val.IsNil() {
EncodePrefix(buf, Null, key)
} else {
encodeField(buf, key, val.Elem())
}
default:
panic(NewBsonError("don't know how to marshal %v", val.Type()))
}
}
// EncodeOptionalPrefix encodes the key as prefix if it's not empty.
// If it is empty, then it's a no-op, with the assumption that
// it's a top level object.
func EncodeOptionalPrefix(buf *bytes2.ChunkedWriter, etype byte, key string) {
if key == "" {
return
}
EncodePrefix(buf, etype, key)
}
// EncodePrefix encodes key as prefix for the next object or value.
func EncodePrefix(buf *bytes2.ChunkedWriter, etype byte, key string) {
b := buf.Reserve(len(key) + 2)
b[0] = etype
copy(b[1:], key)
b[len(b)-1] = 0
}
// EncodeString encodes a string.
func EncodeString(buf *bytes2.ChunkedWriter, key string, val string) {
// Encode strings as binary; go strings are not necessarily unicode
EncodePrefix(buf, Binary, key)
putUint32(buf, uint32(len(val)))
buf.WriteByte(0)
buf.WriteString(val)
}
// EncodeBinary encodes a []byte as binary.
func EncodeBinary(buf *bytes2.ChunkedWriter, key string, val []byte) {
EncodePrefix(buf, Binary, key)
putUint32(buf, uint32(len(val)))
buf.WriteByte(0)
buf.Write(val)
}
// EncodeInt64 encodes an int64.
func EncodeInt64(buf *bytes2.ChunkedWriter, key string, val int64) {
EncodePrefix(buf, Long, key)
putUint64(buf, uint64(val))
}
// EncodeInt32 encodes an int32.
func EncodeInt32(buf *bytes2.ChunkedWriter, key string, val int32) {
EncodePrefix(buf, Int, key)
putUint32(buf, uint32(val))
}
// EncodeInt encodes an int.
func EncodeInt(buf *bytes2.ChunkedWriter, key string, val int) {
EncodeInt64(buf, key, int64(val))
}
// EncodeUint64 encodes an uint64.
func EncodeUint64(buf *bytes2.ChunkedWriter, key string, val uint64) {
EncodePrefix(buf, Long, key)
putUint64(buf, val)
}
// EncodeUint32 encodes an uint32.
func EncodeUint32(buf *bytes2.ChunkedWriter, key string, val uint32) {
EncodeUint64(buf, key, uint64(val))
}
// EncodeUint encodes an uint.
func EncodeUint(buf *bytes2.ChunkedWriter, key string, val uint) {
EncodeUint64(buf, key, uint64(val))
}
// EncodeFloat64 encodes a float64.
func EncodeFloat64(buf *bytes2.ChunkedWriter, key string, val float64) {
EncodePrefix(buf, Number, key)
bits := math.Float64bits(val)
putUint64(buf, bits)
}
// EncodeBool encodes a bool.
func EncodeBool(buf *bytes2.ChunkedWriter, key string, val bool) {
EncodePrefix(buf, Boolean, key)
if val {
buf.WriteByte(1)
} else {
buf.WriteByte(0)
}
}
// EncodeTime encodes a time.Time.
func EncodeTime(buf *bytes2.ChunkedWriter, key string, val time.Time) {
EncodePrefix(buf, Datetime, key)
mtime := val.UnixNano() / 1e6
putUint64(buf, uint64(mtime))
}
func encodeStruct(buf *bytes2.ChunkedWriter, key string, val reflect.Value) {
EncodePrefix(buf, Object, key)
encodeStructContent(buf, val)
}
func encodeStructContent(buf *bytes2.ChunkedWriter, val reflect.Value) {
lenWriter := NewLenWriter(buf)
t := val.Type()
for i := 0; i < t.NumField(); i++ {
key := t.Field(i).Name
// NOTE(szopa): Ignore private fields (copied from
// encoding/json). Yes, it feels like a hack.
if t.Field(i).PkgPath != "" {
continue
}
encodeField(buf, key, val.Field(i))
}
lenWriter.Close()
}
func encodeMap(buf *bytes2.ChunkedWriter, key string, val reflect.Value) {
EncodePrefix(buf, Object, key)
encodeMapContent(buf, val)
}
// a map seems to lose the 'CanAddr' property. So if we want
// to use a custom marshaler with a struct pointer receiver, like:
// func (ps *PrivateStruct) MarshalBson(buf *bytes2.ChunkedWriter, key string) {
// the map has to be using pointers, i.e:
// map[string]*PrivateStruct
// and not:
// map[string]PrivateStruct
// (see unit test)
func encodeMapContent(buf *bytes2.ChunkedWriter, val reflect.Value) {
lenWriter := NewLenWriter(buf)
mt := val.Type()
if mt.Key().Kind() != reflect.String {
panic(NewBsonError("can't marshall maps with non-string key types"))
}
keys := val.MapKeys()
for _, k := range keys {
key := k.String()
encodeField(buf, key, val.MapIndex(k))
}
lenWriter.Close()
}
func encodeSlice(buf *bytes2.ChunkedWriter, key string, val reflect.Value) {
EncodePrefix(buf, Array, key)
encodeSliceContent(buf, val)
}
func encodeSliceContent(buf *bytes2.ChunkedWriter, val reflect.Value) {
lenWriter := NewLenWriter(buf)
for i := 0; i < val.Len(); i++ {
encodeField(buf, Itoa(i), val.Index(i))
}
lenWriter.Close()
}
func putUint32(buf *bytes2.ChunkedWriter, val uint32) {
Pack.PutUint32(buf.Reserve(WORD32), val)
}
func putUint64(buf *bytes2.ChunkedWriter, val uint64) {
Pack.PutUint64(buf.Reserve(WORD64), val)
}
var intStrMap [intAliasSize + 1]string
const (
intAliasSize = 1024
)
func init() {
for i := 0; i <= intAliasSize; i++ {
intStrMap[i] = strconv.Itoa(i)
}
}
// Itoa is used in code generated by bsongen.
func Itoa(i int) string {
if i <= intAliasSize {
return intStrMap[i]
}
return strconv.Itoa(i)
}