mongo-driver: go.mongodb.org/mongo-driver/bson/bsoncodec Index | Examples | Files

package bsoncodec

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

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

Package Files

bsoncodec.go byte_slice_codec.go cond_addr_codec.go default_value_decoders.go default_value_encoders.go doc.go empty_interface_codec.go map_codec.go mode.go pointer_codec.go proxy.go registry.go slice_codec.go string_codec.go struct_codec.go struct_tag_parser.go time_codec.go types.go uint_codec.go

Variables

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

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

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

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

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

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

type ByteSliceCodec Uses

type ByteSliceCodec struct {
    EncodeNilAsEmpty bool
}

ByteSliceCodec is the Codec used for []byte values.

func NewByteSliceCodec Uses

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

NewByteSliceCodec returns a StringCodec with options opts.

func (*ByteSliceCodec) DecodeValue Uses

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

DecodeValue is the ValueDecoder for []byte.

func (*ByteSliceCodec) EncodeValue Uses

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

EncodeValue is the ValueEncoder for []byte.

type CodecZeroer Uses

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 Uses

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 Uses

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 Uses

func (de *DecodeError) Error() string

Error implements the error interface.

func (*DecodeError) Keys Uses

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 Uses

func (de *DecodeError) Unwrap() error

Unwrap returns the underlying error

type DefaultValueDecoders Uses

type DefaultValueDecoders struct{}

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

func (DefaultValueDecoders) ArrayDecodeValue Uses

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

ArrayDecodeValue is the ValueDecoderFunc for array types.

func (DefaultValueDecoders) BinaryDecodeValue Uses

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

BinaryDecodeValue is the ValueDecoderFunc for Binary.

func (DefaultValueDecoders) BooleanDecodeValue Uses

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

BooleanDecodeValue is the ValueDecoderFunc for bool types.

func (DefaultValueDecoders) ByteSliceDecodeValue Uses

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 Uses

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

CodeWithScopeDecodeValue is the ValueDecoderFunc for CodeWithScope.

func (DefaultValueDecoders) CoreDocumentDecodeValue Uses

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

CoreDocumentDecodeValue is the ValueDecoderFunc for bsoncore.Document.

func (DefaultValueDecoders) DBPointerDecodeValue Uses

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

DBPointerDecodeValue is the ValueDecoderFunc for DBPointer.

func (DefaultValueDecoders) DDecodeValue Uses

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

DDecodeValue is the ValueDecoderFunc for primitive.D instances.

func (DefaultValueDecoders) DateTimeDecodeValue Uses

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

DateTimeDecodeValue is the ValueDecoderFunc for DateTime.

func (DefaultValueDecoders) Decimal128DecodeValue Uses

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

Decimal128DecodeValue is the ValueDecoderFunc for primitive.Decimal128.

func (DefaultValueDecoders) EmptyInterfaceDecodeValue Uses

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 Uses

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

FloatDecodeValue is the ValueDecoderFunc for float types.

func (DefaultValueDecoders) IntDecodeValue Uses

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

IntDecodeValue is the ValueDecoderFunc for int types.

func (DefaultValueDecoders) JSONNumberDecodeValue Uses

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

JSONNumberDecodeValue is the ValueDecoderFunc for json.Number.

func (DefaultValueDecoders) JavaScriptDecodeValue Uses

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 Uses

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 Uses

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

MaxKeyDecodeValue is the ValueDecoderFunc for MaxKey.

func (DefaultValueDecoders) MinKeyDecodeValue Uses

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

MinKeyDecodeValue is the ValueDecoderFunc for MinKey.

func (DefaultValueDecoders) NullDecodeValue Uses

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

NullDecodeValue is the ValueDecoderFunc for Null.

func (DefaultValueDecoders) ObjectIDDecodeValue Uses

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

ObjectIDDecodeValue is the ValueDecoderFunc for primitive.ObjectID.

func (DefaultValueDecoders) RegexDecodeValue Uses

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

RegexDecodeValue is the ValueDecoderFunc for Regex.

func (DefaultValueDecoders) RegisterDefaultDecoders Uses

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 avaialble in the bson package.

func (DefaultValueDecoders) SliceDecodeValue Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

TimestampDecodeValue is the ValueDecoderFunc for Timestamp.

func (DefaultValueDecoders) URLDecodeValue Uses

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

URLDecodeValue is the ValueDecoderFunc for url.URL.

func (DefaultValueDecoders) UintDecodeValue Uses

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 Uses

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

UndefinedDecodeValue is the ValueDecoderFunc for Undefined.

func (DefaultValueDecoders) UnmarshalerDecodeValue Uses

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

UnmarshalerDecodeValue is the ValueDecoderFunc for Unmarshaler implementations.

func (DefaultValueDecoders) ValueUnmarshalerDecodeValue Uses

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

ValueUnmarshalerDecodeValue is the ValueDecoderFunc for ValueUnmarshaler implementations.

type DefaultValueEncoders Uses

type DefaultValueEncoders struct{}

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

func (DefaultValueEncoders) ArrayEncodeValue Uses

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

ArrayEncodeValue is the ValueEncoderFunc for array types.

func (DefaultValueEncoders) BinaryEncodeValue Uses

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

BinaryEncodeValue is the ValueEncoderFunc for Binary.

func (DefaultValueEncoders) BooleanEncodeValue Uses

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

BooleanEncodeValue is the ValueEncoderFunc for bool types.

func (DefaultValueEncoders) ByteSliceEncodeValue Uses

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 Uses

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

CodeWithScopeEncodeValue is the ValueEncoderFunc for CodeWithScope.

func (DefaultValueEncoders) CoreDocumentEncodeValue Uses

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

CoreDocumentEncodeValue is the ValueEncoderFunc for bsoncore.Document.

func (DefaultValueEncoders) DBPointerEncodeValue Uses

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

DBPointerEncodeValue is the ValueEncoderFunc for DBPointer.

func (DefaultValueEncoders) DateTimeEncodeValue Uses

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

DateTimeEncodeValue is the ValueEncoderFunc for DateTime.

func (DefaultValueEncoders) Decimal128EncodeValue Uses

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

Decimal128EncodeValue is the ValueEncoderFunc for primitive.Decimal128.

func (DefaultValueEncoders) EmptyInterfaceEncodeValue Uses

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 Uses

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

FloatEncodeValue is the ValueEncoderFunc for float types.

func (DefaultValueEncoders) IntEncodeValue Uses

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

IntEncodeValue is the ValueEncoderFunc for int types.

func (DefaultValueEncoders) JSONNumberEncodeValue Uses

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

JSONNumberEncodeValue is the ValueEncoderFunc for json.Number.

func (DefaultValueEncoders) JavaScriptEncodeValue Uses

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

JavaScriptEncodeValue is the ValueEncoderFunc for the primitive.JavaScript type.

func (DefaultValueEncoders) MapEncodeValue Uses

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 Uses

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

MarshalerEncodeValue is the ValueEncoderFunc for Marshaler implementations.

func (DefaultValueEncoders) MaxKeyEncodeValue Uses

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

MaxKeyEncodeValue is the ValueEncoderFunc for MaxKey.

func (DefaultValueEncoders) MinKeyEncodeValue Uses

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

MinKeyEncodeValue is the ValueEncoderFunc for MinKey.

func (DefaultValueEncoders) NullEncodeValue Uses

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

NullEncodeValue is the ValueEncoderFunc for Null.

func (DefaultValueEncoders) ObjectIDEncodeValue Uses

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

ObjectIDEncodeValue is the ValueEncoderFunc for primitive.ObjectID.

func (DefaultValueEncoders) ProxyEncodeValue Uses

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

ProxyEncodeValue is the ValueEncoderFunc for Proxy implementations.

func (DefaultValueEncoders) RegexEncodeValue Uses

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

RegexEncodeValue is the ValueEncoderFunc for Regex.

func (DefaultValueEncoders) RegisterDefaultEncoders Uses

func (dve DefaultValueEncoders) RegisterDefaultEncoders(rb *RegistryBuilder)

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

func (DefaultValueEncoders) SliceEncodeValue Uses

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 Uses

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 Uses

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

SymbolEncodeValue is the ValueEncoderFunc for the primitive.Symbol type.

func (DefaultValueEncoders) TimeEncodeValue Uses

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 Uses

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

TimestampEncodeValue is the ValueEncoderFunc for Timestamp.

func (DefaultValueEncoders) URLEncodeValue Uses

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

URLEncodeValue is the ValueEncoderFunc for url.URL.

func (DefaultValueEncoders) UintEncodeValue Uses

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 Uses

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

UndefinedEncodeValue is the ValueEncoderFunc for Undefined.

func (DefaultValueEncoders) ValueMarshalerEncodeValue Uses

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

ValueMarshalerEncodeValue is the ValueEncoderFunc for ValueMarshaler implementations.

type EmptyInterfaceCodec Uses

type EmptyInterfaceCodec struct {
    DecodeBinaryAsSlice bool
}

EmptyInterfaceCodec is the Codec used for interface{} values.

func NewEmptyInterfaceCodec Uses

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

NewEmptyInterfaceCodec returns a EmptyInterfaceCodec with options opts.

func (EmptyInterfaceCodec) DecodeValue Uses

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

DecodeValue is the ValueDecoderFunc for interface{}.

func (EmptyInterfaceCodec) EncodeValue Uses

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

EncodeValue is the ValueEncoderFunc for interface{}.

type EncodeContext Uses

type EncodeContext struct {
    *Registry
    MinSize bool
}

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

type ErrNoDecoder Uses

type ErrNoDecoder struct {
    Type reflect.Type
}

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

func (ErrNoDecoder) Error Uses

func (end ErrNoDecoder) Error() string

type ErrNoEncoder Uses

type ErrNoEncoder struct {
    Type reflect.Type
}

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

func (ErrNoEncoder) Error Uses

func (ene ErrNoEncoder) Error() string

type ErrNoTypeMapEntry Uses

type ErrNoTypeMapEntry struct {
    Type bsontype.Type
}

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

func (ErrNoTypeMapEntry) Error Uses

func (entme ErrNoTypeMapEntry) Error() string

type KeyMarshaler Uses

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 Uses

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 Uses

type MapCodec struct {
    DecodeZerosMap         bool
    EncodeNilAsEmpty       bool
    EncodeKeysWithStringer bool
}

MapCodec is the Codec used for map values.

func NewMapCodec Uses

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

NewMapCodec returns a MapCodec with options opts.

func (*MapCodec) DecodeValue Uses

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 Uses

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

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

type Marshaler Uses

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 Uses

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

PointerCodec is the Codec used for pointers.

func NewPointerCodec Uses

func NewPointerCodec() *PointerCodec

NewPointerCodec returns a PointerCodec that has been initialized.

func (*PointerCodec) DecodeValue Uses

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 Uses

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 Uses

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 Uses

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.

Code:

// 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 and 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))

Code:

// 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))

func (*Registry) LookupDecoder Uses

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 Uses

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 Uses

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 Uses

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

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

func NewRegistryBuilder Uses

func NewRegistryBuilder() *RegistryBuilder

NewRegistryBuilder creates a new empty RegistryBuilder.

func (*RegistryBuilder) Build Uses

func (rb *RegistryBuilder) Build() *Registry

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

func (*RegistryBuilder) RegisterCodec Uses

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

RegisterCodec will register the provided ValueCodec for the provided type.

func (*RegistryBuilder) RegisterDecoder Uses

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 Uses

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

RegisterDefaultDecoder will register the provided ValueDecoder to the provided kind.

func (*RegistryBuilder) RegisterDefaultEncoder Uses

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

RegisterDefaultEncoder will registr the provided ValueEncoder to the provided kind.

func (*RegistryBuilder) RegisterEncoder Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

type SliceCodec struct {
    EncodeNilAsEmpty bool
}

SliceCodec is the Codec used for slice values.

func NewSliceCodec Uses

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

NewSliceCodec returns a MapCodec with options opts.

func (*SliceCodec) DecodeValue Uses

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

DecodeValue is the ValueDecoder for slice types.

func (SliceCodec) EncodeValue Uses

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

EncodeValue is the ValueEncoder for slice types.

type StringCodec Uses

type StringCodec struct {
    DecodeObjectIDAsHex bool
}

StringCodec is the Codec used for struct values.

func NewStringCodec Uses

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

NewStringCodec returns a StringCodec with options opts.

func (*StringCodec) DecodeValue Uses

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

DecodeValue is the ValueDecoder for string types.

func (*StringCodec) EncodeValue Uses

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

EncodeValue is the ValueEncoder for string types.

type StructCodec Uses

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

StructCodec is the Codec used for struct values.

func NewStructCodec Uses

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

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

func (*StructCodec) DecodeValue Uses

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 Uses

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

EncodeValue handles encoding generic struct types.

type StructTagParser Uses

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

StructTagParser returns the struct tags for a given struct field.

type StructTagParserFunc Uses

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 Uses

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

ParseStructTags implements the StructTagParser interface.

type StructTags Uses

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 Uses

type TimeCodec struct {
    UseLocalTimeZone bool
}

TimeCodec is the Codec used for time.Time values.

func NewTimeCodec Uses

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

NewTimeCodec returns a TimeCodec with options opts.

func (*TimeCodec) DecodeValue Uses

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

DecodeValue is the ValueDecoderFunc for time.Time.

func (*TimeCodec) EncodeValue Uses

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

EncodeValue is the ValueEncoderFunc for time.TIme.

type TransitionError Uses

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 Uses

func (te TransitionError) Error() string

type UIntCodec Uses

type UIntCodec struct {
    EncodeToMinSize bool
}

UIntCodec is the Codec used for uint values.

func NewUIntCodec Uses

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

NewUIntCodec returns a UIntCodec with options opts.

func (*UIntCodec) DecodeValue Uses

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

DecodeValue is the ValueDecoder for uint types.

func (*UIntCodec) EncodeValue Uses

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

EncodeValue is the ValueEncoder for uint types.

type Unmarshaler Uses

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 Uses

type ValueCodec interface {
    ValueEncoder
    ValueDecoder
}

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

type ValueDecoder Uses

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.

Code:

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
}

type ValueDecoderError Uses

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 Uses

func (vde ValueDecoderError) Error() string

type ValueDecoderFunc Uses

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 Uses

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

DecodeValue implements the ValueDecoder interface.

type ValueEncoder Uses

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.

Code:

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())
}

type ValueEncoderError Uses

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 Uses

func (vee ValueEncoderError) Error() string

type ValueEncoderFunc Uses

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 Uses

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

EncodeValue implements the ValueEncoder interface.

type ValueMarshaler Uses

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 Uses

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 Uses

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.

Package bsoncodec imports 15 packages (graph) and is imported by 19 packages. Updated 2020-09-23. Refresh now. Tools for package owners.