diff --git a/bson/benchmark_test.go b/bson/benchmark_test.go index 2b7d6d293a..0bc89b8ce8 100644 --- a/bson/benchmark_test.go +++ b/bson/benchmark_test.go @@ -147,14 +147,14 @@ var nestedInstance = nestedtest1{ const extendedBSONDir = "../testdata/extended_bson" var ( - extJSONFiles map[string]map[string]interface{} + extJSONFiles map[string]map[string]any extJSONFilesMu sync.Mutex ) // readExtJSONFile reads the GZIP-compressed extended JSON document from the given filename in the // "extended BSON" test data directory (../testdata/extended_bson) and returns it as a -// map[string]interface{}. It panics on any errors. -func readExtJSONFile(filename string) map[string]interface{} { +// map[string]any. It panics on any errors. +func readExtJSONFile(filename string) map[string]any { extJSONFilesMu.Lock() defer extJSONFilesMu.Unlock() if v, ok := extJSONFiles[filename]; ok { @@ -182,14 +182,14 @@ func readExtJSONFile(filename string) map[string]interface{} { panic(fmt.Sprintf("error reading GZIP contents of file: %s", err)) } - var v map[string]interface{} + var v map[string]any err = UnmarshalExtJSON(data, false, &v) if err != nil { panic(fmt.Sprintf("error unmarshalling extended JSON: %s", err)) } if extJSONFiles == nil { - extJSONFiles = make(map[string]map[string]interface{}) + extJSONFiles = make(map[string]map[string]any) } extJSONFiles[filename] = v return v diff --git a/bson/bson_test.go b/bson/bson_test.go index 01aaf18934..d00306115c 100644 --- a/bson/bson_test.go +++ b/bson/bson_test.go @@ -305,7 +305,7 @@ func TestD_MarshalJSON(t *testing.T) { testcases := []struct { name string test D - expected interface{} + expected any }{ { "nil", @@ -329,21 +329,21 @@ func TestD_MarshalJSON(t *testing.T) { {"g", D{{"foo", "bar"}}}, }, struct { - A int `json:"a"` - B bool `json:"b"` - C string `json:"c"` - D interface{} `json:"d"` - E float32 `json:"e"` - F []interface{} `json:"f"` - G map[string]interface{} `json:"g"` + A int `json:"a"` + B bool `json:"b"` + C string `json:"c"` + D any `json:"d"` + E float32 `json:"e"` + F []any `json:"f"` + G map[string]any `json:"g"` }{ A: 42, B: true, C: "answer", D: nil, E: 2.71828, - F: []interface{}{42, true, "answer", nil, 2.71828}, - G: map[string]interface{}{"foo": "bar"}, + F: []any{42, true, "answer", nil, 2.71828}, + G: map[string]any{"foo": "bar"}, }, }, } @@ -400,7 +400,7 @@ func TestD_UnmarshalJSON(t *testing.T) { {"pi", 3.142}, {"boolean", true}, {"nothing", nil}, - {"list", []interface{}{"hello world", 3.142, false, nil, D{{"Lorem", "ipsum"}}}}, + {"list", []any{"hello world", 3.142, false, nil, D{{"Lorem", "ipsum"}}}}, {"document", D{{"foo", "bar"}}}, }, }, @@ -453,7 +453,7 @@ func TestD_UnmarshalJSON(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() - var a map[string]interface{} + var a map[string]any want := json.Unmarshal([]byte(tc.test), &a) var b D got := json.Unmarshal([]byte(tc.test), &b) diff --git a/bson/bsoncodec.go b/bson/bsoncodec.go index 91592a3e63..78b861a315 100644 --- a/bson/bsoncodec.go +++ b/bson/bsoncodec.go @@ -107,7 +107,7 @@ type DecodeContext struct { truncate bool // 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 + // usage for this field is restricted to data typed as "any" or "map[string]any". If DocumentType is // set to a type that a BSON document cannot be unmarshaled into (e.g. "string"), unmarshalling will result in an // error. defaultDocumentType reflect.Type diff --git a/bson/bsoncodec_test.go b/bson/bsoncodec_test.go index 57bbec8d36..7d7919f46f 100644 --- a/bson/bsoncodec_test.go +++ b/bson/bsoncodec_test.go @@ -43,12 +43,12 @@ func ExampleValueDecoder() { type llCodec struct { t *testing.T - decodeval interface{} - encodeval interface{} + decodeval any + encodeval any err error } -func (llc *llCodec) EncodeValue(_ EncodeContext, _ ValueWriter, i interface{}) error { +func (llc *llCodec) EncodeValue(_ EncodeContext, _ ValueWriter, i any) error { if llc.err != nil { return llc.err } diff --git a/bson/bsonrw_test.go b/bson/bsonrw_test.go index ea98925a09..9c449f9687 100644 --- a/bson/bsonrw_test.go +++ b/bson/bsonrw_test.go @@ -186,7 +186,7 @@ func (i invoked) String() string { type valueReaderWriter struct { T *testing.T invoked invoked - Return interface{} // Can be a primitive or a bsoncore.Value + Return any // Can be a primitive or a bsoncore.Value BSONType Type Err error ErrAfter invoked // error after this method is called diff --git a/bson/codec_cache.go b/bson/codec_cache.go index b4042822e6..de97441e1c 100644 --- a/bson/codec_cache.go +++ b/bson/codec_cache.go @@ -49,7 +49,7 @@ func (c *typeEncoderCache) LoadOrStore(rt reflect.Type, enc ValueEncoder) ValueE func (c *typeEncoderCache) Clone() *typeEncoderCache { cc := new(typeEncoderCache) - c.cache.Range(func(k, v interface{}) bool { + c.cache.Range(func(k, v any) bool { if k != nil && v != nil { cc.cache.Store(k, v) } @@ -82,7 +82,7 @@ func (c *typeDecoderCache) LoadOrStore(rt reflect.Type, dec ValueDecoder) ValueD func (c *typeDecoderCache) Clone() *typeDecoderCache { cc := new(typeDecoderCache) - c.cache.Range(func(k, v interface{}) bool { + c.cache.Range(func(k, v any) bool { if k != nil && v != nil { cc.cache.Store(k, v) } diff --git a/bson/decimal.go b/bson/decimal.go index 85c506ef8a..6241733a19 100644 --- a/bson/decimal.go +++ b/bson/decimal.go @@ -145,7 +145,7 @@ func (d *Decimal128) UnmarshalJSON(b []byte) error { return nil } - var res interface{} + var res any err := json.Unmarshal(b, &res) if err != nil { return err @@ -154,7 +154,7 @@ func (d *Decimal128) UnmarshalJSON(b []byte) error { // Extended JSON if !ok { - m, ok := res.(map[string]interface{}) + m, ok := res.(map[string]any) if !ok { return errors.New("not an extended JSON Decimal128: expected document") } diff --git a/bson/decoder.go b/bson/decoder.go index 2fa9e6f1d6..4c24dc6611 100644 --- a/bson/decoder.go +++ b/bson/decoder.go @@ -20,7 +20,7 @@ var ErrDecodeToNil = errors.New("cannot Decode to nil value") // methods and is not consumable from outside of this package. The Decoders retrieved from this pool // must have both Reset and SetRegistry called on them. var decPool = sync.Pool{ - New: func() interface{} { + New: func() any { return new(Decoder) }, } @@ -44,7 +44,7 @@ func NewDecoder(vr ValueReader) *Decoder { // value pointed to by val. // // See [Unmarshal] for details about BSON unmarshaling behavior. -func (d *Decoder) Decode(val interface{}) error { +func (d *Decoder) Decode(val any) error { if unmarshaler, ok := val.(Unmarshaler); ok { // TODO(skriptble): Reuse a []byte here and use the AppendDocumentBytes method. buf, err := copyDocumentToBytes(d.vr) @@ -88,7 +88,7 @@ func (d *Decoder) SetRegistry(r *Registry) { } // DefaultDocumentM causes the Decoder to always unmarshal documents into the bson.M type. This -// behavior is restricted to data typed as "interface{}" or "map[string]interface{}". +// behavior is restricted to data typed as "any" or "map[string]any". func (d *Decoder) DefaultDocumentM() { d.dc.defaultDocumentType = reflect.TypeOf(M{}) } diff --git a/bson/decoder_example_test.go b/bson/decoder_example_test.go index bd6a1d9145..a1db3cf867 100644 --- a/bson/decoder_example_test.go +++ b/bson/decoder_example_test.go @@ -70,8 +70,8 @@ func ExampleDecoder_DefaultDocumentM() { decoder := bson.NewDecoder(bson.NewDocumentReader(bytes.NewReader(data))) type City struct { - Name string `bson:"name"` - Properties interface{} `bson:"properties"` + Name string `bson:"name"` + Properties any `bson:"properties"` } // Configure the Decoder to default to decoding BSON documents as the M diff --git a/bson/decoder_test.go b/bson/decoder_test.go index 4179b5e4ba..68efdc6161 100644 --- a/bson/decoder_test.go +++ b/bson/decoder_test.go @@ -44,14 +44,14 @@ func TestDecodingInterfaces(t *testing.T) { type testCase struct { name string - stub func() ([]byte, interface{}, func(*testing.T)) + stub func() ([]byte, any, func(*testing.T)) } testCases := []testCase{ { name: "struct with interface containing a concrete value", - stub: func() ([]byte, interface{}, func(*testing.T)) { + stub: func() ([]byte, any, func(*testing.T)) { type testStruct struct { - Value interface{} + Value any } var value string @@ -73,13 +73,13 @@ func TestDecodingInterfaces(t *testing.T) { }, { name: "struct with interface containing a struct", - stub: func() ([]byte, interface{}, func(*testing.T)) { + stub: func() ([]byte, any, func(*testing.T)) { type demo struct { Data string } type testStruct struct { - Value interface{} + Value any } var value demo @@ -101,9 +101,9 @@ func TestDecodingInterfaces(t *testing.T) { }, { name: "struct with interface containing a slice", - stub: func() ([]byte, interface{}, func(*testing.T)) { + stub: func() ([]byte, any, func(*testing.T)) { type testStruct struct { - Values interface{} + Values any } var values []string @@ -125,9 +125,9 @@ func TestDecodingInterfaces(t *testing.T) { }, { name: "struct with interface containing an array", - stub: func() ([]byte, interface{}, func(*testing.T)) { + stub: func() ([]byte, any, func(*testing.T)) { type testStruct struct { - Values interface{} + Values any } var values [2]string @@ -149,27 +149,27 @@ func TestDecodingInterfaces(t *testing.T) { }, { name: "struct with interface array containing concrete values", - stub: func() ([]byte, interface{}, func(*testing.T)) { + stub: func() ([]byte, any, func(*testing.T)) { type testStruct struct { - Values [3]interface{} + Values [3]any } var str string var i, j int data := docToBytes(struct { - Values []interface{} + Values []any }{ - Values: []interface{}{"foo", 42, nil}, + Values: []any{"foo", 42, nil}, }) - receiver := testStruct{[3]interface{}{&str, &i, &j}} + receiver := testStruct{[3]any{&str, &i, &j}} check := func(t *testing.T) { t.Helper() assert.Equal(t, "foo", str) assert.Equal(t, 42, i) assert.Equal(t, 0, j) - assert.Equal(t, testStruct{[3]interface{}{&str, &i, nil}}, receiver) + assert.Equal(t, testStruct{[3]any{&str, &i, nil}}, receiver) } return data, &receiver, check @@ -177,22 +177,22 @@ func TestDecodingInterfaces(t *testing.T) { }, { name: "overwriting prepopulated slice", - stub: func() ([]byte, interface{}, func(*testing.T)) { + stub: func() ([]byte, any, func(*testing.T)) { type testStruct struct { - Values []interface{} + Values []any } data := docToBytes(struct { - Values []interface{} + Values []any }{ - Values: []interface{}{1, 2, 3}, + Values: []any{1, 2, 3}, }) - receiver := testStruct{[]interface{}{7, 8}} + receiver := testStruct{[]any{7, 8}} check := func(t *testing.T) { t.Helper() - assert.Equal(t, testStruct{[]interface{}{1, 2, int32(3)}}, receiver) + assert.Equal(t, testStruct{[]any{1, 2, int32(3)}}, receiver) } return data, &receiver, check @@ -478,8 +478,8 @@ func TestDecoderConfiguration(t *testing.T) { description string configure func(*Decoder) input []byte - decodeInto func() interface{} - want interface{} + decodeInto func() any + want any }{ // Test that AllowTruncatingDoubles causes the Decoder to unmarshal BSON doubles with // fractional parts into Go integer types by truncating the fractional part. @@ -500,7 +500,7 @@ func TestDecoderConfiguration(t *testing.T) { AppendDouble("myUint32", 1.999). AppendDouble("myUint64", 1.999). Build(), - decodeInto: func() interface{} { return &truncateDoublesTest{} }, + decodeInto: func() any { return &truncateDoublesTest{} }, want: &truncateDoublesTest{ MyInt: 1, MyInt8: 1, @@ -524,7 +524,7 @@ func TestDecoderConfiguration(t *testing.T) { input: bsoncore.NewDocumentBuilder(). AppendBinary("myBinary", TypeBinaryGeneric, []byte{}). Build(), - decodeInto: func() interface{} { return &D{} }, + decodeInto: func() any { return &D{} }, want: &D{{Key: "myBinary", Value: []byte{}}}, }, // Test that the default decoder always decodes BSON documents into bson.D values, @@ -537,7 +537,7 @@ func TestDecoderConfiguration(t *testing.T) { AppendString("myString", "test value"). Build()). Build(), - decodeInto: func() interface{} { return M{} }, + decodeInto: func() any { return M{} }, want: M{ "myDocument": D{{Key: "myString", Value: "test value"}}, }, @@ -554,7 +554,7 @@ func TestDecoderConfiguration(t *testing.T) { AppendString("myString", "test value"). Build()). Build(), - decodeInto: func() interface{} { return &D{} }, + decodeInto: func() any { return &D{} }, want: &D{ {Key: "myDocument", Value: M{"myString": "test value"}}, }, @@ -571,7 +571,7 @@ func TestDecoderConfiguration(t *testing.T) { return id }()). Build(), - decodeInto: func() interface{} { return &objectIDTest{} }, + decodeInto: func() any { return &objectIDTest{} }, want: &objectIDTest{ID: "5ef7fdd91c19e3222b41b839"}, }, // Test that UseJSONStructTags causes the Decoder to fall back to "json" struct tags if @@ -584,7 +584,7 @@ func TestDecoderConfiguration(t *testing.T) { input: bsoncore.NewDocumentBuilder(). AppendString("jsonFieldName", "test value"). Build(), - decodeInto: func() interface{} { return &jsonStructTest{} }, + decodeInto: func() any { return &jsonStructTest{} }, want: &jsonStructTest{StructFieldName: "test value"}, }, // Test that UseLocalTimeZone causes the Decoder to use the local time zone for decoded @@ -597,7 +597,7 @@ func TestDecoderConfiguration(t *testing.T) { input: bsoncore.NewDocumentBuilder(). AppendDateTime("myTime", 1684349179939). Build(), - decodeInto: func() interface{} { return &localTimeZoneTest{} }, + decodeInto: func() any { return &localTimeZoneTest{} }, want: &localTimeZoneTest{MyTime: time.UnixMilli(1684349179939)}, }, // Test that ZeroMaps causes the Decoder to empty any Go map values before decoding BSON @@ -612,7 +612,7 @@ func TestDecoderConfiguration(t *testing.T) { AppendString("myString", "test value"). Build()). Build(), - decodeInto: func() interface{} { + decodeInto: func() any { return &zeroMapsTest{MyMap: map[string]string{"myExtraValue": "extra value"}} }, want: &zeroMapsTest{MyMap: map[string]string{"myString": "test value"}}, @@ -627,7 +627,7 @@ func TestDecoderConfiguration(t *testing.T) { input: bsoncore.NewDocumentBuilder(). AppendString("myString", "test value"). Build(), - decodeInto: func() interface{} { + decodeInto: func() any { return &zeroStructsTest{MyInt: 1} }, want: &zeroStructsTest{MyString: "test value"}, @@ -686,7 +686,7 @@ func TestDecoderConfiguration(t *testing.T) { dec.DefaultDocumentM() - var got interface{} + var got any err := dec.Decode(&got) require.NoError(t, err, "Decode error") @@ -708,7 +708,7 @@ func TestDecoderConfiguration(t *testing.T) { dec := NewDecoder(NewDocumentReader(bytes.NewReader(input))) - var got interface{} + var got any err := dec.Decode(&got) require.NoError(t, err, "Decode error") diff --git a/bson/default_value_decoders.go b/bson/default_value_decoders.go index b7d2033999..8ce5954de7 100644 --- a/bson/default_value_decoders.go +++ b/bson/default_value_decoders.go @@ -32,8 +32,8 @@ func (d decodeBinaryError) Error() string { // registerDefaultDecoders will register the decoder methods attached to DefaultValueDecoders with // the provided RegistryBuilder. // -// 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 +// There is no support for decoding map[string]any because there is no decoder for +// any, so users must either register this decoder themselves or use the // EmptyInterfaceDecoder available in the bson package. func registerDefaultDecoders(reg *Registry) { intDecoder := decodeAdapter{intDecodeValue, intDecodeType} @@ -150,7 +150,7 @@ func dDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { return err } - var v interface{} + var v any err = decoder.DecodeValue(dc, elemVr, reflect.ValueOf(&v).Elem()) if err != nil { return err @@ -1356,7 +1356,7 @@ func decodeDefault(dc DecodeContext, vr ValueReader, val reflect.Value) ([]refle var elem reflect.Value if isInterfaceSlice && idx < val.Len() { - // Decode into an existing interface{} slot. + // Decode into an existing any slot. elem = val.Index(idx).Elem() switch { diff --git a/bson/default_value_decoders_test.go b/bson/default_value_decoders_test.go index b0e68b8f76..760ac346ba 100644 --- a/bson/default_value_decoders_test.go +++ b/bson/default_value_decoders_test.go @@ -53,7 +53,7 @@ func TestDefaultValueDecoders(t *testing.T) { type subtest struct { name string - val interface{} + val any dctx *DecodeContext llvrw *valueReaderWriter invoke invoked @@ -811,7 +811,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "wrong kind (non-string key)", - map[bool]interface{}{}, + map[bool]any{}, &DecodeContext{Registry: buildDefaultRegistry()}, &valueReaderWriter{}, readElement, @@ -819,7 +819,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "ReadDocument Error", - make(map[string]interface{}), + make(map[string]any), nil, &valueReaderWriter{Err: errors.New("rd error"), ErrAfter: readDocument}, readDocument, @@ -835,7 +835,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "ReadElement Error", - make(map[string]interface{}), + make(map[string]any), &DecodeContext{Registry: buildDefaultRegistry()}, &valueReaderWriter{Err: errors.New("re error"), ErrAfter: readElement}, readElement, @@ -851,7 +851,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "wrong BSON type", - map[string]interface{}{}, + map[string]any{}, nil, &valueReaderWriter{BSONType: TypeString}, nothing, @@ -859,7 +859,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "decode null", - (map[string]interface{})(nil), + (map[string]any)(nil), nil, &valueReaderWriter{BSONType: TypeNull}, readNull, @@ -867,7 +867,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "decode undefined", - (map[string]interface{})(nil), + (map[string]any)(nil), nil, &valueReaderWriter{BSONType: TypeUndefined}, readUndefined, @@ -901,7 +901,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "Not Type Array", - [1]interface{}{}, + [1]any{}, nil, &valueReaderWriter{BSONType: TypeString}, nothing, @@ -909,7 +909,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "ReadArray Error", - [1]interface{}{}, + [1]any{}, nil, &valueReaderWriter{Err: errors.New("ra error"), ErrAfter: readArray, BSONType: TypeArray}, readArray, @@ -999,7 +999,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "Not Type Array", - []interface{}{}, + []any{}, nil, &valueReaderWriter{BSONType: TypeInt32}, nothing, @@ -1007,7 +1007,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "ReadArray Error", - []interface{}{}, + []any{}, nil, &valueReaderWriter{Err: errors.New("ra error"), ErrAfter: readArray, BSONType: TypeArray}, readArray, @@ -2440,7 +2440,7 @@ func TestDefaultValueDecoders(t *testing.T) { llvrw = rc.llvrw } llvrw.T = t - // var got interface{} + // var got any if rc.val == cansetreflectiontest { // We're doing a CanSet reflection test err := tc.vd.DecodeValue(dc, llvrw, reflect.Value{}) if !assert.CompareErrors(err, rc.err) { @@ -2492,7 +2492,7 @@ func TestDefaultValueDecoders(t *testing.T) { if !cmp.Equal(invoked, rc.invoke) { t.Errorf("Incorrect method invoked. got %v; want %v", invoked, rc.invoke) } - var got interface{} + var got any if val.IsValid() && val.CanInterface() { got = val.Interface() } @@ -2600,7 +2600,7 @@ func TestDefaultValueDecoders(t *testing.T) { testCases := []struct { name string - value interface{} + value any b []byte err error }{ @@ -2681,8 +2681,8 @@ func TestDefaultValueDecoders(t *testing.T) { nil, }, { - "map[mystring]interface{}", - map[mystring]interface{}{"pi": 3.14159}, + "map[mystring]any", + map[mystring]any{"pi": 3.14159}, buildDocument(bsoncore.AppendDoubleElement(nil, "pi", 3.14159)), nil, }, @@ -2925,20 +2925,20 @@ func TestDefaultValueDecoders(t *testing.T) { AJ *ObjectID AK *ObjectID AL testValueUnmarshaler - AM interface{} - AN interface{} - AO interface{} + AM any + AN any + AO any AP D AQ A AR [2]E AS []byte - AT map[string]interface{} + AT map[string]any AU CodeWithScope AV M AW D - AX map[string]interface{} + AX map[string]any AY []E - AZ interface{} + AZ any }{ A: true, B: 123, @@ -2982,7 +2982,7 @@ func TestDefaultValueDecoders(t *testing.T) { AU: CodeWithScope{Code: "var hello = 'world';", Scope: D{{"pi", 3.14159}}}, AV: M{"foo": D{{"bar", "baz"}}}, AW: D{{"foo", D{{"bar", "baz"}}}}, - AX: map[string]interface{}{"foo": D{{"bar", "baz"}}}, + AX: map[string]any{"foo": D{{"bar", "baz"}}}, AY: []E{{"foo", D{{"bar", "baz"}}}}, AZ: D{{"foo", D{{"bar", "baz"}}}}, }, @@ -3043,7 +3043,7 @@ func TestDefaultValueDecoders(t *testing.T) { nil, }, { - "struct{[]interface{}}", + "struct{[]any}", struct { A []bool B []int32 @@ -3245,7 +3245,7 @@ func TestDefaultValueDecoders(t *testing.T) { t.Run("error path", func(t *testing.T) { testCases := []struct { name string - value interface{} + value any b []byte err error }{ @@ -3284,7 +3284,7 @@ func TestDefaultValueDecoders(t *testing.T) { t.Run("DecodeValue", func(t *testing.T) { testCases := []struct { name string - val interface{} + val any bsontype Type }{ { @@ -3458,7 +3458,7 @@ func TestDefaultValueDecoders(t *testing.T) { } }) - t.Run("non-interface{}", func(t *testing.T) { + t.Run("non-any", func(t *testing.T) { val := uint64(1234567890) want := ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: reflect.ValueOf(val)} got := (&emptyInterfaceCodec{}).DecodeValue(DecodeContext{}, nil, reflect.ValueOf(val)) @@ -3467,8 +3467,8 @@ func TestDefaultValueDecoders(t *testing.T) { } }) - t.Run("nil *interface{}", func(t *testing.T) { - var val interface{} + t.Run("nil *any", func(t *testing.T) { + var val any want := ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: reflect.ValueOf(val)} got := (&emptyInterfaceCodec{}).DecodeValue(DecodeContext{}, nil, reflect.ValueOf(val)) if !assert.CompareErrors(got, want) { @@ -3489,7 +3489,7 @@ func TestDefaultValueDecoders(t *testing.T) { data := bsoncore.BuildDocument(nil, bsoncore.AppendDoubleElement(nil, "pi", 3.14159)) vr := NewDocumentReader(bytes.NewReader(data)) want := D{{"pi", 3.14159}} - var got interface{} + var got any val := reflect.ValueOf(&got).Elem() err := (&emptyInterfaceCodec{}).DecodeValue(DecodeContext{Registry: buildDefaultRegistry()}, vr, val) noerr(t, err) @@ -3499,7 +3499,7 @@ func TestDefaultValueDecoders(t *testing.T) { }) t.Run("custom type map entry", func(t *testing.T) { // registering a custom type map entry for both Type(0) anad TypeEmbeddedDocument should cause - // the top-level to decode to registered type when unmarshalling to interface{} + // the top-level to decode to registered type when unmarshalling to any topLevelReg := &Registry{ typeEncoders: new(typeEncoderCache), @@ -3542,7 +3542,7 @@ func TestDefaultValueDecoders(t *testing.T) { {"embedded", embeddedReg}, } for _, tc := range testCases { - var got interface{} + var got any vr := NewDocumentReader(bytes.NewReader(doc)) val := reflect.ValueOf(&got).Elem() @@ -3601,7 +3601,7 @@ func TestDefaultValueDecoders(t *testing.T) { 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{} + // Set up a document {foo: 10} and an error that would happen if the value were decoded into any // using the registry defined above. docBytes := bsoncore.BuildDocumentFromElements( nil, @@ -3612,11 +3612,11 @@ func TestDefaultValueDecoders(t *testing.T) { wrapped: decodeValueError, } - // Set up struct definitions where Foo maps to interface{} and string. When decoded using the registry defined - // above, the interface{} struct will get an error when calling DecodeValue and the string struct will get an + // Set up struct definitions where Foo maps to any and string. When decoded using the registry defined + // above, the any struct will get an error when calling DecodeValue and the string struct will get an // error when looking up a decoder. type emptyInterfaceStruct struct { - Foo interface{} + Foo any } type stringStruct struct { Foo string @@ -3632,7 +3632,7 @@ func TestDefaultValueDecoders(t *testing.T) { // Test a deeply nested struct mixed with maps and slices. // Build document {"first": {"second": {"randomKey": {"third": [{}, {"fourth": "value"}]}}}} - type inner3 struct{ Fourth interface{} } + type inner3 struct{ Fourth any } type inner2 struct{ Third []inner3 } type inner1 struct{ Second map[string]inner2 } type outer struct{ First inner1 } @@ -3650,7 +3650,7 @@ func TestDefaultValueDecoders(t *testing.T) { inner1Doc := buildDocument(bsoncore.AppendDocumentElement(nil, "second", inner2Map)) outerDoc := buildDocument(bsoncore.AppendDocumentElement(nil, "first", inner1Doc)) - // Use a registry that has all default decoders with the custom interface{} decoder that always errors. + // Use a registry that has all default decoders with the custom any decoder that always errors. nestedRegistry := &Registry{ typeEncoders: new(typeEncoderCache), typeDecoders: new(typeDecoderCache), @@ -3666,7 +3666,7 @@ func TestDefaultValueDecoders(t *testing.T) { testCases := []struct { name string - val interface{} + val any vr ValueReader registry *Registry // buildDefaultRegistry will be used if this is nil decoder ValueDecoder @@ -3721,7 +3721,7 @@ func TestDefaultValueDecoders(t *testing.T) { { // DecodeValue error when decoding into a map. "map", - map[string]interface{}{}, + map[string]any{}, NewDocumentReader(bytes.NewReader(docBytes)), emptyInterfaceErrorRegistry, &mapCodec{}, diff --git a/bson/default_value_encoders.go b/bson/default_value_encoders.go index bd5a20f2f9..67d464cb88 100644 --- a/bson/default_value_encoders.go +++ b/bson/default_value_encoders.go @@ -18,7 +18,7 @@ import ( ) var bvwPool = sync.Pool{ - New: func() interface{} { + New: func() any { return new(valueWriter) }, } @@ -26,7 +26,7 @@ var bvwPool = sync.Pool{ var errInvalidValue = errors.New("cannot encode invalid element") var sliceWriterPool = sync.Pool{ - New: func() interface{} { + New: func() any { sw := make(sliceWriter, 0) return &sw }, diff --git a/bson/default_value_encoders_test.go b/bson/default_value_encoders_test.go index e15019785d..3e4ef35055 100644 --- a/bson/default_value_encoders_test.go +++ b/bson/default_value_encoders_test.go @@ -63,7 +63,7 @@ func TestDefaultValueEncoders(t *testing.T) { type subtest struct { name string - val interface{} + val any ectx *EncodeContext llvrw *valueReaderWriter invoke invoked @@ -223,7 +223,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "WriteDocument Error", - map[string]interface{}{}, + map[string]any{}, nil, &valueReaderWriter{Err: errors.New("wd error"), ErrAfter: writeDocument}, writeDocument, @@ -239,7 +239,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "WriteDocumentElement Error", - map[string]interface{}{"foo": "bar"}, + map[string]any{"foo": "bar"}, &EncodeContext{Registry: buildDefaultRegistry()}, &valueReaderWriter{Err: errors.New("wde error"), ErrAfter: writeDocumentElement}, writeDocumentElement, @@ -247,7 +247,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "EncodeValue Error", - map[string]interface{}{"foo": "bar"}, + map[string]any{"foo": "bar"}, &EncodeContext{Registry: buildDefaultRegistry()}, &valueReaderWriter{Err: errors.New("ev error"), ErrAfter: writeString}, writeString, @@ -255,7 +255,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "empty map/success", - map[string]interface{}{}, + map[string]any{}, &EncodeContext{Registry: newTestRegistry()}, &valueReaderWriter{}, writeDocumentEnd, @@ -279,7 +279,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "non-string key success", - map[int]interface{}{ + map[int]any{ 1: "foobar", }, &EncodeContext{Registry: buildDefaultRegistry()}, @@ -429,7 +429,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "empty slice/success", - []interface{}{}, + []any{}, &EncodeContext{Registry: newTestRegistry()}, &valueReaderWriter{}, writeArrayEnd, @@ -1142,7 +1142,7 @@ func TestDefaultValueEncoders(t *testing.T) { testCases := []struct { name string - value interface{} + value any b []byte err error }{ @@ -1474,7 +1474,7 @@ func TestDefaultValueEncoders(t *testing.T) { AC Decimal128 AD *time.Time AE testValueMarshaler - AF map[string]interface{} + AF map[string]any AG CodeWithScope }{ A: true, @@ -1536,7 +1536,7 @@ func TestDefaultValueEncoders(t *testing.T) { nil, }, { - "struct{[]interface{}}", + "struct{[]any}", struct { A []bool B []int32 @@ -1674,7 +1674,7 @@ func TestDefaultValueEncoders(t *testing.T) { t.Run("error path", func(t *testing.T) { testCases := []struct { name string - value interface{} + value any err error }{ { diff --git a/bson/doc.go b/bson/doc.go index e59f1b4985..b346f71f05 100644 --- a/bson/doc.go +++ b/bson/doc.go @@ -74,8 +74,8 @@ // 4. A pointer field is marshaled as the underlying type if the pointer is non-nil. If the pointer is nil, it is // marshaled as a BSON null value. // -// 5. When unmarshaling, a field of type interface{} will follow the D/M type mappings listed above. BSON documents -// unmarshaled into an interface{} field will be unmarshaled as a D. +// 5. When unmarshaling, a field of type any will follow the D/M type mappings listed above. BSON documents +// unmarshaled into an any field will be unmarshaled as a D. // // The encoding of each struct field can be customized by the "bson" struct tag. The "bson" tag gives the name of the // field, followed by a comma-separated list of options. The name may be omitted in order to specify options without @@ -101,7 +101,7 @@ // 4. inline: If the inline struct tag is specified for a struct or map field, the field will be "flattened" when // marshaling and "un-flattened" when unmarshaling. This means that all of the fields in that struct/map will be // pulled up one level and will become top-level fields rather than being fields in a nested document. For example, -// if a map field named "Map" with value map[string]interface{}{"foo": "bar"} is inlined, the resulting document will +// if a map field named "Map" with value map[string]any{"foo": "bar"} is inlined, the resulting document will // be {"foo": "bar"} instead of {"map": {"foo": "bar"}}. There can only be one inlined map field in a struct. If // there are duplicated fields in the resulting document when an inlined struct is marshaled, the inlined field will // be overwritten. If there are duplicated fields in the resulting document when an inlined map is marshaled, an diff --git a/bson/empty_interface_codec.go b/bson/empty_interface_codec.go index 80d44d8c66..ae1db53f9d 100644 --- a/bson/empty_interface_codec.go +++ b/bson/empty_interface_codec.go @@ -10,7 +10,7 @@ import ( "reflect" ) -// emptyInterfaceCodec is the Codec used for interface{} values. +// emptyInterfaceCodec is the Codec used for any values. type emptyInterfaceCodec struct { // decodeBinaryAsSlice causes DecodeValue to unmarshal BSON binary field values that are the // "Generic" or "Old" BSON binary subtype as a Go byte slice instead of a Binary. @@ -22,7 +22,7 @@ type emptyInterfaceCodec struct { // collection. var _ typeDecoder = &emptyInterfaceCodec{} -// EncodeValue is the ValueEncoderFunc for interface{}. +// EncodeValue is the ValueEncoderFunc for any. func (eic *emptyInterfaceCodec) EncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tEmpty { return ValueEncoderError{Name: "EmptyInterfaceEncodeValue", Types: []reflect.Type{tEmpty}, Received: val} @@ -111,7 +111,7 @@ func (eic *emptyInterfaceCodec) decodeType(dc DecodeContext, vr ValueReader, t r return elem, nil } -// DecodeValue is the ValueDecoderFunc for interface{}. +// DecodeValue is the ValueDecoderFunc for any. func (eic *emptyInterfaceCodec) DecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tEmpty { return ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: val} diff --git a/bson/encoder.go b/bson/encoder.go index 8299e94f5f..d27bb7b598 100644 --- a/bson/encoder.go +++ b/bson/encoder.go @@ -15,7 +15,7 @@ import ( // methods and is not consumable from outside of this package. The Encoders retrieved from this pool // must have both Reset and SetRegistry called on them. var encPool = sync.Pool{ - New: func() interface{} { + New: func() any { return new(Encoder) }, } @@ -38,7 +38,7 @@ func NewEncoder(vw ValueWriter) *Encoder { // Encode writes the BSON encoding of val to the stream. // // See [Marshal] for details about BSON marshaling behavior. -func (e *Encoder) Encode(val interface{}) error { +func (e *Encoder) Encode(val any) error { if marshaler, ok := val.(Marshaler); ok { // TODO(skriptble): Should we have a MarshalAppender interface so that we can have []byte reuse? buf, err := marshaler.MarshalBSON() diff --git a/bson/encoder_test.go b/bson/encoder_test.go index af26617204..d852c0eeec 100644 --- a/bson/encoder_test.go +++ b/bson/encoder_test.go @@ -121,7 +121,7 @@ type testMarshaler struct { func (tm testMarshaler) MarshalBSON() ([]byte, error) { return tm.buf, tm.err } -func docToBytes(d interface{}) []byte { +func docToBytes(d any) []byte { b, err := Marshal(d) if err != nil { panic(err) @@ -152,7 +152,7 @@ func TestEncoderConfiguration(t *testing.T) { testCases := []struct { description string configure func(*Encoder) - input interface{} + input any want []byte wantErr error }{ diff --git a/bson/extjson_parser.go b/bson/extjson_parser.go index a63f23a295..eb536a6753 100644 --- a/bson/extjson_parser.go +++ b/bson/extjson_parser.go @@ -46,7 +46,7 @@ const ( type extJSONValue struct { t Type - v interface{} + v any } type extJSONObject struct { diff --git a/bson/extjson_parser_test.go b/bson/extjson_parser_test.go index ae6bbf7bb3..f4222e0ce4 100644 --- a/bson/extjson_parser_test.go +++ b/bson/extjson_parser_test.go @@ -71,8 +71,8 @@ func expectSpecificError(expected error) expectedErrorFunc { } } -func specificDiff(name string) func(t *testing.T, expected, actual interface{}, desc string) { - return func(t *testing.T, expected, actual interface{}, desc string) { +func specificDiff(name string) func(t *testing.T, expected, actual any, desc string) { + return func(t *testing.T, expected, actual any, desc string) { if diff := cmp.Diff(expected, actual); diff != "" { t.Helper() t.Errorf("%s: Incorrect JSON %s (-want, +got): %s\n", desc, name, diff) @@ -373,19 +373,19 @@ func TestExtJSONParserReadKeyReadValue(t *testing.T) { } } -type ejpExpectationTest func(t *testing.T, p *extJSONParser, expectedKey string, expectedType Type, expectedValue interface{}) +type ejpExpectationTest func(t *testing.T, p *extJSONParser, expectedKey string, expectedType Type, expectedValue any) type ejpTestCase struct { f ejpExpectationTest p *extJSONParser k string t Type - v interface{} + v any } // expectSingleValue is used for simple JSON types (strings, numbers, literals) and for extended JSON types that // have single key-value pairs (i.e. { "$minKey": 1 }, { "$numberLong": "42.42" }) -func expectSingleValue(t *testing.T, p *extJSONParser, expectedKey string, expectedType Type, expectedValue interface{}) { +func expectSingleValue(t *testing.T, p *extJSONParser, expectedKey string, expectedType Type, expectedValue any) { eVal := expectedValue.(*extJSONValue) k, typ, err := p.readKey() @@ -397,7 +397,7 @@ func expectSingleValue(t *testing.T, p *extJSONParser, expectedKey string, expec // expectMultipleValues is used for values that are subdocuments of known size and with known keys (such as extended // JSON types { "$timestamp": {"t": 1, "i": 1} } and { "$regularExpression": {"pattern": "", options: ""} }) -func expectMultipleValues(t *testing.T, p *extJSONParser, expectedKey string, expectedType Type, expectedValue interface{}) { +func expectMultipleValues(t *testing.T, p *extJSONParser, expectedKey string, expectedType Type, expectedValue any) { k, typ, err := p.readKey() readKeyDiff(t, expectedKey, k, expectedType, typ, err, expectNoError, expectedKey) @@ -433,7 +433,7 @@ type ejpSubDocumentTestValue struct { // expectSubDocument is used for embedded documents and code with scope types; it reads all the keys and values // in the embedded document (or scope for codeWithScope) and compares them to the expectedValue's list of (key, type, // value) triples -func expectSubDocument(t *testing.T, p *extJSONParser, expectedKey string, expectedType Type, expectedValue interface{}) { +func expectSubDocument(t *testing.T, p *extJSONParser, expectedKey string, expectedType Type, expectedValue any) { subdoc := expectedValue.(ejpSubDocumentTestValue) k, typ, err := p.readKey() @@ -469,7 +469,7 @@ func expectSubDocument(t *testing.T, p *extJSONParser, expectedKey string, expec // expectArray takes the expectedKey, ignores the expectedType, and uses the expectedValue // as a slice of (type Type, value *extJSONValue) pairs -func expectArray(t *testing.T, p *extJSONParser, expectedKey string, _ Type, expectedValue interface{}) { +func expectArray(t *testing.T, p *extJSONParser, expectedKey string, _ Type, expectedValue any) { ktvs := expectedValue.([]ejpKeyTypValTriple) k, typ, err := p.readKey() diff --git a/bson/extjson_writer_test.go b/bson/extjson_writer_test.go index 964b7f29f6..2c26c49548 100644 --- a/bson/extjson_writer_test.go +++ b/bson/extjson_writer_test.go @@ -20,108 +20,108 @@ func TestExtJSONValueWriter(t *testing.T) { oid := ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C} testCases := []struct { name string - fn interface{} - params []interface{} + fn any + params []any }{ { "WriteBinary", (*extJSONValueWriter).WriteBinary, - []interface{}{[]byte{0x01, 0x02, 0x03}}, + []any{[]byte{0x01, 0x02, 0x03}}, }, { "WriteBinaryWithSubtype (not 0x02)", (*extJSONValueWriter).WriteBinaryWithSubtype, - []interface{}{[]byte{0x01, 0x02, 0x03}, byte(0xFF)}, + []any{[]byte{0x01, 0x02, 0x03}, byte(0xFF)}, }, { "WriteBinaryWithSubtype (0x02)", (*extJSONValueWriter).WriteBinaryWithSubtype, - []interface{}{[]byte{0x01, 0x02, 0x03}, byte(0x02)}, + []any{[]byte{0x01, 0x02, 0x03}, byte(0x02)}, }, { "WriteBoolean", (*extJSONValueWriter).WriteBoolean, - []interface{}{true}, + []any{true}, }, { "WriteDBPointer", (*extJSONValueWriter).WriteDBPointer, - []interface{}{"bar", oid}, + []any{"bar", oid}, }, { "WriteDateTime", (*extJSONValueWriter).WriteDateTime, - []interface{}{int64(12345678)}, + []any{int64(12345678)}, }, { "WriteDecimal128", (*extJSONValueWriter).WriteDecimal128, - []interface{}{NewDecimal128(10, 20)}, + []any{NewDecimal128(10, 20)}, }, { "WriteDouble", (*extJSONValueWriter).WriteDouble, - []interface{}{float64(3.14159)}, + []any{float64(3.14159)}, }, { "WriteInt32", (*extJSONValueWriter).WriteInt32, - []interface{}{int32(123456)}, + []any{int32(123456)}, }, { "WriteInt64", (*extJSONValueWriter).WriteInt64, - []interface{}{int64(1234567890)}, + []any{int64(1234567890)}, }, { "WriteJavascript", (*extJSONValueWriter).WriteJavascript, - []interface{}{"var foo = 'bar';"}, + []any{"var foo = 'bar';"}, }, { "WriteMaxKey", (*extJSONValueWriter).WriteMaxKey, - []interface{}{}, + []any{}, }, { "WriteMinKey", (*extJSONValueWriter).WriteMinKey, - []interface{}{}, + []any{}, }, { "WriteNull", (*extJSONValueWriter).WriteNull, - []interface{}{}, + []any{}, }, { "WriteObjectID", (*extJSONValueWriter).WriteObjectID, - []interface{}{oid}, + []any{oid}, }, { "WriteRegex", (*extJSONValueWriter).WriteRegex, - []interface{}{"bar", "baz"}, + []any{"bar", "baz"}, }, { "WriteString", (*extJSONValueWriter).WriteString, - []interface{}{"hello, world!"}, + []any{"hello, world!"}, }, { "WriteSymbol", (*extJSONValueWriter).WriteSymbol, - []interface{}{"symbollolz"}, + []any{"symbollolz"}, }, { "WriteTimestamp", (*extJSONValueWriter).WriteTimestamp, - []interface{}{uint32(10), uint32(20)}, + []any{uint32(10), uint32(20)}, }, { "WriteUndefined", (*extJSONValueWriter).WriteUndefined, - []interface{}{}, + []any{}, }, } diff --git a/bson/fuzz_test.go b/bson/fuzz_test.go index 8b799c1271..89df946cd3 100644 --- a/bson/fuzz_test.go +++ b/bson/fuzz_test.go @@ -19,13 +19,13 @@ func FuzzDecode(f *testing.F) { seedBSONCorpus(f) f.Fuzz(func(t *testing.T, data []byte) { - for _, typ := range []func() interface{}{ - func() interface{} { return new(D) }, - func() interface{} { return new([]E) }, - func() interface{} { return new(M) }, - func() interface{} { return new(interface{}) }, - func() interface{} { return make(map[string]interface{}) }, - func() interface{} { return new([]interface{}) }, + for _, typ := range []func() any{ + func() any { return new(D) }, + func() any { return new([]E) }, + func() any { return new(M) }, + func() any { return new(any) }, + func() any { return make(map[string]any) }, + func() any { return new([]any) }, } { i := typ() if err := Unmarshal(data, i); err != nil { diff --git a/bson/json_scanner.go b/bson/json_scanner.go index b6eba79e9e..bc03915d6e 100644 --- a/bson/json_scanner.go +++ b/bson/json_scanner.go @@ -37,7 +37,7 @@ const ( type jsonToken struct { t jsonTokenType - v interface{} + v any p int } diff --git a/bson/json_scanner_test.go b/bson/json_scanner_test.go index b46d5aac9c..b5c431e581 100644 --- a/bson/json_scanner_test.go +++ b/bson/json_scanner_test.go @@ -23,7 +23,7 @@ func jttDiff(t *testing.T, expected, actual jsonTokenType, desc string) { } } -func jtvDiff(t *testing.T, expected, actual interface{}, desc string) { +func jtvDiff(t *testing.T, expected, actual any, desc string) { if diff := cmp.Diff(expected, actual); diff != "" { t.Helper() t.Errorf("%s: Incorrect JSON Token Value (-want, +got): %s\n", desc, diff) diff --git a/bson/marshal.go b/bson/marshal.go index 88a85c0ffb..71a28dab74 100644 --- a/bson/marshal.go +++ b/bson/marshal.go @@ -15,7 +15,7 @@ import ( const defaultDstCap = 256 var extjPool = sync.Pool{ - New: func() interface{} { + New: func() any { return new(extJSONValueWriter) }, } @@ -43,7 +43,7 @@ type ValueMarshaler interface { // Pool of buffers for marshalling BSON. var bufPool = sync.Pool{ - New: func() interface{} { + New: func() any { return new(bytes.Buffer) }, } @@ -54,7 +54,7 @@ var bufPool = sync.Pool{ // Marshal will use the default registry created by NewRegistry to recursively // marshal val into a []byte. Marshal will inspect struct tags and alter the // marshaling process accordingly. -func Marshal(val interface{}) ([]byte, error) { +func Marshal(val any) ([]byte, error) { sw := bufPool.Get().(*bytes.Buffer) defer func() { // Proper usage of a sync.Pool requires each entry to have approximately @@ -94,7 +94,7 @@ func Marshal(val interface{}) ([]byte, error) { // // MarshalValue will use bson.NewRegistry() to transform val into a BSON value. If val is a struct, this function will // inspect struct tags and alter the marshalling process accordingly. -func MarshalValue(val interface{}) (Type, []byte, error) { +func MarshalValue(val any) (Type, []byte, error) { sw := bufPool.Get().(*bytes.Buffer) defer func() { // Proper usage of a sync.Pool requires each entry to have approximately @@ -143,7 +143,7 @@ func MarshalValue(val interface{}) (Type, []byte, error) { } // MarshalExtJSON returns the extended JSON encoding of val. -func MarshalExtJSON(val interface{}, canonical, escapeHTML bool) ([]byte, error) { +func MarshalExtJSON(val any, canonical, escapeHTML bool) ([]byte, error) { sw := sliceWriter(make([]byte, 0, defaultDstCap)) ejvw := extjPool.Get().(*extJSONValueWriter) ejvw.reset(sw, canonical, escapeHTML) @@ -175,7 +175,7 @@ func IndentExtJSON(dst *bytes.Buffer, src []byte, prefix, indent string) error { // MarshalExtJSONIndent returns the extended JSON encoding of val with each line with prefixed // and indented. -func MarshalExtJSONIndent(val interface{}, canonical, escapeHTML bool, prefix, indent string) ([]byte, error) { +func MarshalExtJSONIndent(val any, canonical, escapeHTML bool, prefix, indent string) ([]byte, error) { marshaled, err := MarshalExtJSON(val, canonical, escapeHTML) if err != nil { return nil, err diff --git a/bson/marshal_test.go b/bson/marshal_test.go index 8ede9627ba..70ce9c915a 100644 --- a/bson/marshal_test.go +++ b/bson/marshal_test.go @@ -161,7 +161,7 @@ func TestCachingEncodersNotSharedAcrossRegistries(t *testing.T) { // Helper function to run the test and make assertions. The provided original value should result in the document // {"x": {$numberInt: 1}} when marshalled with the default registry. - verifyResults := func(t *testing.T, original interface{}) { + verifyResults := func(t *testing.T, original any) { // Marshal using the default and custom registries. Assert that the result is {x: 1} and {x: -1}, respectively. first, err := Marshal(original) @@ -244,7 +244,7 @@ func TestNullBytes(t *testing.T) { func TestMarshalExtJSONIndent(t *testing.T) { type indentTestCase struct { name string - val interface{} + val any expectedExtJSON string } @@ -259,8 +259,8 @@ func TestMarshalExtJSONIndent(t *testing.T) { { "embedded struct", struct { - Embedded interface{} `json:"embedded"` - Foo string `json:"foo"` + Embedded any `json:"embedded"` + Foo string `json:"foo"` }{ Embedded: struct { Name string `json:"name"` diff --git a/bson/marshal_value_cases_test.go b/bson/marshal_value_cases_test.go index d25e815a98..44607a306b 100644 --- a/bson/marshal_value_cases_test.go +++ b/bson/marshal_value_cases_test.go @@ -212,7 +212,7 @@ type marshalValueStruct struct { type marshalValueTestCase struct { name string - val interface{} + val any bsontype Type bytes []byte } diff --git a/bson/marshaling_cases_test.go b/bson/marshaling_cases_test.go index 8e63ee5d41..10799671cc 100644 --- a/bson/marshaling_cases_test.go +++ b/bson/marshaling_cases_test.go @@ -9,7 +9,7 @@ package bson type marshalingTestCase struct { name string reg *Registry - val interface{} + val any want []byte } diff --git a/bson/mgoregistry.go b/bson/mgoregistry.go index f42935e5d8..6aa74f292c 100644 --- a/bson/mgoregistry.go +++ b/bson/mgoregistry.go @@ -17,7 +17,7 @@ var ( tInt = reflect.TypeOf(int(0)) tM = reflect.TypeOf(M{}) - tInterfaceSlice = reflect.TypeOf([]interface{}{}) + tInterfaceSlice = reflect.TypeOf([]any{}) tGetter = reflect.TypeOf((*getter)(nil)).Elem() tSetter = reflect.TypeOf((*setter)(nil)).Elem() ) @@ -131,7 +131,7 @@ type setter interface { // If GetBSON returns return a non-nil error, the marshalling procedure // will stop and error out with the provided value. type getter interface { - GetBSON() (interface{}, error) + GetBSON() (any, error) } // setterDecodeValue is the ValueDecoderFunc for Setter types. diff --git a/bson/mgoregistry_test.go b/bson/mgoregistry_test.go index d9dacbbce8..c2ea576465 100644 --- a/bson/mgoregistry_test.go +++ b/bson/mgoregistry_test.go @@ -33,7 +33,7 @@ func wrapInDoc(data string) string { return string(result) } -func makeZeroDoc(value interface{}) (zero interface{}) { +func makeZeroDoc(value any) (zero any) { v := reflect.ValueOf(value) t := v.Type() switch t.Kind() { @@ -51,7 +51,7 @@ func makeZeroDoc(value interface{}) (zero interface{}) { return zero } -func unmarshalWithRegistry(t *testing.T, r *Registry, data []byte, val interface{}) error { +func unmarshalWithRegistry(t *testing.T, r *Registry, data []byte, val any) error { t.Helper() dec := NewDecoder(NewDocumentReader(bytes.NewReader(data))) @@ -59,7 +59,7 @@ func unmarshalWithRegistry(t *testing.T, r *Registry, data []byte, val interface return dec.Decode(val) } -func testUnmarshal(t *testing.T, data string, obj interface{}) { +func testUnmarshal(t *testing.T, data string, obj any) { zero := makeZeroDoc(obj) err := unmarshalWithRegistry(t, NewMgoRegistry(), []byte(data), zero) assert.Nil(t, err, "expected nil error, got: %v", err) @@ -67,7 +67,7 @@ func testUnmarshal(t *testing.T, data string, obj interface{}) { } type testItemType struct { - obj interface{} + obj any data string } @@ -77,7 +77,7 @@ type testItemType struct { var sampleItems = []testItemType{ {M{"hello": "world"}, "\x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00"}, - {M{"BSON": []interface{}{"awesome", float64(5.05), 1986}}, + {M{"BSON": []any{"awesome", float64(5.05), 1986}}, "1\x00\x00\x00\x04BSON\x00&\x00\x00\x00\x020\x00\x08\x00\x00\x00" + "awesome\x00\x011\x00333333\x14@\x102\x00\xc2\x07\x00\x00\x00\x00"}, {M{"slice": []uint8{1, 2}}, @@ -128,7 +128,7 @@ var allItems = []testItemType{ "\x02_\x00\x03\x00\x00\x00yo\x00"}, {M{"_": M{"a": true}}, "\x03_\x00\x09\x00\x00\x00\x08a\x00\x01\x00"}, - {M{"_": []interface{}{true, false}}, + {M{"_": []any{true, false}}, "\x04_\x00\r\x00\x00\x00\x080\x00\x01\x081\x00\x00\x00"}, {M{"_": []byte("yo")}, "\x05_\x00\x02\x00\x00\x00\x00yo"}, @@ -262,7 +262,7 @@ func TestUnmarshalNonNilInterface(t *testing.T) { err := enc.Encode(M{"b": 2}) assert.Nil(t, err, "expected nil error, got: %v", err) m := M{"a": 1} - var i interface{} = m + var i any = m err = unmarshalWithRegistry(t, NewMgoRegistry(), buf.Bytes(), &i) assert.Nil(t, err, "expected nil error, got: %v", err) assert.True(t, reflect.DeepEqual(M{"b": 2}, i), "expected: %v, got: %v", M{"b": 2}, i) @@ -271,7 +271,7 @@ func TestUnmarshalNonNilInterface(t *testing.T) { func TestPtrInline(t *testing.T) { cases := []struct { - In interface{} + In any Out M }{ { @@ -340,7 +340,7 @@ var oneWayMarshalItems = []testItemType{ {M{"": [2]bool{true, false}}, "\x04\x00\r\x00\x00\x00\x080\x00\x01\x081\x00\x00\x00"}, - // The typed slice will be unmarshaled as []interface{}. + // The typed slice will be unmarshaled as []any. {M{"": []bool{true, false}}, "\x04\x00\r\x00\x00\x00\x080\x00\x01\x081\x00\x00\x00"}, @@ -408,13 +408,13 @@ type specSample1 struct { } type specSample2 struct { - BSON []interface{} `bson:"BSON"` + BSON []any `bson:"BSON"` } var structSampleItems = []testItemType{ {&specSample1{"world"}, "\x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00"}, - {&specSample2{[]interface{}{"awesome", float64(5.05), 1986}}, + {&specSample2{[]any{"awesome", float64(5.05), 1986}}, "1\x00\x00\x00\x04BSON\x00&\x00\x00\x00\x020\x00\x08\x00\x00\x00" + "awesome\x00\x011\x00333333\x14@\x102\x00\xc2\x07\x00\x00\x00\x00"}, } @@ -468,7 +468,7 @@ func Test64bitInt(t *testing.T) { type prefixPtr string type prefixVal string -func (t *prefixPtr) GetBSON() (interface{}, error) { +func (t *prefixPtr) GetBSON() (any, error) { if t == nil { return nil, nil } @@ -498,7 +498,7 @@ func (t *prefixPtr) SetBSON(raw RawValue) error { return nil } -func (t prefixVal) GetBSON() (interface{}, error) { +func (t prefixVal) GetBSON() (any, error) { return "foo-" + string(t), nil } @@ -633,7 +633,7 @@ func TestUnmarshalRawStructItems(t *testing.T) { // One-way marshaling tests. type dOnIface struct { - D interface{} + D any } type ignoreField struct { @@ -766,7 +766,7 @@ var marshalErrorItems = []testItemType{ "Multiple ,inline maps in struct bson_test.inlineDupMap"}, {&inlineBadKeyMap{}, "Option ,inline needs a map with string keys in struct bson_test.inlineBadKeyMap"}, - {&inlineMap{A: 1, M: map[string]interface{}{"a": 1}}, + {&inlineMap{A: 1, M: map[string]any{"a": 1}}, `Can't have key "a" in inlined map; conflicts with struct field`}, } @@ -791,7 +791,7 @@ func TestMarshalErrorItems(t *testing.T) { // Unmarshalling error cases. type unmarshalErrorType struct { - obj interface{} + obj any data string } @@ -819,7 +819,7 @@ var unmarshalErrorItems = []unmarshalErrorType{ }, // Non-string and not numeric map key. { - obj: map[bool]interface{}{true: 1}, + obj: map[bool]any{true: 1}, data: "\x10true\x00\x01\x00\x00\x00", }, } @@ -828,7 +828,7 @@ func TestUnmarshalErrorItems(t *testing.T) { for i, item := range unmarshalErrorItems { t.Run(strconv.Itoa(i), func(t *testing.T) { data := []byte(wrapInDoc(item.data)) - var value interface{} + var value any switch reflect.ValueOf(item.obj).Kind() { case reflect.Map, reflect.Ptr: value = makeZeroDoc(item.obj) @@ -844,7 +844,7 @@ func TestUnmarshalErrorItems(t *testing.T) { } type unmarshalRawErrorType struct { - obj interface{} + obj any raw RawValue } @@ -924,7 +924,7 @@ func TestUnmarshalMapDocumentTooShort(t *testing.T) { var setterResult = map[string]error{} type setterType struct { - Received interface{} + Received any } func (o *setterType) SetBSON(raw RawValue) error { @@ -1050,11 +1050,11 @@ func TestUnmarshalSetterErrSetZero(t *testing.T) { // Getter test cases. type typeWithGetter struct { - result interface{} + result any err error } -func (t *typeWithGetter) GetBSON() (interface{}, error) { +func (t *typeWithGetter) GetBSON() (any, error) { if t == nil { return "", nil } @@ -1124,7 +1124,7 @@ func TestGetterErrors(t *testing.T) { type intGetter int64 -func (t intGetter) GetBSON() (interface{}, error) { +func (t intGetter) GetBSON() (any, error) { return int64(t), nil } @@ -1165,8 +1165,8 @@ func TestMarshalWithGetterNil(t *testing.T) { // Cross-type conversion tests. type crossTypeItem struct { - obj1 interface{} - obj2 interface{} + obj1 any + obj2 any } type condStr struct { @@ -1188,7 +1188,7 @@ type condFloat struct { V float64 `bson:",omitempty"` } type condIface struct { - V interface{} `bson:",omitempty"` + V any `bson:",omitempty"` } type condPtr struct { V *bool `bson:",omitempty"` @@ -1216,7 +1216,7 @@ type shortUint struct { V uint64 `bson:",minsize"` } type shortIface struct { - V interface{} `bson:",minsize"` + V any `bson:",minsize"` } type shortPtr struct { V *int64 `bson:",minsize"` @@ -1234,7 +1234,7 @@ type inlineDupName struct { } type inlineMap struct { A int - M map[string]interface{} `bson:",inline"` + M map[string]any `bson:",inline"` } type inlineMapInt struct { A int @@ -1245,14 +1245,14 @@ type inlineMapMyM struct { M MyM `bson:",inline"` } type inlineDupMap struct { - M1 map[string]interface{} `bson:",inline"` - M2 map[string]interface{} `bson:",inline"` + M1 map[string]any `bson:",inline"` + M2 map[string]any `bson:",inline"` } type inlineBadKeyMap struct { M map[int]int `bson:",inline"` } type inlineUnexported struct { - M map[string]interface{} `bson:",inline"` + M map[string]any `bson:",inline"` unexported `bson:",inline"` } type MStruct struct { @@ -1272,7 +1272,7 @@ type unexported struct { type getterSetterD D -func (s getterSetterD) GetBSON() (interface{}, error) { +func (s getterSetterD) GetBSON() (any, error) { if len(s) == 0 { return D{}, nil } @@ -1301,7 +1301,7 @@ func (s *getterSetterD) SetBSON(raw RawValue) error { type getterSetterInt int -func (i getterSetterInt) GetBSON() (interface{}, error) { +func (i getterSetterInt) GetBSON() (any, error) { return D{{"a", int(i)}}, nil } @@ -1346,7 +1346,7 @@ func (s *ifaceSlice) SetBSON(raw RawValue) error { return nil } -func (s ifaceSlice) GetBSON() (interface{}, error) { +func (s ifaceSlice) GetBSON() (any, error) { return []int{len(s)}, nil } @@ -1356,7 +1356,7 @@ type ( MyBool bool MyD D MyRawD Raw - MyM map[string]interface{} + MyM map[string]any ) var ( @@ -1506,30 +1506,30 @@ var twoWayCrossItems = []crossTypeItem{ {&condTime{time.Unix(123456789, 123e6).UTC()}, map[string]time.Time{"v": time.Unix(123456789, 123e6).UTC()}}, {&condTime{}, map[string]string{}}, - {&condStruct{struct{ A []int }{[]int{1}}}, M{"v": M{"a": []interface{}{1}}}}, + {&condStruct{struct{ A []int }{[]int{1}}}, M{"v": M{"a": []any{1}}}}, {&condStruct{struct{ A []int }{}}, M{}}, {&namedCondStr{"yo"}, map[string]string{"myv": "yo"}}, {&namedCondStr{}, map[string]string{}}, - {&shortInt{1}, map[string]interface{}{"v": 1}}, - {&shortInt{1 << 30}, map[string]interface{}{"v": 1 << 30}}, - {&shortInt{1 << 31}, map[string]interface{}{"v": int64(1 << 31)}}, - {&shortUint{1 << 30}, map[string]interface{}{"v": 1 << 30}}, - {&shortUint{1 << 31}, map[string]interface{}{"v": int64(1 << 31)}}, - {&shortIface{int64(1) << 31}, map[string]interface{}{"v": int64(1 << 31)}}, - {&shortPtr{int64ptr}, map[string]interface{}{"v": intvar}}, - - {&shortNonEmptyInt{1}, map[string]interface{}{"v": 1}}, - {&shortNonEmptyInt{1 << 31}, map[string]interface{}{"v": int64(1 << 31)}}, - {&shortNonEmptyInt{}, map[string]interface{}{}}, - - {&inlineInt{struct{ A, B int }{1, 2}}, map[string]interface{}{"a": 1, "b": 2}}, - {&inlineMap{A: 1, M: map[string]interface{}{"b": 2}}, map[string]interface{}{"a": 1, "b": 2}}, - {&inlineMap{A: 1, M: nil}, map[string]interface{}{"a": 1}}, + {&shortInt{1}, map[string]any{"v": 1}}, + {&shortInt{1 << 30}, map[string]any{"v": 1 << 30}}, + {&shortInt{1 << 31}, map[string]any{"v": int64(1 << 31)}}, + {&shortUint{1 << 30}, map[string]any{"v": 1 << 30}}, + {&shortUint{1 << 31}, map[string]any{"v": int64(1 << 31)}}, + {&shortIface{int64(1) << 31}, map[string]any{"v": int64(1 << 31)}}, + {&shortPtr{int64ptr}, map[string]any{"v": intvar}}, + + {&shortNonEmptyInt{1}, map[string]any{"v": 1}}, + {&shortNonEmptyInt{1 << 31}, map[string]any{"v": int64(1 << 31)}}, + {&shortNonEmptyInt{}, map[string]any{}}, + + {&inlineInt{struct{ A, B int }{1, 2}}, map[string]any{"a": 1, "b": 2}}, + {&inlineMap{A: 1, M: map[string]any{"b": 2}}, map[string]any{"a": 1, "b": 2}}, + {&inlineMap{A: 1, M: nil}, map[string]any{"a": 1}}, {&inlineMapInt{A: 1, M: map[string]int{"b": 2}}, map[string]int{"a": 1, "b": 2}}, {&inlineMapInt{A: 1, M: nil}, map[string]int{"a": 1}}, - {&inlineUnexported{M: map[string]interface{}{"b": 1}, unexported: unexported{A: 2}}, map[string]interface{}{"b": 1, "a": 2}}, + {&inlineUnexported{M: map[string]any{"b": 1}, unexported: unexported{A: 2}}, map[string]any{"b": 1, "a": 2}}, // []byte <=> Binary {&struct{ B []byte }{[]byte("abc")}, map[string]Binary{"b": {Data: []byte("abc")}}}, @@ -1551,37 +1551,37 @@ var twoWayCrossItems = []crossTypeItem{ {&struct{ V [2]byte }{[...]byte{1, 2}}, map[string][2]byte{"v": {1, 2}}}, // zero time - {&struct{ V time.Time }{}, map[string]interface{}{"v": time.Time{}}}, + {&struct{ V time.Time }{}, map[string]any{"v": time.Time{}}}, // zero time + 1 second + 1 millisecond; overflows int64 as nanoseconds {&struct{ V time.Time }{time.Unix(-62135596799, 1e6).UTC()}, - map[string]interface{}{"v": time.Unix(-62135596799, 1e6).UTC()}}, + map[string]any{"v": time.Unix(-62135596799, 1e6).UTC()}}, // json.Number <=> int64, float64 - {&struct{ N json.Number }{"5"}, map[string]interface{}{"n": int64(5)}}, - {&struct{ N json.Number }{"5.05"}, map[string]interface{}{"n": 5.05}}, - {&struct{ N json.Number }{"9223372036854776000"}, map[string]interface{}{"n": float64(1 << 63)}}, + {&struct{ N json.Number }{"5"}, map[string]any{"n": int64(5)}}, + {&struct{ N json.Number }{"5.05"}, map[string]any{"n": 5.05}}, + {&struct{ N json.Number }{"9223372036854776000"}, map[string]any{"n": float64(1 << 63)}}, // D <=> non-struct getter/setter {&D{{"a", 1}}, &getterSetterD{{"a", 1}, {"suffix", true}}}, {&D{{"a", 42}}, &gsintvar}, // Interface slice setter. - {&struct{ V ifaceSlice }{ifaceSlice{nil, nil, nil}}, M{"v": []interface{}{3}}}, + {&struct{ V ifaceSlice }{ifaceSlice{nil, nil, nil}}, M{"v": []any{3}}}, } // Same thing, but only one way (obj1 => obj2). var oneWayCrossItems = []crossTypeItem{ // Would get decoded into a int32 too in the opposite direction. - {&shortIface{int64(1) << 30}, map[string]interface{}{"v": 1 << 30}}, + {&shortIface{int64(1) << 30}, map[string]any{"v": 1 << 30}}, // Ensure omitempty on struct with private fields works properly. {&struct { V struct{ v time.Time } `bson:",omitempty"` - }{}, map[string]interface{}{}}, + }{}, map[string]any{}}, - {&inlineMapMyM{A: 1, M: MyM{"b": MyM{"c": 3}}}, map[string]interface{}{"a": 1, "b": M{"c": 3}}}, - {map[string]interface{}{"a": 1, "b": map[string]interface{}{"c": 3}}, &inlineMapMyM{A: 1, M: MyM{"b": M{"c": 3}}}}, + {&inlineMapMyM{A: 1, M: MyM{"b": MyM{"c": 3}}}, map[string]any{"a": 1, "b": M{"c": 3}}}, + {map[string]any{"a": 1, "b": map[string]any{"c": 3}}, &inlineMapMyM{A: 1, M: MyM{"b": M{"c": 3}}}}, {&D{{"a", D{{"b", 1}, {"c", 2}}}}, &D{{"a", M{"b": 1, "c": 2}}}}, @@ -1594,13 +1594,13 @@ var oneWayCrossItems = []crossTypeItem{ {&M{"a": M{"b": 1, "c": 2}}, MyM{"a": M{"b": 1, "c": 2}}}, {MyM{"a": MyM{"b": 1, "c": 2}}, &M{"a": M{"b": 1, "c": 2}}}, - {map[string]interface{}{"a": map[string]interface{}{"b": 1, "c": 2}}, &M{"a": M{"b": 1, "c": 2}}}, + {map[string]any{"a": map[string]any{"b": 1, "c": 2}}, &M{"a": M{"b": 1, "c": 2}}}, - {&M{"a": M{"b": 1, "c": 2}}, map[MyString]interface{}{"a": M{"b": 1, "c": 2}}}, - {map[MyString]interface{}{"a": map[MyString]interface{}{"b": 1, "c": 2}}, &M{"a": M{"b": 1, "c": 2}}}, + {&M{"a": M{"b": 1, "c": 2}}, map[MyString]any{"a": M{"b": 1, "c": 2}}}, + {map[MyString]any{"a": map[MyString]any{"b": 1, "c": 2}}, &M{"a": M{"b": 1, "c": 2}}}, } -func testCrossPair(t *testing.T, dump interface{}, load interface{}) { +func testCrossPair(t *testing.T, dump any, load any) { zero := makeZeroDoc(load) buf := new(bytes.Buffer) vw := NewDocumentWriter(buf) @@ -1709,7 +1709,7 @@ func TestMarshalNotRespectNil(t *testing.T) { type T struct { Slice []int BSlice []byte - Map map[string]interface{} + Map map[string]any } testStruct1 := T{} @@ -1739,8 +1739,8 @@ func TestMarshalRespectNil(t *testing.T) { Slice []int SlicePtr *[]int Ptr *int - Map map[string]interface{} - MapPtr *map[string]interface{} + Map map[string]any + MapPtr *map[string]any } testStruct1 := T{} @@ -1771,8 +1771,8 @@ func TestMarshalRespectNil(t *testing.T) { testStruct1 = T{ Slice: []int{}, SlicePtr: &[]int{}, - Map: map[string]interface{}{}, - MapPtr: &map[string]interface{}{}, + Map: map[string]any{}, + MapPtr: &map[string]any{}, } assert.NotNil(t, testStruct1.Slice, "expected non-nil slice") diff --git a/bson/primitive.go b/bson/primitive.go index 162bfa7133..55d57446e6 100644 --- a/bson/primitive.go +++ b/bson/primitive.go @@ -137,7 +137,7 @@ type Symbol string // CodeWithScope represents a BSON JavaScript code with scope value. type CodeWithScope struct { Code JavaScript - Scope interface{} + Scope any } func (cws CodeWithScope) String() string { @@ -257,17 +257,17 @@ func (d *D) UnmarshalJSON(b []byte) error { // E represents a BSON element for a D. It is usually used inside a D. type E struct { Key string - Value interface{} + Value any } // M is an unordered representation of a BSON document. This type should be used when the order of the elements does not -// matter. This type is handled as a regular map[string]interface{} when encoding and decoding. Elements will be +// matter. This type is handled as a regular map[string]any when encoding and decoding. Elements will be // serialized in an undefined, random order. If the order of the elements matters, a D should be used instead. // // Example usage: // // bson.M{"foo": "bar", "hello": "world", "pi": 3.14159} -type M map[string]interface{} +type M map[string]any func (m M) String() string { b, err := MarshalExtJSON(m, true, false) @@ -282,7 +282,7 @@ func (m M) String() string { // Example usage: // // bson.A{"bar", "world", 3.14159, bson.D{{"qux", 12345}}} -type A []interface{} +type A []any func jsonDecodeD(dec *json.Decoder) (D, error) { res := D{} @@ -326,8 +326,8 @@ func jsonDecodeD(dec *json.Decoder) (D, error) { return res, nil } -func jsonDecodeSlice(dec *json.Decoder) ([]interface{}, error) { - var res []interface{} +func jsonDecodeSlice(dec *json.Decoder) ([]any, error) { + var res []any done := false for !done { t, err := dec.Token() diff --git a/bson/primitive_codecs_test.go b/bson/primitive_codecs_test.go index 6071ea02f9..8798d54494 100644 --- a/bson/primitive_codecs_test.go +++ b/bson/primitive_codecs_test.go @@ -21,7 +21,7 @@ import ( "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" ) -func bytesFromDoc(doc interface{}) []byte { +func bytesFromDoc(doc any) []byte { b, err := Marshal(doc) if err != nil { panic(fmt.Errorf("Couldn't marshal BSON document: %w", err)) @@ -36,7 +36,7 @@ func TestPrimitiveValueEncoders(t *testing.T) { type subtest struct { name string - val interface{} + val any ectx *EncodeContext llvrw *valueReaderWriter invoke invoked @@ -207,7 +207,7 @@ func TestPrimitiveValueEncoders(t *testing.T) { testCases := []struct { name string - value interface{} + value any b []byte err error }{ @@ -347,7 +347,7 @@ func TestPrimitiveValueEncoders(t *testing.T) { nil, }, { - "struct{[]interface{}}", + "struct{[]any}", struct { A []bool B []int32 @@ -482,7 +482,7 @@ func TestPrimitiveValueDecoders(t *testing.T) { type subtest struct { name string - val interface{} + val any dctx *DecodeContext llvrw *valueReaderWriter invoke invoked @@ -623,7 +623,7 @@ func TestPrimitiveValueDecoders(t *testing.T) { if !cmp.Equal(invoked, rc.invoke) { t.Errorf("Incorrect method invoked. got %v; want %v", invoked, rc.invoke) } - var got interface{} + var got any if val.IsValid() && val.CanInterface() { got = val.Interface() } @@ -654,7 +654,7 @@ func TestPrimitiveValueDecoders(t *testing.T) { testCases := []struct { name string - value interface{} + value any b []byte err error }{ @@ -927,7 +927,7 @@ func TestPrimitiveValueDecoders(t *testing.T) { nil, }, { - "struct{[]interface{}}", + "struct{[]any}", struct { A []bool B []int32 diff --git a/bson/raw_test.go b/bson/raw_test.go index 4cb2f5a077..7770359e75 100644 --- a/bson/raw_test.go +++ b/bson/raw_test.go @@ -364,7 +364,7 @@ func BenchmarkRawString(b *testing.B) { cases := []struct { description string - value interface{} + value any }{ { description: "string", diff --git a/bson/raw_value.go b/bson/raw_value.go index 84b737128e..24283a24c5 100644 --- a/bson/raw_value.go +++ b/bson/raw_value.go @@ -43,7 +43,7 @@ func (rv RawValue) IsZero() bool { // error is returned. This method will use the registry used to create the RawValue, if the RawValue // was created from partial BSON processing, or it will use the default registry. Users wishing to // specify the registry to use should use UnmarshalWithRegistry. -func (rv RawValue) Unmarshal(val interface{}) error { +func (rv RawValue) Unmarshal(val any) error { reg := rv.r if reg == nil { reg = defaultRegistry @@ -66,7 +66,7 @@ func (rv RawValue) Equal(rv2 RawValue) bool { // UnmarshalWithRegistry performs the same unmarshalling as Unmarshal but uses the provided registry // instead of the one attached or the default registry. -func (rv RawValue) UnmarshalWithRegistry(r *Registry, val interface{}) error { +func (rv RawValue) UnmarshalWithRegistry(r *Registry, val any) error { if r == nil { return ErrNilRegistry } @@ -86,7 +86,7 @@ func (rv RawValue) UnmarshalWithRegistry(r *Registry, val interface{}) error { // UnmarshalWithContext performs the same unmarshalling as Unmarshal but uses the provided DecodeContext // instead of the one attached or the default registry. -func (rv RawValue) UnmarshalWithContext(dc *DecodeContext, val interface{}) error { +func (rv RawValue) UnmarshalWithContext(dc *DecodeContext, val any) error { if dc == nil { return ErrNilContext } diff --git a/bson/registry.go b/bson/registry.go index d8f65ddc0d..21057da4c5 100644 --- a/bson/registry.go +++ b/bson/registry.go @@ -65,7 +65,7 @@ func (entme errNoTypeMapEntry) Error() string { // for any value whose type implements bson.Marshaler, regardless of the value's concrete type. // // 3. Type map entries - This can be used to associate a BSON type with a Go type. These type -// associations are used when decoding into a bson.D/bson.M or a struct field of type interface{}. +// associations are used when decoding into a bson.D/bson.M or a struct field of type any. // For example, by default, BSON int32 and int64 values decode as Go int32 and int64 instances, // respectively, when decoding into a bson.D. The following code would change the behavior so these // values decode as Go int instances instead: @@ -214,7 +214,7 @@ func (r *Registry) RegisterInterfaceDecoder(iface reflect.Type, dec ValueDecoder // 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 +// By default, BSON documents will decode into any 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: // diff --git a/bson/struct_codec_test.go b/bson/struct_codec_test.go index cae19c7a01..a1490c6e85 100644 --- a/bson/struct_codec_test.go +++ b/bson/struct_codec_test.go @@ -18,7 +18,7 @@ func TestIsZero(t *testing.T) { t.Parallel() testCases := []struct { description string - value interface{} + value any omitZeroStruct bool want bool }{ diff --git a/bson/truncation_test.go b/bson/truncation_test.go index 958ea6c5cd..e86f9874a7 100644 --- a/bson/truncation_test.go +++ b/bson/truncation_test.go @@ -23,7 +23,7 @@ type outputArgs struct { Val *int64 } -func unmarshalWithContext(t *testing.T, dc DecodeContext, data []byte, val interface{}) error { +func unmarshalWithContext(t *testing.T, dc DecodeContext, data []byte, val any) error { t.Helper() vr := NewDocumentReader(bytes.NewReader(data)) diff --git a/bson/types.go b/bson/types.go index c2883aa4ef..d11cb2aab3 100644 --- a/bson/types.go +++ b/bson/types.go @@ -83,7 +83,7 @@ var tInt64 = reflect.TypeOf(int64(0)) var tString = reflect.TypeOf("") var tTime = reflect.TypeOf(time.Time{}) -var tEmpty = reflect.TypeOf((*interface{})(nil)).Elem() +var tEmpty = reflect.TypeOf((*any)(nil)).Elem() var tByteSlice = reflect.TypeOf([]byte(nil)) var tByte = reflect.TypeOf(byte(0x00)) var tURL = reflect.TypeOf(url.URL{}) diff --git a/bson/unmarshal.go b/bson/unmarshal.go index 5597bc7a92..4377c4e428 100644 --- a/bson/unmarshal.go +++ b/bson/unmarshal.go @@ -41,7 +41,7 @@ type ValueUnmarshaler interface { // // When unmarshaling BSON, if the BSON value is null and the Go value is a // pointer, the pointer is set to nil without calling UnmarshalBSONValue. -func Unmarshal(data []byte, val interface{}) error { +func Unmarshal(data []byte, val any) error { vr := getBufferedDocumentReader(data) defer putBufferedDocumentReader(vr) @@ -56,7 +56,7 @@ func Unmarshal(data []byte, val interface{}) error { // UnmarshalValue parses the BSON value of type t with bson.NewRegistry() and // stores the result in the value pointed to by val. If val is nil or not a pointer, // UnmarshalValue returns an error. -func UnmarshalValue(t Type, data []byte, val interface{}) error { +func UnmarshalValue(t Type, data []byte, val any) error { vr := newBufferedValueReader(t, data) return unmarshalFromReader(DecodeContext{Registry: defaultRegistry}, vr, val) } @@ -70,7 +70,7 @@ func UnmarshalValue(t Type, data []byte, val interface{}) error { // // For more information about Extended JSON, see // https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/ -func UnmarshalExtJSON(data []byte, canonicalOnly bool, val interface{}) error { +func UnmarshalExtJSON(data []byte, canonicalOnly bool, val any) error { ejvr, err := NewExtJSONValueReader(bytes.NewReader(data), canonicalOnly) if err != nil { return err @@ -79,7 +79,7 @@ func UnmarshalExtJSON(data []byte, canonicalOnly bool, val interface{}) error { return unmarshalFromReader(DecodeContext{Registry: defaultRegistry}, ejvr, val) } -func unmarshalFromReader(dc DecodeContext, vr ValueReader, val interface{}) error { +func unmarshalFromReader(dc DecodeContext, vr ValueReader, val any) error { dec := decPool.Get().(*Decoder) defer decPool.Put(dec) diff --git a/bson/unmarshal_test.go b/bson/unmarshal_test.go index 702abcd152..2d05261374 100644 --- a/bson/unmarshal_test.go +++ b/bson/unmarshal_test.go @@ -44,7 +44,7 @@ func TestUnmarshalWithRegistry(t *testing.T) { testCases := []struct { name string - val interface{} + val any bsontype Type bytes []byte }{ @@ -151,7 +151,7 @@ func TestUnmarshalExtJSONWithUndefinedField(t *testing.T) { // When unmarshalling extJSON, fields that are undefined in the destination struct are skipped. // This process must not skip other, defined fields and must not raise errors. type expectedResponse struct { - DefinedField interface{} + DefinedField any } unmarshalExpectedResponse := func(t *testing.T, extJSON string) *expectedResponse { @@ -165,7 +165,7 @@ func TestUnmarshalExtJSONWithUndefinedField(t *testing.T) { testCases := []struct { name string testJSON string - expectedValue interface{} + expectedValue any }{ { "no array", @@ -294,14 +294,14 @@ func TestUnmarshalInterface(t *testing.T) { type testCase struct { name string - stub func() ([]byte, interface{}, func(*testing.T)) + stub func() ([]byte, any, func(*testing.T)) } testCases := []testCase{ { name: "struct with interface containing a concrete value", - stub: func() ([]byte, interface{}, func(*testing.T)) { + stub: func() ([]byte, any, func(*testing.T)) { type testStruct struct { - Value interface{} + Value any } var value string @@ -323,13 +323,13 @@ func TestUnmarshalInterface(t *testing.T) { }, { name: "struct with interface containing a struct", - stub: func() ([]byte, interface{}, func(*testing.T)) { + stub: func() ([]byte, any, func(*testing.T)) { type demo struct { Data string } type testStruct struct { - Value interface{} + Value any } var value demo @@ -351,9 +351,9 @@ func TestUnmarshalInterface(t *testing.T) { }, { name: "struct with interface containing a slice", - stub: func() ([]byte, interface{}, func(*testing.T)) { + stub: func() ([]byte, any, func(*testing.T)) { type testStruct struct { - Values interface{} + Values any } var values []string @@ -375,9 +375,9 @@ func TestUnmarshalInterface(t *testing.T) { }, { name: "struct with interface containing an array", - stub: func() ([]byte, interface{}, func(*testing.T)) { + stub: func() ([]byte, any, func(*testing.T)) { type testStruct struct { - Values interface{} + Values any } var values [2]string @@ -399,27 +399,27 @@ func TestUnmarshalInterface(t *testing.T) { }, { name: "struct with interface array containing concrete values", - stub: func() ([]byte, interface{}, func(*testing.T)) { + stub: func() ([]byte, any, func(*testing.T)) { type testStruct struct { - Values [3]interface{} + Values [3]any } var str string var i, j int data := docToBytes(struct { - Values []interface{} + Values []any }{ - Values: []interface{}{"foo", 42, nil}, + Values: []any{"foo", 42, nil}, }) - receiver := testStruct{[3]interface{}{&str, &i, &j}} + receiver := testStruct{[3]any{&str, &i, &j}} check := func(t *testing.T) { t.Helper() assert.Equal(t, "foo", str) assert.Equal(t, 42, i) assert.Equal(t, 0, j) - assert.Equal(t, testStruct{[3]interface{}{&str, &i, nil}}, receiver) + assert.Equal(t, testStruct{[3]any{&str, &i, nil}}, receiver) } return data, &receiver, check @@ -427,21 +427,21 @@ func TestUnmarshalInterface(t *testing.T) { }, { name: "overwriting prepopulated slice", - stub: func() ([]byte, interface{}, func(*testing.T)) { + stub: func() ([]byte, any, func(*testing.T)) { type testStruct struct { - Values []interface{} + Values []any } data := docToBytes(struct { - Values []interface{} + Values []any }{ - Values: []interface{}{1, 2, 3}, + Values: []any{1, 2, 3}, }) - receiver := testStruct{[]interface{}{7, 8}} + receiver := testStruct{[]any{7, 8}} check := func(t *testing.T) { t.Helper() - assert.Equal(t, testStruct{[]interface{}{1, 2, int32(3)}}, receiver) + assert.Equal(t, testStruct{[]any{1, 2, int32(3)}}, receiver) } return data, &receiver, check @@ -642,11 +642,11 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { description string data []byte sType reflect.Type - want interface{} + want any // getByteSlice returns the byte slice from the unmarshaled value, allowing the test to // inspect the addresses of the underlying byte array. - getByteSlice func(interface{}) []byte + getByteSlice func(any) []byte }{ { description: "struct with byte slice", @@ -657,7 +657,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { want: &fooBytes{ Foo: []byte{0, 1, 2, 3, 4, 5}, }, - getByteSlice: func(val interface{}) []byte { + getByteSlice: func(val any) []byte { return (val.(*fooBytes)).Foo }, }, @@ -670,7 +670,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { want: &D{ {"foo", Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}}, }, - getByteSlice: func(val interface{}) []byte { + getByteSlice: func(val any) []byte { return (*(val.(*D)))[0].Value.(Binary).Data }, }, @@ -683,7 +683,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { want: &fooMyBytes{ Foo: myBytes{0, 1, 2, 3, 4, 5}, }, - getByteSlice: func(val interface{}) []byte { + getByteSlice: func(val any) []byte { return (val.(*fooMyBytes)).Foo }, }, @@ -696,7 +696,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { want: &D{ {"foo", Binary{Subtype: 0, Data: myBytes{0, 1, 2, 3, 4, 5}}}, }, - getByteSlice: func(val interface{}) []byte { + getByteSlice: func(val any) []byte { return (*(val.(*D)))[0].Value.(Binary).Data }, }, @@ -709,7 +709,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { want: &fooBinary{ Foo: Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}, }, - getByteSlice: func(val interface{}) []byte { + getByteSlice: func(val any) []byte { return (val.(*fooBinary)).Foo.Data }, }, @@ -722,7 +722,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { want: &D{ {"foo", Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}}, }, - getByteSlice: func(val interface{}) []byte { + getByteSlice: func(val any) []byte { return (*(val.(*D)))[0].Value.(Binary).Data }, }, @@ -735,7 +735,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { want: &fooObjectID{ Foo: ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, }, - getByteSlice: func(val interface{}) []byte { + getByteSlice: func(val any) []byte { return (val.(*fooObjectID)).Foo[:] }, }, @@ -748,7 +748,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { want: &D{ {"foo", ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}}, }, - getByteSlice: func(val interface{}) []byte { + getByteSlice: func(val any) []byte { oid := (*(val.(*D)))[0].Value.(ObjectID) return oid[:] }, @@ -768,7 +768,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { Pointer: ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, }, }, - getByteSlice: func(val interface{}) []byte { + getByteSlice: func(val any) []byte { return (val.(*fooDBPointer)).Foo.Pointer[:] }, }, @@ -787,7 +787,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { Pointer: ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, }}, }, - getByteSlice: func(val interface{}) []byte { + getByteSlice: func(val any) []byte { oid := (*(val.(*D)))[0].Value.(DBPointer).Pointer return oid[:] }, diff --git a/bson/unmarshaling_cases_test.go b/bson/unmarshaling_cases_test.go index 61dbe9dc2a..66b7a27573 100644 --- a/bson/unmarshaling_cases_test.go +++ b/bson/unmarshaling_cases_test.go @@ -13,7 +13,7 @@ import ( type unmarshalingTestCase struct { name string sType reflect.Type - want interface{} + want any data []byte } diff --git a/bson/value_reader.go b/bson/value_reader.go index 62d9d0f772..e5bcc1985f 100644 --- a/bson/value_reader.go +++ b/bson/value_reader.go @@ -63,7 +63,7 @@ type vrState struct { } var vrPool = sync.Pool{ - New: func() interface{} { + New: func() any { return &valueReader{ stack: make([]vrState, 1, 5), } diff --git a/bson/value_reader_writer_test.go b/bson/value_reader_writer_test.go index 20d00e93c7..bccba27de9 100644 --- a/bson/value_reader_writer_test.go +++ b/bson/value_reader_writer_test.go @@ -70,7 +70,7 @@ const ( type TestValueReaderWriter struct { t *testing.T invoked VRWInvoked - readval interface{} + readval any bsontype Type err error errAfter VRWInvoked // error after this method is called diff --git a/bson/value_writer.go b/bson/value_writer.go index 2748696fbe..9dd8912d08 100644 --- a/bson/value_writer.go +++ b/bson/value_writer.go @@ -21,7 +21,7 @@ import ( var _ ValueWriter = &valueWriter{} var vwPool = sync.Pool{ - New: func() interface{} { + New: func() any { return new(valueWriter) }, } @@ -34,7 +34,7 @@ func putValueWriter(vw *valueWriter) { } var documentWriterPool = sync.Pool{ - New: func() interface{} { + New: func() any { return newDocumentWriter(nil) }, } diff --git a/bson/value_writer_test.go b/bson/value_writer_test.go index a52d61689b..e47b019d40 100644 --- a/bson/value_writer_test.go +++ b/bson/value_writer_test.go @@ -32,128 +32,128 @@ func TestDocumentWriter(t *testing.T) { oid := ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C} testCases := []struct { name string - fn interface{} - params []interface{} + fn any + params []any want []byte }{ { "WriteBinary", (*valueWriter).WriteBinary, - []interface{}{[]byte{0x01, 0x02, 0x03}}, + []any{[]byte{0x01, 0x02, 0x03}}, bsoncore.AppendBinaryElement(header, "foo", 0x00, []byte{0x01, 0x02, 0x03}), }, { "WriteBinaryWithSubtype (not 0x02)", (*valueWriter).WriteBinaryWithSubtype, - []interface{}{[]byte{0x01, 0x02, 0x03}, byte(0xFF)}, + []any{[]byte{0x01, 0x02, 0x03}, byte(0xFF)}, bsoncore.AppendBinaryElement(header, "foo", 0xFF, []byte{0x01, 0x02, 0x03}), }, { "WriteBinaryWithSubtype (0x02)", (*valueWriter).WriteBinaryWithSubtype, - []interface{}{[]byte{0x01, 0x02, 0x03}, byte(0x02)}, + []any{[]byte{0x01, 0x02, 0x03}, byte(0x02)}, bsoncore.AppendBinaryElement(header, "foo", 0x02, []byte{0x01, 0x02, 0x03}), }, { "WriteBoolean", (*valueWriter).WriteBoolean, - []interface{}{true}, + []any{true}, bsoncore.AppendBooleanElement(header, "foo", true), }, { "WriteDBPointer", (*valueWriter).WriteDBPointer, - []interface{}{"bar", oid}, + []any{"bar", oid}, bsoncore.AppendDBPointerElement(header, "foo", "bar", oid), }, { "WriteDateTime", (*valueWriter).WriteDateTime, - []interface{}{int64(12345678)}, + []any{int64(12345678)}, bsoncore.AppendDateTimeElement(header, "foo", 12345678), }, { "WriteDecimal128", (*valueWriter).WriteDecimal128, - []interface{}{NewDecimal128(10, 20)}, + []any{NewDecimal128(10, 20)}, bsoncore.AppendDecimal128Element(header, "foo", 10, 20), }, { "WriteDouble", (*valueWriter).WriteDouble, - []interface{}{float64(3.14159)}, + []any{float64(3.14159)}, bsoncore.AppendDoubleElement(header, "foo", 3.14159), }, { "WriteInt32", (*valueWriter).WriteInt32, - []interface{}{int32(123456)}, + []any{int32(123456)}, bsoncore.AppendInt32Element(header, "foo", 123456), }, { "WriteInt64", (*valueWriter).WriteInt64, - []interface{}{int64(1234567890)}, + []any{int64(1234567890)}, bsoncore.AppendInt64Element(header, "foo", 1234567890), }, { "WriteJavascript", (*valueWriter).WriteJavascript, - []interface{}{"var foo = 'bar';"}, + []any{"var foo = 'bar';"}, bsoncore.AppendJavaScriptElement(header, "foo", "var foo = 'bar';"), }, { "WriteMaxKey", (*valueWriter).WriteMaxKey, - []interface{}{}, + []any{}, bsoncore.AppendMaxKeyElement(header, "foo"), }, { "WriteMinKey", (*valueWriter).WriteMinKey, - []interface{}{}, + []any{}, bsoncore.AppendMinKeyElement(header, "foo"), }, { "WriteNull", (*valueWriter).WriteNull, - []interface{}{}, + []any{}, bsoncore.AppendNullElement(header, "foo"), }, { "WriteObjectID", (*valueWriter).WriteObjectID, - []interface{}{oid}, + []any{oid}, bsoncore.AppendObjectIDElement(header, "foo", oid), }, { "WriteRegex", (*valueWriter).WriteRegex, - []interface{}{"bar", "baz"}, + []any{"bar", "baz"}, bsoncore.AppendRegexElement(header, "foo", "bar", "abz"), }, { "WriteString", (*valueWriter).WriteString, - []interface{}{"hello, world!"}, + []any{"hello, world!"}, bsoncore.AppendStringElement(header, "foo", "hello, world!"), }, { "WriteSymbol", (*valueWriter).WriteSymbol, - []interface{}{"symbollolz"}, + []any{"symbollolz"}, bsoncore.AppendSymbolElement(header, "foo", "symbollolz"), }, { "WriteTimestamp", (*valueWriter).WriteTimestamp, - []interface{}{uint32(10), uint32(20)}, + []any{uint32(10), uint32(20)}, bsoncore.AppendTimestampElement(header, "foo", 10, 20), }, { "WriteUndefined", (*valueWriter).WriteUndefined, - []interface{}{}, + []any{}, bsoncore.AppendUndefinedElement(header, "foo"), }, }