From 666fad1ac2fde7204f7344d354aa6104e8c896e2 Mon Sep 17 00:00:00 2001 From: Qingyang Hu Date: Wed, 24 Apr 2024 11:01:25 -0400 Subject: [PATCH] WIP --- bson/bsoncodec.go | 18 +- bson/decoder.go | 19 +- bson/default_value_decoders.go | 763 +++++++--------------------- bson/default_value_decoders_test.go | 159 +++--- bson/default_value_encoders.go | 513 ++++--------------- bson/default_value_encoders_test.go | 80 ++- bson/map_codec.go | 2 +- bson/mgocompat/bson_test.go | 3 - bson/mgocompat/registry.go | 77 ++- bson/primitive_codecs.go | 54 +- bson/primitive_codecs_test.go | 12 +- bson/raw_value_test.go | 6 +- bson/registry.go | 197 +------ bson/registry_test.go | 143 +++--- bson/slice_codec.go | 6 +- bson/string_codec.go | 9 +- bson/struct_codec.go | 2 +- 17 files changed, 553 insertions(+), 1510 deletions(-) diff --git a/bson/bsoncodec.go b/bson/bsoncodec.go index 860a6b82af..592768e911 100644 --- a/bson/bsoncodec.go +++ b/bson/bsoncodec.go @@ -179,11 +179,12 @@ type DecodeContext struct { // error. DocumentType overrides the Ancestor field. defaultDocumentType reflect.Type - binaryAsSlice bool - useJSONStructTags bool - useLocalTimeZone bool - zeroMaps bool - zeroStructs bool + binaryAsSlice bool + decodeObjectIDAsHex bool + useJSONStructTags bool + useLocalTimeZone bool + zeroMaps bool + zeroStructs bool } // BinaryAsSlice causes the Decoder to unmarshal BSON binary field values that are the "Generic" or @@ -194,6 +195,13 @@ func (dc *DecodeContext) BinaryAsSlice() { dc.binaryAsSlice = true } +// DecodeObjectIDAsHex causes the Decoder to unmarshal BSON ObjectID as a hexadecimal string. +// +// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.DecodeObjectIDAsHex] instead. +func (dc *DecodeContext) DecodeObjectIDAsHex() { + dc.binaryAsSlice = true +} + // UseJSONStructTags causes the Decoder to fall back to using the "json" struct tag if a "bson" // struct tag is not specified. // diff --git a/bson/decoder.go b/bson/decoder.go index 6ea5ad97c1..ed0eb34b0f 100644 --- a/bson/decoder.go +++ b/bson/decoder.go @@ -36,11 +36,12 @@ type Decoder struct { defaultDocumentM bool defaultDocumentD bool - binaryAsSlice bool - useJSONStructTags bool - useLocalTimeZone bool - zeroMaps bool - zeroStructs bool + binaryAsSlice bool + decodeObjectIDAsHex bool + useJSONStructTags bool + useLocalTimeZone bool + zeroMaps bool + zeroStructs bool } // NewDecoder returns a new decoder that uses the DefaultRegistry to read from vr. @@ -93,6 +94,9 @@ func (d *Decoder) Decode(val interface{}) error { if d.binaryAsSlice { d.dc.BinaryAsSlice() } + if d.decodeObjectIDAsHex { + d.dc.DecodeObjectIDAsHex() + } if d.useJSONStructTags { d.dc.UseJSONStructTags() } @@ -145,6 +149,11 @@ func (d *Decoder) BinaryAsSlice() { d.binaryAsSlice = true } +// DecodeObjectIDAsHex causes the Decoder to unmarshal BSON ObjectID as a hexadecimal string. +func (d *Decoder) DecodeObjectIDAsHex() { + d.binaryAsSlice = true +} + // UseJSONStructTags causes the Decoder to fall back to using the "json" struct tag if a "bson" // struct tag is not specified. func (d *Decoder) UseJSONStructTags() { diff --git a/bson/default_value_decoders.go b/bson/default_value_decoders.go index bc8c7b9344..a9155c0d4f 100644 --- a/bson/default_value_decoders.go +++ b/bson/default_value_decoders.go @@ -14,14 +14,12 @@ import ( "net/url" "reflect" "strconv" - "time" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) var ( - defaultValueDecoders DefaultValueDecoders - errCannotTruncate = errors.New("float64 can only be truncated to a lower precision type when truncation is enabled") + errCannotTruncate = errors.New("float64 can only be truncated to a lower precision type when truncation is enabled") ) type decodeBinaryError struct { @@ -43,102 +41,87 @@ func newDefaultStructCodec() *StructCodec { return codec } -// DefaultValueDecoders is a namespace type for the default ValueDecoders used -// when creating a registry. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -type DefaultValueDecoders struct{} - -// RegisterDefaultDecoders will register the decoder methods attached to DefaultValueDecoders with -// the provided RegistryBuilder. +// registerDefaultDecoders will register the default decoder methods with the provided Registry. // // There is no support for decoding map[string]interface{} because there is no decoder for // interface{}, so users must either register this decoder themselves or use the // EmptyInterfaceDecoder available in the bson package. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) RegisterDefaultDecoders(rb *RegistryBuilder) { - if rb == nil { +func registerDefaultDecoders(reg *Registry) { + if reg == nil { panic(errors.New("argument to RegisterDefaultDecoders must not be nil")) } - intDecoder := decodeAdapter{dvd.IntDecodeValue, dvd.intDecodeType} - floatDecoder := decodeAdapter{dvd.FloatDecodeValue, dvd.floatDecodeType} - - rb. - RegisterTypeDecoder(tD, ValueDecoderFunc(dvd.DDecodeValue)). - RegisterTypeDecoder(tBinary, decodeAdapter{dvd.BinaryDecodeValue, dvd.binaryDecodeType}). - RegisterTypeDecoder(tUndefined, decodeAdapter{dvd.UndefinedDecodeValue, dvd.undefinedDecodeType}). - RegisterTypeDecoder(tDateTime, decodeAdapter{dvd.DateTimeDecodeValue, dvd.dateTimeDecodeType}). - RegisterTypeDecoder(tNull, decodeAdapter{dvd.NullDecodeValue, dvd.nullDecodeType}). - RegisterTypeDecoder(tRegex, decodeAdapter{dvd.RegexDecodeValue, dvd.regexDecodeType}). - RegisterTypeDecoder(tDBPointer, decodeAdapter{dvd.DBPointerDecodeValue, dvd.dBPointerDecodeType}). - RegisterTypeDecoder(tTimestamp, decodeAdapter{dvd.TimestampDecodeValue, dvd.timestampDecodeType}). - RegisterTypeDecoder(tMinKey, decodeAdapter{dvd.MinKeyDecodeValue, dvd.minKeyDecodeType}). - RegisterTypeDecoder(tMaxKey, decodeAdapter{dvd.MaxKeyDecodeValue, dvd.maxKeyDecodeType}). - RegisterTypeDecoder(tJavaScript, decodeAdapter{dvd.JavaScriptDecodeValue, dvd.javaScriptDecodeType}). - RegisterTypeDecoder(tSymbol, decodeAdapter{dvd.SymbolDecodeValue, dvd.symbolDecodeType}). - RegisterTypeDecoder(tByteSlice, defaultByteSliceCodec). - RegisterTypeDecoder(tTime, defaultTimeCodec). - RegisterTypeDecoder(tEmpty, defaultEmptyInterfaceCodec). - RegisterTypeDecoder(tCoreArray, defaultArrayCodec). - RegisterTypeDecoder(tOID, decodeAdapter{dvd.ObjectIDDecodeValue, dvd.objectIDDecodeType}). - RegisterTypeDecoder(tDecimal, decodeAdapter{dvd.Decimal128DecodeValue, dvd.decimal128DecodeType}). - RegisterTypeDecoder(tJSONNumber, decodeAdapter{dvd.JSONNumberDecodeValue, dvd.jsonNumberDecodeType}). - RegisterTypeDecoder(tURL, decodeAdapter{dvd.URLDecodeValue, dvd.urlDecodeType}). - RegisterTypeDecoder(tCoreDocument, ValueDecoderFunc(dvd.CoreDocumentDecodeValue)). - RegisterTypeDecoder(tCodeWithScope, decodeAdapter{dvd.CodeWithScopeDecodeValue, dvd.codeWithScopeDecodeType}). - RegisterDefaultDecoder(reflect.Bool, decodeAdapter{dvd.BooleanDecodeValue, dvd.booleanDecodeType}). - RegisterDefaultDecoder(reflect.Int, intDecoder). - RegisterDefaultDecoder(reflect.Int8, intDecoder). - RegisterDefaultDecoder(reflect.Int16, intDecoder). - RegisterDefaultDecoder(reflect.Int32, intDecoder). - RegisterDefaultDecoder(reflect.Int64, intDecoder). - RegisterDefaultDecoder(reflect.Uint, defaultUIntCodec). - RegisterDefaultDecoder(reflect.Uint8, defaultUIntCodec). - RegisterDefaultDecoder(reflect.Uint16, defaultUIntCodec). - RegisterDefaultDecoder(reflect.Uint32, defaultUIntCodec). - RegisterDefaultDecoder(reflect.Uint64, defaultUIntCodec). - RegisterDefaultDecoder(reflect.Float32, floatDecoder). - RegisterDefaultDecoder(reflect.Float64, floatDecoder). - RegisterDefaultDecoder(reflect.Array, ValueDecoderFunc(dvd.ArrayDecodeValue)). - RegisterDefaultDecoder(reflect.Map, defaultMapCodec). - RegisterDefaultDecoder(reflect.Slice, defaultSliceCodec). - RegisterDefaultDecoder(reflect.String, defaultStringCodec). - RegisterDefaultDecoder(reflect.Struct, newDefaultStructCodec()). - RegisterDefaultDecoder(reflect.Ptr, NewPointerCodec()). - RegisterTypeMapEntry(TypeDouble, tFloat64). - RegisterTypeMapEntry(TypeString, tString). - RegisterTypeMapEntry(TypeArray, tA). - RegisterTypeMapEntry(TypeBinary, tBinary). - RegisterTypeMapEntry(TypeUndefined, tUndefined). - RegisterTypeMapEntry(TypeObjectID, tOID). - RegisterTypeMapEntry(TypeBoolean, tBool). - RegisterTypeMapEntry(TypeDateTime, tDateTime). - RegisterTypeMapEntry(TypeRegex, tRegex). - RegisterTypeMapEntry(TypeDBPointer, tDBPointer). - RegisterTypeMapEntry(TypeJavaScript, tJavaScript). - RegisterTypeMapEntry(TypeSymbol, tSymbol). - RegisterTypeMapEntry(TypeCodeWithScope, tCodeWithScope). - RegisterTypeMapEntry(TypeInt32, tInt32). - RegisterTypeMapEntry(TypeInt64, tInt64). - RegisterTypeMapEntry(TypeTimestamp, tTimestamp). - RegisterTypeMapEntry(TypeDecimal128, tDecimal). - RegisterTypeMapEntry(TypeMinKey, tMinKey). - RegisterTypeMapEntry(TypeMaxKey, tMaxKey). - RegisterTypeMapEntry(Type(0), tD). - RegisterTypeMapEntry(TypeEmbeddedDocument, tD). - RegisterHookDecoder(tValueUnmarshaler, ValueDecoderFunc(dvd.ValueUnmarshalerDecodeValue)). - RegisterHookDecoder(tUnmarshaler, ValueDecoderFunc(dvd.UnmarshalerDecodeValue)) + intDecoder := decodeAdapter{intDecodeValue, intDecodeType} + floatDecoder := decodeAdapter{floatDecodeValue, floatDecodeType} + + reg.RegisterTypeDecoder(tD, ValueDecoderFunc(dDecodeValue)) + reg.RegisterTypeDecoder(tBinary, decodeAdapter{binaryDecodeValue, binaryDecodeType}) + reg.RegisterTypeDecoder(tUndefined, decodeAdapter{undefinedDecodeValue, undefinedDecodeType}) + reg.RegisterTypeDecoder(tDateTime, decodeAdapter{dateTimeDecodeValue, dateTimeDecodeType}) + reg.RegisterTypeDecoder(tNull, decodeAdapter{nullDecodeValue, nullDecodeType}) + reg.RegisterTypeDecoder(tRegex, decodeAdapter{regexDecodeValue, regexDecodeType}) + reg.RegisterTypeDecoder(tDBPointer, decodeAdapter{dbPointerDecodeValue, dbPointerDecodeType}) + reg.RegisterTypeDecoder(tTimestamp, decodeAdapter{timestampDecodeValue, timestampDecodeType}) + reg.RegisterTypeDecoder(tMinKey, decodeAdapter{minKeyDecodeValue, minKeyDecodeType}) + reg.RegisterTypeDecoder(tMaxKey, decodeAdapter{maxKeyDecodeValue, maxKeyDecodeType}) + reg.RegisterTypeDecoder(tJavaScript, decodeAdapter{javaScriptDecodeValue, javaScriptDecodeType}) + reg.RegisterTypeDecoder(tSymbol, decodeAdapter{symbolDecodeValue, symbolDecodeType}) + reg.RegisterTypeDecoder(tByteSlice, defaultByteSliceCodec) + reg.RegisterTypeDecoder(tTime, defaultTimeCodec) + reg.RegisterTypeDecoder(tEmpty, defaultEmptyInterfaceCodec) + reg.RegisterTypeDecoder(tCoreArray, defaultArrayCodec) + reg.RegisterTypeDecoder(tOID, decodeAdapter{objectIDDecodeValue, objectIDDecodeType}) + reg.RegisterTypeDecoder(tDecimal, decodeAdapter{decimal128DecodeValue, decimal128DecodeType}) + reg.RegisterTypeDecoder(tJSONNumber, decodeAdapter{jsonNumberDecodeValue, jsonNumberDecodeType}) + reg.RegisterTypeDecoder(tURL, decodeAdapter{urlDecodeValue, urlDecodeType}) + reg.RegisterTypeDecoder(tCoreDocument, ValueDecoderFunc(coreDocumentDecodeValue)) + reg.RegisterTypeDecoder(tCodeWithScope, decodeAdapter{codeWithScopeDecodeValue, codeWithScopeDecodeType}) + reg.RegisterKindDecoder(reflect.Bool, decodeAdapter{booleanDecodeValue, booleanDecodeType}) + reg.RegisterKindDecoder(reflect.Int, intDecoder) + reg.RegisterKindDecoder(reflect.Int8, intDecoder) + reg.RegisterKindDecoder(reflect.Int16, intDecoder) + reg.RegisterKindDecoder(reflect.Int32, intDecoder) + reg.RegisterKindDecoder(reflect.Int64, intDecoder) + reg.RegisterKindDecoder(reflect.Uint, defaultUIntCodec) + reg.RegisterKindDecoder(reflect.Uint8, defaultUIntCodec) + reg.RegisterKindDecoder(reflect.Uint16, defaultUIntCodec) + reg.RegisterKindDecoder(reflect.Uint32, defaultUIntCodec) + reg.RegisterKindDecoder(reflect.Uint64, defaultUIntCodec) + reg.RegisterKindDecoder(reflect.Float32, floatDecoder) + reg.RegisterKindDecoder(reflect.Float64, floatDecoder) + reg.RegisterKindDecoder(reflect.Array, ValueDecoderFunc(arrayDecodeValue)) + reg.RegisterKindDecoder(reflect.Map, defaultMapCodec) + reg.RegisterKindDecoder(reflect.Slice, defaultSliceCodec) + reg.RegisterKindDecoder(reflect.String, defaultStringCodec) + reg.RegisterKindDecoder(reflect.Struct, newDefaultStructCodec()) + reg.RegisterKindDecoder(reflect.Ptr, NewPointerCodec()) + reg.RegisterTypeMapEntry(TypeDouble, tFloat64) + reg.RegisterTypeMapEntry(TypeString, tString) + reg.RegisterTypeMapEntry(TypeArray, tA) + reg.RegisterTypeMapEntry(TypeBinary, tBinary) + reg.RegisterTypeMapEntry(TypeUndefined, tUndefined) + reg.RegisterTypeMapEntry(TypeObjectID, tOID) + reg.RegisterTypeMapEntry(TypeBoolean, tBool) + reg.RegisterTypeMapEntry(TypeDateTime, tDateTime) + reg.RegisterTypeMapEntry(TypeRegex, tRegex) + reg.RegisterTypeMapEntry(TypeDBPointer, tDBPointer) + reg.RegisterTypeMapEntry(TypeJavaScript, tJavaScript) + reg.RegisterTypeMapEntry(TypeSymbol, tSymbol) + reg.RegisterTypeMapEntry(TypeCodeWithScope, tCodeWithScope) + reg.RegisterTypeMapEntry(TypeInt32, tInt32) + reg.RegisterTypeMapEntry(TypeInt64, tInt64) + reg.RegisterTypeMapEntry(TypeTimestamp, tTimestamp) + reg.RegisterTypeMapEntry(TypeDecimal128, tDecimal) + reg.RegisterTypeMapEntry(TypeMinKey, tMinKey) + reg.RegisterTypeMapEntry(TypeMaxKey, tMaxKey) + reg.RegisterTypeMapEntry(Type(0), tD) + reg.RegisterTypeMapEntry(TypeEmbeddedDocument, tD) + reg.RegisterInterfaceDecoder(tValueUnmarshaler, ValueDecoderFunc(valueUnmarshalerDecodeValue)) + reg.RegisterInterfaceDecoder(tUnmarshaler, ValueDecoderFunc(unmarshalerDecodeValue)) } -// DDecodeValue is the ValueDecoderFunc for D instances. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) DDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// dDecodeValue is the ValueDecoderFunc for D instances. +func dDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.IsValid() || !val.CanSet() || val.Type() != tD { return ValueDecoderError{Name: "DDecodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val} } @@ -194,7 +177,7 @@ func (dvd DefaultValueDecoders) DDecodeValue(dc DecodeContext, vr ValueReader, v return nil } -func (dvd DefaultValueDecoders) booleanDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func booleanDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t.Kind() != reflect.Bool { return emptyValue, ValueDecoderError{ Name: "BooleanDecodeValue", @@ -240,16 +223,13 @@ func (dvd DefaultValueDecoders) booleanDecodeType(_ DecodeContext, vr ValueReade return reflect.ValueOf(b), nil } -// BooleanDecodeValue is the ValueDecoderFunc for bool types. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) BooleanDecodeValue(dctx DecodeContext, vr ValueReader, val reflect.Value) error { +// booleanDecodeValue is the ValueDecoderFunc for bool types. +func booleanDecodeValue(dctx DecodeContext, vr ValueReader, val reflect.Value) error { if !val.IsValid() || !val.CanSet() || val.Kind() != reflect.Bool { return ValueDecoderError{Name: "BooleanDecodeValue", Kinds: []reflect.Kind{reflect.Bool}, Received: val} } - elem, err := dvd.booleanDecodeType(dctx, vr, val.Type()) + elem, err := booleanDecodeType(dctx, vr, val.Type()) if err != nil { return err } @@ -258,7 +238,7 @@ func (dvd DefaultValueDecoders) BooleanDecodeValue(dctx DecodeContext, vr ValueR return nil } -func (DefaultValueDecoders) intDecodeType(dc DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func intDecodeType(dc DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { var i64 int64 var err error switch vrType := vr.Type(); vrType { @@ -341,11 +321,8 @@ func (DefaultValueDecoders) intDecodeType(dc DecodeContext, vr ValueReader, t re } } -// IntDecodeValue is the ValueDecoderFunc for int types. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) IntDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// intDecodeValue is the ValueDecoderFunc for int types. +func intDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() { return ValueDecoderError{ Name: "IntDecodeValue", @@ -354,7 +331,7 @@ func (dvd DefaultValueDecoders) IntDecodeValue(dc DecodeContext, vr ValueReader, } } - elem, err := dvd.intDecodeType(dc, vr, val.Type()) + elem, err := intDecodeType(dc, vr, val.Type()) if err != nil { return err } @@ -363,90 +340,7 @@ func (dvd DefaultValueDecoders) IntDecodeValue(dc DecodeContext, vr ValueReader, return nil } -// UintDecodeValue is the ValueDecoderFunc for uint types. -// -// Deprecated: UintDecodeValue is not registered by default. Use UintCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) UintDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { - var i64 int64 - var err error - switch vr.Type() { - case TypeInt32: - i32, err := vr.ReadInt32() - if err != nil { - return err - } - i64 = int64(i32) - case TypeInt64: - i64, err = vr.ReadInt64() - if err != nil { - return err - } - case TypeDouble: - f64, err := vr.ReadDouble() - if err != nil { - return err - } - if !dc.Truncate && math.Floor(f64) != f64 { - return errors.New("UintDecodeValue can only truncate float64 to an integer type when truncation is enabled") - } - if f64 > float64(math.MaxInt64) { - return fmt.Errorf("%g overflows int64", f64) - } - i64 = int64(f64) - case TypeBoolean: - b, err := vr.ReadBoolean() - if err != nil { - return err - } - if b { - i64 = 1 - } - default: - return fmt.Errorf("cannot decode %v into an integer type", vr.Type()) - } - - if !val.CanSet() { - return ValueDecoderError{ - Name: "UintDecodeValue", - Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint}, - Received: val, - } - } - - switch val.Kind() { - case reflect.Uint8: - if i64 < 0 || i64 > math.MaxUint8 { - return fmt.Errorf("%d overflows uint8", i64) - } - case reflect.Uint16: - if i64 < 0 || i64 > math.MaxUint16 { - return fmt.Errorf("%d overflows uint16", i64) - } - case reflect.Uint32: - if i64 < 0 || i64 > math.MaxUint32 { - return fmt.Errorf("%d overflows uint32", i64) - } - case reflect.Uint64: - if i64 < 0 { - return fmt.Errorf("%d overflows uint64", i64) - } - case reflect.Uint: - if i64 < 0 || int64(uint(i64)) != i64 { // Can we fit this inside of an uint - return fmt.Errorf("%d overflows uint", i64) - } - default: - return ValueDecoderError{ - Name: "UintDecodeValue", - Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint}, - Received: val, - } - } - - val.SetUint(uint64(i64)) - return nil -} - -func (dvd DefaultValueDecoders) floatDecodeType(dc DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func floatDecodeType(dc DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { var f float64 var err error switch vrType := vr.Type(); vrType { @@ -505,11 +399,8 @@ func (dvd DefaultValueDecoders) floatDecodeType(dc DecodeContext, vr ValueReader } } -// FloatDecodeValue is the ValueDecoderFunc for float types. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) FloatDecodeValue(ec DecodeContext, vr ValueReader, val reflect.Value) error { +// floatDecodeValue is the ValueDecoderFunc for float types. +func floatDecodeValue(ec DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() { return ValueDecoderError{ Name: "FloatDecodeValue", @@ -518,7 +409,7 @@ func (dvd DefaultValueDecoders) FloatDecodeValue(ec DecodeContext, vr ValueReade } } - elem, err := dvd.floatDecodeType(ec, vr, val.Type()) + elem, err := floatDecodeType(ec, vr, val.Type()) if err != nil { return err } @@ -527,31 +418,7 @@ func (dvd DefaultValueDecoders) FloatDecodeValue(ec DecodeContext, vr ValueReade return nil } -// StringDecodeValue is the ValueDecoderFunc for string types. -// -// Deprecated: StringDecodeValue is not registered by default. Use StringCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) StringDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { - var str string - var err error - switch vr.Type() { - // TODO(GODRIVER-577): Handle JavaScript and Symbol BSON types when allowed. - case TypeString: - str, err = vr.ReadString() - if err != nil { - return err - } - default: - return fmt.Errorf("cannot decode %v into a string type", vr.Type()) - } - if !val.CanSet() || val.Kind() != reflect.String { - return ValueDecoderError{Name: "StringDecodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val} - } - - val.SetString(str) - return nil -} - -func (DefaultValueDecoders) javaScriptDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func javaScriptDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tJavaScript { return emptyValue, ValueDecoderError{ Name: "JavaScriptDecodeValue", @@ -579,16 +446,13 @@ func (DefaultValueDecoders) javaScriptDecodeType(_ DecodeContext, vr ValueReader return reflect.ValueOf(JavaScript(js)), nil } -// JavaScriptDecodeValue is the ValueDecoderFunc for the JavaScript type. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) JavaScriptDecodeValue(dctx DecodeContext, vr ValueReader, val reflect.Value) error { +// javaScriptDecodeValue is the ValueDecoderFunc for the JavaScript type. +func javaScriptDecodeValue(dctx DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tJavaScript { return ValueDecoderError{Name: "JavaScriptDecodeValue", Types: []reflect.Type{tJavaScript}, Received: val} } - elem, err := dvd.javaScriptDecodeType(dctx, vr, tJavaScript) + elem, err := javaScriptDecodeType(dctx, vr, tJavaScript) if err != nil { return err } @@ -597,7 +461,7 @@ func (dvd DefaultValueDecoders) JavaScriptDecodeValue(dctx DecodeContext, vr Val return nil } -func (DefaultValueDecoders) symbolDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func symbolDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tSymbol { return emptyValue, ValueDecoderError{ Name: "SymbolDecodeValue", @@ -637,16 +501,13 @@ func (DefaultValueDecoders) symbolDecodeType(_ DecodeContext, vr ValueReader, t return reflect.ValueOf(Symbol(symbol)), nil } -// SymbolDecodeValue is the ValueDecoderFunc for the Symbol type. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) SymbolDecodeValue(dctx DecodeContext, vr ValueReader, val reflect.Value) error { +// symbolDecodeValue is the ValueDecoderFunc for the Symbol type. +func symbolDecodeValue(dctx DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tSymbol { return ValueDecoderError{Name: "SymbolDecodeValue", Types: []reflect.Type{tSymbol}, Received: val} } - elem, err := dvd.symbolDecodeType(dctx, vr, tSymbol) + elem, err := symbolDecodeType(dctx, vr, tSymbol) if err != nil { return err } @@ -655,7 +516,7 @@ func (dvd DefaultValueDecoders) SymbolDecodeValue(dctx DecodeContext, vr ValueRe return nil } -func (DefaultValueDecoders) binaryDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func binaryDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tBinary { return emptyValue, ValueDecoderError{ Name: "BinaryDecodeValue", @@ -684,16 +545,13 @@ func (DefaultValueDecoders) binaryDecodeType(_ DecodeContext, vr ValueReader, t return reflect.ValueOf(Binary{Subtype: subtype, Data: data}), nil } -// BinaryDecodeValue is the ValueDecoderFunc for Binary. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) BinaryDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// binaryDecodeValue is the ValueDecoderFunc for Binary. +func binaryDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tBinary { return ValueDecoderError{Name: "BinaryDecodeValue", Types: []reflect.Type{tBinary}, Received: val} } - elem, err := dvd.binaryDecodeType(dc, vr, tBinary) + elem, err := binaryDecodeType(dc, vr, tBinary) if err != nil { return err } @@ -702,7 +560,7 @@ func (dvd DefaultValueDecoders) BinaryDecodeValue(dc DecodeContext, vr ValueRead return nil } -func (DefaultValueDecoders) undefinedDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func undefinedDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tUndefined { return emptyValue, ValueDecoderError{ Name: "UndefinedDecodeValue", @@ -727,16 +585,13 @@ func (DefaultValueDecoders) undefinedDecodeType(_ DecodeContext, vr ValueReader, return reflect.ValueOf(Undefined{}), nil } -// UndefinedDecodeValue is the ValueDecoderFunc for Undefined. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) UndefinedDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// undefinedDecodeValue is the ValueDecoderFunc for Undefined. +func undefinedDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tUndefined { return ValueDecoderError{Name: "UndefinedDecodeValue", Types: []reflect.Type{tUndefined}, Received: val} } - elem, err := dvd.undefinedDecodeType(dc, vr, tUndefined) + elem, err := undefinedDecodeType(dc, vr, tUndefined) if err != nil { return err } @@ -746,7 +601,7 @@ func (dvd DefaultValueDecoders) UndefinedDecodeValue(dc DecodeContext, vr ValueR } // Accept both 12-byte string and pretty-printed 24-byte hex string formats. -func (dvd DefaultValueDecoders) objectIDDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func objectIDDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tOID { return emptyValue, ValueDecoderError{ Name: "ObjectIDDecodeValue", @@ -791,16 +646,13 @@ func (dvd DefaultValueDecoders) objectIDDecodeType(_ DecodeContext, vr ValueRead return reflect.ValueOf(oid), nil } -// ObjectIDDecodeValue is the ValueDecoderFunc for ObjectID. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) ObjectIDDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// objectIDDecodeValue is the ValueDecoderFunc for ObjectID. +func objectIDDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tOID { return ValueDecoderError{Name: "ObjectIDDecodeValue", Types: []reflect.Type{tOID}, Received: val} } - elem, err := dvd.objectIDDecodeType(dc, vr, tOID) + elem, err := objectIDDecodeType(dc, vr, tOID) if err != nil { return err } @@ -809,7 +661,7 @@ func (dvd DefaultValueDecoders) ObjectIDDecodeValue(dc DecodeContext, vr ValueRe return nil } -func (DefaultValueDecoders) dateTimeDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func dateTimeDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tDateTime { return emptyValue, ValueDecoderError{ Name: "DateTimeDecodeValue", @@ -837,16 +689,13 @@ func (DefaultValueDecoders) dateTimeDecodeType(_ DecodeContext, vr ValueReader, return reflect.ValueOf(DateTime(dt)), nil } -// DateTimeDecodeValue is the ValueDecoderFunc for DateTime. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) DateTimeDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// dateTimeDecodeValue is the ValueDecoderFunc for DateTime. +func dateTimeDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tDateTime { return ValueDecoderError{Name: "DateTimeDecodeValue", Types: []reflect.Type{tDateTime}, Received: val} } - elem, err := dvd.dateTimeDecodeType(dc, vr, tDateTime) + elem, err := dateTimeDecodeType(dc, vr, tDateTime) if err != nil { return err } @@ -855,7 +704,7 @@ func (dvd DefaultValueDecoders) DateTimeDecodeValue(dc DecodeContext, vr ValueRe return nil } -func (DefaultValueDecoders) nullDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func nullDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tNull { return emptyValue, ValueDecoderError{ Name: "NullDecodeValue", @@ -880,16 +729,13 @@ func (DefaultValueDecoders) nullDecodeType(_ DecodeContext, vr ValueReader, t re return reflect.ValueOf(Null{}), nil } -// NullDecodeValue is the ValueDecoderFunc for Null. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) NullDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// nullDecodeValue is the ValueDecoderFunc for Null. +func nullDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tNull { return ValueDecoderError{Name: "NullDecodeValue", Types: []reflect.Type{tNull}, Received: val} } - elem, err := dvd.nullDecodeType(dc, vr, tNull) + elem, err := nullDecodeType(dc, vr, tNull) if err != nil { return err } @@ -898,7 +744,7 @@ func (dvd DefaultValueDecoders) NullDecodeValue(dc DecodeContext, vr ValueReader return nil } -func (DefaultValueDecoders) regexDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func regexDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tRegex { return emptyValue, ValueDecoderError{ Name: "RegexDecodeValue", @@ -926,16 +772,13 @@ func (DefaultValueDecoders) regexDecodeType(_ DecodeContext, vr ValueReader, t r return reflect.ValueOf(Regex{Pattern: pattern, Options: options}), nil } -// RegexDecodeValue is the ValueDecoderFunc for Regex. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) RegexDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// regexDecodeValue is the ValueDecoderFunc for Regex. +func regexDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tRegex { return ValueDecoderError{Name: "RegexDecodeValue", Types: []reflect.Type{tRegex}, Received: val} } - elem, err := dvd.regexDecodeType(dc, vr, tRegex) + elem, err := regexDecodeType(dc, vr, tRegex) if err != nil { return err } @@ -944,7 +787,7 @@ func (dvd DefaultValueDecoders) RegexDecodeValue(dc DecodeContext, vr ValueReade return nil } -func (DefaultValueDecoders) dBPointerDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func dbPointerDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tDBPointer { return emptyValue, ValueDecoderError{ Name: "DBPointerDecodeValue", @@ -973,16 +816,13 @@ func (DefaultValueDecoders) dBPointerDecodeType(_ DecodeContext, vr ValueReader, return reflect.ValueOf(DBPointer{DB: ns, Pointer: pointer}), nil } -// DBPointerDecodeValue is the ValueDecoderFunc for DBPointer. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) DBPointerDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// dbPointerDecodeValue is the ValueDecoderFunc for DBPointer. +func dbPointerDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tDBPointer { return ValueDecoderError{Name: "DBPointerDecodeValue", Types: []reflect.Type{tDBPointer}, Received: val} } - elem, err := dvd.dBPointerDecodeType(dc, vr, tDBPointer) + elem, err := dbPointerDecodeType(dc, vr, tDBPointer) if err != nil { return err } @@ -991,7 +831,7 @@ func (dvd DefaultValueDecoders) DBPointerDecodeValue(dc DecodeContext, vr ValueR return nil } -func (DefaultValueDecoders) timestampDecodeType(_ DecodeContext, vr ValueReader, reflectType reflect.Type) (reflect.Value, error) { +func timestampDecodeType(_ DecodeContext, vr ValueReader, reflectType reflect.Type) (reflect.Value, error) { if reflectType != tTimestamp { return emptyValue, ValueDecoderError{ Name: "TimestampDecodeValue", @@ -1019,16 +859,13 @@ func (DefaultValueDecoders) timestampDecodeType(_ DecodeContext, vr ValueReader, return reflect.ValueOf(Timestamp{T: t, I: incr}), nil } -// TimestampDecodeValue is the ValueDecoderFunc for Timestamp. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) TimestampDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// timestampDecodeValue is the ValueDecoderFunc for Timestamp. +func timestampDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tTimestamp { return ValueDecoderError{Name: "TimestampDecodeValue", Types: []reflect.Type{tTimestamp}, Received: val} } - elem, err := dvd.timestampDecodeType(dc, vr, tTimestamp) + elem, err := timestampDecodeType(dc, vr, tTimestamp) if err != nil { return err } @@ -1037,7 +874,7 @@ func (dvd DefaultValueDecoders) TimestampDecodeValue(dc DecodeContext, vr ValueR return nil } -func (DefaultValueDecoders) minKeyDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func minKeyDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tMinKey { return emptyValue, ValueDecoderError{ Name: "MinKeyDecodeValue", @@ -1064,16 +901,13 @@ func (DefaultValueDecoders) minKeyDecodeType(_ DecodeContext, vr ValueReader, t return reflect.ValueOf(MinKey{}), nil } -// MinKeyDecodeValue is the ValueDecoderFunc for MinKey. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) MinKeyDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// minKeyDecodeValue is the ValueDecoderFunc for MinKey. +func minKeyDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tMinKey { return ValueDecoderError{Name: "MinKeyDecodeValue", Types: []reflect.Type{tMinKey}, Received: val} } - elem, err := dvd.minKeyDecodeType(dc, vr, tMinKey) + elem, err := minKeyDecodeType(dc, vr, tMinKey) if err != nil { return err } @@ -1082,7 +916,7 @@ func (dvd DefaultValueDecoders) MinKeyDecodeValue(dc DecodeContext, vr ValueRead return nil } -func (DefaultValueDecoders) maxKeyDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func maxKeyDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tMaxKey { return emptyValue, ValueDecoderError{ Name: "MaxKeyDecodeValue", @@ -1109,16 +943,13 @@ func (DefaultValueDecoders) maxKeyDecodeType(_ DecodeContext, vr ValueReader, t return reflect.ValueOf(MaxKey{}), nil } -// MaxKeyDecodeValue is the ValueDecoderFunc for MaxKey. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) MaxKeyDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// maxKeyDecodeValue is the ValueDecoderFunc for MaxKey. +func maxKeyDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tMaxKey { return ValueDecoderError{Name: "MaxKeyDecodeValue", Types: []reflect.Type{tMaxKey}, Received: val} } - elem, err := dvd.maxKeyDecodeType(dc, vr, tMaxKey) + elem, err := maxKeyDecodeType(dc, vr, tMaxKey) if err != nil { return err } @@ -1127,7 +958,7 @@ func (dvd DefaultValueDecoders) MaxKeyDecodeValue(dc DecodeContext, vr ValueRead return nil } -func (dvd DefaultValueDecoders) decimal128DecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func decimal128DecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tDecimal { return emptyValue, ValueDecoderError{ Name: "Decimal128DecodeValue", @@ -1155,16 +986,13 @@ func (dvd DefaultValueDecoders) decimal128DecodeType(_ DecodeContext, vr ValueRe return reflect.ValueOf(d128), nil } -// Decimal128DecodeValue is the ValueDecoderFunc for Decimal128. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) Decimal128DecodeValue(dctx DecodeContext, vr ValueReader, val reflect.Value) error { +// decimal128DecodeValue is the ValueDecoderFunc for Decimal128. +func decimal128DecodeValue(dctx DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tDecimal { return ValueDecoderError{Name: "Decimal128DecodeValue", Types: []reflect.Type{tDecimal}, Received: val} } - elem, err := dvd.decimal128DecodeType(dctx, vr, tDecimal) + elem, err := decimal128DecodeType(dctx, vr, tDecimal) if err != nil { return err } @@ -1173,7 +1001,7 @@ func (dvd DefaultValueDecoders) Decimal128DecodeValue(dctx DecodeContext, vr Val return nil } -func (dvd DefaultValueDecoders) jsonNumberDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func jsonNumberDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tJSONNumber { return emptyValue, ValueDecoderError{ Name: "JSONNumberDecodeValue", @@ -1217,16 +1045,13 @@ func (dvd DefaultValueDecoders) jsonNumberDecodeType(_ DecodeContext, vr ValueRe return reflect.ValueOf(jsonNum), nil } -// JSONNumberDecodeValue is the ValueDecoderFunc for json.Number. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) JSONNumberDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// jsonNumberDecodeValue is the ValueDecoderFunc for json.Number. +func jsonNumberDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tJSONNumber { return ValueDecoderError{Name: "JSONNumberDecodeValue", Types: []reflect.Type{tJSONNumber}, Received: val} } - elem, err := dvd.jsonNumberDecodeType(dc, vr, tJSONNumber) + elem, err := jsonNumberDecodeType(dc, vr, tJSONNumber) if err != nil { return err } @@ -1235,7 +1060,7 @@ func (dvd DefaultValueDecoders) JSONNumberDecodeValue(dc DecodeContext, vr Value return nil } -func (dvd DefaultValueDecoders) urlDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func urlDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tURL { return emptyValue, ValueDecoderError{ Name: "URLDecodeValue", @@ -1269,16 +1094,13 @@ func (dvd DefaultValueDecoders) urlDecodeType(_ DecodeContext, vr ValueReader, t return reflect.ValueOf(urlPtr).Elem(), nil } -// URLDecodeValue is the ValueDecoderFunc for url.URL. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) URLDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// urlDecodeValue is the ValueDecoderFunc for url.URL. +func urlDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tURL { return ValueDecoderError{Name: "URLDecodeValue", Types: []reflect.Type{tURL}, Received: val} } - elem, err := dvd.urlDecodeType(dc, vr, tURL) + elem, err := urlDecodeType(dc, vr, tURL) if err != nil { return err } @@ -1287,119 +1109,8 @@ func (dvd DefaultValueDecoders) URLDecodeValue(dc DecodeContext, vr ValueReader, return nil } -// TimeDecodeValue is the ValueDecoderFunc for time.Time. -// -// Deprecated: TimeDecodeValue is not registered by default. Use TimeCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) TimeDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { - if vr.Type() != TypeDateTime { - return fmt.Errorf("cannot decode %v into a time.Time", vr.Type()) - } - - dt, err := vr.ReadDateTime() - if err != nil { - return err - } - - if !val.CanSet() || val.Type() != tTime { - return ValueDecoderError{Name: "TimeDecodeValue", Types: []reflect.Type{tTime}, Received: val} - } - - val.Set(reflect.ValueOf(time.Unix(dt/1000, dt%1000*1000000).UTC())) - return nil -} - -// ByteSliceDecodeValue is the ValueDecoderFunc for []byte. -// -// Deprecated: ByteSliceDecodeValue is not registered by default. Use ByteSliceCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) ByteSliceDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { - if vr.Type() != TypeBinary && vr.Type() != TypeNull { - return fmt.Errorf("cannot decode %v into a []byte", vr.Type()) - } - - if !val.CanSet() || val.Type() != tByteSlice { - return ValueDecoderError{Name: "ByteSliceDecodeValue", Types: []reflect.Type{tByteSlice}, Received: val} - } - - if vr.Type() == TypeNull { - val.Set(reflect.Zero(val.Type())) - return vr.ReadNull() - } - - data, subtype, err := vr.ReadBinary() - if err != nil { - return err - } - if subtype != 0x00 { - return fmt.Errorf("ByteSliceDecodeValue can only be used to decode subtype 0x00 for %s, got %v", TypeBinary, subtype) - } - - val.Set(reflect.ValueOf(data)) - return nil -} - -// MapDecodeValue is the ValueDecoderFunc for map[string]* types. -// -// Deprecated: MapDecodeValue is not registered by default. Use MapCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) MapDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { - if !val.CanSet() || val.Kind() != reflect.Map || val.Type().Key().Kind() != reflect.String { - return ValueDecoderError{Name: "MapDecodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val} - } - - switch vr.Type() { - case Type(0), TypeEmbeddedDocument: - case TypeNull: - val.Set(reflect.Zero(val.Type())) - return vr.ReadNull() - default: - return fmt.Errorf("cannot decode %v into a %s", vr.Type(), val.Type()) - } - - dr, err := vr.ReadDocument() - if err != nil { - return err - } - - if val.IsNil() { - val.Set(reflect.MakeMap(val.Type())) - } - - eType := val.Type().Elem() - decoder, err := dc.LookupDecoder(eType) - if err != nil { - return err - } - - if eType == tEmpty { - dc.Ancestor = val.Type() - } - - keyType := val.Type().Key() - for { - key, vr, err := dr.ReadElement() - if errors.Is(err, ErrEOD) { - break - } - if err != nil { - return err - } - - elem := reflect.New(eType).Elem() - - err = decoder.DecodeValue(dc, vr, elem) - if err != nil { - return err - } - - val.SetMapIndex(reflect.ValueOf(key).Convert(keyType), elem) - } - return nil -} - -// ArrayDecodeValue is the ValueDecoderFunc for array types. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) ArrayDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// arrayDecodeValue is the ValueDecoderFunc for array types. +func arrayDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.IsValid() || val.Kind() != reflect.Array { return ValueDecoderError{Name: "ArrayDecodeValue", Kinds: []reflect.Kind{reflect.Array}, Received: val} } @@ -1443,9 +1154,9 @@ func (dvd DefaultValueDecoders) ArrayDecodeValue(dc DecodeContext, vr ValueReade var elemsFunc func(DecodeContext, ValueReader, reflect.Value) ([]reflect.Value, error) switch val.Type().Elem() { case tE: - elemsFunc = dvd.decodeD + elemsFunc = decodeD default: - elemsFunc = dvd.decodeDefault + elemsFunc = decodeDefault } elems, err := elemsFunc(dc, vr, val) @@ -1464,56 +1175,8 @@ func (dvd DefaultValueDecoders) ArrayDecodeValue(dc DecodeContext, vr ValueReade return nil } -// SliceDecodeValue is the ValueDecoderFunc for slice types. -// -// Deprecated: SliceDecodeValue is not registered by default. Use SliceCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) SliceDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { - if !val.CanSet() || val.Kind() != reflect.Slice { - return ValueDecoderError{Name: "SliceDecodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val} - } - - switch vr.Type() { - case TypeArray: - case TypeNull: - val.Set(reflect.Zero(val.Type())) - return vr.ReadNull() - case Type(0), TypeEmbeddedDocument: - if val.Type().Elem() != tE { - return fmt.Errorf("cannot decode document into %s", val.Type()) - } - default: - return fmt.Errorf("cannot decode %v into a slice", vr.Type()) - } - - var elemsFunc func(DecodeContext, ValueReader, reflect.Value) ([]reflect.Value, error) - switch val.Type().Elem() { - case tE: - dc.Ancestor = val.Type() - elemsFunc = dvd.decodeD - default: - elemsFunc = dvd.decodeDefault - } - - elems, err := elemsFunc(dc, vr, val) - if err != nil { - return err - } - - if val.IsNil() { - val.Set(reflect.MakeSlice(val.Type(), 0, len(elems))) - } - - val.SetLen(0) - val.Set(reflect.Append(val, elems...)) - - return nil -} - -// ValueUnmarshalerDecodeValue is the ValueDecoderFunc for ValueUnmarshaler implementations. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) ValueUnmarshalerDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { +// valueUnmarshalerDecodeValue is the ValueDecoderFunc for ValueUnmarshaler implementations. +func valueUnmarshalerDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { if !val.IsValid() || (!val.Type().Implements(tValueUnmarshaler) && !reflect.PtrTo(val.Type()).Implements(tValueUnmarshaler)) { return ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val} } @@ -1545,11 +1208,8 @@ func (dvd DefaultValueDecoders) ValueUnmarshalerDecodeValue(_ DecodeContext, vr return m.UnmarshalBSONValue(t, src) } -// UnmarshalerDecodeValue is the ValueDecoderFunc for Unmarshaler implementations. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) UnmarshalerDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { +// unmarshalerDecodeValue is the ValueDecoderFunc for Unmarshaler implementations. +func unmarshalerDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { if !val.IsValid() || (!val.Type().Implements(tUnmarshaler) && !reflect.PtrTo(val.Type()).Implements(tUnmarshaler)) { return ValueDecoderError{Name: "UnmarshalerDecodeValue", Types: []reflect.Type{tUnmarshaler}, Received: val} } @@ -1593,51 +1253,8 @@ func (dvd DefaultValueDecoders) UnmarshalerDecodeValue(_ DecodeContext, vr Value return m.UnmarshalBSON(src) } -// EmptyInterfaceDecodeValue is the ValueDecoderFunc for interface{}. -// -// Deprecated: EmptyInterfaceDecodeValue is not registered by default. Use EmptyInterfaceCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) EmptyInterfaceDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { - if !val.CanSet() || val.Type() != tEmpty { - return ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: val} - } - - rtype, err := dc.LookupTypeMapEntry(vr.Type()) - if err != nil { - switch vr.Type() { - case TypeEmbeddedDocument: - if dc.Ancestor != nil { - rtype = dc.Ancestor - break - } - rtype = tD - case TypeNull: - val.Set(reflect.Zero(val.Type())) - return vr.ReadNull() - default: - return err - } - } - - decoder, err := dc.LookupDecoder(rtype) - if err != nil { - return err - } - - elem := reflect.New(rtype).Elem() - err = decoder.DecodeValue(dc, vr, elem) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -// CoreDocumentDecodeValue is the ValueDecoderFunc for bsoncore.Document. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (DefaultValueDecoders) CoreDocumentDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { +// coreDocumentDecodeValue is the ValueDecoderFunc for bsoncore.Document. +func coreDocumentDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tCoreDocument { return ValueDecoderError{Name: "CoreDocumentDecodeValue", Types: []reflect.Type{tCoreDocument}, Received: val} } @@ -1653,7 +1270,7 @@ func (DefaultValueDecoders) CoreDocumentDecodeValue(_ DecodeContext, vr ValueRea return err } -func (dvd DefaultValueDecoders) decodeDefault(dc DecodeContext, vr ValueReader, val reflect.Value) ([]reflect.Value, error) { +func decodeDefault(dc DecodeContext, vr ValueReader, val reflect.Value) ([]reflect.Value, error) { elems := make([]reflect.Value, 0) ar, err := vr.ReadArray() @@ -1690,31 +1307,7 @@ func (dvd DefaultValueDecoders) decodeDefault(dc DecodeContext, vr ValueReader, return elems, nil } -func (dvd DefaultValueDecoders) readCodeWithScope(dc DecodeContext, vr ValueReader) (CodeWithScope, error) { - var cws CodeWithScope - - code, dr, err := vr.ReadCodeWithScope() - if err != nil { - return cws, err - } - - scope := reflect.New(tD).Elem() - elems, err := dvd.decodeElemsFromDocumentReader(dc, dr) - if err != nil { - return cws, err - } - - scope.Set(reflect.MakeSlice(tD, 0, len(elems))) - scope.Set(reflect.Append(scope, elems...)) - - cws = CodeWithScope{ - Code: JavaScript(code), - Scope: scope.Interface().(D), - } - return cws, nil -} - -func (dvd DefaultValueDecoders) codeWithScopeDecodeType(dc DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func codeWithScopeDecodeType(dc DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tCodeWithScope { return emptyValue, ValueDecoderError{ Name: "CodeWithScopeDecodeValue", @@ -1724,34 +1317,44 @@ func (dvd DefaultValueDecoders) codeWithScopeDecodeType(dc DecodeContext, vr Val } var cws CodeWithScope - var err error switch vrType := vr.Type(); vrType { case TypeCodeWithScope: - cws, err = dvd.readCodeWithScope(dc, vr) + code, dr, err := vr.ReadCodeWithScope() + if err != nil { + return emptyValue, err + } + + scope := reflect.New(tD).Elem() + elems, err := decodeElemsFromDocumentReader(dc, dr) + if err != nil { + return emptyValue, err + } + + scope.Set(reflect.MakeSlice(tD, 0, len(elems))) + scope.Set(reflect.Append(scope, elems...)) + + cws = CodeWithScope{ + Code: JavaScript(code), + Scope: scope.Interface().(D), + } case TypeNull: - err = vr.ReadNull() + return emptyValue, vr.ReadNull() case TypeUndefined: - err = vr.ReadUndefined() + return emptyValue, vr.ReadUndefined() default: return emptyValue, fmt.Errorf("cannot decode %v into a CodeWithScope", vrType) } - if err != nil { - return emptyValue, err - } return reflect.ValueOf(cws), nil } -// CodeWithScopeDecodeValue is the ValueDecoderFunc for CodeWithScope. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) CodeWithScopeDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { +// codeWithScopeDecodeValue is the ValueDecoderFunc for CodeWithScope. +func codeWithScopeDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tCodeWithScope { return ValueDecoderError{Name: "CodeWithScopeDecodeValue", Types: []reflect.Type{tCodeWithScope}, Received: val} } - elem, err := dvd.codeWithScopeDecodeType(dc, vr, tCodeWithScope) + elem, err := codeWithScopeDecodeType(dc, vr, tCodeWithScope) if err != nil { return err } @@ -1760,7 +1363,7 @@ func (dvd DefaultValueDecoders) CodeWithScopeDecodeValue(dc DecodeContext, vr Va return nil } -func (dvd DefaultValueDecoders) decodeD(dc DecodeContext, vr ValueReader, _ reflect.Value) ([]reflect.Value, error) { +func decodeD(dc DecodeContext, vr ValueReader, _ reflect.Value) ([]reflect.Value, error) { switch vr.Type() { case Type(0), TypeEmbeddedDocument: default: @@ -1772,10 +1375,10 @@ func (dvd DefaultValueDecoders) decodeD(dc DecodeContext, vr ValueReader, _ refl return nil, err } - return dvd.decodeElemsFromDocumentReader(dc, dr) + return decodeElemsFromDocumentReader(dc, dr) } -func (DefaultValueDecoders) decodeElemsFromDocumentReader(dc DecodeContext, dr DocumentReader) ([]reflect.Value, error) { +func decodeElemsFromDocumentReader(dc DecodeContext, dr DocumentReader) ([]reflect.Value, error) { decoder, err := dc.LookupDecoder(tEmpty) if err != nil { return nil, err diff --git a/bson/default_value_decoders_test.go b/bson/default_value_decoders_test.go index 699a958605..56fdc464c2 100644 --- a/bson/default_value_decoders_test.go +++ b/bson/default_value_decoders_test.go @@ -27,7 +27,6 @@ var ( ) func TestDefaultValueDecoders(t *testing.T) { - var dvd DefaultValueDecoders var wrong = func(string, string) string { return "wrong" } type mybool bool @@ -71,7 +70,7 @@ func TestDefaultValueDecoders(t *testing.T) { }{ { "BooleanDecodeValue", - ValueDecoderFunc(dvd.BooleanDecodeValue), + ValueDecoderFunc(booleanDecodeValue), []subtest{ { "wrong type", @@ -140,7 +139,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "IntDecodeValue", - ValueDecoderFunc(dvd.IntDecodeValue), + ValueDecoderFunc(intDecodeValue), []subtest{ { "wrong type", @@ -608,7 +607,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "FloatDecodeValue", - ValueDecoderFunc(dvd.FloatDecodeValue), + ValueDecoderFunc(floatDecodeValue), []subtest{ { "wrong type", @@ -820,7 +819,7 @@ func TestDefaultValueDecoders(t *testing.T) { { "Lookup Error", map[string]string{}, - &DecodeContext{Registry: newTestRegistryBuilder().Build()}, + &DecodeContext{Registry: newTestRegistry()}, &valueReaderWriter{}, readDocument, ErrNoDecoder{Type: reflect.TypeOf("")}, @@ -869,7 +868,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "ArrayDecodeValue", - ValueDecoderFunc(dvd.ArrayDecodeValue), + ValueDecoderFunc(arrayDecodeValue), []subtest{ { "wrong kind", @@ -906,7 +905,7 @@ func TestDefaultValueDecoders(t *testing.T) { { "Lookup Error", [1]string{}, - &DecodeContext{Registry: newTestRegistryBuilder().Build()}, + &DecodeContext{Registry: newTestRegistry()}, &valueReaderWriter{BSONType: TypeArray}, readArray, ErrNoDecoder{Type: reflect.TypeOf("")}, @@ -1000,7 +999,7 @@ func TestDefaultValueDecoders(t *testing.T) { { "Lookup Error", []string{}, - &DecodeContext{Registry: newTestRegistryBuilder().Build()}, + &DecodeContext{Registry: newTestRegistry()}, &valueReaderWriter{BSONType: TypeArray}, readArray, ErrNoDecoder{Type: reflect.TypeOf("")}, @@ -1057,7 +1056,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "ObjectIDDecodeValue", - ValueDecoderFunc(dvd.ObjectIDDecodeValue), + ValueDecoderFunc(objectIDDecodeValue), []subtest{ { "wrong type", @@ -1144,7 +1143,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "Decimal128DecodeValue", - ValueDecoderFunc(dvd.Decimal128DecodeValue), + ValueDecoderFunc(decimal128DecodeValue), []subtest{ { "wrong type", @@ -1206,7 +1205,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "JSONNumberDecodeValue", - ValueDecoderFunc(dvd.JSONNumberDecodeValue), + ValueDecoderFunc(jsonNumberDecodeValue), []subtest{ { "wrong type", @@ -1300,7 +1299,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "URLDecodeValue", - ValueDecoderFunc(dvd.URLDecodeValue), + ValueDecoderFunc(urlDecodeValue), []subtest{ { "wrong type", @@ -1472,7 +1471,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "ValueUnmarshalerDecodeValue", - ValueDecoderFunc(dvd.ValueUnmarshalerDecodeValue), + ValueDecoderFunc(valueUnmarshalerDecodeValue), []subtest{ { "wrong type", @@ -1506,7 +1505,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "UnmarshalerDecodeValue", - ValueDecoderFunc(dvd.UnmarshalerDecodeValue), + ValueDecoderFunc(unmarshalerDecodeValue), []subtest{ { "wrong type", @@ -1585,7 +1584,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "BinaryDecodeValue", - ValueDecoderFunc(dvd.BinaryDecodeValue), + ValueDecoderFunc(binaryDecodeValue), []subtest{ { "wrong type", @@ -1645,7 +1644,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "UndefinedDecodeValue", - ValueDecoderFunc(dvd.UndefinedDecodeValue), + ValueDecoderFunc(undefinedDecodeValue), []subtest{ { "wrong type", @@ -1691,7 +1690,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "DateTimeDecodeValue", - ValueDecoderFunc(dvd.DateTimeDecodeValue), + ValueDecoderFunc(dateTimeDecodeValue), []subtest{ { "wrong type", @@ -1745,7 +1744,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "NullDecodeValue", - ValueDecoderFunc(dvd.NullDecodeValue), + ValueDecoderFunc(nullDecodeValue), []subtest{ { "wrong type", @@ -1783,7 +1782,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "RegexDecodeValue", - ValueDecoderFunc(dvd.RegexDecodeValue), + ValueDecoderFunc(regexDecodeValue), []subtest{ { "wrong type", @@ -1843,7 +1842,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "DBPointerDecodeValue", - ValueDecoderFunc(dvd.DBPointerDecodeValue), + ValueDecoderFunc(dbPointerDecodeValue), []subtest{ { "wrong type", @@ -1908,7 +1907,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "TimestampDecodeValue", - ValueDecoderFunc(dvd.TimestampDecodeValue), + ValueDecoderFunc(timestampDecodeValue), []subtest{ { "wrong type", @@ -1968,7 +1967,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "MinKeyDecodeValue", - ValueDecoderFunc(dvd.MinKeyDecodeValue), + ValueDecoderFunc(minKeyDecodeValue), []subtest{ { "wrong type", @@ -2022,7 +2021,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "MaxKeyDecodeValue", - ValueDecoderFunc(dvd.MaxKeyDecodeValue), + ValueDecoderFunc(maxKeyDecodeValue), []subtest{ { "wrong type", @@ -2076,7 +2075,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "JavaScriptDecodeValue", - ValueDecoderFunc(dvd.JavaScriptDecodeValue), + ValueDecoderFunc(javaScriptDecodeValue), []subtest{ { "wrong type", @@ -2130,7 +2129,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "SymbolDecodeValue", - ValueDecoderFunc(dvd.SymbolDecodeValue), + ValueDecoderFunc(symbolDecodeValue), []subtest{ { "wrong type", @@ -2184,7 +2183,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "CoreDocumentDecodeValue", - ValueDecoderFunc(dvd.CoreDocumentDecodeValue), + ValueDecoderFunc(coreDocumentDecodeValue), []subtest{ { "wrong type", @@ -2252,7 +2251,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "CodeWithScopeDecodeValue", - ValueDecoderFunc(dvd.CodeWithScopeDecodeValue), + ValueDecoderFunc(codeWithScopeDecodeValue), []subtest{ { "wrong type", @@ -2439,7 +2438,7 @@ func TestDefaultValueDecoders(t *testing.T) { Scope: D{{"bar", nil}}, } val := reflect.New(tCodeWithScope).Elem() - err = dvd.CodeWithScopeDecodeValue(dc, vr, val) + err = codeWithScopeDecodeValue(dc, vr, val) noerr(t, err) got := val.Interface().(CodeWithScope) @@ -2454,7 +2453,7 @@ func TestDefaultValueDecoders(t *testing.T) { want := errors.New("ubsonv error") valUnmarshaler := &testValueUnmarshaler{err: want} - got := dvd.ValueUnmarshalerDecodeValue(dc, llvrw, reflect.ValueOf(valUnmarshaler)) + got := valueUnmarshalerDecodeValue(dc, llvrw, reflect.ValueOf(valUnmarshaler)) if !assert.CompareErrors(got, want) { t.Errorf("Errors do not match. got %v; want %v", got, want) } @@ -2466,16 +2465,7 @@ func TestDefaultValueDecoders(t *testing.T) { val := reflect.ValueOf(testValueUnmarshaler{}) want := ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val} - got := dvd.ValueUnmarshalerDecodeValue(dc, llvrw, val) - if !assert.CompareErrors(got, want) { - t.Errorf("Errors do not match. got %v; want %v", got, want) - } - }) - - t.Run("SliceCodec/DecodeValue/can't set slice", func(t *testing.T) { - var val []string - want := ValueDecoderError{Name: "SliceDecodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: reflect.ValueOf(val)} - got := dvd.SliceDecodeValue(DecodeContext{}, nil, reflect.ValueOf(val)) + got := valueUnmarshalerDecodeValue(dc, llvrw, val) if !assert.CompareErrors(got, want) { t.Errorf("Errors do not match. got %v; want %v", got, want) } @@ -2499,7 +2489,7 @@ func TestDefaultValueDecoders(t *testing.T) { want := fmt.Errorf("more elements returned in array than can fit inside %T, got 2 elements", val) dc := DecodeContext{Registry: buildDefaultRegistry()} - got := dvd.ArrayDecodeValue(dc, vr, reflect.ValueOf(val)) + got := arrayDecodeValue(dc, vr, reflect.ValueOf(val)) if !assert.CompareErrors(got, want) { t.Errorf("Errors do not match. got %v; want %v", got, want) } @@ -3319,7 +3309,7 @@ func TestDefaultValueDecoders(t *testing.T) { t.Skip() } val := reflect.New(tEmpty).Elem() - dc := DecodeContext{Registry: newTestRegistryBuilder().Build()} + dc := DecodeContext{Registry: newTestRegistry()} want := ErrNoTypeMapEntry{Type: tc.bsontype} got := defaultEmptyInterfaceCodec.DecodeValue(dc, llvr, val) if !assert.CompareErrors(got, want) { @@ -3332,10 +3322,10 @@ func TestDefaultValueDecoders(t *testing.T) { t.Skip() } val := reflect.New(tEmpty).Elem() + reg := newTestRegistry() + reg.RegisterTypeMapEntry(tc.bsontype, reflect.TypeOf(tc.val)) dc := DecodeContext{ - Registry: newTestRegistryBuilder(). - RegisterTypeMapEntry(tc.bsontype, reflect.TypeOf(tc.val)). - Build(), + Registry: reg, } want := ErrNoDecoder{Type: reflect.TypeOf(tc.val)} got := defaultEmptyInterfaceCodec.DecodeValue(dc, llvr, val) @@ -3350,11 +3340,11 @@ func TestDefaultValueDecoders(t *testing.T) { } want := errors.New("DecodeValue failure error") llc := &llCodec{t: t, err: want} + reg := newTestRegistry() + reg.RegisterTypeDecoder(reflect.TypeOf(tc.val), llc) + reg.RegisterTypeMapEntry(tc.bsontype, reflect.TypeOf(tc.val)) dc := DecodeContext{ - Registry: newTestRegistryBuilder(). - RegisterTypeDecoder(reflect.TypeOf(tc.val), llc). - RegisterTypeMapEntry(tc.bsontype, reflect.TypeOf(tc.val)). - Build(), + Registry: reg, } got := defaultEmptyInterfaceCodec.DecodeValue(dc, llvr, reflect.New(tEmpty).Elem()) if !assert.CompareErrors(got, want) { @@ -3365,11 +3355,11 @@ func TestDefaultValueDecoders(t *testing.T) { t.Run("Success", func(t *testing.T) { want := tc.val llc := &llCodec{t: t, decodeval: tc.val} + reg := newTestRegistry() + reg.RegisterTypeDecoder(reflect.TypeOf(tc.val), llc) + reg.RegisterTypeMapEntry(tc.bsontype, reflect.TypeOf(tc.val)) dc := DecodeContext{ - Registry: newTestRegistryBuilder(). - RegisterTypeDecoder(reflect.TypeOf(tc.val), llc). - RegisterTypeMapEntry(tc.bsontype, reflect.TypeOf(tc.val)). - Build(), + Registry: reg, } got := reflect.New(tEmpty).Elem() err := defaultEmptyInterfaceCodec.DecodeValue(dc, llvr, got) @@ -3404,7 +3394,7 @@ func TestDefaultValueDecoders(t *testing.T) { llvr := &valueReaderWriter{BSONType: TypeDouble} want := ErrNoTypeMapEntry{Type: TypeDouble} val := reflect.New(tEmpty).Elem() - got := defaultEmptyInterfaceCodec.DecodeValue(DecodeContext{Registry: newTestRegistryBuilder().Build()}, llvr, val) + got := defaultEmptyInterfaceCodec.DecodeValue(DecodeContext{Registry: newTestRegistry()}, llvr, val) if !assert.CompareErrors(got, want) { t.Errorf("Errors are not equal. got %v; want %v", got, want) } @@ -3425,15 +3415,15 @@ func TestDefaultValueDecoders(t *testing.T) { // registering a custom type map entry for both Type(0) anad TypeEmbeddedDocument should cause // both top-level and embedded documents to decode to registered type when unmarshalling to interface{} - topLevelRb := newTestRegistryBuilder() - defaultValueEncoders.RegisterDefaultEncoders(topLevelRb) - defaultValueDecoders.RegisterDefaultDecoders(topLevelRb) - topLevelRb.RegisterTypeMapEntry(Type(0), reflect.TypeOf(M{})) + topLevelReg := newTestRegistry() + registerDefaultEncoders(topLevelReg) + registerDefaultDecoders(topLevelReg) + topLevelReg.RegisterTypeMapEntry(Type(0), reflect.TypeOf(M{})) - embeddedRb := newTestRegistryBuilder() - defaultValueEncoders.RegisterDefaultEncoders(embeddedRb) - defaultValueDecoders.RegisterDefaultDecoders(embeddedRb) - embeddedRb.RegisterTypeMapEntry(Type(0), reflect.TypeOf(M{})) + embeddedReg := newTestRegistry() + registerDefaultEncoders(embeddedReg) + registerDefaultDecoders(embeddedReg) + embeddedReg.RegisterTypeMapEntry(Type(0), reflect.TypeOf(M{})) // create doc {"nested": {"foo": 1}} innerDoc := bsoncore.BuildDocument( @@ -3454,8 +3444,8 @@ func TestDefaultValueDecoders(t *testing.T) { name string registry *Registry }{ - {"top level", topLevelRb.Build()}, - {"embedded", embeddedRb.Build()}, + {"top level", topLevelReg}, + {"embedded", embeddedReg}, } for _, tc := range testCases { var got interface{} @@ -3473,11 +3463,10 @@ func TestDefaultValueDecoders(t *testing.T) { // If a type map entry is registered for TypeEmbeddedDocument, the decoder should use ancestor // information if available instead of the registered entry. - rb := newTestRegistryBuilder() - defaultValueEncoders.RegisterDefaultEncoders(rb) - defaultValueDecoders.RegisterDefaultDecoders(rb) - rb.RegisterTypeMapEntry(TypeEmbeddedDocument, reflect.TypeOf(M{})) - reg := rb.Build() + reg := newTestRegistry() + registerDefaultEncoders(reg) + registerDefaultDecoders(reg) + reg.RegisterTypeMapEntry(TypeEmbeddedDocument, reflect.TypeOf(M{})) // build document {"nested": {"foo": 10}} inner := bsoncore.BuildDocument( @@ -3510,8 +3499,8 @@ func TestDefaultValueDecoders(t *testing.T) { emptyInterfaceErrorDecode := func(DecodeContext, ValueReader, reflect.Value) error { return decodeValueError } - emptyInterfaceErrorRegistry := newTestRegistryBuilder(). - RegisterTypeDecoder(tEmpty, ValueDecoderFunc(emptyInterfaceErrorDecode)).Build() + emptyInterfaceErrorRegistry := newTestRegistry() + emptyInterfaceErrorRegistry.RegisterTypeDecoder(tEmpty, ValueDecoderFunc(emptyInterfaceErrorDecode)) // Set up a document {foo: 10} and an error that would happen if the value were decoded into interface{} // using the registry defined above. @@ -3563,11 +3552,9 @@ func TestDefaultValueDecoders(t *testing.T) { outerDoc := buildDocument(bsoncore.AppendDocumentElement(nil, "first", inner1Doc)) // Use a registry that has all default decoders with the custom interface{} decoder that always errors. - nestedRegistryBuilder := newTestRegistryBuilder() - defaultValueDecoders.RegisterDefaultDecoders(nestedRegistryBuilder) - nestedRegistry := nestedRegistryBuilder. - RegisterTypeDecoder(tEmpty, ValueDecoderFunc(emptyInterfaceErrorDecode)). - Build() + nestedRegistry := newTestRegistry() + registerDefaultDecoders(nestedRegistry) + nestedRegistry.RegisterTypeDecoder(tEmpty, ValueDecoderFunc(emptyInterfaceErrorDecode)) nestedErr := &DecodeError{ keys: []string{"fourth", "1", "third", "randomKey", "second", "first"}, wrapped: decodeValueError, @@ -3610,7 +3597,7 @@ func TestDefaultValueDecoders(t *testing.T) { [1]E{}, NewValueReader(docBytes), emptyInterfaceErrorRegistry, - ValueDecoderFunc(dvd.ArrayDecodeValue), + ValueDecoderFunc(arrayDecodeValue), docEmptyInterfaceErr, }, { @@ -3621,7 +3608,7 @@ func TestDefaultValueDecoders(t *testing.T) { [1]string{}, &valueReaderWriter{BSONType: TypeArray}, nil, - ValueDecoderFunc(dvd.ArrayDecodeValue), + ValueDecoderFunc(arrayDecodeValue), &DecodeError{ keys: []string{"0"}, wrapped: errors.New("cannot decode array into a string type"), @@ -3652,7 +3639,7 @@ func TestDefaultValueDecoders(t *testing.T) { "struct - no decoder found", stringStruct{}, NewValueReader(docBytes), - newTestRegistryBuilder().Build(), + newTestRegistry(), defaultTestStructCodec, stringStructErr, }, @@ -3717,14 +3704,14 @@ func TestDefaultValueDecoders(t *testing.T) { bsoncore.BuildArrayElement(nil, "boolArray", trueValue), ) - rb := newTestRegistryBuilder() - defaultValueDecoders.RegisterDefaultDecoders(rb) - reg := rb.RegisterTypeMapEntry(TypeBoolean, reflect.TypeOf(mybool(true))).Build() + reg := newTestRegistry() + registerDefaultDecoders(reg) + reg.RegisterTypeMapEntry(TypeBoolean, reflect.TypeOf(mybool(true))) dc := DecodeContext{Registry: reg} vr := NewValueReader(docBytes) val := reflect.New(tD).Elem() - err := defaultValueDecoders.DDecodeValue(dc, vr, val) + err := dDecodeValue(dc, vr, val) assert.Nil(t, err, "DDecodeValue error: %v", err) want := D{ @@ -3786,8 +3773,8 @@ func buildDocument(elems []byte) []byte { } func buildDefaultRegistry() *Registry { - rb := newTestRegistryBuilder() - defaultValueEncoders.RegisterDefaultEncoders(rb) - defaultValueDecoders.RegisterDefaultDecoders(rb) - return rb.Build() + reg := newTestRegistry() + registerDefaultEncoders(reg) + registerDefaultDecoders(reg) + return reg } diff --git a/bson/default_value_encoders.go b/bson/default_value_encoders.go index f2773c36e5..6b28f1594b 100644 --- a/bson/default_value_encoders.go +++ b/bson/default_value_encoders.go @@ -9,18 +9,14 @@ package bson import ( "encoding/json" "errors" - "fmt" "math" "net/url" "reflect" "sync" - "time" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) -var defaultValueEncoders DefaultValueEncoders - var bvwPool = NewValueWriterPool() var errInvalidValue = errors.New("cannot encode invalid element") @@ -53,73 +49,58 @@ func encodeElement(ec EncodeContext, dw DocumentWriter, e E) error { return nil } -// DefaultValueEncoders is a namespace type for the default ValueEncoders used -// when creating a registry. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -type DefaultValueEncoders struct{} - -// RegisterDefaultEncoders will register the encoder methods attached to DefaultValueEncoders with -// the provided RegistryBuilder. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) RegisterDefaultEncoders(rb *RegistryBuilder) { - if rb == nil { +// registerDefaultEncoders will register the default encoder methods with the provided Registry. +func registerDefaultEncoders(reg *Registry) { + if reg == nil { panic(errors.New("argument to RegisterDefaultEncoders must not be nil")) } - rb. - RegisterTypeEncoder(tByteSlice, defaultByteSliceCodec). - RegisterTypeEncoder(tTime, defaultTimeCodec). - RegisterTypeEncoder(tEmpty, defaultEmptyInterfaceCodec). - RegisterTypeEncoder(tCoreArray, defaultArrayCodec). - RegisterTypeEncoder(tOID, ValueEncoderFunc(dve.ObjectIDEncodeValue)). - RegisterTypeEncoder(tDecimal, ValueEncoderFunc(dve.Decimal128EncodeValue)). - RegisterTypeEncoder(tJSONNumber, ValueEncoderFunc(dve.JSONNumberEncodeValue)). - RegisterTypeEncoder(tURL, ValueEncoderFunc(dve.URLEncodeValue)). - RegisterTypeEncoder(tJavaScript, ValueEncoderFunc(dve.JavaScriptEncodeValue)). - RegisterTypeEncoder(tSymbol, ValueEncoderFunc(dve.SymbolEncodeValue)). - RegisterTypeEncoder(tBinary, ValueEncoderFunc(dve.BinaryEncodeValue)). - RegisterTypeEncoder(tUndefined, ValueEncoderFunc(dve.UndefinedEncodeValue)). - RegisterTypeEncoder(tDateTime, ValueEncoderFunc(dve.DateTimeEncodeValue)). - RegisterTypeEncoder(tNull, ValueEncoderFunc(dve.NullEncodeValue)). - RegisterTypeEncoder(tRegex, ValueEncoderFunc(dve.RegexEncodeValue)). - RegisterTypeEncoder(tDBPointer, ValueEncoderFunc(dve.DBPointerEncodeValue)). - RegisterTypeEncoder(tTimestamp, ValueEncoderFunc(dve.TimestampEncodeValue)). - RegisterTypeEncoder(tMinKey, ValueEncoderFunc(dve.MinKeyEncodeValue)). - RegisterTypeEncoder(tMaxKey, ValueEncoderFunc(dve.MaxKeyEncodeValue)). - RegisterTypeEncoder(tCoreDocument, ValueEncoderFunc(dve.CoreDocumentEncodeValue)). - RegisterTypeEncoder(tCodeWithScope, ValueEncoderFunc(dve.CodeWithScopeEncodeValue)). - RegisterDefaultEncoder(reflect.Bool, ValueEncoderFunc(dve.BooleanEncodeValue)). - RegisterDefaultEncoder(reflect.Int, ValueEncoderFunc(dve.IntEncodeValue)). - RegisterDefaultEncoder(reflect.Int8, ValueEncoderFunc(dve.IntEncodeValue)). - RegisterDefaultEncoder(reflect.Int16, ValueEncoderFunc(dve.IntEncodeValue)). - RegisterDefaultEncoder(reflect.Int32, ValueEncoderFunc(dve.IntEncodeValue)). - RegisterDefaultEncoder(reflect.Int64, ValueEncoderFunc(dve.IntEncodeValue)). - RegisterDefaultEncoder(reflect.Uint, defaultUIntCodec). - RegisterDefaultEncoder(reflect.Uint8, defaultUIntCodec). - RegisterDefaultEncoder(reflect.Uint16, defaultUIntCodec). - RegisterDefaultEncoder(reflect.Uint32, defaultUIntCodec). - RegisterDefaultEncoder(reflect.Uint64, defaultUIntCodec). - RegisterDefaultEncoder(reflect.Float32, ValueEncoderFunc(dve.FloatEncodeValue)). - RegisterDefaultEncoder(reflect.Float64, ValueEncoderFunc(dve.FloatEncodeValue)). - RegisterDefaultEncoder(reflect.Array, ValueEncoderFunc(dve.ArrayEncodeValue)). - RegisterDefaultEncoder(reflect.Map, defaultMapCodec). - RegisterDefaultEncoder(reflect.Slice, defaultSliceCodec). - RegisterDefaultEncoder(reflect.String, defaultStringCodec). - RegisterDefaultEncoder(reflect.Struct, newDefaultStructCodec()). - RegisterDefaultEncoder(reflect.Ptr, NewPointerCodec()). - RegisterHookEncoder(tValueMarshaler, ValueEncoderFunc(dve.ValueMarshalerEncodeValue)). - RegisterHookEncoder(tMarshaler, ValueEncoderFunc(dve.MarshalerEncodeValue)). - RegisterHookEncoder(tProxy, ValueEncoderFunc(dve.ProxyEncodeValue)) -} - -// BooleanEncodeValue is the ValueEncoderFunc for bool types. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) BooleanEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { + reg.RegisterTypeEncoder(tByteSlice, defaultByteSliceCodec) + reg.RegisterTypeEncoder(tTime, defaultTimeCodec) + reg.RegisterTypeEncoder(tEmpty, defaultEmptyInterfaceCodec) + reg.RegisterTypeEncoder(tCoreArray, defaultArrayCodec) + reg.RegisterTypeEncoder(tOID, ValueEncoderFunc(objectIDEncodeValue)) + reg.RegisterTypeEncoder(tDecimal, ValueEncoderFunc(decimal128EncodeValue)) + reg.RegisterTypeEncoder(tJSONNumber, ValueEncoderFunc(jsonNumberEncodeValue)) + reg.RegisterTypeEncoder(tURL, ValueEncoderFunc(urlEncodeValue)) + reg.RegisterTypeEncoder(tJavaScript, ValueEncoderFunc(javaScriptEncodeValue)) + reg.RegisterTypeEncoder(tSymbol, ValueEncoderFunc(symbolEncodeValue)) + reg.RegisterTypeEncoder(tBinary, ValueEncoderFunc(binaryEncodeValue)) + reg.RegisterTypeEncoder(tUndefined, ValueEncoderFunc(undefinedEncodeValue)) + reg.RegisterTypeEncoder(tDateTime, ValueEncoderFunc(dateTimeEncodeValue)) + reg.RegisterTypeEncoder(tNull, ValueEncoderFunc(nullEncodeValue)) + reg.RegisterTypeEncoder(tRegex, ValueEncoderFunc(regexEncodeValue)) + reg.RegisterTypeEncoder(tDBPointer, ValueEncoderFunc(dbPointerEncodeValue)) + reg.RegisterTypeEncoder(tTimestamp, ValueEncoderFunc(timestampEncodeValue)) + reg.RegisterTypeEncoder(tMinKey, ValueEncoderFunc(minKeyEncodeValue)) + reg.RegisterTypeEncoder(tMaxKey, ValueEncoderFunc(maxKeyEncodeValue)) + reg.RegisterTypeEncoder(tCoreDocument, ValueEncoderFunc(coreDocumentEncodeValue)) + reg.RegisterTypeEncoder(tCodeWithScope, ValueEncoderFunc(codeWithScopeEncodeValue)) + reg.RegisterKindEncoder(reflect.Bool, ValueEncoderFunc(booleanEncodeValue)) + reg.RegisterKindEncoder(reflect.Int, ValueEncoderFunc(intEncodeValue)) + reg.RegisterKindEncoder(reflect.Int8, ValueEncoderFunc(intEncodeValue)) + reg.RegisterKindEncoder(reflect.Int16, ValueEncoderFunc(intEncodeValue)) + reg.RegisterKindEncoder(reflect.Int32, ValueEncoderFunc(intEncodeValue)) + reg.RegisterKindEncoder(reflect.Int64, ValueEncoderFunc(intEncodeValue)) + reg.RegisterKindEncoder(reflect.Uint, defaultUIntCodec) + reg.RegisterKindEncoder(reflect.Uint8, defaultUIntCodec) + reg.RegisterKindEncoder(reflect.Uint16, defaultUIntCodec) + reg.RegisterKindEncoder(reflect.Uint32, defaultUIntCodec) + reg.RegisterKindEncoder(reflect.Uint64, defaultUIntCodec) + reg.RegisterKindEncoder(reflect.Float32, ValueEncoderFunc(floatEncodeValue)) + reg.RegisterKindEncoder(reflect.Float64, ValueEncoderFunc(floatEncodeValue)) + reg.RegisterKindEncoder(reflect.Array, ValueEncoderFunc(arrayEncodeValue)) + reg.RegisterKindEncoder(reflect.Map, defaultMapCodec) + reg.RegisterKindEncoder(reflect.Slice, defaultSliceCodec) + reg.RegisterKindEncoder(reflect.String, defaultStringCodec) + reg.RegisterKindEncoder(reflect.Struct, newDefaultStructCodec()) + reg.RegisterKindEncoder(reflect.Ptr, NewPointerCodec()) + reg.RegisterInterfaceEncoder(tValueMarshaler, ValueEncoderFunc(valueMarshalerEncodeValue)) + reg.RegisterInterfaceEncoder(tMarshaler, ValueEncoderFunc(marshalerEncodeValue)) + reg.RegisterInterfaceEncoder(tProxy, ValueEncoderFunc(proxyEncodeValue)) +} + +// booleanEncodeValue is the ValueEncoderFunc for bool types. +func booleanEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Kind() != reflect.Bool { return ValueEncoderError{Name: "BooleanEncodeValue", Kinds: []reflect.Kind{reflect.Bool}, Received: val} } @@ -130,11 +111,8 @@ func fitsIn32Bits(i int64) bool { return math.MinInt32 <= i && i <= math.MaxInt32 } -// IntEncodeValue is the ValueEncoderFunc for int types. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) IntEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { +// intEncodeValue is the ValueEncoderFunc for int types. +func intEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { switch val.Kind() { case reflect.Int8, reflect.Int16, reflect.Int32: return vw.WriteInt32(int32(val.Int())) @@ -159,36 +137,8 @@ func (dve DefaultValueEncoders) IntEncodeValue(ec EncodeContext, vw ValueWriter, } } -// UintEncodeValue is the ValueEncoderFunc for uint types. -// -// Deprecated: UintEncodeValue is not registered by default. Use UintCodec.EncodeValue instead. -func (dve DefaultValueEncoders) UintEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { - switch val.Kind() { - case reflect.Uint8, reflect.Uint16: - return vw.WriteInt32(int32(val.Uint())) - case reflect.Uint, reflect.Uint32, reflect.Uint64: - u64 := val.Uint() - if ec.MinSize && u64 <= math.MaxInt32 { - return vw.WriteInt32(int32(u64)) - } - if u64 > math.MaxInt64 { - return fmt.Errorf("%d overflows int64", u64) - } - return vw.WriteInt64(int64(u64)) - } - - return ValueEncoderError{ - Name: "UintEncodeValue", - Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint}, - Received: val, - } -} - -// FloatEncodeValue is the ValueEncoderFunc for float types. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) FloatEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// floatEncodeValue is the ValueEncoderFunc for float types. +func floatEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { switch val.Kind() { case reflect.Float32, reflect.Float64: return vw.WriteDouble(val.Float()) @@ -197,48 +147,24 @@ func (dve DefaultValueEncoders) FloatEncodeValue(_ EncodeContext, vw ValueWriter return ValueEncoderError{Name: "FloatEncodeValue", Kinds: []reflect.Kind{reflect.Float32, reflect.Float64}, Received: val} } -// StringEncodeValue is the ValueEncoderFunc for string types. -// -// Deprecated: StringEncodeValue is not registered by default. Use StringCodec.EncodeValue instead. -func (dve DefaultValueEncoders) StringEncodeValue(_ EncodeContext, vw 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()) -} - -// ObjectIDEncodeValue is the ValueEncoderFunc for ObjectID. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) ObjectIDEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// objectIDEncodeValue is the ValueEncoderFunc for ObjectID. +func objectIDEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tOID { return ValueEncoderError{Name: "ObjectIDEncodeValue", Types: []reflect.Type{tOID}, Received: val} } return vw.WriteObjectID(val.Interface().(ObjectID)) } -// Decimal128EncodeValue is the ValueEncoderFunc for Decimal128. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) Decimal128EncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// decimal128EncodeValue is the ValueEncoderFunc for Decimal128. +func decimal128EncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tDecimal { return ValueEncoderError{Name: "Decimal128EncodeValue", Types: []reflect.Type{tDecimal}, Received: val} } return vw.WriteDecimal128(val.Interface().(Decimal128)) } -// JSONNumberEncodeValue is the ValueEncoderFunc for json.Number. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) JSONNumberEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { +// jsonNumberEncodeValue is the ValueEncoderFunc for json.Number. +func jsonNumberEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tJSONNumber { return ValueEncoderError{Name: "JSONNumberEncodeValue", Types: []reflect.Type{tJSONNumber}, Received: val} } @@ -246,7 +172,7 @@ func (dve DefaultValueEncoders) JSONNumberEncodeValue(ec EncodeContext, vw Value // Attempt int first, then float64 if i64, err := jsnum.Int64(); err == nil { - return dve.IntEncodeValue(ec, vw, reflect.ValueOf(i64)) + return intEncodeValue(ec, vw, reflect.ValueOf(i64)) } f64, err := jsnum.Float64() @@ -254,14 +180,11 @@ func (dve DefaultValueEncoders) JSONNumberEncodeValue(ec EncodeContext, vw Value return err } - return dve.FloatEncodeValue(ec, vw, reflect.ValueOf(f64)) + return floatEncodeValue(ec, vw, reflect.ValueOf(f64)) } -// URLEncodeValue is the ValueEncoderFunc for url.URL. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) URLEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// urlEncodeValue is the ValueEncoderFunc for url.URL. +func urlEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tURL { return ValueEncoderError{Name: "URLEncodeValue", Types: []reflect.Type{tURL}, Received: val} } @@ -269,108 +192,8 @@ func (dve DefaultValueEncoders) URLEncodeValue(_ EncodeContext, vw ValueWriter, return vw.WriteString(u.String()) } -// TimeEncodeValue is the ValueEncoderFunc for time.TIme. -// -// Deprecated: TimeEncodeValue is not registered by default. Use TimeCodec.EncodeValue instead. -func (dve DefaultValueEncoders) TimeEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { - if !val.IsValid() || val.Type() != tTime { - return ValueEncoderError{Name: "TimeEncodeValue", Types: []reflect.Type{tTime}, Received: val} - } - tt := val.Interface().(time.Time) - dt := NewDateTimeFromTime(tt) - return vw.WriteDateTime(int64(dt)) -} - -// ByteSliceEncodeValue is the ValueEncoderFunc for []byte. -// -// Deprecated: ByteSliceEncodeValue is not registered by default. Use ByteSliceCodec.EncodeValue instead. -func (dve DefaultValueEncoders) ByteSliceEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { - if !val.IsValid() || val.Type() != tByteSlice { - return ValueEncoderError{Name: "ByteSliceEncodeValue", Types: []reflect.Type{tByteSlice}, Received: val} - } - if val.IsNil() { - return vw.WriteNull() - } - return vw.WriteBinary(val.Interface().([]byte)) -} - -// MapEncodeValue is the ValueEncoderFunc for map[string]* types. -// -// Deprecated: MapEncodeValue is not registered by default. Use MapCodec.EncodeValue instead. -func (dve DefaultValueEncoders) MapEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { - if !val.IsValid() || val.Kind() != reflect.Map || val.Type().Key().Kind() != reflect.String { - return ValueEncoderError{Name: "MapEncodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val} - } - - if val.IsNil() { - // If we have a nill map but we can't WriteNull, that means we're probably trying to encode - // to a TopLevel document. We can't currently tell if this is what actually happened, but if - // there's a deeper underlying problem, the error will also be returned from WriteDocument, - // so just continue. The operations on a map reflection value are valid, so we can call - // MapKeys within mapEncodeValue without a problem. - err := vw.WriteNull() - if err == nil { - return nil - } - } - - dw, err := vw.WriteDocument() - if err != nil { - return err - } - - return dve.mapEncodeValue(ec, dw, val, nil) -} - -// mapEncodeValue handles encoding of the values of a map. The collisionFn returns -// true if the provided key exists, this is mainly used for inline maps in the -// struct codec. -func (dve DefaultValueEncoders) mapEncodeValue(ec EncodeContext, dw DocumentWriter, val reflect.Value, collisionFn func(string) bool) error { - - elemType := val.Type().Elem() - encoder, err := ec.LookupEncoder(elemType) - if err != nil && elemType.Kind() != reflect.Interface { - return err - } - - keys := val.MapKeys() - for _, key := range keys { - if collisionFn != nil && collisionFn(key.String()) { - return fmt.Errorf("Key %s of inlined map conflicts with a struct field name", key) - } - - currEncoder, currVal, lookupErr := dve.lookupElementEncoder(ec, encoder, val.MapIndex(key)) - if lookupErr != nil && !errors.Is(lookupErr, errInvalidValue) { - return lookupErr - } - - vw, err := dw.WriteDocumentElement(key.String()) - if err != nil { - return err - } - - if errors.Is(lookupErr, errInvalidValue) { - err = vw.WriteNull() - if err != nil { - return err - } - continue - } - - err = currEncoder.EncodeValue(ec, vw, currVal) - if err != nil { - return err - } - } - - return dw.WriteDocumentEnd() -} - -// ArrayEncodeValue is the ValueEncoderFunc for array types. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) ArrayEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { +// arrayEncodeValue is the ValueEncoderFunc for array types. +func arrayEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Kind() != reflect.Array { return ValueEncoderError{Name: "ArrayEncodeValue", Kinds: []reflect.Kind{reflect.Array}, Received: val} } @@ -414,76 +237,7 @@ func (dve DefaultValueEncoders) ArrayEncodeValue(ec EncodeContext, vw ValueWrite } for idx := 0; idx < val.Len(); idx++ { - currEncoder, currVal, lookupErr := dve.lookupElementEncoder(ec, encoder, val.Index(idx)) - if lookupErr != nil && !errors.Is(lookupErr, errInvalidValue) { - return lookupErr - } - - vw, err := aw.WriteArrayElement() - if err != nil { - return err - } - - if errors.Is(lookupErr, errInvalidValue) { - err = vw.WriteNull() - if err != nil { - return err - } - continue - } - - err = currEncoder.EncodeValue(ec, vw, currVal) - if err != nil { - return err - } - } - return aw.WriteArrayEnd() -} - -// SliceEncodeValue is the ValueEncoderFunc for slice types. -// -// Deprecated: SliceEncodeValue is not registered by default. Use SliceCodec.EncodeValue instead. -func (dve DefaultValueEncoders) SliceEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { - if !val.IsValid() || val.Kind() != reflect.Slice { - return ValueEncoderError{Name: "SliceEncodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val} - } - - if val.IsNil() { - return vw.WriteNull() - } - - // If we have a []E we want to treat it as a document instead of as an array. - if val.Type().ConvertibleTo(tD) { - d := val.Convert(tD).Interface().(D) - - dw, err := vw.WriteDocument() - if err != nil { - return err - } - - for _, e := range d { - err = encodeElement(ec, dw, e) - if err != nil { - return err - } - } - - return dw.WriteDocumentEnd() - } - - aw, err := vw.WriteArray() - if err != nil { - return err - } - - elemType := val.Type().Elem() - encoder, err := ec.LookupEncoder(elemType) - if err != nil && elemType.Kind() != reflect.Interface { - return err - } - - for idx := 0; idx < val.Len(); idx++ { - currEncoder, currVal, lookupErr := dve.lookupElementEncoder(ec, encoder, val.Index(idx)) + currEncoder, currVal, lookupErr := lookupElementEncoder(ec, encoder, val.Index(idx)) if lookupErr != nil && !errors.Is(lookupErr, errInvalidValue) { return lookupErr } @@ -509,7 +263,7 @@ func (dve DefaultValueEncoders) SliceEncodeValue(ec EncodeContext, vw ValueWrite return aw.WriteArrayEnd() } -func (dve DefaultValueEncoders) lookupElementEncoder(ec EncodeContext, origEncoder ValueEncoder, currVal reflect.Value) (ValueEncoder, reflect.Value, error) { +func lookupElementEncoder(ec EncodeContext, origEncoder ValueEncoder, currVal reflect.Value) (ValueEncoder, reflect.Value, error) { if origEncoder != nil || (currVal.Kind() != reflect.Interface) { return origEncoder, currVal, nil } @@ -522,30 +276,8 @@ func (dve DefaultValueEncoders) lookupElementEncoder(ec EncodeContext, origEncod return currEncoder, currVal, err } -// EmptyInterfaceEncodeValue is the ValueEncoderFunc for interface{}. -// -// Deprecated: EmptyInterfaceEncodeValue is not registered by default. Use EmptyInterfaceCodec.EncodeValue instead. -func (dve DefaultValueEncoders) EmptyInterfaceEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { - if !val.IsValid() || val.Type() != tEmpty { - return ValueEncoderError{Name: "EmptyInterfaceEncodeValue", Types: []reflect.Type{tEmpty}, Received: val} - } - - if val.IsNil() { - return vw.WriteNull() - } - encoder, err := ec.LookupEncoder(val.Elem().Type()) - if err != nil { - return err - } - - return encoder.EncodeValue(ec, vw, val.Elem()) -} - -// ValueMarshalerEncodeValue is the ValueEncoderFunc for ValueMarshaler implementations. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) ValueMarshalerEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// valueMarshalerEncodeValue is the ValueEncoderFunc for ValueMarshaler implementations. +func valueMarshalerEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { // Either val or a pointer to val must implement ValueMarshaler switch { case !val.IsValid(): @@ -572,11 +304,8 @@ func (dve DefaultValueEncoders) ValueMarshalerEncodeValue(_ EncodeContext, vw Va return copyValueFromBytes(vw, t, data) } -// MarshalerEncodeValue is the ValueEncoderFunc for Marshaler implementations. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) MarshalerEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// marshalerEncodeValue is the ValueEncoderFunc for Marshaler implementations. +func marshalerEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { // Either val or a pointer to val must implement Marshaler switch { case !val.IsValid(): @@ -603,11 +332,8 @@ func (dve DefaultValueEncoders) MarshalerEncodeValue(_ EncodeContext, vw ValueWr return copyValueFromBytes(vw, TypeEmbeddedDocument, data) } -// ProxyEncodeValue is the ValueEncoderFunc for Proxy implementations. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) ProxyEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { +// proxyEncodeValue is the ValueEncoderFunc for Proxy implementations. +func proxyEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { // Either val or a pointer to val must implement Proxy switch { case !val.IsValid(): @@ -650,11 +376,8 @@ func (dve DefaultValueEncoders) ProxyEncodeValue(ec EncodeContext, vw ValueWrite return encoder.EncodeValue(ec, vw, vv) } -// JavaScriptEncodeValue is the ValueEncoderFunc for the JavaScript type. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) JavaScriptEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// javaScriptEncodeValue is the ValueEncoderFunc for the JavaScript type. +func javaScriptEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tJavaScript { return ValueEncoderError{Name: "JavaScriptEncodeValue", Types: []reflect.Type{tJavaScript}, Received: val} } @@ -662,11 +385,8 @@ func (DefaultValueEncoders) JavaScriptEncodeValue(_ EncodeContext, vw ValueWrite return vw.WriteJavascript(val.String()) } -// SymbolEncodeValue is the ValueEncoderFunc for the Symbol type. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) SymbolEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// symbolEncodeValue is the ValueEncoderFunc for the Symbol type. +func symbolEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tSymbol { return ValueEncoderError{Name: "SymbolEncodeValue", Types: []reflect.Type{tSymbol}, Received: val} } @@ -674,11 +394,8 @@ func (DefaultValueEncoders) SymbolEncodeValue(_ EncodeContext, vw ValueWriter, v return vw.WriteSymbol(val.String()) } -// BinaryEncodeValue is the ValueEncoderFunc for Binary. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) BinaryEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// binaryEncodeValue is the ValueEncoderFunc for Binary. +func binaryEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tBinary { return ValueEncoderError{Name: "BinaryEncodeValue", Types: []reflect.Type{tBinary}, Received: val} } @@ -687,11 +404,8 @@ func (DefaultValueEncoders) BinaryEncodeValue(_ EncodeContext, vw ValueWriter, v return vw.WriteBinaryWithSubtype(b.Data, b.Subtype) } -// UndefinedEncodeValue is the ValueEncoderFunc for Undefined. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) UndefinedEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// undefinedEncodeValue is the ValueEncoderFunc for Undefined. +func undefinedEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tUndefined { return ValueEncoderError{Name: "UndefinedEncodeValue", Types: []reflect.Type{tUndefined}, Received: val} } @@ -699,11 +413,8 @@ func (DefaultValueEncoders) UndefinedEncodeValue(_ EncodeContext, vw ValueWriter return vw.WriteUndefined() } -// DateTimeEncodeValue is the ValueEncoderFunc for DateTime. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) DateTimeEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// dateTimeEncodeValue is the ValueEncoderFunc for DateTime. +func dateTimeEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tDateTime { return ValueEncoderError{Name: "DateTimeEncodeValue", Types: []reflect.Type{tDateTime}, Received: val} } @@ -711,11 +422,8 @@ func (DefaultValueEncoders) DateTimeEncodeValue(_ EncodeContext, vw ValueWriter, return vw.WriteDateTime(val.Int()) } -// NullEncodeValue is the ValueEncoderFunc for Null. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) NullEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// nullEncodeValue is the ValueEncoderFunc for Null. +func nullEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tNull { return ValueEncoderError{Name: "NullEncodeValue", Types: []reflect.Type{tNull}, Received: val} } @@ -723,11 +431,8 @@ func (DefaultValueEncoders) NullEncodeValue(_ EncodeContext, vw ValueWriter, val return vw.WriteNull() } -// RegexEncodeValue is the ValueEncoderFunc for Regex. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) RegexEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// regexEncodeValue is the ValueEncoderFunc for Regex. +func regexEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tRegex { return ValueEncoderError{Name: "RegexEncodeValue", Types: []reflect.Type{tRegex}, Received: val} } @@ -737,11 +442,8 @@ func (DefaultValueEncoders) RegexEncodeValue(_ EncodeContext, vw ValueWriter, va return vw.WriteRegex(regex.Pattern, regex.Options) } -// DBPointerEncodeValue is the ValueEncoderFunc for DBPointer. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) DBPointerEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// dbPointerEncodeValue is the ValueEncoderFunc for DBPointer. +func dbPointerEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tDBPointer { return ValueEncoderError{Name: "DBPointerEncodeValue", Types: []reflect.Type{tDBPointer}, Received: val} } @@ -751,11 +453,8 @@ func (DefaultValueEncoders) DBPointerEncodeValue(_ EncodeContext, vw ValueWriter return vw.WriteDBPointer(dbp.DB, dbp.Pointer) } -// TimestampEncodeValue is the ValueEncoderFunc for Timestamp. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) TimestampEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// timestampEncodeValue is the ValueEncoderFunc for Timestamp. +func timestampEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tTimestamp { return ValueEncoderError{Name: "TimestampEncodeValue", Types: []reflect.Type{tTimestamp}, Received: val} } @@ -765,11 +464,8 @@ func (DefaultValueEncoders) TimestampEncodeValue(_ EncodeContext, vw ValueWriter return vw.WriteTimestamp(ts.T, ts.I) } -// MinKeyEncodeValue is the ValueEncoderFunc for MinKey. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) MinKeyEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// minKeyEncodeValue is the ValueEncoderFunc for MinKey. +func minKeyEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tMinKey { return ValueEncoderError{Name: "MinKeyEncodeValue", Types: []reflect.Type{tMinKey}, Received: val} } @@ -777,11 +473,8 @@ func (DefaultValueEncoders) MinKeyEncodeValue(_ EncodeContext, vw ValueWriter, v return vw.WriteMinKey() } -// MaxKeyEncodeValue is the ValueEncoderFunc for MaxKey. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) MaxKeyEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// maxKeyEncodeValue is the ValueEncoderFunc for MaxKey. +func maxKeyEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tMaxKey { return ValueEncoderError{Name: "MaxKeyEncodeValue", Types: []reflect.Type{tMaxKey}, Received: val} } @@ -789,11 +482,8 @@ func (DefaultValueEncoders) MaxKeyEncodeValue(_ EncodeContext, vw ValueWriter, v return vw.WriteMaxKey() } -// CoreDocumentEncodeValue is the ValueEncoderFunc for bsoncore.Document. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) CoreDocumentEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// coreDocumentEncodeValue is the ValueEncoderFunc for bsoncore.Document. +func coreDocumentEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tCoreDocument { return ValueEncoderError{Name: "CoreDocumentEncodeValue", Types: []reflect.Type{tCoreDocument}, Received: val} } @@ -803,11 +493,8 @@ func (DefaultValueEncoders) CoreDocumentEncodeValue(_ EncodeContext, vw ValueWri return copyDocumentFromBytes(vw, cdoc) } -// CodeWithScopeEncodeValue is the ValueEncoderFunc for CodeWithScope. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) CodeWithScopeEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { +// codeWithScopeEncodeValue is the ValueEncoderFunc for CodeWithScope. +func codeWithScopeEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tCodeWithScope { return ValueEncoderError{Name: "CodeWithScopeEncodeValue", Types: []reflect.Type{tCodeWithScope}, Received: val} } diff --git a/bson/default_value_encoders_test.go b/bson/default_value_encoders_test.go index 481c6cb1a1..1ebd57f891 100644 --- a/bson/default_value_encoders_test.go +++ b/bson/default_value_encoders_test.go @@ -35,7 +35,6 @@ func (ms myStruct) Foo() int { } func TestDefaultValueEncoders(t *testing.T) { - var dve DefaultValueEncoders var wrong = func(string, string) string { return "wrong" } type mybool bool @@ -80,7 +79,7 @@ func TestDefaultValueEncoders(t *testing.T) { }{ { "BooleanEncodeValue", - ValueEncoderFunc(dve.BooleanEncodeValue), + ValueEncoderFunc(booleanEncodeValue), []subtest{ { "wrong type", @@ -96,7 +95,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "IntEncodeValue", - ValueEncoderFunc(dve.IntEncodeValue), + ValueEncoderFunc(intEncodeValue), []subtest{ { "wrong type", @@ -177,7 +176,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "FloatEncodeValue", - ValueEncoderFunc(dve.FloatEncodeValue), + ValueEncoderFunc(floatEncodeValue), []subtest{ { "wrong type", @@ -235,7 +234,7 @@ func TestDefaultValueEncoders(t *testing.T) { { "Lookup Error", map[string]int{"foo": 1}, - &EncodeContext{Registry: newTestRegistryBuilder().Build()}, + &EncodeContext{Registry: newTestRegistry()}, &valueReaderWriter{}, writeDocument, fmt.Errorf("no encoder found for int"), @@ -259,7 +258,7 @@ func TestDefaultValueEncoders(t *testing.T) { { "empty map/success", map[string]interface{}{}, - &EncodeContext{Registry: newTestRegistryBuilder().Build()}, + &EncodeContext{Registry: newTestRegistry()}, &valueReaderWriter{}, writeDocumentEnd, nil, @@ -294,7 +293,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "ArrayEncodeValue", - ValueEncoderFunc(dve.ArrayEncodeValue), + ValueEncoderFunc(arrayEncodeValue), []subtest{ { "wrong kind", @@ -315,7 +314,7 @@ func TestDefaultValueEncoders(t *testing.T) { { "Lookup Error", [1]int{1}, - &EncodeContext{Registry: newTestRegistryBuilder().Build()}, + &EncodeContext{Registry: newTestRegistry()}, &valueReaderWriter{}, writeArray, fmt.Errorf("no encoder found for int"), @@ -393,7 +392,7 @@ func TestDefaultValueEncoders(t *testing.T) { { "Lookup Error", []int{1}, - &EncodeContext{Registry: newTestRegistryBuilder().Build()}, + &EncodeContext{Registry: newTestRegistry()}, &valueReaderWriter{}, writeArray, fmt.Errorf("no encoder found for int"), @@ -433,7 +432,7 @@ func TestDefaultValueEncoders(t *testing.T) { { "empty slice/success", []interface{}{}, - &EncodeContext{Registry: newTestRegistryBuilder().Build()}, + &EncodeContext{Registry: newTestRegistry()}, &valueReaderWriter{}, writeArrayEnd, nil, @@ -458,7 +457,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "ObjectIDEncodeValue", - ValueEncoderFunc(dve.ObjectIDEncodeValue), + ValueEncoderFunc(objectIDEncodeValue), []subtest{ { "wrong type", @@ -477,7 +476,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "Decimal128EncodeValue", - ValueEncoderFunc(dve.Decimal128EncodeValue), + ValueEncoderFunc(decimal128EncodeValue), []subtest{ { "wrong type", @@ -492,7 +491,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "JSONNumberEncodeValue", - ValueEncoderFunc(dve.JSONNumberEncodeValue), + ValueEncoderFunc(jsonNumberEncodeValue), []subtest{ { "wrong type", @@ -521,7 +520,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "URLEncodeValue", - ValueEncoderFunc(dve.URLEncodeValue), + ValueEncoderFunc(urlEncodeValue), []subtest{ { "wrong type", @@ -566,7 +565,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "ValueMarshalerEncodeValue", - ValueEncoderFunc(dve.ValueMarshalerEncodeValue), + ValueEncoderFunc(valueMarshalerEncodeValue), []subtest{ { "wrong type", @@ -644,7 +643,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "MarshalerEncodeValue", - ValueEncoderFunc(dve.MarshalerEncodeValue), + ValueEncoderFunc(marshalerEncodeValue), []subtest{ { "wrong type", @@ -706,7 +705,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "ProxyEncodeValue", - ValueEncoderFunc(dve.ProxyEncodeValue), + ValueEncoderFunc(proxyEncodeValue), []subtest{ { "wrong type", @@ -844,7 +843,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "JavaScriptEncodeValue", - ValueEncoderFunc(dve.JavaScriptEncodeValue), + ValueEncoderFunc(javaScriptEncodeValue), []subtest{ { "wrong type", @@ -859,7 +858,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "SymbolEncodeValue", - ValueEncoderFunc(dve.SymbolEncodeValue), + ValueEncoderFunc(symbolEncodeValue), []subtest{ { "wrong type", @@ -874,7 +873,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "BinaryEncodeValue", - ValueEncoderFunc(dve.BinaryEncodeValue), + ValueEncoderFunc(binaryEncodeValue), []subtest{ { "wrong type", @@ -889,7 +888,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "UndefinedEncodeValue", - ValueEncoderFunc(dve.UndefinedEncodeValue), + ValueEncoderFunc(undefinedEncodeValue), []subtest{ { "wrong type", @@ -904,7 +903,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "DateTimeEncodeValue", - ValueEncoderFunc(dve.DateTimeEncodeValue), + ValueEncoderFunc(dateTimeEncodeValue), []subtest{ { "wrong type", @@ -919,7 +918,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "NullEncodeValue", - ValueEncoderFunc(dve.NullEncodeValue), + ValueEncoderFunc(nullEncodeValue), []subtest{ { "wrong type", @@ -934,7 +933,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "RegexEncodeValue", - ValueEncoderFunc(dve.RegexEncodeValue), + ValueEncoderFunc(regexEncodeValue), []subtest{ { "wrong type", @@ -949,7 +948,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "DBPointerEncodeValue", - ValueEncoderFunc(dve.DBPointerEncodeValue), + ValueEncoderFunc(dbPointerEncodeValue), []subtest{ { "wrong type", @@ -971,7 +970,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "TimestampEncodeValue", - ValueEncoderFunc(dve.TimestampEncodeValue), + ValueEncoderFunc(timestampEncodeValue), []subtest{ { "wrong type", @@ -986,7 +985,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "MinKeyEncodeValue", - ValueEncoderFunc(dve.MinKeyEncodeValue), + ValueEncoderFunc(minKeyEncodeValue), []subtest{ { "wrong type", @@ -1001,7 +1000,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "MaxKeyEncodeValue", - ValueEncoderFunc(dve.MaxKeyEncodeValue), + ValueEncoderFunc(maxKeyEncodeValue), []subtest{ { "wrong type", @@ -1016,7 +1015,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "CoreDocumentEncodeValue", - ValueEncoderFunc(dve.CoreDocumentEncodeValue), + ValueEncoderFunc(coreDocumentEncodeValue), []subtest{ { "wrong type", @@ -1096,7 +1095,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "CodeWithScopeEncodeValue", - ValueEncoderFunc(dve.CodeWithScopeEncodeValue), + ValueEncoderFunc(codeWithScopeEncodeValue), []subtest{ { "wrong type", @@ -1828,27 +1827,6 @@ func TestDefaultValueEncoders(t *testing.T) { }) } }) - - t.Run("EmptyInterfaceEncodeValue/nil", func(t *testing.T) { - val := reflect.New(tEmpty).Elem() - llvrw := new(valueReaderWriter) - err := dve.EmptyInterfaceEncodeValue(EncodeContext{Registry: newTestRegistryBuilder().Build()}, llvrw, val) - noerr(t, err) - if llvrw.invoked != writeNull { - t.Errorf("Incorrect method called. got %v; want %v", llvrw.invoked, writeNull) - } - }) - - t.Run("EmptyInterfaceEncodeValue/LookupEncoder error", func(t *testing.T) { - val := reflect.New(tEmpty).Elem() - val.Set(reflect.ValueOf(int64(1234567890))) - llvrw := new(valueReaderWriter) - got := dve.EmptyInterfaceEncodeValue(EncodeContext{Registry: newTestRegistryBuilder().Build()}, llvrw, val) - want := ErrNoEncoder{Type: tInt64} - if !assert.CompareErrors(got, want) { - t.Errorf("Did not receive expected error. got %v; want %v", got, want) - } - }) } type testValueMarshalPtr struct { diff --git a/bson/map_codec.go b/bson/map_codec.go index 9592957db4..f1294ae99d 100644 --- a/bson/map_codec.go +++ b/bson/map_codec.go @@ -126,7 +126,7 @@ func (mc *MapCodec) mapEncodeValue(ec EncodeContext, dw DocumentWriter, val refl return fmt.Errorf("Key %s of inlined map conflicts with a struct field name", key) } - currEncoder, currVal, lookupErr := defaultValueEncoders.lookupElementEncoder(ec, encoder, val.MapIndex(key)) + currEncoder, currVal, lookupErr := lookupElementEncoder(ec, encoder, val.MapIndex(key)) if lookupErr != nil && !errors.Is(lookupErr, errInvalidValue) { return lookupErr } diff --git a/bson/mgocompat/bson_test.go b/bson/mgocompat/bson_test.go index 6651509983..a74a5a892d 100644 --- a/bson/mgocompat/bson_test.go +++ b/bson/mgocompat/bson_test.go @@ -1442,9 +1442,6 @@ var twoWayCrossItems = []crossTypeItem{ {&struct{ S []byte }{[]byte("def")}, &struct{ S bson.Symbol }{"def"}}, {&struct{ S string }{"ghi"}, &struct{ S bson.Symbol }{"ghi"}}, - {&struct{ S string }{"0123456789ab"}, - &struct{ S bson.ObjectID }{bson.ObjectID{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62}}}, - // map <=> struct {&struct { A struct { diff --git a/bson/mgocompat/registry.go b/bson/mgocompat/registry.go index 7024ab9fdc..0d61a029ec 100644 --- a/bson/mgocompat/registry.go +++ b/bson/mgocompat/registry.go @@ -31,19 +31,14 @@ var ( // Registry is the mgo compatible bson.Registry. It contains the default and // primitive codecs with mgo compatible options. -var Registry = NewRegistryBuilder().Build() +var Registry = newRegistry() // RespectNilValuesRegistry is the bson.Registry compatible with mgo withSetRespectNilValues set to true. -var RespectNilValuesRegistry = NewRespectNilValuesRegistryBuilder().Build() +var RespectNilValuesRegistry = newRespectNilValuesRegistry() -// NewRegistryBuilder creates a new bson.RegistryBuilder configured with the default encoders and -// decoders from the bson.DefaultValueEncoders and bson.DefaultValueDecoders types and the -// PrimitiveCodecs type in this package. -func NewRegistryBuilder() *bson.RegistryBuilder { - rb := bson.NewRegistryBuilder() - bson.DefaultValueEncoders{}.RegisterDefaultEncoders(rb) - bson.DefaultValueDecoders{}.RegisterDefaultDecoders(rb) - bson.PrimitiveCodecs{}.RegisterPrimitiveCodecs(rb) +// newRegistry creates a new bson.Registry configured with the default encoders and decoders. +func newRegistry() *bson.Registry { + reg := bson.NewRegistry() structcodec, _ := bson.NewStructCodec(bson.DefaultStructTagParser, bsonoptions.StructCodec(). @@ -61,34 +56,34 @@ func NewRegistryBuilder() *bson.RegistryBuilder { SetEncodeKeysWithStringer(true)) uintcodec := bson.NewUIntCodec(bsonoptions.UIntCodec().SetEncodeToMinSize(true)) - rb.RegisterTypeDecoder(tEmpty, emptyInterCodec). - RegisterDefaultDecoder(reflect.String, bson.NewStringCodec(bsonoptions.StringCodec().SetDecodeObjectIDAsHex(false))). - RegisterDefaultDecoder(reflect.Struct, structcodec). - RegisterDefaultDecoder(reflect.Map, mapCodec). - RegisterTypeEncoder(tByteSlice, bson.NewByteSliceCodec(bsonoptions.ByteSliceCodec().SetEncodeNilAsEmpty(true))). - RegisterDefaultEncoder(reflect.Struct, structcodec). - RegisterDefaultEncoder(reflect.Slice, bson.NewSliceCodec(bsonoptions.SliceCodec().SetEncodeNilAsEmpty(true))). - RegisterDefaultEncoder(reflect.Map, mapCodec). - RegisterDefaultEncoder(reflect.Uint, uintcodec). - RegisterDefaultEncoder(reflect.Uint8, uintcodec). - RegisterDefaultEncoder(reflect.Uint16, uintcodec). - RegisterDefaultEncoder(reflect.Uint32, uintcodec). - RegisterDefaultEncoder(reflect.Uint64, uintcodec). - RegisterTypeMapEntry(bson.TypeInt32, tInt). - RegisterTypeMapEntry(bson.TypeDateTime, tTime). - RegisterTypeMapEntry(bson.TypeArray, tInterfaceSlice). - RegisterTypeMapEntry(bson.Type(0), tM). - RegisterTypeMapEntry(bson.TypeEmbeddedDocument, tM). - RegisterHookEncoder(tGetter, bson.ValueEncoderFunc(GetterEncodeValue)). - RegisterHookDecoder(tSetter, bson.ValueDecoderFunc(SetterDecodeValue)) + reg.RegisterTypeDecoder(tEmpty, emptyInterCodec) + reg.RegisterKindDecoder(reflect.String, bson.NewStringCodec(bsonoptions.StringCodec().SetDecodeObjectIDAsHex(false))) + reg.RegisterKindDecoder(reflect.Struct, structcodec) + reg.RegisterKindDecoder(reflect.Map, mapCodec) + reg.RegisterTypeEncoder(tByteSlice, bson.NewByteSliceCodec(bsonoptions.ByteSliceCodec().SetEncodeNilAsEmpty(true))) + reg.RegisterKindEncoder(reflect.Struct, structcodec) + reg.RegisterKindEncoder(reflect.Slice, bson.NewSliceCodec(bsonoptions.SliceCodec().SetEncodeNilAsEmpty(true))) + reg.RegisterKindEncoder(reflect.Map, mapCodec) + reg.RegisterKindEncoder(reflect.Uint, uintcodec) + reg.RegisterKindEncoder(reflect.Uint8, uintcodec) + reg.RegisterKindEncoder(reflect.Uint16, uintcodec) + reg.RegisterKindEncoder(reflect.Uint32, uintcodec) + reg.RegisterKindEncoder(reflect.Uint64, uintcodec) + reg.RegisterTypeMapEntry(bson.TypeInt32, tInt) + reg.RegisterTypeMapEntry(bson.TypeDateTime, tTime) + reg.RegisterTypeMapEntry(bson.TypeArray, tInterfaceSlice) + reg.RegisterTypeMapEntry(bson.Type(0), tM) + reg.RegisterTypeMapEntry(bson.TypeEmbeddedDocument, tM) + reg.RegisterInterfaceEncoder(tGetter, bson.ValueEncoderFunc(GetterEncodeValue)) + reg.RegisterInterfaceDecoder(tSetter, bson.ValueDecoderFunc(SetterDecodeValue)) - return rb + return reg } -// NewRespectNilValuesRegistryBuilder creates a new bson.RegistryBuilder configured to behave like mgo/bson +// newRespectNilValuesRegistry creates a new bson.Registry configured to behave like mgo/bson // with RespectNilValues set to true. -func NewRespectNilValuesRegistryBuilder() *bson.RegistryBuilder { - rb := NewRegistryBuilder() +func newRespectNilValuesRegistry() *bson.Registry { + reg := newRegistry() structcodec, _ := bson.NewStructCodec(bson.DefaultStructTagParser, bsonoptions.StructCodec(). @@ -101,12 +96,12 @@ func NewRespectNilValuesRegistryBuilder() *bson.RegistryBuilder { SetDecodeZerosMap(true). SetEncodeNilAsEmpty(false)) - rb.RegisterDefaultDecoder(reflect.Struct, structcodec). - RegisterDefaultDecoder(reflect.Map, mapCodec). - RegisterTypeEncoder(tByteSlice, bson.NewByteSliceCodec(bsonoptions.ByteSliceCodec().SetEncodeNilAsEmpty(false))). - RegisterDefaultEncoder(reflect.Struct, structcodec). - RegisterDefaultEncoder(reflect.Slice, bson.NewSliceCodec(bsonoptions.SliceCodec().SetEncodeNilAsEmpty(false))). - RegisterDefaultEncoder(reflect.Map, mapCodec) + reg.RegisterKindDecoder(reflect.Struct, structcodec) + reg.RegisterKindDecoder(reflect.Map, mapCodec) + reg.RegisterTypeEncoder(tByteSlice, bson.NewByteSliceCodec(bsonoptions.ByteSliceCodec().SetEncodeNilAsEmpty(false))) + reg.RegisterKindEncoder(reflect.Struct, structcodec) + reg.RegisterKindEncoder(reflect.Slice, bson.NewSliceCodec(bsonoptions.SliceCodec().SetEncodeNilAsEmpty(false))) + reg.RegisterKindEncoder(reflect.Map, mapCodec) - return rb + return reg } diff --git a/bson/primitive_codecs.go b/bson/primitive_codecs.go index 262645ce4c..df6e059c4a 100644 --- a/bson/primitive_codecs.go +++ b/bson/primitive_codecs.go @@ -15,38 +15,23 @@ import ( var tRawValue = reflect.TypeOf(RawValue{}) var tRaw = reflect.TypeOf(Raw(nil)) -// PrimitiveCodecs is a namespace for all of the default Codecs for the primitive types -// defined in this package. -// -// Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders -// registered. -type PrimitiveCodecs struct{} - -// RegisterPrimitiveCodecs will register the encode and decode methods attached to PrimitiveCodecs -// with the provided RegistryBuilder. if rb is nil, a new empty RegistryBuilder will be created. -// -// Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders -// registered. -func (pc PrimitiveCodecs) RegisterPrimitiveCodecs(rb *RegistryBuilder) { - if rb == nil { +// registerPrimitiveCodecs will register the encode and decode methods with the provided Registry. +func registerPrimitiveCodecs(reg *Registry) { + if reg == nil { panic(errors.New("argument to RegisterPrimitiveCodecs must not be nil")) } - rb. - RegisterTypeEncoder(tRawValue, ValueEncoderFunc(pc.RawValueEncodeValue)). - RegisterTypeEncoder(tRaw, ValueEncoderFunc(pc.RawEncodeValue)). - RegisterTypeDecoder(tRawValue, ValueDecoderFunc(pc.RawValueDecodeValue)). - RegisterTypeDecoder(tRaw, ValueDecoderFunc(pc.RawDecodeValue)) + reg.RegisterTypeEncoder(tRawValue, ValueEncoderFunc(rawValueEncodeValue)) + reg.RegisterTypeEncoder(tRaw, ValueEncoderFunc(rawEncodeValue)) + reg.RegisterTypeDecoder(tRawValue, ValueDecoderFunc(rawValueDecodeValue)) + reg.RegisterTypeDecoder(tRaw, ValueDecoderFunc(rawDecodeValue)) } -// RawValueEncodeValue is the ValueEncoderFunc for RawValue. +// rawValueEncodeValue is the ValueEncoderFunc for RawValue. // // If the RawValue's Type is "invalid" and the RawValue's Value is not empty or // nil, then this method will return an error. -// -// Deprecated: Use bson.NewRegistry to get a registry with all primitive -// encoders and decoders registered. -func (PrimitiveCodecs) RawValueEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +func rawValueEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tRawValue { return ValueEncoderError{ Name: "RawValueEncodeValue", @@ -64,11 +49,8 @@ func (PrimitiveCodecs) RawValueEncodeValue(_ EncodeContext, vw ValueWriter, val return copyValueFromBytes(vw, rawvalue.Type, rawvalue.Value) } -// RawValueDecodeValue is the ValueDecoderFunc for RawValue. -// -// Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders -// registered. -func (PrimitiveCodecs) RawValueDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { +// rawValueDecodeValue is the ValueDecoderFunc for RawValue. +func rawValueDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tRawValue { return ValueDecoderError{Name: "RawValueDecodeValue", Types: []reflect.Type{tRawValue}, Received: val} } @@ -82,11 +64,8 @@ func (PrimitiveCodecs) RawValueDecodeValue(_ DecodeContext, vr ValueReader, val return nil } -// RawEncodeValue is the ValueEncoderFunc for Reader. -// -// Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders -// registered. -func (PrimitiveCodecs) RawEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { +// rawEncodeValue is the ValueEncoderFunc for Reader. +func rawEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tRaw { return ValueEncoderError{Name: "RawEncodeValue", Types: []reflect.Type{tRaw}, Received: val} } @@ -96,11 +75,8 @@ func (PrimitiveCodecs) RawEncodeValue(_ EncodeContext, vw ValueWriter, val refle return copyDocumentFromBytes(vw, rdr) } -// RawDecodeValue is the ValueDecoderFunc for Reader. -// -// Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders -// registered. -func (PrimitiveCodecs) RawDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { +// rawDecodeValue is the ValueDecoderFunc for Reader. +func rawDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tRaw { return ValueDecoderError{Name: "RawDecodeValue", Types: []reflect.Type{tRaw}, Received: val} } diff --git a/bson/primitive_codecs_test.go b/bson/primitive_codecs_test.go index be3aeab978..6b0c4c1e05 100644 --- a/bson/primitive_codecs_test.go +++ b/bson/primitive_codecs_test.go @@ -32,8 +32,6 @@ func bytesFromDoc(doc interface{}) []byte { func TestPrimitiveValueEncoders(t *testing.T) { t.Parallel() - var pc PrimitiveCodecs - var wrong = func(string, string) string { return "wrong" } type subtest struct { @@ -52,7 +50,7 @@ func TestPrimitiveValueEncoders(t *testing.T) { }{ { "RawValueEncodeValue", - ValueEncoderFunc(pc.RawValueEncodeValue), + ValueEncoderFunc(rawValueEncodeValue), []subtest{ { "wrong type", @@ -100,7 +98,7 @@ func TestPrimitiveValueEncoders(t *testing.T) { }, { "RawEncodeValue", - ValueEncoderFunc(pc.RawEncodeValue), + ValueEncoderFunc(rawEncodeValue), []subtest{ { "wrong type", @@ -478,8 +476,6 @@ func TestPrimitiveValueEncoders(t *testing.T) { } func TestPrimitiveValueDecoders(t *testing.T) { - var pc PrimitiveCodecs - var wrong = func(string, string) string { return "wrong" } const cansetreflectiontest = "cansetreflectiontest" @@ -500,7 +496,7 @@ func TestPrimitiveValueDecoders(t *testing.T) { }{ { "RawValueDecodeValue", - ValueDecoderFunc(pc.RawValueDecodeValue), + ValueDecoderFunc(rawValueDecodeValue), []subtest{ { "wrong type", @@ -544,7 +540,7 @@ func TestPrimitiveValueDecoders(t *testing.T) { }, { "RawDecodeValue", - ValueDecoderFunc(pc.RawDecodeValue), + ValueDecoderFunc(rawDecodeValue), []subtest{ { "wrong type", diff --git a/bson/raw_value_test.go b/bson/raw_value_test.go index f02fe8f326..67444faa61 100644 --- a/bson/raw_value_test.go +++ b/bson/raw_value_test.go @@ -25,7 +25,7 @@ func TestRawValue(t *testing.T) { t.Run("Uses registry attached to value", func(t *testing.T) { t.Parallel() - reg := newTestRegistryBuilder().Build() + reg := newTestRegistry() val := RawValue{Type: TypeString, Value: bsoncore.AppendString(nil, "foobar"), r: reg} var s string want := ErrNoDecoder{Type: reflect.TypeOf(s)} @@ -63,7 +63,7 @@ func TestRawValue(t *testing.T) { t.Run("Returns lookup error", func(t *testing.T) { t.Parallel() - reg := newTestRegistryBuilder().Build() + reg := newTestRegistry() var val RawValue var s string want := ErrNoDecoder{Type: reflect.TypeOf(s)} @@ -114,7 +114,7 @@ func TestRawValue(t *testing.T) { t.Run("Returns lookup error", func(t *testing.T) { t.Parallel() - dc := DecodeContext{Registry: newTestRegistryBuilder().Build()} + dc := DecodeContext{Registry: newTestRegistry()} var val RawValue var s string want := ErrNoDecoder{Type: reflect.TypeOf(s)} diff --git a/bson/registry.go b/bson/registry.go index 74b99e93ab..d20424b340 100644 --- a/bson/registry.go +++ b/bson/registry.go @@ -22,11 +22,6 @@ var DefaultRegistry = NewRegistry() // Deprecated: ErrNilType will not be supported in Go Driver 2.0. var ErrNilType = errors.New("cannot perform a decoder lookup on ") -// ErrNotPointer is returned when a non-pointer type is provided to LookupDecoder. -// -// Deprecated: ErrNotPointer will not be supported in Go Driver 2.0. -var ErrNotPointer = errors.New("non-pointer provided to LookupDecoder") - // ErrNoEncoder is returned when there wasn't an encoder available for a type. // // Deprecated: ErrNoEncoder will not be supported in Go Driver 2.0. @@ -63,187 +58,6 @@ func (entme ErrNoTypeMapEntry) Error() string { return "no type map entry found for " + entme.Type.String() } -// ErrNotInterface is returned when the provided type is not an interface. -// -// Deprecated: ErrNotInterface will not be supported in Go Driver 2.0. -var ErrNotInterface = errors.New("The provided type is not an interface") - -// A RegistryBuilder is used to build a Registry. This type is not goroutine -// safe. -// -// Deprecated: Use Registry instead. -type RegistryBuilder struct { - registry *Registry -} - -// NewRegistryBuilder creates a new empty RegistryBuilder. -// -// Deprecated: Use NewRegistry instead. -func NewRegistryBuilder() *RegistryBuilder { - rb := &RegistryBuilder{ - registry: &Registry{ - typeEncoders: new(typeEncoderCache), - typeDecoders: new(typeDecoderCache), - kindEncoders: new(kindEncoderCache), - kindDecoders: new(kindDecoderCache), - }, - } - DefaultValueEncoders{}.RegisterDefaultEncoders(rb) - DefaultValueDecoders{}.RegisterDefaultDecoders(rb) - PrimitiveCodecs{}.RegisterPrimitiveCodecs(rb) - return rb -} - -// RegisterCodec will register the provided ValueCodec for the provided type. -// -// Deprecated: Use Registry.RegisterTypeEncoder and Registry.RegisterTypeDecoder instead. -func (rb *RegistryBuilder) RegisterCodec(t reflect.Type, codec ValueCodec) *RegistryBuilder { - rb.RegisterTypeEncoder(t, codec) - rb.RegisterTypeDecoder(t, codec) - return rb -} - -// 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 marshaling a type that is that interface. It -// will not be called when marshaling a non-interface type that implements the interface. -// -// Deprecated: Use Registry.RegisterTypeEncoder instead. -func (rb *RegistryBuilder) RegisterTypeEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder { - rb.registry.RegisterTypeEncoder(t, enc) - return rb -} - -// RegisterHookEncoder will register an encoder for the provided interface type t. This encoder will be called when -// marshaling 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. -// -// Deprecated: Use Registry.RegisterInterfaceEncoder instead. -func (rb *RegistryBuilder) RegisterHookEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder { - rb.registry.RegisterInterfaceEncoder(t, enc) - return rb -} - -// 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 unmarshaling into a type that is that interface. -// It will not be called when unmarshaling into a non-interface type that implements the interface. -// -// Deprecated: Use Registry.RegisterTypeDecoder instead. -func (rb *RegistryBuilder) RegisterTypeDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder { - rb.registry.RegisterTypeDecoder(t, dec) - return rb -} - -// RegisterHookDecoder will register an decoder for the provided interface type t. This decoder will be called when -// unmarshaling 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. -// -// Deprecated: Use Registry.RegisterInterfaceDecoder instead. -func (rb *RegistryBuilder) RegisterHookDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder { - rb.registry.RegisterInterfaceDecoder(t, dec) - return rb -} - -// RegisterEncoder registers the provided type and encoder pair. -// -// Deprecated: Use Registry.RegisterTypeEncoder or Registry.RegisterInterfaceEncoder instead. -func (rb *RegistryBuilder) RegisterEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder { - if t == tEmpty { - rb.registry.RegisterTypeEncoder(t, enc) - return rb - } - switch t.Kind() { - case reflect.Interface: - rb.registry.RegisterInterfaceEncoder(t, enc) - default: - rb.registry.RegisterTypeEncoder(t, enc) - } - return rb -} - -// RegisterDecoder registers the provided type and decoder pair. -// -// Deprecated: Use Registry.RegisterTypeDecoder or Registry.RegisterInterfaceDecoder instead. -func (rb *RegistryBuilder) RegisterDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder { - if t == nil { - rb.registry.RegisterTypeDecoder(t, dec) - return rb - } - if t == tEmpty { - rb.registry.RegisterTypeDecoder(t, dec) - return rb - } - switch t.Kind() { - case reflect.Interface: - rb.registry.RegisterInterfaceDecoder(t, dec) - default: - rb.registry.RegisterTypeDecoder(t, dec) - } - return rb -} - -// RegisterDefaultEncoder will register the provided ValueEncoder to the provided -// kind. -// -// Deprecated: Use Registry.RegisterKindEncoder instead. -func (rb *RegistryBuilder) RegisterDefaultEncoder(kind reflect.Kind, enc ValueEncoder) *RegistryBuilder { - rb.registry.RegisterKindEncoder(kind, enc) - return rb -} - -// RegisterDefaultDecoder will register the provided ValueDecoder to the -// provided kind. -// -// Deprecated: Use Registry.RegisterKindDecoder instead. -func (rb *RegistryBuilder) RegisterDefaultDecoder(kind reflect.Kind, dec ValueDecoder) *RegistryBuilder { - rb.registry.RegisterKindDecoder(kind, dec) - return rb -} - -// 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 TypeEmbeddedDocument should be registered. For example, to force BSON documents -// to decode to bson.Raw, use the following code: -// -// rb.RegisterTypeMapEntry(TypeEmbeddedDocument, reflect.TypeOf(bson.Raw{})) -// -// Deprecated: Use Registry.RegisterTypeMapEntry instead. -func (rb *RegistryBuilder) RegisterTypeMapEntry(bt Type, rt reflect.Type) *RegistryBuilder { - rb.registry.RegisterTypeMapEntry(bt, rt) - return rb -} - -// Build creates a Registry from the current state of this RegistryBuilder. -// -// Deprecated: Use NewRegistry instead. -func (rb *RegistryBuilder) Build() *Registry { - r := &Registry{ - interfaceEncoders: append([]interfaceValueEncoder(nil), rb.registry.interfaceEncoders...), - interfaceDecoders: append([]interfaceValueDecoder(nil), rb.registry.interfaceDecoders...), - typeEncoders: rb.registry.typeEncoders.Clone(), - typeDecoders: rb.registry.typeDecoders.Clone(), - kindEncoders: rb.registry.kindEncoders.Clone(), - kindDecoders: rb.registry.kindDecoders.Clone(), - } - rb.registry.typeMap.Range(func(k, v interface{}) bool { - if k != nil && v != nil { - r.typeMap.Store(k, v) - } - return true - }) - return r -} - // A Registry is a 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 // have four main types of codecs: @@ -289,7 +103,16 @@ type Registry struct { // NewRegistry creates a new empty Registry. func NewRegistry() *Registry { - return NewRegistryBuilder().Build() + reg := &Registry{ + typeEncoders: new(typeEncoderCache), + typeDecoders: new(typeDecoderCache), + kindEncoders: new(kindEncoderCache), + kindDecoders: new(kindDecoderCache), + } + registerDefaultEncoders(reg) + registerDefaultDecoders(reg) + registerPrimitiveCodecs(reg) + return reg } // RegisterTypeEncoder registers the provided ValueEncoder for the provided type. diff --git a/bson/registry_test.go b/bson/registry_test.go index 2bc87364d3..c7963d4edd 100644 --- a/bson/registry_test.go +++ b/bson/registry_test.go @@ -15,15 +15,13 @@ import ( "go.mongodb.org/mongo-driver/internal/assert" ) -// newTestRegistryBuilder creates a new empty Registry. -func newTestRegistryBuilder() *RegistryBuilder { - return &RegistryBuilder{ - registry: &Registry{ - typeEncoders: new(typeEncoderCache), - typeDecoders: new(typeDecoderCache), - kindEncoders: new(kindEncoderCache), - kindDecoders: new(kindDecoderCache), - }, +// newTestRegistry creates a new empty Registry. +func newTestRegistry() *Registry { + return &Registry{ + typeEncoders: new(typeEncoderCache), + typeDecoders: new(typeDecoderCache), + kindEncoders: new(kindEncoderCache), + kindDecoders: new(kindDecoderCache), } } @@ -45,12 +43,11 @@ func TestRegistryBuilder(t *testing.T) { {i: reflect.TypeOf(t2f).Elem(), ve: fc2}, {i: reflect.TypeOf(t4f).Elem(), ve: fc4}, } - rb := newTestRegistryBuilder() + reg := newTestRegistry() for _, ip := range ips { - rb.RegisterHookEncoder(ip.i, ip.ve) + reg.RegisterInterfaceEncoder(ip.i, ip.ve) } - reg := rb.Build() got := reg.interfaceEncoders if !cmp.Equal(got, want, cmp.AllowUnexported(interfaceValueEncoder{}, fakeCodec{}), cmp.Comparer(typeComparer)) { t.Errorf("the registered interfaces are not correct: got %#v, want %#v", got, want) @@ -58,11 +55,11 @@ func TestRegistryBuilder(t *testing.T) { }) t.Run("type", func(t *testing.T) { ft1, ft2, ft4 := fakeType1{}, fakeType2{}, fakeType4{} - rb := newTestRegistryBuilder(). - RegisterTypeEncoder(reflect.TypeOf(ft1), fc1). - RegisterTypeEncoder(reflect.TypeOf(ft2), fc2). - RegisterTypeEncoder(reflect.TypeOf(ft1), fc3). - RegisterTypeEncoder(reflect.TypeOf(ft4), fc4) + reg := newTestRegistry() + reg.RegisterTypeEncoder(reflect.TypeOf(ft1), fc1) + reg.RegisterTypeEncoder(reflect.TypeOf(ft2), fc2) + reg.RegisterTypeEncoder(reflect.TypeOf(ft1), fc3) + reg.RegisterTypeEncoder(reflect.TypeOf(ft4), fc4) want := []struct { t reflect.Type c ValueEncoder @@ -72,7 +69,6 @@ func TestRegistryBuilder(t *testing.T) { {reflect.TypeOf(ft4), fc4}, } - reg := rb.Build() got := reg.typeEncoders for _, s := range want { wantT, wantC := s.t, s.c @@ -87,11 +83,11 @@ func TestRegistryBuilder(t *testing.T) { }) t.Run("kind", func(t *testing.T) { k1, k2, k4 := reflect.Struct, reflect.Slice, reflect.Map - rb := newTestRegistryBuilder(). - RegisterDefaultEncoder(k1, fc1). - RegisterDefaultEncoder(k2, fc2). - RegisterDefaultEncoder(k1, fc3). - RegisterDefaultEncoder(k4, fc4) + reg := newTestRegistry() + reg.RegisterKindEncoder(k1, fc1) + reg.RegisterKindEncoder(k2, fc2) + reg.RegisterKindEncoder(k1, fc3) + reg.RegisterKindEncoder(k4, fc4) want := []struct { k reflect.Kind c ValueEncoder @@ -101,7 +97,6 @@ func TestRegistryBuilder(t *testing.T) { {k4, fc4}, } - reg := rb.Build() got := reg.kindEncoders for _, s := range want { wantK, wantC := s.k, s.c @@ -118,16 +113,14 @@ func TestRegistryBuilder(t *testing.T) { t.Run("MapCodec", func(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - rb := newTestRegistryBuilder() + reg := newTestRegistry() - rb.RegisterDefaultEncoder(reflect.Map, codec) - reg := rb.Build() + reg.RegisterKindEncoder(reflect.Map, codec) if reg.kindEncoders.get(reflect.Map) != codec { t.Errorf("map codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Map), codec) } - rb.RegisterDefaultEncoder(reflect.Map, codec2) - reg = rb.Build() + reg.RegisterKindEncoder(reflect.Map, codec2) if reg.kindEncoders.get(reflect.Map) != codec2 { t.Errorf("map codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Map), codec2) } @@ -135,16 +128,14 @@ func TestRegistryBuilder(t *testing.T) { t.Run("StructCodec", func(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - rb := newTestRegistryBuilder() + reg := newTestRegistry() - rb.RegisterDefaultEncoder(reflect.Struct, codec) - reg := rb.Build() + reg.RegisterKindEncoder(reflect.Struct, codec) if reg.kindEncoders.get(reflect.Struct) != codec { t.Errorf("struct codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Struct), codec) } - rb.RegisterDefaultEncoder(reflect.Struct, codec2) - reg = rb.Build() + reg.RegisterKindEncoder(reflect.Struct, codec2) if reg.kindEncoders.get(reflect.Struct) != codec2 { t.Errorf("struct codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Struct), codec2) } @@ -152,16 +143,14 @@ func TestRegistryBuilder(t *testing.T) { t.Run("SliceCodec", func(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - rb := newTestRegistryBuilder() + reg := newTestRegistry() - rb.RegisterDefaultEncoder(reflect.Slice, codec) - reg := rb.Build() + reg.RegisterKindEncoder(reflect.Slice, codec) if reg.kindEncoders.get(reflect.Slice) != codec { t.Errorf("slice codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Slice), codec) } - rb.RegisterDefaultEncoder(reflect.Slice, codec2) - reg = rb.Build() + reg.RegisterKindEncoder(reflect.Slice, codec2) if reg.kindEncoders.get(reflect.Slice) != codec2 { t.Errorf("slice codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Slice), codec2) } @@ -169,16 +158,14 @@ func TestRegistryBuilder(t *testing.T) { t.Run("ArrayCodec", func(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - rb := newTestRegistryBuilder() + reg := newTestRegistry() - rb.RegisterDefaultEncoder(reflect.Array, codec) - reg := rb.Build() + reg.RegisterKindEncoder(reflect.Array, codec) if reg.kindEncoders.get(reflect.Array) != codec { t.Errorf("slice codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Array), codec) } - rb.RegisterDefaultEncoder(reflect.Array, codec2) - reg = rb.Build() + reg.RegisterKindEncoder(reflect.Array, codec2) if reg.kindEncoders.get(reflect.Array) != codec2 { t.Errorf("slice codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Array), codec2) } @@ -211,28 +198,27 @@ func TestRegistryBuilder(t *testing.T) { pc = NewPointerCodec() ) - reg := newTestRegistryBuilder(). - RegisterTypeEncoder(ft1, fc1). - RegisterTypeEncoder(ft2, fc2). - RegisterTypeEncoder(ti1, fc1). - RegisterDefaultEncoder(reflect.Struct, fsc). - RegisterDefaultEncoder(reflect.Slice, fslcc). - RegisterDefaultEncoder(reflect.Array, fslcc). - RegisterDefaultEncoder(reflect.Map, fmc). - RegisterDefaultEncoder(reflect.Ptr, pc). - RegisterTypeDecoder(ft1, fc1). - RegisterTypeDecoder(ft2, fc2). - RegisterTypeDecoder(ti1, fc1). // values whose exact type is testInterface1 will use fc1 encoder - RegisterDefaultDecoder(reflect.Struct, fsc). - RegisterDefaultDecoder(reflect.Slice, fslcc). - RegisterDefaultDecoder(reflect.Array, fslcc). - RegisterDefaultDecoder(reflect.Map, fmc). - RegisterDefaultDecoder(reflect.Ptr, pc). - RegisterHookEncoder(ti2, fc2). - RegisterHookDecoder(ti2, fc2). - RegisterHookEncoder(ti3, fc3). - RegisterHookDecoder(ti3, fc3). - Build() + reg := newTestRegistry() + reg.RegisterTypeEncoder(ft1, fc1) + reg.RegisterTypeEncoder(ft2, fc2) + reg.RegisterTypeEncoder(ti1, fc1) + reg.RegisterKindEncoder(reflect.Struct, fsc) + reg.RegisterKindEncoder(reflect.Slice, fslcc) + reg.RegisterKindEncoder(reflect.Array, fslcc) + reg.RegisterKindEncoder(reflect.Map, fmc) + reg.RegisterKindEncoder(reflect.Ptr, pc) + reg.RegisterTypeDecoder(ft1, fc1) + reg.RegisterTypeDecoder(ft2, fc2) + reg.RegisterTypeDecoder(ti1, fc1) // values whose exact type is testInterface1 will use fc1 encoder + reg.RegisterKindDecoder(reflect.Struct, fsc) + reg.RegisterKindDecoder(reflect.Slice, fslcc) + reg.RegisterKindDecoder(reflect.Array, fslcc) + reg.RegisterKindDecoder(reflect.Map, fmc) + reg.RegisterKindDecoder(reflect.Ptr, pc) + reg.RegisterInterfaceEncoder(ti2, fc2) + reg.RegisterInterfaceEncoder(ti3, fc3) + reg.RegisterInterfaceDecoder(ti2, fc2) + reg.RegisterInterfaceDecoder(ti3, fc3) testCases := []struct { name string @@ -409,10 +395,9 @@ func TestRegistryBuilder(t *testing.T) { }) }) t.Run("Type Map", func(t *testing.T) { - reg := newTestRegistryBuilder(). - RegisterTypeMapEntry(TypeString, reflect.TypeOf("")). - RegisterTypeMapEntry(TypeInt32, reflect.TypeOf(int(0))). - Build() + reg := newTestRegistry() + reg.RegisterTypeMapEntry(TypeString, reflect.TypeOf("")) + reg.RegisterTypeMapEntry(TypeInt32, reflect.TypeOf(int(0))) var got, want reflect.Type @@ -466,7 +451,7 @@ func TestRegistry(t *testing.T) { {i: reflect.TypeOf(t2f).Elem(), ve: fc2}, {i: reflect.TypeOf(t4f).Elem(), ve: fc4}, } - reg := newTestRegistryBuilder().Build() + reg := newTestRegistry() for _, ip := range ips { reg.RegisterInterfaceEncoder(ip.i, ip.ve) } @@ -479,7 +464,7 @@ func TestRegistry(t *testing.T) { t.Parallel() ft1, ft2, ft4 := fakeType1{}, fakeType2{}, fakeType4{} - reg := newTestRegistryBuilder().Build() + reg := newTestRegistry() reg.RegisterTypeEncoder(reflect.TypeOf(ft1), fc1) reg.RegisterTypeEncoder(reflect.TypeOf(ft2), fc2) reg.RegisterTypeEncoder(reflect.TypeOf(ft1), fc3) @@ -509,7 +494,7 @@ func TestRegistry(t *testing.T) { t.Parallel() k1, k2, k4 := reflect.Struct, reflect.Slice, reflect.Map - reg := newTestRegistryBuilder().Build() + reg := newTestRegistry() reg.RegisterKindEncoder(k1, fc1) reg.RegisterKindEncoder(k2, fc2) reg.RegisterKindEncoder(k1, fc3) @@ -543,7 +528,7 @@ func TestRegistry(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - reg := newTestRegistryBuilder().Build() + reg := newTestRegistry() reg.RegisterKindEncoder(reflect.Map, codec) if reg.kindEncoders.get(reflect.Map) != codec { t.Errorf("map codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Map), codec) @@ -558,7 +543,7 @@ func TestRegistry(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - reg := newTestRegistryBuilder().Build() + reg := newTestRegistry() reg.RegisterKindEncoder(reflect.Struct, codec) if reg.kindEncoders.get(reflect.Struct) != codec { t.Errorf("struct codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Struct), codec) @@ -573,7 +558,7 @@ func TestRegistry(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - reg := newTestRegistryBuilder().Build() + reg := newTestRegistry() reg.RegisterKindEncoder(reflect.Slice, codec) if reg.kindEncoders.get(reflect.Slice) != codec { t.Errorf("slice codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Slice), codec) @@ -588,7 +573,7 @@ func TestRegistry(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - reg := newTestRegistryBuilder().Build() + reg := newTestRegistry() reg.RegisterKindEncoder(reflect.Array, codec) if reg.kindEncoders.get(reflect.Array) != codec { t.Errorf("slice codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Array), codec) @@ -628,7 +613,7 @@ func TestRegistry(t *testing.T) { pc = NewPointerCodec() ) - reg := newTestRegistryBuilder().Build() + reg := newTestRegistry() reg.RegisterTypeEncoder(ft1, fc1) reg.RegisterTypeEncoder(ft2, fc2) reg.RegisterTypeEncoder(ti1, fc1) @@ -869,7 +854,7 @@ func TestRegistry(t *testing.T) { }) t.Run("Type Map", func(t *testing.T) { t.Parallel() - reg := newTestRegistryBuilder().Build() + reg := newTestRegistry() reg.RegisterTypeMapEntry(TypeString, reflect.TypeOf("")) reg.RegisterTypeMapEntry(TypeInt32, reflect.TypeOf(int(0))) diff --git a/bson/slice_codec.go b/bson/slice_codec.go index 52449239b9..f29c36b26d 100644 --- a/bson/slice_codec.go +++ b/bson/slice_codec.go @@ -90,7 +90,7 @@ func (sc SliceCodec) EncodeValue(ec EncodeContext, vw ValueWriter, val reflect.V } for idx := 0; idx < val.Len(); idx++ { - currEncoder, currVal, lookupErr := defaultValueEncoders.lookupElementEncoder(ec, encoder, val.Index(idx)) + currEncoder, currVal, lookupErr := lookupElementEncoder(ec, encoder, val.Index(idx)) if lookupErr != nil && !errors.Is(lookupErr, errInvalidValue) { return lookupErr } @@ -176,9 +176,9 @@ func (sc *SliceCodec) DecodeValue(dc DecodeContext, vr ValueReader, val reflect. switch val.Type().Elem() { case tE: dc.Ancestor = val.Type() - elemsFunc = defaultValueDecoders.decodeD + elemsFunc = decodeD default: - elemsFunc = defaultValueDecoders.decodeDefault + elemsFunc = decodeDefault } elems, err := elemsFunc(dc, vr, val) diff --git a/bson/string_codec.go b/bson/string_codec.go index 50fb9229fe..4681f15bd4 100644 --- a/bson/string_codec.go +++ b/bson/string_codec.go @@ -7,6 +7,7 @@ package bson import ( + "errors" "fmt" "reflect" @@ -56,7 +57,7 @@ func (sc *StringCodec) EncodeValue(_ EncodeContext, vw ValueWriter, val reflect. return vw.WriteString(val.String()) } -func (sc *StringCodec) decodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { +func (sc *StringCodec) decodeType(dc DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t.Kind() != reflect.String { return emptyValue, ValueDecoderError{ Name: "StringDecodeValue", @@ -78,12 +79,10 @@ func (sc *StringCodec) decodeType(_ DecodeContext, vr ValueReader, t reflect.Typ if err != nil { return emptyValue, err } - if sc.DecodeObjectIDAsHex { + if dc.decodeObjectIDAsHex { str = oid.Hex() } else { - // TODO(GODRIVER-2796): Return an error here instead of decoding to a garbled string. - byteArray := [12]byte(oid) - str = string(byteArray[:]) + return emptyValue, errors.New("cannot decode ObjectID as string if DecodeObjectIDAsHex is not set") } case TypeSymbol: str, err = vr.ReadSymbol() diff --git a/bson/struct_codec.go b/bson/struct_codec.go index 917ac17bfd..17e51bce14 100644 --- a/bson/struct_codec.go +++ b/bson/struct_codec.go @@ -153,7 +153,7 @@ func (sc *StructCodec) EncodeValue(ec EncodeContext, vw ValueWriter, val reflect } } - desc.encoder, rv, err = defaultValueEncoders.lookupElementEncoder(ec, desc.encoder, rv) + desc.encoder, rv, err = lookupElementEncoder(ec, desc.encoder, rv) if err != nil && !errors.Is(err, errInvalidValue) { return err