Debian Codegraph @

bson/bson.go

raw symbols SCIP
1 // BSON library for Go
2 //
3 // Copyright (c) 2010-2012 - Gustavo Niemeyer <[email protected]>
4 //
5 // All rights reserved.
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions are met:
9 //
10 // 1. Redistributions of source code must retain the above copyright notice, this
11 // list of conditions and the following disclaimer.
12 // 2. Redistributions in binary form must reproduce the above copyright notice,
13 // this list of conditions and the following disclaimer in the documentation
14 // and/or other materials provided with the distribution.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17 // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
20 // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
27 // Package bson is an implementation of the BSON specification for Go:
28 //
29 // http://bsonspec.org
30 //
31 // It was created as part of the mgo MongoDB driver for Go, but is standalone
32 // and may be used on its own without the driver.
33 package bson
34
35 import (
36 "crypto/md5"
37 "crypto/rand"
38 "encoding/binary"
39 "encoding/hex"
40 "errors"
41 "fmt"
42 "io"
43 "os"
44 "reflect"
45 "runtime"
46 "strings"
47 "sync"
48 "sync/atomic"
49 "time"
50 )
51
52 // --------------------------------------------------------------------------
53 // The public API.
54
55 // A value implementing the bson.Getter interface will have its GetBSON
56 // method called when the given value has to be marshalled, and the result
57 // of this method will be marshaled in place of the actual object.
58 //
59 // If GetBSON returns return a non-nil error, the marshalling procedure
60 // will stop and error out with the provided value.
61 type Getter interface {
62 GetBSON() (interface{}, error)
63 }
64
65 // A value implementing the bson.Setter interface will receive the BSON
66 // value via the SetBSON method during unmarshaling, and the object
67 // itself will not be changed as usual.
68 //
69 // If setting the value works, the method should return nil or alternatively
70 // bson.SetZero to set the respective field to its zero value (nil for
71 // pointer types). If SetBSON returns a value of type bson.TypeError, the
72 // BSON value will be omitted from a map or slice being decoded and the
73 // unmarshalling will continue. If it returns any other non-nil error, the
74 // unmarshalling procedure will stop and error out with the provided value.
75 //
76 // This interface is generally useful in pointer receivers, since the method
77 // will want to change the receiver. A type field that implements the Setter
78 // interface doesn't have to be a pointer, though.
79 //
80 // Unlike the usual behavior, unmarshalling onto a value that implements a
81 // Setter interface will NOT reset the value to its zero state. This allows
82 // the value to decide by itself how to be unmarshalled.
83 //
84 // For example:
85 //
86 // type MyString string
87 //
88 // func (s *MyString) SetBSON(raw bson.Raw) error {
89 // return raw.Unmarshal(s)
90 // }
91 //
92 type Setter interface {
93 SetBSON(raw Raw) error
94 }
95
96 // SetZero may be returned from a SetBSON method to have the value set to
97 // its respective zero value. When used in pointer values, this will set the
98 // field to nil rather than to the pre-allocated value.
99 var SetZero = errors.New("set to zero")
100
101 // M is a convenient alias for a map[string]interface{} map, useful for
102 // dealing with BSON in a native way. For instance:
103 //
104 // bson.M{"a": 1, "b": true}
105 //
106 // There's no special handling for this type in addition to what's done anyway
107 // for an equivalent map type. Elements in the map will be dumped in an
108 // undefined ordered. See also the bson.D type for an ordered alternative.
109 type M map[string]interface{}
110
111 // D represents a BSON document containing ordered elements. For example:
112 //
113 // bson.D{{"a", 1}, {"b", true}}
114 //
115 // In some situations, such as when creating indexes for MongoDB, the order in
116 // which the elements are defined is important. If the order is not important,
117 // using a map is generally more comfortable. See bson.M and bson.RawD.
118 type D []DocElem
119
120 // See the D type.
121 type DocElem struct {
122 Name string
123 Value interface{}
124 }
125
126 // Map returns a map out of the ordered element name/value pairs in d.
127 func (d D) Map() (m M) {
128 m = make(M, len(d))
129 for _, item := range d {
130 m[item.Name] = item.Value
131 }
132 return m
133 }
134
135 // The Raw type represents raw unprocessed BSON documents and elements.
136 // Kind is the kind of element as defined per the BSON specification, and
137 // Data is the raw unprocessed data for the respective element.
138 // Using this type it is possible to unmarshal or marshal values partially.
139 //
140 // Relevant documentation:
141 //
142 // http://bsonspec.org/#/specification
143 //
144 type Raw struct {
145 Kind byte
146 Data []byte
147 }
148
149 // RawD represents a BSON document containing raw unprocessed elements.
150 // This low-level representation may be useful when lazily processing
151 // documents of uncertain content, or when manipulating the raw content
152 // documents in general.
153 type RawD []RawDocElem
154
155 // See the RawD type.
156 type RawDocElem struct {
157 Name string
158 Value Raw
159 }
160
161 // ObjectId is a unique ID identifying a BSON value. It must be exactly 12 bytes
162 // long. MongoDB objects by default have such a property set in their "_id"
163 // property.
164 //
165 // http://www.mongodb.org/display/DOCS/Object+IDs
166 type ObjectId string
167
168 // ObjectIdHex returns an ObjectId from the provided hex representation.
169 // Calling this function with an invalid hex representation will
170 // cause a runtime panic. See the IsObjectIdHex function.
171 func ObjectIdHex(s string) ObjectId {
172 d, err := hex.DecodeString(s)
173 if err != nil || len(d) != 12 {
174 panic(fmt.Sprintf("Invalid input to ObjectIdHex: %q", s))
175 }
176 return ObjectId(d)
177 }
178
179 // IsObjectIdHex returns whether s is a valid hex representation of
180 // an ObjectId. See the ObjectIdHex function.
181 func IsObjectIdHex(s string) bool {
182 if len(s) != 24 {
183 return false
184 }
185 _, err := hex.DecodeString(s)
186 return err == nil
187 }
188
189 // objectIdCounter is atomically incremented when generating a new ObjectId
190 // using NewObjectId() function. It's used as a counter part of an id.
191 var objectIdCounter uint32 = 0
192
193 // machineId stores machine id generated once and used in subsequent calls
194 // to NewObjectId function.
195 var machineId = readMachineId()
196
197 // readMachineId generates machine id and puts it into the machineId global
198 // variable. If this function fails to get the hostname, it will cause
199 // a runtime error.
200 func readMachineId() []byte {
201 var sum [3]byte
202 id := sum[:]
203 hostname, err1 := os.Hostname()
204 if err1 != nil {
205 _, err2 := io.ReadFull(rand.Reader, id)
206 if err2 != nil {
207 panic(fmt.Errorf("cannot get hostname: %v; %v", err1, err2))
208 }
209 return id
210 }
211 hw := md5.New()
212 hw.Write([]byte(hostname))
213 copy(id, hw.Sum(nil))
214 return id
215 }
216
217 // NewObjectId returns a new unique ObjectId.
218 func NewObjectId() ObjectId {
219 var b [12]byte
220 // Timestamp, 4 bytes, big endian
221 binary.BigEndian.PutUint32(b[:], uint32(time.Now().Unix()))
222 // Machine, first 3 bytes of md5(hostname)
223 b[4] = machineId[0]
224 b[5] = machineId[1]
225 b[6] = machineId[2]
226 // Pid, 2 bytes, specs don't specify endianness, but we use big endian.
227 pid := os.Getpid()
228 b[7] = byte(pid >> 8)
229 b[8] = byte(pid)
230 // Increment, 3 bytes, big endian
231 i := atomic.AddUint32(&objectIdCounter, 1)
232 b[9] = byte(i >> 16)
233 b[10] = byte(i >> 8)
234 b[11] = byte(i)
235 return ObjectId(b[:])
236 }
237
238 // NewObjectIdWithTime returns a dummy ObjectId with the timestamp part filled
239 // with the provided number of seconds from epoch UTC, and all other parts
240 // filled with zeroes. It's not safe to insert a document with an id generated
241 // by this method, it is useful only for queries to find documents with ids
242 // generated before or after the specified timestamp.
243 func NewObjectIdWithTime(t time.Time) ObjectId {
244 var b [12]byte
245 binary.BigEndian.PutUint32(b[:4], uint32(t.Unix()))
246 return ObjectId(string(b[:]))
247 }
248
249 // String returns a hex string representation of the id.
250 // Example: ObjectIdHex("4d88e15b60f486e428412dc9").
251 func (id ObjectId) String() string {
252 return fmt.Sprintf(`ObjectIdHex("%x")`, string(id))
253 }
254
255 // Hex returns a hex representation of the ObjectId.
256 func (id ObjectId) Hex() string {
257 return hex.EncodeToString([]byte(id))
258 }
259
260 // MarshalJSON turns a bson.ObjectId into a json.Marshaller.
261 func (id ObjectId) MarshalJSON() ([]byte, error) {
262 return []byte(fmt.Sprintf(`"%x"`, string(id))), nil
263 }
264
265 // UnmarshalJSON turns *bson.ObjectId into a json.Unmarshaller.
266 func (id *ObjectId) UnmarshalJSON(data []byte) error {
267 if len(data) != 26 || data[0] != '"' || data[25] != '"' {
268 return errors.New(fmt.Sprintf("Invalid ObjectId in JSON: %s", string(data)))
269 }
270 var buf [12]byte
271 _, err := hex.Decode(buf[:], data[1:25])
272 if err != nil {
273 return errors.New(fmt.Sprintf("Invalid ObjectId in JSON: %s (%s)", string(data), err))
274 }
275 *id = ObjectId(string(buf[:]))
276 return nil
277 }
278
279 // Valid returns true if id is valid. A valid id must contain exactly 12 bytes.
280 func (id ObjectId) Valid() bool {
281 return len(id) == 12
282 }
283
284 // byteSlice returns byte slice of id from start to end.
285 // Calling this function with an invalid id will cause a runtime panic.
286 func (id ObjectId) byteSlice(start, end int) []byte {
287 if len(id) != 12 {
288 panic(fmt.Sprintf("Invalid ObjectId: %q", string(id)))
289 }
290 return []byte(string(id)[start:end])
291 }
292
293 // Time returns the timestamp part of the id.
294 // It's a runtime error to call this method with an invalid id.
295 func (id ObjectId) Time() time.Time {
296 // First 4 bytes of ObjectId is 32-bit big-endian seconds from epoch.
297 secs := int64(binary.BigEndian.Uint32(id.byteSlice(0, 4)))
298 return time.Unix(secs, 0)
299 }
300
301 // Machine returns the 3-byte machine id part of the id.
302 // It's a runtime error to call this method with an invalid id.
303 func (id ObjectId) Machine() []byte {
304 return id.byteSlice(4, 7)
305 }
306
307 // Pid returns the process id part of the id.
308 // It's a runtime error to call this method with an invalid id.
309 func (id ObjectId) Pid() uint16 {
310 return binary.BigEndian.Uint16(id.byteSlice(7, 9))
311 }
312
313 // Counter returns the incrementing value part of the id.
314 // It's a runtime error to call this method with an invalid id.
315 func (id ObjectId) Counter() int32 {
316 b := id.byteSlice(9, 12)
317 // Counter is stored as big-endian 3-byte value
318 return int32(uint32(b[0])<<16 | uint32(b[1])<<8 | uint32(b[2]))
319 }
320
321 // The Symbol type is similar to a string and is used in languages with a
322 // distinct symbol type.
323 type Symbol string
324
325 // Now returns the current time with millisecond precision. MongoDB stores
326 // timestamps with the same precision, so a Time returned from this method
327 // will not change after a roundtrip to the database. That's the only reason
328 // why this function exists. Using the time.Now function also works fine
329 // otherwise.
330 func Now() time.Time {
331 return time.Unix(0, time.Now().UnixNano()/1e6*1e6)
332 }
333
334 // MongoTimestamp is a special internal type used by MongoDB that for some
335 // strange reason has its own datatype defined in BSON.
336 type MongoTimestamp int64
337
338 type orderKey int64
339
340 // MaxKey is a special value that compares higher than all other possible BSON
341 // values in a MongoDB database.
342 var MaxKey = orderKey(1<<63 - 1)
343
344 // MinKey is a special value that compares lower than all other possible BSON
345 // values in a MongoDB database.
346 var MinKey = orderKey(-1 << 63)
347
348 type undefined struct{}
349
350 // Undefined represents the undefined BSON value.
351 var Undefined undefined
352
353 // Binary is a representation for non-standard binary values. Any kind should
354 // work, but the following are known as of this writing:
355 //
356 // 0x00 - Generic. This is decoded as []byte(data), not Binary{0x00, data}.
357 // 0x01 - Function (!?)
358 // 0x02 - Obsolete generic.
359 // 0x03 - UUID
360 // 0x05 - MD5
361 // 0x80 - User defined.
362 //
363 type Binary struct {
364 Kind byte
365 Data []byte
366 }
367
368 // RegEx represents a regular expression. The Options field may contain
369 // individual characters defining the way in which the pattern should be
370 // applied, and must be sorted. Valid options as of this writing are 'i' for
371 // case insensitive matching, 'm' for multi-line matching, 'x' for verbose
372 // mode, 'l' to make \w, \W, and similar be locale-dependent, 's' for dot-all
373 // mode (a '.' matches everything), and 'u' to make \w, \W, and similar match
374 // unicode. The value of the Options parameter is not verified before being
375 // marshaled into the BSON format.
376 type RegEx struct {
377 Pattern string
378 Options string
379 }
380
381 // JavaScript is a type that holds JavaScript code. If Scope is non-nil, it
382 // will be marshaled as a mapping from identifiers to values that may be
383 // used when evaluating the provided Code.
384 type JavaScript struct {
385 Code string
386 Scope interface{}
387 }
388
389 const initialBufferSize = 64
390
391 func handleErr(err *error) {
392 if r := recover(); r != nil {
393 if _, ok := r.(runtime.Error); ok {
394 panic(r)
395 } else if _, ok := r.(externalPanic); ok {
396 panic(r)
397 } else if s, ok := r.(string); ok {
398 *err = errors.New(s)
399 } else if e, ok := r.(error); ok {
400 *err = e
401 } else {
402 panic(r)
403 }
404 }
405 }
406
407 // Marshal serializes the in value, which may be a map or a struct value.
408 // In the case of struct values, only exported fields will be serialized.
409 // The lowercased field name is used as the key for each exported field,
410 // but this behavior may be changed using the respective field tag.
411 // The tag may also contain flags to tweak the marshalling behavior for
412 // the field. The tag formats accepted are:
413 //
414 // "[<key>][,<flag1>[,<flag2>]]"
415 //
416 // `(...) bson:"[<key>][,<flag1>[,<flag2>]]" (...)`
417 //
418 // The following flags are currently supported:
419 //
420 // omitempty Only include the field if it's not set to the zero
421 // value for the type or to empty slices or maps.
422 //
423 // minsize Marshal an int64 value as an int32, if that's feasible
424 // while preserving the numeric value.
425 //
426 // inline Inline the field, which must be a struct or a map,
427 // causing all of its fields or keys to be processed as if
428 // they were part of the outer struct. For maps, keys must
429 // not conflict with the bson keys of other struct fields.
430 //
431 // Some examples:
432 //
433 // type T struct {
434 // A bool
435 // B int "myb"
436 // C string "myc,omitempty"
437 // D string `bson:",omitempty" json:"jsonkey"`
438 // E int64 ",minsize"
439 // F int64 "myf,omitempty,minsize"
440 // }
441 //
442 func Marshal(in interface{}) (out []byte, err error) {
443 defer handleErr(&err)
444 e := &encoder{make([]byte, 0, initialBufferSize)}
445 e.addDoc(reflect.ValueOf(in))
446 return e.out, nil
447 }
448
449 // Unmarshal deserializes data from in into the out value. The out value
450 // must be a map, a pointer to a struct, or a pointer to a bson.D value.
451 // The lowercased field name is used as the key for each exported field,
452 // but this behavior may be changed using the respective field tag.
453 // The tag may also contain flags to tweak the marshalling behavior for
454 // the field. The tag formats accepted are:
455 //
456 // "[<key>][,<flag1>[,<flag2>]]"
457 //
458 // `(...) bson:"[<key>][,<flag1>[,<flag2>]]" (...)`
459 //
460 // The following flags are currently supported during unmarshal (see the
461 // Marshal method for other flags):
462 //
463 // inline Inline the field, which must be a struct or a map.
464 // Inlined structs are handled as if its fields were part
465 // of the outer struct. An inlined map causes keys that do
466 // not match any other struct field to be inserted in the
467 // map rather than being discarded as usual.
468 //
469 // The target field or element types of out may not necessarily match
470 // the BSON values of the provided data. The following conversions are
471 // made automatically:
472 //
473 // - Numeric types are converted if at least the integer part of the
474 // value would be preserved correctly
475 // - Bools are converted to numeric types as 1 or 0
476 // - Numeric types are converted to bools as true if not 0 or false otherwise
477 // - Binary and string BSON data is converted to a string, array or byte slice
478 //
479 // If the value would not fit the type and cannot be converted, it's
480 // silently skipped.
481 //
482 // Pointer values are initialized when necessary.
483 func Unmarshal(in []byte, out interface{}) (err error) {
484 defer handleErr(&err)
485 v := reflect.ValueOf(out)
486 switch v.Kind() {
487 case reflect.Map, reflect.Ptr:
488 d := newDecoder(in)
489 d.readDocTo(v)
490 case reflect.Struct:
491 return errors.New("Unmarshal can't deal with struct values. Use a pointer.")
492 default:
493 return errors.New("Unmarshal needs a map or a pointer to a struct.")
494 }
495 return nil
496 }
497
498 // Unmarshal deserializes raw into the out value. If the out value type
499 // is not compatible with raw, a *bson.TypeError is returned.
500 //
501 // See the Unmarshal function documentation for more details on the
502 // unmarshalling process.
503 func (raw Raw) Unmarshal(out interface{}) (err error) {
504 defer handleErr(&err)
505 v := reflect.ValueOf(out)
506 switch v.Kind() {
507 case reflect.Ptr:
508 v = v.Elem()
509 fallthrough
510 case reflect.Map:
511 d := newDecoder(raw.Data)
512 good := d.readElemTo(v, raw.Kind)
513 if !good {
514 return &TypeError{v.Type(), raw.Kind}
515 }
516 case reflect.Struct:
517 return errors.New("Raw Unmarshal can't deal with struct values. Use a pointer.")
518 default:
519 return errors.New("Raw Unmarshal needs a map or a valid pointer.")
520 }
521 return nil
522 }
523
524 type TypeError struct {
525 Type reflect.Type
526 Kind byte
527 }
528
529 func (e *TypeError) Error() string {
530 return fmt.Sprintf("BSON kind 0x%02x isn't compatible with type %s", e.Kind, e.Type.String())
531 }
532
533 // --------------------------------------------------------------------------
534 // Maintain a mapping of keys to structure field indexes
535
536 type structInfo struct {
537 FieldsMap map[string]fieldInfo
538 FieldsList []fieldInfo
539 InlineMap int
540 Zero reflect.Value
541 }
542
543 type fieldInfo struct {
544 Key string
545 Num int
546 OmitEmpty bool
547 MinSize bool
548 Inline []int
549 }
550
551 var structMap = make(map[reflect.Type]*structInfo)
552 var structMapMutex sync.RWMutex
553
554 type externalPanic string
555
556 func (e externalPanic) String() string {
557 return string(e)
558 }
559
560 func getStructInfo(st reflect.Type) (*structInfo, error) {
561 structMapMutex.RLock()
562 sinfo, found := structMap[st]
563 structMapMutex.RUnlock()
564 if found {
565 return sinfo, nil
566 }
567 n := st.NumField()
568 fieldsMap := make(map[string]fieldInfo)
569 fieldsList := make([]fieldInfo, 0, n)
570 inlineMap := -1
571 for i := 0; i != n; i++ {
572 field := st.Field(i)
573 if field.PkgPath != "" {
574 continue // Private field
575 }
576
577 info := fieldInfo{Num: i}
578
579 tag := field.Tag.Get("bson")
580 if tag == "" && strings.Index(string(field.Tag), ":") < 0 {
581 tag = string(field.Tag)
582 }
583 if tag == "-" {
584 continue
585 }
586
587 // XXX Drop this after a few releases.
588 if s := strings.Index(tag, "/"); s >= 0 {
589 recommend := tag[:s]
590 for _, c := range tag[s+1:] {
591 switch c {
592 case 'c':
593 recommend += ",omitempty"
594 case 's':
595 recommend += ",minsize"
596 default:
597 msg := fmt.Sprintf("Unsupported flag %q in tag %q of type %s", string([]byte{uint8(c)}), tag, st)
598 panic(externalPanic(msg))
599 }
600 }
601 msg := fmt.Sprintf("Replace tag %q in field %s of type %s by %q", tag, field.Name, st, recommend)
602 panic(externalPanic(msg))
603 }
604
605 inline := false
606 fields := strings.Split(tag, ",")
607 if len(fields) > 1 {
608 for _, flag := range fields[1:] {
609 switch flag {
610 case "omitempty":
611 info.OmitEmpty = true
612 case "minsize":
613 info.MinSize = true
614 case "inline":
615 inline = true
616 default:
617 msg := fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st)
618 panic(externalPanic(msg))
619 }
620 }
621 tag = fields[0]
622 }
623
624 if inline {
625 switch field.Type.Kind() {
626 case reflect.Map:
627 if inlineMap >= 0 {
628 return nil, errors.New("Multiple ,inline maps in struct " + st.String())
629 }
630 if field.Type.Key() != reflect.TypeOf("") {
631 return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String())
632 }
633 inlineMap = info.Num
634 case reflect.Struct:
635 sinfo, err := getStructInfo(field.Type)
636 if err != nil {
637 return nil, err
638 }
639 for _, finfo := range sinfo.FieldsList {
640 if _, found := fieldsMap[finfo.Key]; found {
641 msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String()
642 return nil, errors.New(msg)
643 }
644 if finfo.Inline == nil {
645 finfo.Inline = []int{i, finfo.Num}
646 } else {
647 finfo.Inline = append([]int{i}, finfo.Inline...)
648 }
649 fieldsMap[finfo.Key] = finfo
650 fieldsList = append(fieldsList, finfo)
651 }
652 default:
653 panic("Option ,inline needs a struct value or map field")
654 }
655 continue
656 }
657
658 if tag != "" {
659 info.Key = tag
660 } else {
661 info.Key = strings.ToLower(field.Name)
662 }
663
664 if _, found = fieldsMap[info.Key]; found {
665 msg := "Duplicated key '" + info.Key + "' in struct " + st.String()
666 return nil, errors.New(msg)
667 }
668
669 fieldsList = append(fieldsList, info)
670 fieldsMap[info.Key] = info
671 }
672 sinfo = &structInfo{
673 fieldsMap,
674 fieldsList,
675 inlineMap,
676 reflect.New(st).Elem(),
677 }
678 structMapMutex.Lock()
679 structMap[st] = sinfo
680 structMapMutex.Unlock()
681 return sinfo, nil
682 }