Upgrade dependent version: go.mongodb.org/mongo-driver (#5320)
Upgrade dependent version: go.mongodb.org/mongo-driver v1.3.2 -> v1.10.4 Signed-off-by: hongzhouzi <hongzhouzi@kubesphere.io> Signed-off-by: hongzhouzi <hongzhouzi@kubesphere.io>
This commit is contained in:
50
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/array_codec.go
generated
vendored
Normal file
50
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/array_codec.go
generated
vendored
Normal file
@@ -0,0 +1,50 @@
|
||||
// Copyright (C) MongoDB, Inc. 2017-present.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||
// not use this file except in compliance with the License. You may obtain
|
||||
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
package bsoncodec
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson/bsonrw"
|
||||
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
|
||||
)
|
||||
|
||||
// ArrayCodec is the Codec used for bsoncore.Array values.
|
||||
type ArrayCodec struct{}
|
||||
|
||||
var defaultArrayCodec = NewArrayCodec()
|
||||
|
||||
// NewArrayCodec returns an ArrayCodec.
|
||||
func NewArrayCodec() *ArrayCodec {
|
||||
return &ArrayCodec{}
|
||||
}
|
||||
|
||||
// EncodeValue is the ValueEncoder for bsoncore.Array values.
|
||||
func (ac *ArrayCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
|
||||
if !val.IsValid() || val.Type() != tCoreArray {
|
||||
return ValueEncoderError{Name: "CoreArrayEncodeValue", Types: []reflect.Type{tCoreArray}, Received: val}
|
||||
}
|
||||
|
||||
arr := val.Interface().(bsoncore.Array)
|
||||
return bsonrw.Copier{}.CopyArrayFromBytes(vw, arr)
|
||||
}
|
||||
|
||||
// DecodeValue is the ValueDecoder for bsoncore.Array values.
|
||||
func (ac *ArrayCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
|
||||
if !val.CanSet() || val.Type() != tCoreArray {
|
||||
return ValueDecoderError{Name: "CoreArrayDecodeValue", Types: []reflect.Type{tCoreArray}, Received: val}
|
||||
}
|
||||
|
||||
if val.IsNil() {
|
||||
val.Set(reflect.MakeSlice(val.Type(), 0, 0))
|
||||
}
|
||||
|
||||
val.SetLen(0)
|
||||
arr, err := bsonrw.Copier{}.AppendArrayBytes(val.Interface().(bsoncore.Array), vr)
|
||||
val.Set(reflect.ValueOf(arr))
|
||||
return err
|
||||
}
|
||||
77
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/bsoncodec.go
generated
vendored
77
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/bsoncodec.go
generated
vendored
@@ -13,6 +13,11 @@ import (
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson/bsonrw"
|
||||
"go.mongodb.org/mongo-driver/bson/bsontype"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
)
|
||||
|
||||
var (
|
||||
emptyValue = reflect.Value{}
|
||||
)
|
||||
|
||||
// Marshaler is an interface implemented by types that can marshal themselves
|
||||
@@ -39,7 +44,7 @@ type Unmarshaler interface {
|
||||
}
|
||||
|
||||
// ValueUnmarshaler is an interface implemented by types that can unmarshal a
|
||||
// BSON value representaiton of themselves. The BSON bytes and type can be
|
||||
// BSON value representation of themselves. The BSON bytes and type can be
|
||||
// assumed to be valid. UnmarshalBSONValue must copy the BSON value bytes if it
|
||||
// wishes to retain the data after returning.
|
||||
type ValueUnmarshaler interface {
|
||||
@@ -114,11 +119,32 @@ type EncodeContext struct {
|
||||
type DecodeContext struct {
|
||||
*Registry
|
||||
Truncate bool
|
||||
|
||||
// Ancestor is the type of a containing document. This is mainly used to determine what type
|
||||
// should be used when decoding an embedded document into an empty interface. For example, if
|
||||
// Ancestor is a bson.M, BSON embedded document values being decoded into an empty interface
|
||||
// will be decoded into a bson.M.
|
||||
//
|
||||
// Deprecated: Use DefaultDocumentM or DefaultDocumentD instead.
|
||||
Ancestor reflect.Type
|
||||
|
||||
// defaultDocumentType specifies the Go type to decode top-level and nested BSON documents into. In particular, the
|
||||
// usage for this field is restricted to data typed as "interface{}" or "map[string]interface{}". If DocumentType is
|
||||
// set to a type that a BSON document cannot be unmarshaled into (e.g. "string"), unmarshalling will result in an
|
||||
// error. DocumentType overrides the Ancestor field.
|
||||
defaultDocumentType reflect.Type
|
||||
}
|
||||
|
||||
// DefaultDocumentM will decode empty documents using the primitive.M type. This behavior is restricted to data typed as
|
||||
// "interface{}" or "map[string]interface{}".
|
||||
func (dc *DecodeContext) DefaultDocumentM() {
|
||||
dc.defaultDocumentType = reflect.TypeOf(primitive.M{})
|
||||
}
|
||||
|
||||
// DefaultDocumentD will decode empty documents using the primitive.D type. This behavior is restricted to data typed as
|
||||
// "interface{}" or "map[string]interface{}".
|
||||
func (dc *DecodeContext) DefaultDocumentD() {
|
||||
dc.defaultDocumentType = reflect.TypeOf(primitive.D{})
|
||||
}
|
||||
|
||||
// ValueCodec is the interface that groups the methods to encode and decode
|
||||
@@ -156,6 +182,55 @@ func (fn ValueDecoderFunc) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader,
|
||||
return fn(dc, vr, val)
|
||||
}
|
||||
|
||||
// typeDecoder is the interface implemented by types that can handle the decoding of a value given its type.
|
||||
type typeDecoder interface {
|
||||
decodeType(DecodeContext, bsonrw.ValueReader, reflect.Type) (reflect.Value, error)
|
||||
}
|
||||
|
||||
// typeDecoderFunc is an adapter function that allows a function with the correct signature to be used as a typeDecoder.
|
||||
type typeDecoderFunc func(DecodeContext, bsonrw.ValueReader, reflect.Type) (reflect.Value, error)
|
||||
|
||||
func (fn typeDecoderFunc) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) {
|
||||
return fn(dc, vr, t)
|
||||
}
|
||||
|
||||
// decodeAdapter allows two functions with the correct signatures to be used as both a ValueDecoder and typeDecoder.
|
||||
type decodeAdapter struct {
|
||||
ValueDecoderFunc
|
||||
typeDecoderFunc
|
||||
}
|
||||
|
||||
var _ ValueDecoder = decodeAdapter{}
|
||||
var _ typeDecoder = decodeAdapter{}
|
||||
|
||||
// decodeTypeOrValue calls decoder.decodeType is decoder is a typeDecoder. Otherwise, it allocates a new element of type
|
||||
// t and calls decoder.DecodeValue on it.
|
||||
func decodeTypeOrValue(decoder ValueDecoder, dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) {
|
||||
td, _ := decoder.(typeDecoder)
|
||||
return decodeTypeOrValueWithInfo(decoder, td, dc, vr, t, true)
|
||||
}
|
||||
|
||||
func decodeTypeOrValueWithInfo(vd ValueDecoder, td typeDecoder, dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type, convert bool) (reflect.Value, error) {
|
||||
if td != nil {
|
||||
val, err := td.decodeType(dc, vr, t)
|
||||
if err == nil && convert && val.Type() != t {
|
||||
// This conversion step is necessary for slices and maps. If a user declares variables like:
|
||||
//
|
||||
// type myBool bool
|
||||
// var m map[string]myBool
|
||||
//
|
||||
// and tries to decode BSON bytes into the map, the decoding will fail if this conversion is not present
|
||||
// because we'll try to assign a value of type bool to one of type myBool.
|
||||
val = val.Convert(t)
|
||||
}
|
||||
return val, err
|
||||
}
|
||||
|
||||
val := reflect.New(t).Elem()
|
||||
err := vd.DecodeValue(dc, vr, val)
|
||||
return val, err
|
||||
}
|
||||
|
||||
// CodecZeroer is the interface implemented by Codecs that can also determine if
|
||||
// a value of the type that would be encoded is zero.
|
||||
type CodecZeroer interface {
|
||||
|
||||
54
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/byte_slice_codec.go
generated
vendored
54
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/byte_slice_codec.go
generated
vendored
@@ -15,14 +15,17 @@ import (
|
||||
"go.mongodb.org/mongo-driver/bson/bsontype"
|
||||
)
|
||||
|
||||
var defaultByteSliceCodec = NewByteSliceCodec()
|
||||
|
||||
// ByteSliceCodec is the Codec used for []byte values.
|
||||
type ByteSliceCodec struct {
|
||||
EncodeNilAsEmpty bool
|
||||
}
|
||||
|
||||
var _ ValueCodec = &ByteSliceCodec{}
|
||||
var (
|
||||
defaultByteSliceCodec = NewByteSliceCodec()
|
||||
|
||||
_ ValueCodec = defaultByteSliceCodec
|
||||
_ typeDecoder = defaultByteSliceCodec
|
||||
)
|
||||
|
||||
// NewByteSliceCodec returns a StringCodec with options opts.
|
||||
func NewByteSliceCodec(opts ...*bsonoptions.ByteSliceCodecOptions) *ByteSliceCodec {
|
||||
@@ -45,10 +48,13 @@ func (bsc *ByteSliceCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter,
|
||||
return vw.WriteBinary(val.Interface().([]byte))
|
||||
}
|
||||
|
||||
// DecodeValue is the ValueDecoder for []byte.
|
||||
func (bsc *ByteSliceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
|
||||
if !val.CanSet() || val.Type() != tByteSlice {
|
||||
return ValueDecoderError{Name: "ByteSliceDecodeValue", Types: []reflect.Type{tByteSlice}, Received: val}
|
||||
func (bsc *ByteSliceCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) {
|
||||
if t != tByteSlice {
|
||||
return emptyValue, ValueDecoderError{
|
||||
Name: "ByteSliceDecodeValue",
|
||||
Types: []reflect.Type{tByteSlice},
|
||||
Received: reflect.Zero(t),
|
||||
}
|
||||
}
|
||||
|
||||
var data []byte
|
||||
@@ -57,31 +63,49 @@ func (bsc *ByteSliceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader,
|
||||
case bsontype.String:
|
||||
str, err := vr.ReadString()
|
||||
if err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
data = []byte(str)
|
||||
case bsontype.Symbol:
|
||||
sym, err := vr.ReadSymbol()
|
||||
if err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
data = []byte(sym)
|
||||
case bsontype.Binary:
|
||||
var subtype byte
|
||||
data, subtype, err = vr.ReadBinary()
|
||||
if err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
if subtype != bsontype.BinaryGeneric && subtype != bsontype.BinaryBinaryOld {
|
||||
return fmt.Errorf("ByteSliceDecodeValue can only be used to decode subtype 0x00 or 0x02 for %s, got %v", bsontype.Binary, subtype)
|
||||
return emptyValue, decodeBinaryError{subtype: subtype, typeName: "[]byte"}
|
||||
}
|
||||
case bsontype.Null:
|
||||
val.Set(reflect.Zero(val.Type()))
|
||||
return vr.ReadNull()
|
||||
err = vr.ReadNull()
|
||||
case bsontype.Undefined:
|
||||
err = vr.ReadUndefined()
|
||||
default:
|
||||
return fmt.Errorf("cannot decode %v into a []byte", vrType)
|
||||
return emptyValue, fmt.Errorf("cannot decode %v into a []byte", vrType)
|
||||
}
|
||||
if err != nil {
|
||||
return emptyValue, err
|
||||
}
|
||||
|
||||
val.Set(reflect.ValueOf(data))
|
||||
return reflect.ValueOf(data), nil
|
||||
}
|
||||
|
||||
// DecodeValue is the ValueDecoder for []byte.
|
||||
func (bsc *ByteSliceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
|
||||
if !val.CanSet() || val.Type() != tByteSlice {
|
||||
return ValueDecoderError{Name: "ByteSliceDecodeValue", Types: []reflect.Type{tByteSlice}, Received: val}
|
||||
}
|
||||
|
||||
elem, err := bsc.decodeType(dc, vr, tByteSlice)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
val.Set(elem)
|
||||
return nil
|
||||
}
|
||||
|
||||
63
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/cond_addr_codec.go
generated
vendored
Normal file
63
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/cond_addr_codec.go
generated
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
// Copyright (C) MongoDB, Inc. 2017-present.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||
// not use this file except in compliance with the License. You may obtain
|
||||
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
package bsoncodec
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson/bsonrw"
|
||||
)
|
||||
|
||||
// condAddrEncoder is the encoder used when a pointer to the encoding value has an encoder.
|
||||
type condAddrEncoder struct {
|
||||
canAddrEnc ValueEncoder
|
||||
elseEnc ValueEncoder
|
||||
}
|
||||
|
||||
var _ ValueEncoder = (*condAddrEncoder)(nil)
|
||||
|
||||
// newCondAddrEncoder returns an condAddrEncoder.
|
||||
func newCondAddrEncoder(canAddrEnc, elseEnc ValueEncoder) *condAddrEncoder {
|
||||
encoder := condAddrEncoder{canAddrEnc: canAddrEnc, elseEnc: elseEnc}
|
||||
return &encoder
|
||||
}
|
||||
|
||||
// EncodeValue is the ValueEncoderFunc for a value that may be addressable.
|
||||
func (cae *condAddrEncoder) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
|
||||
if val.CanAddr() {
|
||||
return cae.canAddrEnc.EncodeValue(ec, vw, val)
|
||||
}
|
||||
if cae.elseEnc != nil {
|
||||
return cae.elseEnc.EncodeValue(ec, vw, val)
|
||||
}
|
||||
return ErrNoEncoder{Type: val.Type()}
|
||||
}
|
||||
|
||||
// condAddrDecoder is the decoder used when a pointer to the value has a decoder.
|
||||
type condAddrDecoder struct {
|
||||
canAddrDec ValueDecoder
|
||||
elseDec ValueDecoder
|
||||
}
|
||||
|
||||
var _ ValueDecoder = (*condAddrDecoder)(nil)
|
||||
|
||||
// newCondAddrDecoder returns an CondAddrDecoder.
|
||||
func newCondAddrDecoder(canAddrDec, elseDec ValueDecoder) *condAddrDecoder {
|
||||
decoder := condAddrDecoder{canAddrDec: canAddrDec, elseDec: elseDec}
|
||||
return &decoder
|
||||
}
|
||||
|
||||
// DecodeValue is the ValueDecoderFunc for a value that may be addressable.
|
||||
func (cad *condAddrDecoder) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
|
||||
if val.CanAddr() {
|
||||
return cad.canAddrDec.DecodeValue(dc, vr, val)
|
||||
}
|
||||
if cad.elseDec != nil {
|
||||
return cad.elseDec.DecodeValue(dc, vr, val)
|
||||
}
|
||||
return ErrNoDecoder{Type: val.Type()}
|
||||
}
|
||||
1174
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_decoders.go
generated
vendored
1174
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_decoders.go
generated
vendored
File diff suppressed because it is too large
Load Diff
45
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_encoders.go
generated
vendored
45
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_encoders.go
generated
vendored
@@ -30,7 +30,7 @@ var errInvalidValue = errors.New("cannot encode invalid element")
|
||||
|
||||
var sliceWriterPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
sw := make(bsonrw.SliceWriter, 0, 0)
|
||||
sw := make(bsonrw.SliceWriter, 0)
|
||||
return &sw
|
||||
},
|
||||
}
|
||||
@@ -70,6 +70,7 @@ func (dve DefaultValueEncoders) RegisterDefaultEncoders(rb *RegistryBuilder) {
|
||||
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)).
|
||||
@@ -104,7 +105,7 @@ func (dve DefaultValueEncoders) RegisterDefaultEncoders(rb *RegistryBuilder) {
|
||||
RegisterDefaultEncoder(reflect.Map, defaultMapCodec).
|
||||
RegisterDefaultEncoder(reflect.Slice, defaultSliceCodec).
|
||||
RegisterDefaultEncoder(reflect.String, defaultStringCodec).
|
||||
RegisterDefaultEncoder(reflect.Struct, defaultStructCodec).
|
||||
RegisterDefaultEncoder(reflect.Struct, newDefaultStructCodec()).
|
||||
RegisterDefaultEncoder(reflect.Ptr, NewPointerCodec()).
|
||||
RegisterHookEncoder(tValueMarshaler, ValueEncoderFunc(dve.ValueMarshalerEncodeValue)).
|
||||
RegisterHookEncoder(tMarshaler, ValueEncoderFunc(dve.MarshalerEncodeValue)).
|
||||
@@ -150,8 +151,8 @@ func (dve DefaultValueEncoders) IntEncodeValue(ec EncodeContext, vw bsonrw.Value
|
||||
}
|
||||
|
||||
// UintEncodeValue is the ValueEncoderFunc for uint types.
|
||||
// This method is deprecated and does not have any stability guarantees. It may be removed in the
|
||||
// future. Use UIntCodec.EncodeValue instead.
|
||||
//
|
||||
// Deprecated: UintEncodeValue is not registered by default. Use UintCodec.EncodeValue instead.
|
||||
func (dve DefaultValueEncoders) UintEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
|
||||
switch val.Kind() {
|
||||
case reflect.Uint8, reflect.Uint16:
|
||||
@@ -185,8 +186,8 @@ func (dve DefaultValueEncoders) FloatEncodeValue(ec EncodeContext, vw bsonrw.Val
|
||||
}
|
||||
|
||||
// StringEncodeValue is the ValueEncoderFunc for string types.
|
||||
// This method is deprecated and does not have any stability guarantees. It may be removed in the
|
||||
// future. Use StringCodec.EncodeValue instead.
|
||||
//
|
||||
// Deprecated: StringEncodeValue is not registered by default. Use StringCodec.EncodeValue instead.
|
||||
func (dve DefaultValueEncoders) StringEncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
|
||||
if val.Kind() != reflect.String {
|
||||
return ValueEncoderError{
|
||||
@@ -245,19 +246,20 @@ func (dve DefaultValueEncoders) URLEncodeValue(ec EncodeContext, vw bsonrw.Value
|
||||
}
|
||||
|
||||
// TimeEncodeValue is the ValueEncoderFunc for time.TIme.
|
||||
// This method is deprecated and does not have any stability guarantees. It may be removed in the
|
||||
// future. Use TimeCodec.EncodeValue instead.
|
||||
//
|
||||
// Deprecated: TimeEncodeValue is not registered by default. Use TimeCodec.EncodeValue instead.
|
||||
func (dve DefaultValueEncoders) TimeEncodeValue(ec EncodeContext, vw bsonrw.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)
|
||||
return vw.WriteDateTime(tt.Unix()*1000 + int64(tt.Nanosecond()/1e6))
|
||||
dt := primitive.NewDateTimeFromTime(tt)
|
||||
return vw.WriteDateTime(int64(dt))
|
||||
}
|
||||
|
||||
// ByteSliceEncodeValue is the ValueEncoderFunc for []byte.
|
||||
// This method is deprecated and does not have any stability guarantees. It may be removed in the
|
||||
// future. Use ByteSliceCodec.EncodeValue instead.
|
||||
//
|
||||
// Deprecated: ByteSliceEncodeValue is not registered by default. Use ByteSliceCodec.EncodeValue instead.
|
||||
func (dve DefaultValueEncoders) ByteSliceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
|
||||
if !val.IsValid() || val.Type() != tByteSlice {
|
||||
return ValueEncoderError{Name: "ByteSliceEncodeValue", Types: []reflect.Type{tByteSlice}, Received: val}
|
||||
@@ -269,8 +271,8 @@ func (dve DefaultValueEncoders) ByteSliceEncodeValue(ec EncodeContext, vw bsonrw
|
||||
}
|
||||
|
||||
// MapEncodeValue is the ValueEncoderFunc for map[string]* types.
|
||||
// This method is deprecated and does not have any stability guarantees. It may be removed in the
|
||||
// future. Use MapCodec.EncodeValue instead.
|
||||
//
|
||||
// Deprecated: MapEncodeValue is not registered by default. Use MapCodec.EncodeValue instead.
|
||||
func (dve DefaultValueEncoders) MapEncodeValue(ec EncodeContext, vw bsonrw.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}
|
||||
@@ -331,14 +333,7 @@ func (dve DefaultValueEncoders) mapEncodeValue(ec EncodeContext, dw bsonrw.Docum
|
||||
continue
|
||||
}
|
||||
|
||||
if enc, ok := currEncoder.(ValueEncoder); ok {
|
||||
err = enc.EncodeValue(ec, vw, currVal)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
err = encoder.EncodeValue(ec, vw, currVal)
|
||||
err = currEncoder.EncodeValue(ec, vw, currVal)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -419,8 +414,8 @@ func (dve DefaultValueEncoders) ArrayEncodeValue(ec EncodeContext, vw bsonrw.Val
|
||||
}
|
||||
|
||||
// SliceEncodeValue is the ValueEncoderFunc for slice types.
|
||||
// This method is deprecated and does not have any stability guarantees. It may be removed in the
|
||||
// future. Use SliceCodec.EncodeValue instead.
|
||||
//
|
||||
// Deprecated: SliceEncodeValue is not registered by default. Use SliceCodec.EncodeValue instead.
|
||||
func (dve DefaultValueEncoders) SliceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
|
||||
if !val.IsValid() || val.Kind() != reflect.Slice {
|
||||
return ValueEncoderError{Name: "SliceEncodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val}
|
||||
@@ -501,8 +496,8 @@ func (dve DefaultValueEncoders) lookupElementEncoder(ec EncodeContext, origEncod
|
||||
}
|
||||
|
||||
// EmptyInterfaceEncodeValue is the ValueEncoderFunc for interface{}.
|
||||
// This method is deprecated and does not have any stability guarantees. It may be removed in the
|
||||
// future. Use EmptyInterfaceCodec.EncodeValue instead.
|
||||
//
|
||||
// Deprecated: EmptyInterfaceEncodeValue is not registered by default. Use EmptyInterfaceCodec.EncodeValue instead.
|
||||
func (dve DefaultValueEncoders) EmptyInterfaceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
|
||||
if !val.IsValid() || val.Type() != tEmpty {
|
||||
return ValueEncoderError{Name: "EmptyInterfaceEncodeValue", Types: []reflect.Type{tEmpty}, Received: val}
|
||||
|
||||
18
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/doc.go
generated
vendored
18
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/doc.go
generated
vendored
@@ -1,3 +1,9 @@
|
||||
// Copyright (C) MongoDB, Inc. 2022-present.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||
// not use this file except in compliance with the License. You may obtain
|
||||
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
// Package bsoncodec provides a system for encoding values to BSON representations and decoding
|
||||
// values from BSON representations. This package considers both binary BSON and ExtendedJSON as
|
||||
// BSON representations. The types in this package enable a flexible system for handling this
|
||||
@@ -11,7 +17,7 @@
|
||||
// 2) A Registry that holds these ValueEncoders and ValueDecoders and provides methods for
|
||||
// retrieving them.
|
||||
//
|
||||
// ValueEncoders and ValueDecoders
|
||||
// # ValueEncoders and ValueDecoders
|
||||
//
|
||||
// The ValueEncoder interface is implemented by types that can encode a provided Go type to BSON.
|
||||
// The value to encode is provided as a reflect.Value and a bsonrw.ValueWriter is used within the
|
||||
@@ -25,7 +31,7 @@
|
||||
// allow the use of a function with the correct signature as a ValueDecoder. A DecodeContext
|
||||
// instance is provided and serves similar functionality to the EncodeContext.
|
||||
//
|
||||
// Registry and RegistryBuilder
|
||||
// # Registry and RegistryBuilder
|
||||
//
|
||||
// A Registry is an immutable store for ValueEncoders, ValueDecoders, and a type map. See the Registry type
|
||||
// documentation for examples of registering various custom encoders and decoders. A Registry can be constructed using a
|
||||
@@ -47,15 +53,15 @@
|
||||
// values decode as Go int32 and int64 instances, respectively, when decoding into a bson.D. The following code would
|
||||
// change the behavior so these values decode as Go int instances instead:
|
||||
//
|
||||
// intType := reflect.TypeOf(int(0))
|
||||
// registryBuilder.RegisterTypeMapEntry(bsontype.Int32, intType).RegisterTypeMapEntry(bsontype.Int64, intType)
|
||||
// intType := reflect.TypeOf(int(0))
|
||||
// registryBuilder.RegisterTypeMapEntry(bsontype.Int32, intType).RegisterTypeMapEntry(bsontype.Int64, intType)
|
||||
//
|
||||
// 4. Kind encoder/decoders - These can be registered using the RegisterDefaultEncoder and RegisterDefaultDecoder
|
||||
// methods. The registered codec will be invoked when encoding or decoding values whose reflect.Kind matches the
|
||||
// registered reflect.Kind as long as the value's type doesn't match a registered type or hook encoder/decoder first.
|
||||
// These methods should be used to change the behavior for all values for a specific kind.
|
||||
//
|
||||
// Registry Lookup Procedure
|
||||
// # Registry Lookup Procedure
|
||||
//
|
||||
// When looking up an encoder in a Registry, the precedence rules are as follows:
|
||||
//
|
||||
@@ -73,7 +79,7 @@
|
||||
// rules apply for decoders, with the exception that an error of type ErrNoDecoder will be returned if no decoder is
|
||||
// found.
|
||||
//
|
||||
// DefaultValueEncoders and DefaultValueDecoders
|
||||
// # DefaultValueEncoders and DefaultValueDecoders
|
||||
//
|
||||
// The DefaultValueEncoders and DefaultValueDecoders types provide a full set of ValueEncoders and
|
||||
// ValueDecoders for handling a wide range of Go types, including all of the types within the
|
||||
|
||||
60
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/empty_interface_codec.go
generated
vendored
60
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/empty_interface_codec.go
generated
vendored
@@ -15,14 +15,17 @@ import (
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
)
|
||||
|
||||
var defaultEmptyInterfaceCodec = NewEmptyInterfaceCodec()
|
||||
|
||||
// EmptyInterfaceCodec is the Codec used for interface{} values.
|
||||
type EmptyInterfaceCodec struct {
|
||||
DecodeBinaryAsSlice bool
|
||||
}
|
||||
|
||||
var _ ValueCodec = &EmptyInterfaceCodec{}
|
||||
var (
|
||||
defaultEmptyInterfaceCodec = NewEmptyInterfaceCodec()
|
||||
|
||||
_ ValueCodec = defaultEmptyInterfaceCodec
|
||||
_ typeDecoder = defaultEmptyInterfaceCodec
|
||||
)
|
||||
|
||||
// NewEmptyInterfaceCodec returns a EmptyInterfaceCodec with options opts.
|
||||
func NewEmptyInterfaceCodec(opts ...*bsonoptions.EmptyInterfaceCodecOptions) *EmptyInterfaceCodec {
|
||||
@@ -54,11 +57,18 @@ func (eic EmptyInterfaceCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWrit
|
||||
|
||||
func (eic EmptyInterfaceCodec) getEmptyInterfaceDecodeType(dc DecodeContext, valueType bsontype.Type) (reflect.Type, error) {
|
||||
isDocument := valueType == bsontype.Type(0) || valueType == bsontype.EmbeddedDocument
|
||||
if isDocument && dc.Ancestor != nil {
|
||||
// Using ancestor information rather than looking up the type map entry forces consistent decoding.
|
||||
// If we're decoding into a bson.D, subdocuments should also be decoded as bson.D, even if a type map entry
|
||||
// has been registered.
|
||||
return dc.Ancestor, nil
|
||||
if isDocument {
|
||||
if dc.defaultDocumentType != nil {
|
||||
// If the bsontype is an embedded document and the DocumentType is set on the DecodeContext, then return
|
||||
// that type.
|
||||
return dc.defaultDocumentType, nil
|
||||
}
|
||||
if dc.Ancestor != nil {
|
||||
// Using ancestor information rather than looking up the type map entry forces consistent decoding.
|
||||
// If we're decoding into a bson.D, subdocuments should also be decoded as bson.D, even if a type map entry
|
||||
// has been registered.
|
||||
return dc.Ancestor, nil
|
||||
}
|
||||
}
|
||||
|
||||
rtype, err := dc.LookupTypeMapEntry(valueType)
|
||||
@@ -86,33 +96,31 @@ func (eic EmptyInterfaceCodec) getEmptyInterfaceDecodeType(dc DecodeContext, val
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// DecodeValue is the ValueDecoderFunc for interface{}.
|
||||
func (eic EmptyInterfaceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
|
||||
if !val.CanSet() || val.Type() != tEmpty {
|
||||
return ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: val}
|
||||
func (eic EmptyInterfaceCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) {
|
||||
if t != tEmpty {
|
||||
return emptyValue, ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: reflect.Zero(t)}
|
||||
}
|
||||
|
||||
rtype, err := eic.getEmptyInterfaceDecodeType(dc, vr.Type())
|
||||
if err != nil {
|
||||
switch vr.Type() {
|
||||
case bsontype.Null:
|
||||
val.Set(reflect.Zero(val.Type()))
|
||||
return vr.ReadNull()
|
||||
return reflect.Zero(t), vr.ReadNull()
|
||||
default:
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
}
|
||||
|
||||
decoder, err := dc.LookupDecoder(rtype)
|
||||
if err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
|
||||
elem := reflect.New(rtype).Elem()
|
||||
err = decoder.DecodeValue(dc, vr, elem)
|
||||
elem, err := decodeTypeOrValue(decoder, dc, vr, rtype)
|
||||
if err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
|
||||
if eic.DecodeBinaryAsSlice && rtype == tBinary {
|
||||
binElem := elem.Interface().(primitive.Binary)
|
||||
if binElem.Subtype == bsontype.BinaryGeneric || binElem.Subtype == bsontype.BinaryBinaryOld {
|
||||
@@ -120,6 +128,20 @@ func (eic EmptyInterfaceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueRead
|
||||
}
|
||||
}
|
||||
|
||||
return elem, nil
|
||||
}
|
||||
|
||||
// DecodeValue is the ValueDecoderFunc for interface{}.
|
||||
func (eic EmptyInterfaceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
|
||||
if !val.CanSet() || val.Type() != tEmpty {
|
||||
return ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: val}
|
||||
}
|
||||
|
||||
elem, err := eic.decodeType(dc, vr, val.Type())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
val.Set(elem)
|
||||
return nil
|
||||
}
|
||||
|
||||
169
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/map_codec.go
generated
vendored
169
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/map_codec.go
generated
vendored
@@ -7,6 +7,7 @@
|
||||
package bsoncodec
|
||||
|
||||
import (
|
||||
"encoding"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
@@ -20,12 +21,29 @@ var defaultMapCodec = NewMapCodec()
|
||||
|
||||
// MapCodec is the Codec used for map values.
|
||||
type MapCodec struct {
|
||||
DecodeZerosMap bool
|
||||
EncodeNilAsEmpty bool
|
||||
DecodeZerosMap bool
|
||||
EncodeNilAsEmpty bool
|
||||
EncodeKeysWithStringer bool
|
||||
}
|
||||
|
||||
var _ ValueCodec = &MapCodec{}
|
||||
|
||||
// KeyMarshaler is the interface implemented by an object that can marshal itself into a string key.
|
||||
// This applies to types used as map keys and is similar to encoding.TextMarshaler.
|
||||
type KeyMarshaler interface {
|
||||
MarshalKey() (key string, err error)
|
||||
}
|
||||
|
||||
// KeyUnmarshaler is the interface implemented by an object that can unmarshal a string representation
|
||||
// of itself. This applies to types used as map keys and is similar to encoding.TextUnmarshaler.
|
||||
//
|
||||
// UnmarshalKey must be able to decode the form generated by MarshalKey.
|
||||
// UnmarshalKey must copy the text if it wishes to retain the text
|
||||
// after returning.
|
||||
type KeyUnmarshaler interface {
|
||||
UnmarshalKey(key string) error
|
||||
}
|
||||
|
||||
// NewMapCodec returns a MapCodec with options opts.
|
||||
func NewMapCodec(opts ...*bsonoptions.MapCodecOptions) *MapCodec {
|
||||
mapOpt := bsonoptions.MergeMapCodecOptions(opts...)
|
||||
@@ -37,6 +55,9 @@ func NewMapCodec(opts ...*bsonoptions.MapCodecOptions) *MapCodec {
|
||||
if mapOpt.EncodeNilAsEmpty != nil {
|
||||
codec.EncodeNilAsEmpty = *mapOpt.EncodeNilAsEmpty
|
||||
}
|
||||
if mapOpt.EncodeKeysWithStringer != nil {
|
||||
codec.EncodeKeysWithStringer = *mapOpt.EncodeKeysWithStringer
|
||||
}
|
||||
return &codec
|
||||
}
|
||||
|
||||
@@ -79,7 +100,11 @@ func (mc *MapCodec) mapEncodeValue(ec EncodeContext, dw bsonrw.DocumentWriter, v
|
||||
|
||||
keys := val.MapKeys()
|
||||
for _, key := range keys {
|
||||
keyStr := fmt.Sprint(key)
|
||||
keyStr, err := mc.encodeKey(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if collisionFn != nil && collisionFn(keyStr) {
|
||||
return fmt.Errorf("Key %s of inlined map conflicts with a struct field name", key)
|
||||
}
|
||||
@@ -102,14 +127,7 @@ func (mc *MapCodec) mapEncodeValue(ec EncodeContext, dw bsonrw.DocumentWriter, v
|
||||
continue
|
||||
}
|
||||
|
||||
if enc, ok := currEncoder.(ValueEncoder); ok {
|
||||
err = enc.EncodeValue(ec, vw, currVal)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
err = encoder.EncodeValue(ec, vw, currVal)
|
||||
err = currEncoder.EncodeValue(ec, vw, currVal)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -129,6 +147,9 @@ func (mc *MapCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val ref
|
||||
case bsontype.Null:
|
||||
val.Set(reflect.Zero(val.Type()))
|
||||
return vr.ReadNull()
|
||||
case bsontype.Undefined:
|
||||
val.Set(reflect.Zero(val.Type()))
|
||||
return vr.ReadUndefined()
|
||||
default:
|
||||
return fmt.Errorf("cannot decode %v into a %s", vrType, val.Type())
|
||||
}
|
||||
@@ -151,13 +172,13 @@ func (mc *MapCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val ref
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
eTypeDecoder, _ := decoder.(typeDecoder)
|
||||
|
||||
if eType == tEmpty {
|
||||
dc.Ancestor = val.Type()
|
||||
}
|
||||
|
||||
keyType := val.Type().Key()
|
||||
keyKind := keyType.Kind()
|
||||
|
||||
for {
|
||||
key, vr, err := dr.ReadElement()
|
||||
@@ -168,31 +189,16 @@ func (mc *MapCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val ref
|
||||
return err
|
||||
}
|
||||
|
||||
k := reflect.ValueOf(key)
|
||||
if keyType != tString {
|
||||
switch keyKind {
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
|
||||
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
|
||||
reflect.Float32, reflect.Float64:
|
||||
parsed, err := strconv.ParseFloat(k.String(), 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Map key is defined to be a decimal type (%v) but got error %v", keyKind, err)
|
||||
}
|
||||
k = reflect.ValueOf(parsed)
|
||||
case reflect.String: // if keyType wraps string
|
||||
default:
|
||||
return fmt.Errorf("BSON map must have string or decimal keys. Got:%v", val.Type())
|
||||
}
|
||||
|
||||
k = k.Convert(keyType)
|
||||
}
|
||||
|
||||
elem := reflect.New(eType).Elem()
|
||||
err = decoder.DecodeValue(dc, vr, elem)
|
||||
k, err := mc.decodeKey(key, keyType)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
elem, err := decodeTypeOrValueWithInfo(decoder, eTypeDecoder, dc, vr, eType, true)
|
||||
if err != nil {
|
||||
return newDecodeError(key, err)
|
||||
}
|
||||
|
||||
val.SetMapIndex(k, elem)
|
||||
}
|
||||
return nil
|
||||
@@ -204,3 +210,100 @@ func clearMap(m reflect.Value) {
|
||||
m.SetMapIndex(k, none)
|
||||
}
|
||||
}
|
||||
|
||||
func (mc *MapCodec) encodeKey(val reflect.Value) (string, error) {
|
||||
if mc.EncodeKeysWithStringer {
|
||||
return fmt.Sprint(val), nil
|
||||
}
|
||||
|
||||
// keys of any string type are used directly
|
||||
if val.Kind() == reflect.String {
|
||||
return val.String(), nil
|
||||
}
|
||||
// KeyMarshalers are marshaled
|
||||
if km, ok := val.Interface().(KeyMarshaler); ok {
|
||||
if val.Kind() == reflect.Ptr && val.IsNil() {
|
||||
return "", nil
|
||||
}
|
||||
buf, err := km.MarshalKey()
|
||||
if err == nil {
|
||||
return buf, nil
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
// keys implement encoding.TextMarshaler are marshaled.
|
||||
if km, ok := val.Interface().(encoding.TextMarshaler); ok {
|
||||
if val.Kind() == reflect.Ptr && val.IsNil() {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
buf, err := km.MarshalText()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(buf), nil
|
||||
}
|
||||
|
||||
switch val.Kind() {
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return strconv.FormatInt(val.Int(), 10), nil
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
||||
return strconv.FormatUint(val.Uint(), 10), nil
|
||||
}
|
||||
return "", fmt.Errorf("unsupported key type: %v", val.Type())
|
||||
}
|
||||
|
||||
var keyUnmarshalerType = reflect.TypeOf((*KeyUnmarshaler)(nil)).Elem()
|
||||
var textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
|
||||
|
||||
func (mc *MapCodec) decodeKey(key string, keyType reflect.Type) (reflect.Value, error) {
|
||||
keyVal := reflect.ValueOf(key)
|
||||
var err error
|
||||
switch {
|
||||
// First, if EncodeKeysWithStringer is not enabled, try to decode withKeyUnmarshaler
|
||||
case !mc.EncodeKeysWithStringer && reflect.PtrTo(keyType).Implements(keyUnmarshalerType):
|
||||
keyVal = reflect.New(keyType)
|
||||
v := keyVal.Interface().(KeyUnmarshaler)
|
||||
err = v.UnmarshalKey(key)
|
||||
keyVal = keyVal.Elem()
|
||||
// Try to decode encoding.TextUnmarshalers.
|
||||
case reflect.PtrTo(keyType).Implements(textUnmarshalerType):
|
||||
keyVal = reflect.New(keyType)
|
||||
v := keyVal.Interface().(encoding.TextUnmarshaler)
|
||||
err = v.UnmarshalText([]byte(key))
|
||||
keyVal = keyVal.Elem()
|
||||
// Otherwise, go to type specific behavior
|
||||
default:
|
||||
switch keyType.Kind() {
|
||||
case reflect.String:
|
||||
keyVal = reflect.ValueOf(key).Convert(keyType)
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
n, parseErr := strconv.ParseInt(key, 10, 64)
|
||||
if parseErr != nil || reflect.Zero(keyType).OverflowInt(n) {
|
||||
err = fmt.Errorf("failed to unmarshal number key %v", key)
|
||||
}
|
||||
keyVal = reflect.ValueOf(n).Convert(keyType)
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
||||
n, parseErr := strconv.ParseUint(key, 10, 64)
|
||||
if parseErr != nil || reflect.Zero(keyType).OverflowUint(n) {
|
||||
err = fmt.Errorf("failed to unmarshal number key %v", key)
|
||||
break
|
||||
}
|
||||
keyVal = reflect.ValueOf(n).Convert(keyType)
|
||||
case reflect.Float32, reflect.Float64:
|
||||
if mc.EncodeKeysWithStringer {
|
||||
parsed, err := strconv.ParseFloat(key, 64)
|
||||
if err != nil {
|
||||
return keyVal, fmt.Errorf("Map key is defined to be a decimal type (%v) but got error %v", keyType.Kind(), err)
|
||||
}
|
||||
keyVal = reflect.ValueOf(parsed)
|
||||
break
|
||||
}
|
||||
fallthrough
|
||||
default:
|
||||
return keyVal, fmt.Errorf("unsupported key type: %v", keyType)
|
||||
}
|
||||
}
|
||||
return keyVal, err
|
||||
}
|
||||
|
||||
9
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/pointer_codec.go
generated
vendored
9
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/pointer_codec.go
generated
vendored
@@ -14,11 +14,6 @@ import (
|
||||
"go.mongodb.org/mongo-driver/bson/bsontype"
|
||||
)
|
||||
|
||||
var defaultPointerCodec = &PointerCodec{
|
||||
ecache: make(map[reflect.Type]ValueEncoder),
|
||||
dcache: make(map[reflect.Type]ValueDecoder),
|
||||
}
|
||||
|
||||
var _ ValueEncoder = &PointerCodec{}
|
||||
var _ ValueDecoder = &PointerCodec{}
|
||||
|
||||
@@ -83,6 +78,10 @@ func (pc *PointerCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val
|
||||
val.Set(reflect.Zero(val.Type()))
|
||||
return vr.ReadNull()
|
||||
}
|
||||
if vr.Type() == bsontype.Undefined {
|
||||
val.Set(reflect.Zero(val.Type()))
|
||||
return vr.ReadUndefined()
|
||||
}
|
||||
|
||||
if val.IsNil() {
|
||||
val.Set(reflect.New(val.Type().Elem()))
|
||||
|
||||
55
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/registry.go
generated
vendored
55
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/registry.go
generated
vendored
@@ -54,12 +54,6 @@ func (entme ErrNoTypeMapEntry) Error() string {
|
||||
// ErrNotInterface is returned when the provided type is not an interface.
|
||||
var ErrNotInterface = errors.New("The provided type is not an interface")
|
||||
|
||||
var defaultRegistry *Registry
|
||||
|
||||
func init() {
|
||||
defaultRegistry = buildDefaultRegistry()
|
||||
}
|
||||
|
||||
// A RegistryBuilder is used to build a Registry. This type is not goroutine
|
||||
// safe.
|
||||
type RegistryBuilder struct {
|
||||
@@ -187,8 +181,9 @@ func (rb *RegistryBuilder) RegisterHookDecoder(t reflect.Type, dec ValueDecoder)
|
||||
return rb
|
||||
}
|
||||
|
||||
// RegisterEncoder has been deprecated and will be removed in a future major version release. Use RegisterTypeEncoder
|
||||
// or RegisterHookEncoder instead.
|
||||
// RegisterEncoder registers the provided type and encoder pair.
|
||||
//
|
||||
// Deprecated: Use RegisterTypeEncoder or RegisterHookEncoder instead.
|
||||
func (rb *RegistryBuilder) RegisterEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder {
|
||||
if t == tEmpty {
|
||||
rb.typeEncoders[t] = enc
|
||||
@@ -210,8 +205,9 @@ func (rb *RegistryBuilder) RegisterEncoder(t reflect.Type, enc ValueEncoder) *Re
|
||||
return rb
|
||||
}
|
||||
|
||||
// RegisterDecoder has been deprecated and will be removed in a future major version release. Use RegisterTypeDecoder
|
||||
// or RegisterHookDecoder instead.
|
||||
// RegisterDecoder registers the provided type and decoder pair.
|
||||
//
|
||||
// Deprecated: Use RegisterTypeDecoder or RegisterHookDecoder instead.
|
||||
func (rb *RegistryBuilder) RegisterDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder {
|
||||
if t == nil {
|
||||
rb.typeDecoders[nil] = dec
|
||||
@@ -258,6 +254,7 @@ func (rb *RegistryBuilder) RegisterDefaultDecoder(kind reflect.Kind, dec ValueDe
|
||||
// By default, BSON documents will decode into interface{} values as bson.D. To change the default type for BSON
|
||||
// documents, a type map entry for bsontype.EmbeddedDocument should be registered. For example, to force BSON documents
|
||||
// to decode to bson.Raw, use the following code:
|
||||
//
|
||||
// rb.RegisterTypeMapEntry(bsontype.EmbeddedDocument, reflect.TypeOf(bson.Raw{}))
|
||||
func (rb *RegistryBuilder) RegisterTypeMapEntry(bt bsontype.Type, rt reflect.Type) *RegistryBuilder {
|
||||
rb.typeMap[bt] = rt
|
||||
@@ -302,7 +299,7 @@ func (rb *RegistryBuilder) Build() *Registry {
|
||||
return registry
|
||||
}
|
||||
|
||||
// LookupEncoder inspects the registry for an encoder for the given type. The lookup precendence works as follows:
|
||||
// LookupEncoder inspects the registry for an encoder for the given type. The lookup precedence works as follows:
|
||||
//
|
||||
// 1. An encoder registered for the exact type. If the given type represents an interface, an encoder registered using
|
||||
// RegisterTypeEncoder for the interface will be selected.
|
||||
@@ -325,7 +322,7 @@ func (r *Registry) LookupEncoder(t reflect.Type) (ValueEncoder, error) {
|
||||
return enc, nil
|
||||
}
|
||||
|
||||
enc, found = r.lookupInterfaceEncoder(t)
|
||||
enc, found = r.lookupInterfaceEncoder(t, true)
|
||||
if found {
|
||||
r.mu.Lock()
|
||||
r.typeEncoders[t] = enc
|
||||
@@ -359,19 +356,28 @@ func (r *Registry) lookupTypeEncoder(t reflect.Type) (ValueEncoder, bool) {
|
||||
return enc, found
|
||||
}
|
||||
|
||||
func (r *Registry) lookupInterfaceEncoder(t reflect.Type) (ValueEncoder, bool) {
|
||||
func (r *Registry) lookupInterfaceEncoder(t reflect.Type, allowAddr bool) (ValueEncoder, bool) {
|
||||
if t == nil {
|
||||
return nil, false
|
||||
}
|
||||
for _, ienc := range r.interfaceEncoders {
|
||||
if t.Implements(ienc.i) || reflect.PtrTo(t).Implements(ienc.i) {
|
||||
if t.Implements(ienc.i) {
|
||||
return ienc.ve, true
|
||||
}
|
||||
if allowAddr && t.Kind() != reflect.Ptr && reflect.PtrTo(t).Implements(ienc.i) {
|
||||
// if *t implements an interface, this will catch if t implements an interface further ahead
|
||||
// in interfaceEncoders
|
||||
defaultEnc, found := r.lookupInterfaceEncoder(t, false)
|
||||
if !found {
|
||||
defaultEnc = r.kindEncoders[t.Kind()]
|
||||
}
|
||||
return newCondAddrEncoder(ienc.ve, defaultEnc), true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// LookupDecoder inspects the registry for an decoder for the given type. The lookup precendence works as follows:
|
||||
// LookupDecoder inspects the registry for an decoder for the given type. The lookup precedence works as follows:
|
||||
//
|
||||
// 1. A decoder registered for the exact type. If the given type represents an interface, a decoder registered using
|
||||
// RegisterTypeDecoder for the interface will be selected.
|
||||
@@ -397,7 +403,7 @@ func (r *Registry) LookupDecoder(t reflect.Type) (ValueDecoder, error) {
|
||||
return dec, nil
|
||||
}
|
||||
|
||||
dec, found = r.lookupInterfaceDecoder(t)
|
||||
dec, found = r.lookupInterfaceDecoder(t, true)
|
||||
if found {
|
||||
r.mu.Lock()
|
||||
r.typeDecoders[t] = dec
|
||||
@@ -424,13 +430,20 @@ func (r *Registry) lookupTypeDecoder(t reflect.Type) (ValueDecoder, bool) {
|
||||
return dec, found
|
||||
}
|
||||
|
||||
func (r *Registry) lookupInterfaceDecoder(t reflect.Type) (ValueDecoder, bool) {
|
||||
func (r *Registry) lookupInterfaceDecoder(t reflect.Type, allowAddr bool) (ValueDecoder, bool) {
|
||||
for _, idec := range r.interfaceDecoders {
|
||||
if !t.Implements(idec.i) && !reflect.PtrTo(t).Implements(idec.i) {
|
||||
continue
|
||||
if t.Implements(idec.i) {
|
||||
return idec.vd, true
|
||||
}
|
||||
if allowAddr && t.Kind() != reflect.Ptr && reflect.PtrTo(t).Implements(idec.i) {
|
||||
// if *t implements an interface, this will catch if t implements an interface further ahead
|
||||
// in interfaceDecoders
|
||||
defaultDec, found := r.lookupInterfaceDecoder(t, false)
|
||||
if !found {
|
||||
defaultDec = r.kindDecoders[t.Kind()]
|
||||
}
|
||||
return newCondAddrDecoder(idec.vd, defaultDec), true
|
||||
}
|
||||
|
||||
return idec.vd, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
7
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/slice_codec.go
generated
vendored
7
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/slice_codec.go
generated
vendored
@@ -123,6 +123,9 @@ func (sc *SliceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val r
|
||||
case bsontype.Null:
|
||||
val.Set(reflect.Zero(val.Type()))
|
||||
return vr.ReadNull()
|
||||
case bsontype.Undefined:
|
||||
val.Set(reflect.Zero(val.Type()))
|
||||
return vr.ReadUndefined()
|
||||
case bsontype.Type(0), bsontype.EmbeddedDocument:
|
||||
if val.Type().Elem() != tE {
|
||||
return fmt.Errorf("cannot decode document into %s", val.Type())
|
||||
@@ -149,8 +152,8 @@ func (sc *SliceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val r
|
||||
}
|
||||
return nil
|
||||
case bsontype.String:
|
||||
if val.Type().Elem() != tByte {
|
||||
return fmt.Errorf("SliceDecodeValue can only decode a string into a byte array, got %v", vrType)
|
||||
if sliceType := val.Type().Elem(); sliceType != tByte {
|
||||
return fmt.Errorf("SliceDecodeValue can only decode a string into a byte array, got %v", sliceType)
|
||||
}
|
||||
str, err := vr.ReadString()
|
||||
if err != nil {
|
||||
|
||||
55
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/string_codec.go
generated
vendored
55
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/string_codec.go
generated
vendored
@@ -15,14 +15,17 @@ import (
|
||||
"go.mongodb.org/mongo-driver/bson/bsontype"
|
||||
)
|
||||
|
||||
var defaultStringCodec = NewStringCodec()
|
||||
|
||||
// StringCodec is the Codec used for struct values.
|
||||
type StringCodec struct {
|
||||
DecodeObjectIDAsHex bool
|
||||
}
|
||||
|
||||
var _ ValueCodec = &StringCodec{}
|
||||
var (
|
||||
defaultStringCodec = NewStringCodec()
|
||||
|
||||
_ ValueCodec = defaultStringCodec
|
||||
_ typeDecoder = defaultStringCodec
|
||||
)
|
||||
|
||||
// NewStringCodec returns a StringCodec with options opts.
|
||||
func NewStringCodec(opts ...*bsonoptions.StringCodecOptions) *StringCodec {
|
||||
@@ -43,23 +46,27 @@ func (sc *StringCodec) EncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, va
|
||||
return vw.WriteString(val.String())
|
||||
}
|
||||
|
||||
// DecodeValue is the ValueDecoder for string types.
|
||||
func (sc *StringCodec) DecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
|
||||
if !val.CanSet() || val.Kind() != reflect.String {
|
||||
return ValueDecoderError{Name: "StringDecodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val}
|
||||
func (sc *StringCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) {
|
||||
if t.Kind() != reflect.String {
|
||||
return emptyValue, ValueDecoderError{
|
||||
Name: "StringDecodeValue",
|
||||
Kinds: []reflect.Kind{reflect.String},
|
||||
Received: reflect.Zero(t),
|
||||
}
|
||||
}
|
||||
|
||||
var str string
|
||||
var err error
|
||||
switch vr.Type() {
|
||||
case bsontype.String:
|
||||
str, err = vr.ReadString()
|
||||
if err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
case bsontype.ObjectID:
|
||||
oid, err := vr.ReadObjectID()
|
||||
if err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
if sc.DecodeObjectIDAsHex {
|
||||
str = oid.Hex()
|
||||
@@ -70,25 +77,43 @@ func (sc *StringCodec) DecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, va
|
||||
case bsontype.Symbol:
|
||||
str, err = vr.ReadSymbol()
|
||||
if err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
case bsontype.Binary:
|
||||
data, subtype, err := vr.ReadBinary()
|
||||
if err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
if subtype != bsontype.BinaryGeneric && subtype != bsontype.BinaryBinaryOld {
|
||||
return fmt.Errorf("SliceDecodeValue can only be used to decode subtype 0x00 or 0x02 for %s, got %v", bsontype.Binary, subtype)
|
||||
return emptyValue, decodeBinaryError{subtype: subtype, typeName: "string"}
|
||||
}
|
||||
str = string(data)
|
||||
case bsontype.Null:
|
||||
if err = vr.ReadNull(); err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
case bsontype.Undefined:
|
||||
if err = vr.ReadUndefined(); err != nil {
|
||||
return emptyValue, err
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("cannot decode %v into a string type", vr.Type())
|
||||
return emptyValue, fmt.Errorf("cannot decode %v into a string type", vr.Type())
|
||||
}
|
||||
|
||||
val.SetString(str)
|
||||
return reflect.ValueOf(str), nil
|
||||
}
|
||||
|
||||
// DecodeValue is the ValueDecoder for string types.
|
||||
func (sc *StringCodec) DecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
|
||||
if !val.CanSet() || val.Kind() != reflect.String {
|
||||
return ValueDecoderError{Name: "StringDecodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val}
|
||||
}
|
||||
|
||||
elem, err := sc.decodeType(dctx, vr, val.Type())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
val.SetString(elem.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
198
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_codec.go
generated
vendored
198
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_codec.go
generated
vendored
@@ -10,6 +10,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -19,9 +20,35 @@ import (
|
||||
"go.mongodb.org/mongo-driver/bson/bsontype"
|
||||
)
|
||||
|
||||
var defaultStructCodec = &StructCodec{
|
||||
cache: make(map[reflect.Type]*structDescription),
|
||||
parser: DefaultStructTagParser,
|
||||
// DecodeError represents an error that occurs when unmarshalling BSON bytes into a native Go type.
|
||||
type DecodeError struct {
|
||||
keys []string
|
||||
wrapped error
|
||||
}
|
||||
|
||||
// Unwrap returns the underlying error
|
||||
func (de *DecodeError) Unwrap() error {
|
||||
return de.wrapped
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (de *DecodeError) Error() string {
|
||||
// The keys are stored in reverse order because the de.keys slice is builtup while propagating the error up the
|
||||
// stack of BSON keys, so we call de.Keys(), which reverses them.
|
||||
keyPath := strings.Join(de.Keys(), ".")
|
||||
return fmt.Sprintf("error decoding key %s: %v", keyPath, de.wrapped)
|
||||
}
|
||||
|
||||
// Keys returns the BSON key path that caused an error as a slice of strings. The keys in the slice are in top-down
|
||||
// order. For example, if the document being unmarshalled was {a: {b: {c: 1}}} and the value for c was supposed to be
|
||||
// a string, the keys slice will be ["a", "b", "c"].
|
||||
func (de *DecodeError) Keys() []string {
|
||||
reversedKeys := make([]string, 0, len(de.keys))
|
||||
for idx := len(de.keys) - 1; idx >= 0; idx-- {
|
||||
reversedKeys = append(reversedKeys, de.keys[idx])
|
||||
}
|
||||
|
||||
return reversedKeys
|
||||
}
|
||||
|
||||
// Zeroer allows custom struct types to implement a report of zero
|
||||
@@ -33,13 +60,14 @@ type Zeroer interface {
|
||||
|
||||
// StructCodec is the Codec used for struct values.
|
||||
type StructCodec struct {
|
||||
cache map[reflect.Type]*structDescription
|
||||
l sync.RWMutex
|
||||
parser StructTagParser
|
||||
DecodeZeroStruct bool
|
||||
DecodeDeepZeroInline bool
|
||||
EncodeOmitDefaultStruct bool
|
||||
AllowUnexportedFields bool
|
||||
cache map[reflect.Type]*structDescription
|
||||
l sync.RWMutex
|
||||
parser StructTagParser
|
||||
DecodeZeroStruct bool
|
||||
DecodeDeepZeroInline bool
|
||||
EncodeOmitDefaultStruct bool
|
||||
AllowUnexportedFields bool
|
||||
OverwriteDuplicatedInlinedFields bool
|
||||
}
|
||||
|
||||
var _ ValueEncoder = &StructCodec{}
|
||||
@@ -67,6 +95,9 @@ func NewStructCodec(p StructTagParser, opts ...*bsonoptions.StructCodecOptions)
|
||||
if structOpt.EncodeOmitDefaultStruct != nil {
|
||||
codec.EncodeOmitDefaultStruct = *structOpt.EncodeOmitDefaultStruct
|
||||
}
|
||||
if structOpt.OverwriteDuplicatedInlinedFields != nil {
|
||||
codec.OverwriteDuplicatedInlinedFields = *structOpt.OverwriteDuplicatedInlinedFields
|
||||
}
|
||||
if structOpt.AllowUnexportedFields != nil {
|
||||
codec.AllowUnexportedFields = *structOpt.AllowUnexportedFields
|
||||
}
|
||||
@@ -166,6 +197,19 @@ func (sc *StructCodec) EncodeValue(r EncodeContext, vw bsonrw.ValueWriter, val r
|
||||
return dw.WriteDocumentEnd()
|
||||
}
|
||||
|
||||
func newDecodeError(key string, original error) error {
|
||||
de, ok := original.(*DecodeError)
|
||||
if !ok {
|
||||
return &DecodeError{
|
||||
keys: []string{key},
|
||||
wrapped: original,
|
||||
}
|
||||
}
|
||||
|
||||
de.keys = append(de.keys, key)
|
||||
return de
|
||||
}
|
||||
|
||||
// DecodeValue implements the Codec interface.
|
||||
// By default, map types in val will not be cleared. If a map has existing key/value pairs, it will be extended with the new ones from vr.
|
||||
// For slices, the decoder will set the length of the slice to zero and append all elements. The underlying array will not be cleared.
|
||||
@@ -181,6 +225,13 @@ func (sc *StructCodec) DecodeValue(r DecodeContext, vr bsonrw.ValueReader, val r
|
||||
return err
|
||||
}
|
||||
|
||||
val.Set(reflect.Zero(val.Type()))
|
||||
return nil
|
||||
case bsontype.Undefined:
|
||||
if err := vr.ReadUndefined(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
val.Set(reflect.Zero(val.Type()))
|
||||
return nil
|
||||
default:
|
||||
@@ -267,7 +318,8 @@ func (sc *StructCodec) DecodeValue(r DecodeContext, vr bsonrw.ValueReader, val r
|
||||
}
|
||||
|
||||
if !field.CanSet() { // Being settable is a super set of being addressable.
|
||||
return fmt.Errorf("cannot decode element '%s' into field %v; it is not settable", name, field)
|
||||
innerErr := fmt.Errorf("field %v is not settable", field)
|
||||
return newDecodeError(fd.name, innerErr)
|
||||
}
|
||||
if field.Kind() == reflect.Ptr && field.IsNil() {
|
||||
field.Set(reflect.New(field.Type().Elem()))
|
||||
@@ -276,19 +328,12 @@ func (sc *StructCodec) DecodeValue(r DecodeContext, vr bsonrw.ValueReader, val r
|
||||
|
||||
dctx := DecodeContext{Registry: r.Registry, Truncate: fd.truncate || r.Truncate}
|
||||
if fd.decoder == nil {
|
||||
return ErrNoDecoder{Type: field.Elem().Type()}
|
||||
return newDecodeError(fd.name, ErrNoDecoder{Type: field.Elem().Type()})
|
||||
}
|
||||
|
||||
if decoder, ok := fd.decoder.(ValueDecoder); ok {
|
||||
err = decoder.DecodeValue(dctx, vr, field.Elem())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
err = fd.decoder.DecodeValue(dctx, vr, field)
|
||||
err = fd.decoder.DecodeValue(dctx, vr, field.Elem())
|
||||
if err != nil {
|
||||
return err
|
||||
return newDecodeError(fd.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -350,7 +395,8 @@ type structDescription struct {
|
||||
}
|
||||
|
||||
type fieldDescription struct {
|
||||
name string
|
||||
name string // BSON key name
|
||||
fieldName string // struct field name
|
||||
idx int
|
||||
omitEmpty bool
|
||||
minSize bool
|
||||
@@ -360,6 +406,35 @@ type fieldDescription struct {
|
||||
decoder ValueDecoder
|
||||
}
|
||||
|
||||
type byIndex []fieldDescription
|
||||
|
||||
func (bi byIndex) Len() int { return len(bi) }
|
||||
|
||||
func (bi byIndex) Swap(i, j int) { bi[i], bi[j] = bi[j], bi[i] }
|
||||
|
||||
func (bi byIndex) Less(i, j int) bool {
|
||||
// If a field is inlined, its index in the top level struct is stored at inline[0]
|
||||
iIdx, jIdx := bi[i].idx, bi[j].idx
|
||||
if len(bi[i].inline) > 0 {
|
||||
iIdx = bi[i].inline[0]
|
||||
}
|
||||
if len(bi[j].inline) > 0 {
|
||||
jIdx = bi[j].inline[0]
|
||||
}
|
||||
if iIdx != jIdx {
|
||||
return iIdx < jIdx
|
||||
}
|
||||
for k, biik := range bi[i].inline {
|
||||
if k >= len(bi[j].inline) {
|
||||
return false
|
||||
}
|
||||
if biik != bi[j].inline[k] {
|
||||
return biik < bi[j].inline[k]
|
||||
}
|
||||
}
|
||||
return len(bi[i].inline) < len(bi[j].inline)
|
||||
}
|
||||
|
||||
func (sc *StructCodec) describeStruct(r *Registry, t reflect.Type) (*structDescription, error) {
|
||||
// We need to analyze the struct, including getting the tags, collecting
|
||||
// information about inlining, and create a map of the field name to the field.
|
||||
@@ -377,6 +452,7 @@ func (sc *StructCodec) describeStruct(r *Registry, t reflect.Type) (*structDescr
|
||||
inlineMap: -1,
|
||||
}
|
||||
|
||||
var fields []fieldDescription
|
||||
for i := 0; i < numFields; i++ {
|
||||
sf := t.Field(i)
|
||||
if sf.PkgPath != "" && (!sc.AllowUnexportedFields || !sf.Anonymous) {
|
||||
@@ -394,7 +470,12 @@ func (sc *StructCodec) describeStruct(r *Registry, t reflect.Type) (*structDescr
|
||||
decoder = nil
|
||||
}
|
||||
|
||||
description := fieldDescription{idx: i, encoder: encoder, decoder: decoder}
|
||||
description := fieldDescription{
|
||||
fieldName: sf.Name,
|
||||
idx: i,
|
||||
encoder: encoder,
|
||||
decoder: decoder,
|
||||
}
|
||||
|
||||
stags, err := sc.parser.ParseStructTags(sf)
|
||||
if err != nil {
|
||||
@@ -431,31 +512,62 @@ func (sc *StructCodec) describeStruct(r *Registry, t reflect.Type) (*structDescr
|
||||
return nil, err
|
||||
}
|
||||
for _, fd := range inlinesf.fl {
|
||||
if _, exists := sd.fm[fd.name]; exists {
|
||||
return nil, fmt.Errorf("(struct %s) duplicated key %s", t.String(), fd.name)
|
||||
}
|
||||
if fd.inline == nil {
|
||||
fd.inline = []int{i, fd.idx}
|
||||
} else {
|
||||
fd.inline = append([]int{i}, fd.inline...)
|
||||
}
|
||||
sd.fm[fd.name] = fd
|
||||
sd.fl = append(sd.fl, fd)
|
||||
fields = append(fields, fd)
|
||||
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("(struct %s) inline fields must be a struct, a struct pointer, or a map", t.String())
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if _, exists := sd.fm[description.name]; exists {
|
||||
return nil, fmt.Errorf("struct %s) duplicated key %s", t.String(), description.name)
|
||||
}
|
||||
|
||||
sd.fm[description.name] = description
|
||||
sd.fl = append(sd.fl, description)
|
||||
fields = append(fields, description)
|
||||
}
|
||||
|
||||
// Sort fieldDescriptions by name and use dominance rules to determine which should be added for each name
|
||||
sort.Slice(fields, func(i, j int) bool {
|
||||
x := fields
|
||||
// sort field by name, breaking ties with depth, then
|
||||
// breaking ties with index sequence.
|
||||
if x[i].name != x[j].name {
|
||||
return x[i].name < x[j].name
|
||||
}
|
||||
if len(x[i].inline) != len(x[j].inline) {
|
||||
return len(x[i].inline) < len(x[j].inline)
|
||||
}
|
||||
return byIndex(x).Less(i, j)
|
||||
})
|
||||
|
||||
for advance, i := 0, 0; i < len(fields); i += advance {
|
||||
// One iteration per name.
|
||||
// Find the sequence of fields with the name of this first field.
|
||||
fi := fields[i]
|
||||
name := fi.name
|
||||
for advance = 1; i+advance < len(fields); advance++ {
|
||||
fj := fields[i+advance]
|
||||
if fj.name != name {
|
||||
break
|
||||
}
|
||||
}
|
||||
if advance == 1 { // Only one field with this name
|
||||
sd.fl = append(sd.fl, fi)
|
||||
sd.fm[name] = fi
|
||||
continue
|
||||
}
|
||||
dominant, ok := dominantField(fields[i : i+advance])
|
||||
if !ok || !sc.OverwriteDuplicatedInlinedFields {
|
||||
return nil, fmt.Errorf("struct %s has duplicated key %s", t.String(), name)
|
||||
}
|
||||
sd.fl = append(sd.fl, dominant)
|
||||
sd.fm[name] = dominant
|
||||
}
|
||||
|
||||
sort.Sort(byIndex(sd.fl))
|
||||
|
||||
sc.l.Lock()
|
||||
sc.cache[t] = sd
|
||||
sc.l.Unlock()
|
||||
@@ -463,6 +575,22 @@ func (sc *StructCodec) describeStruct(r *Registry, t reflect.Type) (*structDescr
|
||||
return sd, nil
|
||||
}
|
||||
|
||||
// dominantField looks through the fields, all of which are known to
|
||||
// have the same name, to find the single field that dominates the
|
||||
// others using Go's inlining rules. If there are multiple top-level
|
||||
// fields, the boolean will be false: This condition is an error in Go
|
||||
// and we skip all the fields.
|
||||
func dominantField(fields []fieldDescription) (fieldDescription, bool) {
|
||||
// The fields are sorted in increasing index-length order, then by presence of tag.
|
||||
// That means that the first field is the dominant one. We need only check
|
||||
// for error cases: two fields at top level.
|
||||
if len(fields) > 1 &&
|
||||
len(fields[0].inline) == len(fields[1].inline) {
|
||||
return fieldDescription{}, false
|
||||
}
|
||||
return fields[0], true
|
||||
}
|
||||
|
||||
func fieldByIndexErr(v reflect.Value, index []int) (result reflect.Value, err error) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
|
||||
62
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_tag_parser.go
generated
vendored
62
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_tag_parser.go
generated
vendored
@@ -34,21 +34,21 @@ func (stpf StructTagParserFunc) ParseStructTags(sf reflect.StructField) (StructT
|
||||
//
|
||||
// The properties are defined below:
|
||||
//
|
||||
// OmitEmpty Only include the field if it's not set to the zero value for the type or to
|
||||
// empty slices or maps.
|
||||
// OmitEmpty Only include the field if it's not set to the zero value for the type or to
|
||||
// empty slices or maps.
|
||||
//
|
||||
// MinSize Marshal an integer of a type larger than 32 bits value as an int32, if that's
|
||||
// feasible while preserving the numeric value.
|
||||
// MinSize Marshal an integer of a type larger than 32 bits value as an int32, if that's
|
||||
// feasible while preserving the numeric value.
|
||||
//
|
||||
// Truncate When unmarshaling a BSON double, it is permitted to lose precision to fit within
|
||||
// a float32.
|
||||
// Truncate When unmarshaling a BSON double, it is permitted to lose precision to fit within
|
||||
// a float32.
|
||||
//
|
||||
// Inline Inline the field, which must be a struct or a map, causing all of its fields
|
||||
// or keys to be processed as if they were part of the outer struct. For maps,
|
||||
// keys must not conflict with the bson keys of other struct fields.
|
||||
// Inline Inline the field, which must be a struct or a map, causing all of its fields
|
||||
// or keys to be processed as if they were part of the outer struct. For maps,
|
||||
// keys must not conflict with the bson keys of other struct fields.
|
||||
//
|
||||
// Skip This struct field should be skipped. This is usually denoted by parsing a "-"
|
||||
// for the name.
|
||||
// Skip This struct field should be skipped. This is usually denoted by parsing a "-"
|
||||
// for the name.
|
||||
//
|
||||
// TODO(skriptble): Add tags for undefined as nil and for null as nil.
|
||||
type StructTags struct {
|
||||
@@ -67,20 +67,20 @@ type StructTags struct {
|
||||
// If there is no name in the struct tag fields, the struct field name is lowercased.
|
||||
// The tag formats accepted are:
|
||||
//
|
||||
// "[<key>][,<flag1>[,<flag2>]]"
|
||||
// "[<key>][,<flag1>[,<flag2>]]"
|
||||
//
|
||||
// `(...) bson:"[<key>][,<flag1>[,<flag2>]]" (...)`
|
||||
// `(...) bson:"[<key>][,<flag1>[,<flag2>]]" (...)`
|
||||
//
|
||||
// An example:
|
||||
//
|
||||
// type T struct {
|
||||
// A bool
|
||||
// B int "myb"
|
||||
// C string "myc,omitempty"
|
||||
// D string `bson:",omitempty" json:"jsonkey"`
|
||||
// E int64 ",minsize"
|
||||
// F int64 "myf,omitempty,minsize"
|
||||
// }
|
||||
// type T struct {
|
||||
// A bool
|
||||
// B int "myb"
|
||||
// C string "myc,omitempty"
|
||||
// D string `bson:",omitempty" json:"jsonkey"`
|
||||
// E int64 ",minsize"
|
||||
// F int64 "myf,omitempty,minsize"
|
||||
// }
|
||||
//
|
||||
// A struct tag either consisting entirely of '-' or with a bson key with a
|
||||
// value consisting entirely of '-' will return a StructTags with Skip true and
|
||||
@@ -91,6 +91,10 @@ var DefaultStructTagParser StructTagParserFunc = func(sf reflect.StructField) (S
|
||||
if !ok && !strings.Contains(string(sf.Tag), ":") && len(sf.Tag) > 0 {
|
||||
tag = string(sf.Tag)
|
||||
}
|
||||
return parseTags(key, tag)
|
||||
}
|
||||
|
||||
func parseTags(key string, tag string) (StructTags, error) {
|
||||
var st StructTags
|
||||
if tag == "-" {
|
||||
st.Skip = true
|
||||
@@ -117,3 +121,19 @@ var DefaultStructTagParser StructTagParserFunc = func(sf reflect.StructField) (S
|
||||
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// JSONFallbackStructTagParser has the same behavior as DefaultStructTagParser
|
||||
// but will also fallback to parsing the json tag instead on a field where the
|
||||
// bson tag isn't available.
|
||||
var JSONFallbackStructTagParser StructTagParserFunc = func(sf reflect.StructField) (StructTags, error) {
|
||||
key := strings.ToLower(sf.Name)
|
||||
tag, ok := sf.Tag.Lookup("bson")
|
||||
if !ok {
|
||||
tag, ok = sf.Tag.Lookup("json")
|
||||
}
|
||||
if !ok && !strings.Contains(string(sf.Tag), ":") && len(sf.Tag) > 0 {
|
||||
tag = string(sf.Tag)
|
||||
}
|
||||
|
||||
return parseTags(key, tag)
|
||||
}
|
||||
|
||||
58
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/time_codec.go
generated
vendored
58
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/time_codec.go
generated
vendored
@@ -14,20 +14,24 @@ import (
|
||||
"go.mongodb.org/mongo-driver/bson/bsonoptions"
|
||||
"go.mongodb.org/mongo-driver/bson/bsonrw"
|
||||
"go.mongodb.org/mongo-driver/bson/bsontype"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
)
|
||||
|
||||
const (
|
||||
timeFormatString = "2006-01-02T15:04:05.999Z07:00"
|
||||
)
|
||||
|
||||
var defaultTimeCodec = NewTimeCodec()
|
||||
|
||||
// TimeCodec is the Codec used for time.Time values.
|
||||
type TimeCodec struct {
|
||||
UseLocalTimeZone bool
|
||||
}
|
||||
|
||||
var _ ValueCodec = &TimeCodec{}
|
||||
var (
|
||||
defaultTimeCodec = NewTimeCodec()
|
||||
|
||||
_ ValueCodec = defaultTimeCodec
|
||||
_ typeDecoder = defaultTimeCodec
|
||||
)
|
||||
|
||||
// NewTimeCodec returns a TimeCodec with options opts.
|
||||
func NewTimeCodec(opts ...*bsonoptions.TimeCodecOptions) *TimeCodec {
|
||||
@@ -40,10 +44,13 @@ func NewTimeCodec(opts ...*bsonoptions.TimeCodecOptions) *TimeCodec {
|
||||
return &codec
|
||||
}
|
||||
|
||||
// DecodeValue is the ValueDecoderFunc for time.Time.
|
||||
func (tc *TimeCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
|
||||
if !val.CanSet() || val.Type() != tTime {
|
||||
return ValueDecoderError{Name: "TimeDecodeValue", Types: []reflect.Type{tTime}, Received: val}
|
||||
func (tc *TimeCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) {
|
||||
if t != tTime {
|
||||
return emptyValue, ValueDecoderError{
|
||||
Name: "TimeDecodeValue",
|
||||
Types: []reflect.Type{tTime},
|
||||
Received: reflect.Zero(t),
|
||||
}
|
||||
}
|
||||
|
||||
var timeVal time.Time
|
||||
@@ -51,43 +58,61 @@ func (tc *TimeCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val re
|
||||
case bsontype.DateTime:
|
||||
dt, err := vr.ReadDateTime()
|
||||
if err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
timeVal = time.Unix(dt/1000, dt%1000*1000000)
|
||||
case bsontype.String:
|
||||
// assume strings are in the isoTimeFormat
|
||||
timeStr, err := vr.ReadString()
|
||||
if err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
timeVal, err = time.Parse(timeFormatString, timeStr)
|
||||
if err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
case bsontype.Int64:
|
||||
i64, err := vr.ReadInt64()
|
||||
if err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
timeVal = time.Unix(i64/1000, i64%1000*1000000)
|
||||
case bsontype.Timestamp:
|
||||
t, _, err := vr.ReadTimestamp()
|
||||
if err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
timeVal = time.Unix(int64(t), 0)
|
||||
case bsontype.Null:
|
||||
if err := vr.ReadNull(); err != nil {
|
||||
return err
|
||||
return emptyValue, err
|
||||
}
|
||||
case bsontype.Undefined:
|
||||
if err := vr.ReadUndefined(); err != nil {
|
||||
return emptyValue, err
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("cannot decode %v into a time.Time", vrType)
|
||||
return emptyValue, fmt.Errorf("cannot decode %v into a time.Time", vrType)
|
||||
}
|
||||
|
||||
if !tc.UseLocalTimeZone {
|
||||
timeVal = timeVal.UTC()
|
||||
}
|
||||
val.Set(reflect.ValueOf(timeVal))
|
||||
return reflect.ValueOf(timeVal), nil
|
||||
}
|
||||
|
||||
// DecodeValue is the ValueDecoderFunc for time.Time.
|
||||
func (tc *TimeCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
|
||||
if !val.CanSet() || val.Type() != tTime {
|
||||
return ValueDecoderError{Name: "TimeDecodeValue", Types: []reflect.Type{tTime}, Received: val}
|
||||
}
|
||||
|
||||
elem, err := tc.decodeType(dc, vr, tTime)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
val.Set(elem)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -97,5 +122,6 @@ func (tc *TimeCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val re
|
||||
return ValueEncoderError{Name: "TimeEncodeValue", Types: []reflect.Type{tTime}, Received: val}
|
||||
}
|
||||
tt := val.Interface().(time.Time)
|
||||
return vw.WriteDateTime(tt.Unix()*1000 + int64(tt.Nanosecond()/1e6))
|
||||
dt := primitive.NewDateTimeFromTime(tt)
|
||||
return vw.WriteDateTime(int64(dt))
|
||||
}
|
||||
|
||||
26
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/types.go
generated
vendored
26
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/types.go
generated
vendored
@@ -16,36 +16,12 @@ import (
|
||||
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
|
||||
)
|
||||
|
||||
var ptBool = reflect.TypeOf((*bool)(nil))
|
||||
var ptInt8 = reflect.TypeOf((*int8)(nil))
|
||||
var ptInt16 = reflect.TypeOf((*int16)(nil))
|
||||
var ptInt32 = reflect.TypeOf((*int32)(nil))
|
||||
var ptInt64 = reflect.TypeOf((*int64)(nil))
|
||||
var ptInt = reflect.TypeOf((*int)(nil))
|
||||
var ptUint8 = reflect.TypeOf((*uint8)(nil))
|
||||
var ptUint16 = reflect.TypeOf((*uint16)(nil))
|
||||
var ptUint32 = reflect.TypeOf((*uint32)(nil))
|
||||
var ptUint64 = reflect.TypeOf((*uint64)(nil))
|
||||
var ptUint = reflect.TypeOf((*uint)(nil))
|
||||
var ptFloat32 = reflect.TypeOf((*float32)(nil))
|
||||
var ptFloat64 = reflect.TypeOf((*float64)(nil))
|
||||
var ptString = reflect.TypeOf((*string)(nil))
|
||||
|
||||
var tBool = reflect.TypeOf(false)
|
||||
var tFloat32 = reflect.TypeOf(float32(0))
|
||||
var tFloat64 = reflect.TypeOf(float64(0))
|
||||
var tInt = reflect.TypeOf(int(0))
|
||||
var tInt8 = reflect.TypeOf(int8(0))
|
||||
var tInt16 = reflect.TypeOf(int16(0))
|
||||
var tInt32 = reflect.TypeOf(int32(0))
|
||||
var tInt64 = reflect.TypeOf(int64(0))
|
||||
var tString = reflect.TypeOf("")
|
||||
var tTime = reflect.TypeOf(time.Time{})
|
||||
var tUint = reflect.TypeOf(uint(0))
|
||||
var tUint8 = reflect.TypeOf(uint8(0))
|
||||
var tUint16 = reflect.TypeOf(uint16(0))
|
||||
var tUint32 = reflect.TypeOf(uint32(0))
|
||||
var tUint64 = reflect.TypeOf(uint64(0))
|
||||
|
||||
var tEmpty = reflect.TypeOf((*interface{})(nil)).Elem()
|
||||
var tByteSlice = reflect.TypeOf([]byte(nil))
|
||||
@@ -74,8 +50,8 @@ var tDecimal = reflect.TypeOf(primitive.Decimal128{})
|
||||
var tMinKey = reflect.TypeOf(primitive.MinKey{})
|
||||
var tMaxKey = reflect.TypeOf(primitive.MaxKey{})
|
||||
var tD = reflect.TypeOf(primitive.D{})
|
||||
var tM = reflect.TypeOf(primitive.M{})
|
||||
var tA = reflect.TypeOf(primitive.A{})
|
||||
var tE = reflect.TypeOf(primitive.E{})
|
||||
|
||||
var tCoreDocument = reflect.TypeOf(bsoncore.Document{})
|
||||
var tCoreArray = reflect.TypeOf(bsoncore.Array{})
|
||||
|
||||
171
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/uint_codec.go
generated
vendored
171
vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/uint_codec.go
generated
vendored
@@ -7,7 +7,6 @@
|
||||
package bsoncodec
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"reflect"
|
||||
@@ -17,14 +16,17 @@ import (
|
||||
"go.mongodb.org/mongo-driver/bson/bsontype"
|
||||
)
|
||||
|
||||
var defaultUIntCodec = NewUIntCodec()
|
||||
|
||||
// UIntCodec is the Codec used for uint values.
|
||||
type UIntCodec struct {
|
||||
EncodeToMinSize bool
|
||||
}
|
||||
|
||||
var _ ValueCodec = &UIntCodec{}
|
||||
var (
|
||||
defaultUIntCodec = NewUIntCodec()
|
||||
|
||||
_ ValueCodec = defaultUIntCodec
|
||||
_ typeDecoder = defaultUIntCodec
|
||||
)
|
||||
|
||||
// NewUIntCodec returns a UIntCodec with options opts.
|
||||
func NewUIntCodec(opts ...*bsonoptions.UIntCodecOptions) *UIntCodec {
|
||||
@@ -64,6 +66,93 @@ func (uic *UIntCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val r
|
||||
}
|
||||
}
|
||||
|
||||
func (uic *UIntCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) {
|
||||
var i64 int64
|
||||
var err error
|
||||
switch vrType := vr.Type(); vrType {
|
||||
case bsontype.Int32:
|
||||
i32, err := vr.ReadInt32()
|
||||
if err != nil {
|
||||
return emptyValue, err
|
||||
}
|
||||
i64 = int64(i32)
|
||||
case bsontype.Int64:
|
||||
i64, err = vr.ReadInt64()
|
||||
if err != nil {
|
||||
return emptyValue, err
|
||||
}
|
||||
case bsontype.Double:
|
||||
f64, err := vr.ReadDouble()
|
||||
if err != nil {
|
||||
return emptyValue, err
|
||||
}
|
||||
if !dc.Truncate && math.Floor(f64) != f64 {
|
||||
return emptyValue, errCannotTruncate
|
||||
}
|
||||
if f64 > float64(math.MaxInt64) {
|
||||
return emptyValue, fmt.Errorf("%g overflows int64", f64)
|
||||
}
|
||||
i64 = int64(f64)
|
||||
case bsontype.Boolean:
|
||||
b, err := vr.ReadBoolean()
|
||||
if err != nil {
|
||||
return emptyValue, err
|
||||
}
|
||||
if b {
|
||||
i64 = 1
|
||||
}
|
||||
case bsontype.Null:
|
||||
if err = vr.ReadNull(); err != nil {
|
||||
return emptyValue, err
|
||||
}
|
||||
case bsontype.Undefined:
|
||||
if err = vr.ReadUndefined(); err != nil {
|
||||
return emptyValue, err
|
||||
}
|
||||
default:
|
||||
return emptyValue, fmt.Errorf("cannot decode %v into an integer type", vrType)
|
||||
}
|
||||
|
||||
switch t.Kind() {
|
||||
case reflect.Uint8:
|
||||
if i64 < 0 || i64 > math.MaxUint8 {
|
||||
return emptyValue, fmt.Errorf("%d overflows uint8", i64)
|
||||
}
|
||||
|
||||
return reflect.ValueOf(uint8(i64)), nil
|
||||
case reflect.Uint16:
|
||||
if i64 < 0 || i64 > math.MaxUint16 {
|
||||
return emptyValue, fmt.Errorf("%d overflows uint16", i64)
|
||||
}
|
||||
|
||||
return reflect.ValueOf(uint16(i64)), nil
|
||||
case reflect.Uint32:
|
||||
if i64 < 0 || i64 > math.MaxUint32 {
|
||||
return emptyValue, fmt.Errorf("%d overflows uint32", i64)
|
||||
}
|
||||
|
||||
return reflect.ValueOf(uint32(i64)), nil
|
||||
case reflect.Uint64:
|
||||
if i64 < 0 {
|
||||
return emptyValue, fmt.Errorf("%d overflows uint64", i64)
|
||||
}
|
||||
|
||||
return reflect.ValueOf(uint64(i64)), nil
|
||||
case reflect.Uint:
|
||||
if i64 < 0 || int64(uint(i64)) != i64 { // Can we fit this inside of an uint
|
||||
return emptyValue, fmt.Errorf("%d overflows uint", i64)
|
||||
}
|
||||
|
||||
return reflect.ValueOf(uint(i64)), nil
|
||||
default:
|
||||
return emptyValue, ValueDecoderError{
|
||||
Name: "UintDecodeValue",
|
||||
Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint},
|
||||
Received: reflect.Zero(t),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DecodeValue is the ValueDecoder for uint types.
|
||||
func (uic *UIntCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
|
||||
if !val.CanSet() {
|
||||
@@ -74,77 +163,11 @@ func (uic *UIntCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val r
|
||||
}
|
||||
}
|
||||
|
||||
var i64 int64
|
||||
var err error
|
||||
switch vrType := vr.Type(); vrType {
|
||||
case bsontype.Int32:
|
||||
i32, err := vr.ReadInt32()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
i64 = int64(i32)
|
||||
case bsontype.Int64:
|
||||
i64, err = vr.ReadInt64()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case bsontype.Double:
|
||||
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 bsontype.Boolean:
|
||||
b, err := vr.ReadBoolean()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if b {
|
||||
i64 = 1
|
||||
}
|
||||
case bsontype.Null:
|
||||
if err = vr.ReadNull(); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("cannot decode %v into an integer type", vrType)
|
||||
elem, err := uic.decodeType(dc, vr, val.Type())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
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))
|
||||
val.SetUint(elem.Uint())
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user