bsoncodec

package
v1.7.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 3, 2021 License: Apache-2.0 Imports: 16 Imported by: 490

Documentation

Overview

Package bsoncodec provides a system for encoding values to BSON representations and decoding values from BSON representations. This package considers both binary BSON and ExtendedJSON as BSON representations. The types in this package enable a flexible system for handling this encoding and decoding.

The codec system is composed of two parts:

1) ValueEncoders and ValueDecoders that handle encoding and decoding Go values to and from BSON representations.

2) A Registry that holds these ValueEncoders and ValueDecoders and provides methods for retrieving them.

ValueEncoders and ValueDecoders

The ValueEncoder interface is implemented by types that can encode a provided Go type to BSON. The value to encode is provided as a reflect.Value and a bsonrw.ValueWriter is used within the EncodeValue method to actually create the BSON representation. For convenience, ValueEncoderFunc is provided to allow use of a function with the correct signature as a ValueEncoder. An EncodeContext instance is provided to allow implementations to lookup further ValueEncoders and to provide configuration information.

The ValueDecoder interface is the inverse of the ValueEncoder. Implementations should ensure that the value they receive is settable. Similar to ValueEncoderFunc, ValueDecoderFunc is provided to allow the use of a function with the correct signature as a ValueDecoder. A DecodeContext instance is provided and serves similar functionality to the EncodeContext.

Registry and RegistryBuilder

A Registry is an immutable store for ValueEncoders, ValueDecoders, and a type map. See the Registry type documentation for examples of registering various custom encoders and decoders. A Registry can be constructed using a RegistryBuilder, which handles three main types of codecs:

1. Type encoders/decoders - These can be registered using the RegisterTypeEncoder and RegisterTypeDecoder methods. The registered codec will be invoked when encoding/decoding a value whose type matches the registered type exactly. If the registered type is an interface, the codec will be invoked when encoding or decoding values whose type is the interface, but not for values with concrete types that implement the interface.

2. Hook encoders/decoders - These can be registered using the RegisterHookEncoder and RegisterHookDecoder methods. These methods only accept interface types and the registered codecs will be invoked when encoding or decoding values whose types implement the interface. An example of a hook defined by the driver is bson.Marshaler. The driver will call the MarshalBSON method for any value whose type implements bson.Marshaler, regardless of the value's concrete type.

3. Type map entries - This can be used to associate a BSON type with a Go type. These type associations are used when decoding into a bson.D/bson.M or a struct field of type interface{}. For example, by default, BSON int32 and int64 values decode as Go int32 and int64 instances, respectively, when decoding into a bson.D. The following code would change the behavior so these values decode as Go int instances instead:

intType := reflect.TypeOf(int(0))
registryBuilder.RegisterTypeMapEntry(bsontype.Int32, intType).RegisterTypeMapEntry(bsontype.Int64, intType)

4. Kind encoder/decoders - These can be registered using the RegisterDefaultEncoder and RegisterDefaultDecoder methods. The registered codec will be invoked when encoding or decoding values whose reflect.Kind matches the registered reflect.Kind as long as the value's type doesn't match a registered type or hook encoder/decoder first. These methods should be used to change the behavior for all values for a specific kind.

Registry Lookup Procedure

When looking up an encoder in a Registry, the precedence rules are as follows:

1. A type encoder registered for the exact type of the value.

2. A hook encoder registered for an interface that is implemented by the value or by a pointer to the value. If the value matches multiple hooks (e.g. the type implements bsoncodec.Marshaler and bsoncodec.ValueMarshaler), the first one registered will be selected. Note that registries constructed using bson.NewRegistryBuilder have driver-defined hooks registered for the bsoncodec.Marshaler, bsoncodec.ValueMarshaler, and bsoncodec.Proxy interfaces, so those will take precedence over any new hooks.

3. A kind encoder registered for the value's kind.

If all of these lookups fail to find an encoder, an error of type ErrNoEncoder is returned. The same precedence rules apply for decoders, with the exception that an error of type ErrNoDecoder will be returned if no decoder is found.

DefaultValueEncoders and DefaultValueDecoders

The DefaultValueEncoders and DefaultValueDecoders types provide a full set of ValueEncoders and ValueDecoders for handling a wide range of Go types, including all of the types within the primitive package. To make registering these codecs easier, a helper method on each type is provided. For the DefaultValueEncoders type the method is called RegisterDefaultEncoders and for the DefaultValueDecoders type the method is called RegisterDefaultDecoders, this method also handles registering type map entries for each BSON type.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNilType = errors.New("cannot perform a decoder lookup on <nil>")

ErrNilType is returned when nil is passed to either LookupEncoder or LookupDecoder.

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

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

View Source
var ErrNotPointer = errors.New("non-pointer provided to LookupDecoder")

ErrNotPointer is returned when a non-pointer type is provided to LookupDecoder.

Functions

This section is empty.

Types

type ArrayCodec added in v1.5.0

type ArrayCodec struct{}

ArrayCodec is the Codec used for bsoncore.Array values.

func NewArrayCodec added in v1.5.0

func NewArrayCodec() *ArrayCodec

NewArrayCodec returns an ArrayCodec.

func (*ArrayCodec) DecodeValue added in v1.5.0

func (ac *ArrayCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

DecodeValue is the ValueDecoder for bsoncore.Array values.

func (*ArrayCodec) EncodeValue added in v1.5.0

func (ac *ArrayCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

EncodeValue is the ValueEncoder for bsoncore.Array values.

type ByteSliceCodec added in v1.3.0

type ByteSliceCodec struct {
	EncodeNilAsEmpty bool
}

ByteSliceCodec is the Codec used for []byte values.

func NewByteSliceCodec added in v1.3.0

func NewByteSliceCodec(opts ...*bsonoptions.ByteSliceCodecOptions) *ByteSliceCodec

NewByteSliceCodec returns a StringCodec with options opts.

func (*ByteSliceCodec) DecodeValue added in v1.3.0

func (bsc *ByteSliceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

DecodeValue is the ValueDecoder for []byte.

func (*ByteSliceCodec) EncodeValue added in v1.3.0

func (bsc *ByteSliceCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

EncodeValue is the ValueEncoder for []byte.

type CodecZeroer

type CodecZeroer interface {
	IsTypeZero(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 DecodeContext

type DecodeContext struct {
	*Registry
	Truncate bool
	// Ancestor is the type of a containing document. This is mainly used to determine what type
	// should be used when decoding an embedded document into an empty interface. For example, if
	// Ancestor is a bson.M, BSON embedded document values being decoded into an empty interface
	// will be decoded into a bson.M.
	Ancestor reflect.Type
}

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

type DecodeError added in v1.4.0

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

DecodeError represents an error that occurs when unmarshalling BSON bytes into a native Go type.

func (*DecodeError) Error added in v1.4.0

func (de *DecodeError) Error() string

Error implements the error interface.

func (*DecodeError) Keys added in v1.4.0

func (de *DecodeError) Keys() []string

Keys returns the BSON key path that caused an error as a slice of strings. The keys in the slice are in top-down order. For example, if the document being unmarshalled was {a: {b: {c: 1}}} and the value for c was supposed to be a string, the keys slice will be ["a", "b", "c"].

func (*DecodeError) Unwrap added in v1.4.0

func (de *DecodeError) Unwrap() error

Unwrap returns the underlying error

type DefaultValueDecoders

type DefaultValueDecoders struct{}

DefaultValueDecoders is a namespace type for the default ValueDecoders used when creating a registry.

func (DefaultValueDecoders) ArrayDecodeValue

func (dvd DefaultValueDecoders) ArrayDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

ArrayDecodeValue is the ValueDecoderFunc for array types.

func (DefaultValueDecoders) BinaryDecodeValue

func (dvd DefaultValueDecoders) BinaryDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

BinaryDecodeValue is the ValueDecoderFunc for Binary.

func (DefaultValueDecoders) BooleanDecodeValue

func (dvd DefaultValueDecoders) BooleanDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

BooleanDecodeValue is the ValueDecoderFunc for bool types.

func (DefaultValueDecoders) ByteSliceDecodeValue deprecated

func (dvd DefaultValueDecoders) ByteSliceDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

ByteSliceDecodeValue is the ValueDecoderFunc for []byte.

Deprecated: ByteSliceDecodeValue is not registered by default. Use ByteSliceCodec.DecodeValue instead.

func (DefaultValueDecoders) CodeWithScopeDecodeValue

func (dvd DefaultValueDecoders) CodeWithScopeDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

CodeWithScopeDecodeValue is the ValueDecoderFunc for CodeWithScope.

func (DefaultValueDecoders) CoreDocumentDecodeValue added in v0.1.0

func (DefaultValueDecoders) CoreDocumentDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

CoreDocumentDecodeValue is the ValueDecoderFunc for bsoncore.Document.

func (DefaultValueDecoders) DBPointerDecodeValue

func (dvd DefaultValueDecoders) DBPointerDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

DBPointerDecodeValue is the ValueDecoderFunc for DBPointer.

func (DefaultValueDecoders) DDecodeValue added in v1.5.0

func (dvd DefaultValueDecoders) DDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

DDecodeValue is the ValueDecoderFunc for primitive.D instances.

func (DefaultValueDecoders) DateTimeDecodeValue

func (dvd DefaultValueDecoders) DateTimeDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

DateTimeDecodeValue is the ValueDecoderFunc for DateTime.

func (DefaultValueDecoders) Decimal128DecodeValue

func (dvd DefaultValueDecoders) Decimal128DecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

Decimal128DecodeValue is the ValueDecoderFunc for primitive.Decimal128.

func (DefaultValueDecoders) EmptyInterfaceDecodeValue deprecated

func (dvd DefaultValueDecoders) EmptyInterfaceDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

EmptyInterfaceDecodeValue is the ValueDecoderFunc for interface{}.

Deprecated: EmptyInterfaceDecodeValue is not registered by default. Use EmptyInterfaceCodec.DecodeValue instead.

func (DefaultValueDecoders) FloatDecodeValue

func (dvd DefaultValueDecoders) FloatDecodeValue(ec DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

FloatDecodeValue is the ValueDecoderFunc for float types.

func (DefaultValueDecoders) IntDecodeValue

func (dvd DefaultValueDecoders) IntDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

IntDecodeValue is the ValueDecoderFunc for int types.

func (DefaultValueDecoders) JSONNumberDecodeValue

func (dvd DefaultValueDecoders) JSONNumberDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

JSONNumberDecodeValue is the ValueDecoderFunc for json.Number.

func (DefaultValueDecoders) JavaScriptDecodeValue added in v0.1.0

func (dvd DefaultValueDecoders) JavaScriptDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

JavaScriptDecodeValue is the ValueDecoderFunc for the primitive.JavaScript type.

func (DefaultValueDecoders) MapDecodeValue deprecated

func (dvd DefaultValueDecoders) MapDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

MapDecodeValue is the ValueDecoderFunc for map[string]* types.

Deprecated: MapDecodeValue is not registered by default. Use MapCodec.DecodeValue instead.

func (DefaultValueDecoders) MaxKeyDecodeValue

func (dvd DefaultValueDecoders) MaxKeyDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

MaxKeyDecodeValue is the ValueDecoderFunc for MaxKey.

func (DefaultValueDecoders) MinKeyDecodeValue

func (dvd DefaultValueDecoders) MinKeyDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

MinKeyDecodeValue is the ValueDecoderFunc for MinKey.

func (DefaultValueDecoders) NullDecodeValue

func (dvd DefaultValueDecoders) NullDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

NullDecodeValue is the ValueDecoderFunc for Null.

func (DefaultValueDecoders) ObjectIDDecodeValue

func (dvd DefaultValueDecoders) ObjectIDDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

ObjectIDDecodeValue is the ValueDecoderFunc for primitive.ObjectID.

func (DefaultValueDecoders) RegexDecodeValue

func (dvd DefaultValueDecoders) RegexDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

RegexDecodeValue is the ValueDecoderFunc for Regex.

func (DefaultValueDecoders) RegisterDefaultDecoders added in v0.0.17

func (dvd DefaultValueDecoders) RegisterDefaultDecoders(rb *RegistryBuilder)

RegisterDefaultDecoders will register the decoder methods attached to DefaultValueDecoders with the provided RegistryBuilder.

There is no support for decoding map[string]interface{} becuase there is no decoder for interface{}, so users must either register this decoder themselves or use the EmptyInterfaceDecoder available in the bson package.

func (DefaultValueDecoders) SliceDecodeValue deprecated

func (dvd DefaultValueDecoders) SliceDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

SliceDecodeValue is the ValueDecoderFunc for slice types.

Deprecated: SliceDecodeValue is not registered by default. Use SliceCodec.DecodeValue instead.

func (DefaultValueDecoders) StringDecodeValue deprecated

func (dvd DefaultValueDecoders) StringDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

StringDecodeValue is the ValueDecoderFunc for string types.

Deprecated: StringDecodeValue is not registered by default. Use StringCodec.DecodeValue instead.

func (DefaultValueDecoders) SymbolDecodeValue added in v0.1.0

func (dvd DefaultValueDecoders) SymbolDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

SymbolDecodeValue is the ValueDecoderFunc for the primitive.Symbol type.

func (DefaultValueDecoders) TimeDecodeValue deprecated

func (dvd DefaultValueDecoders) TimeDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

TimeDecodeValue is the ValueDecoderFunc for time.Time.

Deprecated: TimeDecodeValue is not registered by default. Use TimeCodec.DecodeValue instead.

func (DefaultValueDecoders) TimestampDecodeValue

func (dvd DefaultValueDecoders) TimestampDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

TimestampDecodeValue is the ValueDecoderFunc for Timestamp.

func (DefaultValueDecoders) URLDecodeValue

func (dvd DefaultValueDecoders) URLDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

URLDecodeValue is the ValueDecoderFunc for url.URL.

func (DefaultValueDecoders) UintDecodeValue deprecated

func (dvd DefaultValueDecoders) UintDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

UintDecodeValue is the ValueDecoderFunc for uint types.

Deprecated: UintDecodeValue is not registered by default. Use UintCodec.DecodeValue instead.

func (DefaultValueDecoders) UndefinedDecodeValue

func (dvd DefaultValueDecoders) UndefinedDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

UndefinedDecodeValue is the ValueDecoderFunc for Undefined.

func (DefaultValueDecoders) UnmarshalerDecodeValue added in v0.1.0

func (dvd DefaultValueDecoders) UnmarshalerDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

UnmarshalerDecodeValue is the ValueDecoderFunc for Unmarshaler implementations.

func (DefaultValueDecoders) ValueUnmarshalerDecodeValue

func (dvd DefaultValueDecoders) ValueUnmarshalerDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

ValueUnmarshalerDecodeValue is the ValueDecoderFunc for ValueUnmarshaler implementations.

type DefaultValueEncoders

type DefaultValueEncoders struct{}

DefaultValueEncoders is a namespace type for the default ValueEncoders used when creating a registry.

func (DefaultValueEncoders) ArrayEncodeValue

func (dve DefaultValueEncoders) ArrayEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

ArrayEncodeValue is the ValueEncoderFunc for array types.

func (DefaultValueEncoders) BinaryEncodeValue

func (DefaultValueEncoders) BinaryEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

BinaryEncodeValue is the ValueEncoderFunc for Binary.

func (DefaultValueEncoders) BooleanEncodeValue

func (dve DefaultValueEncoders) BooleanEncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

BooleanEncodeValue is the ValueEncoderFunc for bool types.

func (DefaultValueEncoders) ByteSliceEncodeValue deprecated

func (dve DefaultValueEncoders) ByteSliceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

ByteSliceEncodeValue is the ValueEncoderFunc for []byte.

Deprecated: ByteSliceEncodeValue is not registered by default. Use ByteSliceCodec.EncodeValue instead.

func (DefaultValueEncoders) CodeWithScopeEncodeValue

func (dve DefaultValueEncoders) CodeWithScopeEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

CodeWithScopeEncodeValue is the ValueEncoderFunc for CodeWithScope.

func (DefaultValueEncoders) CoreDocumentEncodeValue added in v0.1.0

func (DefaultValueEncoders) CoreDocumentEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

CoreDocumentEncodeValue is the ValueEncoderFunc for bsoncore.Document.

func (DefaultValueEncoders) DBPointerEncodeValue

func (DefaultValueEncoders) DBPointerEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

DBPointerEncodeValue is the ValueEncoderFunc for DBPointer.

func (DefaultValueEncoders) DateTimeEncodeValue

func (DefaultValueEncoders) DateTimeEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

DateTimeEncodeValue is the ValueEncoderFunc for DateTime.

func (DefaultValueEncoders) Decimal128EncodeValue

func (dve DefaultValueEncoders) Decimal128EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

Decimal128EncodeValue is the ValueEncoderFunc for primitive.Decimal128.

func (DefaultValueEncoders) EmptyInterfaceEncodeValue deprecated

func (dve DefaultValueEncoders) EmptyInterfaceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

EmptyInterfaceEncodeValue is the ValueEncoderFunc for interface{}.

Deprecated: EmptyInterfaceEncodeValue is not registered by default. Use EmptyInterfaceCodec.EncodeValue instead.

func (DefaultValueEncoders) FloatEncodeValue

func (dve DefaultValueEncoders) FloatEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

FloatEncodeValue is the ValueEncoderFunc for float types.

func (DefaultValueEncoders) IntEncodeValue

func (dve DefaultValueEncoders) IntEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

IntEncodeValue is the ValueEncoderFunc for int types.

func (DefaultValueEncoders) JSONNumberEncodeValue

func (dve DefaultValueEncoders) JSONNumberEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

JSONNumberEncodeValue is the ValueEncoderFunc for json.Number.

func (DefaultValueEncoders) JavaScriptEncodeValue added in v0.1.0

func (DefaultValueEncoders) JavaScriptEncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

JavaScriptEncodeValue is the ValueEncoderFunc for the primitive.JavaScript type.

func (DefaultValueEncoders) MapEncodeValue deprecated

func (dve DefaultValueEncoders) MapEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

MapEncodeValue is the ValueEncoderFunc for map[string]* types.

Deprecated: MapEncodeValue is not registered by default. Use MapCodec.EncodeValue instead.

func (DefaultValueEncoders) MarshalerEncodeValue added in v0.1.0

func (dve DefaultValueEncoders) MarshalerEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

MarshalerEncodeValue is the ValueEncoderFunc for Marshaler implementations.

func (DefaultValueEncoders) MaxKeyEncodeValue

func (DefaultValueEncoders) MaxKeyEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

MaxKeyEncodeValue is the ValueEncoderFunc for MaxKey.

func (DefaultValueEncoders) MinKeyEncodeValue

func (DefaultValueEncoders) MinKeyEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

MinKeyEncodeValue is the ValueEncoderFunc for MinKey.

func (DefaultValueEncoders) NullEncodeValue

NullEncodeValue is the ValueEncoderFunc for Null.

func (DefaultValueEncoders) ObjectIDEncodeValue

func (dve DefaultValueEncoders) ObjectIDEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

ObjectIDEncodeValue is the ValueEncoderFunc for primitive.ObjectID.

func (DefaultValueEncoders) ProxyEncodeValue added in v0.0.18

func (dve DefaultValueEncoders) ProxyEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

ProxyEncodeValue is the ValueEncoderFunc for Proxy implementations.

func (DefaultValueEncoders) RegexEncodeValue

func (DefaultValueEncoders) RegexEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

RegexEncodeValue is the ValueEncoderFunc for Regex.

func (DefaultValueEncoders) RegisterDefaultEncoders added in v0.0.17

func (dve DefaultValueEncoders) RegisterDefaultEncoders(rb *RegistryBuilder)

RegisterDefaultEncoders will register the encoder methods attached to DefaultValueEncoders with the provided RegistryBuilder.

func (DefaultValueEncoders) SliceEncodeValue deprecated

func (dve DefaultValueEncoders) SliceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

SliceEncodeValue is the ValueEncoderFunc for slice types.

Deprecated: SliceEncodeValue is not registered by default. Use SliceCodec.EncodeValue instead.

func (DefaultValueEncoders) StringEncodeValue deprecated

func (dve DefaultValueEncoders) StringEncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

StringEncodeValue is the ValueEncoderFunc for string types.

Deprecated: StringEncodeValue is not registered by default. Use StringCodec.EncodeValue instead.

func (DefaultValueEncoders) SymbolEncodeValue added in v0.1.0

func (DefaultValueEncoders) SymbolEncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

SymbolEncodeValue is the ValueEncoderFunc for the primitive.Symbol type.

func (DefaultValueEncoders) TimeEncodeValue deprecated

func (dve DefaultValueEncoders) TimeEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

TimeEncodeValue is the ValueEncoderFunc for time.TIme.

Deprecated: TimeEncodeValue is not registered by default. Use TimeCodec.EncodeValue instead.

func (DefaultValueEncoders) TimestampEncodeValue

func (DefaultValueEncoders) TimestampEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

TimestampEncodeValue is the ValueEncoderFunc for Timestamp.

func (DefaultValueEncoders) URLEncodeValue

func (dve DefaultValueEncoders) URLEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

URLEncodeValue is the ValueEncoderFunc for url.URL.

func (DefaultValueEncoders) UintEncodeValue deprecated

func (dve DefaultValueEncoders) UintEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

UintEncodeValue is the ValueEncoderFunc for uint types.

Deprecated: UintEncodeValue is not registered by default. Use UintCodec.EncodeValue instead.

func (DefaultValueEncoders) UndefinedEncodeValue

func (DefaultValueEncoders) UndefinedEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

UndefinedEncodeValue is the ValueEncoderFunc for Undefined.

func (DefaultValueEncoders) ValueMarshalerEncodeValue

func (dve DefaultValueEncoders) ValueMarshalerEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

ValueMarshalerEncodeValue is the ValueEncoderFunc for ValueMarshaler implementations.

type EmptyInterfaceCodec added in v1.3.0

type EmptyInterfaceCodec struct {
	DecodeBinaryAsSlice bool
}

EmptyInterfaceCodec is the Codec used for interface{} values.

func NewEmptyInterfaceCodec added in v1.3.0

func NewEmptyInterfaceCodec(opts ...*bsonoptions.EmptyInterfaceCodecOptions) *EmptyInterfaceCodec

NewEmptyInterfaceCodec returns a EmptyInterfaceCodec with options opts.

func (EmptyInterfaceCodec) DecodeValue added in v1.3.0

func (eic EmptyInterfaceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

DecodeValue is the ValueDecoderFunc for interface{}.

func (EmptyInterfaceCodec) EncodeValue added in v1.3.0

func (eic EmptyInterfaceCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

EncodeValue is the ValueEncoderFunc for interface{}.

type EncodeContext

type EncodeContext struct {
	*Registry
	MinSize bool
}

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

type ErrNoDecoder

type ErrNoDecoder struct {
	Type reflect.Type
}

ErrNoDecoder is returned when there wasn't a decoder available for a type.

func (ErrNoDecoder) Error

func (end ErrNoDecoder) Error() string

type ErrNoEncoder

type ErrNoEncoder struct {
	Type reflect.Type
}

ErrNoEncoder is returned when there wasn't an encoder available for a type.

func (ErrNoEncoder) Error

func (ene ErrNoEncoder) Error() string

type ErrNoTypeMapEntry added in v0.1.0

type ErrNoTypeMapEntry struct {
	Type bsontype.Type
}

ErrNoTypeMapEntry is returned when there wasn't a type available for the provided BSON type.

func (ErrNoTypeMapEntry) Error added in v0.1.0

func (entme ErrNoTypeMapEntry) Error() string

type KeyMarshaler added in v1.4.0

type KeyMarshaler interface {
	MarshalKey() (key string, err error)
}

KeyMarshaler is the interface implemented by an object that can marshal itself into a string key. This applies to types used as map keys and is similar to encoding.TextMarshaler.

type KeyUnmarshaler added in v1.4.0

type KeyUnmarshaler interface {
	UnmarshalKey(key string) error
}

KeyUnmarshaler is the interface implemented by an object that can unmarshal a string representation of itself. This applies to types used as map keys and is similar to encoding.TextUnmarshaler.

UnmarshalKey must be able to decode the form generated by MarshalKey. UnmarshalKey must copy the text if it wishes to retain the text after returning.

type MapCodec added in v1.2.0

type MapCodec struct {
	DecodeZerosMap         bool
	EncodeNilAsEmpty       bool
	EncodeKeysWithStringer bool
}

MapCodec is the Codec used for map values.

func NewMapCodec added in v1.2.0

func NewMapCodec(opts ...*bsonoptions.MapCodecOptions) *MapCodec

NewMapCodec returns a MapCodec with options opts.

func (*MapCodec) DecodeValue added in v1.2.0

func (mc *MapCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

DecodeValue is the ValueDecoder for map[string/decimal]* types.

func (*MapCodec) EncodeValue added in v1.2.0

func (mc *MapCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

EncodeValue is the ValueEncoder for map[*]* types.

type Marshaler

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

Marshaler is an interface implemented by types that can marshal themselves into a BSON document represented as bytes. The bytes returned must be a valid BSON document if the error is nil.

type PointerCodec added in v0.1.0

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

PointerCodec is the Codec used for pointers.

func NewPointerCodec added in v0.1.0

func NewPointerCodec() *PointerCodec

NewPointerCodec returns a PointerCodec that has been initialized.

func (*PointerCodec) DecodeValue added in v0.1.0

func (pc *PointerCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

DecodeValue handles decoding a pointer by looking up a decoder for the type it points to and using that to decode. If the BSON value is Null, this method will set the pointer to nil.

func (*PointerCodec) EncodeValue added in v0.1.0

func (pc *PointerCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

EncodeValue handles encoding a pointer by either encoding it to BSON Null if the pointer is nil or looking up an encoder for the type of value the pointer points to.

type Proxy added in v0.0.18

type Proxy interface {
	ProxyBSON() (interface{}, error)
}

Proxy is an interface implemented by types that cannot themselves be directly encoded. Types that implement this interface with have ProxyBSON called during the encoding process and that value will be encoded in place for the implementer.

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.

Example (CustomDecoder)
package main

import (
	"fmt"
	"reflect"

	"go.mongodb.org/mongo-driver/bson/bsoncodec"
	"go.mongodb.org/mongo-driver/bson/bsonrw"
	"go.mongodb.org/mongo-driver/bson/bsontype"
)

func main() {
	// Write a custom decoder for a boolean type that can be stored in the
	// database as a BSON boolean, int32, int64, double, or null. BSON int32,
	// int64, and double values are considered "true" in this decoder if they
	// are non-zero. BSON null values are always considered false.

	// To register the default encoders and decoders in addition to this custom
	// one, use bson.NewRegistryBuilder instead.
	rb := bsoncodec.NewRegistryBuilder()
	type lenientBool bool

	decoder := func(
		dc bsoncodec.DecodeContext,
		vr bsonrw.ValueReader,
		val reflect.Value,
	) error {
		// All decoder implementations should check that val is valid, settable,
		// and is of the correct kind before proceeding.
		if !val.IsValid() || !val.CanSet() || val.Kind() != reflect.Bool {
			return bsoncodec.ValueDecoderError{
				Name:     "lenientBoolDecodeValue",
				Kinds:    []reflect.Kind{reflect.Bool},
				Received: val,
			}
		}

		var result bool
		switch vr.Type() {
		case bsontype.Boolean:
			b, err := vr.ReadBoolean()
			if err != nil {
				return err
			}
			result = b
		case bsontype.Int32:
			i32, err := vr.ReadInt32()
			if err != nil {
				return err
			}
			result = i32 != 0
		case bsontype.Int64:
			i64, err := vr.ReadInt64()
			if err != nil {
				return err
			}
			result = i64 != 0
		case bsontype.Double:
			f64, err := vr.ReadDouble()
			if err != nil {
				return err
			}
			result = f64 != 0
		case bsontype.Null:
			if err := vr.ReadNull(); err != nil {
				return err
			}
			result = false
		default:
			return fmt.Errorf(
				"received invalid BSON type to decode into lenientBool: %s",
				vr.Type())
		}

		val.SetBool(result)
		return nil
	}

	lbType := reflect.TypeOf(lenientBool(true))
	rb.RegisterTypeDecoder(lbType, bsoncodec.ValueDecoderFunc(decoder))
}
Output:

Example (CustomEncoder)
package main

import (
	"math"
	"reflect"

	"go.mongodb.org/mongo-driver/bson/bsoncodec"
	"go.mongodb.org/mongo-driver/bson/bsonrw"
)

func main() {
	// Write a custom encoder for an integer type that is multiplied by -1 when
	// encoding.

	// To register the default encoders and decoders in addition to this custom
	// one, use bson.NewRegistryBuilder instead.
	rb := bsoncodec.NewRegistryBuilder()
	type negatedInt int

	niType := reflect.TypeOf(negatedInt(0))
	encoder := func(
		ec bsoncodec.EncodeContext,
		vw bsonrw.ValueWriter,
		val reflect.Value,
	) error {
		// All encoder implementations should check that val is valid and is of
		// the correct type before proceeding.
		if !val.IsValid() || val.Type() != niType {
			return bsoncodec.ValueEncoderError{
				Name:     "negatedIntEncodeValue",
				Types:    []reflect.Type{niType},
				Received: val,
			}
		}

		// Negate val and encode as a BSON int32 if it can fit in 32 bits and a
		// BSON int64 otherwise.
		negatedVal := val.Int() * -1
		if math.MinInt32 <= negatedVal && negatedVal <= math.MaxInt32 {
			return vw.WriteInt32(int32(negatedVal))
		}
		return vw.WriteInt64(negatedVal)
	}

	rb.RegisterTypeEncoder(niType, bsoncodec.ValueEncoderFunc(encoder))
}
Output:

func (*Registry) LookupDecoder

func (r *Registry) LookupDecoder(t reflect.Type) (ValueDecoder, error)

LookupDecoder inspects the registry for an decoder for the given type. The lookup precendence works as follows:

1. A decoder registered for the exact type. If the given type represents an interface, a decoder registered using RegisterTypeDecoder for the interface will be selected.

2. A decoder registered using RegisterHookDecoder for an interface implemented by the type or by a pointer to the type.

3. A decoder registered for the reflect.Kind of the value.

If no decoder is found, an error of type ErrNoDecoder is returned.

func (*Registry) LookupEncoder

func (r *Registry) LookupEncoder(t reflect.Type) (ValueEncoder, error)

LookupEncoder inspects the registry for an encoder for the given type. The lookup precendence works as follows:

1. An encoder registered for the exact type. If the given type represents an interface, an encoder registered using RegisterTypeEncoder for the interface will be selected.

2. An encoder registered using RegisterHookEncoder for an interface implemented by the type or by a pointer to the type.

3. An encoder registered for the reflect.Kind of the value.

If no encoder is found, an error of type ErrNoEncoder is returned.

func (*Registry) LookupTypeMapEntry added in v0.1.0

func (r *Registry) LookupTypeMapEntry(bt bsontype.Type) (reflect.Type, error)

LookupTypeMapEntry inspects the registry's type map for a Go type for the corresponding BSON type. If no type is found, ErrNoTypeMapEntry is 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 NewRegistryBuilder

func NewRegistryBuilder() *RegistryBuilder

NewRegistryBuilder creates a new empty RegistryBuilder.

func (*RegistryBuilder) Build

func (rb *RegistryBuilder) Build() *Registry

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

func (*RegistryBuilder) RegisterCodec

func (rb *RegistryBuilder) RegisterCodec(t reflect.Type, codec ValueCodec) *RegistryBuilder

RegisterCodec will register the provided ValueCodec for the provided type.

func (*RegistryBuilder) RegisterDecoder deprecated

func (rb *RegistryBuilder) RegisterDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder

RegisterDecoder registers the provided type and decoder pair.

Deprecated: Use RegisterTypeDecoder or RegisterHookDecoder instead.

func (*RegistryBuilder) RegisterDefaultDecoder

func (rb *RegistryBuilder) RegisterDefaultDecoder(kind reflect.Kind, dec ValueDecoder) *RegistryBuilder

RegisterDefaultDecoder will register the provided ValueDecoder to the provided kind.

func (*RegistryBuilder) RegisterDefaultEncoder

func (rb *RegistryBuilder) RegisterDefaultEncoder(kind reflect.Kind, enc ValueEncoder) *RegistryBuilder

RegisterDefaultEncoder will registr the provided ValueEncoder to the provided kind.

func (*RegistryBuilder) RegisterEncoder deprecated

func (rb *RegistryBuilder) RegisterEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder

RegisterEncoder registers the provided type and encoder pair.

Deprecated: Use RegisterTypeEncoder or RegisterHookEncoder instead.

func (*RegistryBuilder) RegisterHookDecoder added in v1.3.0

func (rb *RegistryBuilder) RegisterHookDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder

RegisterHookDecoder will register an decoder for the provided interface type t. This decoder will be called when unmarshalling into a type if the type implements t or a pointer to the type implements t. If the provided type is not an interface (i.e. t.Kind() != reflect.Interface), this method will panic.

func (*RegistryBuilder) RegisterHookEncoder added in v1.3.0

func (rb *RegistryBuilder) RegisterHookEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder

RegisterHookEncoder will register an encoder for the provided interface type t. This encoder will be called when marshalling a type if the type implements t or a pointer to the type implements t. If the provided type is not an interface (i.e. t.Kind() != reflect.Interface), this method will panic.

func (*RegistryBuilder) RegisterTypeDecoder added in v1.3.0

func (rb *RegistryBuilder) RegisterTypeDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder

RegisterTypeDecoder will register the provided ValueDecoder for the provided type.

The type will be used directly, so a decoder can be registered for a type and a different decoder can be registered for a pointer to that type.

If the given type is an interface, the decoder will be called when unmarshalling into a type that is that interface. It will not be called when unmarshalling into a non-interface type that implements the interface.

func (*RegistryBuilder) RegisterTypeEncoder added in v1.3.0

func (rb *RegistryBuilder) RegisterTypeEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder

RegisterTypeEncoder will register the provided ValueEncoder for the provided type.

The type will be used directly, so an encoder can be registered for a type and a different encoder can be registered for a pointer to that type.

If the given type is an interface, the encoder will be called when marshalling a type that is that interface. It will not be called when marshalling a non-interface type that implements the interface.

func (*RegistryBuilder) RegisterTypeMapEntry added in v0.1.0

func (rb *RegistryBuilder) RegisterTypeMapEntry(bt bsontype.Type, rt reflect.Type) *RegistryBuilder

RegisterTypeMapEntry will register the provided type to the BSON type. The primary usage for this mapping is decoding situations where an empty interface is used and a default type needs to be created and decoded into.

By default, BSON documents will decode into interface{} values as bson.D. To change the default type for BSON documents, a type map entry for bsontype.EmbeddedDocument should be registered. For example, to force BSON documents to decode to bson.Raw, use the following code:

rb.RegisterTypeMapEntry(bsontype.EmbeddedDocument, reflect.TypeOf(bson.Raw{}))

type SliceCodec added in v1.3.0

type SliceCodec struct {
	EncodeNilAsEmpty bool
}

SliceCodec is the Codec used for slice values.

func NewSliceCodec added in v1.3.0

func NewSliceCodec(opts ...*bsonoptions.SliceCodecOptions) *SliceCodec

NewSliceCodec returns a MapCodec with options opts.

func (*SliceCodec) DecodeValue added in v1.3.0

func (sc *SliceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

DecodeValue is the ValueDecoder for slice types.

func (SliceCodec) EncodeValue added in v1.3.0

func (sc SliceCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

EncodeValue is the ValueEncoder for slice types.

type StringCodec added in v1.2.0

type StringCodec struct {
	DecodeObjectIDAsHex bool
}

StringCodec is the Codec used for struct values.

func NewStringCodec added in v1.2.0

func NewStringCodec(opts ...*bsonoptions.StringCodecOptions) *StringCodec

NewStringCodec returns a StringCodec with options opts.

func (*StringCodec) DecodeValue added in v1.2.0

func (sc *StringCodec) DecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

DecodeValue is the ValueDecoder for string types.

func (*StringCodec) EncodeValue added in v1.2.0

func (sc *StringCodec) EncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

EncodeValue is the ValueEncoder for string types.

type StructCodec

type StructCodec struct {
	DecodeZeroStruct                 bool
	DecodeDeepZeroInline             bool
	EncodeOmitDefaultStruct          bool
	AllowUnexportedFields            bool
	OverwriteDuplicatedInlinedFields bool
	// contains filtered or unexported fields
}

StructCodec is the Codec used for struct values.

func NewStructCodec

func NewStructCodec(p StructTagParser, opts ...*bsonoptions.StructCodecOptions) (*StructCodec, error)

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

func (*StructCodec) DecodeValue

func (sc *StructCodec) DecodeValue(r DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

DecodeValue implements the Codec interface. By default, map types in val will not be cleared. If a map has existing key/value pairs, it will be extended with the new ones from vr. For slices, the decoder will set the length of the slice to zero and append all elements. The underlying array will not be cleared.

func (*StructCodec) EncodeValue

func (sc *StructCodec) EncodeValue(r EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) 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)
	}
	return parseTags(key, tag)
}

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.

var JSONFallbackStructTagParser StructTagParserFunc = func(sf reflect.StructField) (StructTags, error) {
	key := strings.ToLower(sf.Name)
	tag, ok := sf.Tag.Lookup("bson")
	if !ok {
		tag, ok = sf.Tag.Lookup("json")
	}
	if !ok && !strings.Contains(string(sf.Tag), ":") && len(sf.Tag) > 0 {
		tag = string(sf.Tag)
	}

	return parseTags(key, tag)
}

JSONFallbackStructTagParser has the same behavior as DefaultStructTagParser but will also fallback to parsing the json tag instead on a field where the bson tag isn't available.

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 TimeCodec added in v1.2.0

type TimeCodec struct {
	UseLocalTimeZone bool
}

TimeCodec is the Codec used for time.Time values.

func NewTimeCodec added in v1.2.0

func NewTimeCodec(opts ...*bsonoptions.TimeCodecOptions) *TimeCodec

NewTimeCodec returns a TimeCodec with options opts.

func (*TimeCodec) DecodeValue added in v1.2.0

func (tc *TimeCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

DecodeValue is the ValueDecoderFunc for time.Time.

func (*TimeCodec) EncodeValue added in v1.2.0

func (tc *TimeCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

EncodeValue is the ValueEncoderFunc for time.TIme.

type TransitionError

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

TransitionError is an error returned when an invalid progressing a ValueReader or ValueWriter state machine occurs.

func (TransitionError) Error

func (te TransitionError) Error() string

type UIntCodec added in v1.3.0

type UIntCodec struct {
	EncodeToMinSize bool
}

UIntCodec is the Codec used for uint values.

func NewUIntCodec added in v1.3.0

func NewUIntCodec(opts ...*bsonoptions.UIntCodecOptions) *UIntCodec

NewUIntCodec returns a UIntCodec with options opts.

func (*UIntCodec) DecodeValue added in v1.3.0

func (uic *UIntCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

DecodeValue is the ValueDecoder for uint types.

func (*UIntCodec) EncodeValue added in v1.3.0

func (uic *UIntCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

EncodeValue is the ValueEncoder for uint types.

type Unmarshaler

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

Unmarshaler is an interface implemented by types that can unmarshal a BSON document representation of themselves. The BSON bytes can be assumed to be valid. UnmarshalBSON must copy the BSON bytes if it wishes to retain the data after returning.

type ValueCodec

type ValueCodec interface {
	ValueEncoder
	ValueDecoder
}

ValueCodec is the interface that groups the methods to encode and decode values.

type ValueDecoder

type ValueDecoder interface {
	DecodeValue(DecodeContext, bsonrw.ValueReader, reflect.Value) error
}

ValueDecoder is the interface implemented by types that can handle the decoding of a value.

Example
var _ ValueDecoderFunc = func(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
	if !val.CanSet() || val.Kind() != reflect.String {
		return ValueDecoderError{Name: "StringDecodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val}
	}

	if vr.Type() != bsontype.String {
		return fmt.Errorf("cannot decode %v into a string type", vr.Type())
	}

	str, err := vr.ReadString()
	if err != nil {
		return err
	}
	val.SetString(str)
	return nil
}
Output:

type ValueDecoderError

type ValueDecoderError struct {
	Name     string
	Types    []reflect.Type
	Kinds    []reflect.Kind
	Received reflect.Value
}

ValueDecoderError is an error returned from a ValueDecoder when the provided value can't be decoded by the ValueDecoder.

func (ValueDecoderError) Error

func (vde ValueDecoderError) Error() string

type ValueDecoderFunc

type ValueDecoderFunc func(DecodeContext, bsonrw.ValueReader, reflect.Value) error

ValueDecoderFunc is an adapter function that allows a function with the correct signature to be used as a ValueDecoder.

func (ValueDecoderFunc) DecodeValue

func (fn ValueDecoderFunc) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

DecodeValue implements the ValueDecoder interface.

type ValueEncoder

type ValueEncoder interface {
	EncodeValue(EncodeContext, bsonrw.ValueWriter, reflect.Value) error
}

ValueEncoder is the interface implemented by types that can handle the encoding of a value.

Example
var _ ValueEncoderFunc = func(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
	if val.Kind() != reflect.String {
		return ValueEncoderError{Name: "StringEncodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val}
	}

	return vw.WriteString(val.String())
}
Output:

type ValueEncoderError

type ValueEncoderError struct {
	Name     string
	Types    []reflect.Type
	Kinds    []reflect.Kind
	Received reflect.Value
}

ValueEncoderError is an error returned from a ValueEncoder when the provided value can't be encoded by the ValueEncoder.

func (ValueEncoderError) Error

func (vee ValueEncoderError) Error() string

type ValueEncoderFunc

type ValueEncoderFunc func(EncodeContext, bsonrw.ValueWriter, reflect.Value) error

ValueEncoderFunc is an adapter function that allows a function with the correct signature to be used as a ValueEncoder.

func (ValueEncoderFunc) EncodeValue

func (fn ValueEncoderFunc) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error

EncodeValue implements the ValueEncoder interface.

type ValueMarshaler

type ValueMarshaler interface {
	MarshalBSONValue() (bsontype.Type, []byte, error)
}

ValueMarshaler is an interface implemented by types that can marshal themselves into a BSON value as bytes. The type must be the valid type for the bytes returned. The bytes and byte type together must be valid if the error is nil.

type ValueUnmarshaler

type ValueUnmarshaler interface {
	UnmarshalBSONValue(bsontype.Type, []byte) error
}

ValueUnmarshaler is an interface implemented by types that can unmarshal a BSON value representaiton of themselves. The BSON bytes and type can be assumed to be valid. UnmarshalBSONValue must copy the BSON value bytes if it wishes to retain the data after returning.

type Zeroer added in v0.0.17

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL