blob: 466528457b5fd0734234db9c4581f1ea1e2b8d9f [file] [log] [blame]
Serge Bazanskicc25bdf2018-10-25 14:02:58 +02001package bson
2
3import (
4 "bytes"
5 "encoding/binary"
6 "fmt"
7 "io"
8)
9
10const (
11 // MinDocumentSize is the size of the smallest possible valid BSON document:
12 // an int32 size header + 0x00 (end of document).
13 MinDocumentSize = 5
14
15 // MaxDocumentSize is the largest possible size for a BSON document allowed by MongoDB,
16 // that is, 16 MiB (see https://docs.mongodb.com/manual/reference/limits/).
17 MaxDocumentSize = 16777216
18)
19
20// ErrInvalidDocumentSize is an error returned when a BSON document's header
21// contains a size smaller than MinDocumentSize or greater than MaxDocumentSize.
22type ErrInvalidDocumentSize struct {
23 DocumentSize int32
24}
25
26func (e ErrInvalidDocumentSize) Error() string {
27 return fmt.Sprintf("invalid document size %d", e.DocumentSize)
28}
29
30// A Decoder reads and decodes BSON values from an input stream.
31type Decoder struct {
32 source io.Reader
33}
34
35// NewDecoder returns a new Decoder that reads from source.
36// It does not add any extra buffering, and may not read data from source beyond the BSON values requested.
37func NewDecoder(source io.Reader) *Decoder {
38 return &Decoder{source: source}
39}
40
41// Decode reads the next BSON-encoded value from its input and stores it in the value pointed to by v.
42// See the documentation for Unmarshal for details about the conversion of BSON into a Go value.
43func (dec *Decoder) Decode(v interface{}) (err error) {
44 // BSON documents start with their size as a *signed* int32.
45 var docSize int32
46 if err = binary.Read(dec.source, binary.LittleEndian, &docSize); err != nil {
47 return
48 }
49
50 if docSize < MinDocumentSize || docSize > MaxDocumentSize {
51 return ErrInvalidDocumentSize{DocumentSize: docSize}
52 }
53
54 docBuffer := bytes.NewBuffer(make([]byte, 0, docSize))
55 if err = binary.Write(docBuffer, binary.LittleEndian, docSize); err != nil {
56 return
57 }
58
59 // docSize is the *full* document's size (including the 4-byte size header,
60 // which has already been read).
61 if _, err = io.CopyN(docBuffer, dec.source, int64(docSize-4)); err != nil {
62 return
63 }
64
65 // Let Unmarshal handle the rest.
66 defer handleErr(&err)
67 return Unmarshal(docBuffer.Bytes(), v)
68}
69
70// An Encoder encodes and writes BSON values to an output stream.
71type Encoder struct {
72 target io.Writer
73}
74
75// NewEncoder returns a new Encoder that writes to target.
76func NewEncoder(target io.Writer) *Encoder {
77 return &Encoder{target: target}
78}
79
80// Encode encodes v to BSON, and if successful writes it to the Encoder's output stream.
81// See the documentation for Marshal for details about the conversion of Go values to BSON.
82func (enc *Encoder) Encode(v interface{}) error {
83 data, err := Marshal(v)
84 if err != nil {
85 return err
86 }
87
88 _, err = enc.target.Write(data)
89 return err
90}