package bson

import "go.mongodb.org/mongo-driver/bson"

Package bson is a library for reading, writing, and manipulating BSON. The library has three types for representing BSON.

The Reader type is used to validate and retrieve elements from a byte slice. If you are not manipulating the underlying document and just want to validate or ensure the document has certain keys, this is the type you should use.

The Document type is a more generic type that can do all the read actions the Reader can do and allows for manipulation of documents. The main usecase for this type is reading some BSON and then adding, changing, or removing elements or to build a document that will need to be manipulated later. If the document can be created in a single pass without the need to do any lookups, the Builder type is might be more appropriate.

The Builder type (in the "bson/builder" package) is used to create a BSON document. The type only allows the iterative building of a document, so there is no way to verify the contents outside of writing the document. If you have a Builder and need to conditionally add a field, you can write the document to a byte slice and use the Reader type to lookup the desired document, but in this case you should probably use a Document instead.

The Element type represents a BSON element and the Value type represents an individual value for a BSON element.

The Encoder and Decoder types can be used to marshal a type to an io.Writer or to unmarshal into a type from an io.Reader. These types will use reflection and evaluate struct tags unless the provided types implements the Marshaler or Unmarshaler interfaces. The Builder and Reader types can be used to implement these interfaces for types.

The DocumentEncoder type can be used to encode a type to a Document instead of an io.Writer. This is useful if some additional manipulation is required after encoding a document. This type supports the same encoding behavior as the Encoder type.

Index

Examples

Variables

var ErrEOA = errors.New("end of array")

ErrEOA is the error returned when the end of a BSON array has been reached.

var ErrEOD = errors.New("end of document")

ErrEOD is the error returned when the end of a BSON document has been reached.

var ErrElementNotFound = errors.New("element not found")

ErrElementNotFound indicates that an Element matching a certain condition does not exist.

var ErrEmptyKey = errors.New("empty key provided")

ErrEmptyKey indicates that no key was provided to a Lookup method.

var ErrEncoderNilWriter = errors.New("encoder.Encode called on Encoder with nil io.Writer")

ErrEncoderNilWriter indicates that encoder.Encode was called with a nil argument.

var ErrInvalidArrayKey = errors.New("invalid array key")

ErrInvalidArrayKey indicates that a key that isn't a positive integer was used to lookup an element in an array.

var ErrInvalidBinarySubtype = errors.New("invalid BSON binary Subtype")

ErrInvalidBinarySubtype indicates that a BSON binary value had an undefined subtype.

var ErrInvalidBooleanType = errors.New("invalid value for BSON Boolean Type")

ErrInvalidBooleanType indicates that a BSON boolean value had an incorrect byte.

var ErrInvalidDepthTraversal = errors.New("invalid depth traversal")

ErrInvalidDepthTraversal indicates that a provided path of keys to a nested value in a document does not exist.

TODO(skriptble): This error message is pretty awful. Please fix.

var ErrInvalidDocumentType = errors.New("invalid document type")

ErrInvalidDocumentType indicates that a type which doesn't represent a BSON document was was provided when a document was expected.

var ErrInvalidElement = errors.New("invalid Element")

ErrInvalidElement indicates that a bson.Element had invalid underlying BSON.

var ErrInvalidKey = errors.New("invalid document key")

ErrInvalidKey indicates that the BSON representation of a key is missing a null terminator.

var ErrInvalidLength = errors.New("document length is invalid")

ErrInvalidLength indicates that a length in a binary representation of a BSON document is invalid.

var ErrInvalidReadOnlyDocument = errors.New("invalid read-only document")

ErrInvalidReadOnlyDocument indicates that the underlying bytes of a bson.Reader are invalid.

var ErrInvalidString = errors.New("invalid string value")

ErrInvalidString indicates that a BSON string value had an incorrect length.

var ErrInvalidWriter = errors.New("bson: invalid writer provided")

ErrInvalidWriter indicates that a type that can't be written into was passed to a writer method.

var ErrNilDocument = errors.New("document is nil")

ErrNilDocument indicates that an operation was attempted on a nil *bson.Document.

var ErrNilElement = errors.New("element is nil")

ErrNilElement indicates that a nil element was provided when none was expected.

var ErrNilReader = errors.New("nil reader")

ErrNilReader indicates that an operation was attempted on a nil bson.Reader.

var ErrNotInterface = errors.New("The provided type is not an interface")

ErrNotInterface is returned when the provided type is not an interface.

var ErrOutOfBounds = errors.New("out of bounds")

ErrOutOfBounds indicates that an index provided to access something was invalid.

var ErrStringLargerThanContainer = errors.New("string size is larger than the JavaScript code with scope container")

ErrStringLargerThanContainer indicates that the code portion of a BSON JavaScript code with scope value is larger than the specified length of the entire value.

var ErrUninitializedElement = errors.New("bson/ast/compact: Method call on uninitialized Element")

ErrUninitializedElement is returned whenever any method is invoked on an uninitialized Element.

var MaxKey struct{}

MaxKey represents the BSON minkey value.

var MinKey struct{}

MinKey represents the BSON maxkey value.

var Null struct{}

Null represents the BSON null value.

var Undefined struct{}

Undefined represents the BSON undefined value.

Functions

func CopyDocument

func CopyDocument(dst ValueWriter, src ValueReader) error

CopyDocument handles copying a document from src to dst.

func ElementAsBSON

func ElementAsBSON(vr ValueReader) (kind byte, data []byte, err error)

ElementAsBSON will retrieve the next value from vr and return it as a kind byte and the value as a slice of bytes.

func Marshal

func Marshal(value interface{}) ([]byte, error)

Marshal converts a BSON type to bytes.

The value can be any one of the following types:

The following flags are currently supported for marshaling:

    omitempty  Only include the field if it's not set to the zero value for the type or to
               empty slices or maps.

    minsize    Marshal an integer of a type larger than 32 bits value as an int32, if that's
				  feasible while preserving the numeric value.

    inline     Inline the field, which must be a struct or a map, causing all of its fields
               or keys to be processed as if they were part of the outer struct. For maps,
               keys must not conflict with the bson keys of other struct fields.

    Skip       This struct field should be skipped. This is usually denoted by parsing a "-"
               for the name.

See the DefaultStructTagParser declaration and the StructTags type for more information.

func MarshalAppend

func MarshalAppend(dst []byte, val interface{}) ([]byte, error)

MarshalAppend will append the BSON encoding of val to dst. If dst is not large enough to hold the BSON encoding of val, dst will be grown.

func MarshalAppendWithRegistry

func MarshalAppendWithRegistry(r *Registry, dst []byte, val interface{}) ([]byte, error)

MarshalAppendWithRegistry will append the BSON encoding of val to dst using Registry r. If dst is not large enough to hold the BSON encoding of val, dst will be grown.

func MarshalWithRegistry

func MarshalWithRegistry(r *Registry, val interface{}) ([]byte, error)

MarshalWithRegistry returns the BSON encoding of val using Registry r.

func Marshalv2

func Marshalv2(val interface{}) ([]byte, error)

Marshalv2 returns the BSON encoding of val.

Marshal will use the default registry created by NewRegistry to recursively marshal val into a []byte. Marshal will inspect struct tags and alter the marshaling process accordingly.

func ToExtJSON

func ToExtJSON(canonical bool, bson []byte) (string, error)

ToExtJSON converts a BSON byte slice into an extended JSON string. If canonical is true, it will output canonical extended JSON. Otherwise, it will output relaxed extended JSON.

func Unmarshal

func Unmarshal(in []byte, out interface{}) error

Unmarshal converts bytes into a BSON type.

The value can be any one of the following types:

In the case of struct values, only exported fields will be deserialized. The lowercased field name is used as the key for each exported field, but this behavior may be changed using a struct tag. The tag may also contain flags to adjust the unmarshaling behavior for the field. The tag formats accepted are:

"[<key>][,<flag1>[,<flag2>]]"

`(...) bson:"[<key>][,<flag1>[,<flag2>]]" (...)`

The target field or element types of out may not necessarily match the BSON values of the provided data. The following conversions are made automatically:

If the value would not fit the type and cannot be converted, it is silently skipped.

Pointer values are initialized when necessary.

func UnmarshalDocumentWithRegistry

func UnmarshalDocumentWithRegistry(r *Registry, d *Document, val interface{}) error

UnmarshalDocumentWithRegistry behaves the same as UnmarshalDocument but uses r as the *Registry.

func UnmarshalDocumentv2

func UnmarshalDocumentv2(d *Document, val interface{}) error

UnmarshalDocumentv2 parses the *Document and stores the result in the value pointed to by val. If val is nil or not a pointer, UnmarshalDocument returns InvalidUnmarshalError.

func UnmarshalWithRegistry

func UnmarshalWithRegistry(r *Registry, data []byte, val interface{}) error

UnmarshalWithRegistry parses the BSON-encoded data using Registry r and stores the result in the value pointed to by val. If val is nil or not a pointer, UnmarshalWithRegistry returns InvalidUnmarshalError.

func Unmarshalv2

func Unmarshalv2(data []byte, val interface{}) error

Unmarshalv2 parses the BSON-encoded data and stores the result in the value pointed to by val. If val is nil or not a pointer, Unmarshal returns InvalidUnmarshalError.

Types

type Array

type Array struct {
	// contains filtered or unexported fields
}

Array represents an array in BSON. The methods of this type are more expensive than those on Document because they require potentially updating multiple keys to ensure the array stays valid at all times.

Example

Code:

{
	internalVersion := "1234567"

	f := func(appName string) *Array {
		arr := NewArray()
		arr.Append(
			VC.DocumentFromElements(
				EC.String("name", "mongo-go-driver"),
				EC.String("version", internalVersion),
			),
			VC.DocumentFromElements(
				EC.String("type", "darwin"),
				EC.String("architecture", "amd64"),
			),
			VC.String("go1.9.2"),
		)
		if appName != "" {
			arr.Append(VC.DocumentFromElements(EC.String("name", appName)))
		}

		return arr
	}
	buf, err := f("hello-world").MarshalBSON()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(buf)

	// Output: [154 0 0 0 3 48 0 52 0 0 0 2 110 97 109 101 0 16 0 0 0 109 111 110 103 111 45 103 111 45 100 114 105 118 101 114 0 2 118 101 114 115 105 111 110 0 8 0 0 0 49 50 51 52 53 54 55 0 0 3 49 0 46 0 0 0 2 116 121 112 101 0 7 0 0 0 100 97 114 119 105 110 0 2 97 114 99 104 105 116 101 99 116 117 114 101 0 6 0 0 0 97 109 100 54 52 0 0 2 50 0 8 0 0 0 103 111 49 46 57 46 50 0 3 51 0 27 0 0 0 2 110 97 109 101 0 12 0 0 0 104 101 108 108 111 45 119 111 114 108 100 0 0 0]
}

Output:

[154 0 0 0 3 48 0 52 0 0 0 2 110 97 109 101 0 16 0 0 0 109 111 110 103 111 45 103 111 45 100 114 105 118 101 114 0 2 118 101 114 115 105 111 110 0 8 0 0 0 49 50 51 52 53 54 55 0 0 3 49 0 46 0 0 0 2 116 121 112 101 0 7 0 0 0 100 97 114 119 105 110 0 2 97 114 99 104 105 116 101 99 116 117 114 101 0 6 0 0 0 97 109 100 54 52 0 0 2 50 0 8 0 0 0 103 111 49 46 57 46 50 0 3 51 0 27 0 0 0 2 110 97 109 101 0 12 0 0 0 104 101 108 108 111 45 119 111 114 108 100 0 0 0]

func ArrayFromDocument

func ArrayFromDocument(doc *Document) *Array

ArrayFromDocument creates an array from a *Document. The returned array does not make a copy of the *Document, so any changes made to either will be present in both.

func NewArray

func NewArray(values ...*Value) *Array

NewArray creates a new array with the specified value.

func ParseExtJSONArray

func ParseExtJSONArray(s string) (*Array, error)

ParseExtJSONArray parses a JSON array string into a *Array.

func (*Array) Append

func (a *Array) Append(values ...*Value) *Array

Append adds the given values to the end of the array. It returns a reference to itself.

func (*Array) Concat

func (a *Array) Concat(docs ...interface{}) error

Concat will append all the values from each of the arguments onto the array.

Each argument must be one of the following:

Note that in the case of *Document, []byte, and bson.Reader, the keys will be ignored and only the values will be appended.

func (*Array) Delete

func (a *Array) Delete(index uint) *Value

Delete removes the value at the given index from the array.

func (*Array) Equal

func (a *Array) Equal(a2 *Array) bool

Equal compares this document to another, returning true if they are equal.

func (*Array) Iterator

func (a *Array) Iterator() (*ArrayIterator, error)

Iterator returns a ArrayIterator that can be used to iterate through the elements of this Array.

func (*Array) Len

func (a *Array) Len() int

Len returns the number of elements in the array.

func (*Array) Lookup

func (a *Array) Lookup(index uint) (*Value, error)

Lookup returns the value in the array at the given index or an error if it cannot be found.

TODO: We should fix this to align with the semantics of the *Document type, e.g. have Lookup return just a *Value or panic if it's out of bounds and have a LookupOK that returns a bool. Although if we want to align with the semantics of how Go arrays and slices work, we would not provide a LookupOK and force users to use the Len method before hand to avoid panics.

func (*Array) MarshalBSON

func (a *Array) MarshalBSON() ([]byte, error)

MarshalBSON implements the Marshaler interface.

func (*Array) Prepend

func (a *Array) Prepend(values ...*Value) *Array

Prepend adds the given values to the beginning of the array. It returns a reference to itself.

func (*Array) Reset

func (a *Array) Reset()

Reset clears all elements from the array.

func (*Array) Set

func (a *Array) Set(index uint, value *Value) *Array

Set replaces the value at the given index with the parameter value. It panics if the index is out of bounds.

func (*Array) String

func (a *Array) String() string

String implements the fmt.Stringer interface.

func (*Array) Validate

func (a *Array) Validate() (uint32, error)

Validate ensures that the array's underlying BSON is valid. It returns the the number of bytes in the underlying BSON if it is valid or an error if it isn't.

func (*Array) WriteArray

func (a *Array) WriteArray(start uint, writer []byte) (int64, error)

WriteArray will serialize this array to the provided writer beginning at the provided start position.

func (*Array) WriteTo

func (a *Array) WriteTo(w io.Writer) (int64, error)

WriteTo implements the io.WriterTo interface.

type ArrayCodec

type ArrayCodec struct{}

ArrayCodec is the Codec used for *Array values.

func (*ArrayCodec) DecodeValue

func (ac *ArrayCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*ArrayCodec) EncodeValue

func (ac *ArrayCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type ArrayIterator

type ArrayIterator struct {
	// contains filtered or unexported fields
}

ArrayIterator facilitates iterating over a bson.Array.

func NewArrayIterator

func NewArrayIterator(array *Array) (*ArrayIterator, error)

NewArrayIterator constructs a new ArrayIterator over a given Array

func (*ArrayIterator) Err

func (iter *ArrayIterator) Err() error

Err returns the error that occurred while iterating, or nil if none occurred.

func (*ArrayIterator) Next

func (iter *ArrayIterator) Next() bool

Next fetches the next value in the Array, returning whether or not it could be fetched successfully. If true is returned, call Value to get the value. If false is returned, call Err to check if an error occurred.

func (*ArrayIterator) Value

func (iter *ArrayIterator) Value() *Value

Value returns the current value of the ArrayIterator. The pointer returned will _always_ be the same for a given ArrayIterator. The returned value will be nil if this function is called before the first successful call to Next().

type ArrayReader

type ArrayReader interface {
	ReadValue() (ValueReader, error)
}

ArrayReader is implemented by types that allow reading values from a BSON array.

type ArrayWriter

type ArrayWriter interface {
	WriteArrayElement() (ValueWriter, error)
	WriteArrayEnd() error
}

ArrayWriter is the interface used to create a BSON or BSON adjacent array. Callers must ensure they call WriteArrayEnd when they have finished creating the array.

type Binary

type Binary struct {
	Subtype byte
	Data    []byte
}

Binary represents a BSON binary value.

type BinaryCodec

type BinaryCodec struct{}

BinaryCodec is the Codec used for Binary values.

func (*BinaryCodec) DecodeValue

func (bc *BinaryCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*BinaryCodec) EncodeValue

func (bc *BinaryCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type BooleanCodec

type BooleanCodec struct{}

BooleanCodec is the Codec used for bool values.

func (*BooleanCodec) DecodeValue

func (bc *BooleanCodec) DecodeValue(dctx DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*BooleanCodec) EncodeValue

func (bc *BooleanCodec) EncodeValue(ectx EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type ByteSliceCodec

type ByteSliceCodec struct{}

ByteSliceCodec is the Codec for []byte values.

func (*ByteSliceCodec) DecodeValue

func (bsc *ByteSliceCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*ByteSliceCodec) EncodeValue

func (bsc *ByteSliceCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type CodeWithScope

type CodeWithScope struct {
	Code  string
	Scope *Document
}

CodeWithScope represents a BSON JavaScript code with scope value.

func (CodeWithScope) String

func (cws CodeWithScope) String() string

type CodeWithScopeCodec

type CodeWithScopeCodec struct{}

CodeWithScopeCodec is the Codec for CodeWithScope values.

func (*CodeWithScopeCodec) DecodeValue

func (cwsc *CodeWithScopeCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*CodeWithScopeCodec) EncodeValue

func (cwsc *CodeWithScopeCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type Codec

type Codec interface {
	EncodeValue(EncodeContext, ValueWriter, interface{}) error
	DecodeValue(DecodeContext, ValueReader, interface{}) error
}

Codec implementations handle encoding and decoding values. They can be registered in a registry which will handle invoking them. Callers of the DecodeValue methods pass in a pointer to the value, and implementations operate on a pointer to the value. This is true of pointer values as well, so a caller of DecodeValue for a pointer type *Foo will pass in **Foo.

type CodecDecodeError

type CodecDecodeError struct {
	Codec    interface{}
	Types    []interface{}
	Received interface{}
}

CodecDecodeError is an error returned from a Codec's DecodeValue method when the provided value can't be decoded with the given Codec.

func (CodecDecodeError) Error

func (dee CodecDecodeError) Error() string

type CodecEncodeError

type CodecEncodeError struct {
	Codec    interface{}
	Types    []interface{}
	Received interface{}
}

CodecEncodeError is an error returned from a Codec's EncodeValue method when the provided value can't be encoded with the given Codec.

func (CodecEncodeError) Error

func (cee CodecEncodeError) Error() string

type CodecZeroer

type CodecZeroer interface {
	Codec
	IsZero(interface{}) bool
}

CodecZeroer is the interface implemented by Codecs that can also determine if a value of the type that would be encoded is zero.

type DBPointer

type DBPointer struct {
	DB      string
	Pointer objectid.ObjectID
}

DBPointer represents a BSON dbpointer value.

func (DBPointer) String

func (d DBPointer) String() string

type DBPointerCodec

type DBPointerCodec struct{}

DBPointerCodec is the Codec for DBPointer values.

func (*DBPointerCodec) DecodeValue

func (dbpc *DBPointerCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*DBPointerCodec) EncodeValue

func (dbpc *DBPointerCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type DateTime

type DateTime int64

DateTime represents the BSON datetime value.

type DateTimeCodec

type DateTimeCodec struct{}

DateTimeCodec is the Codec for DateTime values.

func (*DateTimeCodec) DecodeValue

func (dtc *DateTimeCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*DateTimeCodec) EncodeValue

func (dtc *DateTimeCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type Decimal128Codec

type Decimal128Codec struct{}

Decimal128Codec is the Codec for decimal.Decimal128 values.

func (*Decimal128Codec) DecodeValue

func (dc *Decimal128Codec) DecodeValue(dctx DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*Decimal128Codec) EncodeValue

func (dc *Decimal128Codec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type DecodeContext

type DecodeContext struct {
	*Registry
	Truncate bool
}

DecodeContext is the contextual information required for a Codec to decode a value.

type Decoder

type Decoder interface {
	Decode(interface{}) error
}

Decoder describes a BSON representation that can decodes itself into a value.

func NewDecoder

func NewDecoder(r io.Reader) Decoder

NewDecoder constructs a new default Decoder implementation from the given io.Reader.

In this implementation, the value can be any one of the following types:

In the case of struct values, only exported fields will be deserialized. The lowercased field name is used as the key for each exported field, but this behavior may be changed using a struct tag. The tag may also contain flags to adjust the unmarshaling behavior for the field. The tag formats accepted are:

"[<key>][,<flag1>[,<flag2>]]"

`(...) bson:"[<key>][,<flag1>[,<flag2>]]" (...)`

The target field or element types of out may not necessarily match the BSON values of the provided data. The following conversions are made automatically:

If the value would not fit the type and cannot be converted, it is silently skipped.

Pointer values are initialized when necessary.

type Decoderv2

type Decoderv2 struct {
	// contains filtered or unexported fields
}

A Decoderv2 reads and decodes BSON documents from a stream.

func NewDecoderv2

func NewDecoderv2(r *Registry, vr ValueReader) (*Decoderv2, error)

NewDecoderv2 returns a new decoder that uses Registry reg to read from r.

func (*Decoderv2) Decode

func (d *Decoderv2) Decode(val interface{}) error

Decode reads the next BSON document from the stream and decodes it into the value pointed to by val.

The documentation for Unmarshal contains details about of BSON into a Go value.

func (*Decoderv2) Reset

func (d *Decoderv2) Reset(vr ValueReader) error

Reset will reset the state of the decoder, using the same *Registry used in the original construction but using r for reading.

func (*Decoderv2) SetRegistry

func (d *Decoderv2) SetRegistry(r *Registry) error

SetRegistry replaces the current registry of the decoder with r.

type Document

type Document struct {
	// The default behavior or Append, Prepend, and Replace is to panic on the
	// insertion of a nil element. Setting IgnoreNilInsert to true will instead
	// silently ignore any nil parameters to these methods.
	IgnoreNilInsert bool
	// contains filtered or unexported fields
}

Document is a mutable ordered map that compactly represents a BSON document.

Example

Code:

{
	internalVersion := "1234567"

	f := func(appName string) *Document {
		doc := NewDocument(
			EC.SubDocumentFromElements("driver",
				EC.String("name", "mongo-go-driver"),
				EC.String("version", internalVersion),
			),
			EC.SubDocumentFromElements("os",
				EC.String("type", "darwin"),
				EC.String("architecture", "amd64"),
			),
			EC.String("platform", "go1.9.2"),
		)
		if appName != "" {
			doc.Append(EC.SubDocumentFromElements("application", EC.String("name", appName)))
		}

		return doc
	}
	buf, err := f("hello-world").MarshalBSON()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(buf)

	// Output: [177 0 0 0 3 100 114 105 118 101 114 0 52 0 0 0 2 110 97 109 101 0 16 0 0 0 109 111 110 103 111 45 103 111 45 100 114 105 118 101 114 0 2 118 101 114 115 105 111 110 0 8 0 0 0 49 50 51 52 53 54 55 0 0 3 111 115 0 46 0 0 0 2 116 121 112 101 0 7 0 0 0 100 97 114 119 105 110 0 2 97 114 99 104 105 116 101 99 116 117 114 101 0 6 0 0 0 97 109 100 54 52 0 0 2 112 108 97 116 102 111 114 109 0 8 0 0 0 103 111 49 46 57 46 50 0 3 97 112 112 108 105 99 97 116 105 111 110 0 27 0 0 0 2 110 97 109 101 0 12 0 0 0 104 101 108 108 111 45 119 111 114 108 100 0 0 0]
}

Output:

[177 0 0 0 3 100 114 105 118 101 114 0 52 0 0 0 2 110 97 109 101 0 16 0 0 0 109 111 110 103 111 45 103 111 45 100 114 105 118 101 114 0 2 118 101 114 115 105 111 110 0 8 0 0 0 49 50 51 52 53 54 55 0 0 3 111 115 0 46 0 0 0 2 116 121 112 101 0 7 0 0 0 100 97 114 119 105 110 0 2 97 114 99 104 105 116 101 99 116 117 114 101 0 6 0 0 0 97 109 100 54 52 0 0 2 112 108 97 116 102 111 114 109 0 8 0 0 0 103 111 49 46 57 46 50 0 3 97 112 112 108 105 99 97 116 105 111 110 0 27 0 0 0 2 110 97 109 101 0 12 0 0 0 104 101 108 108 111 45 119 111 114 108 100 0 0 0]

func MarshalDocument

func MarshalDocument(val interface{}) (*Document, error)

MarshalDocument returns val encoded as a *Document.

MarshalDocument will use the default registry created by NewRegistry to recursively marshal val into a *Document. MarshalDocument will inspect struct tags and alter the marshaling process accordingly.

func MarshalDocumentAppend

func MarshalDocumentAppend(dst *Document, val interface{}) (*Document, error)

MarshalDocumentAppend will append val encoded to dst. If dst is nil, a new *Document will be allocated and the encoding of val will be appended to that.

func MarshalDocumentAppendWithRegistry

func MarshalDocumentAppendWithRegistry(r *Registry, dst *Document, val interface{}) (*Document, error)

MarshalDocumentAppendWithRegistry will append val encoded to dst using r. If dst is nil, a new *Document will be allocated and the encoding of val will be appended to that.

func MarshalDocumentWithRegistry

func MarshalDocumentWithRegistry(r *Registry, val interface{}) (*Document, error)

MarshalDocumentWithRegistry returns val encoded as a *Document using r.

func NewDocument

func NewDocument(elems ...*Element) *Document

NewDocument creates an empty Document. The numberOfElems parameter will preallocate the underlying storage which can prevent extra allocations.

func ParseExtJSONObject

func ParseExtJSONObject(s string) (*Document, error)

ParseExtJSONObject parses a JSON object string into a *Document.

func ReadDocument

func ReadDocument(b []byte) (*Document, error)

ReadDocument will create a Document using the provided slice of bytes. If the slice of bytes is not a valid BSON document, this method will return an error.

func UnmarshalDocument

func UnmarshalDocument(bson []byte) (*Document, error)

UnmarshalDocument converts bytes into a *bson.Document.

func (*Document) Append

func (d *Document) Append(elems ...*Element) *Document

Append adds each element to the end of the document, in order. If a nil element is passed as a parameter this method will panic. To change this behavior to silently ignore a nil element, set IgnoreNilInsert to true on the Document.

If a nil element is inserted and this method panics, it does not remove the previously added elements.

func (*Document) Concat

func (d *Document) Concat(docs ...interface{}) error

Concat will take the keys from the provided document and concat them onto the end of this document.

doc must be one of the following:

func (*Document) Copy

func (d *Document) Copy() *Document

Copy makes a shallow copy of this document.

func (*Document) Delete

func (d *Document) Delete(key ...string) *Element

Delete removes the keys from the Document. The deleted element is returned. If the key does not exist, then nil is returned and the delete is a no-op. The same is true if something along the depth tree does not exist or is not a traversable type.

func (*Document) ElementAt

func (d *Document) ElementAt(index uint) *Element

ElementAt retrieves the element at the given index in a Document. It panics if the index is out-of-bounds.

TODO(skriptble): This method could be variadic and return the element at the provided depth.

func (*Document) ElementAtOK

func (d *Document) ElementAtOK(index uint) (*Element, bool)

ElementAtOK is the same as ElementAt, but returns a boolean instead of panicking.

func (*Document) Equal

func (d *Document) Equal(d2 *Document) bool

Equal compares this document to another, returning true if they are equal.

func (*Document) Iterator

func (d *Document) Iterator() *Iterator

Iterator creates an Iterator for this document and returns it.

func (*Document) Keys

func (d *Document) Keys(recursive bool) (Keys, error)

Keys returns all of the element keys for this document. If recursive is true, this method will also return the keys of any subdocuments or arrays.

func (*Document) Len

func (d *Document) Len() int

Len returns the number of elements in the document.

func (*Document) Lookup

func (d *Document) Lookup(key ...string) *Value

Lookup searches the document and potentially subdocuments or arrays for the provided key. Each key provided to this method represents a layer of depth.

Lookup will return nil if it encounters an error.

func (*Document) LookupElement

func (d *Document) LookupElement(key ...string) *Element

LookupElement searches the document and potentially subdocuments or arrays for the provided key. Each key provided to this method represents a layer of depth.

LookupElement will return nil if it encounters an error.

func (*Document) LookupElementErr

func (d *Document) LookupElementErr(key ...string) (*Element, error)

LookupElementErr searches the document and potentially subdocuments or arrays for the provided key. Each key provided to this method represents a layer of depth.

func (*Document) LookupErr

func (d *Document) LookupErr(key ...string) (*Value, error)

LookupErr searches the document and potentially subdocuments or arrays for the provided key. Each key provided to this method represents a layer of depth.

func (*Document) MarshalBSON

func (d *Document) MarshalBSON() ([]byte, error)

MarshalBSON implements the Marshaler interface.

func (*Document) Prepend

func (d *Document) Prepend(elems ...*Element) *Document

Prepend adds each element to the beginning of the document, in order. If a nil element is passed as a parameter this method will panic. To change this behavior to silently ignore a nil element, set IgnoreNilInsert to true on the Document.

If a nil element is inserted and this method panics, it does not remove the previously added elements.

func (*Document) ReadFrom

func (d *Document) ReadFrom(r io.Reader) (int64, error)

ReadFrom will read one BSON document from the given io.Reader.

func (*Document) Reset

func (d *Document) Reset()

Reset clears a document so it can be reused. This method clears references to the underlying pointers to elements so they can be garbage collected.

func (*Document) Set

func (d *Document) Set(elem *Element) *Document

Set replaces an element of a document. If an element with a matching key is found, the element will be replaced with the one provided. If the document does not have an element with that key, the element is appended to the document instead. If a nil element is passed as a parameter this method will panic. To change this behavior to silently ignore a nil element, set IgnoreNilInsert to true on the Document.

If a nil element is inserted and this method panics, it does not remove the previously added elements.

TODO(skriptble): Do we need to panic on a nil element? Semantically, if you ask to replace an element in the document with a nil element, you aren't asking for anything to be done.

func (*Document) String

func (d *Document) String() string

String implements the fmt.Stringer interface.

func (*Document) ToExtJSON

func (d *Document) ToExtJSON(canonical bool) string

ToExtJSON marshals this document to BSON and transforms that BSON to extended JSON. If there is an error during the conversion, this method will return an empty string. To receive the error, use the ToExtJSONErr method.

func (*Document) ToExtJSONErr

func (d *Document) ToExtJSONErr(canonical bool) (string, error)

ToExtJSONErr marshals this document to BSON and transforms that BSON to extended JSON.

func (*Document) UnmarshalBSON

func (d *Document) UnmarshalBSON(b []byte) error

UnmarshalBSON implements the Unmarshaler interface.

func (*Document) Validate

func (d *Document) Validate() (uint32, error)

Validate validates the document and returns its total size.

func (*Document) WriteDocument

func (d *Document) WriteDocument(start uint, writer interface{}) (int64, error)

WriteDocument will serialize this document to the provided writer beginning at the provided start position.

func (*Document) WriteTo

func (d *Document) WriteTo(w io.Writer) (int64, error)

WriteTo implements the io.WriterTo interface.

TODO(skriptble): We can optimize this by having creating implementations of writeByteSlice that write directly to an io.Writer instead.

type DocumentCodec

type DocumentCodec struct{}

DocumentCodec is the Codec used for *Document values.

func (*DocumentCodec) DecodeValue

func (dc *DocumentCodec) DecodeValue(dctx DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*DocumentCodec) EncodeValue

func (dc *DocumentCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type DocumentEncoder

type DocumentEncoder interface {
	EncodeDocument(interface{}) (*Document, error)
}

DocumentEncoder describes a type that can marshal itself into a value and return the bson.Document it represents.

func NewDocumentEncoder

func NewDocumentEncoder() DocumentEncoder

NewDocumentEncoder creates an encoder that encodes into a *Document.

type DocumentMarshaler

type DocumentMarshaler interface {
	MarshalBSONDocument() (*Document, error)
}

DocumentMarshaler describes a type that can marshal itself into a bson.Document.

type DocumentReader

type DocumentReader interface {
	ReadElement() (string, ValueReader, error)
}

DocumentReader is implemented by types that allow reading elements from a BSON document.

type DocumentUnmarshaler

type DocumentUnmarshaler interface {
	UnmarshalBSONDocument(*Document) error
}

DocumentUnmarshaler describes a type that can unmarshal itself from a bson.Document.

type DocumentWriter

type DocumentWriter interface {
	WriteDocumentElement(string) (ValueWriter, error)
	WriteDocumentEnd() error
}

DocumentWriter is the interface used to create a BSON or BSON adjacent document. Callers must ensure they call WriteDocumentEnd when they have finished creating the document.

type Element

type Element struct {
	// contains filtered or unexported fields
}

Element represents a BSON element, i.e. key-value pair of a BSON document.

func (*Element) Clone

func (e *Element) Clone() *Element

Clone creates a shallow copy of the element/

func (*Element) Key

func (e *Element) Key() string

Key returns the key for this element. It panics if e is uninitialized.

func (*Element) MarshalBSON

func (e *Element) MarshalBSON() ([]byte, error)

MarshalBSON implements the Marshaler interface.

func (*Element) String

func (e *Element) String() string

String implements the fmt.Stringer interface.

func (*Element) Validate

func (e *Element) Validate() (uint32, error)

Validate validates the element and returns its total size.

func (*Element) Value

func (e *Element) Value() *Value

Value returns the value associated with the BSON element.

func (*Element) WriteElement

func (e *Element) WriteElement(start uint, writer interface{}) (int64, error)

WriteElement serializes this element to the provided writer starting at the provided start position.

func (*Element) WriteTo

func (e *Element) WriteTo(w io.Writer) (int64, error)

WriteTo implements the io.WriterTo interface.

type ElementConstructor

type ElementConstructor struct{}

ElementConstructor is used as a namespace for document element constructor functions.

EC is a convenience variable provided for access to the ElementConstructor methods.

func (ElementConstructor) Array

func (ElementConstructor) Array(key string, a *Array) *Element

Array creates an array element with the given key and value.

func (ElementConstructor) ArrayFromElements

func (c ElementConstructor) ArrayFromElements(key string, values ...*Value) *Element

ArrayFromElements creates an element with the given key. The elements passed as arguments will be used to create a new array as the value.

func (ElementConstructor) Binary

func (c ElementConstructor) Binary(key string, b []byte) *Element

Binary creates a binary element with the given key and value.

func (ElementConstructor) BinaryWithSubtype

func (ElementConstructor) BinaryWithSubtype(key string, b []byte, btype byte) *Element

BinaryWithSubtype creates a binary element with the given key. It will create a new BSON binary value with the given data and subtype.

func (ElementConstructor) Boolean

func (ElementConstructor) Boolean(key string, b bool) *Element

Boolean creates a boolean element with the given key and value.

func (ElementConstructor) CodeWithScope

func (ElementConstructor) CodeWithScope(key string, code string, scope *Document) *Element

CodeWithScope creates a JavaScript code with scope element with the given key and value.

func (ElementConstructor) DBPointer

func (ElementConstructor) DBPointer(key string, ns string, oid objectid.ObjectID) *Element

DBPointer creates a dbpointer element with the given key and value.

func (ElementConstructor) DateTime

func (ElementConstructor) DateTime(key string, dt int64) *Element

DateTime creates a datetime element with the given key and value. dt represents milliseconds since the Unix epoch

func (ElementConstructor) Decimal128

func (ElementConstructor) Decimal128(key string, d decimal.Decimal128) *Element

Decimal128 creates a decimal element with the given key and value.

func (ElementConstructor) Double

func (ElementConstructor) Double(key string, f float64) *Element

Double creates a double element with the given key and value.

func (ElementConstructor) Int32

func (ElementConstructor) Int32(key string, i int32) *Element

Int32 creates a int32 element with the given key and value.

func (ElementConstructor) Int64

func (ElementConstructor) Int64(key string, i int64) *Element

Int64 creates a int64 element with the given key and value.

func (ElementConstructor) Interface

func (ElementConstructor) Interface(key string, value interface{}) *Element

Interface will attempt to turn the provided key and value into an Element. For common types, type casting is used, if the type is more complex, such as a map or struct, reflection is used. If the value cannot be converted either by typecasting or through reflection, a null Element is constructed with the key. This method will never return a nil *Element. If an error turning the value into an Element is desired, use the InterfaceErr method.

func (ElementConstructor) InterfaceErr

func (c ElementConstructor) InterfaceErr(key string, value interface{}) (*Element, error)

InterfaceErr does what Interface does, but returns an error when it cannot properly convert a value into an *Element. See Interface for details.

func (ElementConstructor) JavaScript

func (ElementConstructor) JavaScript(key string, code string) *Element

JavaScript creates a JavaScript code element with the given key and value.

func (ElementConstructor) MaxKey

func (ElementConstructor) MaxKey(key string) *Element

MaxKey creates a maxkey element with the given key and value.

func (ElementConstructor) MinKey

func (ElementConstructor) MinKey(key string) *Element

MinKey creates a minkey element with the given key and value.

func (ElementConstructor) Null

func (ElementConstructor) Null(key string) *Element

Null creates a null element with the given key.

func (ElementConstructor) ObjectID

func (ElementConstructor) ObjectID(key string, oid objectid.ObjectID) *Element

ObjectID creates a objectid element with the given key and value.

func (ElementConstructor) Regex

func (ElementConstructor) Regex(key string, pattern, options string) *Element

Regex creates a regex element with the given key and value.

func (ElementConstructor) String

func (ElementConstructor) String(key string, val string) *Element

String creates a string element with the given key and value.

func (ElementConstructor) SubDocument

func (ElementConstructor) SubDocument(key string, d *Document) *Element

SubDocument creates a subdocument element with the given key and value.

func (ElementConstructor) SubDocumentFromElements

func (c ElementConstructor) SubDocumentFromElements(key string, elems ...*Element) *Element

SubDocumentFromElements creates a subdocument element with the given key. The elements passed as arguments will be used to create a new document as the value.

func (ElementConstructor) SubDocumentFromReader

func (ElementConstructor) SubDocumentFromReader(key string, r Reader) *Element

SubDocumentFromReader creates a subdocument element with the given key and value.

func (ElementConstructor) Symbol

func (ElementConstructor) Symbol(key string, symbol string) *Element

Symbol creates a symbol element with the given key and value.

func (ElementConstructor) Time

func (c ElementConstructor) Time(key string, t time.Time) *Element

Time creates a datetime element with the given key and value.

func (ElementConstructor) Timestamp

func (ElementConstructor) Timestamp(key string, t uint32, i uint32) *Element

Timestamp creates a timestamp element with the given key and value.

func (ElementConstructor) Undefined

func (ElementConstructor) Undefined(key string) *Element

Undefined creates a undefined element with the given key.

type ElementMarshaler

type ElementMarshaler interface {
	MarshalBSONElement() (*Element, error)
}

ElementMarshaler describes a type that can marshal itself into a bson.Element.

type ElementSliceCodec

type ElementSliceCodec struct{}

ElementSliceCodec is the Codec for []*Element values.

func (*ElementSliceCodec) DecodeValue

func (esc *ElementSliceCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*ElementSliceCodec) EncodeValue

func (esc *ElementSliceCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type ElementTypeError

type ElementTypeError struct {
	Method string
	Type   Type
}

ElementTypeError specifies that a method to obtain a BSON value an incorrect type was called on a bson.Value.

func (ElementTypeError) Error

func (ete ElementTypeError) Error() string

Error implements the error interface.

type EmptyInterfaceCodec

type EmptyInterfaceCodec struct{}

EmptyInterfaceCodec is the Codec used for empty interface (interface{}) values.

func (*EmptyInterfaceCodec) DecodeValue

func (eic *EmptyInterfaceCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*EmptyInterfaceCodec) EncodeValue

func (eic *EmptyInterfaceCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type EncodeContext

type EncodeContext struct {
	*Registry
	MinSize bool
}

EncodeContext is the contextual information required for a Codec to encode a value.

type Encoder

type Encoder interface {
	// Encode encodes a value from an io.Writer into the given value.
	//
	// The value can be any one of the following types:
	//
	//   - bson.Marshaler
	//   - io.Reader
	//   - []byte
	//   - bson.Reader
	//   - any map with string keys
	//   - a struct (possibly with tags)
	//
	// In the case of a struct, the lowercased field name is used as the key for each exported
	// field but this behavior may be changed using a struct tag. The tag may also contain flags to
	// adjust the marshalling behavior for the field. The tag formats accepted are:
	//
	//     "[<key>][,<flag1>[,<flag2>]]"
	//
	//     `(...) bson:"[<key>][,<flag1>[,<flag2>]]" (...)`
	//
	// The following flags are currently supported:
	//
	//     omitempty  Only include the field if it's not set to the zero value for the type or to
	//                empty slices or maps.
	//
	//     minsize    Marshal an integer of a type larger than 32 bits value as an int32, if that's
	//                feasible while preserving the numeric value.
	//
	//     inline     Inline the field, which must be a struct or a map, causing all of its fields
	//                or keys to be processed as if they were part of the outer struct.
	//
	// An example:
	//
	//     type T struct {
	//         A bool
	//         B int    "myb"
	//         C string "myc,omitempty"
	//         D string `bson:",omitempty" json:"jsonkey"`
	//         E int64  ",minsize"
	//         F int64  "myf,omitempty,minsize"
	//     }
	Encode(interface{}) error
}

Encoder describes a type that can encode itself into a value.

func NewEncoder

func NewEncoder(w io.Writer) Encoder

NewEncoder creates an encoder that writes to w.

type Encoderv2

type Encoderv2 struct {
	// contains filtered or unexported fields
}

An Encoderv2 writes a serialization format to an output stream.

func NewEncoderv2

func NewEncoderv2(r *Registry, vw ValueWriter) (*Encoderv2, error)

NewEncoderv2 returns a new encoder that uses Registry r to write to w.

func (*Encoderv2) Encode

func (e *Encoderv2) Encode(val interface{}) error

Encode writes the BSON encoding of val to the stream.

The documentation for Marshal contains details about the conversion of Go values to BSON.

func (*Encoderv2) Reset

func (e *Encoderv2) Reset(vw ValueWriter) error

Reset will reset the state of the encoder, using the same *Registry used in the original construction but using vw.

func (*Encoderv2) SetRegistry

func (e *Encoderv2) SetRegistry(r *Registry) error

SetRegistry replaces the current registry of the encoder with r.

type ErrNoCodec

type ErrNoCodec struct {
	Type reflect.Type
}

ErrNoCodec is returned when there is no codec available for a type or interface in the registry.

func (ErrNoCodec) Error

func (enc ErrNoCodec) Error() string

type ErrTooSmall

type ErrTooSmall struct {
	Stack stack.CallStack
}

ErrTooSmall indicates that a slice provided to write into is not large enough to fit the data.

func NewErrTooSmall

func NewErrTooSmall() ErrTooSmall

NewErrTooSmall creates a new ErrTooSmall with the given message and the current stack.

func (ErrTooSmall) Equals

func (e ErrTooSmall) Equals(err2 error) bool

Equals checks that err2 also is an ErrTooSmall.

func (ErrTooSmall) Error

func (e ErrTooSmall) Error() string

Error implements the error interface.

func (ErrTooSmall) ErrorStack

func (e ErrTooSmall) ErrorStack() string

ErrorStack returns a string representing the stack at the point where the error occurred.

type FloatCodec

type FloatCodec struct{}

FloatCodec is the Codec used for float32 and float64 values.

func (*FloatCodec) DecodeValue

func (fc *FloatCodec) DecodeValue(ec DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*FloatCodec) EncodeValue

func (fc *FloatCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type IntCodec

type IntCodec struct{}

IntCodec is the Codec used for int8, int16, int32, int64, and int values.

func (*IntCodec) DecodeValue

func (ic *IntCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*IntCodec) EncodeValue

func (ic *IntCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type Iterator

type Iterator struct {
	// contains filtered or unexported fields
}

Iterator facilitates iterating over a bson.Document.

func (*Iterator) Element

func (itr *Iterator) Element() *Element

Element returns the current element of the Iterator. The pointer that it returns will _always_ be the same for a given Iterator.

func (*Iterator) Err

func (itr *Iterator) Err() error

Err returns the error that occurred when iterating, or nil if none occurred.

func (*Iterator) Next

func (itr *Iterator) Next() bool

Next fetches the next element of the document, returning whether or not the next element was able to be fetched. If true is returned, then call Element to get the element. If false is returned, call Err to check if an error occurred.

type JSONNumberCodec

type JSONNumberCodec struct{}

JSONNumberCodec is the Codec for json.Number values.

func (*JSONNumberCodec) DecodeValue

func (jnc *JSONNumberCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*JSONNumberCodec) EncodeValue

func (jnc *JSONNumberCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type JavaScriptCode

type JavaScriptCode string

JavaScriptCode represents a BSON JavaScript code value.

type Key

type Key struct {
	Prefix []string
	Name   string
}

Key represents an individual key of a BSON document. The Prefix property is used to represent the depth of this key.

func (Key) String

func (k Key) String() string

String implements the fmt.Stringer interface.

type Keys

type Keys []Key

Keys represents the keys of a BSON document.

type MapCodec

type MapCodec struct{}

MapCodec is the Codec used for map values.

func (*MapCodec) DecodeValue

func (mc *MapCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*MapCodec) EncodeValue

func (mc *MapCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type Marshaler

type Marshaler interface {
	MarshalBSON() ([]byte, error)
}

Marshaler describes a type that can marshal a BSON representation of itself into bytes.

type MaxKeyCodec

type MaxKeyCodec struct{}

MaxKeyCodec is the Codec for MaxKey values.

func (*MaxKeyCodec) DecodeValue

func (mkc *MaxKeyCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*MaxKeyCodec) EncodeValue

func (mkc *MaxKeyCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type MaxKeyv2

type MaxKeyv2 struct{}

MaxKeyv2 represents the BSON maxkey value.

type MinKeyCodec

type MinKeyCodec struct{}

MinKeyCodec is the Codec for MinKey values.

func (*MinKeyCodec) DecodeValue

func (mkc *MinKeyCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*MinKeyCodec) EncodeValue

func (mkc *MinKeyCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type MinKeyv2

type MinKeyv2 struct{}

MinKeyv2 represents the BSON minkey value.

type NullCodec

type NullCodec struct{}

NullCodec is the Codec for Null values.

func (*NullCodec) DecodeValue

func (nc *NullCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*NullCodec) EncodeValue

func (nc *NullCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type Nullv2

type Nullv2 struct{}

Nullv2 repreesnts the BSON null value.

type ObjectIDCodec

type ObjectIDCodec struct{}

ObjectIDCodec is the Codec for objectid.ObjectID values.

func (*ObjectIDCodec) DecodeValue

func (oidc *ObjectIDCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*ObjectIDCodec) EncodeValue

func (oidc *ObjectIDCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type Reader

type Reader []byte

Reader is a wrapper around a byte slice. It will interpret the slice as a BSON document. Most of the methods on Reader are low cost and are meant for simple operations that are run a few times. Because there is no metadata stored all methods run in O(n) time. If a more efficient lookup method is necessary then the Document type should be used.

func NewFromIOReader

func NewFromIOReader(r io.Reader) (Reader, error)

NewFromIOReader reads in a document from the given io.Reader and constructs a bson.Reader from it.

func (Reader) ElementAt

func (r Reader) ElementAt(index uint) (*Element, error)

ElementAt searches for a retrieves the element at the given index. This method will validate all the elements up to and including the element at the given index.

func (Reader) Iterator

func (r Reader) Iterator() (*ReaderIterator, error)

Iterator returns a ReaderIterator that can be used to iterate through the elements of this Reader.

func (Reader) Keys

func (r Reader) Keys(recursive bool) (Keys, error)

Keys returns the keys for this document. If recursive is true then this method will also return the keys for subdocuments and arrays.

The keys will be return in order.

func (Reader) Lookup

func (r Reader) Lookup(key ...string) (*Element, error)

Lookup search the document, potentially recursively, for the given key. If there are multiple keys provided, this method will recurse down, as long as the top and intermediate nodes are either documents or arrays. If any key except for the last is not a document or an array, an error will be returned.

TODO(skriptble): Implement better error messages.

TODO(skriptble): Determine if this should return an error on empty key and key not found.

func (Reader) String

func (r Reader) String() string

String implements the fmt.Stringer interface.

func (Reader) Validate

func (r Reader) Validate() (size uint32, err error)

Validate validates the document. This method only validates the first document in the slice, to validate other documents, the slice must be resliced.

Example

Code:

{
	rdr := make(Reader, 500)
	rdr[250], rdr[251], rdr[252], rdr[253], rdr[254] = '\x05', '\x00', '\x00', '\x00', '\x00'
	n, err := rdr[250:].Validate()
	fmt.Println(n, err)

	// Output: 5 <nil>
}

Output:

5 <nil>

type ReaderCodec

type ReaderCodec struct{}

ReaderCodec is the Codec for Reader values.

func (*ReaderCodec) DecodeValue

func (rc *ReaderCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*ReaderCodec) EncodeValue

func (rc *ReaderCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type ReaderIterator

type ReaderIterator struct {
	// contains filtered or unexported fields
}

ReaderIterator facilitates iterating over a bson.Reader.

func NewReaderIterator

func NewReaderIterator(r Reader) (*ReaderIterator, error)

NewReaderIterator constructors a new ReaderIterator over a given Reader.

func (*ReaderIterator) Element

func (itr *ReaderIterator) Element() *Element

Element returns the current element of the ReaderIterator. The pointer that it returns will _always_ be the same for a given ReaderIterator.

func (*ReaderIterator) Err

func (itr *ReaderIterator) Err() error

Err returns the error that occurred when iterating, or nil if none occurred.

func (*ReaderIterator) Next

func (itr *ReaderIterator) Next() bool

Next fetches the next element of the Reader, returning whether or not the next element was able to be fetched. If true is returned, then call Element to get the element. If false is returned, call Err to check if an error occurred.

type Regex

type Regex struct {
	Pattern string
	Options string
}

Regex represents a BSON regex value.

func (Regex) String

func (r Regex) String() string

type RegexCodec

type RegexCodec struct{}

RegexCodec is the Codec for Regex values.

func (*RegexCodec) DecodeValue

func (rc *RegexCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*RegexCodec) EncodeValue

func (rc *RegexCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

A Registry is used to store and retrieve codecs for types and interfaces. This type is the main typed passed around and Encoders and Decoders are constructed from it.

TODO: Create a RegistryBuilder type and make the Registry type immutable.

func (*Registry) Lookup

func (r *Registry) Lookup(t reflect.Type) (Codec, error)

Lookup will inspect the type registry for either the type or a pointer to the type, if it doesn't find a codec it will inspect the interface registry for an interface that the type satisfies, if it doesn't find a codec there it will attempt to return either the default map codec or the default struct codec. If none of those apply, an error will be returned.

type RegistryBuilder

type RegistryBuilder struct {
	// contains filtered or unexported fields
}

A RegistryBuilder is used to build a Registry. This type is not goroutine safe.

func NewEmptyRegistryBuilder

func NewEmptyRegistryBuilder() *RegistryBuilder

NewEmptyRegistryBuilder creates a new RegistryBuilder with no default kind Codecs.

func NewRegistryBuilder

func NewRegistryBuilder() *RegistryBuilder

NewRegistryBuilder creates a new RegistryBuilder.

func (*RegistryBuilder) Build

func (rb *RegistryBuilder) Build() *Registry

Build creates a Registry from the current state of this RegistryBuilder.

func (*RegistryBuilder) Register

func (rb *RegistryBuilder) Register(t reflect.Type, codec Codec) *RegistryBuilder

Register will register the provided Codec to the provided type. If the type is an interface, it will be registered in the interface registry. If the type is a pointer to or a type that is not an interface, it will be registered in the type registry.

func (*RegistryBuilder) RegisterDefault

func (rb *RegistryBuilder) RegisterDefault(kind reflect.Kind, codec Codec) *RegistryBuilder

RegisterDefault will register the provided Codec to the provided kind.

type SliceCodec

type SliceCodec struct{}

SliceCodec is the Codec used for slice and array values.

func (*SliceCodec) DecodeValue

func (sc *SliceCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*SliceCodec) EncodeValue

func (sc *SliceCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type StringCodec

type StringCodec struct{}

StringCodec is the Codec used for string values.

func (*StringCodec) DecodeValue

func (sc *StringCodec) DecodeValue(dctx DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*StringCodec) EncodeValue

func (sc *StringCodec) EncodeValue(ectx EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type StructCodec

type StructCodec struct {
	// contains filtered or unexported fields
}

StructCodec is the Codec used for struct values.

func NewStructCodec

func NewStructCodec(p StructTagParser) (*StructCodec, error)

NewStructCodec returns a StructCodec that uses p for struct tag parsing.

func (*StructCodec) DecodeValue

func (sc *StructCodec) DecodeValue(r DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*StructCodec) EncodeValue

func (sc *StructCodec) EncodeValue(r EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue handles encoding generic struct types.

type StructTagParser

type StructTagParser interface {
	ParseStructTags(reflect.StructField) (StructTags, error)
}

StructTagParser returns the struct tags for a given struct field.

type StructTagParserFunc

type StructTagParserFunc func(reflect.StructField) (StructTags, error)

StructTagParserFunc is an adapter that allows a generic function to be used as a StructTagParser.

var DefaultStructTagParser StructTagParserFunc = func(sf reflect.StructField) (StructTags, error) {
	key := strings.ToLower(sf.Name)
	tag, ok := sf.Tag.Lookup("bson")
	if !ok && !strings.Contains(string(sf.Tag), ":") && len(sf.Tag) > 0 {
		tag = string(sf.Tag)
	}
	var st StructTags
	if tag == "-" {
		st.Skip = true
		return st, nil
	}

	for idx, str := range strings.Split(tag, ",") {
		if idx == 0 && str != "" {
			key = str
		}
		switch str {
		case "omitempty":
			st.OmitEmpty = true
		case "minsize":
			st.MinSize = true
		case "truncate":
			st.Truncate = true
		case "inline":
			st.Inline = true
		}
	}

	st.Name = key

	return st, nil
}

DefaultStructTagParser is the StructTagParser used by the StructCodec by default. It will handle the bson struct tag. See the documentation for StructTags to see what each of the returned fields means.

If there is no name in the struct tag fields, the struct field name is lowercased. The tag formats accepted are:

"[<key>][,<flag1>[,<flag2>]]"

`(...) bson:"[<key>][,<flag1>[,<flag2>]]" (...)`

An example:

type T struct {
    A bool
    B int    "myb"
    C string "myc,omitempty"
    D string `bson:",omitempty" json:"jsonkey"`
    E int64  ",minsize"
    F int64  "myf,omitempty,minsize"
}

A struct tag either consisting entirely of '-' or with a bson key with a value consisting entirely of '-' will return a StructTags with Skip true and the remaining fields will be their default values.

func (StructTagParserFunc) ParseStructTags

func (stpf StructTagParserFunc) ParseStructTags(sf reflect.StructField) (StructTags, error)

ParseStructTags implements the StructTagParser interface.

type StructTags

type StructTags struct {
	Name      string
	OmitEmpty bool
	MinSize   bool
	Truncate  bool
	Inline    bool
	Skip      bool
}

StructTags represents the struct tag fields that the StructCodec uses during the encoding and decoding process.

In the case of a struct, the lowercased field name is used as the key for each exported field but this behavior may be changed using a struct tag. The tag may also contain flags to adjust the marshalling behavior for the field.

The properties are defined below:

OmitEmpty  Only include the field if it's not set to the zero value for the type or to
           empty slices or maps.

MinSize    Marshal an integer of a type larger than 32 bits value as an int32, if that's
           feasible while preserving the numeric value.

Truncate   When unmarshaling a BSON double, it is permitted to lose precision to fit within
           a float32.

Inline     Inline the field, which must be a struct or a map, causing all of its fields
           or keys to be processed as if they were part of the outer struct. For maps,
           keys must not conflict with the bson keys of other struct fields.

Skip       This struct field should be skipped. This is usually denoted by parsing a "-"
           for the name.

TODO(skriptble): Add tags for undefined as nil and for null as nil.

type Symbol

type Symbol string

Symbol represents a BSON symbol value.

type TimeCodec

type TimeCodec struct{}

TimeCodec is the Codec for time.Time values.

func (*TimeCodec) DecodeValue

func (tc *TimeCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*TimeCodec) EncodeValue

func (tc *TimeCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type Timestamp

type Timestamp struct {
	T uint32
	I uint32
}

Timestamp represents a BSON timestamp value.

type TimestampCodec

type TimestampCodec struct{}

TimestampCodec is the Codec for Timestamp values.

func (*TimestampCodec) DecodeValue

func (tc *TimestampCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*TimestampCodec) EncodeValue

func (tc *TimestampCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type Type

type Type byte

Type represents a BSON type.

const (
	TypeDouble           Type = 0x01
	TypeString           Type = 0x02
	TypeEmbeddedDocument Type = 0x03
	TypeArray            Type = 0x04
	TypeBinary           Type = 0x05
	TypeUndefined        Type = 0x06
	TypeObjectID         Type = 0x07
	TypeBoolean          Type = 0x08
	TypeDateTime         Type = 0x09
	TypeNull             Type = 0x0A
	TypeRegex            Type = 0x0B
	TypeDBPointer        Type = 0x0C
	TypeJavaScript       Type = 0x0D
	TypeSymbol           Type = 0x0E
	TypeCodeWithScope    Type = 0x0F
	TypeInt32            Type = 0x10
	TypeTimestamp        Type = 0x11
	TypeInt64            Type = 0x12
	TypeDecimal128       Type = 0x13
	TypeMinKey           Type = 0xFF
	TypeMaxKey           Type = 0x7F
)

These constants uniquely refer to each BSON type.

func (Type) String

func (bt Type) String() string

String returns the string representation of the BSON type's name.

type URLCodec

type URLCodec struct{}

URLCodec is the Codec for url.URL values.

func (*URLCodec) DecodeValue

func (uc *URLCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*URLCodec) EncodeValue

func (uc *URLCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type UintCodec

type UintCodec struct{}

UintCodec is the Codec used for uint8, uint16, uint32, uint64, and uint values.

func (*UintCodec) DecodeValue

func (uc *UintCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*UintCodec) EncodeValue

func (uc *UintCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type UndefinedCodec

type UndefinedCodec struct{}

UndefinedCodec is the Codec for Undefined values.

func (*UndefinedCodec) DecodeValue

func (uc *UndefinedCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*UndefinedCodec) EncodeValue

func (uc *UndefinedCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type Undefinedv2

type Undefinedv2 struct{}

Undefinedv2 represents the BSON undefined value type.

type Unmarshaler

type Unmarshaler interface {
	UnmarshalBSON([]byte) error
}

Unmarshaler describes a type that can unmarshal itself from BSON bytes.

type Value

type Value struct {
	// contains filtered or unexported fields
}

Value represents a BSON value. It can be obtained as part of a bson.Element or created for use in a bson.Array with the bson.VC constructors.

func (*Value) Add

func (v *Value) Add(v2 *Value) error

Add will add this Value to another. This is currently only implemented for strings and numbers. If either value is a string, the other type is coerced into a string and added to the other.

func (*Value) Binary

func (v *Value) Binary() (subtype byte, data []byte)

Binary returns the BSON binary value the Value represents. It panics if the value is a BSON type other than binary.

func (*Value) BinaryOK

func (v *Value) BinaryOK() (subtype byte, data []byte, ok bool)

BinaryOK is the same as Binary, except it returns a boolean instead of panicking.

func (*Value) Boolean

func (v *Value) Boolean() bool

Boolean returns the boolean value the Value represents. It panics if the value is a BSON type other than boolean.

func (*Value) BooleanOK

func (v *Value) BooleanOK() (bool, bool)

BooleanOK is the same as Boolean, except it returns a boolean instead of panicking.

func (*Value) DBPointer

func (v *Value) DBPointer() (string, objectid.ObjectID)

DBPointer returns the BSON dbpointer value the Value represents. It panics if the value is a BSON type other than DBPointer.

func (*Value) DBPointerOK

func (v *Value) DBPointerOK() (string, objectid.ObjectID, bool)

DBPointerOK is the same as DBPoitner, except that it returns a boolean instead of panicking.

func (*Value) DateTime

func (v *Value) DateTime() int64

DateTime returns the BSON datetime value the Value represents as a unix timestamp. It panics if the value is a BSON type other than datetime.

func (*Value) DateTimeOK

func (v *Value) DateTimeOK() (int64, bool)

DateTimeOK is the same as DateTime, except it returns a boolean instead of panicking.

func (*Value) Decimal128

func (v *Value) Decimal128() decimal.Decimal128

Decimal128 returns the decimal the Value represents. It panics if the value is a BSON type other than decimal.

func (*Value) Decimal128OK

func (v *Value) Decimal128OK() (decimal.Decimal128, bool)

Decimal128OK is the same as Decimal128, except that it returns a boolean instead of panicking.

func (*Value) Double

func (v *Value) Double() float64

Double returns the float64 value for this element. It panics if e's BSON type is not double ('\x01') or if e is uninitialized.

func (*Value) DoubleOK

func (v *Value) DoubleOK() (float64, bool)

DoubleOK is the same as Double, but returns a boolean instead of panicking.

func (*Value) Int32

func (v *Value) Int32() int32

Int32 returns the int32 the Value represents. It panics if the value is a BSON type other than int32.

func (*Value) Int32OK

func (v *Value) Int32OK() (int32, bool)

Int32OK is the same as Int32, except that it returns a boolean instead of panicking.

func (*Value) Int64

func (v *Value) Int64() int64

Int64 returns the int64 the Value represents. It panics if the value is a BSON type other than int64.

func (*Value) Int64OK

func (v *Value) Int64OK() (int64, bool)

Int64OK is the same as Int64, except that it returns a boolean instead of panicking.

func (*Value) Interface

func (v *Value) Interface() interface{}

Interface returns the Go value of this Value as an empty interface.

func (*Value) IsNumber

func (v *Value) IsNumber() bool

IsNumber returns true if the type of v is a numberic BSON type.

func (*Value) JavaScript

func (v *Value) JavaScript() string

JavaScript returns the BSON JavaScript code value the Value represents. It panics if the value is a BSON type other than JavaScript code.

func (*Value) JavaScriptOK

func (v *Value) JavaScriptOK() (string, bool)

JavaScriptOK is the same as Javascript, excepti that it returns a boolean instead of panicking.

func (*Value) MutableArray

func (v *Value) MutableArray() *Array

MutableArray returns the array for this element.

func (*Value) MutableArrayOK

func (v *Value) MutableArrayOK() (*Array, bool)

MutableArrayOK is the same as MutableArray, except it returns a boolean instead of panicking.

func (*Value) MutableDocument

func (v *Value) MutableDocument() *Document

MutableDocument returns the subdocument for this element.

func (*Value) MutableDocumentOK

func (v *Value) MutableDocumentOK() (*Document, bool)

MutableDocumentOK is the same as MutableDocument, except it returns a boolean instead of panicking.

func (*Value) MutableJavaScriptWithScope

func (v *Value) MutableJavaScriptWithScope() (code string, d *Document)

MutableJavaScriptWithScope returns the javascript code and the scope document for this element.

func (*Value) MutableJavaScriptWithScopeOK

func (v *Value) MutableJavaScriptWithScopeOK() (string, *Document, bool)

MutableJavaScriptWithScopeOK is the same as MutableJavascriptWithScope, except that it returns a boolean instead of panicking.

func (*Value) ObjectID

func (v *Value) ObjectID() objectid.ObjectID

ObjectID returns the BSON objectid value the Value represents. It panics if the value is a BSON type other than objectid.

func (*Value) ObjectIDOK

func (v *Value) ObjectIDOK() (objectid.ObjectID, bool)

ObjectIDOK is the same as ObjectID, except it returns a boolean instead of panicking.

func (*Value) Offset

func (v *Value) Offset() uint32

Offset returns the offset to the beginning of the value in the underlying data. When called on a value obtained from a Reader, it can be used to find the value manually within the Reader's bytes.

func (*Value) ReaderArray

func (v *Value) ReaderArray() Reader

ReaderArray returns the BSON document the Value represents as a bson.Reader. It panics if the value is a BSON type other than array.

func (*Value) ReaderArrayOK

func (v *Value) ReaderArrayOK() (Reader, bool)

ReaderArrayOK is the same as ReaderArray, except it returns a boolean instead of panicking.

func (*Value) ReaderDocument

func (v *Value) ReaderDocument() Reader

ReaderDocument returns the BSON document the Value represents as a bson.Reader. It panics if the value is a BSON type other than document.

func (*Value) ReaderDocumentOK

func (v *Value) ReaderDocumentOK() (Reader, bool)

ReaderDocumentOK is the same as ReaderDocument, except it returns a boolean instead of panicking.

func (*Value) ReaderJavaScriptWithScope

func (v *Value) ReaderJavaScriptWithScope() (string, Reader)

ReaderJavaScriptWithScope returns the BSON JavaScript code with scope the Value represents, with the scope being returned as a bson.Reader. It panics if the value is a BSON type other than JavaScript code with scope.

func (*Value) ReaderJavaScriptWithScopeOK

func (v *Value) ReaderJavaScriptWithScopeOK() (string, Reader, bool)

ReaderJavaScriptWithScopeOK is the same as ReaderJavaScriptWithScope, except that it returns a boolean instead of panicking.

func (*Value) Regex

func (v *Value) Regex() (pattern, options string)

Regex returns the BSON regex value the Value represents. It panics if the value is a BSON type other than regex.

func (*Value) StringValue

func (v *Value) StringValue() string

StringValue returns the string balue for this element. It panics if e's BSON type is not StringValue ('\x02') or if e is uninitialized.

NOTE: This method is called StringValue to avoid it implementing the fmt.Stringer interface.

func (*Value) StringValueOK

func (v *Value) StringValueOK() (string, bool)

StringValueOK is the same as StringValue, but returns a boolean instead of panicking.

func (*Value) Symbol

func (v *Value) Symbol() string

Symbol returns the BSON symbol value the Value represents. It panics if the value is a BSON type other than symbol.

func (*Value) Time

func (v *Value) Time() time.Time

Time returns the BSON datetime value the Value represents. It panics if the value is a BSON type other than datetime.

func (*Value) TimeOK

func (v *Value) TimeOK() (time.Time, bool)

TimeOK is the same as Time, except it returns a boolean instead of panicking.

func (*Value) Timestamp

func (v *Value) Timestamp() (uint32, uint32)

Timestamp returns the BSON timestamp value the Value represents. It panics if the value is a BSON type other than timestamp.

func (*Value) TimestampOK

func (v *Value) TimestampOK() (uint32, uint32, bool)

TimestampOK is the same as Timestamp, except that it returns a boolean instead of panicking.

func (*Value) Type

func (v *Value) Type() Type

Type returns the identifying element byte for this element. It panics if e is uninitialized.

type ValueCodec

type ValueCodec struct{}

ValueCodec is the Codec for *Value values.

func (*ValueCodec) DecodeValue

func (vc *ValueCodec) DecodeValue(dc DecodeContext, vr ValueReader, i interface{}) error

DecodeValue implements the Codec interface.

func (*ValueCodec) EncodeValue

func (vc *ValueCodec) EncodeValue(ec EncodeContext, vw ValueWriter, i interface{}) error

EncodeValue implements the Codec interface.

type ValueConstructor

type ValueConstructor struct{}

ValueConstructor is used as a namespace for document element constructor functions.

VC is a convenience variable provided for access to the ValueConstructor methods.

func (ValueConstructor) Array

func (ValueConstructor) Array(a *Array) *Value

Array creates an array value from the argument.

func (ValueConstructor) ArrayFromValues

func (ValueConstructor) ArrayFromValues(values ...*Value) *Value

ArrayFromValues creates an array element from the given the elements.

func (ValueConstructor) Binary

func (ac ValueConstructor) Binary(b []byte) *Value

Binary creates a binary value from the argument.

func (ValueConstructor) BinaryWithSubtype

func (ValueConstructor) BinaryWithSubtype(b []byte, btype byte) *Value

BinaryWithSubtype creates a new binary element with the given data and subtype.

func (ValueConstructor) Boolean

func (ValueConstructor) Boolean(b bool) *Value

Boolean creates a boolean value from the argument.

func (ValueConstructor) CodeWithScope

func (ValueConstructor) CodeWithScope(code string, scope *Document) *Value

CodeWithScope creates a JavaScript code with scope value from the arguments.

func (ValueConstructor) DBPointer

func (ValueConstructor) DBPointer(ns string, oid objectid.ObjectID) *Value

DBPointer creates a dbpointer value from the arguments.

func (ValueConstructor) DateTime

func (ValueConstructor) DateTime(dt int64) *Value

DateTime creates a datetime value from the argument.

func (ValueConstructor) Decimal128

func (ValueConstructor) Decimal128(d decimal.Decimal128) *Value

Decimal128 creates a decimal value from the argument.

func (ValueConstructor) Document

func (ValueConstructor) Document(d *Document) *Value

Document creates a subdocument value from the argument.

func (ValueConstructor) DocumentFromElements

func (ValueConstructor) DocumentFromElements(elems ...*Element) *Value

DocumentFromElements creates a subdocument element from the given elements.

func (ValueConstructor) DocumentFromReader

func (ValueConstructor) DocumentFromReader(r Reader) *Value

DocumentFromReader creates a subdocument element from the given value.

func (ValueConstructor) Double

func (ValueConstructor) Double(f float64) *Value

Double creates a double element with the given value.

func (ValueConstructor) Int32

func (ValueConstructor) Int32(i int32) *Value

Int32 creates a int32 value from the argument.

func (ValueConstructor) Int64

func (ValueConstructor) Int64(i int64) *Value

Int64 creates a int64 value from the argument.

func (ValueConstructor) JavaScript

func (ValueConstructor) JavaScript(code string) *Value

JavaScript creates a JavaScript code value from the argument.

func (ValueConstructor) MaxKey

func (ValueConstructor) MaxKey() *Value

MaxKey creates a maxkey value from the argument.

func (ValueConstructor) MinKey

func (ValueConstructor) MinKey() *Value

MinKey creates a minkey value from the argument.

func (ValueConstructor) Null

func (ValueConstructor) Null() *Value

Null creates a null value from the argument.

func (ValueConstructor) ObjectID

func (ValueConstructor) ObjectID(oid objectid.ObjectID) *Value

ObjectID creates a objectid value from the argument.

func (ValueConstructor) Regex

func (ValueConstructor) Regex(pattern, options string) *Value

Regex creates a regex value from the arguments.

func (ValueConstructor) String

func (ValueConstructor) String(val string) *Value

String creates a string element with the given value.

func (ValueConstructor) Symbol

func (ValueConstructor) Symbol(symbol string) *Value

Symbol creates a symbol value from the argument.

func (ValueConstructor) Timestamp

func (ValueConstructor) Timestamp(t uint32, i uint32) *Value

Timestamp creates a timestamp value from the arguments.

func (ValueConstructor) Undefined

func (ValueConstructor) Undefined() *Value

Undefined creates a undefined element.

type ValueMarshaler

type ValueMarshaler interface {
	MarshalBSONValue() (*Value, error)
}

ValueMarshaler describes a type that can marshal itself into a bson.Value.

type ValueReader

type ValueReader interface {
	Type() Type
	Skip() error

	ReadArray() (ArrayReader, error)
	ReadBinary() (b []byte, btype byte, err error)
	ReadBoolean() (bool, error)
	ReadDocument() (DocumentReader, error)
	ReadCodeWithScope() (code string, dr DocumentReader, err error)
	ReadDBPointer() (ns string, oid objectid.ObjectID, err error)
	ReadDateTime() (int64, error)
	ReadDecimal128() (decimal.Decimal128, error)
	ReadDouble() (float64, error)
	ReadInt32() (int32, error)
	ReadInt64() (int64, error)
	ReadJavascript() (code string, err error)
	ReadMaxKey() error
	ReadMinKey() error
	ReadNull() error
	ReadObjectID() (objectid.ObjectID, error)
	ReadRegex() (pattern, options string, err error)
	ReadString() (string, error)
	ReadSymbol() (symbol string, err error)
	ReadTimestamp() (t, i uint32, err error)
	ReadUndefined() error
}

ValueReader is a generic interface used to read values from BSON. This type is implemented by several types with different underlying representations of BSON, such as a bson.Document, raw BSON bytes, or extended JSON.

func NewDocumentValueReader

func NewDocumentValueReader(d *Document) (ValueReader, error)

NewDocumentValueReader creates a new ValueReader from the given *Document.

func NewValueReader

func NewValueReader(b []byte) ValueReader

NewValueReader returns a ValueReader using b for the underlying BSON representation.

type ValueWriter

type ValueWriter interface {
	WriteArray() (ArrayWriter, error)
	WriteBinary(b []byte) error
	WriteBinaryWithSubtype(b []byte, btype byte) error
	WriteBoolean(bool) error
	WriteCodeWithScope(code string) (DocumentWriter, error)
	WriteDBPointer(ns string, oid objectid.ObjectID) error
	WriteDateTime(dt int64) error
	WriteDecimal128(decimal.Decimal128) error
	WriteDouble(float64) error
	WriteInt32(int32) error
	WriteInt64(int64) error
	WriteJavascript(code string) error
	WriteMaxKey() error
	WriteMinKey() error
	WriteNull() error
	WriteObjectID(objectid.ObjectID) error
	WriteRegex(pattern, options string) error
	WriteString(string) error
	WriteDocument() (DocumentWriter, error)
	WriteSymbol(symbol string) error
	WriteTimestamp(t, i uint32) error
	WriteUndefined() error
}

ValueWriter is the interface used to write BSON values. Implementations of this interface handle creating BSON or BSON adjacent representations of the values.

func NewBSONValueWriter

func NewBSONValueWriter(w io.Writer) (ValueWriter, error)

NewBSONValueWriter creates a ValueWriter that writes BSON to w.

This ValueWriter will only write entire documents to the io.Writer and it will buffer the document as it is built.

func NewDocumentValueWriter

func NewDocumentValueWriter(d *Document) (ValueWriter, error)

NewDocumentValueWriter creates a ValueWriter that adds elements to d.

func NewExtJSONValueWriter

func NewExtJSONValueWriter(w io.Writer) (ValueWriter, error)

NewExtJSONValueWriter creates a ValueWriter that writes Extended JSON to w.

type Zeroer

type Zeroer interface {
	IsZero() bool
}

Zeroer allows custom struct types to implement a report of zero state. All struct types that don't implement Zeroer or where IsZero returns false are considered to be not zero.

Source Files

array.go array_iterator.go bson.go codec.go constructor.go decode.go decoder.go doc.go document.go document_decoder.go document_encoder.go document_value_reader.go document_value_writer.go element.go empty_interface_codec.go encode.go encoder.go extjson_builder.go extjson_bytes_converter.go extjson_parse.go extjson_reader.go extjson_wrappers.go extjson_writer.go internal_reader.go iterator.go map_codec.go marshal.go mode.go reader.go reader_iterator.go registry.go slice_codec.go struct_codec.go struct_tag_parser.go types.go unmarshal.go value.go value_read_writer_copy.go value_reader.go value_types.go value_writer.go writer.go

Directories

PathSynopsis
bson/builder
bson/decimal
bson/elementsPackage elements holds the logic to encode and decode the BSON element types from native Go to BSON binary and vice versa.
bson/internal
bson/objectid
bson/parser
bson/parser/ast
Version
v0.0.14
Published
Sep 20, 2018
Platform
linux/amd64
Imports
25 packages
Last checked
8 seconds ago

Tools for package owners.