bsoncodec

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2019 License: Apache-2.0 Imports: 14 Imported by: 0

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. For looking up ValueEncoders and Decoders the Registry first attempts to find a ValueEncoder or ValueDecoder for the type provided; if one cannot be found it then checks to see if a registered ValueEncoder or ValueDecoder exists for an interface the type implements. Finally, the reflect.Kind of the type is used to lookup a default ValueEncoder or ValueDecoder for that kind. If no ValueEncoder or ValueDecoder can be found, an error is returned.

The Registry also holds a type map. This allows users to retrieve the Go type that should be used when decoding a BSON value into an empty interface. This is primarily only used for the empty interface ValueDecoder.

A RegistryBuilder is used to construct a Registry. The Register methods are used to associate either a reflect.Type or a reflect.Kind with a ValueEncoder or ValueDecoder. A RegistryBuilder returned from NewRegistryBuilder contains no registered ValueEncoders nor ValueDecoders and contains an empty type map.

The RegisterTypeMapEntry method handles associating a BSON type with a Go type. For example, if you want to decode BSON int64 and int32 values into Go int instances, you would do the following:

var regbuilder *RegistryBuilder = ... intType := reflect.TypeOf(int(0))
regbuilder.RegisterTypeMapEntry(bsontype.Int64, intType).RegisterTypeMapEntry(bsontype.Int32,
intType)

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

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

ByteSliceDecodeValue is the ValueDecoderFunc for []byte.

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 (DefaultValueDecoders) DBPointerDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

DBPointerDecodeValue is the ValueDecoderFunc for DBPointer.

func (DefaultValueDecoders) DateTimeDecodeValue

func (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

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

EmptyInterfaceDecodeValue is the ValueDecoderFunc for interface{}.

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 bool 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 (DefaultValueDecoders) JavaScriptDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error

JavaScriptDecodeValue is the ValueDecoderFunc for the primitive.JavaScript type.

func (DefaultValueDecoders) MapDecodeValue

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

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

func (DefaultValueDecoders) MaxKeyDecodeValue

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

MaxKeyDecodeValue is the ValueDecoderFunc for MaxKey.

func (DefaultValueDecoders) MinKeyDecodeValue

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

MinKeyDecodeValue is the ValueDecoderFunc for MinKey.

func (DefaultValueDecoders) NullDecodeValue

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

func (DefaultValueDecoders) SliceDecodeValue

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

SliceDecodeValue is the ValueDecoderFunc for slice types.

func (DefaultValueDecoders) StringDecodeValue

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

StringDecodeValue is the ValueDecoderFunc for string types.

func (DefaultValueDecoders) SymbolDecodeValue added in v0.1.0

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

SymbolDecodeValue is the ValueDecoderFunc for the primitive.Symbol type.

func (DefaultValueDecoders) TimeDecodeValue

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

TimeDecodeValue is the ValueDecoderFunc for time.Time.

func (DefaultValueDecoders) TimestampDecodeValue

func (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

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

UintDecodeValue is the ValueDecoderFunc for uint types.

func (DefaultValueDecoders) UndefinedDecodeValue

func (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

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

ByteSliceEncodeValue is the ValueEncoderFunc for []byte.

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

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

EmptyInterfaceEncodeValue is the ValueEncoderFunc for interface{}.

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

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

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

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

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

SliceEncodeValue is the ValueEncoderFunc for slice types.

func (DefaultValueEncoders) StringEncodeValue

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

StringEncodeValue is the ValueEncoderFunc for string types.

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

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

TimeEncodeValue is the ValueEncoderFunc for time.TIme.

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

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

UintEncodeValue is the ValueEncoderFunc for uint types.

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 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 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.

func (*Registry) LookupDecoder

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

LookupDecoder will inspect the registry for a decoder that satisfies the type provided. A decoder registered for a specific type will take precedence over a decoder registered for an interface the type satisfies, which takes precedence over a decoder for the reflect.Kind of the value. If no decoder can be found, an error is returned.

func (*Registry) LookupEncoder

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

LookupEncoder will inspect the registry for an encoder that satisfies the type provided. An encoder registered for a specific type will take precedence over an encoder registered for an interface the type satisfies, which takes precedence over an encoder for the reflect.Kind of the value. If no encoder can be found, an error 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

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

RegisterDecoder will register the provided ValueDecoder to the provided type.

The type registered 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.

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

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

RegisterEncoder will register the provided ValueEncoder to the provided type.

The type registered 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.

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.

NOTE: It is unlikely that registering a type for BSON Embedded Document is actually desired. By registering a type map entry for BSON Embedded Document the type registered will be used in any case where a BSON Embedded Document will be decoded into an empty interface. For example, if you register primitive.M, the EmptyInterface decoder will always use primitive.M, even if an ancestor was a primitive.D.

type StructCodec

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

StructCodec is the Codec used for struct values.

func NewStructCodec

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

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

func (*StructCodec) DecodeValue

func (sc *StructCodec) DecodeValue(r DecodeContext, vr 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)
	}
	var st StructTags
	if tag == "-" {
		st.Skip = true
		return st, nil
	}

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

	st.Name = key

	return st, nil
}

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

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

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

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

An example:

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

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

func (StructTagParserFunc) ParseStructTags

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

ParseStructTags implements the StructTagParser interface.

type StructTags

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

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

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

The properties are defined below:

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

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

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

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

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

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

type 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 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