/
bson_encode.go
372 lines (335 loc) · 10.3 KB
/
bson_encode.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
// Copyright 2010 Gary Burd
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package mongo
import (
"math"
"os"
"reflect"
"runtime"
"strconv"
)
var (
typeDoc = reflect.Typeof(Doc{})
typeBSONData = reflect.Typeof(BSONData{})
)
// EncodeTypeError is the error indicating that Encode could not encode an input type.
type EncodeTypeError struct {
Type reflect.Type
}
func (e *EncodeTypeError) String() string {
return "bson: unsupported type: " + e.Type.String()
}
type interfaceOrPtrValue interface {
IsNil() bool
Elem() reflect.Value
}
type encodeState struct {
buffer
}
// Encode appends the BSON encoding of doc to buf and returns the new slice.
//
// Encode traverses the value doc recursively using the following
// type-dependent encodings:
//
// Struct values encode as BSON documents. Each struct field becomes an element
// of the document using the field name as the element key. If the struct field
// has a tag, then the tag is used as the element name. Only exported names are
// encoded.
//
// Array and slice values encode as BSON arrays.
//
// Map values encode as BSON documents. The map's key type must be string; the
// object keys are used directly as map keys.
//
// Pointer values encode as the value pointed to. A nil pointer encodes as a BSON null.
//
// Interface values encode as the value contained in the interface. A nil
// interface value encodes as BSON null.
//
// Other types are encoded as follows
//
// Go -> BSON
// bool -> Boolean
// float32 -> Double
// float64 -> Double
// int32 -> 32-bit Integer
// int -> 32-bit Integer
// int64 -> 64-bit Integer
// string -> String
// []byte -> Binary data
// mongo.Code -> Javascript code
// mongo.CodeWithScope -> Javascript code with scope
// mongo.DateTime -> UTC Datetime
// mongo.Doc -> Document. Use when element order is important.
// mongo.MinMax -> Minimum / Maximum value
// mongo.ObjectId -> ObjectId
// mongo.Regexp -> Regular expression
// mongo.Symbol -> Symbol
// mongo.Timestamp -> Timestamp
//
// Other types including channels, complex and function values cannot be encoded.
//
// BSON cannot represent cyclic data structurs and Encode does not handle them.
// Passing cyclic structures to Encode will result in an infinite recursion.
func Encode(buf []byte, doc interface{}) (result []byte, err os.Error) {
defer func() {
if r := recover(); r != nil {
if _, ok := r.(runtime.Error); ok {
panic(r)
}
err = r.(os.Error)
}
}()
v := reflect.NewValue(doc)
if pv, ok := v.(interfaceOrPtrValue); ok {
v = pv.Elem()
}
e := encodeState{buffer: buf}
switch v.Type() {
case typeDoc:
e.writeDoc(v.Interface().(Doc))
case typeBSONData:
rd := v.Interface().(BSONData)
if rd.Kind != kindDocument {
return nil, &EncodeTypeError{v.Type()}
}
e.Write(rd.Data)
default:
switch v := v.(type) {
case *reflect.StructValue:
e.writeStruct(v)
case *reflect.MapValue:
e.writeMap(v)
default:
return nil, &EncodeTypeError{v.Type()}
}
}
return e.buffer, nil
}
func (e *encodeState) abort(err os.Error) {
panic(err)
}
func (e *encodeState) beginDoc() (offset int) {
offset = len(e.buffer)
e.buffer.Next(4)
return
}
func (e *encodeState) endDoc(offset int) {
n := len(e.buffer) - offset
wire.PutUint32(e.buffer[offset:offset+4], uint32(n))
}
func (e *encodeState) writeKindName(kind int, name string) {
e.WriteByte(byte(kind))
e.WriteString(name)
e.WriteByte(0)
}
func (e *encodeState) writeStruct(v *reflect.StructValue) {
offset := e.beginDoc()
for name, f := range compileStruct(v.Type().(*reflect.StructType)) {
e.encodeValue(name, v.FieldByIndex(f.Index))
}
e.WriteByte(0)
e.endDoc(offset)
}
func (e *encodeState) writeMap(v *reflect.MapValue) {
if v.IsNil() {
return
}
if _, ok := v.Type().(*reflect.MapType).Key().(*reflect.StringType); !ok {
e.abort(&EncodeTypeError{v.Type()})
}
offset := e.beginDoc()
for _, k := range v.Keys() {
e.encodeValue(k.(*reflect.StringValue).Get(), v.Elem(k))
}
e.WriteByte(0)
e.endDoc(offset)
}
func (e *encodeState) writeDoc(v Doc) {
offset := e.beginDoc()
for _, kv := range v {
e.encodeValue(kv.Key, reflect.NewValue(kv.Value))
}
e.WriteByte(0)
e.endDoc(offset)
}
func (e *encodeState) encodeValue(name string, value reflect.Value) {
if value == nil {
return
}
t := value.Type()
encoder, found := typeEncoder[t]
if !found {
encoder, found = kindEncoder[t.Kind()]
if !found {
e.abort(&EncodeTypeError{value.Type()})
}
}
encoder(e, name, value)
}
func encodeBool(e *encodeState, name string, value reflect.Value) {
e.writeKindName(kindBool, name)
if value.(*reflect.BoolValue).Get() {
e.WriteByte(1)
} else {
e.WriteByte(0)
}
}
func encodeInt(e *encodeState, name string, value reflect.Value) {
e.writeKindName(kindInt32, name)
e.WriteUint32(uint32(value.(*reflect.IntValue).Get()))
}
func encodeInt64(e *encodeState, kind int, name string, value reflect.Value) {
e.writeKindName(kind, name)
e.WriteUint64(uint64(value.(*reflect.IntValue).Get()))
}
func encodeFloat(e *encodeState, name string, value reflect.Value) {
e.writeKindName(kindFloat, name)
e.WriteUint64(math.Float64bits(value.(*reflect.FloatValue).Get()))
}
func encodeString(e *encodeState, kind int, name string, value reflect.Value) {
e.writeKindName(kind, name)
s := value.(*reflect.StringValue).Get()
e.WriteUint32(uint32(len(s) + 1))
e.WriteString(s)
e.WriteByte(0)
}
func encodeRegexp(e *encodeState, name string, value reflect.Value) {
e.writeKindName(kindRegexp, name)
r := value.Interface().(Regexp)
e.WriteString(r.Pattern)
e.WriteByte(0)
e.WriteString(r.Options)
e.WriteByte(0)
}
func encodeObjectId(e *encodeState, name string, value reflect.Value) {
oid := value.Interface().(ObjectId)
skip := true
for i := 0; i < len(oid); i++ {
if oid[i] != 0 {
skip = false
break
}
}
if skip {
return
}
e.writeKindName(kindObjectId, name)
e.Write(oid[:])
}
func encodeBSONData(e *encodeState, name string, value reflect.Value) {
rd := value.Interface().(BSONData)
e.writeKindName(rd.Kind, name)
e.Write(rd.Data)
}
func encodeCodeWithScope(e *encodeState, name string, value reflect.Value) {
e.writeKindName(kindCodeWithScope, name)
c := value.Interface().(CodeWithScope)
offset := e.beginDoc()
e.WriteUint32(uint32(len(c.Code) + 1))
e.WriteString(c.Code)
e.WriteByte(0)
scopeOffset := e.beginDoc()
for k, v := range c.Scope {
e.encodeValue(k, reflect.NewValue(v))
}
e.WriteByte(0)
e.endDoc(scopeOffset)
e.endDoc(offset)
}
func encodeMinMax(e *encodeState, name string, value reflect.Value) {
switch value.Interface().(MinMax) {
case 1:
e.writeKindName(kindMaxValue, name)
case -1:
e.writeKindName(kindMinValue, name)
default:
e.abort(os.NewError("bson: unknown MinMax value"))
}
}
func encodeStruct(e *encodeState, name string, value reflect.Value) {
e.writeKindName(kindDocument, name)
e.writeStruct(value.(*reflect.StructValue))
}
func encodeMap(e *encodeState, name string, value reflect.Value) {
v := value.(*reflect.MapValue)
if !v.IsNil() {
e.writeKindName(kindDocument, name)
e.writeMap(v)
}
}
func encodeDoc(e *encodeState, name string, value reflect.Value) {
v := value.Interface().(Doc)
if v != nil {
e.writeKindName(kindDocument, name)
e.writeDoc(v)
}
}
func encodeByteSlice(e *encodeState, name string, value reflect.Value) {
e.writeKindName(kindBinary, name)
b := value.Interface().([]byte)
e.WriteUint32(uint32(len(b)))
e.WriteByte(0)
e.Write(b)
}
func encodeArrayOrSlice(e *encodeState, name string, value reflect.Value) {
e.writeKindName(kindArray, name)
offset := e.beginDoc()
v := value.(reflect.ArrayOrSliceValue)
n := v.Len()
for i := 0; i < n; i++ {
e.encodeValue(strconv.Itoa(i), v.Elem(i))
}
e.WriteByte(0)
e.endDoc(offset)
}
func encodeInterfaceOrPtr(e *encodeState, name string, value reflect.Value) {
v := value.(interfaceOrPtrValue)
if !v.IsNil() {
e.encodeValue(name, v.Elem())
}
}
type encoderFunc func(e *encodeState, name string, v reflect.Value)
var kindEncoder map[reflect.Kind]encoderFunc
var typeEncoder map[reflect.Type]encoderFunc
func init() {
kindEncoder = map[reflect.Kind]encoderFunc{
reflect.Array: encodeArrayOrSlice,
reflect.Bool: encodeBool,
reflect.Float32: encodeFloat,
reflect.Float64: encodeFloat,
reflect.Int32: encodeInt,
reflect.Int64: func(e *encodeState, name string, value reflect.Value) { encodeInt64(e, kindInt64, name, value) },
reflect.Int: encodeInt,
reflect.Interface: encodeInterfaceOrPtr,
reflect.Map: encodeMap,
reflect.Ptr: encodeInterfaceOrPtr,
reflect.Slice: encodeArrayOrSlice,
reflect.String: func(e *encodeState, name string, value reflect.Value) { encodeString(e, kindString, name, value) },
reflect.Struct: encodeStruct,
}
typeEncoder = map[reflect.Type]encoderFunc{
typeDoc: encodeDoc,
typeBSONData: encodeBSONData,
reflect.Typeof(Code("")): func(e *encodeState, name string, value reflect.Value) { encodeString(e, kindCode, name, value) },
reflect.Typeof(CodeWithScope{}): encodeCodeWithScope,
reflect.Typeof(DateTime(0)): func(e *encodeState, name string, value reflect.Value) { encodeInt64(e, kindDateTime, name, value) },
reflect.Typeof(MinMax(0)): encodeMinMax,
reflect.Typeof(ObjectId{}): encodeObjectId,
reflect.Typeof(Regexp{}): encodeRegexp,
reflect.Typeof(Symbol("")): func(e *encodeState, name string, value reflect.Value) { encodeString(e, kindSymbol, name, value) },
reflect.Typeof(Timestamp(0)): func(e *encodeState, name string, value reflect.Value) { encodeInt64(e, kindTimestamp, name, value) },
reflect.Typeof([]byte{}): encodeByteSlice,
}
}