diff --git a/bson/bsoncodec/array_codec.go b/bson/array_codec.go similarity index 78% rename from bson/bsoncodec/array_codec.go rename to bson/array_codec.go index 6ca8d9ad6c..5b07f4acd4 100644 --- a/bson/bsoncodec/array_codec.go +++ b/bson/array_codec.go @@ -4,12 +4,11 @@ // 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 +package bson import ( "reflect" - "go.mongodb.org/mongo-driver/bson/bsonrw" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -30,17 +29,17 @@ func NewArrayCodec() *ArrayCodec { } // EncodeValue is the ValueEncoder for bsoncore.Array values. -func (ac *ArrayCodec) EncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (ac *ArrayCodec) EncodeValue(_ EncodeContext, vw 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) + return copyArrayFromBytes(vw, arr) } // DecodeValue is the ValueDecoder for bsoncore.Array values. -func (ac *ArrayCodec) DecodeValue(_ DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (ac *ArrayCodec) DecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tCoreArray { return ValueDecoderError{Name: "CoreArrayDecodeValue", Types: []reflect.Type{tCoreArray}, Received: val} } @@ -50,7 +49,7 @@ func (ac *ArrayCodec) DecodeValue(_ DecodeContext, vr bsonrw.ValueReader, val re } val.SetLen(0) - arr, err := bsonrw.Copier{}.AppendArrayBytes(val.Interface().(bsoncore.Array), vr) + arr, err := appendArrayBytes(val.Interface().(bsoncore.Array), vr) val.Set(reflect.ValueOf(arr)) return err } diff --git a/bson/bson.go b/bson/bson.go deleted file mode 100644 index a0d8185826..0000000000 --- a/bson/bson.go +++ /dev/null @@ -1,50 +0,0 @@ -// 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 -// -// Based on gopkg.in/mgo.v2/bson by Gustavo Niemeyer -// See THIRD-PARTY-NOTICES for original license terms. - -package bson // import "go.mongodb.org/mongo-driver/bson" - -import ( - "go.mongodb.org/mongo-driver/bson/primitive" -) - -// Zeroer allows custom struct types to implement a report of zero -// state. All struct types that don't implement Zeroer or where IsZero -// returns false are considered to be not zero. -type Zeroer interface { - IsZero() bool -} - -// D is an ordered representation of a BSON document. This type should be used when the order of the elements matters, -// such as MongoDB command documents. If the order of the elements does not matter, an M should be used instead. -// -// A D should not be constructed with duplicate key names, as that can cause undefined server behavior. -// -// Example usage: -// -// bson.D{{"foo", "bar"}, {"hello", "world"}, {"pi", 3.14159}} -type D = primitive.D - -// E represents a BSON element for a D. It is usually used inside a D. -type E = primitive.E - -// 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 -// 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 = primitive.M - -// An A is an ordered representation of a BSON array. -// -// Example usage: -// -// bson.A{"bar", "world", 3.14159, bson.D{{"qux", 12345}}} -type A = primitive.A diff --git a/bson/bson_corpus_spec_test.go b/bson/bson_corpus_spec_test.go index 8a27b06272..90343df7e9 100644 --- a/bson/bson_corpus_spec_test.go +++ b/bson/bson_corpus_spec_test.go @@ -11,7 +11,6 @@ import ( "encoding/hex" "encoding/json" "fmt" - "math" "os" "path" "reflect" @@ -22,7 +21,6 @@ import ( "unicode/utf8" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/require" ) @@ -185,26 +183,6 @@ func unescapeUnicode(s, bsonType string) string { return newS } -func formatDouble(f float64) string { - var s string - if math.IsInf(f, 1) { - s = "Infinity" - } else if math.IsInf(f, -1) { - s = "-Infinity" - } else if math.IsNaN(f) { - s = "NaN" - } else { - // Print exactly one decimalType place for integers; otherwise, print as many are necessary to - // perfectly represent it. - s = strconv.FormatFloat(f, 'G', -1, 64) - if !strings.ContainsRune(s, 'E') && !strings.ContainsRune(s, '.') { - s += ".0" - } - } - - return s -} - func normalizeCanonicalDouble(t *testing.T, key string, cEJ string) string { // Unmarshal string into map cEJMap := make(map[string]map[string]string) @@ -410,7 +388,7 @@ func runTest(t *testing.T, file string) { for _, elem := range doc { value := reflect.ValueOf(elem.Value) invalidString := (value.Kind() == reflect.String) && !utf8.ValidString(value.String()) - dbPtr, ok := elem.Value.(primitive.DBPointer) + dbPtr, ok := elem.Value.(DBPointer) invalidDBPtr := ok && !utf8.ValidString(dbPtr.DB) if invalidString || invalidDBPtr { diff --git a/bson/bson_test.go b/bson/bson_test.go index 5a3b017f84..31b6ffb884 100644 --- a/bson/bson_test.go +++ b/bson/bson_test.go @@ -8,6 +8,7 @@ package bson import ( "bytes" + "encoding/json" "fmt" "reflect" "strconv" @@ -16,11 +17,9 @@ import ( "time" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsoncodec" "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/internal/assert" + "go.mongodb.org/mongo-driver/internal/require" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -32,6 +31,186 @@ func noerr(t *testing.T, err error) { } } +func TestCompareTimestamp(t *testing.T) { + testcases := []struct { + name string + tp Timestamp + tp2 Timestamp + expected int + }{ + {"equal", Timestamp{T: 12345, I: 67890}, Timestamp{T: 12345, I: 67890}, 0}, + {"T greater than", Timestamp{T: 12345, I: 67890}, Timestamp{T: 2345, I: 67890}, 1}, + {"I greater than", Timestamp{T: 12345, I: 67890}, Timestamp{T: 12345, I: 7890}, 1}, + {"T less than", Timestamp{T: 12345, I: 67890}, Timestamp{T: 112345, I: 67890}, -1}, + {"I less than", Timestamp{T: 12345, I: 67890}, Timestamp{T: 12345, I: 167890}, -1}, + } + + for _, tc := range testcases { + t.Run(tc.name, func(t *testing.T) { + result := CompareTimestamp(tc.tp, tc.tp2) + require.Equal(t, tc.expected, result) + }) + } +} + +func TestTimestamp(t *testing.T) { + t.Parallel() + + testCases := []struct { + description string + tp Timestamp + tp2 Timestamp + expectedAfter bool + expectedBefore bool + expectedEqual bool + expectedCompare int + }{ + { + description: "equal", + tp: Timestamp{T: 12345, I: 67890}, + tp2: Timestamp{T: 12345, I: 67890}, + expectedBefore: false, + expectedAfter: false, + expectedEqual: true, + expectedCompare: 0, + }, + { + description: "T greater than", + tp: Timestamp{T: 12345, I: 67890}, + tp2: Timestamp{T: 2345, I: 67890}, + expectedBefore: false, + expectedAfter: true, + expectedEqual: false, + expectedCompare: 1, + }, + { + description: "I greater than", + tp: Timestamp{T: 12345, I: 67890}, + tp2: Timestamp{T: 12345, I: 7890}, + expectedBefore: false, + expectedAfter: true, + expectedEqual: false, + expectedCompare: 1, + }, + { + description: "T less than", + tp: Timestamp{T: 12345, I: 67890}, + tp2: Timestamp{T: 112345, I: 67890}, + expectedBefore: true, + expectedAfter: false, + expectedEqual: false, + expectedCompare: -1, + }, + { + description: "I less than", + tp: Timestamp{T: 12345, I: 67890}, + tp2: Timestamp{T: 12345, I: 167890}, + expectedBefore: true, + expectedAfter: false, + expectedEqual: false, + expectedCompare: -1, + }, + } + + for _, tc := range testCases { + tc := tc // Capture range variable. + + t.Run(tc.description, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tc.expectedAfter, tc.tp.After(tc.tp2), "expected After results to be the same") + assert.Equal(t, tc.expectedBefore, tc.tp.Before(tc.tp2), "expected Before results to be the same") + assert.Equal(t, tc.expectedEqual, tc.tp.Equal(tc.tp2), "expected Equal results to be the same") + assert.Equal(t, tc.expectedCompare, tc.tp.Compare(tc.tp2), "expected Compare result to be the same") + }) + } +} + +func TestPrimitiveIsZero(t *testing.T) { + testcases := []struct { + name string + zero Zeroer + nonzero Zeroer + }{ + {"binary", Binary{}, Binary{Data: []byte{0x01, 0x02, 0x03}, Subtype: 0xFF}}, + {"decimal128", Decimal128{}, NewDecimal128(1, 2)}, + {"objectID", ObjectID{}, NewObjectID()}, + {"regex", Regex{}, Regex{Pattern: "foo", Options: "bar"}}, + {"dbPointer", DBPointer{}, DBPointer{DB: "foobar", Pointer: ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}}}, + {"timestamp", Timestamp{}, Timestamp{T: 12345, I: 67890}}, + } + + for _, tc := range testcases { + t.Run(tc.name, func(t *testing.T) { + require.True(t, tc.zero.IsZero()) + require.False(t, tc.nonzero.IsZero()) + }) + } +} + +func TestRegexCompare(t *testing.T) { + testcases := []struct { + name string + r1 Regex + r2 Regex + eq bool + }{ + {"equal", Regex{Pattern: "foo1", Options: "bar1"}, Regex{Pattern: "foo1", Options: "bar1"}, true}, + {"not equal", Regex{Pattern: "foo1", Options: "bar1"}, Regex{Pattern: "foo2", Options: "bar2"}, false}, + {"not equal", Regex{Pattern: "foo1", Options: "bar1"}, Regex{Pattern: "foo1", Options: "bar2"}, false}, + {"not equal", Regex{Pattern: "foo1", Options: "bar1"}, Regex{Pattern: "foo2", Options: "bar1"}, false}, + } + + for _, tc := range testcases { + t.Run(tc.name, func(t *testing.T) { + require.True(t, tc.r1.Equal(tc.r2) == tc.eq) + }) + } +} + +func TestDateTime(t *testing.T) { + t.Run("json", func(t *testing.T) { + t.Run("round trip", func(t *testing.T) { + original := DateTime(1000) + jsonBytes, err := json.Marshal(original) + assert.Nil(t, err, "Marshal error: %v", err) + + var unmarshalled DateTime + err = json.Unmarshal(jsonBytes, &unmarshalled) + assert.Nil(t, err, "Unmarshal error: %v", err) + + assert.Equal(t, original, unmarshalled, "expected DateTime %v, got %v", original, unmarshalled) + }) + t.Run("decode null", func(t *testing.T) { + jsonBytes := []byte("null") + var dt DateTime + err := json.Unmarshal(jsonBytes, &dt) + assert.Nil(t, err, "Unmarshal error: %v", err) + assert.Equal(t, DateTime(0), dt, "expected DateTime value to be 0, got %v", dt) + }) + t.Run("UTC", func(t *testing.T) { + dt := DateTime(1681145535123) + jsonBytes, err := json.Marshal(dt) + assert.Nil(t, err, "Marshal error: %v", err) + assert.Equal(t, `"2023-04-10T16:52:15.123Z"`, string(jsonBytes)) + }) + }) + t.Run("NewDateTimeFromTime", func(t *testing.T) { + t.Run("range is not limited", func(t *testing.T) { + // If the implementation internally calls time.Time.UnixNano(), the constructor cannot handle times after + // the year 2262. + + timeFormat := "2006-01-02T15:04:05.999Z07:00" + timeString := "3001-01-01T00:00:00Z" + tt, err := time.Parse(timeFormat, timeString) + assert.Nil(t, err, "Parse error: %v", err) + + dt := NewDateTimeFromTime(tt) + assert.True(t, dt > 0, "expected a valid DateTime greater than 0, got %v", dt) + }) + }) +} + func TestTimeRoundTrip(t *testing.T) { val := struct { Value time.Time @@ -180,11 +359,11 @@ func TestMapCodec(t *testing.T) { } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - mapCodec := bsoncodec.NewMapCodec(tc.opts) + mapCodec := NewMapCodec(tc.opts) mapRegistry := NewRegistry() mapRegistry.RegisterKindEncoder(reflect.Map, mapCodec) buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := NewValueWriter(buf) enc := NewEncoder(vw) enc.SetRegistry(mapRegistry) err := enc.Encode(mapObj) @@ -282,5 +461,5 @@ func TestBsoncoreArray(t *testing.T) { doc := bsoncore.Document(actualBSON) v := doc.Lookup("array") - assert.Equal(t, bsontype.Array, v.Type, "expected type array, got %v", v.Type) + assert.Equal(t, bsoncore.TypeArray, v.Type, "expected type array, got %v", v.Type) } diff --git a/bson/bsoncodec/bsoncodec.go b/bson/bsoncodec.go similarity index 77% rename from bson/bsoncodec/bsoncodec.go rename to bson/bsoncodec.go index 0693bd432f..860a6b82af 100644 --- a/bson/bsoncodec/bsoncodec.go +++ b/bson/bsoncodec.go @@ -4,61 +4,18 @@ // 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 "go.mongodb.org/mongo-driver/bson/bsoncodec" +package bson import ( "fmt" "reflect" "strings" - - "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 -// into a BSON document represented as bytes. The bytes returned must be a valid -// BSON document if the error is nil. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Marshaler] instead. -type Marshaler interface { - MarshalBSON() ([]byte, error) -} - -// ValueMarshaler is an interface implemented by types that can marshal -// themselves into a BSON value as bytes. The type must be the valid type for -// the bytes returned. The bytes and byte type together must be valid if the -// error is nil. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.ValueMarshaler] instead. -type ValueMarshaler interface { - MarshalBSONValue() (bsontype.Type, []byte, error) -} - -// Unmarshaler is an interface implemented by types that can unmarshal a BSON -// document representation of themselves. The BSON bytes can be assumed to be -// valid. UnmarshalBSON must copy the BSON bytes if it wishes to retain the data -// after returning. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Unmarshaler] instead. -type Unmarshaler interface { - UnmarshalBSON([]byte) error -} - -// ValueUnmarshaler is an interface implemented by types that can unmarshal a -// 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.ValueUnmarshaler] instead. -type ValueUnmarshaler interface { - UnmarshalBSONValue(bsontype.Type, []byte) error -} - // ValueEncoderError is an error returned from a ValueEncoder when the provided value can't be // encoded by the ValueEncoder. type ValueEncoderError struct { @@ -230,7 +187,7 @@ type DecodeContext struct { } // BinaryAsSlice causes the Decoder to unmarshal BSON binary field values that are the "Generic" or -// "Old" BSON binary subtype as a Go byte slice instead of a primitive.Binary. +// "Old" BSON binary subtype as a Go byte slice instead of a Binary. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.BinaryAsSlice] instead. func (dc *DecodeContext) BinaryAsSlice() { @@ -269,20 +226,20 @@ func (dc *DecodeContext) ZeroStructs() { dc.zeroStructs = true } -// DefaultDocumentM causes the Decoder to always unmarshal documents into the primitive.M type. This +// DefaultDocumentM causes the Decoder to always unmarshal documents into the M type. This // behavior is restricted to data typed as "interface{}" or "map[string]interface{}". // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.DefaultDocumentM] instead. func (dc *DecodeContext) DefaultDocumentM() { - dc.defaultDocumentType = reflect.TypeOf(primitive.M{}) + dc.defaultDocumentType = reflect.TypeOf(M{}) } -// DefaultDocumentD causes the Decoder to always unmarshal documents into the primitive.D type. This +// DefaultDocumentD causes the Decoder to always unmarshal documents into the D type. This // behavior is restricted to data typed as "interface{}" or "map[string]interface{}". // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.DefaultDocumentD] instead. func (dc *DecodeContext) DefaultDocumentD() { - dc.defaultDocumentType = reflect.TypeOf(primitive.D{}) + dc.defaultDocumentType = reflect.TypeOf(D{}) } // ValueCodec is an interface for encoding and decoding a reflect.Value. @@ -294,43 +251,52 @@ type ValueCodec interface { ValueDecoder } -// ValueEncoder is the interface implemented by types that can handle the encoding of a value. +// ValueEncoder is the interface implemented by types that can encode a provided Go type to BSON. +// The value to encode is provided as a reflect.Value and a bson.ValueWriter is used within the +// EncodeValue method to actually create the BSON representation. For convenience, ValueEncoderFunc +// is provided to allow use of a function with the correct signature as a ValueEncoder. An +// EncodeContext instance is provided to allow implementations to lookup further ValueEncoders and +// to provide configuration information. type ValueEncoder interface { - EncodeValue(EncodeContext, bsonrw.ValueWriter, reflect.Value) error + EncodeValue(EncodeContext, ValueWriter, reflect.Value) error } // ValueEncoderFunc is an adapter function that allows a function with the correct signature to be // used as a ValueEncoder. -type ValueEncoderFunc func(EncodeContext, bsonrw.ValueWriter, reflect.Value) error +type ValueEncoderFunc func(EncodeContext, ValueWriter, reflect.Value) error // EncodeValue implements the ValueEncoder interface. -func (fn ValueEncoderFunc) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (fn ValueEncoderFunc) EncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { return fn(ec, vw, val) } -// ValueDecoder is the interface implemented by types that can handle the decoding of a value. +// ValueDecoder is the interface implemented by types that can decode BSON to a provided Go type. +// Implementations should ensure that the value they receive is settable. Similar to ValueEncoderFunc, +// ValueDecoderFunc is provided to allow the use of a function with the correct signature as a +// ValueDecoder. A DecodeContext instance is provided and serves similar functionality to the +// EncodeContext. type ValueDecoder interface { - DecodeValue(DecodeContext, bsonrw.ValueReader, reflect.Value) error + DecodeValue(DecodeContext, ValueReader, reflect.Value) error } // ValueDecoderFunc is an adapter function that allows a function with the correct signature to be // used as a ValueDecoder. -type ValueDecoderFunc func(DecodeContext, bsonrw.ValueReader, reflect.Value) error +type ValueDecoderFunc func(DecodeContext, ValueReader, reflect.Value) error // DecodeValue implements the ValueDecoder interface. -func (fn ValueDecoderFunc) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (fn ValueDecoderFunc) DecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { 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) + decodeType(DecodeContext, 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) +type typeDecoderFunc func(DecodeContext, ValueReader, reflect.Type) (reflect.Value, error) -func (fn typeDecoderFunc) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (fn typeDecoderFunc) decodeType(dc DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { return fn(dc, vr, t) } @@ -345,12 +311,12 @@ 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) { +func decodeTypeOrValue(decoder ValueDecoder, dc DecodeContext, vr 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) { +func decodeTypeOrValueWithInfo(vd ValueDecoder, td typeDecoder, dc DecodeContext, vr 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 { diff --git a/bson/bsoncodec/bsoncodec_test.go b/bson/bsoncodec/bsoncodec_test.go deleted file mode 100644 index 2051b08539..0000000000 --- a/bson/bsoncodec/bsoncodec_test.go +++ /dev/null @@ -1,139 +0,0 @@ -// 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 ( - "fmt" - "reflect" - "testing" - "time" - - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" -) - -func ExampleValueEncoder() { - var _ ValueEncoderFunc = func(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { - if val.Kind() != reflect.String { - return ValueEncoderError{Name: "StringEncodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val} - } - - return vw.WriteString(val.String()) - } -} - -func ExampleValueDecoder() { - var _ ValueDecoderFunc = func(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { - if !val.CanSet() || val.Kind() != reflect.String { - return ValueDecoderError{Name: "StringDecodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val} - } - - if vr.Type() != bsontype.String { - return fmt.Errorf("cannot decode %v into a string type", vr.Type()) - } - - str, err := vr.ReadString() - if err != nil { - return err - } - val.SetString(str) - return nil - } -} - -func noerr(t *testing.T, err error) { - if err != nil { - t.Helper() - t.Errorf("Unexpected error: (%T)%v", err, err) - t.FailNow() - } -} - -func compareTime(t1, t2 time.Time) bool { - if t1.Location() != t2.Location() { - return false - } - return t1.Equal(t2) -} - -func compareErrors(err1, err2 error) bool { - if err1 == nil && err2 == nil { - return true - } - - if err1 == nil || err2 == nil { - return false - } - - if err1.Error() != err2.Error() { - return false - } - - return true -} - -func compareDecimal128(d1, d2 primitive.Decimal128) bool { - d1H, d1L := d1.GetBytes() - d2H, d2L := d2.GetBytes() - - if d1H != d2H { - return false - } - - if d1L != d2L { - return false - } - - return true -} - -type noPrivateFields struct { - a string -} - -func compareNoPrivateFields(npf1, npf2 noPrivateFields) bool { - return npf1.a != npf2.a // We don't want these to be equal -} - -type zeroTest struct { - reportZero bool -} - -func (z zeroTest) IsZero() bool { return z.reportZero } - -func compareZeroTest(_, _ zeroTest) bool { return true } - -type llCodec struct { - t *testing.T - decodeval interface{} - encodeval interface{} - err error -} - -func (llc *llCodec) EncodeValue(_ EncodeContext, _ bsonrw.ValueWriter, i interface{}) error { - if llc.err != nil { - return llc.err - } - - llc.encodeval = i - return nil -} - -func (llc *llCodec) DecodeValue(_ DecodeContext, _ bsonrw.ValueReader, val reflect.Value) error { - if llc.err != nil { - return llc.err - } - - if !reflect.TypeOf(llc.decodeval).AssignableTo(val.Type()) { - llc.t.Errorf("decodeval must be assignable to val provided to DecodeValue, but is not. decodeval %T; val %T", llc.decodeval, val) - return nil - } - - val.Set(reflect.ValueOf(llc.decodeval)) - return nil -} diff --git a/bson/bsoncodec/doc.go b/bson/bsoncodec/doc.go deleted file mode 100644 index 4613e5a1ec..0000000000 --- a/bson/bsoncodec/doc.go +++ /dev/null @@ -1,95 +0,0 @@ -// 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 -// encoding and decoding. -// -// The codec system is composed of two parts: -// -// 1) ValueEncoders and ValueDecoders that handle encoding and decoding Go values to and from BSON -// representations. -// -// 2) A Registry that holds these ValueEncoders and ValueDecoders and provides methods for -// retrieving them. -// -// # ValueEncoders and ValueDecoders -// -// The ValueEncoder interface is implemented by types that can encode a provided Go type to BSON. -// The value to encode is provided as a reflect.Value and a bsonrw.ValueWriter is used within the -// EncodeValue method to actually create the BSON representation. For convenience, ValueEncoderFunc -// is provided to allow use of a function with the correct signature as a ValueEncoder. An -// EncodeContext instance is provided to allow implementations to lookup further ValueEncoders and -// to provide configuration information. -// -// The ValueDecoder interface is the inverse of the ValueEncoder. Implementations should ensure that -// the value they receive is settable. Similar to ValueEncoderFunc, ValueDecoderFunc is provided to -// allow the use of a function with the correct signature as a ValueDecoder. A DecodeContext -// instance is provided and serves similar functionality to the EncodeContext. -// -// # Registry -// -// A Registry is a store for ValueEncoders, ValueDecoders, and a type map. See the Registry type -// documentation for examples of registering various custom encoders and decoders. A Registry can -// have three main types of codecs: -// -// 1. Type encoders/decoders - These can be registered using the RegisterTypeEncoder and -// RegisterTypeDecoder methods. The registered codec will be invoked when encoding/decoding a value -// whose type matches the registered type exactly. -// If the registered type is an interface, the codec will be invoked when encoding or decoding -// values whose type is the interface, but not for values with concrete types that implement the -// interface. -// -// 2. Hook encoders/decoders - These can be registered using the RegisterHookEncoder and -// RegisterHookDecoder methods. These methods only accept interface types and the registered codecs -// will be invoked when encoding or decoding values whose types implement the interface. An example -// of a hook defined by the driver is bson.Marshaler. The driver will call the MarshalBSON method -// for any value whose type implements bson.Marshaler, regardless of the value's concrete type. -// -// 3. Type map entries - This can be used to associate a BSON type with a Go type. These type -// associations are used when decoding into a bson.D/bson.M or a struct field of type interface{}. -// For example, by default, BSON int32 and int64 values decode as Go int32 and int64 instances, -// respectively, when decoding into a bson.D. The following code would change the behavior so these -// values decode as Go int instances instead: -// -// intType := reflect.TypeOf(int(0)) -// registry.RegisterTypeMapEntry(bsontype.Int32, intType).RegisterTypeMapEntry(bsontype.Int64, intType) -// -// 4. Kind encoder/decoders - These can be registered using the RegisterDefaultEncoder and -// RegisterDefaultDecoder methods. The registered codec will be invoked when encoding or decoding -// values whose reflect.Kind matches the registered reflect.Kind as long as the value's type doesn't -// match a registered type or hook encoder/decoder first. These methods should be used to change the -// behavior for all values for a specific kind. -// -// # Registry Lookup Procedure -// -// When looking up an encoder in a Registry, the precedence rules are as follows: -// -// 1. A type encoder registered for the exact type of the value. -// -// 2. A hook encoder registered for an interface that is implemented by the value or by a pointer to -// the value. If the value matches multiple hooks (e.g. the type implements bsoncodec.Marshaler and -// bsoncodec.ValueMarshaler), the first one registered will be selected. Note that registries -// constructed using bson.NewRegistry have driver-defined hooks registered for the -// bsoncodec.Marshaler, bsoncodec.ValueMarshaler, and bsoncodec.Proxy interfaces, so those will take -// precedence over any new hooks. -// -// 3. A kind encoder registered for the value's kind. -// -// If all of these lookups fail to find an encoder, an error of type ErrNoEncoder is returned. The -// same precedence rules apply for decoders, with the exception that an error of type ErrNoDecoder -// will be returned if no decoder is found. -// -// # DefaultValueEncoders and DefaultValueDecoders -// -// The DefaultValueEncoders and DefaultValueDecoders types provide a full set of ValueEncoders and -// ValueDecoders for handling a wide range of Go types, including all of the types within the -// primitive package. To make registering these codecs easier, a helper method on each type is -// provided. For the DefaultValueEncoders type the method is called RegisterDefaultEncoders and for -// the DefaultValueDecoders type the method is called RegisterDefaultDecoders, this method also -// handles registering type map entries for each BSON type. -package bsoncodec diff --git a/bson/bsoncodec/mode.go b/bson/bsoncodec/mode.go deleted file mode 100644 index fbd9f0a9e9..0000000000 --- a/bson/bsoncodec/mode.go +++ /dev/null @@ -1,65 +0,0 @@ -// 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 "fmt" - -type mode int - -const ( - _ mode = iota - mTopLevel - mDocument - mArray - mValue - mElement - mCodeWithScope - mSpacer -) - -func (m mode) String() string { - var str string - - switch m { - case mTopLevel: - str = "TopLevel" - case mDocument: - str = "DocumentMode" - case mArray: - str = "ArrayMode" - case mValue: - str = "ValueMode" - case mElement: - str = "ElementMode" - case mCodeWithScope: - str = "CodeWithScopeMode" - case mSpacer: - str = "CodeWithScopeSpacerFrame" - default: - str = "UnknownMode" - } - - return str -} - -// TransitionError is an error returned when an invalid progressing a -// ValueReader or ValueWriter state machine occurs. -type TransitionError struct { - parent mode - current mode - destination mode -} - -func (te TransitionError) Error() string { - if te.destination == mode(0) { - return fmt.Sprintf("invalid state transition: cannot read/write value while in %s", te.current) - } - if te.parent == mode(0) { - return fmt.Sprintf("invalid state transition: %s -> %s", te.current, te.destination) - } - return fmt.Sprintf("invalid state transition: %s -> %s; parent %s", te.current, te.destination, te.parent) -} diff --git a/bson/bsoncodec/registry.go b/bson/bsoncodec/registry.go deleted file mode 100644 index 196c491bbb..0000000000 --- a/bson/bsoncodec/registry.go +++ /dev/null @@ -1,524 +0,0 @@ -// 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 ( - "errors" - "fmt" - "reflect" - "sync" - - "go.mongodb.org/mongo-driver/bson/bsontype" -) - -// ErrNilType is returned when nil is passed to either LookupEncoder or LookupDecoder. -// -// Deprecated: ErrNilType will not be supported in Go Driver 2.0. -var ErrNilType = errors.New("cannot perform a decoder lookup on ") - -// ErrNotPointer is returned when a non-pointer type is provided to LookupDecoder. -// -// Deprecated: ErrNotPointer will not be supported in Go Driver 2.0. -var ErrNotPointer = errors.New("non-pointer provided to LookupDecoder") - -// ErrNoEncoder is returned when there wasn't an encoder available for a type. -// -// Deprecated: ErrNoEncoder will not be supported in Go Driver 2.0. -type ErrNoEncoder struct { - Type reflect.Type -} - -func (ene ErrNoEncoder) Error() string { - if ene.Type == nil { - return "no encoder found for " - } - return "no encoder found for " + ene.Type.String() -} - -// ErrNoDecoder is returned when there wasn't a decoder available for a type. -// -// Deprecated: ErrNoDecoder will not be supported in Go Driver 2.0. -type ErrNoDecoder struct { - Type reflect.Type -} - -func (end ErrNoDecoder) Error() string { - return "no decoder found for " + end.Type.String() -} - -// ErrNoTypeMapEntry is returned when there wasn't a type available for the provided BSON type. -// -// Deprecated: ErrNoTypeMapEntry will not be supported in Go Driver 2.0. -type ErrNoTypeMapEntry struct { - Type bsontype.Type -} - -func (entme ErrNoTypeMapEntry) Error() string { - return "no type map entry found for " + entme.Type.String() -} - -// ErrNotInterface is returned when the provided type is not an interface. -// -// Deprecated: ErrNotInterface will not be supported in Go Driver 2.0. -var ErrNotInterface = errors.New("The provided type is not an interface") - -// A RegistryBuilder is used to build a Registry. This type is not goroutine -// safe. -// -// Deprecated: Use Registry instead. -type RegistryBuilder struct { - registry *Registry -} - -// NewRegistryBuilder creates a new empty RegistryBuilder. -// -// Deprecated: Use NewRegistry instead. -func NewRegistryBuilder() *RegistryBuilder { - return &RegistryBuilder{ - registry: NewRegistry(), - } -} - -// RegisterCodec will register the provided ValueCodec for the provided type. -// -// Deprecated: Use Registry.RegisterTypeEncoder and Registry.RegisterTypeDecoder instead. -func (rb *RegistryBuilder) RegisterCodec(t reflect.Type, codec ValueCodec) *RegistryBuilder { - rb.RegisterTypeEncoder(t, codec) - rb.RegisterTypeDecoder(t, codec) - return rb -} - -// RegisterTypeEncoder will register the provided ValueEncoder for the provided type. -// -// The type will be used directly, so an encoder can be registered for a type and a different encoder can be registered -// for a pointer to that type. -// -// If the given type is an interface, the encoder will be called when marshaling a type that is that interface. It -// will not be called when marshaling a non-interface type that implements the interface. -// -// Deprecated: Use Registry.RegisterTypeEncoder instead. -func (rb *RegistryBuilder) RegisterTypeEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder { - rb.registry.RegisterTypeEncoder(t, enc) - return rb -} - -// RegisterHookEncoder will register an encoder for the provided interface type t. This encoder will be called when -// marshaling a type if the type implements t or a pointer to the type implements t. If the provided type is not -// an interface (i.e. t.Kind() != reflect.Interface), this method will panic. -// -// Deprecated: Use Registry.RegisterInterfaceEncoder instead. -func (rb *RegistryBuilder) RegisterHookEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder { - rb.registry.RegisterInterfaceEncoder(t, enc) - return rb -} - -// RegisterTypeDecoder will register the provided ValueDecoder for the provided type. -// -// The type will be used directly, so a decoder can be registered for a type and a different decoder can be registered -// for a pointer to that type. -// -// If the given type is an interface, the decoder will be called when unmarshaling into a type that is that interface. -// It will not be called when unmarshaling into a non-interface type that implements the interface. -// -// Deprecated: Use Registry.RegisterTypeDecoder instead. -func (rb *RegistryBuilder) RegisterTypeDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder { - rb.registry.RegisterTypeDecoder(t, dec) - return rb -} - -// RegisterHookDecoder will register an decoder for the provided interface type t. This decoder will be called when -// unmarshaling into a type if the type implements t or a pointer to the type implements t. If the provided type is not -// an interface (i.e. t.Kind() != reflect.Interface), this method will panic. -// -// Deprecated: Use Registry.RegisterInterfaceDecoder instead. -func (rb *RegistryBuilder) RegisterHookDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder { - rb.registry.RegisterInterfaceDecoder(t, dec) - return rb -} - -// RegisterEncoder registers the provided type and encoder pair. -// -// Deprecated: Use Registry.RegisterTypeEncoder or Registry.RegisterInterfaceEncoder instead. -func (rb *RegistryBuilder) RegisterEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder { - if t == tEmpty { - rb.registry.RegisterTypeEncoder(t, enc) - return rb - } - switch t.Kind() { - case reflect.Interface: - rb.registry.RegisterInterfaceEncoder(t, enc) - default: - rb.registry.RegisterTypeEncoder(t, enc) - } - return rb -} - -// RegisterDecoder registers the provided type and decoder pair. -// -// Deprecated: Use Registry.RegisterTypeDecoder or Registry.RegisterInterfaceDecoder instead. -func (rb *RegistryBuilder) RegisterDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder { - if t == nil { - rb.registry.RegisterTypeDecoder(t, dec) - return rb - } - if t == tEmpty { - rb.registry.RegisterTypeDecoder(t, dec) - return rb - } - switch t.Kind() { - case reflect.Interface: - rb.registry.RegisterInterfaceDecoder(t, dec) - default: - rb.registry.RegisterTypeDecoder(t, dec) - } - return rb -} - -// RegisterDefaultEncoder will register the provided ValueEncoder to the provided -// kind. -// -// Deprecated: Use Registry.RegisterKindEncoder instead. -func (rb *RegistryBuilder) RegisterDefaultEncoder(kind reflect.Kind, enc ValueEncoder) *RegistryBuilder { - rb.registry.RegisterKindEncoder(kind, enc) - return rb -} - -// RegisterDefaultDecoder will register the provided ValueDecoder to the -// provided kind. -// -// Deprecated: Use Registry.RegisterKindDecoder instead. -func (rb *RegistryBuilder) RegisterDefaultDecoder(kind reflect.Kind, dec ValueDecoder) *RegistryBuilder { - rb.registry.RegisterKindDecoder(kind, dec) - return rb -} - -// RegisterTypeMapEntry will register the provided type to the BSON type. The primary usage for this -// mapping is decoding situations where an empty interface is used and a default type needs to be -// created and decoded into. -// -// By default, BSON documents will decode into interface{} values as bson.D. To change the default type for BSON -// documents, a type map entry for 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{})) -// -// Deprecated: Use Registry.RegisterTypeMapEntry instead. -func (rb *RegistryBuilder) RegisterTypeMapEntry(bt bsontype.Type, rt reflect.Type) *RegistryBuilder { - rb.registry.RegisterTypeMapEntry(bt, rt) - return rb -} - -// Build creates a Registry from the current state of this RegistryBuilder. -// -// Deprecated: Use NewRegistry instead. -func (rb *RegistryBuilder) Build() *Registry { - r := &Registry{ - interfaceEncoders: append([]interfaceValueEncoder(nil), rb.registry.interfaceEncoders...), - interfaceDecoders: append([]interfaceValueDecoder(nil), rb.registry.interfaceDecoders...), - typeEncoders: rb.registry.typeEncoders.Clone(), - typeDecoders: rb.registry.typeDecoders.Clone(), - kindEncoders: rb.registry.kindEncoders.Clone(), - kindDecoders: rb.registry.kindDecoders.Clone(), - } - rb.registry.typeMap.Range(func(k, v interface{}) bool { - if k != nil && v != nil { - r.typeMap.Store(k, v) - } - return true - }) - return r -} - -// A Registry is used to store and retrieve codecs for types and interfaces. This type is the main -// typed passed around and Encoders and Decoders are constructed from it. -type Registry struct { - interfaceEncoders []interfaceValueEncoder - interfaceDecoders []interfaceValueDecoder - typeEncoders *typeEncoderCache - typeDecoders *typeDecoderCache - kindEncoders *kindEncoderCache - kindDecoders *kindDecoderCache - typeMap sync.Map // map[bsontype.Type]reflect.Type -} - -// NewRegistry creates a new empty Registry. -func NewRegistry() *Registry { - return &Registry{ - typeEncoders: new(typeEncoderCache), - typeDecoders: new(typeDecoderCache), - kindEncoders: new(kindEncoderCache), - kindDecoders: new(kindDecoderCache), - } -} - -// RegisterTypeEncoder registers the provided ValueEncoder for the provided type. -// -// The type will be used as provided, so an encoder can be registered for a type and a different -// encoder can be registered for a pointer to that type. -// -// If the given type is an interface, the encoder will be called when marshaling a type that is -// that interface. It will not be called when marshaling a non-interface type that implements the -// interface. To get the latter behavior, call RegisterHookEncoder instead. -// -// RegisterTypeEncoder should not be called concurrently with any other Registry method. -func (r *Registry) RegisterTypeEncoder(valueType reflect.Type, enc ValueEncoder) { - r.typeEncoders.Store(valueType, enc) -} - -// RegisterTypeDecoder registers the provided ValueDecoder for the provided type. -// -// The type will be used as provided, so a decoder can be registered for a type and a different -// decoder can be registered for a pointer to that type. -// -// If the given type is an interface, the decoder will be called when unmarshaling into a type that -// is that interface. It will not be called when unmarshaling into a non-interface type that -// implements the interface. To get the latter behavior, call RegisterHookDecoder instead. -// -// RegisterTypeDecoder should not be called concurrently with any other Registry method. -func (r *Registry) RegisterTypeDecoder(valueType reflect.Type, dec ValueDecoder) { - r.typeDecoders.Store(valueType, dec) -} - -// RegisterKindEncoder registers the provided ValueEncoder for the provided kind. -// -// Use RegisterKindEncoder to register an encoder for any type with the same underlying kind. For -// example, consider the type MyInt defined as -// -// type MyInt int32 -// -// To define an encoder for MyInt and int32, use RegisterKindEncoder like -// -// reg.RegisterKindEncoder(reflect.Int32, myEncoder) -// -// RegisterKindEncoder should not be called concurrently with any other Registry method. -func (r *Registry) RegisterKindEncoder(kind reflect.Kind, enc ValueEncoder) { - r.kindEncoders.Store(kind, enc) -} - -// RegisterKindDecoder registers the provided ValueDecoder for the provided kind. -// -// Use RegisterKindDecoder to register a decoder for any type with the same underlying kind. For -// example, consider the type MyInt defined as -// -// type MyInt int32 -// -// To define an decoder for MyInt and int32, use RegisterKindDecoder like -// -// reg.RegisterKindDecoder(reflect.Int32, myDecoder) -// -// RegisterKindDecoder should not be called concurrently with any other Registry method. -func (r *Registry) RegisterKindDecoder(kind reflect.Kind, dec ValueDecoder) { - r.kindDecoders.Store(kind, dec) -} - -// RegisterInterfaceEncoder registers an encoder for the provided interface type iface. This encoder will -// be called when marshaling a type if the type implements iface or a pointer to the type -// implements iface. If the provided type is not an interface -// (i.e. iface.Kind() != reflect.Interface), this method will panic. -// -// RegisterInterfaceEncoder should not be called concurrently with any other Registry method. -func (r *Registry) RegisterInterfaceEncoder(iface reflect.Type, enc ValueEncoder) { - if iface.Kind() != reflect.Interface { - panicStr := fmt.Errorf("RegisterInterfaceEncoder expects a type with kind reflect.Interface, "+ - "got type %s with kind %s", iface, iface.Kind()) - panic(panicStr) - } - - for idx, encoder := range r.interfaceEncoders { - if encoder.i == iface { - r.interfaceEncoders[idx].ve = enc - return - } - } - - r.interfaceEncoders = append(r.interfaceEncoders, interfaceValueEncoder{i: iface, ve: enc}) -} - -// RegisterInterfaceDecoder registers an decoder for the provided interface type iface. This decoder will -// be called when unmarshaling into a type if the type implements iface or a pointer to the type -// implements iface. If the provided type is not an interface (i.e. iface.Kind() != reflect.Interface), -// this method will panic. -// -// RegisterInterfaceDecoder should not be called concurrently with any other Registry method. -func (r *Registry) RegisterInterfaceDecoder(iface reflect.Type, dec ValueDecoder) { - if iface.Kind() != reflect.Interface { - panicStr := fmt.Errorf("RegisterInterfaceDecoder expects a type with kind reflect.Interface, "+ - "got type %s with kind %s", iface, iface.Kind()) - panic(panicStr) - } - - for idx, decoder := range r.interfaceDecoders { - if decoder.i == iface { - r.interfaceDecoders[idx].vd = dec - return - } - } - - r.interfaceDecoders = append(r.interfaceDecoders, interfaceValueDecoder{i: iface, vd: dec}) -} - -// RegisterTypeMapEntry will register the provided type to the BSON type. The primary usage for this -// mapping is decoding situations where an empty interface is used and a default type needs to be -// created and decoded into. -// -// By default, BSON documents will decode into interface{} values as bson.D. To change the default type for BSON -// documents, a type map entry for bsontype.EmbeddedDocument should be registered. For example, to force BSON documents -// to decode to bson.Raw, use the following code: -// -// reg.RegisterTypeMapEntry(bsontype.EmbeddedDocument, reflect.TypeOf(bson.Raw{})) -func (r *Registry) RegisterTypeMapEntry(bt bsontype.Type, rt reflect.Type) { - r.typeMap.Store(bt, rt) -} - -// LookupEncoder returns the first matching encoder in the Registry. It uses the following lookup -// order: -// -// 1. An encoder registered for the exact type. If the given type is an interface, an encoder -// registered using RegisterTypeEncoder for that interface will be selected. -// -// 2. An encoder registered using RegisterInterfaceEncoder for an interface implemented by the type -// or by a pointer to the type. -// -// 3. An encoder registered using RegisterKindEncoder for the kind of value. -// -// If no encoder is found, an error of type ErrNoEncoder is returned. LookupEncoder is safe for -// concurrent use by multiple goroutines after all codecs and encoders are registered. -func (r *Registry) LookupEncoder(valueType reflect.Type) (ValueEncoder, error) { - if valueType == nil { - return nil, ErrNoEncoder{Type: valueType} - } - enc, found := r.lookupTypeEncoder(valueType) - if found { - if enc == nil { - return nil, ErrNoEncoder{Type: valueType} - } - return enc, nil - } - - enc, found = r.lookupInterfaceEncoder(valueType, true) - if found { - return r.typeEncoders.LoadOrStore(valueType, enc), nil - } - - if v, ok := r.kindEncoders.Load(valueType.Kind()); ok { - return r.storeTypeEncoder(valueType, v), nil - } - return nil, ErrNoEncoder{Type: valueType} -} - -func (r *Registry) storeTypeEncoder(rt reflect.Type, enc ValueEncoder) ValueEncoder { - return r.typeEncoders.LoadOrStore(rt, enc) -} - -func (r *Registry) lookupTypeEncoder(rt reflect.Type) (ValueEncoder, bool) { - return r.typeEncoders.Load(rt) -} - -func (r *Registry) lookupInterfaceEncoder(valueType reflect.Type, allowAddr bool) (ValueEncoder, bool) { - if valueType == nil { - return nil, false - } - for _, ienc := range r.interfaceEncoders { - if valueType.Implements(ienc.i) { - return ienc.ve, true - } - if allowAddr && valueType.Kind() != reflect.Ptr && reflect.PtrTo(valueType).Implements(ienc.i) { - // if *t implements an interface, this will catch if t implements an interface further - // ahead in interfaceEncoders - defaultEnc, found := r.lookupInterfaceEncoder(valueType, false) - if !found { - defaultEnc, _ = r.kindEncoders.Load(valueType.Kind()) - } - return newCondAddrEncoder(ienc.ve, defaultEnc), true - } - } - return nil, false -} - -// LookupDecoder returns the first matching decoder in the Registry. It uses the following lookup -// order: -// -// 1. A decoder registered for the exact type. If the given type is an interface, a decoder -// registered using RegisterTypeDecoder for that interface will be selected. -// -// 2. A decoder registered using RegisterInterfaceDecoder for an interface implemented by the type or by -// a pointer to the type. -// -// 3. A decoder registered using RegisterKindDecoder for the kind of value. -// -// If no decoder is found, an error of type ErrNoDecoder is returned. LookupDecoder is safe for -// concurrent use by multiple goroutines after all codecs and decoders are registered. -func (r *Registry) LookupDecoder(valueType reflect.Type) (ValueDecoder, error) { - if valueType == nil { - return nil, ErrNilType - } - dec, found := r.lookupTypeDecoder(valueType) - if found { - if dec == nil { - return nil, ErrNoDecoder{Type: valueType} - } - return dec, nil - } - - dec, found = r.lookupInterfaceDecoder(valueType, true) - if found { - return r.storeTypeDecoder(valueType, dec), nil - } - - if v, ok := r.kindDecoders.Load(valueType.Kind()); ok { - return r.storeTypeDecoder(valueType, v), nil - } - return nil, ErrNoDecoder{Type: valueType} -} - -func (r *Registry) lookupTypeDecoder(valueType reflect.Type) (ValueDecoder, bool) { - return r.typeDecoders.Load(valueType) -} - -func (r *Registry) storeTypeDecoder(typ reflect.Type, dec ValueDecoder) ValueDecoder { - return r.typeDecoders.LoadOrStore(typ, dec) -} - -func (r *Registry) lookupInterfaceDecoder(valueType reflect.Type, allowAddr bool) (ValueDecoder, bool) { - for _, idec := range r.interfaceDecoders { - if valueType.Implements(idec.i) { - return idec.vd, true - } - if allowAddr && valueType.Kind() != reflect.Ptr && reflect.PtrTo(valueType).Implements(idec.i) { - // if *t implements an interface, this will catch if t implements an interface further - // ahead in interfaceDecoders - defaultDec, found := r.lookupInterfaceDecoder(valueType, false) - if !found { - defaultDec, _ = r.kindDecoders.Load(valueType.Kind()) - } - return newCondAddrDecoder(idec.vd, defaultDec), true - } - } - return nil, false -} - -// LookupTypeMapEntry inspects the registry's type map for a Go type for the corresponding BSON -// type. If no type is found, ErrNoTypeMapEntry is returned. -// -// LookupTypeMapEntry should not be called concurrently with any other Registry method. -func (r *Registry) LookupTypeMapEntry(bt bsontype.Type) (reflect.Type, error) { - v, ok := r.typeMap.Load(bt) - if v == nil || !ok { - return nil, ErrNoTypeMapEntry{Type: bt} - } - return v.(reflect.Type), nil -} - -type interfaceValueEncoder struct { - i reflect.Type - ve ValueEncoder -} - -type interfaceValueDecoder struct { - i reflect.Type - vd ValueDecoder -} diff --git a/bson/bsoncodec/types.go b/bson/bsoncodec/types.go deleted file mode 100644 index 6ade17b7d3..0000000000 --- a/bson/bsoncodec/types.go +++ /dev/null @@ -1,58 +0,0 @@ -// 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 ( - "encoding/json" - "net/url" - "reflect" - "time" - - "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" -) - -var tBool = reflect.TypeOf(false) -var tFloat64 = reflect.TypeOf(float64(0)) -var tInt32 = reflect.TypeOf(int32(0)) -var tInt64 = reflect.TypeOf(int64(0)) -var tString = reflect.TypeOf("") -var tTime = reflect.TypeOf(time.Time{}) - -var tEmpty = reflect.TypeOf((*interface{})(nil)).Elem() -var tByteSlice = reflect.TypeOf([]byte(nil)) -var tByte = reflect.TypeOf(byte(0x00)) -var tURL = reflect.TypeOf(url.URL{}) -var tJSONNumber = reflect.TypeOf(json.Number("")) - -var tValueMarshaler = reflect.TypeOf((*ValueMarshaler)(nil)).Elem() -var tValueUnmarshaler = reflect.TypeOf((*ValueUnmarshaler)(nil)).Elem() -var tMarshaler = reflect.TypeOf((*Marshaler)(nil)).Elem() -var tUnmarshaler = reflect.TypeOf((*Unmarshaler)(nil)).Elem() -var tProxy = reflect.TypeOf((*Proxy)(nil)).Elem() -var tZeroer = reflect.TypeOf((*Zeroer)(nil)).Elem() - -var tBinary = reflect.TypeOf(primitive.Binary{}) -var tUndefined = reflect.TypeOf(primitive.Undefined{}) -var tOID = reflect.TypeOf(primitive.ObjectID{}) -var tDateTime = reflect.TypeOf(primitive.DateTime(0)) -var tNull = reflect.TypeOf(primitive.Null{}) -var tRegex = reflect.TypeOf(primitive.Regex{}) -var tCodeWithScope = reflect.TypeOf(primitive.CodeWithScope{}) -var tDBPointer = reflect.TypeOf(primitive.DBPointer{}) -var tJavaScript = reflect.TypeOf(primitive.JavaScript("")) -var tSymbol = reflect.TypeOf(primitive.Symbol("")) -var tTimestamp = reflect.TypeOf(primitive.Timestamp{}) -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 tA = reflect.TypeOf(primitive.A{}) -var tE = reflect.TypeOf(primitive.E{}) - -var tCoreDocument = reflect.TypeOf(bsoncore.Document{}) -var tCoreArray = reflect.TypeOf(bsoncore.Array{}) diff --git a/bson/bsoncodec_test.go b/bson/bsoncodec_test.go new file mode 100644 index 0000000000..d1dc21a953 --- /dev/null +++ b/bson/bsoncodec_test.go @@ -0,0 +1,72 @@ +// 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 bson + +import ( + "fmt" + "reflect" + "testing" +) + +func ExampleValueEncoder() { + var _ ValueEncoderFunc = func(ec EncodeContext, vw ValueWriter, val reflect.Value) error { + if val.Kind() != reflect.String { + return ValueEncoderError{Name: "StringEncodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val} + } + + return vw.WriteString(val.String()) + } +} + +func ExampleValueDecoder() { + var _ ValueDecoderFunc = func(dc DecodeContext, vr ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Kind() != reflect.String { + return ValueDecoderError{Name: "StringDecodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val} + } + + if vr.Type() != TypeString { + return fmt.Errorf("cannot decode %v into a string type", vr.Type()) + } + + str, err := vr.ReadString() + if err != nil { + return err + } + val.SetString(str) + return nil + } +} + +type llCodec struct { + t *testing.T + decodeval interface{} + encodeval interface{} + err error +} + +func (llc *llCodec) EncodeValue(_ EncodeContext, _ ValueWriter, i interface{}) error { + if llc.err != nil { + return llc.err + } + + llc.encodeval = i + return nil +} + +func (llc *llCodec) DecodeValue(_ DecodeContext, _ ValueReader, val reflect.Value) error { + if llc.err != nil { + return llc.err + } + + if !reflect.TypeOf(llc.decodeval).AssignableTo(val.Type()) { + llc.t.Errorf("decodeval must be assignable to val provided to DecodeValue, but is not. decodeval %T; val %T", llc.decodeval, val) + return nil + } + + val.Set(reflect.ValueOf(llc.decodeval)) + return nil +} diff --git a/bson/bsonrw/bsonrw_test.go b/bson/bsonrw/bsonrw_test.go deleted file mode 100644 index 46579616b2..0000000000 --- a/bson/bsonrw/bsonrw_test.go +++ /dev/null @@ -1,33 +0,0 @@ -// 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 bsonrw - -import "testing" - -func compareErrors(err1, err2 error) bool { - if err1 == nil && err2 == nil { - return true - } - - if err1 == nil || err2 == nil { - return false - } - - if err1.Error() != err2.Error() { - return false - } - - return true -} - -func noerr(t *testing.T, err error) { - if err != nil { - t.Helper() - t.Errorf("Unexpected error: (%T)%v", err, err) - t.FailNow() - } -} diff --git a/bson/bsonrw/bsonrwtest/bsonrwtest.go b/bson/bsonrw/bsonrwtest/bsonrwtest.go deleted file mode 100644 index b28cd7f23b..0000000000 --- a/bson/bsonrw/bsonrwtest/bsonrwtest.go +++ /dev/null @@ -1,848 +0,0 @@ -// 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 bsonrwtest provides utilities for testing the "bson/bsonrw" package. -package bsonrwtest // import "go.mongodb.org/mongo-driver/bson/bsonrw/bsonrwtest" - -import ( - "testing" - - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" -) - -var _ bsonrw.ValueReader = (*ValueReaderWriter)(nil) -var _ bsonrw.ValueWriter = (*ValueReaderWriter)(nil) - -// Invoked is a type used to indicate what method was called last. -type Invoked byte - -// These are the different methods that can be invoked. -const ( - Nothing Invoked = iota - ReadArray - ReadBinary - ReadBoolean - ReadDocument - ReadCodeWithScope - ReadDBPointer - ReadDateTime - ReadDecimal128 - ReadDouble - ReadInt32 - ReadInt64 - ReadJavascript - ReadMaxKey - ReadMinKey - ReadNull - ReadObjectID - ReadRegex - ReadString - ReadSymbol - ReadTimestamp - ReadUndefined - ReadElement - ReadValue - WriteArray - WriteBinary - WriteBinaryWithSubtype - WriteBoolean - WriteCodeWithScope - WriteDBPointer - WriteDateTime - WriteDecimal128 - WriteDouble - WriteInt32 - WriteInt64 - WriteJavascript - WriteMaxKey - WriteMinKey - WriteNull - WriteObjectID - WriteRegex - WriteString - WriteDocument - WriteSymbol - WriteTimestamp - WriteUndefined - WriteDocumentElement - WriteDocumentEnd - WriteArrayElement - WriteArrayEnd - Skip -) - -func (i Invoked) String() string { - switch i { - case Nothing: - return "Nothing" - case ReadArray: - return "ReadArray" - case ReadBinary: - return "ReadBinary" - case ReadBoolean: - return "ReadBoolean" - case ReadDocument: - return "ReadDocument" - case ReadCodeWithScope: - return "ReadCodeWithScope" - case ReadDBPointer: - return "ReadDBPointer" - case ReadDateTime: - return "ReadDateTime" - case ReadDecimal128: - return "ReadDecimal128" - case ReadDouble: - return "ReadDouble" - case ReadInt32: - return "ReadInt32" - case ReadInt64: - return "ReadInt64" - case ReadJavascript: - return "ReadJavascript" - case ReadMaxKey: - return "ReadMaxKey" - case ReadMinKey: - return "ReadMinKey" - case ReadNull: - return "ReadNull" - case ReadObjectID: - return "ReadObjectID" - case ReadRegex: - return "ReadRegex" - case ReadString: - return "ReadString" - case ReadSymbol: - return "ReadSymbol" - case ReadTimestamp: - return "ReadTimestamp" - case ReadUndefined: - return "ReadUndefined" - case ReadElement: - return "ReadElement" - case ReadValue: - return "ReadValue" - case WriteArray: - return "WriteArray" - case WriteBinary: - return "WriteBinary" - case WriteBinaryWithSubtype: - return "WriteBinaryWithSubtype" - case WriteBoolean: - return "WriteBoolean" - case WriteCodeWithScope: - return "WriteCodeWithScope" - case WriteDBPointer: - return "WriteDBPointer" - case WriteDateTime: - return "WriteDateTime" - case WriteDecimal128: - return "WriteDecimal128" - case WriteDouble: - return "WriteDouble" - case WriteInt32: - return "WriteInt32" - case WriteInt64: - return "WriteInt64" - case WriteJavascript: - return "WriteJavascript" - case WriteMaxKey: - return "WriteMaxKey" - case WriteMinKey: - return "WriteMinKey" - case WriteNull: - return "WriteNull" - case WriteObjectID: - return "WriteObjectID" - case WriteRegex: - return "WriteRegex" - case WriteString: - return "WriteString" - case WriteDocument: - return "WriteDocument" - case WriteSymbol: - return "WriteSymbol" - case WriteTimestamp: - return "WriteTimestamp" - case WriteUndefined: - return "WriteUndefined" - case WriteDocumentElement: - return "WriteDocumentElement" - case WriteDocumentEnd: - return "WriteDocumentEnd" - case WriteArrayElement: - return "WriteArrayElement" - case WriteArrayEnd: - return "WriteArrayEnd" - default: - return "" - } -} - -// ValueReaderWriter is a test implementation of a bsonrw.ValueReader and bsonrw.ValueWriter -type ValueReaderWriter struct { - T *testing.T - Invoked Invoked - Return interface{} // Can be a primitive or a bsoncore.Value - BSONType bsontype.Type - Err error - ErrAfter Invoked // error after this method is called - depth uint64 -} - -// prevent infinite recursion. -func (llvrw *ValueReaderWriter) checkdepth() { - llvrw.depth++ - if llvrw.depth > 1000 { - panic("max depth exceeded") - } -} - -// Type implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) Type() bsontype.Type { - llvrw.checkdepth() - return llvrw.BSONType -} - -// Skip implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) Skip() error { - llvrw.checkdepth() - llvrw.Invoked = Skip - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// ReadArray implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadArray() (bsonrw.ArrayReader, error) { - llvrw.checkdepth() - llvrw.Invoked = ReadArray - if llvrw.ErrAfter == llvrw.Invoked { - return nil, llvrw.Err - } - - return llvrw, nil -} - -// ReadBinary implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadBinary() (b []byte, btype byte, err error) { - llvrw.checkdepth() - llvrw.Invoked = ReadBinary - if llvrw.ErrAfter == llvrw.Invoked { - return nil, 0x00, llvrw.Err - } - - switch tt := llvrw.Return.(type) { - case bsoncore.Value: - subtype, data, _, ok := bsoncore.ReadBinary(tt.Data) - if !ok { - llvrw.T.Error("Invalid Value provided for return value of ReadBinary.") - return nil, 0x00, nil - } - return data, subtype, nil - default: - llvrw.T.Errorf("Incorrect type provided for return value of ReadBinary: %T", llvrw.Return) - return nil, 0x00, nil - } -} - -// ReadBoolean implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadBoolean() (bool, error) { - llvrw.checkdepth() - llvrw.Invoked = ReadBoolean - if llvrw.ErrAfter == llvrw.Invoked { - return false, llvrw.Err - } - - switch tt := llvrw.Return.(type) { - case bool: - return tt, nil - case bsoncore.Value: - b, _, ok := bsoncore.ReadBoolean(tt.Data) - if !ok { - llvrw.T.Error("Invalid Value provided for return value of ReadBoolean.") - return false, nil - } - return b, nil - default: - llvrw.T.Errorf("Incorrect type provided for return value of ReadBoolean: %T", llvrw.Return) - return false, nil - } -} - -// ReadDocument implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadDocument() (bsonrw.DocumentReader, error) { - llvrw.checkdepth() - llvrw.Invoked = ReadDocument - if llvrw.ErrAfter == llvrw.Invoked { - return nil, llvrw.Err - } - - return llvrw, nil -} - -// ReadCodeWithScope implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadCodeWithScope() (code string, dr bsonrw.DocumentReader, err error) { - llvrw.checkdepth() - llvrw.Invoked = ReadCodeWithScope - if llvrw.ErrAfter == llvrw.Invoked { - return "", nil, llvrw.Err - } - - return "", llvrw, nil -} - -// ReadDBPointer implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadDBPointer() (ns string, oid primitive.ObjectID, err error) { - llvrw.checkdepth() - llvrw.Invoked = ReadDBPointer - if llvrw.ErrAfter == llvrw.Invoked { - return "", primitive.ObjectID{}, llvrw.Err - } - - switch tt := llvrw.Return.(type) { - case bsoncore.Value: - ns, oid, _, ok := bsoncore.ReadDBPointer(tt.Data) - if !ok { - llvrw.T.Error("Invalid Value instance provided for return value of ReadDBPointer") - return "", primitive.ObjectID{}, nil - } - return ns, oid, nil - default: - llvrw.T.Errorf("Incorrect type provided for return value of ReadDBPointer: %T", llvrw.Return) - return "", primitive.ObjectID{}, nil - } -} - -// ReadDateTime implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadDateTime() (int64, error) { - llvrw.checkdepth() - llvrw.Invoked = ReadDateTime - if llvrw.ErrAfter == llvrw.Invoked { - return 0, llvrw.Err - } - - dt, ok := llvrw.Return.(int64) - if !ok { - llvrw.T.Errorf("Incorrect type provided for return value of ReadDateTime: %T", llvrw.Return) - return 0, nil - } - - return dt, nil -} - -// ReadDecimal128 implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadDecimal128() (primitive.Decimal128, error) { - llvrw.checkdepth() - llvrw.Invoked = ReadDecimal128 - if llvrw.ErrAfter == llvrw.Invoked { - return primitive.Decimal128{}, llvrw.Err - } - - d128, ok := llvrw.Return.(primitive.Decimal128) - if !ok { - llvrw.T.Errorf("Incorrect type provided for return value of ReadDecimal128: %T", llvrw.Return) - return primitive.Decimal128{}, nil - } - - return d128, nil -} - -// ReadDouble implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadDouble() (float64, error) { - llvrw.checkdepth() - llvrw.Invoked = ReadDouble - if llvrw.ErrAfter == llvrw.Invoked { - return 0, llvrw.Err - } - - f64, ok := llvrw.Return.(float64) - if !ok { - llvrw.T.Errorf("Incorrect type provided for return value of ReadDouble: %T", llvrw.Return) - return 0, nil - } - - return f64, nil -} - -// ReadInt32 implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadInt32() (int32, error) { - llvrw.checkdepth() - llvrw.Invoked = ReadInt32 - if llvrw.ErrAfter == llvrw.Invoked { - return 0, llvrw.Err - } - - i32, ok := llvrw.Return.(int32) - if !ok { - llvrw.T.Errorf("Incorrect type provided for return value of ReadInt32: %T", llvrw.Return) - return 0, nil - } - - return i32, nil -} - -// ReadInt64 implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadInt64() (int64, error) { - llvrw.checkdepth() - llvrw.Invoked = ReadInt64 - if llvrw.ErrAfter == llvrw.Invoked { - return 0, llvrw.Err - } - i64, ok := llvrw.Return.(int64) - if !ok { - llvrw.T.Errorf("Incorrect type provided for return value of ReadInt64: %T", llvrw.Return) - return 0, nil - } - - return i64, nil -} - -// ReadJavascript implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadJavascript() (code string, err error) { - llvrw.checkdepth() - llvrw.Invoked = ReadJavascript - if llvrw.ErrAfter == llvrw.Invoked { - return "", llvrw.Err - } - js, ok := llvrw.Return.(string) - if !ok { - llvrw.T.Errorf("Incorrect type provided for return value of ReadJavascript: %T", llvrw.Return) - return "", nil - } - - return js, nil -} - -// ReadMaxKey implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadMaxKey() error { - llvrw.checkdepth() - llvrw.Invoked = ReadMaxKey - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - - return nil -} - -// ReadMinKey implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadMinKey() error { - llvrw.checkdepth() - llvrw.Invoked = ReadMinKey - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - - return nil -} - -// ReadNull implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadNull() error { - llvrw.checkdepth() - llvrw.Invoked = ReadNull - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - - return nil -} - -// ReadObjectID implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadObjectID() (primitive.ObjectID, error) { - llvrw.checkdepth() - llvrw.Invoked = ReadObjectID - if llvrw.ErrAfter == llvrw.Invoked { - return primitive.ObjectID{}, llvrw.Err - } - oid, ok := llvrw.Return.(primitive.ObjectID) - if !ok { - llvrw.T.Errorf("Incorrect type provided for return value of ReadObjectID: %T", llvrw.Return) - return primitive.ObjectID{}, nil - } - - return oid, nil -} - -// ReadRegex implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadRegex() (pattern string, options string, err error) { - llvrw.checkdepth() - llvrw.Invoked = ReadRegex - if llvrw.ErrAfter == llvrw.Invoked { - return "", "", llvrw.Err - } - switch tt := llvrw.Return.(type) { - case bsoncore.Value: - pattern, options, _, ok := bsoncore.ReadRegex(tt.Data) - if !ok { - llvrw.T.Error("Invalid Value instance provided for ReadRegex") - return "", "", nil - } - return pattern, options, nil - default: - llvrw.T.Errorf("Incorrect type provided for return value of ReadRegex: %T", llvrw.Return) - return "", "", nil - } -} - -// ReadString implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadString() (string, error) { - llvrw.checkdepth() - llvrw.Invoked = ReadString - if llvrw.ErrAfter == llvrw.Invoked { - return "", llvrw.Err - } - str, ok := llvrw.Return.(string) - if !ok { - llvrw.T.Errorf("Incorrect type provided for return value of ReadString: %T", llvrw.Return) - return "", nil - } - - return str, nil -} - -// ReadSymbol implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadSymbol() (symbol string, err error) { - llvrw.checkdepth() - llvrw.Invoked = ReadSymbol - if llvrw.ErrAfter == llvrw.Invoked { - return "", llvrw.Err - } - switch tt := llvrw.Return.(type) { - case string: - return tt, nil - case bsoncore.Value: - symbol, _, ok := bsoncore.ReadSymbol(tt.Data) - if !ok { - llvrw.T.Error("Invalid Value instance provided for ReadSymbol") - return "", nil - } - return symbol, nil - default: - llvrw.T.Errorf("Incorrect type provided for return value of ReadSymbol: %T", llvrw.Return) - return "", nil - } -} - -// ReadTimestamp implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadTimestamp() (t uint32, i uint32, err error) { - llvrw.checkdepth() - llvrw.Invoked = ReadTimestamp - if llvrw.ErrAfter == llvrw.Invoked { - return 0, 0, llvrw.Err - } - switch tt := llvrw.Return.(type) { - case bsoncore.Value: - t, i, _, ok := bsoncore.ReadTimestamp(tt.Data) - if !ok { - llvrw.T.Errorf("Invalid Value instance provided for return value of ReadTimestamp") - return 0, 0, nil - } - return t, i, nil - default: - llvrw.T.Errorf("Incorrect type provided for return value of ReadTimestamp: %T", llvrw.Return) - return 0, 0, nil - } -} - -// ReadUndefined implements the bsonrw.ValueReader interface. -func (llvrw *ValueReaderWriter) ReadUndefined() error { - llvrw.checkdepth() - llvrw.Invoked = ReadUndefined - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - - return nil -} - -// WriteArray implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteArray() (bsonrw.ArrayWriter, error) { - llvrw.checkdepth() - llvrw.Invoked = WriteArray - if llvrw.ErrAfter == llvrw.Invoked { - return nil, llvrw.Err - } - return llvrw, nil -} - -// WriteBinary implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteBinary([]byte) error { - llvrw.checkdepth() - llvrw.Invoked = WriteBinary - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteBinaryWithSubtype implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteBinaryWithSubtype([]byte, byte) error { - llvrw.checkdepth() - llvrw.Invoked = WriteBinaryWithSubtype - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteBoolean implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteBoolean(bool) error { - llvrw.checkdepth() - llvrw.Invoked = WriteBoolean - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteCodeWithScope implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteCodeWithScope(string) (bsonrw.DocumentWriter, error) { - llvrw.checkdepth() - llvrw.Invoked = WriteCodeWithScope - if llvrw.ErrAfter == llvrw.Invoked { - return nil, llvrw.Err - } - return llvrw, nil -} - -// WriteDBPointer implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteDBPointer(string, primitive.ObjectID) error { - llvrw.checkdepth() - llvrw.Invoked = WriteDBPointer - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteDateTime implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteDateTime(int64) error { - llvrw.checkdepth() - llvrw.Invoked = WriteDateTime - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteDecimal128 implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteDecimal128(primitive.Decimal128) error { - llvrw.checkdepth() - llvrw.Invoked = WriteDecimal128 - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteDouble implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteDouble(float64) error { - llvrw.checkdepth() - llvrw.Invoked = WriteDouble - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteInt32 implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteInt32(int32) error { - llvrw.checkdepth() - llvrw.Invoked = WriteInt32 - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteInt64 implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteInt64(int64) error { - llvrw.checkdepth() - llvrw.Invoked = WriteInt64 - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteJavascript implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteJavascript(string) error { - llvrw.checkdepth() - llvrw.Invoked = WriteJavascript - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteMaxKey implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteMaxKey() error { - llvrw.checkdepth() - llvrw.Invoked = WriteMaxKey - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteMinKey implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteMinKey() error { - llvrw.checkdepth() - llvrw.Invoked = WriteMinKey - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteNull implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteNull() error { - llvrw.checkdepth() - llvrw.Invoked = WriteNull - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteObjectID implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteObjectID(primitive.ObjectID) error { - llvrw.checkdepth() - llvrw.Invoked = WriteObjectID - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteRegex implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteRegex(string, string) error { - llvrw.checkdepth() - llvrw.Invoked = WriteRegex - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteString implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteString(string) error { - llvrw.checkdepth() - llvrw.Invoked = WriteString - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteDocument implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteDocument() (bsonrw.DocumentWriter, error) { - llvrw.checkdepth() - llvrw.Invoked = WriteDocument - if llvrw.ErrAfter == llvrw.Invoked { - return nil, llvrw.Err - } - return llvrw, nil -} - -// WriteSymbol implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteSymbol(string) error { - llvrw.checkdepth() - llvrw.Invoked = WriteSymbol - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteTimestamp implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteTimestamp(uint32, uint32) error { - llvrw.checkdepth() - llvrw.Invoked = WriteTimestamp - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// WriteUndefined implements the bsonrw.ValueWriter interface. -func (llvrw *ValueReaderWriter) WriteUndefined() error { - llvrw.checkdepth() - llvrw.Invoked = WriteUndefined - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - return nil -} - -// ReadElement implements the bsonrw.DocumentReader interface. -func (llvrw *ValueReaderWriter) ReadElement() (string, bsonrw.ValueReader, error) { - llvrw.checkdepth() - llvrw.Invoked = ReadElement - if llvrw.ErrAfter == llvrw.Invoked { - return "", nil, llvrw.Err - } - - return "", llvrw, nil -} - -// WriteDocumentElement implements the bsonrw.DocumentWriter interface. -func (llvrw *ValueReaderWriter) WriteDocumentElement(string) (bsonrw.ValueWriter, error) { - llvrw.checkdepth() - llvrw.Invoked = WriteDocumentElement - if llvrw.ErrAfter == llvrw.Invoked { - return nil, llvrw.Err - } - - return llvrw, nil -} - -// WriteDocumentEnd implements the bsonrw.DocumentWriter interface. -func (llvrw *ValueReaderWriter) WriteDocumentEnd() error { - llvrw.checkdepth() - llvrw.Invoked = WriteDocumentEnd - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - - return nil -} - -// ReadValue implements the bsonrw.ArrayReader interface. -func (llvrw *ValueReaderWriter) ReadValue() (bsonrw.ValueReader, error) { - llvrw.checkdepth() - llvrw.Invoked = ReadValue - if llvrw.ErrAfter == llvrw.Invoked { - return nil, llvrw.Err - } - - return llvrw, nil -} - -// WriteArrayElement implements the bsonrw.ArrayWriter interface. -func (llvrw *ValueReaderWriter) WriteArrayElement() (bsonrw.ValueWriter, error) { - llvrw.checkdepth() - llvrw.Invoked = WriteArrayElement - if llvrw.ErrAfter == llvrw.Invoked { - return nil, llvrw.Err - } - - return llvrw, nil -} - -// WriteArrayEnd implements the bsonrw.ArrayWriter interface. -func (llvrw *ValueReaderWriter) WriteArrayEnd() error { - llvrw.checkdepth() - llvrw.Invoked = WriteArrayEnd - if llvrw.ErrAfter == llvrw.Invoked { - return llvrw.Err - } - - return nil -} diff --git a/bson/bsonrw/doc.go b/bson/bsonrw/doc.go deleted file mode 100644 index 750b0d2af5..0000000000 --- a/bson/bsonrw/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -// 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 bsonrw contains abstractions for reading and writing -// BSON and BSON like types from sources. -package bsonrw // import "go.mongodb.org/mongo-driver/bson/bsonrw" diff --git a/bson/bsonrw_test.go b/bson/bsonrw_test.go new file mode 100644 index 0000000000..f37eb0142e --- /dev/null +++ b/bson/bsonrw_test.go @@ -0,0 +1,844 @@ +// 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 bson + +import ( + "testing" + + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" +) + +var _ ValueReader = (*valueReaderWriter)(nil) +var _ ValueWriter = (*valueReaderWriter)(nil) + +// invoked is a type used to indicate what method was called last. +type invoked byte + +// These are the different methods that can be invoked. +const ( + nothing invoked = iota + readArray + readBinary + readBoolean + readDocument + readCodeWithScope + readDBPointer + readDateTime + readDecimal128 + readDouble + readInt32 + readInt64 + readJavascript + readMaxKey + readMinKey + readNull + readObjectID + readRegex + readString + readSymbol + readTimestamp + readUndefined + readElement + readValue + writeArray + writeBinary + writeBinaryWithSubtype + writeBoolean + writeCodeWithScope + writeDBPointer + writeDateTime + writeDecimal128 + writeDouble + writeInt32 + writeInt64 + writeJavascript + writeMaxKey + writeMinKey + writeNull + writeObjectID + writeRegex + writeString + writeDocument + writeSymbol + writeTimestamp + writeUndefined + writeDocumentElement + writeDocumentEnd + writeArrayElement + writeArrayEnd + skip +) + +func (i invoked) String() string { + switch i { + case nothing: + return "Nothing" + case readArray: + return "ReadArray" + case readBinary: + return "ReadBinary" + case readBoolean: + return "ReadBoolean" + case readDocument: + return "ReadDocument" + case readCodeWithScope: + return "ReadCodeWithScope" + case readDBPointer: + return "ReadDBPointer" + case readDateTime: + return "ReadDateTime" + case readDecimal128: + return "ReadDecimal128" + case readDouble: + return "ReadDouble" + case readInt32: + return "ReadInt32" + case readInt64: + return "ReadInt64" + case readJavascript: + return "ReadJavascript" + case readMaxKey: + return "ReadMaxKey" + case readMinKey: + return "ReadMinKey" + case readNull: + return "ReadNull" + case readObjectID: + return "ReadObjectID" + case readRegex: + return "ReadRegex" + case readString: + return "ReadString" + case readSymbol: + return "ReadSymbol" + case readTimestamp: + return "ReadTimestamp" + case readUndefined: + return "ReadUndefined" + case readElement: + return "ReadElement" + case readValue: + return "ReadValue" + case writeArray: + return "WriteArray" + case writeBinary: + return "WriteBinary" + case writeBinaryWithSubtype: + return "WriteBinaryWithSubtype" + case writeBoolean: + return "WriteBoolean" + case writeCodeWithScope: + return "WriteCodeWithScope" + case writeDBPointer: + return "WriteDBPointer" + case writeDateTime: + return "WriteDateTime" + case writeDecimal128: + return "WriteDecimal128" + case writeDouble: + return "WriteDouble" + case writeInt32: + return "WriteInt32" + case writeInt64: + return "WriteInt64" + case writeJavascript: + return "WriteJavascript" + case writeMaxKey: + return "WriteMaxKey" + case writeMinKey: + return "WriteMinKey" + case writeNull: + return "WriteNull" + case writeObjectID: + return "WriteObjectID" + case writeRegex: + return "WriteRegex" + case writeString: + return "WriteString" + case writeDocument: + return "WriteDocument" + case writeSymbol: + return "WriteSymbol" + case writeTimestamp: + return "WriteTimestamp" + case writeUndefined: + return "WriteUndefined" + case writeDocumentElement: + return "WriteDocumentElement" + case writeDocumentEnd: + return "WriteDocumentEnd" + case writeArrayElement: + return "WriteArrayElement" + case writeArrayEnd: + return "WriteArrayEnd" + default: + return "" + } +} + +// valueReaderWriter is a test implementation of a bsonrw.ValueReader and bsonrw.ValueWriter +type valueReaderWriter struct { + T *testing.T + invoked invoked + Return interface{} // Can be a primitive or a bsoncore.Value + BSONType Type + Err error + ErrAfter invoked // error after this method is called + depth uint64 +} + +// prevent infinite recursion. +func (llvrw *valueReaderWriter) checkdepth() { + llvrw.depth++ + if llvrw.depth > 1000 { + panic("max depth exceeded") + } +} + +// Type implements the ValueReader interface. +func (llvrw *valueReaderWriter) Type() Type { + llvrw.checkdepth() + return llvrw.BSONType +} + +// Skip implements the ValueReader interface. +func (llvrw *valueReaderWriter) Skip() error { + llvrw.checkdepth() + llvrw.invoked = skip + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// ReadArray implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadArray() (ArrayReader, error) { + llvrw.checkdepth() + llvrw.invoked = readArray + if llvrw.ErrAfter == llvrw.invoked { + return nil, llvrw.Err + } + + return llvrw, nil +} + +// ReadBinary implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadBinary() (b []byte, btype byte, err error) { + llvrw.checkdepth() + llvrw.invoked = readBinary + if llvrw.ErrAfter == llvrw.invoked { + return nil, 0x00, llvrw.Err + } + + switch tt := llvrw.Return.(type) { + case bsoncore.Value: + subtype, data, _, ok := bsoncore.ReadBinary(tt.Data) + if !ok { + llvrw.T.Error("Invalid Value provided for return value of ReadBinary.") + return nil, 0x00, nil + } + return data, subtype, nil + default: + llvrw.T.Errorf("Incorrect type provided for return value of ReadBinary: %T", llvrw.Return) + return nil, 0x00, nil + } +} + +// ReadBoolean implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadBoolean() (bool, error) { + llvrw.checkdepth() + llvrw.invoked = readBoolean + if llvrw.ErrAfter == llvrw.invoked { + return false, llvrw.Err + } + + switch tt := llvrw.Return.(type) { + case bool: + return tt, nil + case bsoncore.Value: + b, _, ok := bsoncore.ReadBoolean(tt.Data) + if !ok { + llvrw.T.Error("Invalid Value provided for return value of ReadBoolean.") + return false, nil + } + return b, nil + default: + llvrw.T.Errorf("Incorrect type provided for return value of ReadBoolean: %T", llvrw.Return) + return false, nil + } +} + +// ReadDocument implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadDocument() (DocumentReader, error) { + llvrw.checkdepth() + llvrw.invoked = readDocument + if llvrw.ErrAfter == llvrw.invoked { + return nil, llvrw.Err + } + + return llvrw, nil +} + +// ReadCodeWithScope implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadCodeWithScope() (code string, dr DocumentReader, err error) { + llvrw.checkdepth() + llvrw.invoked = readCodeWithScope + if llvrw.ErrAfter == llvrw.invoked { + return "", nil, llvrw.Err + } + + return "", llvrw, nil +} + +// ReadDBPointer implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadDBPointer() (ns string, oid ObjectID, err error) { + llvrw.checkdepth() + llvrw.invoked = readDBPointer + if llvrw.ErrAfter == llvrw.invoked { + return "", ObjectID{}, llvrw.Err + } + + switch tt := llvrw.Return.(type) { + case bsoncore.Value: + ns, oid, _, ok := bsoncore.ReadDBPointer(tt.Data) + if !ok { + llvrw.T.Error("Invalid Value instance provided for return value of ReadDBPointer") + return "", ObjectID{}, nil + } + return ns, oid, nil + default: + llvrw.T.Errorf("Incorrect type provided for return value of ReadDBPointer: %T", llvrw.Return) + return "", ObjectID{}, nil + } +} + +// ReadDateTime implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadDateTime() (int64, error) { + llvrw.checkdepth() + llvrw.invoked = readDateTime + if llvrw.ErrAfter == llvrw.invoked { + return 0, llvrw.Err + } + + dt, ok := llvrw.Return.(int64) + if !ok { + llvrw.T.Errorf("Incorrect type provided for return value of ReadDateTime: %T", llvrw.Return) + return 0, nil + } + + return dt, nil +} + +// ReadDecimal128 implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadDecimal128() (Decimal128, error) { + llvrw.checkdepth() + llvrw.invoked = readDecimal128 + if llvrw.ErrAfter == llvrw.invoked { + return Decimal128{}, llvrw.Err + } + + d128, ok := llvrw.Return.(Decimal128) + if !ok { + llvrw.T.Errorf("Incorrect type provided for return value of ReadDecimal128: %T", llvrw.Return) + return Decimal128{}, nil + } + + return d128, nil +} + +// ReadDouble implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadDouble() (float64, error) { + llvrw.checkdepth() + llvrw.invoked = readDouble + if llvrw.ErrAfter == llvrw.invoked { + return 0, llvrw.Err + } + + f64, ok := llvrw.Return.(float64) + if !ok { + llvrw.T.Errorf("Incorrect type provided for return value of ReadDouble: %T", llvrw.Return) + return 0, nil + } + + return f64, nil +} + +// ReadInt32 implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadInt32() (int32, error) { + llvrw.checkdepth() + llvrw.invoked = readInt32 + if llvrw.ErrAfter == llvrw.invoked { + return 0, llvrw.Err + } + + i32, ok := llvrw.Return.(int32) + if !ok { + llvrw.T.Errorf("Incorrect type provided for return value of ReadInt32: %T", llvrw.Return) + return 0, nil + } + + return i32, nil +} + +// ReadInt64 implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadInt64() (int64, error) { + llvrw.checkdepth() + llvrw.invoked = readInt64 + if llvrw.ErrAfter == llvrw.invoked { + return 0, llvrw.Err + } + i64, ok := llvrw.Return.(int64) + if !ok { + llvrw.T.Errorf("Incorrect type provided for return value of ReadInt64: %T", llvrw.Return) + return 0, nil + } + + return i64, nil +} + +// ReadJavascript implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadJavascript() (code string, err error) { + llvrw.checkdepth() + llvrw.invoked = readJavascript + if llvrw.ErrAfter == llvrw.invoked { + return "", llvrw.Err + } + js, ok := llvrw.Return.(string) + if !ok { + llvrw.T.Errorf("Incorrect type provided for return value of ReadJavascript: %T", llvrw.Return) + return "", nil + } + + return js, nil +} + +// ReadMaxKey implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadMaxKey() error { + llvrw.checkdepth() + llvrw.invoked = readMaxKey + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + + return nil +} + +// ReadMinKey implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadMinKey() error { + llvrw.checkdepth() + llvrw.invoked = readMinKey + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + + return nil +} + +// ReadNull implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadNull() error { + llvrw.checkdepth() + llvrw.invoked = readNull + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + + return nil +} + +// ReadObjectID implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadObjectID() (ObjectID, error) { + llvrw.checkdepth() + llvrw.invoked = readObjectID + if llvrw.ErrAfter == llvrw.invoked { + return ObjectID{}, llvrw.Err + } + oid, ok := llvrw.Return.(ObjectID) + if !ok { + llvrw.T.Errorf("Incorrect type provided for return value of ReadObjectID: %T", llvrw.Return) + return ObjectID{}, nil + } + + return oid, nil +} + +// ReadRegex implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadRegex() (pattern string, options string, err error) { + llvrw.checkdepth() + llvrw.invoked = readRegex + if llvrw.ErrAfter == llvrw.invoked { + return "", "", llvrw.Err + } + switch tt := llvrw.Return.(type) { + case bsoncore.Value: + pattern, options, _, ok := bsoncore.ReadRegex(tt.Data) + if !ok { + llvrw.T.Error("Invalid Value instance provided for ReadRegex") + return "", "", nil + } + return pattern, options, nil + default: + llvrw.T.Errorf("Incorrect type provided for return value of ReadRegex: %T", llvrw.Return) + return "", "", nil + } +} + +// ReadString implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadString() (string, error) { + llvrw.checkdepth() + llvrw.invoked = readString + if llvrw.ErrAfter == llvrw.invoked { + return "", llvrw.Err + } + str, ok := llvrw.Return.(string) + if !ok { + llvrw.T.Errorf("Incorrect type provided for return value of ReadString: %T", llvrw.Return) + return "", nil + } + + return str, nil +} + +// ReadSymbol implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadSymbol() (symbol string, err error) { + llvrw.checkdepth() + llvrw.invoked = readSymbol + if llvrw.ErrAfter == llvrw.invoked { + return "", llvrw.Err + } + switch tt := llvrw.Return.(type) { + case string: + return tt, nil + case bsoncore.Value: + symbol, _, ok := bsoncore.ReadSymbol(tt.Data) + if !ok { + llvrw.T.Error("Invalid Value instance provided for ReadSymbol") + return "", nil + } + return symbol, nil + default: + llvrw.T.Errorf("Incorrect type provided for return value of ReadSymbol: %T", llvrw.Return) + return "", nil + } +} + +// ReadTimestamp implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadTimestamp() (t uint32, i uint32, err error) { + llvrw.checkdepth() + llvrw.invoked = readTimestamp + if llvrw.ErrAfter == llvrw.invoked { + return 0, 0, llvrw.Err + } + switch tt := llvrw.Return.(type) { + case bsoncore.Value: + t, i, _, ok := bsoncore.ReadTimestamp(tt.Data) + if !ok { + llvrw.T.Errorf("Invalid Value instance provided for return value of ReadTimestamp") + return 0, 0, nil + } + return t, i, nil + default: + llvrw.T.Errorf("Incorrect type provided for return value of ReadTimestamp: %T", llvrw.Return) + return 0, 0, nil + } +} + +// ReadUndefined implements the ValueReader interface. +func (llvrw *valueReaderWriter) ReadUndefined() error { + llvrw.checkdepth() + llvrw.invoked = readUndefined + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + + return nil +} + +// WriteArray implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteArray() (ArrayWriter, error) { + llvrw.checkdepth() + llvrw.invoked = writeArray + if llvrw.ErrAfter == llvrw.invoked { + return nil, llvrw.Err + } + return llvrw, nil +} + +// WriteBinary implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteBinary([]byte) error { + llvrw.checkdepth() + llvrw.invoked = writeBinary + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteBinaryWithSubtype implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteBinaryWithSubtype([]byte, byte) error { + llvrw.checkdepth() + llvrw.invoked = writeBinaryWithSubtype + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteBoolean implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteBoolean(bool) error { + llvrw.checkdepth() + llvrw.invoked = writeBoolean + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteCodeWithScope implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteCodeWithScope(string) (DocumentWriter, error) { + llvrw.checkdepth() + llvrw.invoked = writeCodeWithScope + if llvrw.ErrAfter == llvrw.invoked { + return nil, llvrw.Err + } + return llvrw, nil +} + +// WriteDBPointer implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteDBPointer(string, ObjectID) error { + llvrw.checkdepth() + llvrw.invoked = writeDBPointer + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteDateTime implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteDateTime(int64) error { + llvrw.checkdepth() + llvrw.invoked = writeDateTime + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteDecimal128 implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteDecimal128(Decimal128) error { + llvrw.checkdepth() + llvrw.invoked = writeDecimal128 + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteDouble implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteDouble(float64) error { + llvrw.checkdepth() + llvrw.invoked = writeDouble + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteInt32 implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteInt32(int32) error { + llvrw.checkdepth() + llvrw.invoked = writeInt32 + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteInt64 implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteInt64(int64) error { + llvrw.checkdepth() + llvrw.invoked = writeInt64 + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteJavascript implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteJavascript(string) error { + llvrw.checkdepth() + llvrw.invoked = writeJavascript + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteMaxKey implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteMaxKey() error { + llvrw.checkdepth() + llvrw.invoked = writeMaxKey + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteMinKey implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteMinKey() error { + llvrw.checkdepth() + llvrw.invoked = writeMinKey + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteNull implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteNull() error { + llvrw.checkdepth() + llvrw.invoked = writeNull + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteObjectID implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteObjectID(ObjectID) error { + llvrw.checkdepth() + llvrw.invoked = writeObjectID + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteRegex implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteRegex(string, string) error { + llvrw.checkdepth() + llvrw.invoked = writeRegex + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteString implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteString(string) error { + llvrw.checkdepth() + llvrw.invoked = writeString + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteDocument implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteDocument() (DocumentWriter, error) { + llvrw.checkdepth() + llvrw.invoked = writeDocument + if llvrw.ErrAfter == llvrw.invoked { + return nil, llvrw.Err + } + return llvrw, nil +} + +// WriteSymbol implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteSymbol(string) error { + llvrw.checkdepth() + llvrw.invoked = writeSymbol + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteTimestamp implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteTimestamp(uint32, uint32) error { + llvrw.checkdepth() + llvrw.invoked = writeTimestamp + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// WriteUndefined implements the ValueWriter interface. +func (llvrw *valueReaderWriter) WriteUndefined() error { + llvrw.checkdepth() + llvrw.invoked = writeUndefined + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + return nil +} + +// ReadElement implements the DocumentReader interface. +func (llvrw *valueReaderWriter) ReadElement() (string, ValueReader, error) { + llvrw.checkdepth() + llvrw.invoked = readElement + if llvrw.ErrAfter == llvrw.invoked { + return "", nil, llvrw.Err + } + + return "", llvrw, nil +} + +// WriteDocumentElement implements the DocumentWriter interface. +func (llvrw *valueReaderWriter) WriteDocumentElement(string) (ValueWriter, error) { + llvrw.checkdepth() + llvrw.invoked = writeDocumentElement + if llvrw.ErrAfter == llvrw.invoked { + return nil, llvrw.Err + } + + return llvrw, nil +} + +// WriteDocumentEnd implements the DocumentWriter interface. +func (llvrw *valueReaderWriter) WriteDocumentEnd() error { + llvrw.checkdepth() + llvrw.invoked = writeDocumentEnd + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + + return nil +} + +// ReadValue implements the ArrayReader interface. +func (llvrw *valueReaderWriter) ReadValue() (ValueReader, error) { + llvrw.checkdepth() + llvrw.invoked = readValue + if llvrw.ErrAfter == llvrw.invoked { + return nil, llvrw.Err + } + + return llvrw, nil +} + +// WriteArrayElement implements the ArrayWriter interface. +func (llvrw *valueReaderWriter) WriteArrayElement() (ValueWriter, error) { + llvrw.checkdepth() + llvrw.invoked = writeArrayElement + if llvrw.ErrAfter == llvrw.invoked { + return nil, llvrw.Err + } + + return llvrw, nil +} + +// WriteArrayEnd implements the ArrayWriter interface. +func (llvrw *valueReaderWriter) WriteArrayEnd() error { + llvrw.checkdepth() + llvrw.invoked = writeArrayEnd + if llvrw.ErrAfter == llvrw.invoked { + return llvrw.Err + } + + return nil +} diff --git a/bson/bsontype/bsontype.go b/bson/bsontype/bsontype.go deleted file mode 100644 index 255d9909e3..0000000000 --- a/bson/bsontype/bsontype.go +++ /dev/null @@ -1,116 +0,0 @@ -// 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 bsontype is a utility package that contains types for each BSON type and the -// a stringifier for the Type to enable easier debugging when working with BSON. -package bsontype // import "go.mongodb.org/mongo-driver/bson/bsontype" - -// BSON element types as described in https://bsonspec.org/spec.html. -// -// Deprecated: Use bson.Type* constants instead. -const ( - Double Type = 0x01 - String Type = 0x02 - EmbeddedDocument Type = 0x03 - Array Type = 0x04 - Binary Type = 0x05 - Undefined Type = 0x06 - ObjectID Type = 0x07 - Boolean Type = 0x08 - DateTime Type = 0x09 - Null Type = 0x0A - Regex Type = 0x0B - DBPointer Type = 0x0C - JavaScript Type = 0x0D - Symbol Type = 0x0E - CodeWithScope Type = 0x0F - Int32 Type = 0x10 - Timestamp Type = 0x11 - Int64 Type = 0x12 - Decimal128 Type = 0x13 - MinKey Type = 0xFF - MaxKey Type = 0x7F -) - -// BSON binary element subtypes as described in https://bsonspec.org/spec.html. -// -// Deprecated: Use the bson.TypeBinary* constants instead. -const ( - BinaryGeneric byte = 0x00 - BinaryFunction byte = 0x01 - BinaryBinaryOld byte = 0x02 - BinaryUUIDOld byte = 0x03 - BinaryUUID byte = 0x04 - BinaryMD5 byte = 0x05 - BinaryEncrypted byte = 0x06 - BinaryColumn byte = 0x07 - BinarySensitive byte = 0x08 - BinaryUserDefined byte = 0x80 -) - -// Type represents a BSON type. -type Type byte - -// String returns the string representation of the BSON type's name. -func (bt Type) String() string { - switch bt { - case '\x01': - return "double" - case '\x02': - return "string" - case '\x03': - return "embedded document" - case '\x04': - return "array" - case '\x05': - return "binary" - case '\x06': - return "undefined" - case '\x07': - return "objectID" - case '\x08': - return "boolean" - case '\x09': - return "UTC datetime" - case '\x0A': - return "null" - case '\x0B': - return "regex" - case '\x0C': - return "dbPointer" - case '\x0D': - return "javascript" - case '\x0E': - return "symbol" - case '\x0F': - return "code with scope" - case '\x10': - return "32-bit integer" - case '\x11': - return "timestamp" - case '\x12': - return "64-bit integer" - case '\x13': - return "128-bit decimal" - case '\xFF': - return "min key" - case '\x7F': - return "max key" - default: - return "invalid" - } -} - -// IsValid will return true if the Type is valid. -func (bt Type) IsValid() bool { - switch bt { - case Double, String, EmbeddedDocument, Array, Binary, Undefined, ObjectID, Boolean, DateTime, Null, Regex, - DBPointer, JavaScript, Symbol, CodeWithScope, Int32, Timestamp, Int64, Decimal128, MinKey, MaxKey: - return true - default: - return false - } -} diff --git a/bson/bsontype/bsontype_test.go b/bson/bsontype/bsontype_test.go deleted file mode 100644 index 61d4f2e6e1..0000000000 --- a/bson/bsontype/bsontype_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// 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 bsontype - -import "testing" - -func TestType(t *testing.T) { - testCases := []struct { - name string - t Type - want string - }{ - {"double", Double, "double"}, - {"string", String, "string"}, - {"embedded document", EmbeddedDocument, "embedded document"}, - {"array", Array, "array"}, - {"binary", Binary, "binary"}, - {"undefined", Undefined, "undefined"}, - {"objectID", ObjectID, "objectID"}, - {"boolean", Boolean, "boolean"}, - {"UTC datetime", DateTime, "UTC datetime"}, - {"null", Null, "null"}, - {"regex", Regex, "regex"}, - {"dbPointer", DBPointer, "dbPointer"}, - {"javascript", JavaScript, "javascript"}, - {"symbol", Symbol, "symbol"}, - {"code with scope", CodeWithScope, "code with scope"}, - {"32-bit integer", Int32, "32-bit integer"}, - {"timestamp", Timestamp, "timestamp"}, - {"64-bit integer", Int64, "64-bit integer"}, - {"128-bit decimal", Decimal128, "128-bit decimal"}, - {"min key", MinKey, "min key"}, - {"max key", MaxKey, "max key"}, - {"invalid", (0), "invalid"}, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - got := tc.t.String() - if got != tc.want { - t.Errorf("String outputs do not match. got %s; want %s", got, tc.want) - } - }) - } -} diff --git a/bson/bsoncodec/byte_slice_codec.go b/bson/byte_slice_codec.go similarity index 82% rename from bson/bsoncodec/byte_slice_codec.go rename to bson/byte_slice_codec.go index dde3e76815..586c006467 100644 --- a/bson/bsoncodec/byte_slice_codec.go +++ b/bson/byte_slice_codec.go @@ -4,15 +4,13 @@ // 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 +package bson import ( "fmt" "reflect" "go.mongodb.org/mongo-driver/bson/bsonoptions" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" ) // ByteSliceCodec is the Codec used for []byte values. @@ -50,7 +48,7 @@ func NewByteSliceCodec(opts ...*bsonoptions.ByteSliceCodecOptions) *ByteSliceCod } // EncodeValue is the ValueEncoder for []byte. -func (bsc *ByteSliceCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (bsc *ByteSliceCodec) EncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tByteSlice { return ValueEncoderError{Name: "ByteSliceEncodeValue", Types: []reflect.Type{tByteSlice}, Received: val} } @@ -60,7 +58,7 @@ func (bsc *ByteSliceCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, return vw.WriteBinary(val.Interface().([]byte)) } -func (bsc *ByteSliceCodec) decodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (bsc *ByteSliceCodec) decodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tByteSlice { return emptyValue, ValueDecoderError{ Name: "ByteSliceDecodeValue", @@ -72,30 +70,30 @@ func (bsc *ByteSliceCodec) decodeType(_ DecodeContext, vr bsonrw.ValueReader, t var data []byte var err error switch vrType := vr.Type(); vrType { - case bsontype.String: + case TypeString: str, err := vr.ReadString() if err != nil { return emptyValue, err } data = []byte(str) - case bsontype.Symbol: + case TypeSymbol: sym, err := vr.ReadSymbol() if err != nil { return emptyValue, err } data = []byte(sym) - case bsontype.Binary: + case TypeBinary: var subtype byte data, subtype, err = vr.ReadBinary() if err != nil { return emptyValue, err } - if subtype != bsontype.BinaryGeneric && subtype != bsontype.BinaryBinaryOld { + if subtype != TypeBinaryGeneric && subtype != TypeBinaryBinaryOld { return emptyValue, decodeBinaryError{subtype: subtype, typeName: "[]byte"} } - case bsontype.Null: + case TypeNull: err = vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() default: return emptyValue, fmt.Errorf("cannot decode %v into a []byte", vrType) @@ -108,7 +106,7 @@ func (bsc *ByteSliceCodec) decodeType(_ DecodeContext, vr bsonrw.ValueReader, t } // DecodeValue is the ValueDecoder for []byte. -func (bsc *ByteSliceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (bsc *ByteSliceCodec) DecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tByteSlice { return ValueDecoderError{Name: "ByteSliceDecodeValue", Types: []reflect.Type{tByteSlice}, Received: val} } diff --git a/bson/bsoncodec/codec_cache.go b/bson/codec_cache.go similarity index 99% rename from bson/bsoncodec/codec_cache.go rename to bson/codec_cache.go index 844b50299f..b4042822e6 100644 --- a/bson/bsoncodec/codec_cache.go +++ b/bson/codec_cache.go @@ -4,7 +4,7 @@ // 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 +package bson import ( "reflect" diff --git a/bson/bsoncodec/codec_cache_test.go b/bson/codec_cache_test.go similarity index 99% rename from bson/bsoncodec/codec_cache_test.go rename to bson/codec_cache_test.go index 054a45df50..d48e05f5a3 100644 --- a/bson/bsoncodec/codec_cache_test.go +++ b/bson/codec_cache_test.go @@ -4,7 +4,7 @@ // 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 +package bson import ( "reflect" diff --git a/bson/bsoncodec/cond_addr_codec.go b/bson/cond_addr_codec.go similarity index 85% rename from bson/bsoncodec/cond_addr_codec.go rename to bson/cond_addr_codec.go index cb8180f25c..fba139ff07 100644 --- a/bson/bsoncodec/cond_addr_codec.go +++ b/bson/cond_addr_codec.go @@ -4,12 +4,10 @@ // 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 +package bson import ( "reflect" - - "go.mongodb.org/mongo-driver/bson/bsonrw" ) // condAddrEncoder is the encoder used when a pointer to the encoding value has an encoder. @@ -27,7 +25,7 @@ func newCondAddrEncoder(canAddrEnc, elseEnc ValueEncoder) *condAddrEncoder { } // EncodeValue is the ValueEncoderFunc for a value that may be addressable. -func (cae *condAddrEncoder) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (cae *condAddrEncoder) EncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if val.CanAddr() { return cae.canAddrEnc.EncodeValue(ec, vw, val) } @@ -52,7 +50,7 @@ func newCondAddrDecoder(canAddrDec, elseDec ValueDecoder) *condAddrDecoder { } // DecodeValue is the ValueDecoderFunc for a value that may be addressable. -func (cad *condAddrDecoder) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (cad *condAddrDecoder) DecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if val.CanAddr() { return cad.canAddrDec.DecodeValue(dc, vr, val) } diff --git a/bson/bsoncodec/cond_addr_codec_test.go b/bson/cond_addr_codec_test.go similarity index 82% rename from bson/bsoncodec/cond_addr_codec_test.go rename to bson/cond_addr_codec_test.go index 4d308f9172..c22c29fe72 100644 --- a/bson/bsoncodec/cond_addr_codec_test.go +++ b/bson/cond_addr_codec_test.go @@ -4,14 +4,12 @@ // 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 +package bson import ( "reflect" "testing" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsonrw/bsonrwtest" "go.mongodb.org/mongo-driver/internal/assert" ) @@ -20,15 +18,15 @@ func TestCondAddrCodec(t *testing.T) { canAddrVal := reflect.ValueOf(&inner) addressable := canAddrVal.Elem() unaddressable := reflect.ValueOf(inner) - rw := &bsonrwtest.ValueReaderWriter{} + rw := &valueReaderWriter{} t.Run("addressEncode", func(t *testing.T) { invoked := 0 - encode1 := ValueEncoderFunc(func(EncodeContext, bsonrw.ValueWriter, reflect.Value) error { + encode1 := ValueEncoderFunc(func(EncodeContext, ValueWriter, reflect.Value) error { invoked = 1 return nil }) - encode2 := ValueEncoderFunc(func(EncodeContext, bsonrw.ValueWriter, reflect.Value) error { + encode2 := ValueEncoderFunc(func(EncodeContext, ValueWriter, reflect.Value) error { invoked = 2 return nil }) @@ -60,11 +58,11 @@ func TestCondAddrCodec(t *testing.T) { }) t.Run("addressDecode", func(t *testing.T) { invoked := 0 - decode1 := ValueDecoderFunc(func(DecodeContext, bsonrw.ValueReader, reflect.Value) error { + decode1 := ValueDecoderFunc(func(DecodeContext, ValueReader, reflect.Value) error { invoked = 1 return nil }) - decode2 := ValueDecoderFunc(func(DecodeContext, bsonrw.ValueReader, reflect.Value) error { + decode2 := ValueDecoderFunc(func(DecodeContext, ValueReader, reflect.Value) error { invoked = 2 return nil }) diff --git a/bson/bsonrw/copier.go b/bson/copier.go similarity index 64% rename from bson/bsonrw/copier.go rename to bson/copier.go index 1e25570b85..abdd7162e4 100644 --- a/bson/bsonrw/copier.go +++ b/bson/copier.go @@ -4,47 +4,21 @@ // 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 bsonrw +package bson import ( "errors" "fmt" "io" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) -// Copier is a type that allows copying between ValueReaders, ValueWriters, and -// []byte values. +// copyDocument handles copying one document from the src to the dst. // // Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be // supported in Go Driver 2.0. -type Copier struct{} - -// NewCopier creates a new copier with the given registry. If a nil registry is provided -// a default registry is used. -// -// Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be -// supported in Go Driver 2.0. -func NewCopier() Copier { - return Copier{} -} - -// CopyDocument handles copying a document from src to dst. -// -// Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be -// supported in Go Driver 2.0. -func CopyDocument(dst ValueWriter, src ValueReader) error { - return Copier{}.CopyDocument(dst, src) -} - -// CopyDocument handles copying one document from the src to the dst. -// -// Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be -// supported in Go Driver 2.0. -func (c Copier) CopyDocument(dst ValueWriter, src ValueReader) error { +func copyDocument(dst ValueWriter, src ValueReader) error { dr, err := src.ReadDocument() if err != nil { return err @@ -55,21 +29,21 @@ func (c Copier) CopyDocument(dst ValueWriter, src ValueReader) error { return err } - return c.copyDocumentCore(dw, dr) + return copyDocumentCore(dw, dr) } -// CopyArrayFromBytes copies the values from a BSON array represented as a +// copyArrayFromBytes copies the values from a BSON array represented as a // []byte to a ValueWriter. // // Deprecated: Copying BSON arrays using the ValueWriter and ValueReader interfaces will not be // supported in Go Driver 2.0. -func (c Copier) CopyArrayFromBytes(dst ValueWriter, src []byte) error { +func copyArrayFromBytes(dst ValueWriter, src []byte) error { aw, err := dst.WriteArray() if err != nil { return err } - err = c.CopyBytesToArrayWriter(aw, src) + err = copyBytesToArrayWriter(aw, src) if err != nil { return err } @@ -77,18 +51,18 @@ func (c Copier) CopyArrayFromBytes(dst ValueWriter, src []byte) error { return aw.WriteArrayEnd() } -// CopyDocumentFromBytes copies the values from a BSON document represented as a +// copyDocumentFromBytes copies the values from a BSON document represented as a // []byte to a ValueWriter. // // Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be // supported in Go Driver 2.0. -func (c Copier) CopyDocumentFromBytes(dst ValueWriter, src []byte) error { +func copyDocumentFromBytes(dst ValueWriter, src []byte) error { dw, err := dst.WriteDocument() if err != nil { return err } - err = c.CopyBytesToDocumentWriter(dw, src) + err = copyBytesToDocumentWriter(dw, src) if err != nil { return err } @@ -98,33 +72,33 @@ func (c Copier) CopyDocumentFromBytes(dst ValueWriter, src []byte) error { type writeElementFn func(key string) (ValueWriter, error) -// CopyBytesToArrayWriter copies the values from a BSON Array represented as a []byte to an +// copyBytesToArrayWriter copies the values from a BSON Array represented as a []byte to an // ArrayWriter. // // Deprecated: Copying BSON arrays using the ArrayWriter interface will not be supported in Go // Driver 2.0. -func (c Copier) CopyBytesToArrayWriter(dst ArrayWriter, src []byte) error { +func copyBytesToArrayWriter(dst ArrayWriter, src []byte) error { wef := func(_ string) (ValueWriter, error) { return dst.WriteArrayElement() } - return c.copyBytesToValueWriter(src, wef) + return copyBytesToValueWriter(src, wef) } -// CopyBytesToDocumentWriter copies the values from a BSON document represented as a []byte to a +// copyBytesToDocumentWriter copies the values from a BSON document represented as a []byte to a // DocumentWriter. // // Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be // supported in Go Driver 2.0. -func (c Copier) CopyBytesToDocumentWriter(dst DocumentWriter, src []byte) error { +func copyBytesToDocumentWriter(dst DocumentWriter, src []byte) error { wef := func(key string) (ValueWriter, error) { return dst.WriteDocumentElement(key) } - return c.copyBytesToValueWriter(src, wef) + return copyBytesToValueWriter(src, wef) } -func (c Copier) copyBytesToValueWriter(src []byte, wef writeElementFn) error { +func copyBytesToValueWriter(src []byte, wef writeElementFn) error { // TODO(skriptble): Create errors types here. Anything that is a tag should be a property. length, rem, ok := bsoncore.ReadLength(src) if !ok { @@ -135,7 +109,7 @@ func (c Copier) copyBytesToValueWriter(src []byte, wef writeElementFn) error { } rem = rem[:length-4] - var t bsontype.Type + var t bsoncore.Type var key string var val bsoncore.Value for { @@ -143,7 +117,7 @@ func (c Copier) copyBytesToValueWriter(src []byte, wef writeElementFn) error { if !ok { return io.EOF } - if t == bsontype.Type(0) { + if t == bsoncore.Type(0) { if len(rem) != 0 { return fmt.Errorf("document end byte found before end of document. remaining bytes=%v", rem) } @@ -165,7 +139,7 @@ func (c Copier) copyBytesToValueWriter(src []byte, wef writeElementFn) error { if !ok { return fmt.Errorf("not enough bytes available to read type. bytes=%d type=%s", len(rem), t) } - err = c.CopyValueFromBytes(vw, t, val.Data) + err = copyValueFromBytes(vw, Type(t), val.Data) if err != nil { return err } @@ -173,21 +147,21 @@ func (c Copier) copyBytesToValueWriter(src []byte, wef writeElementFn) error { return nil } -// CopyDocumentToBytes copies an entire document from the ValueReader and +// copyDocumentToBytes copies an entire document from the ValueReader and // returns it as bytes. // // Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be // supported in Go Driver 2.0. -func (c Copier) CopyDocumentToBytes(src ValueReader) ([]byte, error) { - return c.AppendDocumentBytes(nil, src) +func copyDocumentToBytes(src ValueReader) ([]byte, error) { + return appendDocumentBytes(nil, src) } -// AppendDocumentBytes functions the same as CopyDocumentToBytes, but will +// appendDocumentBytes functions the same as CopyDocumentToBytes, but will // append the result to dst. // // Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be // supported in Go Driver 2.0. -func (c Copier) AppendDocumentBytes(dst []byte, src ValueReader) ([]byte, error) { +func appendDocumentBytes(dst []byte, src ValueReader) ([]byte, error) { if br, ok := src.(BytesReader); ok { _, dst, err := br.ReadValueBytes(dst) return dst, err @@ -198,16 +172,16 @@ func (c Copier) AppendDocumentBytes(dst []byte, src ValueReader) ([]byte, error) vw.reset(dst) - err := c.CopyDocument(vw, src) + err := copyDocument(vw, src) dst = vw.buf return dst, err } -// AppendArrayBytes copies an array from the ValueReader to dst. +// appendArrayBytes copies an array from the ValueReader to dst. // // Deprecated: Copying BSON arrays using the ValueWriter and ValueReader interfaces will not be // supported in Go Driver 2.0. -func (c Copier) AppendArrayBytes(dst []byte, src ValueReader) ([]byte, error) { +func appendArrayBytes(dst []byte, src ValueReader) ([]byte, error) { if br, ok := src.(BytesReader); ok { _, dst, err := br.ReadValueBytes(dst) return dst, err @@ -218,15 +192,15 @@ func (c Copier) AppendArrayBytes(dst []byte, src ValueReader) ([]byte, error) { vw.reset(dst) - err := c.copyArray(vw, src) + err := copyArray(vw, src) dst = vw.buf return dst, err } -// CopyValueFromBytes will write the value represtend by t and src to dst. +// copyValueFromBytes will write the value represtend by t and src to dst. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.UnmarshalValue] instead. -func (c Copier) CopyValueFromBytes(dst ValueWriter, t bsontype.Type, src []byte) error { +func copyValueFromBytes(dst ValueWriter, t Type, src []byte) error { if wvb, ok := dst.(BytesWriter); ok { return wvb.WriteValueBytes(t, src) } @@ -237,23 +211,23 @@ func (c Copier) CopyValueFromBytes(dst ValueWriter, t bsontype.Type, src []byte) vr.reset(src) vr.pushElement(t) - return c.CopyValue(dst, vr) + return copyValue(dst, vr) } -// CopyValueToBytes copies a value from src and returns it as a bsontype.Type and a +// CopyValueToBytes copies a value from src and returns it as a Type and a // []byte. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.MarshalValue] instead. -func (c Copier) CopyValueToBytes(src ValueReader) (bsontype.Type, []byte, error) { - return c.AppendValueBytes(nil, src) +func CopyValueToBytes(src ValueReader) (Type, []byte, error) { + return appendValueBytes(nil, src) } -// AppendValueBytes functions the same as CopyValueToBytes, but will append the +// appendValueBytes functions the same as CopyValueToBytes, but will append the // result to dst. // // Deprecated: Appending individual BSON elements to an existing slice will not be supported in Go // Driver 2.0. -func (c Copier) AppendValueBytes(dst []byte, src ValueReader) (bsontype.Type, []byte, error) { +func appendValueBytes(dst []byte, src ValueReader) (Type, []byte, error) { if br, ok := src.(BytesReader); ok { return br.ReadValueBytes(dst) } @@ -266,40 +240,40 @@ func (c Copier) AppendValueBytes(dst []byte, src ValueReader) (bsontype.Type, [] vw.reset(dst) vw.push(mElement) - err := c.CopyValue(vw, src) + err := copyValue(vw, src) if err != nil { return 0, dst, err } - return bsontype.Type(vw.buf[start]), vw.buf[start+2:], nil + return Type(vw.buf[start]), vw.buf[start+2:], nil } -// CopyValue will copy a single value from src to dst. +// copyValue will copy a single value from src to dst. // // Deprecated: Copying BSON values using the ValueWriter and ValueReader interfaces will not be // supported in Go Driver 2.0. -func (c Copier) CopyValue(dst ValueWriter, src ValueReader) error { +func copyValue(dst ValueWriter, src ValueReader) error { var err error switch src.Type() { - case bsontype.Double: + case TypeDouble: var f64 float64 f64, err = src.ReadDouble() if err != nil { break } err = dst.WriteDouble(f64) - case bsontype.String: + case TypeString: var str string str, err = src.ReadString() if err != nil { return err } err = dst.WriteString(str) - case bsontype.EmbeddedDocument: - err = c.CopyDocument(dst, src) - case bsontype.Array: - err = c.copyArray(dst, src) - case bsontype.Binary: + case TypeEmbeddedDocument: + err = copyDocument(dst, src) + case TypeArray: + err = copyArray(dst, src) + case TypeBinary: var data []byte var subtype byte data, subtype, err = src.ReadBinary() @@ -307,69 +281,69 @@ func (c Copier) CopyValue(dst ValueWriter, src ValueReader) error { break } err = dst.WriteBinaryWithSubtype(data, subtype) - case bsontype.Undefined: + case TypeUndefined: err = src.ReadUndefined() if err != nil { break } err = dst.WriteUndefined() - case bsontype.ObjectID: - var oid primitive.ObjectID + case TypeObjectID: + var oid ObjectID oid, err = src.ReadObjectID() if err != nil { break } err = dst.WriteObjectID(oid) - case bsontype.Boolean: + case TypeBoolean: var b bool b, err = src.ReadBoolean() if err != nil { break } err = dst.WriteBoolean(b) - case bsontype.DateTime: + case TypeDateTime: var dt int64 dt, err = src.ReadDateTime() if err != nil { break } err = dst.WriteDateTime(dt) - case bsontype.Null: + case TypeNull: err = src.ReadNull() if err != nil { break } err = dst.WriteNull() - case bsontype.Regex: + case TypeRegex: var pattern, options string pattern, options, err = src.ReadRegex() if err != nil { break } err = dst.WriteRegex(pattern, options) - case bsontype.DBPointer: + case TypeDBPointer: var ns string - var pointer primitive.ObjectID + var pointer ObjectID ns, pointer, err = src.ReadDBPointer() if err != nil { break } err = dst.WriteDBPointer(ns, pointer) - case bsontype.JavaScript: + case TypeJavaScript: var js string js, err = src.ReadJavascript() if err != nil { break } err = dst.WriteJavascript(js) - case bsontype.Symbol: + case TypeSymbol: var symbol string symbol, err = src.ReadSymbol() if err != nil { break } err = dst.WriteSymbol(symbol) - case bsontype.CodeWithScope: + case TypeCodeWithScope: var code string var srcScope DocumentReader code, srcScope, err = src.ReadCodeWithScope() @@ -382,55 +356,55 @@ func (c Copier) CopyValue(dst ValueWriter, src ValueReader) error { if err != nil { break } - err = c.copyDocumentCore(dstScope, srcScope) - case bsontype.Int32: + err = copyDocumentCore(dstScope, srcScope) + case TypeInt32: var i32 int32 i32, err = src.ReadInt32() if err != nil { break } err = dst.WriteInt32(i32) - case bsontype.Timestamp: + case TypeTimestamp: var t, i uint32 t, i, err = src.ReadTimestamp() if err != nil { break } err = dst.WriteTimestamp(t, i) - case bsontype.Int64: + case TypeInt64: var i64 int64 i64, err = src.ReadInt64() if err != nil { break } err = dst.WriteInt64(i64) - case bsontype.Decimal128: - var d128 primitive.Decimal128 + case TypeDecimal128: + var d128 Decimal128 d128, err = src.ReadDecimal128() if err != nil { break } err = dst.WriteDecimal128(d128) - case bsontype.MinKey: + case TypeMinKey: err = src.ReadMinKey() if err != nil { break } err = dst.WriteMinKey() - case bsontype.MaxKey: + case TypeMaxKey: err = src.ReadMaxKey() if err != nil { break } err = dst.WriteMaxKey() default: - err = fmt.Errorf("Cannot copy unknown BSON type %s", src.Type()) + err = fmt.Errorf("cannot copy unknown BSON type %s", src.Type()) } return err } -func (c Copier) copyArray(dst ValueWriter, src ValueReader) error { +func copyArray(dst ValueWriter, src ValueReader) error { ar, err := src.ReadArray() if err != nil { return err @@ -455,7 +429,7 @@ func (c Copier) copyArray(dst ValueWriter, src ValueReader) error { return err } - err = c.CopyValue(vw, vr) + err = copyValue(vw, vr) if err != nil { return err } @@ -464,7 +438,7 @@ func (c Copier) copyArray(dst ValueWriter, src ValueReader) error { return aw.WriteArrayEnd() } -func (c Copier) copyDocumentCore(dw DocumentWriter, dr DocumentReader) error { +func copyDocumentCore(dw DocumentWriter, dr DocumentReader) error { for { key, vr, err := dr.ReadElement() if errors.Is(err, ErrEOD) { @@ -479,7 +453,7 @@ func (c Copier) copyDocumentCore(dw DocumentWriter, dr DocumentReader) error { return err } - err = c.CopyValue(vw, vr) + err = copyValue(vw, vr) if err != nil { return err } diff --git a/bson/bsonrw/copier_test.go b/bson/copier_test.go similarity index 57% rename from bson/bsonrw/copier_test.go rename to bson/copier_test.go index c57235cb56..23c13447a4 100644 --- a/bson/bsonrw/copier_test.go +++ b/bson/copier_test.go @@ -4,7 +4,7 @@ // 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 bsonrw +package bson import ( "bytes" @@ -12,8 +12,7 @@ import ( "fmt" "testing" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -22,8 +21,8 @@ func TestCopier(t *testing.T) { t.Run("ReadDocument Error", func(t *testing.T) { want := errors.New("ReadDocumentError") src := &TestValueReaderWriter{t: t, err: want, errAfter: llvrwReadDocument} - got := Copier{}.CopyDocument(nil, src) - if !compareErrors(got, want) { + got := copyDocument(nil, src) + if !assert.CompareErrors(got, want) { t.Errorf("Did not receive correct error. got %v; want %v", got, want) } }) @@ -31,8 +30,8 @@ func TestCopier(t *testing.T) { want := errors.New("WriteDocumentError") src := &TestValueReaderWriter{} dst := &TestValueReaderWriter{t: t, err: want, errAfter: llvrwWriteDocument} - got := Copier{}.CopyDocument(dst, src) - if !compareErrors(got, want) { + got := copyDocument(dst, src) + if !assert.CompareErrors(got, want) { t.Errorf("Did not receive correct error. got %v; want %v", got, want) } }) @@ -44,7 +43,7 @@ func TestCopier(t *testing.T) { src := newValueReader(doc) dst := newValueWriterFromSlice(make([]byte, 0)) want := doc - err = Copier{}.CopyDocument(dst, src) + err = copyDocument(dst, src) noerr(t, err) got := dst.buf if !bytes.Equal(got, want) { @@ -56,8 +55,8 @@ func TestCopier(t *testing.T) { t.Run("ReadArray Error", func(t *testing.T) { want := errors.New("ReadArrayError") src := &TestValueReaderWriter{t: t, err: want, errAfter: llvrwReadArray} - got := Copier{}.copyArray(nil, src) - if !compareErrors(got, want) { + got := copyArray(nil, src) + if !assert.CompareErrors(got, want) { t.Errorf("Did not receive correct error. got %v; want %v", got, want) } }) @@ -65,8 +64,8 @@ func TestCopier(t *testing.T) { want := errors.New("WriteArrayError") src := &TestValueReaderWriter{} dst := &TestValueReaderWriter{t: t, err: want, errAfter: llvrwWriteArray} - got := Copier{}.copyArray(dst, src) - if !compareErrors(got, want) { + got := copyArray(dst, src) + if !assert.CompareErrors(got, want) { t.Errorf("Did not receive correct error. got %v; want %v", got, want) } }) @@ -92,7 +91,7 @@ func TestCopier(t *testing.T) { noerr(t, err) want := doc - err = Copier{}.copyArray(dst, src) + err = copyArray(dst, src) noerr(t, err) err = dst.WriteDocumentEnd() @@ -114,52 +113,52 @@ func TestCopier(t *testing.T) { { "Double/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.Double, err: errors.New("1"), errAfter: llvrwReadDouble}, + &TestValueReaderWriter{bsontype: TypeDouble, err: errors.New("1"), errAfter: llvrwReadDouble}, errors.New("1"), }, { "Double/dst/error", - &TestValueReaderWriter{bsontype: bsontype.Double, err: errors.New("2"), errAfter: llvrwWriteDouble}, - &TestValueReaderWriter{bsontype: bsontype.Double, readval: float64(3.14159)}, + &TestValueReaderWriter{bsontype: TypeDouble, err: errors.New("2"), errAfter: llvrwWriteDouble}, + &TestValueReaderWriter{bsontype: TypeDouble, readval: float64(3.14159)}, errors.New("2"), }, { "String/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.String, err: errors.New("1"), errAfter: llvrwReadString}, + &TestValueReaderWriter{bsontype: TypeString, err: errors.New("1"), errAfter: llvrwReadString}, errors.New("1"), }, { "String/dst/error", - &TestValueReaderWriter{bsontype: bsontype.String, err: errors.New("2"), errAfter: llvrwWriteString}, - &TestValueReaderWriter{bsontype: bsontype.String, readval: "hello, world"}, + &TestValueReaderWriter{bsontype: TypeString, err: errors.New("2"), errAfter: llvrwWriteString}, + &TestValueReaderWriter{bsontype: TypeString, readval: "hello, world"}, errors.New("2"), }, { "Document/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.EmbeddedDocument, err: errors.New("1"), errAfter: llvrwReadDocument}, + &TestValueReaderWriter{bsontype: TypeEmbeddedDocument, err: errors.New("1"), errAfter: llvrwReadDocument}, errors.New("1"), }, { "Array/dst/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.Array, err: errors.New("2"), errAfter: llvrwReadArray}, + &TestValueReaderWriter{bsontype: TypeArray, err: errors.New("2"), errAfter: llvrwReadArray}, errors.New("2"), }, { "Binary/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.Binary, err: errors.New("1"), errAfter: llvrwReadBinary}, + &TestValueReaderWriter{bsontype: TypeBinary, err: errors.New("1"), errAfter: llvrwReadBinary}, errors.New("1"), }, { "Binary/dst/error", - &TestValueReaderWriter{bsontype: bsontype.Binary, err: errors.New("2"), errAfter: llvrwWriteBinaryWithSubtype}, + &TestValueReaderWriter{bsontype: TypeBinary, err: errors.New("2"), errAfter: llvrwWriteBinaryWithSubtype}, &TestValueReaderWriter{ - bsontype: bsontype.Binary, + bsontype: TypeBinary, readval: bsoncore.Value{ - Type: bsontype.Binary, + Type: bsoncore.TypeBinary, Data: []byte{0x03, 0x00, 0x00, 0x00, 0xFF, 0x01, 0x02, 0x03}, }, }, @@ -168,76 +167,76 @@ func TestCopier(t *testing.T) { { "Undefined/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.Undefined, err: errors.New("1"), errAfter: llvrwReadUndefined}, + &TestValueReaderWriter{bsontype: TypeUndefined, err: errors.New("1"), errAfter: llvrwReadUndefined}, errors.New("1"), }, { "Undefined/dst/error", - &TestValueReaderWriter{bsontype: bsontype.Undefined, err: errors.New("2"), errAfter: llvrwWriteUndefined}, - &TestValueReaderWriter{bsontype: bsontype.Undefined}, + &TestValueReaderWriter{bsontype: TypeUndefined, err: errors.New("2"), errAfter: llvrwWriteUndefined}, + &TestValueReaderWriter{bsontype: TypeUndefined}, errors.New("2"), }, { "ObjectID/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.ObjectID, err: errors.New("1"), errAfter: llvrwReadObjectID}, + &TestValueReaderWriter{bsontype: TypeObjectID, err: errors.New("1"), errAfter: llvrwReadObjectID}, errors.New("1"), }, { "ObjectID/dst/error", - &TestValueReaderWriter{bsontype: bsontype.ObjectID, err: errors.New("2"), errAfter: llvrwWriteObjectID}, - &TestValueReaderWriter{bsontype: bsontype.ObjectID, readval: primitive.ObjectID{0x01, 0x02, 0x03}}, + &TestValueReaderWriter{bsontype: TypeObjectID, err: errors.New("2"), errAfter: llvrwWriteObjectID}, + &TestValueReaderWriter{bsontype: TypeObjectID, readval: ObjectID{0x01, 0x02, 0x03}}, errors.New("2"), }, { "Boolean/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.Boolean, err: errors.New("1"), errAfter: llvrwReadBoolean}, + &TestValueReaderWriter{bsontype: TypeBoolean, err: errors.New("1"), errAfter: llvrwReadBoolean}, errors.New("1"), }, { "Boolean/dst/error", - &TestValueReaderWriter{bsontype: bsontype.Boolean, err: errors.New("2"), errAfter: llvrwWriteBoolean}, - &TestValueReaderWriter{bsontype: bsontype.Boolean, readval: bool(true)}, + &TestValueReaderWriter{bsontype: TypeBoolean, err: errors.New("2"), errAfter: llvrwWriteBoolean}, + &TestValueReaderWriter{bsontype: TypeBoolean, readval: bool(true)}, errors.New("2"), }, { "DateTime/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.DateTime, err: errors.New("1"), errAfter: llvrwReadDateTime}, + &TestValueReaderWriter{bsontype: TypeDateTime, err: errors.New("1"), errAfter: llvrwReadDateTime}, errors.New("1"), }, { "DateTime/dst/error", - &TestValueReaderWriter{bsontype: bsontype.DateTime, err: errors.New("2"), errAfter: llvrwWriteDateTime}, - &TestValueReaderWriter{bsontype: bsontype.DateTime, readval: int64(1234567890)}, + &TestValueReaderWriter{bsontype: TypeDateTime, err: errors.New("2"), errAfter: llvrwWriteDateTime}, + &TestValueReaderWriter{bsontype: TypeDateTime, readval: int64(1234567890)}, errors.New("2"), }, { "Null/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.Null, err: errors.New("1"), errAfter: llvrwReadNull}, + &TestValueReaderWriter{bsontype: TypeNull, err: errors.New("1"), errAfter: llvrwReadNull}, errors.New("1"), }, { "Null/dst/error", - &TestValueReaderWriter{bsontype: bsontype.Null, err: errors.New("2"), errAfter: llvrwWriteNull}, - &TestValueReaderWriter{bsontype: bsontype.Null}, + &TestValueReaderWriter{bsontype: TypeNull, err: errors.New("2"), errAfter: llvrwWriteNull}, + &TestValueReaderWriter{bsontype: TypeNull}, errors.New("2"), }, { "Regex/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.Regex, err: errors.New("1"), errAfter: llvrwReadRegex}, + &TestValueReaderWriter{bsontype: TypeRegex, err: errors.New("1"), errAfter: llvrwReadRegex}, errors.New("1"), }, { "Regex/dst/error", - &TestValueReaderWriter{bsontype: bsontype.Regex, err: errors.New("2"), errAfter: llvrwWriteRegex}, + &TestValueReaderWriter{bsontype: TypeRegex, err: errors.New("2"), errAfter: llvrwWriteRegex}, &TestValueReaderWriter{ - bsontype: bsontype.Regex, + bsontype: TypeRegex, readval: bsoncore.Value{ - Type: bsontype.Regex, + Type: bsoncore.TypeRegex, Data: bsoncore.AppendRegex(nil, "hello", "world"), }, }, @@ -246,17 +245,17 @@ func TestCopier(t *testing.T) { { "DBPointer/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.DBPointer, err: errors.New("1"), errAfter: llvrwReadDBPointer}, + &TestValueReaderWriter{bsontype: TypeDBPointer, err: errors.New("1"), errAfter: llvrwReadDBPointer}, errors.New("1"), }, { "DBPointer/dst/error", - &TestValueReaderWriter{bsontype: bsontype.DBPointer, err: errors.New("2"), errAfter: llvrwWriteDBPointer}, + &TestValueReaderWriter{bsontype: TypeDBPointer, err: errors.New("2"), errAfter: llvrwWriteDBPointer}, &TestValueReaderWriter{ - bsontype: bsontype.DBPointer, + bsontype: TypeDBPointer, readval: bsoncore.Value{ - Type: bsontype.DBPointer, - Data: bsoncore.AppendDBPointer(nil, "foo", primitive.ObjectID{0x01, 0x02, 0x03}), + Type: bsoncore.TypeDBPointer, + Data: bsoncore.AppendDBPointer(nil, "foo", ObjectID{0x01, 0x02, 0x03}), }, }, errors.New("2"), @@ -264,28 +263,28 @@ func TestCopier(t *testing.T) { { "Javascript/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.JavaScript, err: errors.New("1"), errAfter: llvrwReadJavascript}, + &TestValueReaderWriter{bsontype: TypeJavaScript, err: errors.New("1"), errAfter: llvrwReadJavascript}, errors.New("1"), }, { "Javascript/dst/error", - &TestValueReaderWriter{bsontype: bsontype.JavaScript, err: errors.New("2"), errAfter: llvrwWriteJavascript}, - &TestValueReaderWriter{bsontype: bsontype.JavaScript, readval: "hello, world"}, + &TestValueReaderWriter{bsontype: TypeJavaScript, err: errors.New("2"), errAfter: llvrwWriteJavascript}, + &TestValueReaderWriter{bsontype: TypeJavaScript, readval: "hello, world"}, errors.New("2"), }, { "Symbol/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.Symbol, err: errors.New("1"), errAfter: llvrwReadSymbol}, + &TestValueReaderWriter{bsontype: TypeSymbol, err: errors.New("1"), errAfter: llvrwReadSymbol}, errors.New("1"), }, { "Symbol/dst/error", - &TestValueReaderWriter{bsontype: bsontype.Symbol, err: errors.New("2"), errAfter: llvrwWriteSymbol}, + &TestValueReaderWriter{bsontype: TypeSymbol, err: errors.New("2"), errAfter: llvrwWriteSymbol}, &TestValueReaderWriter{ - bsontype: bsontype.Symbol, + bsontype: TypeSymbol, readval: bsoncore.Value{ - Type: bsontype.Symbol, + Type: bsoncore.TypeSymbol, Data: bsoncore.AppendSymbol(nil, "hello, world"), }, }, @@ -294,46 +293,46 @@ func TestCopier(t *testing.T) { { "CodeWithScope/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.CodeWithScope, err: errors.New("1"), errAfter: llvrwReadCodeWithScope}, + &TestValueReaderWriter{bsontype: TypeCodeWithScope, err: errors.New("1"), errAfter: llvrwReadCodeWithScope}, errors.New("1"), }, { "CodeWithScope/dst/error", - &TestValueReaderWriter{bsontype: bsontype.CodeWithScope, err: errors.New("2"), errAfter: llvrwWriteCodeWithScope}, - &TestValueReaderWriter{bsontype: bsontype.CodeWithScope}, + &TestValueReaderWriter{bsontype: TypeCodeWithScope, err: errors.New("2"), errAfter: llvrwWriteCodeWithScope}, + &TestValueReaderWriter{bsontype: TypeCodeWithScope}, errors.New("2"), }, { "CodeWithScope/dst/copyDocumentCore error", &TestValueReaderWriter{err: errors.New("3"), errAfter: llvrwWriteDocumentElement}, - &TestValueReaderWriter{bsontype: bsontype.CodeWithScope}, + &TestValueReaderWriter{bsontype: TypeCodeWithScope}, errors.New("3"), }, { "Int32/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.Int32, err: errors.New("1"), errAfter: llvrwReadInt32}, + &TestValueReaderWriter{bsontype: TypeInt32, err: errors.New("1"), errAfter: llvrwReadInt32}, errors.New("1"), }, { "Int32/dst/error", - &TestValueReaderWriter{bsontype: bsontype.Int32, err: errors.New("2"), errAfter: llvrwWriteInt32}, - &TestValueReaderWriter{bsontype: bsontype.Int32, readval: int32(12345)}, + &TestValueReaderWriter{bsontype: TypeInt32, err: errors.New("2"), errAfter: llvrwWriteInt32}, + &TestValueReaderWriter{bsontype: TypeInt32, readval: int32(12345)}, errors.New("2"), }, { "Timestamp/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.Timestamp, err: errors.New("1"), errAfter: llvrwReadTimestamp}, + &TestValueReaderWriter{bsontype: TypeTimestamp, err: errors.New("1"), errAfter: llvrwReadTimestamp}, errors.New("1"), }, { "Timestamp/dst/error", - &TestValueReaderWriter{bsontype: bsontype.Timestamp, err: errors.New("2"), errAfter: llvrwWriteTimestamp}, + &TestValueReaderWriter{bsontype: TypeTimestamp, err: errors.New("2"), errAfter: llvrwWriteTimestamp}, &TestValueReaderWriter{ - bsontype: bsontype.Timestamp, + bsontype: TypeTimestamp, readval: bsoncore.Value{ - Type: bsontype.Timestamp, + Type: bsoncore.TypeTimestamp, Data: bsoncore.AppendTimestamp(nil, 12345, 67890), }, }, @@ -342,64 +341,64 @@ func TestCopier(t *testing.T) { { "Int64/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.Int64, err: errors.New("1"), errAfter: llvrwReadInt64}, + &TestValueReaderWriter{bsontype: TypeInt64, err: errors.New("1"), errAfter: llvrwReadInt64}, errors.New("1"), }, { "Int64/dst/error", - &TestValueReaderWriter{bsontype: bsontype.Int64, err: errors.New("2"), errAfter: llvrwWriteInt64}, - &TestValueReaderWriter{bsontype: bsontype.Int64, readval: int64(1234567890)}, + &TestValueReaderWriter{bsontype: TypeInt64, err: errors.New("2"), errAfter: llvrwWriteInt64}, + &TestValueReaderWriter{bsontype: TypeInt64, readval: int64(1234567890)}, errors.New("2"), }, { "Decimal128/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.Decimal128, err: errors.New("1"), errAfter: llvrwReadDecimal128}, + &TestValueReaderWriter{bsontype: TypeDecimal128, err: errors.New("1"), errAfter: llvrwReadDecimal128}, errors.New("1"), }, { "Decimal128/dst/error", - &TestValueReaderWriter{bsontype: bsontype.Decimal128, err: errors.New("2"), errAfter: llvrwWriteDecimal128}, - &TestValueReaderWriter{bsontype: bsontype.Decimal128, readval: primitive.NewDecimal128(12345, 67890)}, + &TestValueReaderWriter{bsontype: TypeDecimal128, err: errors.New("2"), errAfter: llvrwWriteDecimal128}, + &TestValueReaderWriter{bsontype: TypeDecimal128, readval: NewDecimal128(12345, 67890)}, errors.New("2"), }, { "MinKey/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.MinKey, err: errors.New("1"), errAfter: llvrwReadMinKey}, + &TestValueReaderWriter{bsontype: TypeMinKey, err: errors.New("1"), errAfter: llvrwReadMinKey}, errors.New("1"), }, { "MinKey/dst/error", - &TestValueReaderWriter{bsontype: bsontype.MinKey, err: errors.New("2"), errAfter: llvrwWriteMinKey}, - &TestValueReaderWriter{bsontype: bsontype.MinKey}, + &TestValueReaderWriter{bsontype: TypeMinKey, err: errors.New("2"), errAfter: llvrwWriteMinKey}, + &TestValueReaderWriter{bsontype: TypeMinKey}, errors.New("2"), }, { "MaxKey/src/error", &TestValueReaderWriter{}, - &TestValueReaderWriter{bsontype: bsontype.MaxKey, err: errors.New("1"), errAfter: llvrwReadMaxKey}, + &TestValueReaderWriter{bsontype: TypeMaxKey, err: errors.New("1"), errAfter: llvrwReadMaxKey}, errors.New("1"), }, { "MaxKey/dst/error", - &TestValueReaderWriter{bsontype: bsontype.MaxKey, err: errors.New("2"), errAfter: llvrwWriteMaxKey}, - &TestValueReaderWriter{bsontype: bsontype.MaxKey}, + &TestValueReaderWriter{bsontype: TypeMaxKey, err: errors.New("2"), errAfter: llvrwWriteMaxKey}, + &TestValueReaderWriter{bsontype: TypeMaxKey}, errors.New("2"), }, { "Unknown BSON type error", &TestValueReaderWriter{}, &TestValueReaderWriter{}, - fmt.Errorf("Cannot copy unknown BSON type %s", bsontype.Type(0)), + fmt.Errorf("cannot copy unknown BSON type %s", Type(0)), }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { tc.dst.t, tc.src.t = t, t - err := Copier{}.CopyValue(tc.dst, tc.src) - if !compareErrors(err, tc.err) { + err := copyValue(tc.dst, tc.src) + if !assert.CompareErrors(err, tc.err) { t.Errorf("Did not receive expected error. got %v; want %v", err, tc.err) } }) @@ -412,7 +411,7 @@ func TestCopier(t *testing.T) { noerr(t, err) _, err = vw.WriteDocumentElement("foo") noerr(t, err) - err = Copier{}.CopyValueFromBytes(vw, bsontype.String, bsoncore.AppendString(nil, "bar")) + err = copyValueFromBytes(vw, TypeString, bsoncore.AppendString(nil, "bar")) noerr(t, err) err = vw.WriteDocumentEnd() noerr(t, err) @@ -432,7 +431,7 @@ func TestCopier(t *testing.T) { }) t.Run("Non BytesWriter", func(t *testing.T) { llvrw := &TestValueReaderWriter{t: t} - err := Copier{}.CopyValueFromBytes(llvrw, bsontype.String, bsoncore.AppendString(nil, "bar")) + err := copyValueFromBytes(llvrw, TypeString, bsoncore.AppendString(nil, "bar")) noerr(t, err) got, want := llvrw.invoked, llvrwWriteString if got != want { @@ -456,23 +455,23 @@ func TestCopier(t *testing.T) { noerr(t, err) _, _, err = vr.ReadElement() noerr(t, err) - btype, got, err := Copier{}.CopyValueToBytes(vr) + btype, got, err := CopyValueToBytes(vr) noerr(t, err) want := bsoncore.AppendString(nil, "world") - if btype != bsontype.String { - t.Errorf("Incorrect type returned. got %v; want %v", btype, bsontype.String) + if btype != TypeString { + t.Errorf("Incorrect type returned. got %v; want %v", btype, TypeString) } if !bytes.Equal(got, want) { t.Errorf("Bytes do not match. got %v; want %v", got, want) } }) t.Run("Non BytesReader", func(t *testing.T) { - llvrw := &TestValueReaderWriter{t: t, bsontype: bsontype.String, readval: "Hello, world!"} - btype, got, err := Copier{}.CopyValueToBytes(llvrw) + llvrw := &TestValueReaderWriter{t: t, bsontype: TypeString, readval: "Hello, world!"} + btype, got, err := CopyValueToBytes(llvrw) noerr(t, err) want := bsoncore.AppendString(nil, "Hello, world!") - if btype != bsontype.String { - t.Errorf("Incorrect type returned. got %v; want %v", btype, bsontype.String) + if btype != TypeString { + t.Errorf("Incorrect type returned. got %v; want %v", btype, TypeString) } if !bytes.Equal(got, want) { t.Errorf("Bytes do not match. got %v; want %v", got, want) @@ -495,23 +494,23 @@ func TestCopier(t *testing.T) { noerr(t, err) _, _, err = vr.ReadElement() noerr(t, err) - btype, got, err := Copier{}.AppendValueBytes(nil, vr) + btype, got, err := appendValueBytes(nil, vr) noerr(t, err) want := bsoncore.AppendString(nil, "world") - if btype != bsontype.String { - t.Errorf("Incorrect type returned. got %v; want %v", btype, bsontype.String) + if btype != TypeString { + t.Errorf("Incorrect type returned. got %v; want %v", btype, TypeString) } if !bytes.Equal(got, want) { t.Errorf("Bytes do not match. got %v; want %v", got, want) } }) t.Run("Non BytesReader", func(t *testing.T) { - llvrw := &TestValueReaderWriter{t: t, bsontype: bsontype.String, readval: "Hello, world!"} - btype, got, err := Copier{}.AppendValueBytes(nil, llvrw) + llvrw := &TestValueReaderWriter{t: t, bsontype: TypeString, readval: "Hello, world!"} + btype, got, err := appendValueBytes(nil, llvrw) noerr(t, err) want := bsoncore.AppendString(nil, "Hello, world!") - if btype != bsontype.String { - t.Errorf("Incorrect type returned. got %v; want %v", btype, bsontype.String) + if btype != TypeString { + t.Errorf("Incorrect type returned. got %v; want %v", btype, TypeString) } if !bytes.Equal(got, want) { t.Errorf("Bytes do not match. got %v; want %v", got, want) @@ -519,9 +518,9 @@ func TestCopier(t *testing.T) { }) t.Run("CopyValue error", func(t *testing.T) { want := errors.New("CopyValue error") - llvrw := &TestValueReaderWriter{t: t, bsontype: bsontype.String, err: want, errAfter: llvrwReadString} - _, _, got := Copier{}.AppendValueBytes(make([]byte, 0), llvrw) - if !compareErrors(got, want) { + llvrw := &TestValueReaderWriter{t: t, bsontype: TypeString, err: want, errAfter: llvrwReadString} + _, _, got := appendValueBytes(make([]byte, 0), llvrw) + if !assert.CompareErrors(got, want) { t.Errorf("Errors do not match. got %v; want %v", got, want) } }) diff --git a/bson/primitive/decimal.go b/bson/decimal.go similarity index 76% rename from bson/primitive/decimal.go rename to bson/decimal.go index 08c39514be..7133c235ee 100644 --- a/bson/primitive/decimal.go +++ b/bson/decimal.go @@ -7,7 +7,7 @@ // Based on gopkg.in/mgo.v2/bson by Gustavo Niemeyer // See THIRD-PARTY-NOTICES for original license terms. -package primitive +package bson import ( "encoding/json" @@ -17,6 +17,8 @@ import ( "regexp" "strconv" "strings" + + "go.mongodb.org/mongo-driver/internal/decimal128" ) // These constants are the maximum and minimum values for the exponent field in a decimal128 value. @@ -50,86 +52,7 @@ func (d Decimal128) GetBytes() (uint64, uint64) { // String returns a string representation of the decimal value. func (d Decimal128) String() string { - var posSign int // positive sign - var exp int // exponent - var high, low uint64 // significand high/low - - if d.h>>63&1 == 0 { - posSign = 1 - } - - switch d.h >> 58 & (1<<5 - 1) { - case 0x1F: - return "NaN" - case 0x1E: - return "-Infinity"[posSign:] - } - - low = d.l - if d.h>>61&3 == 3 { - // Bits: 1*sign 2*ignored 14*exponent 111*significand. - // Implicit 0b100 prefix in significand. - exp = int(d.h >> 47 & (1<<14 - 1)) - //high = 4<<47 | d.h&(1<<47-1) - // Spec says all of these values are out of range. - high, low = 0, 0 - } else { - // Bits: 1*sign 14*exponent 113*significand - exp = int(d.h >> 49 & (1<<14 - 1)) - high = d.h & (1<<49 - 1) - } - exp += MinDecimal128Exp - - // Would be handled by the logic below, but that's trivial and common. - if high == 0 && low == 0 && exp == 0 { - return "-0"[posSign:] - } - - var repr [48]byte // Loop 5 times over 9 digits plus dot, negative sign, and leading zero. - var last = len(repr) - var i = len(repr) - var dot = len(repr) + exp - var rem uint32 -Loop: - for d9 := 0; d9 < 5; d9++ { - high, low, rem = divmod(high, low, 1e9) - for d1 := 0; d1 < 9; d1++ { - // Handle "-0.0", "0.00123400", "-1.00E-6", "1.050E+3", etc. - if i < len(repr) && (dot == i || low == 0 && high == 0 && rem > 0 && rem < 10 && (dot < i-6 || exp > 0)) { - exp += len(repr) - i - i-- - repr[i] = '.' - last = i - 1 - dot = len(repr) // Unmark. - } - c := '0' + byte(rem%10) - rem /= 10 - i-- - repr[i] = c - // Handle "0E+3", "1E+3", etc. - if low == 0 && high == 0 && rem == 0 && i == len(repr)-1 && (dot < i-5 || exp > 0) { - last = i - break Loop - } - if c != '0' { - last = i - } - // Break early. Works without it, but why. - if dot > i && low == 0 && high == 0 && rem == 0 { - break Loop - } - } - } - repr[last-1] = '-' - last-- - - if exp > 0 { - return string(repr[last+posSign:]) + "E+" + strconv.Itoa(exp) - } - if exp < 0 { - return string(repr[last+posSign:]) + "E" + strconv.Itoa(exp) - } - return string(repr[last+posSign:]) + return decimal128.String(d.h, d.l) } // BigInt returns significand as big.Int and exponent, bi * 10 ^ exp. @@ -212,7 +135,7 @@ func (d Decimal128) MarshalJSON() ([]byte, error) { return json.Marshal(d.String()) } -// UnmarshalJSON creates a primitive.Decimal128 from a JSON string, an extended JSON $numberDecimal value, or the string +// UnmarshalJSON creates a Decimal128 from a JSON string, an extended JSON $numberDecimal value, or the string // "null". If b is a JSON string or extended JSON value, d will have the value of that string, and if b is "null", d will // be unchanged. func (d *Decimal128) UnmarshalJSON(b []byte) error { @@ -250,23 +173,6 @@ func (d *Decimal128) UnmarshalJSON(b []byte) error { return err } -func divmod(h, l uint64, div uint32) (qh, ql uint64, rem uint32) { - div64 := uint64(div) - a := h >> 32 - aq := a / div64 - ar := a % div64 - b := ar<<32 + h&(1<<32-1) - bq := b / div64 - br := b % div64 - c := br<<32 + l>>32 - cq := c / div64 - cr := c % div64 - d := cr<<32 + l&(1<<32-1) - dq := d / div64 - dr := d % div64 - return (aq<<32 | bq), (cq<<32 | dq), uint32(dr) -} - var dNaN = Decimal128{0x1F << 58, 0} var dPosInf = Decimal128{0x1E << 58, 0} var dNegInf = Decimal128{0x3E << 58, 0} diff --git a/bson/primitive/decimal_test.go b/bson/decimal_test.go similarity index 99% rename from bson/primitive/decimal_test.go rename to bson/decimal_test.go index e67e11265b..cdd3318f26 100644 --- a/bson/primitive/decimal_test.go +++ b/bson/decimal_test.go @@ -4,7 +4,7 @@ // 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 primitive +package bson import ( "encoding/json" diff --git a/bson/decoder.go b/bson/decoder.go index 4ab9e7c43f..6ea5ad97c1 100644 --- a/bson/decoder.go +++ b/bson/decoder.go @@ -11,9 +11,6 @@ import ( "fmt" "reflect" "sync" - - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" ) // ErrDecodeToNil is the error returned when trying to decode to a nil value @@ -28,11 +25,11 @@ var decPool = sync.Pool{ }, } -// A Decoder reads and decodes BSON documents from a stream. It reads from a bsonrw.ValueReader as +// A Decoder reads and decodes BSON documents from a stream. It reads from a ValueReader as // the source of BSON data. type Decoder struct { - dc bsoncodec.DecodeContext - vr bsonrw.ValueReader + dc DecodeContext + vr ValueReader // We persist defaultDocumentM and defaultDocumentD on the Decoder to prevent overwriting from // (*Decoder).SetContext. @@ -47,9 +44,9 @@ type Decoder struct { } // NewDecoder returns a new decoder that uses the DefaultRegistry to read from vr. -func NewDecoder(vr bsonrw.ValueReader) *Decoder { +func NewDecoder(vr ValueReader) *Decoder { return &Decoder{ - dc: bsoncodec.DecodeContext{Registry: DefaultRegistry}, + dc: DecodeContext{Registry: DefaultRegistry}, vr: vr, } } @@ -61,7 +58,7 @@ func NewDecoder(vr bsonrw.ValueReader) *Decoder { func (d *Decoder) Decode(val interface{}) error { if unmarshaler, ok := val.(Unmarshaler); ok { // TODO(skriptble): Reuse a []byte here and use the AppendDocumentBytes method. - buf, err := bsonrw.Copier{}.CopyDocumentToBytes(d.vr) + buf, err := copyDocumentToBytes(d.vr) if err != nil { return err } @@ -114,12 +111,12 @@ func (d *Decoder) Decode(val interface{}) error { // Reset will reset the state of the decoder, using the same *DecodeContext used in // the original construction but using vr for reading. -func (d *Decoder) Reset(vr bsonrw.ValueReader) { +func (d *Decoder) Reset(vr ValueReader) { d.vr = vr } // SetRegistry replaces the current registry of the decoder with r. -func (d *Decoder) SetRegistry(r *bsoncodec.Registry) { +func (d *Decoder) SetRegistry(r *Registry) { d.dc.Registry = r } diff --git a/bson/decoder_example_test.go b/bson/decoder_example_test.go index a04d1129e4..3e17e98927 100644 --- a/bson/decoder_example_test.go +++ b/bson/decoder_example_test.go @@ -13,7 +13,6 @@ import ( "io" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsonrw" ) func ExampleDecoder() { @@ -31,7 +30,7 @@ func ExampleDecoder() { // Create a Decoder that reads the marshaled BSON document and use it to // unmarshal the document into a Product struct. - decoder := bson.NewDecoder(bsonrw.NewValueReader(data)) + decoder := bson.NewDecoder(bson.NewValueReader(data)) type Product struct { Name string `bson:"name"` @@ -67,17 +66,17 @@ func ExampleDecoder_DefaultDocumentM() { // Create a Decoder that reads the marshaled BSON document and use it to unmarshal the document // into a City struct. - decoder := bson.NewDecoder(bsonrw.NewValueReader(data)) + decoder := bson.NewDecoder(bson.NewValueReader(data)) type City struct { Name string `bson:"name"` Properties interface{} `bson:"properties"` } - // Configure the Decoder to default to decoding BSON documents as the bson.M + // Configure the Decoder to default to decoding BSON documents as the M // type if the decode destination has no type information. The Properties - // field in the City struct will be decoded as a "bson.M" (i.e. map) instead - // of the default "bson.D". + // field in the City struct will be decoded as a "M" (i.e. map) instead + // of the default "D". decoder.DefaultDocumentM() var res City @@ -105,7 +104,7 @@ func ExampleDecoder_UseJSONStructTags() { // Create a Decoder that reads the marshaled BSON document and use it to // unmarshal the document into a Product struct. - decoder := bson.NewDecoder(bsonrw.NewValueReader(data)) + decoder := bson.NewDecoder(bson.NewValueReader(data)) type Product struct { Name string `json:"name"` @@ -134,7 +133,7 @@ func ExampleDecoder_extendedJSON() { // Create a Decoder that reads the Extended JSON document and use it to // unmarshal the document into a Product struct. - vr, err := bsonrw.NewExtJSONValueReader(bytes.NewReader(data), true) + vr, err := bson.NewExtJSONValueReader(bytes.NewReader(data), true) if err != nil { panic(err) } @@ -169,7 +168,7 @@ func ExampleDecoder_multipleExtendedJSONDocuments() { // Create a Decoder that reads the Extended JSON documents and use it to // unmarshal the documents Coordinate structs. - vr, err := bsonrw.NewExtJSONValueReader(bytes.NewReader(data), true) + vr, err := bson.NewExtJSONValueReader(bytes.NewReader(data), true) if err != nil { panic(err) } diff --git a/bson/decoder_test.go b/bson/decoder_test.go index f1b5e7af7a..8fe8d07480 100644 --- a/bson/decoder_test.go +++ b/bson/decoder_test.go @@ -13,10 +13,6 @@ import ( "testing" "time" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsonrw/bsonrwtest" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/require" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" @@ -32,11 +28,11 @@ func TestBasicDecode(t *testing.T) { t.Parallel() got := reflect.New(tc.sType).Elem() - vr := bsonrw.NewValueReader(tc.data) + vr := NewValueReader(tc.data) reg := DefaultRegistry decoder, err := reg.LookupDecoder(reflect.TypeOf(got)) noerr(t, err) - err = decoder.DecodeValue(bsoncodec.DecodeContext{Registry: reg}, vr, got) + err = decoder.DecodeValue(DecodeContext{Registry: reg}, vr, got) noerr(t, err) assert.Equal(t, tc.want, got.Addr().Interface(), "Results do not match.") }) @@ -56,7 +52,7 @@ func TestDecoderv2(t *testing.T) { t.Parallel() got := reflect.New(tc.sType).Interface() - vr := bsonrw.NewValueReader(tc.data) + vr := NewValueReader(tc.data) dec := NewDecoder(vr) err := dec.Decode(got) noerr(t, err) @@ -71,8 +67,8 @@ func TestDecoderv2(t *testing.T) { _ = certainlydoesntexistelsewhereihope(func(string, string) string { return "" }) cdeih := func(string, string) string { return "certainlydoesntexistelsewhereihope" } - dec := NewDecoder(bsonrw.NewValueReader([]byte{})) - want := bsoncodec.ErrNoDecoder{Type: reflect.TypeOf(cdeih)} + dec := NewDecoder(NewValueReader([]byte{})) + want := ErrNoDecoder{Type: reflect.TypeOf(cdeih)} got := dec.Decode(&cdeih) assert.Equal(t, want, got, "Received unexpected error.") }) @@ -82,25 +78,25 @@ func TestDecoderv2(t *testing.T) { testCases := []struct { name string err error - vr bsonrw.ValueReader + vr ValueReader invoked bool }{ { "error", errors.New("Unmarshaler error"), - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.EmbeddedDocument, Err: bsonrw.ErrEOD, ErrAfter: bsonrwtest.ReadElement}, + &valueReaderWriter{BSONType: TypeEmbeddedDocument, Err: ErrEOD, ErrAfter: readElement}, true, }, { "copy error", errors.New("copy error"), - &bsonrwtest.ValueReaderWriter{Err: errors.New("copy error"), ErrAfter: bsonrwtest.ReadDocument}, + &valueReaderWriter{Err: errors.New("copy error"), ErrAfter: readDocument}, false, }, { "success", nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.EmbeddedDocument, Err: bsonrw.ErrEOD, ErrAfter: bsonrwtest.ReadElement}, + &valueReaderWriter{BSONType: TypeEmbeddedDocument, Err: ErrEOD, ErrAfter: readElement}, true, }, } @@ -111,14 +107,14 @@ func TestDecoderv2(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() - unmarshaler := &testUnmarshaler{err: tc.err} + unmarshaler := &testUnmarshaler{Err: tc.err} dec := NewDecoder(tc.vr) got := dec.Decode(unmarshaler) want := tc.err - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not receive expected error. got %v; want %v", got, want) } - if unmarshaler.invoked != tc.invoked { + if unmarshaler.Invoked != tc.invoked { if tc.invoked { t.Error("Expected to have UnmarshalBSON invoked, but it wasn't.") } else { @@ -128,16 +124,16 @@ func TestDecoderv2(t *testing.T) { }) } - t.Run("Unmarshaler/success bsonrw.ValueReader", func(t *testing.T) { + t.Run("Unmarshaler/success ValueReader", func(t *testing.T) { t.Parallel() want := bsoncore.BuildDocument(nil, bsoncore.AppendDoubleElement(nil, "pi", 3.14159)) unmarshaler := &testUnmarshaler{} - vr := bsonrw.NewValueReader(want) + vr := NewValueReader(want) dec := NewDecoder(vr) err := dec.Decode(unmarshaler) noerr(t, err) - got := unmarshaler.data + got := unmarshaler.Val if !bytes.Equal(got, want) { t.Errorf("Did not unmarshal properly. got %v; want %v", got, want) } @@ -150,7 +146,7 @@ func TestDecoderv2(t *testing.T) { t.Run("success", func(t *testing.T) { t.Parallel() - got := NewDecoder(bsonrw.NewValueReader([]byte{})) + got := NewDecoder(NewValueReader([]byte{})) if got == nil { t.Errorf("Was expecting a non-nil Decoder, but got ") } @@ -162,7 +158,7 @@ func TestDecoderv2(t *testing.T) { t.Run("success", func(t *testing.T) { t.Parallel() - got := NewDecoder(bsonrw.NewValueReader([]byte{})) + got := NewDecoder(NewValueReader([]byte{})) if got == nil { t.Errorf("Was expecting a non-nil Decoder, but got ") } @@ -180,7 +176,7 @@ func TestDecoderv2(t *testing.T) { got.Item = "apple" got.Bonus = 2 data := docToBytes(D{{"item", "canvas"}, {"qty", 4}}) - vr := bsonrw.NewValueReader(data) + vr := NewValueReader(data) dec := NewDecoder(vr) err := dec.Decode(&got) noerr(t, err) @@ -190,7 +186,7 @@ func TestDecoderv2(t *testing.T) { t.Run("Reset", func(t *testing.T) { t.Parallel() - vr1, vr2 := bsonrw.NewValueReader([]byte{}), bsonrw.NewValueReader([]byte{}) + vr1, vr2 := NewValueReader([]byte{}), NewValueReader([]byte{}) dec := NewDecoder(vr1) if dec.vr != vr1 { t.Errorf("Decoder should use the value reader provided. got %v; want %v", dec.vr, vr1) @@ -204,9 +200,9 @@ func TestDecoderv2(t *testing.T) { t.Parallel() r1, r2 := DefaultRegistry, NewRegistry() - dc1 := bsoncodec.DecodeContext{Registry: r1} - dc2 := bsoncodec.DecodeContext{Registry: r2} - dec := NewDecoder(bsonrw.NewValueReader([]byte{})) + dc1 := DecodeContext{Registry: r1} + dc2 := DecodeContext{Registry: r2} + dec := NewDecoder(NewValueReader([]byte{})) if !reflect.DeepEqual(dec.dc, dc1) { t.Errorf("Decoder should use the Registry provided. got %v; want %v", dec.dc, dc1) } @@ -219,7 +215,7 @@ func TestDecoderv2(t *testing.T) { t.Parallel() data := docToBytes(D{{"item", "canvas"}, {"qty", 4}}) - vr := bsonrw.NewValueReader(data) + vr := NewValueReader(data) dec := NewDecoder(vr) var got *D @@ -231,15 +227,15 @@ func TestDecoderv2(t *testing.T) { } type testUnmarshaler struct { - invoked bool - err error - data []byte + Invoked bool + Val []byte + Err error } func (tu *testUnmarshaler) UnmarshalBSON(d []byte) error { - tu.invoked = true - tu.data = d - return tu.err + tu.Invoked = true + tu.Val = d + return tu.Err } func TestDecoderConfiguration(t *testing.T) { @@ -321,7 +317,7 @@ func TestDecoderConfiguration(t *testing.T) { dec.BinaryAsSlice() }, input: bsoncore.NewDocumentBuilder(). - AppendBinary("myBinary", bsontype.BinaryGeneric, []byte{}). + AppendBinary("myBinary", TypeBinaryGeneric, []byte{}). Build(), decodeInto: func() interface{} { return &D{} }, want: &D{{Key: "myBinary", Value: []byte{}}}, @@ -426,7 +422,7 @@ func TestDecoderConfiguration(t *testing.T) { t.Run(tc.description, func(t *testing.T) { t.Parallel() - dec := NewDecoder(bsonrw.NewValueReader(tc.input)) + dec := NewDecoder(NewValueReader(tc.input)) tc.configure(dec) @@ -447,7 +443,7 @@ func TestDecoderConfiguration(t *testing.T) { Build()). Build() - dec := NewDecoder(bsonrw.NewValueReader(input)) + dec := NewDecoder(NewValueReader(input)) dec.DefaultDocumentM() @@ -471,7 +467,7 @@ func TestDecoderConfiguration(t *testing.T) { Build()). Build() - dec := NewDecoder(bsonrw.NewValueReader(input)) + dec := NewDecoder(NewValueReader(input)) dec.DefaultDocumentD() diff --git a/bson/bsoncodec/default_value_decoders.go b/bson/default_value_decoders.go similarity index 81% rename from bson/bsoncodec/default_value_decoders.go rename to bson/default_value_decoders.go index 7e08aab35e..bc8c7b9344 100644 --- a/bson/bsoncodec/default_value_decoders.go +++ b/bson/default_value_decoders.go @@ -4,7 +4,7 @@ // 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 +package bson import ( "encoding/json" @@ -16,9 +16,6 @@ import ( "strconv" "time" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -112,48 +109,48 @@ func (dvd DefaultValueDecoders) RegisterDefaultDecoders(rb *RegistryBuilder) { RegisterDefaultDecoder(reflect.String, defaultStringCodec). RegisterDefaultDecoder(reflect.Struct, newDefaultStructCodec()). RegisterDefaultDecoder(reflect.Ptr, NewPointerCodec()). - RegisterTypeMapEntry(bsontype.Double, tFloat64). - RegisterTypeMapEntry(bsontype.String, tString). - RegisterTypeMapEntry(bsontype.Array, tA). - RegisterTypeMapEntry(bsontype.Binary, tBinary). - RegisterTypeMapEntry(bsontype.Undefined, tUndefined). - RegisterTypeMapEntry(bsontype.ObjectID, tOID). - RegisterTypeMapEntry(bsontype.Boolean, tBool). - RegisterTypeMapEntry(bsontype.DateTime, tDateTime). - RegisterTypeMapEntry(bsontype.Regex, tRegex). - RegisterTypeMapEntry(bsontype.DBPointer, tDBPointer). - RegisterTypeMapEntry(bsontype.JavaScript, tJavaScript). - RegisterTypeMapEntry(bsontype.Symbol, tSymbol). - RegisterTypeMapEntry(bsontype.CodeWithScope, tCodeWithScope). - RegisterTypeMapEntry(bsontype.Int32, tInt32). - RegisterTypeMapEntry(bsontype.Int64, tInt64). - RegisterTypeMapEntry(bsontype.Timestamp, tTimestamp). - RegisterTypeMapEntry(bsontype.Decimal128, tDecimal). - RegisterTypeMapEntry(bsontype.MinKey, tMinKey). - RegisterTypeMapEntry(bsontype.MaxKey, tMaxKey). - RegisterTypeMapEntry(bsontype.Type(0), tD). - RegisterTypeMapEntry(bsontype.EmbeddedDocument, tD). + RegisterTypeMapEntry(TypeDouble, tFloat64). + RegisterTypeMapEntry(TypeString, tString). + RegisterTypeMapEntry(TypeArray, tA). + RegisterTypeMapEntry(TypeBinary, tBinary). + RegisterTypeMapEntry(TypeUndefined, tUndefined). + RegisterTypeMapEntry(TypeObjectID, tOID). + RegisterTypeMapEntry(TypeBoolean, tBool). + RegisterTypeMapEntry(TypeDateTime, tDateTime). + RegisterTypeMapEntry(TypeRegex, tRegex). + RegisterTypeMapEntry(TypeDBPointer, tDBPointer). + RegisterTypeMapEntry(TypeJavaScript, tJavaScript). + RegisterTypeMapEntry(TypeSymbol, tSymbol). + RegisterTypeMapEntry(TypeCodeWithScope, tCodeWithScope). + RegisterTypeMapEntry(TypeInt32, tInt32). + RegisterTypeMapEntry(TypeInt64, tInt64). + RegisterTypeMapEntry(TypeTimestamp, tTimestamp). + RegisterTypeMapEntry(TypeDecimal128, tDecimal). + RegisterTypeMapEntry(TypeMinKey, tMinKey). + RegisterTypeMapEntry(TypeMaxKey, tMaxKey). + RegisterTypeMapEntry(Type(0), tD). + RegisterTypeMapEntry(TypeEmbeddedDocument, tD). RegisterHookDecoder(tValueUnmarshaler, ValueDecoderFunc(dvd.ValueUnmarshalerDecodeValue)). RegisterHookDecoder(tUnmarshaler, ValueDecoderFunc(dvd.UnmarshalerDecodeValue)) } -// DDecodeValue is the ValueDecoderFunc for primitive.D instances. +// DDecodeValue is the ValueDecoderFunc for D instances. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) DDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) DDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.IsValid() || !val.CanSet() || val.Type() != tD { return ValueDecoderError{Name: "DDecodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val} } switch vrType := vr.Type(); vrType { - case bsontype.Type(0), bsontype.EmbeddedDocument: + case Type(0), TypeEmbeddedDocument: dc.Ancestor = tD - case bsontype.Null: + case TypeNull: val.Set(reflect.Zero(val.Type())) return vr.ReadNull() default: - return fmt.Errorf("cannot decode %v into a primitive.D", vrType) + return fmt.Errorf("cannot decode %v into a D", vrType) } dr, err := vr.ReadDocument() @@ -168,17 +165,17 @@ func (dvd DefaultValueDecoders) DDecodeValue(dc DecodeContext, vr bsonrw.ValueRe tEmptyTypeDecoder, _ := decoder.(typeDecoder) // Use the elements in the provided value if it's non nil. Otherwise, allocate a new D instance. - var elems primitive.D + var elems D if !val.IsNil() { val.SetLen(0) - elems = val.Interface().(primitive.D) + elems = val.Interface().(D) } else { - elems = make(primitive.D, 0) + elems = make(D, 0) } for { key, elemVr, err := dr.ReadElement() - if errors.Is(err, bsonrw.ErrEOD) { + if errors.Is(err, ErrEOD) { break } else if err != nil { return err @@ -190,14 +187,14 @@ func (dvd DefaultValueDecoders) DDecodeValue(dc DecodeContext, vr bsonrw.ValueRe return err } - elems = append(elems, primitive.E{Key: key, Value: elem.Interface()}) + elems = append(elems, E{Key: key, Value: elem.Interface()}) } val.Set(reflect.ValueOf(elems)) return nil } -func (dvd DefaultValueDecoders) booleanDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (dvd DefaultValueDecoders) booleanDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t.Kind() != reflect.Bool { return emptyValue, ValueDecoderError{ Name: "BooleanDecodeValue", @@ -209,29 +206,29 @@ func (dvd DefaultValueDecoders) booleanDecodeType(_ DecodeContext, vr bsonrw.Val var b bool var err error switch vrType := vr.Type(); vrType { - case bsontype.Int32: + case TypeInt32: i32, err := vr.ReadInt32() if err != nil { return emptyValue, err } b = (i32 != 0) - case bsontype.Int64: + case TypeInt64: i64, err := vr.ReadInt64() if err != nil { return emptyValue, err } b = (i64 != 0) - case bsontype.Double: + case TypeDouble: f64, err := vr.ReadDouble() if err != nil { return emptyValue, err } b = (f64 != 0) - case bsontype.Boolean: + case TypeBoolean: b, err = vr.ReadBoolean() - case bsontype.Null: + case TypeNull: err = vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() default: return emptyValue, fmt.Errorf("cannot decode %v into a boolean", vrType) @@ -247,7 +244,7 @@ func (dvd DefaultValueDecoders) booleanDecodeType(_ DecodeContext, vr bsonrw.Val // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) BooleanDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) BooleanDecodeValue(dctx DecodeContext, vr ValueReader, val reflect.Value) error { if !val.IsValid() || !val.CanSet() || val.Kind() != reflect.Bool { return ValueDecoderError{Name: "BooleanDecodeValue", Kinds: []reflect.Kind{reflect.Bool}, Received: val} } @@ -261,22 +258,22 @@ func (dvd DefaultValueDecoders) BooleanDecodeValue(dctx DecodeContext, vr bsonrw return nil } -func (DefaultValueDecoders) intDecodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (DefaultValueDecoders) intDecodeType(dc DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { var i64 int64 var err error switch vrType := vr.Type(); vrType { - case bsontype.Int32: + case TypeInt32: i32, err := vr.ReadInt32() if err != nil { return emptyValue, err } i64 = int64(i32) - case bsontype.Int64: + case TypeInt64: i64, err = vr.ReadInt64() if err != nil { return emptyValue, err } - case bsontype.Double: + case TypeDouble: f64, err := vr.ReadDouble() if err != nil { return emptyValue, err @@ -288,7 +285,7 @@ func (DefaultValueDecoders) intDecodeType(dc DecodeContext, vr bsonrw.ValueReade return emptyValue, fmt.Errorf("%g overflows int64", f64) } i64 = int64(f64) - case bsontype.Boolean: + case TypeBoolean: b, err := vr.ReadBoolean() if err != nil { return emptyValue, err @@ -296,11 +293,11 @@ func (DefaultValueDecoders) intDecodeType(dc DecodeContext, vr bsonrw.ValueReade if b { i64 = 1 } - case bsontype.Null: + case TypeNull: if err = vr.ReadNull(); err != nil { return emptyValue, err } - case bsontype.Undefined: + case TypeUndefined: if err = vr.ReadUndefined(); err != nil { return emptyValue, err } @@ -348,7 +345,7 @@ func (DefaultValueDecoders) intDecodeType(dc DecodeContext, vr bsonrw.ValueReade // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) IntDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) IntDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() { return ValueDecoderError{ Name: "IntDecodeValue", @@ -369,22 +366,22 @@ func (dvd DefaultValueDecoders) IntDecodeValue(dc DecodeContext, vr bsonrw.Value // UintDecodeValue is the ValueDecoderFunc for uint types. // // Deprecated: UintDecodeValue is not registered by default. Use UintCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) UintDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) UintDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { var i64 int64 var err error switch vr.Type() { - case bsontype.Int32: + case TypeInt32: i32, err := vr.ReadInt32() if err != nil { return err } i64 = int64(i32) - case bsontype.Int64: + case TypeInt64: i64, err = vr.ReadInt64() if err != nil { return err } - case bsontype.Double: + case TypeDouble: f64, err := vr.ReadDouble() if err != nil { return err @@ -396,7 +393,7 @@ func (dvd DefaultValueDecoders) UintDecodeValue(dc DecodeContext, vr bsonrw.Valu return fmt.Errorf("%g overflows int64", f64) } i64 = int64(f64) - case bsontype.Boolean: + case TypeBoolean: b, err := vr.ReadBoolean() if err != nil { return err @@ -449,28 +446,28 @@ func (dvd DefaultValueDecoders) UintDecodeValue(dc DecodeContext, vr bsonrw.Valu return nil } -func (dvd DefaultValueDecoders) floatDecodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (dvd DefaultValueDecoders) floatDecodeType(dc DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { var f float64 var err error switch vrType := vr.Type(); vrType { - case bsontype.Int32: + case TypeInt32: i32, err := vr.ReadInt32() if err != nil { return emptyValue, err } f = float64(i32) - case bsontype.Int64: + case TypeInt64: i64, err := vr.ReadInt64() if err != nil { return emptyValue, err } f = float64(i64) - case bsontype.Double: + case TypeDouble: f, err = vr.ReadDouble() if err != nil { return emptyValue, err } - case bsontype.Boolean: + case TypeBoolean: b, err := vr.ReadBoolean() if err != nil { return emptyValue, err @@ -478,11 +475,11 @@ func (dvd DefaultValueDecoders) floatDecodeType(dc DecodeContext, vr bsonrw.Valu if b { f = 1 } - case bsontype.Null: + case TypeNull: if err = vr.ReadNull(); err != nil { return emptyValue, err } - case bsontype.Undefined: + case TypeUndefined: if err = vr.ReadUndefined(); err != nil { return emptyValue, err } @@ -512,7 +509,7 @@ func (dvd DefaultValueDecoders) floatDecodeType(dc DecodeContext, vr bsonrw.Valu // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) FloatDecodeValue(ec DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) FloatDecodeValue(ec DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() { return ValueDecoderError{ Name: "FloatDecodeValue", @@ -533,12 +530,12 @@ func (dvd DefaultValueDecoders) FloatDecodeValue(ec DecodeContext, vr bsonrw.Val // StringDecodeValue is the ValueDecoderFunc for string types. // // Deprecated: StringDecodeValue is not registered by default. Use StringCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) StringDecodeValue(_ DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) StringDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { var str string var err error switch vr.Type() { // TODO(GODRIVER-577): Handle JavaScript and Symbol BSON types when allowed. - case bsontype.String: + case TypeString: str, err = vr.ReadString() if err != nil { return err @@ -554,7 +551,7 @@ func (dvd DefaultValueDecoders) StringDecodeValue(_ DecodeContext, vr bsonrw.Val return nil } -func (DefaultValueDecoders) javaScriptDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (DefaultValueDecoders) javaScriptDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tJavaScript { return emptyValue, ValueDecoderError{ Name: "JavaScriptDecodeValue", @@ -566,27 +563,27 @@ func (DefaultValueDecoders) javaScriptDecodeType(_ DecodeContext, vr bsonrw.Valu var js string var err error switch vrType := vr.Type(); vrType { - case bsontype.JavaScript: + case TypeJavaScript: js, err = vr.ReadJavascript() - case bsontype.Null: + case TypeNull: err = vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() default: - return emptyValue, fmt.Errorf("cannot decode %v into a primitive.JavaScript", vrType) + return emptyValue, fmt.Errorf("cannot decode %v into a JavaScript", vrType) } if err != nil { return emptyValue, err } - return reflect.ValueOf(primitive.JavaScript(js)), nil + return reflect.ValueOf(JavaScript(js)), nil } -// JavaScriptDecodeValue is the ValueDecoderFunc for the primitive.JavaScript type. +// JavaScriptDecodeValue is the ValueDecoderFunc for the JavaScript type. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) JavaScriptDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) JavaScriptDecodeValue(dctx DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tJavaScript { return ValueDecoderError{Name: "JavaScriptDecodeValue", Types: []reflect.Type{tJavaScript}, Received: val} } @@ -600,7 +597,7 @@ func (dvd DefaultValueDecoders) JavaScriptDecodeValue(dctx DecodeContext, vr bso return nil } -func (DefaultValueDecoders) symbolDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (DefaultValueDecoders) symbolDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tSymbol { return emptyValue, ValueDecoderError{ Name: "SymbolDecodeValue", @@ -612,39 +609,39 @@ func (DefaultValueDecoders) symbolDecodeType(_ DecodeContext, vr bsonrw.ValueRea var symbol string var err error switch vrType := vr.Type(); vrType { - case bsontype.String: + case TypeString: symbol, err = vr.ReadString() - case bsontype.Symbol: + case TypeSymbol: symbol, err = vr.ReadSymbol() - case bsontype.Binary: + case TypeBinary: data, subtype, err := vr.ReadBinary() if err != nil { return emptyValue, err } - if subtype != bsontype.BinaryGeneric && subtype != bsontype.BinaryBinaryOld { - return emptyValue, decodeBinaryError{subtype: subtype, typeName: "primitive.Symbol"} + if subtype != TypeBinaryGeneric && subtype != TypeBinaryBinaryOld { + return emptyValue, decodeBinaryError{subtype: subtype, typeName: "Symbol"} } symbol = string(data) - case bsontype.Null: + case TypeNull: err = vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() default: - return emptyValue, fmt.Errorf("cannot decode %v into a primitive.Symbol", vrType) + return emptyValue, fmt.Errorf("cannot decode %v into a Symbol", vrType) } if err != nil { return emptyValue, err } - return reflect.ValueOf(primitive.Symbol(symbol)), nil + return reflect.ValueOf(Symbol(symbol)), nil } -// SymbolDecodeValue is the ValueDecoderFunc for the primitive.Symbol type. +// SymbolDecodeValue is the ValueDecoderFunc for the Symbol type. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) SymbolDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) SymbolDecodeValue(dctx DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tSymbol { return ValueDecoderError{Name: "SymbolDecodeValue", Types: []reflect.Type{tSymbol}, Received: val} } @@ -658,7 +655,7 @@ func (dvd DefaultValueDecoders) SymbolDecodeValue(dctx DecodeContext, vr bsonrw. return nil } -func (DefaultValueDecoders) binaryDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (DefaultValueDecoders) binaryDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tBinary { return emptyValue, ValueDecoderError{ Name: "BinaryDecodeValue", @@ -671,11 +668,11 @@ func (DefaultValueDecoders) binaryDecodeType(_ DecodeContext, vr bsonrw.ValueRea var subtype byte var err error switch vrType := vr.Type(); vrType { - case bsontype.Binary: + case TypeBinary: data, subtype, err = vr.ReadBinary() - case bsontype.Null: + case TypeNull: err = vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() default: return emptyValue, fmt.Errorf("cannot decode %v into a Binary", vrType) @@ -684,14 +681,14 @@ func (DefaultValueDecoders) binaryDecodeType(_ DecodeContext, vr bsonrw.ValueRea return emptyValue, err } - return reflect.ValueOf(primitive.Binary{Subtype: subtype, Data: data}), nil + return reflect.ValueOf(Binary{Subtype: subtype, Data: data}), nil } // BinaryDecodeValue is the ValueDecoderFunc for Binary. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) BinaryDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) BinaryDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tBinary { return ValueDecoderError{Name: "BinaryDecodeValue", Types: []reflect.Type{tBinary}, Received: val} } @@ -705,7 +702,7 @@ func (dvd DefaultValueDecoders) BinaryDecodeValue(dc DecodeContext, vr bsonrw.Va return nil } -func (DefaultValueDecoders) undefinedDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (DefaultValueDecoders) undefinedDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tUndefined { return emptyValue, ValueDecoderError{ Name: "UndefinedDecodeValue", @@ -716,9 +713,9 @@ func (DefaultValueDecoders) undefinedDecodeType(_ DecodeContext, vr bsonrw.Value var err error switch vrType := vr.Type(); vrType { - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() - case bsontype.Null: + case TypeNull: err = vr.ReadNull() default: return emptyValue, fmt.Errorf("cannot decode %v into an Undefined", vr.Type()) @@ -727,14 +724,14 @@ func (DefaultValueDecoders) undefinedDecodeType(_ DecodeContext, vr bsonrw.Value return emptyValue, err } - return reflect.ValueOf(primitive.Undefined{}), nil + return reflect.ValueOf(Undefined{}), nil } // UndefinedDecodeValue is the ValueDecoderFunc for Undefined. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) UndefinedDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) UndefinedDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tUndefined { return ValueDecoderError{Name: "UndefinedDecodeValue", Types: []reflect.Type{tUndefined}, Received: val} } @@ -749,7 +746,7 @@ func (dvd DefaultValueDecoders) UndefinedDecodeValue(dc DecodeContext, vr bsonrw } // Accept both 12-byte string and pretty-printed 24-byte hex string formats. -func (dvd DefaultValueDecoders) objectIDDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (dvd DefaultValueDecoders) objectIDDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tOID { return emptyValue, ValueDecoderError{ Name: "ObjectIDDecodeValue", @@ -758,20 +755,20 @@ func (dvd DefaultValueDecoders) objectIDDecodeType(_ DecodeContext, vr bsonrw.Va } } - var oid primitive.ObjectID + var oid ObjectID var err error switch vrType := vr.Type(); vrType { - case bsontype.ObjectID: + case TypeObjectID: oid, err = vr.ReadObjectID() if err != nil { return emptyValue, err } - case bsontype.String: + case TypeString: str, err := vr.ReadString() if err != nil { return emptyValue, err } - if oid, err = primitive.ObjectIDFromHex(str); err == nil { + if oid, err = ObjectIDFromHex(str); err == nil { break } if len(str) != 12 { @@ -779,11 +776,11 @@ func (dvd DefaultValueDecoders) objectIDDecodeType(_ DecodeContext, vr bsonrw.Va } byteArr := []byte(str) copy(oid[:], byteArr) - case bsontype.Null: + case TypeNull: if err = vr.ReadNull(); err != nil { return emptyValue, err } - case bsontype.Undefined: + case TypeUndefined: if err = vr.ReadUndefined(); err != nil { return emptyValue, err } @@ -794,11 +791,11 @@ func (dvd DefaultValueDecoders) objectIDDecodeType(_ DecodeContext, vr bsonrw.Va return reflect.ValueOf(oid), nil } -// ObjectIDDecodeValue is the ValueDecoderFunc for primitive.ObjectID. +// ObjectIDDecodeValue is the ValueDecoderFunc for ObjectID. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) ObjectIDDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) ObjectIDDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tOID { return ValueDecoderError{Name: "ObjectIDDecodeValue", Types: []reflect.Type{tOID}, Received: val} } @@ -812,7 +809,7 @@ func (dvd DefaultValueDecoders) ObjectIDDecodeValue(dc DecodeContext, vr bsonrw. return nil } -func (DefaultValueDecoders) dateTimeDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (DefaultValueDecoders) dateTimeDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tDateTime { return emptyValue, ValueDecoderError{ Name: "DateTimeDecodeValue", @@ -824,11 +821,11 @@ func (DefaultValueDecoders) dateTimeDecodeType(_ DecodeContext, vr bsonrw.ValueR var dt int64 var err error switch vrType := vr.Type(); vrType { - case bsontype.DateTime: + case TypeDateTime: dt, err = vr.ReadDateTime() - case bsontype.Null: + case TypeNull: err = vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() default: return emptyValue, fmt.Errorf("cannot decode %v into a DateTime", vrType) @@ -837,14 +834,14 @@ func (DefaultValueDecoders) dateTimeDecodeType(_ DecodeContext, vr bsonrw.ValueR return emptyValue, err } - return reflect.ValueOf(primitive.DateTime(dt)), nil + return reflect.ValueOf(DateTime(dt)), nil } // DateTimeDecodeValue is the ValueDecoderFunc for DateTime. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) DateTimeDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) DateTimeDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tDateTime { return ValueDecoderError{Name: "DateTimeDecodeValue", Types: []reflect.Type{tDateTime}, Received: val} } @@ -858,7 +855,7 @@ func (dvd DefaultValueDecoders) DateTimeDecodeValue(dc DecodeContext, vr bsonrw. return nil } -func (DefaultValueDecoders) nullDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (DefaultValueDecoders) nullDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tNull { return emptyValue, ValueDecoderError{ Name: "NullDecodeValue", @@ -869,9 +866,9 @@ func (DefaultValueDecoders) nullDecodeType(_ DecodeContext, vr bsonrw.ValueReade var err error switch vrType := vr.Type(); vrType { - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() - case bsontype.Null: + case TypeNull: err = vr.ReadNull() default: return emptyValue, fmt.Errorf("cannot decode %v into a Null", vr.Type()) @@ -880,14 +877,14 @@ func (DefaultValueDecoders) nullDecodeType(_ DecodeContext, vr bsonrw.ValueReade return emptyValue, err } - return reflect.ValueOf(primitive.Null{}), nil + return reflect.ValueOf(Null{}), nil } // NullDecodeValue is the ValueDecoderFunc for Null. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) NullDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) NullDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tNull { return ValueDecoderError{Name: "NullDecodeValue", Types: []reflect.Type{tNull}, Received: val} } @@ -901,7 +898,7 @@ func (dvd DefaultValueDecoders) NullDecodeValue(dc DecodeContext, vr bsonrw.Valu return nil } -func (DefaultValueDecoders) regexDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (DefaultValueDecoders) regexDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tRegex { return emptyValue, ValueDecoderError{ Name: "RegexDecodeValue", @@ -913,11 +910,11 @@ func (DefaultValueDecoders) regexDecodeType(_ DecodeContext, vr bsonrw.ValueRead var pattern, options string var err error switch vrType := vr.Type(); vrType { - case bsontype.Regex: + case TypeRegex: pattern, options, err = vr.ReadRegex() - case bsontype.Null: + case TypeNull: err = vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() default: return emptyValue, fmt.Errorf("cannot decode %v into a Regex", vrType) @@ -926,14 +923,14 @@ func (DefaultValueDecoders) regexDecodeType(_ DecodeContext, vr bsonrw.ValueRead return emptyValue, err } - return reflect.ValueOf(primitive.Regex{Pattern: pattern, Options: options}), nil + return reflect.ValueOf(Regex{Pattern: pattern, Options: options}), nil } // RegexDecodeValue is the ValueDecoderFunc for Regex. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) RegexDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) RegexDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tRegex { return ValueDecoderError{Name: "RegexDecodeValue", Types: []reflect.Type{tRegex}, Received: val} } @@ -947,7 +944,7 @@ func (dvd DefaultValueDecoders) RegexDecodeValue(dc DecodeContext, vr bsonrw.Val return nil } -func (DefaultValueDecoders) dBPointerDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (DefaultValueDecoders) dBPointerDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tDBPointer { return emptyValue, ValueDecoderError{ Name: "DBPointerDecodeValue", @@ -957,14 +954,14 @@ func (DefaultValueDecoders) dBPointerDecodeType(_ DecodeContext, vr bsonrw.Value } var ns string - var pointer primitive.ObjectID + var pointer ObjectID var err error switch vrType := vr.Type(); vrType { - case bsontype.DBPointer: + case TypeDBPointer: ns, pointer, err = vr.ReadDBPointer() - case bsontype.Null: + case TypeNull: err = vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() default: return emptyValue, fmt.Errorf("cannot decode %v into a DBPointer", vrType) @@ -973,14 +970,14 @@ func (DefaultValueDecoders) dBPointerDecodeType(_ DecodeContext, vr bsonrw.Value return emptyValue, err } - return reflect.ValueOf(primitive.DBPointer{DB: ns, Pointer: pointer}), nil + return reflect.ValueOf(DBPointer{DB: ns, Pointer: pointer}), nil } // DBPointerDecodeValue is the ValueDecoderFunc for DBPointer. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) DBPointerDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) DBPointerDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tDBPointer { return ValueDecoderError{Name: "DBPointerDecodeValue", Types: []reflect.Type{tDBPointer}, Received: val} } @@ -994,7 +991,7 @@ func (dvd DefaultValueDecoders) DBPointerDecodeValue(dc DecodeContext, vr bsonrw return nil } -func (DefaultValueDecoders) timestampDecodeType(_ DecodeContext, vr bsonrw.ValueReader, reflectType reflect.Type) (reflect.Value, error) { +func (DefaultValueDecoders) timestampDecodeType(_ DecodeContext, vr ValueReader, reflectType reflect.Type) (reflect.Value, error) { if reflectType != tTimestamp { return emptyValue, ValueDecoderError{ Name: "TimestampDecodeValue", @@ -1006,11 +1003,11 @@ func (DefaultValueDecoders) timestampDecodeType(_ DecodeContext, vr bsonrw.Value var t, incr uint32 var err error switch vrType := vr.Type(); vrType { - case bsontype.Timestamp: + case TypeTimestamp: t, incr, err = vr.ReadTimestamp() - case bsontype.Null: + case TypeNull: err = vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() default: return emptyValue, fmt.Errorf("cannot decode %v into a Timestamp", vrType) @@ -1019,14 +1016,14 @@ func (DefaultValueDecoders) timestampDecodeType(_ DecodeContext, vr bsonrw.Value return emptyValue, err } - return reflect.ValueOf(primitive.Timestamp{T: t, I: incr}), nil + return reflect.ValueOf(Timestamp{T: t, I: incr}), nil } // TimestampDecodeValue is the ValueDecoderFunc for Timestamp. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) TimestampDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) TimestampDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tTimestamp { return ValueDecoderError{Name: "TimestampDecodeValue", Types: []reflect.Type{tTimestamp}, Received: val} } @@ -1040,7 +1037,7 @@ func (dvd DefaultValueDecoders) TimestampDecodeValue(dc DecodeContext, vr bsonrw return nil } -func (DefaultValueDecoders) minKeyDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (DefaultValueDecoders) minKeyDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tMinKey { return emptyValue, ValueDecoderError{ Name: "MinKeyDecodeValue", @@ -1051,11 +1048,11 @@ func (DefaultValueDecoders) minKeyDecodeType(_ DecodeContext, vr bsonrw.ValueRea var err error switch vrType := vr.Type(); vrType { - case bsontype.MinKey: + case TypeMinKey: err = vr.ReadMinKey() - case bsontype.Null: + case TypeNull: err = vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() default: return emptyValue, fmt.Errorf("cannot decode %v into a MinKey", vr.Type()) @@ -1064,14 +1061,14 @@ func (DefaultValueDecoders) minKeyDecodeType(_ DecodeContext, vr bsonrw.ValueRea return emptyValue, err } - return reflect.ValueOf(primitive.MinKey{}), nil + return reflect.ValueOf(MinKey{}), nil } // MinKeyDecodeValue is the ValueDecoderFunc for MinKey. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) MinKeyDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) MinKeyDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tMinKey { return ValueDecoderError{Name: "MinKeyDecodeValue", Types: []reflect.Type{tMinKey}, Received: val} } @@ -1085,7 +1082,7 @@ func (dvd DefaultValueDecoders) MinKeyDecodeValue(dc DecodeContext, vr bsonrw.Va return nil } -func (DefaultValueDecoders) maxKeyDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (DefaultValueDecoders) maxKeyDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tMaxKey { return emptyValue, ValueDecoderError{ Name: "MaxKeyDecodeValue", @@ -1096,11 +1093,11 @@ func (DefaultValueDecoders) maxKeyDecodeType(_ DecodeContext, vr bsonrw.ValueRea var err error switch vrType := vr.Type(); vrType { - case bsontype.MaxKey: + case TypeMaxKey: err = vr.ReadMaxKey() - case bsontype.Null: + case TypeNull: err = vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() default: return emptyValue, fmt.Errorf("cannot decode %v into a MaxKey", vr.Type()) @@ -1109,14 +1106,14 @@ func (DefaultValueDecoders) maxKeyDecodeType(_ DecodeContext, vr bsonrw.ValueRea return emptyValue, err } - return reflect.ValueOf(primitive.MaxKey{}), nil + return reflect.ValueOf(MaxKey{}), nil } // MaxKeyDecodeValue is the ValueDecoderFunc for MaxKey. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) MaxKeyDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) MaxKeyDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tMaxKey { return ValueDecoderError{Name: "MaxKeyDecodeValue", Types: []reflect.Type{tMaxKey}, Received: val} } @@ -1130,7 +1127,7 @@ func (dvd DefaultValueDecoders) MaxKeyDecodeValue(dc DecodeContext, vr bsonrw.Va return nil } -func (dvd DefaultValueDecoders) decimal128DecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (dvd DefaultValueDecoders) decimal128DecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tDecimal { return emptyValue, ValueDecoderError{ Name: "Decimal128DecodeValue", @@ -1139,17 +1136,17 @@ func (dvd DefaultValueDecoders) decimal128DecodeType(_ DecodeContext, vr bsonrw. } } - var d128 primitive.Decimal128 + var d128 Decimal128 var err error switch vrType := vr.Type(); vrType { - case bsontype.Decimal128: + case TypeDecimal128: d128, err = vr.ReadDecimal128() - case bsontype.Null: + case TypeNull: err = vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() default: - return emptyValue, fmt.Errorf("cannot decode %v into a primitive.Decimal128", vr.Type()) + return emptyValue, fmt.Errorf("cannot decode %v into a Decimal128", vr.Type()) } if err != nil { return emptyValue, err @@ -1158,11 +1155,11 @@ func (dvd DefaultValueDecoders) decimal128DecodeType(_ DecodeContext, vr bsonrw. return reflect.ValueOf(d128), nil } -// Decimal128DecodeValue is the ValueDecoderFunc for primitive.Decimal128. +// Decimal128DecodeValue is the ValueDecoderFunc for Decimal128. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) Decimal128DecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) Decimal128DecodeValue(dctx DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tDecimal { return ValueDecoderError{Name: "Decimal128DecodeValue", Types: []reflect.Type{tDecimal}, Received: val} } @@ -1176,7 +1173,7 @@ func (dvd DefaultValueDecoders) Decimal128DecodeValue(dctx DecodeContext, vr bso return nil } -func (dvd DefaultValueDecoders) jsonNumberDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (dvd DefaultValueDecoders) jsonNumberDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tJSONNumber { return emptyValue, ValueDecoderError{ Name: "JSONNumberDecodeValue", @@ -1188,27 +1185,27 @@ func (dvd DefaultValueDecoders) jsonNumberDecodeType(_ DecodeContext, vr bsonrw. var jsonNum json.Number var err error switch vrType := vr.Type(); vrType { - case bsontype.Double: + case TypeDouble: f64, err := vr.ReadDouble() if err != nil { return emptyValue, err } jsonNum = json.Number(strconv.FormatFloat(f64, 'f', -1, 64)) - case bsontype.Int32: + case TypeInt32: i32, err := vr.ReadInt32() if err != nil { return emptyValue, err } jsonNum = json.Number(strconv.FormatInt(int64(i32), 10)) - case bsontype.Int64: + case TypeInt64: i64, err := vr.ReadInt64() if err != nil { return emptyValue, err } jsonNum = json.Number(strconv.FormatInt(i64, 10)) - case bsontype.Null: + case TypeNull: err = vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() default: return emptyValue, fmt.Errorf("cannot decode %v into a json.Number", vrType) @@ -1224,7 +1221,7 @@ func (dvd DefaultValueDecoders) jsonNumberDecodeType(_ DecodeContext, vr bsonrw. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) JSONNumberDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) JSONNumberDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tJSONNumber { return ValueDecoderError{Name: "JSONNumberDecodeValue", Types: []reflect.Type{tJSONNumber}, Received: val} } @@ -1238,7 +1235,7 @@ func (dvd DefaultValueDecoders) JSONNumberDecodeValue(dc DecodeContext, vr bsonr return nil } -func (dvd DefaultValueDecoders) urlDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (dvd DefaultValueDecoders) urlDecodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tURL { return emptyValue, ValueDecoderError{ Name: "URLDecodeValue", @@ -1250,7 +1247,7 @@ func (dvd DefaultValueDecoders) urlDecodeType(_ DecodeContext, vr bsonrw.ValueRe urlPtr := &url.URL{} var err error switch vrType := vr.Type(); vrType { - case bsontype.String: + case TypeString: var str string // Declare str here to avoid shadowing err during the ReadString call. str, err = vr.ReadString() if err != nil { @@ -1258,9 +1255,9 @@ func (dvd DefaultValueDecoders) urlDecodeType(_ DecodeContext, vr bsonrw.ValueRe } urlPtr, err = url.Parse(str) - case bsontype.Null: + case TypeNull: err = vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() default: return emptyValue, fmt.Errorf("cannot decode %v into a *url.URL", vrType) @@ -1276,7 +1273,7 @@ func (dvd DefaultValueDecoders) urlDecodeType(_ DecodeContext, vr bsonrw.ValueRe // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) URLDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) URLDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tURL { return ValueDecoderError{Name: "URLDecodeValue", Types: []reflect.Type{tURL}, Received: val} } @@ -1293,8 +1290,8 @@ func (dvd DefaultValueDecoders) URLDecodeValue(dc DecodeContext, vr bsonrw.Value // TimeDecodeValue is the ValueDecoderFunc for time.Time. // // Deprecated: TimeDecodeValue is not registered by default. Use TimeCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) TimeDecodeValue(_ DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { - if vr.Type() != bsontype.DateTime { +func (dvd DefaultValueDecoders) TimeDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { + if vr.Type() != TypeDateTime { return fmt.Errorf("cannot decode %v into a time.Time", vr.Type()) } @@ -1314,8 +1311,8 @@ func (dvd DefaultValueDecoders) TimeDecodeValue(_ DecodeContext, vr bsonrw.Value // ByteSliceDecodeValue is the ValueDecoderFunc for []byte. // // Deprecated: ByteSliceDecodeValue is not registered by default. Use ByteSliceCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) ByteSliceDecodeValue(_ DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { - if vr.Type() != bsontype.Binary && vr.Type() != bsontype.Null { +func (dvd DefaultValueDecoders) ByteSliceDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { + if vr.Type() != TypeBinary && vr.Type() != TypeNull { return fmt.Errorf("cannot decode %v into a []byte", vr.Type()) } @@ -1323,7 +1320,7 @@ func (dvd DefaultValueDecoders) ByteSliceDecodeValue(_ DecodeContext, vr bsonrw. return ValueDecoderError{Name: "ByteSliceDecodeValue", Types: []reflect.Type{tByteSlice}, Received: val} } - if vr.Type() == bsontype.Null { + if vr.Type() == TypeNull { val.Set(reflect.Zero(val.Type())) return vr.ReadNull() } @@ -1333,7 +1330,7 @@ func (dvd DefaultValueDecoders) ByteSliceDecodeValue(_ DecodeContext, vr bsonrw. return err } if subtype != 0x00 { - return fmt.Errorf("ByteSliceDecodeValue can only be used to decode subtype 0x00 for %s, got %v", bsontype.Binary, subtype) + return fmt.Errorf("ByteSliceDecodeValue can only be used to decode subtype 0x00 for %s, got %v", TypeBinary, subtype) } val.Set(reflect.ValueOf(data)) @@ -1343,14 +1340,14 @@ func (dvd DefaultValueDecoders) ByteSliceDecodeValue(_ DecodeContext, vr bsonrw. // MapDecodeValue is the ValueDecoderFunc for map[string]* types. // // Deprecated: MapDecodeValue is not registered by default. Use MapCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) MapDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) MapDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Kind() != reflect.Map || val.Type().Key().Kind() != reflect.String { return ValueDecoderError{Name: "MapDecodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val} } switch vr.Type() { - case bsontype.Type(0), bsontype.EmbeddedDocument: - case bsontype.Null: + case Type(0), TypeEmbeddedDocument: + case TypeNull: val.Set(reflect.Zero(val.Type())) return vr.ReadNull() default: @@ -1379,7 +1376,7 @@ func (dvd DefaultValueDecoders) MapDecodeValue(dc DecodeContext, vr bsonrw.Value keyType := val.Type().Key() for { key, vr, err := dr.ReadElement() - if errors.Is(err, bsonrw.ErrEOD) { + if errors.Is(err, ErrEOD) { break } if err != nil { @@ -1402,18 +1399,18 @@ func (dvd DefaultValueDecoders) MapDecodeValue(dc DecodeContext, vr bsonrw.Value // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) ArrayDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) ArrayDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.IsValid() || val.Kind() != reflect.Array { return ValueDecoderError{Name: "ArrayDecodeValue", Kinds: []reflect.Kind{reflect.Array}, Received: val} } switch vrType := vr.Type(); vrType { - case bsontype.Array: - case bsontype.Type(0), bsontype.EmbeddedDocument: + case TypeArray: + case Type(0), TypeEmbeddedDocument: if val.Type().Elem() != tE { return fmt.Errorf("cannot decode document into %s", val.Type()) } - case bsontype.Binary: + case TypeBinary: if val.Type().Elem() != tByte { return fmt.Errorf("ArrayDecodeValue can only be used to decode binary into a byte array, got %v", vrType) } @@ -1421,8 +1418,8 @@ func (dvd DefaultValueDecoders) ArrayDecodeValue(dc DecodeContext, vr bsonrw.Val if err != nil { return err } - if subtype != bsontype.BinaryGeneric && subtype != bsontype.BinaryBinaryOld { - return fmt.Errorf("ArrayDecodeValue can only be used to decode subtype 0x00 or 0x02 for %s, got %v", bsontype.Binary, subtype) + if subtype != TypeBinaryGeneric && subtype != TypeBinaryBinaryOld { + return fmt.Errorf("ArrayDecodeValue can only be used to decode subtype 0x00 or 0x02 for %s, got %v", TypeBinary, subtype) } if len(data) > val.Len() { @@ -1433,17 +1430,17 @@ func (dvd DefaultValueDecoders) ArrayDecodeValue(dc DecodeContext, vr bsonrw.Val val.Index(idx).Set(reflect.ValueOf(elem)) } return nil - case bsontype.Null: + case TypeNull: val.Set(reflect.Zero(val.Type())) return vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: val.Set(reflect.Zero(val.Type())) return vr.ReadUndefined() default: return fmt.Errorf("cannot decode %v into an array", vrType) } - var elemsFunc func(DecodeContext, bsonrw.ValueReader, reflect.Value) ([]reflect.Value, error) + var elemsFunc func(DecodeContext, ValueReader, reflect.Value) ([]reflect.Value, error) switch val.Type().Elem() { case tE: elemsFunc = dvd.decodeD @@ -1470,17 +1467,17 @@ func (dvd DefaultValueDecoders) ArrayDecodeValue(dc DecodeContext, vr bsonrw.Val // SliceDecodeValue is the ValueDecoderFunc for slice types. // // Deprecated: SliceDecodeValue is not registered by default. Use SliceCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) SliceDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) SliceDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Kind() != reflect.Slice { return ValueDecoderError{Name: "SliceDecodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val} } switch vr.Type() { - case bsontype.Array: - case bsontype.Null: + case TypeArray: + case TypeNull: val.Set(reflect.Zero(val.Type())) return vr.ReadNull() - case bsontype.Type(0), bsontype.EmbeddedDocument: + case Type(0), TypeEmbeddedDocument: if val.Type().Elem() != tE { return fmt.Errorf("cannot decode document into %s", val.Type()) } @@ -1488,7 +1485,7 @@ func (dvd DefaultValueDecoders) SliceDecodeValue(dc DecodeContext, vr bsonrw.Val return fmt.Errorf("cannot decode %v into a slice", vr.Type()) } - var elemsFunc func(DecodeContext, bsonrw.ValueReader, reflect.Value) ([]reflect.Value, error) + var elemsFunc func(DecodeContext, ValueReader, reflect.Value) ([]reflect.Value, error) switch val.Type().Elem() { case tE: dc.Ancestor = val.Type() @@ -1516,7 +1513,7 @@ func (dvd DefaultValueDecoders) SliceDecodeValue(dc DecodeContext, vr bsonrw.Val // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) ValueUnmarshalerDecodeValue(_ DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) ValueUnmarshalerDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { if !val.IsValid() || (!val.Type().Implements(tValueUnmarshaler) && !reflect.PtrTo(val.Type()).Implements(tValueUnmarshaler)) { return ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val} } @@ -1535,7 +1532,7 @@ func (dvd DefaultValueDecoders) ValueUnmarshalerDecodeValue(_ DecodeContext, vr val = val.Addr() // If the type doesn't implement the interface, a pointer to it must. } - t, src, err := bsonrw.Copier{}.CopyValueToBytes(vr) + t, src, err := CopyValueToBytes(vr) if err != nil { return err } @@ -1552,7 +1549,7 @@ func (dvd DefaultValueDecoders) ValueUnmarshalerDecodeValue(_ DecodeContext, vr // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) UnmarshalerDecodeValue(_ DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) UnmarshalerDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { if !val.IsValid() || (!val.Type().Implements(tUnmarshaler) && !reflect.PtrTo(val.Type()).Implements(tUnmarshaler)) { return ValueDecoderError{Name: "UnmarshalerDecodeValue", Types: []reflect.Type{tUnmarshaler}, Received: val} } @@ -1564,7 +1561,7 @@ func (dvd DefaultValueDecoders) UnmarshalerDecodeValue(_ DecodeContext, vr bsonr val.Set(reflect.New(val.Type().Elem())) } - _, src, err := bsonrw.Copier{}.CopyValueToBytes(vr) + _, src, err := CopyValueToBytes(vr) if err != nil { return err } @@ -1599,7 +1596,7 @@ func (dvd DefaultValueDecoders) UnmarshalerDecodeValue(_ DecodeContext, vr bsonr // EmptyInterfaceDecodeValue is the ValueDecoderFunc for interface{}. // // Deprecated: EmptyInterfaceDecodeValue is not registered by default. Use EmptyInterfaceCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) EmptyInterfaceDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) EmptyInterfaceDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tEmpty { return ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: val} } @@ -1607,13 +1604,13 @@ func (dvd DefaultValueDecoders) EmptyInterfaceDecodeValue(dc DecodeContext, vr b rtype, err := dc.LookupTypeMapEntry(vr.Type()) if err != nil { switch vr.Type() { - case bsontype.EmbeddedDocument: + case TypeEmbeddedDocument: if dc.Ancestor != nil { rtype = dc.Ancestor break } rtype = tD - case bsontype.Null: + case TypeNull: val.Set(reflect.Zero(val.Type())) return vr.ReadNull() default: @@ -1640,7 +1637,7 @@ func (dvd DefaultValueDecoders) EmptyInterfaceDecodeValue(dc DecodeContext, vr b // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (DefaultValueDecoders) CoreDocumentDecodeValue(_ DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (DefaultValueDecoders) CoreDocumentDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tCoreDocument { return ValueDecoderError{Name: "CoreDocumentDecodeValue", Types: []reflect.Type{tCoreDocument}, Received: val} } @@ -1651,12 +1648,12 @@ func (DefaultValueDecoders) CoreDocumentDecodeValue(_ DecodeContext, vr bsonrw.V val.SetLen(0) - cdoc, err := bsonrw.Copier{}.AppendDocumentBytes(val.Interface().(bsoncore.Document), vr) + cdoc, err := appendDocumentBytes(val.Interface().(bsoncore.Document), vr) val.Set(reflect.ValueOf(cdoc)) return err } -func (dvd DefaultValueDecoders) decodeDefault(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) ([]reflect.Value, error) { +func (dvd DefaultValueDecoders) decodeDefault(dc DecodeContext, vr ValueReader, val reflect.Value) ([]reflect.Value, error) { elems := make([]reflect.Value, 0) ar, err := vr.ReadArray() @@ -1675,7 +1672,7 @@ func (dvd DefaultValueDecoders) decodeDefault(dc DecodeContext, vr bsonrw.ValueR idx := 0 for { vr, err := ar.ReadValue() - if errors.Is(err, bsonrw.ErrEOA) { + if errors.Is(err, ErrEOA) { break } if err != nil { @@ -1693,8 +1690,8 @@ func (dvd DefaultValueDecoders) decodeDefault(dc DecodeContext, vr bsonrw.ValueR return elems, nil } -func (dvd DefaultValueDecoders) readCodeWithScope(dc DecodeContext, vr bsonrw.ValueReader) (primitive.CodeWithScope, error) { - var cws primitive.CodeWithScope +func (dvd DefaultValueDecoders) readCodeWithScope(dc DecodeContext, vr ValueReader) (CodeWithScope, error) { + var cws CodeWithScope code, dr, err := vr.ReadCodeWithScope() if err != nil { @@ -1710,14 +1707,14 @@ func (dvd DefaultValueDecoders) readCodeWithScope(dc DecodeContext, vr bsonrw.Va scope.Set(reflect.MakeSlice(tD, 0, len(elems))) scope.Set(reflect.Append(scope, elems...)) - cws = primitive.CodeWithScope{ - Code: primitive.JavaScript(code), - Scope: scope.Interface().(primitive.D), + cws = CodeWithScope{ + Code: JavaScript(code), + Scope: scope.Interface().(D), } return cws, nil } -func (dvd DefaultValueDecoders) codeWithScopeDecodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (dvd DefaultValueDecoders) codeWithScopeDecodeType(dc DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tCodeWithScope { return emptyValue, ValueDecoderError{ Name: "CodeWithScopeDecodeValue", @@ -1726,17 +1723,17 @@ func (dvd DefaultValueDecoders) codeWithScopeDecodeType(dc DecodeContext, vr bso } } - var cws primitive.CodeWithScope + var cws CodeWithScope var err error switch vrType := vr.Type(); vrType { - case bsontype.CodeWithScope: + case TypeCodeWithScope: cws, err = dvd.readCodeWithScope(dc, vr) - case bsontype.Null: + case TypeNull: err = vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: err = vr.ReadUndefined() default: - return emptyValue, fmt.Errorf("cannot decode %v into a primitive.CodeWithScope", vrType) + return emptyValue, fmt.Errorf("cannot decode %v into a CodeWithScope", vrType) } if err != nil { return emptyValue, err @@ -1749,7 +1746,7 @@ func (dvd DefaultValueDecoders) codeWithScopeDecodeType(dc DecodeContext, vr bso // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value decoders registered. -func (dvd DefaultValueDecoders) CodeWithScopeDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (dvd DefaultValueDecoders) CodeWithScopeDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tCodeWithScope { return ValueDecoderError{Name: "CodeWithScopeDecodeValue", Types: []reflect.Type{tCodeWithScope}, Received: val} } @@ -1763,9 +1760,9 @@ func (dvd DefaultValueDecoders) CodeWithScopeDecodeValue(dc DecodeContext, vr bs return nil } -func (dvd DefaultValueDecoders) decodeD(dc DecodeContext, vr bsonrw.ValueReader, _ reflect.Value) ([]reflect.Value, error) { +func (dvd DefaultValueDecoders) decodeD(dc DecodeContext, vr ValueReader, _ reflect.Value) ([]reflect.Value, error) { switch vr.Type() { - case bsontype.Type(0), bsontype.EmbeddedDocument: + case Type(0), TypeEmbeddedDocument: default: return nil, fmt.Errorf("cannot decode %v into a D", vr.Type()) } @@ -1778,7 +1775,7 @@ func (dvd DefaultValueDecoders) decodeD(dc DecodeContext, vr bsonrw.ValueReader, return dvd.decodeElemsFromDocumentReader(dc, dr) } -func (DefaultValueDecoders) decodeElemsFromDocumentReader(dc DecodeContext, dr bsonrw.DocumentReader) ([]reflect.Value, error) { +func (DefaultValueDecoders) decodeElemsFromDocumentReader(dc DecodeContext, dr DocumentReader) ([]reflect.Value, error) { decoder, err := dc.LookupDecoder(tEmpty) if err != nil { return nil, err @@ -1787,7 +1784,7 @@ func (DefaultValueDecoders) decodeElemsFromDocumentReader(dc DecodeContext, dr b elems := make([]reflect.Value, 0) for { key, vr, err := dr.ReadElement() - if errors.Is(err, bsonrw.ErrEOD) { + if errors.Is(err, ErrEOD) { break } if err != nil { @@ -1800,7 +1797,7 @@ func (DefaultValueDecoders) decodeElemsFromDocumentReader(dc DecodeContext, dr b return nil, newDecodeError(key, err) } - elems = append(elems, reflect.ValueOf(primitive.E{Key: key, Value: val.Interface()})) + elems = append(elems, reflect.ValueOf(E{Key: key, Value: val.Interface()})) } return elems, nil diff --git a/bson/bsoncodec/default_value_decoders_test.go b/bson/default_value_decoders_test.go similarity index 63% rename from bson/bsoncodec/default_value_decoders_test.go rename to bson/default_value_decoders_test.go index c73a6fc292..699a958605 100644 --- a/bson/bsoncodec/default_value_decoders_test.go +++ b/bson/default_value_decoders_test.go @@ -4,10 +4,9 @@ // 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 +package bson import ( - "bytes" "encoding/json" "errors" "fmt" @@ -19,10 +18,6 @@ import ( "time" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsonrw/bsonrwtest" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -55,7 +50,7 @@ func TestDefaultValueDecoders(t *testing.T) { const cansettest = "cansettest" now := time.Now().Truncate(time.Millisecond) - d128 := primitive.NewDecimal128(12345, 67890) + d128 := NewDecimal128(12345, 67890) var pbool = func(b bool) *bool { return &b } var pi32 = func(i32 int32) *int32 { return &i32 } var pi64 = func(i64 int64) *int64 { return &i64 } @@ -64,8 +59,8 @@ func TestDefaultValueDecoders(t *testing.T) { name string val interface{} dctx *DecodeContext - llvrw *bsonrwtest.ValueReaderWriter - invoke bsonrwtest.Invoked + llvrw *valueReaderWriter + invoke invoked err error } @@ -82,63 +77,63 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Boolean}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeBoolean}, + nothing, ValueDecoderError{Name: "BooleanDecodeValue", Kinds: []reflect.Kind{reflect.Bool}, Received: reflect.ValueOf(wrong)}, }, { "type not boolean", bool(false), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a boolean", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into a boolean", TypeString), }, { "fast path", bool(true), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Boolean, Return: bool(true)}, - bsonrwtest.ReadBoolean, + &valueReaderWriter{BSONType: TypeBoolean, Return: bool(true)}, + readBoolean, nil, }, { "reflection path", mybool(true), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Boolean, Return: bool(true)}, - bsonrwtest.ReadBoolean, + &valueReaderWriter{BSONType: TypeBoolean, Return: bool(true)}, + readBoolean, nil, }, { "reflection path error", mybool(true), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Boolean, Return: bool(true), Err: errors.New("ReadBoolean Error"), ErrAfter: bsonrwtest.ReadBoolean}, - bsonrwtest.ReadBoolean, errors.New("ReadBoolean Error"), + &valueReaderWriter{BSONType: TypeBoolean, Return: bool(true), Err: errors.New("ReadBoolean Error"), ErrAfter: readBoolean}, + readBoolean, errors.New("ReadBoolean Error"), }, { "can set false", cansettest, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Boolean}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeBoolean}, + nothing, ValueDecoderError{Name: "BooleanDecodeValue", Kinds: []reflect.Kind{reflect.Bool}}, }, { "decode null", mybool(false), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", mybool(false), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -151,8 +146,8 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0)}, - bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0)}, + readInt32, ValueDecoderError{ Name: "IntDecodeValue", Kinds: []reflect.Kind{reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int}, @@ -163,62 +158,62 @@ func TestDefaultValueDecoders(t *testing.T) { "type not int32/int64", 0, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into an integer type", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into an integer type", TypeString), }, { "ReadInt32 error", 0, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0), Err: errors.New("ReadInt32 error"), ErrAfter: bsonrwtest.ReadInt32}, - bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0), Err: errors.New("ReadInt32 error"), ErrAfter: readInt32}, + readInt32, errors.New("ReadInt32 error"), }, { "ReadInt64 error", 0, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(0), Err: errors.New("ReadInt64 error"), ErrAfter: bsonrwtest.ReadInt64}, - bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(0), Err: errors.New("ReadInt64 error"), ErrAfter: readInt64}, + readInt64, errors.New("ReadInt64 error"), }, { "ReadDouble error", 0, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(0), Err: errors.New("ReadDouble error"), ErrAfter: bsonrwtest.ReadDouble}, - bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(0), Err: errors.New("ReadDouble error"), ErrAfter: readDouble}, + readDouble, errors.New("ReadDouble error"), }, { "ReadDouble", int64(3), &DecodeContext{}, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.00)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.00)}, readDouble, nil, }, { "ReadDouble (truncate)", int64(3), &DecodeContext{Truncate: true}, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.14)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.14)}, readDouble, nil, }, { "ReadDouble (no truncate)", int64(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.14)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.14)}, readDouble, errCannotTruncate, }, { "ReadDouble overflows int64", int64(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: math.MaxFloat64}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: math.MaxFloat64}, readDouble, fmt.Errorf("%g overflows int64", math.MaxFloat64), }, - {"int8/fast path", int8(127), nil, &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(127)}, bsonrwtest.ReadInt32, nil}, - {"int16/fast path", int16(32676), nil, &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(32676)}, bsonrwtest.ReadInt32, nil}, - {"int32/fast path", int32(1234), nil, &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(1234)}, bsonrwtest.ReadInt32, nil}, - {"int64/fast path", int64(1234), nil, &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(1234)}, bsonrwtest.ReadInt64, nil}, - {"int/fast path", int(1234), nil, &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(1234)}, bsonrwtest.ReadInt64, nil}, + {"int8/fast path", int8(127), nil, &valueReaderWriter{BSONType: TypeInt32, Return: int32(127)}, readInt32, nil}, + {"int16/fast path", int16(32676), nil, &valueReaderWriter{BSONType: TypeInt32, Return: int32(32676)}, readInt32, nil}, + {"int32/fast path", int32(1234), nil, &valueReaderWriter{BSONType: TypeInt32, Return: int32(1234)}, readInt32, nil}, + {"int64/fast path", int64(1234), nil, &valueReaderWriter{BSONType: TypeInt64, Return: int64(1234)}, readInt64, nil}, + {"int/fast path", int(1234), nil, &valueReaderWriter{BSONType: TypeInt64, Return: int64(1234)}, readInt64, nil}, { "int8/fast path - nil", (*int8)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0)}, readInt32, ValueDecoderError{ Name: "IntDecodeValue", Kinds: []reflect.Kind{reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int}, @@ -227,7 +222,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "int16/fast path - nil", (*int16)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0)}, readInt32, ValueDecoderError{ Name: "IntDecodeValue", Kinds: []reflect.Kind{reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int}, @@ -236,7 +231,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "int32/fast path - nil", (*int32)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0)}, readInt32, ValueDecoderError{ Name: "IntDecodeValue", Kinds: []reflect.Kind{reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int}, @@ -245,7 +240,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "int64/fast path - nil", (*int64)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0)}, readInt32, ValueDecoderError{ Name: "IntDecodeValue", Kinds: []reflect.Kind{reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int}, @@ -254,7 +249,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "int/fast path - nil", (*int)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0)}, readInt32, ValueDecoderError{ Name: "IntDecodeValue", Kinds: []reflect.Kind{reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int}, @@ -263,95 +258,95 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "int8/fast path - overflow", int8(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(129)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(129)}, readInt32, fmt.Errorf("%d overflows int8", 129), }, { "int16/fast path - overflow", int16(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(32768)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(32768)}, readInt32, fmt.Errorf("%d overflows int16", 32768), }, { "int32/fast path - overflow", int32(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(2147483648)}, bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(2147483648)}, readInt64, fmt.Errorf("%d overflows int32", int64(2147483648)), }, { "int8/fast path - overflow (negative)", int8(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(-129)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(-129)}, readInt32, fmt.Errorf("%d overflows int8", -129), }, { "int16/fast path - overflow (negative)", int16(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(-32769)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(-32769)}, readInt32, fmt.Errorf("%d overflows int16", -32769), }, { "int32/fast path - overflow (negative)", int32(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(-2147483649)}, bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(-2147483649)}, readInt64, fmt.Errorf("%d overflows int32", int64(-2147483649)), }, { "int8/reflection path", myint8(127), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(127)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(127)}, readInt32, nil, }, { "int16/reflection path", myint16(255), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(255)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(255)}, readInt32, nil, }, { "int32/reflection path", myint32(511), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(511)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(511)}, readInt32, nil, }, { "int64/reflection path", myint64(1023), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(1023)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(1023)}, readInt32, nil, }, { "int/reflection path", myint(2047), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(2047)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(2047)}, readInt32, nil, }, { "int8/reflection path - overflow", myint8(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(129)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(129)}, readInt32, fmt.Errorf("%d overflows int8", 129), }, { "int16/reflection path - overflow", myint16(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(32768)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(32768)}, readInt32, fmt.Errorf("%d overflows int16", 32768), }, { "int32/reflection path - overflow", myint32(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(2147483648)}, bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(2147483648)}, readInt64, fmt.Errorf("%d overflows int32", int64(2147483648)), }, { "int8/reflection path - overflow (negative)", myint8(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(-129)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(-129)}, readInt32, fmt.Errorf("%d overflows int8", -129), }, { "int16/reflection path - overflow (negative)", myint16(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(-32769)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(-32769)}, readInt32, fmt.Errorf("%d overflows int16", -32769), }, { "int32/reflection path - overflow (negative)", myint32(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(-2147483649)}, bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(-2147483649)}, readInt64, fmt.Errorf("%d overflows int32", int64(-2147483649)), }, { "can set false", cansettest, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0)}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0)}, + nothing, ValueDecoderError{ Name: "IntDecodeValue", Kinds: []reflect.Kind{reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int}, @@ -361,16 +356,16 @@ func TestDefaultValueDecoders(t *testing.T) { "decode null", myint(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", myint(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -383,8 +378,8 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0)}, - bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0)}, + readInt32, ValueDecoderError{ Name: "UintDecodeValue", Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint}, @@ -395,62 +390,62 @@ func TestDefaultValueDecoders(t *testing.T) { "type not int32/int64", 0, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into an integer type", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into an integer type", TypeString), }, { "ReadInt32 error", uint(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0), Err: errors.New("ReadInt32 error"), ErrAfter: bsonrwtest.ReadInt32}, - bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0), Err: errors.New("ReadInt32 error"), ErrAfter: readInt32}, + readInt32, errors.New("ReadInt32 error"), }, { "ReadInt64 error", uint(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(0), Err: errors.New("ReadInt64 error"), ErrAfter: bsonrwtest.ReadInt64}, - bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(0), Err: errors.New("ReadInt64 error"), ErrAfter: readInt64}, + readInt64, errors.New("ReadInt64 error"), }, { "ReadDouble error", 0, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(0), Err: errors.New("ReadDouble error"), ErrAfter: bsonrwtest.ReadDouble}, - bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(0), Err: errors.New("ReadDouble error"), ErrAfter: readDouble}, + readDouble, errors.New("ReadDouble error"), }, { "ReadDouble", uint64(3), &DecodeContext{}, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.00)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.00)}, readDouble, nil, }, { "ReadDouble (truncate)", uint64(3), &DecodeContext{Truncate: true}, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.14)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.14)}, readDouble, nil, }, { "ReadDouble (no truncate)", uint64(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.14)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.14)}, readDouble, errCannotTruncate, }, { "ReadDouble overflows int64", uint64(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: math.MaxFloat64}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: math.MaxFloat64}, readDouble, fmt.Errorf("%g overflows int64", math.MaxFloat64), }, - {"uint8/fast path", uint8(127), nil, &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(127)}, bsonrwtest.ReadInt32, nil}, - {"uint16/fast path", uint16(255), nil, &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(255)}, bsonrwtest.ReadInt32, nil}, - {"uint32/fast path", uint32(1234), nil, &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(1234)}, bsonrwtest.ReadInt32, nil}, - {"uint64/fast path", uint64(1234), nil, &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(1234)}, bsonrwtest.ReadInt64, nil}, - {"uint/fast path", uint(1234), nil, &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(1234)}, bsonrwtest.ReadInt64, nil}, + {"uint8/fast path", uint8(127), nil, &valueReaderWriter{BSONType: TypeInt32, Return: int32(127)}, readInt32, nil}, + {"uint16/fast path", uint16(255), nil, &valueReaderWriter{BSONType: TypeInt32, Return: int32(255)}, readInt32, nil}, + {"uint32/fast path", uint32(1234), nil, &valueReaderWriter{BSONType: TypeInt32, Return: int32(1234)}, readInt32, nil}, + {"uint64/fast path", uint64(1234), nil, &valueReaderWriter{BSONType: TypeInt64, Return: int64(1234)}, readInt64, nil}, + {"uint/fast path", uint(1234), nil, &valueReaderWriter{BSONType: TypeInt64, Return: int64(1234)}, readInt64, nil}, { "uint8/fast path - nil", (*uint8)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0)}, readInt32, ValueDecoderError{ Name: "UintDecodeValue", Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint}, @@ -459,7 +454,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "uint16/fast path - nil", (*uint16)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0)}, readInt32, ValueDecoderError{ Name: "UintDecodeValue", Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint}, @@ -468,7 +463,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "uint32/fast path - nil", (*uint32)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0)}, readInt32, ValueDecoderError{ Name: "UintDecodeValue", Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint}, @@ -477,7 +472,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "uint64/fast path - nil", (*uint64)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0)}, readInt32, ValueDecoderError{ Name: "UintDecodeValue", Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint}, @@ -486,7 +481,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "uint/fast path - nil", (*uint)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0)}, readInt32, ValueDecoderError{ Name: "UintDecodeValue", Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint}, @@ -495,115 +490,115 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "uint8/fast path - overflow", uint8(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(1 << 8)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(1 << 8)}, readInt32, fmt.Errorf("%d overflows uint8", 1<<8), }, { "uint16/fast path - overflow", uint16(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(1 << 16)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(1 << 16)}, readInt32, fmt.Errorf("%d overflows uint16", 1<<16), }, { "uint32/fast path - overflow", uint32(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(1 << 32)}, bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(1 << 32)}, readInt64, fmt.Errorf("%d overflows uint32", int64(1<<32)), }, { "uint8/fast path - overflow (negative)", uint8(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(-1)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(-1)}, readInt32, fmt.Errorf("%d overflows uint8", -1), }, { "uint16/fast path - overflow (negative)", uint16(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(-1)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(-1)}, readInt32, fmt.Errorf("%d overflows uint16", -1), }, { "uint32/fast path - overflow (negative)", uint32(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(-1)}, bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(-1)}, readInt64, fmt.Errorf("%d overflows uint32", -1), }, { "uint64/fast path - overflow (negative)", uint64(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(-1)}, bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(-1)}, readInt64, fmt.Errorf("%d overflows uint64", -1), }, { "uint/fast path - overflow (negative)", uint(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(-1)}, bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(-1)}, readInt64, fmt.Errorf("%d overflows uint", -1), }, { "uint8/reflection path", myuint8(127), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(127)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(127)}, readInt32, nil, }, { "uint16/reflection path", myuint16(255), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(255)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(255)}, readInt32, nil, }, { "uint32/reflection path", myuint32(511), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(511)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(511)}, readInt32, nil, }, { "uint64/reflection path", myuint64(1023), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(1023)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(1023)}, readInt32, nil, }, { "uint/reflection path", myuint(2047), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(2047)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(2047)}, readInt32, nil, }, { "uint8/reflection path - overflow", myuint8(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(1 << 8)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(1 << 8)}, readInt32, fmt.Errorf("%d overflows uint8", 1<<8), }, { "uint16/reflection path - overflow", myuint16(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(1 << 16)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(1 << 16)}, readInt32, fmt.Errorf("%d overflows uint16", 1<<16), }, { "uint32/reflection path - overflow", myuint32(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(1 << 32)}, bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(1 << 32)}, readInt64, fmt.Errorf("%d overflows uint32", int64(1<<32)), }, { "uint8/reflection path - overflow (negative)", myuint8(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(-1)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(-1)}, readInt32, fmt.Errorf("%d overflows uint8", -1), }, { "uint16/reflection path - overflow (negative)", myuint16(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(-1)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(-1)}, readInt32, fmt.Errorf("%d overflows uint16", -1), }, { "uint32/reflection path - overflow (negative)", myuint32(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(-1)}, bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(-1)}, readInt64, fmt.Errorf("%d overflows uint32", -1), }, { "uint64/reflection path - overflow (negative)", myuint64(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(-1)}, bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(-1)}, readInt64, fmt.Errorf("%d overflows uint64", -1), }, { "uint/reflection path - overflow (negative)", myuint(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(-1)}, bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(-1)}, readInt64, fmt.Errorf("%d overflows uint", -1), }, { "can set false", cansettest, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0)}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0)}, + nothing, ValueDecoderError{ Name: "UintDecodeValue", Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint}, @@ -619,8 +614,8 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(0)}, - bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(0)}, + readDouble, ValueDecoderError{ Name: "FloatDecodeValue", Kinds: []reflect.Kind{reflect.Float32, reflect.Float64}, @@ -631,67 +626,67 @@ func TestDefaultValueDecoders(t *testing.T) { "type not double", 0, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a float32 or float64 type", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into a float32 or float64 type", TypeString), }, { "ReadDouble error", float64(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(0), Err: errors.New("ReadDouble error"), ErrAfter: bsonrwtest.ReadDouble}, - bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(0), Err: errors.New("ReadDouble error"), ErrAfter: readDouble}, + readDouble, errors.New("ReadDouble error"), }, { "ReadInt32 error", float64(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(0), Err: errors.New("ReadInt32 error"), ErrAfter: bsonrwtest.ReadInt32}, - bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(0), Err: errors.New("ReadInt32 error"), ErrAfter: readInt32}, + readInt32, errors.New("ReadInt32 error"), }, { "ReadInt64 error", float64(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(0), Err: errors.New("ReadInt64 error"), ErrAfter: bsonrwtest.ReadInt64}, - bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(0), Err: errors.New("ReadInt64 error"), ErrAfter: readInt64}, + readInt64, errors.New("ReadInt64 error"), }, { "float64/int32", float32(32.0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(32)}, bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(32)}, readInt32, nil, }, { "float64/int64", float32(64.0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(64)}, bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(64)}, readInt64, nil, }, { "float32/fast path (equal)", float32(3.0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.0)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.0)}, readDouble, nil, }, { "float64/fast path", float64(3.14159), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.14159)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.14159)}, readDouble, nil, }, { "float32/fast path (truncate)", float32(3.14), &DecodeContext{Truncate: true}, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.14)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.14)}, readDouble, nil, }, { "float32/fast path (no truncate)", float32(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.14)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.14)}, readDouble, errCannotTruncate, }, { "float32/fast path - nil", (*float32)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(0)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(0)}, readDouble, ValueDecoderError{ Name: "FloatDecodeValue", Kinds: []reflect.Kind{reflect.Float32, reflect.Float64}, @@ -700,7 +695,7 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "float64/fast path - nil", (*float64)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(0)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(0)}, readDouble, ValueDecoderError{ Name: "FloatDecodeValue", Kinds: []reflect.Kind{reflect.Float32, reflect.Float64}, @@ -709,30 +704,30 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "float32/reflection path (equal)", myfloat32(3.0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.0)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.0)}, readDouble, nil, }, { "float64/reflection path", myfloat64(3.14159), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.14159)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.14159)}, readDouble, nil, }, { "float32/reflection path (truncate)", myfloat32(3.14), &DecodeContext{Truncate: true}, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.14)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.14)}, readDouble, nil, }, { "float32/reflection path (no truncate)", myfloat32(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.14)}, bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.14)}, readDouble, errCannotTruncate, }, { "can set false", cansettest, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(0)}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(0)}, + nothing, ValueDecoderError{ Name: "FloatDecodeValue", Kinds: []reflect.Kind{reflect.Float32, reflect.Float64}, @@ -748,48 +743,48 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.DateTime, Return: int64(0)}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeDateTime, Return: int64(0)}, + nothing, ValueDecoderError{Name: "TimeDecodeValue", Types: []reflect.Type{tTime}, Received: reflect.ValueOf(wrong)}, }, { "ReadDateTime error", time.Time{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.DateTime, Return: int64(0), Err: errors.New("ReadDateTime error"), ErrAfter: bsonrwtest.ReadDateTime}, - bsonrwtest.ReadDateTime, + &valueReaderWriter{BSONType: TypeDateTime, Return: int64(0), Err: errors.New("ReadDateTime error"), ErrAfter: readDateTime}, + readDateTime, errors.New("ReadDateTime error"), }, { "time.Time", now, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.DateTime, Return: now.UnixNano() / int64(time.Millisecond)}, - bsonrwtest.ReadDateTime, + &valueReaderWriter{BSONType: TypeDateTime, Return: now.UnixNano() / int64(time.Millisecond)}, + readDateTime, nil, }, { "can set false", cansettest, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.DateTime, Return: int64(0)}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeDateTime, Return: int64(0)}, + nothing, ValueDecoderError{Name: "TimeDecodeValue", Types: []reflect.Type{tTime}}, }, { "decode null", time.Time{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", time.Time{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -802,72 +797,72 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong kind", wrong, nil, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.Nothing, + &valueReaderWriter{}, + nothing, ValueDecoderError{Name: "MapDecodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: reflect.ValueOf(wrong)}, }, { "wrong kind (non-string key)", map[bool]interface{}{}, &DecodeContext{Registry: buildDefaultRegistry()}, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.ReadElement, + &valueReaderWriter{}, + readElement, fmt.Errorf("unsupported key type: %T", false), }, { "ReadDocument Error", make(map[string]interface{}), nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("rd error"), ErrAfter: bsonrwtest.ReadDocument}, - bsonrwtest.ReadDocument, + &valueReaderWriter{Err: errors.New("rd error"), ErrAfter: readDocument}, + readDocument, errors.New("rd error"), }, { "Lookup Error", map[string]string{}, - &DecodeContext{Registry: NewRegistryBuilder().Build()}, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.ReadDocument, + &DecodeContext{Registry: newTestRegistryBuilder().Build()}, + &valueReaderWriter{}, + readDocument, ErrNoDecoder{Type: reflect.TypeOf("")}, }, { "ReadElement Error", make(map[string]interface{}), &DecodeContext{Registry: buildDefaultRegistry()}, - &bsonrwtest.ValueReaderWriter{Err: errors.New("re error"), ErrAfter: bsonrwtest.ReadElement}, - bsonrwtest.ReadElement, + &valueReaderWriter{Err: errors.New("re error"), ErrAfter: readElement}, + readElement, errors.New("re error"), }, { "can set false", cansettest, nil, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.Nothing, + &valueReaderWriter{}, + nothing, ValueDecoderError{Name: "MapDecodeValue", Kinds: []reflect.Kind{reflect.Map}}, }, { "wrong BSON type", map[string]interface{}{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeString}, + nothing, errors.New("cannot decode string into a map[string]interface {}"), }, { "decode null", (map[string]interface{})(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", (map[string]interface{})(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -880,88 +875,88 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong kind", wrong, nil, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.Nothing, + &valueReaderWriter{}, + nothing, ValueDecoderError{Name: "ArrayDecodeValue", Kinds: []reflect.Kind{reflect.Array}, Received: reflect.ValueOf(wrong)}, }, { "can set false", cansettest, nil, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.Nothing, + &valueReaderWriter{}, + nothing, ValueDecoderError{Name: "ArrayDecodeValue", Kinds: []reflect.Kind{reflect.Array}}, }, { "Not Type Array", [1]interface{}{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeString}, + nothing, errors.New("cannot decode string into an array"), }, { "ReadArray Error", [1]interface{}{}, nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("ra error"), ErrAfter: bsonrwtest.ReadArray, BSONType: bsontype.Array}, - bsonrwtest.ReadArray, + &valueReaderWriter{Err: errors.New("ra error"), ErrAfter: readArray, BSONType: TypeArray}, + readArray, errors.New("ra error"), }, { "Lookup Error", [1]string{}, - &DecodeContext{Registry: NewRegistryBuilder().Build()}, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Array}, - bsonrwtest.ReadArray, + &DecodeContext{Registry: newTestRegistryBuilder().Build()}, + &valueReaderWriter{BSONType: TypeArray}, + readArray, ErrNoDecoder{Type: reflect.TypeOf("")}, }, { "ReadValue Error", [1]string{}, &DecodeContext{Registry: buildDefaultRegistry()}, - &bsonrwtest.ValueReaderWriter{Err: errors.New("rv error"), ErrAfter: bsonrwtest.ReadValue, BSONType: bsontype.Array}, - bsonrwtest.ReadValue, + &valueReaderWriter{Err: errors.New("rv error"), ErrAfter: readValue, BSONType: TypeArray}, + readValue, errors.New("rv error"), }, { "DecodeValue Error", [1]string{}, &DecodeContext{Registry: buildDefaultRegistry()}, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Array}, - bsonrwtest.ReadValue, + &valueReaderWriter{BSONType: TypeArray}, + readValue, &DecodeError{keys: []string{"0"}, wrapped: errors.New("cannot decode array into a string type")}, }, { "Document but not D", [1]string{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Type(0)}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: Type(0)}, + nothing, errors.New("cannot decode document into [1]string"), }, { "EmbeddedDocument but not D", [1]string{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.EmbeddedDocument}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeEmbeddedDocument}, + nothing, errors.New("cannot decode document into [1]string"), }, { "decode null", [1]string{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", [1]string{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -974,88 +969,88 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong kind", wrong, nil, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.Nothing, + &valueReaderWriter{}, + nothing, ValueDecoderError{Name: "SliceDecodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: reflect.ValueOf(wrong)}, }, { "can set false", cansettest, nil, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.Nothing, + &valueReaderWriter{}, + nothing, ValueDecoderError{Name: "SliceDecodeValue", Kinds: []reflect.Kind{reflect.Slice}}, }, { "Not Type Array", []interface{}{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeInt32}, + nothing, errors.New("cannot decode 32-bit integer into a slice"), }, { "ReadArray Error", []interface{}{}, nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("ra error"), ErrAfter: bsonrwtest.ReadArray, BSONType: bsontype.Array}, - bsonrwtest.ReadArray, + &valueReaderWriter{Err: errors.New("ra error"), ErrAfter: readArray, BSONType: TypeArray}, + readArray, errors.New("ra error"), }, { "Lookup Error", []string{}, - &DecodeContext{Registry: NewRegistryBuilder().Build()}, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Array}, - bsonrwtest.ReadArray, + &DecodeContext{Registry: newTestRegistryBuilder().Build()}, + &valueReaderWriter{BSONType: TypeArray}, + readArray, ErrNoDecoder{Type: reflect.TypeOf("")}, }, { "ReadValue Error", []string{}, &DecodeContext{Registry: buildDefaultRegistry()}, - &bsonrwtest.ValueReaderWriter{Err: errors.New("rv error"), ErrAfter: bsonrwtest.ReadValue, BSONType: bsontype.Array}, - bsonrwtest.ReadValue, + &valueReaderWriter{Err: errors.New("rv error"), ErrAfter: readValue, BSONType: TypeArray}, + readValue, errors.New("rv error"), }, { "DecodeValue Error", []string{}, &DecodeContext{Registry: buildDefaultRegistry()}, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Array}, - bsonrwtest.ReadValue, + &valueReaderWriter{BSONType: TypeArray}, + readValue, &DecodeError{keys: []string{"0"}, wrapped: errors.New("cannot decode array into a string type")}, }, { "Document but not D", []string{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Type(0)}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: Type(0)}, + nothing, errors.New("cannot decode document into []string"), }, { "EmbeddedDocument but not D", []string{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.EmbeddedDocument}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeEmbeddedDocument}, + nothing, errors.New("cannot decode document into []string"), }, { "decode null", ([]string)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", ([]string)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -1068,81 +1063,81 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.ObjectID}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeObjectID}, + nothing, ValueDecoderError{Name: "ObjectIDDecodeValue", Types: []reflect.Type{tOID}, Received: reflect.ValueOf(wrong)}, }, { "type not objectID", - primitive.ObjectID{}, + ObjectID{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into an ObjectID", bsontype.Int32), + &valueReaderWriter{BSONType: TypeInt32}, + nothing, + fmt.Errorf("cannot decode %v into an ObjectID", TypeInt32), }, { "ReadObjectID Error", - primitive.ObjectID{}, + ObjectID{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.ObjectID, Err: errors.New("roid error"), ErrAfter: bsonrwtest.ReadObjectID}, - bsonrwtest.ReadObjectID, + &valueReaderWriter{BSONType: TypeObjectID, Err: errors.New("roid error"), ErrAfter: readObjectID}, + readObjectID, errors.New("roid error"), }, { "can set false", cansettest, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.ObjectID, Return: primitive.ObjectID{}}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeObjectID, Return: ObjectID{}}, + nothing, ValueDecoderError{Name: "ObjectIDDecodeValue", Types: []reflect.Type{tOID}}, }, { "success", - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, nil, - &bsonrwtest.ValueReaderWriter{ - BSONType: bsontype.ObjectID, - Return: primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + &valueReaderWriter{ + BSONType: TypeObjectID, + Return: ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, }, - bsonrwtest.ReadObjectID, + readObjectID, nil, }, { "success/string", - primitive.ObjectID{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62}, + ObjectID{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62}, nil, - &bsonrwtest.ValueReaderWriter{ - BSONType: bsontype.String, + &valueReaderWriter{ + BSONType: TypeString, Return: "0123456789ab", }, - bsonrwtest.ReadString, + readString, nil, }, { "success/string-hex", - primitive.ObjectID{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62}, + ObjectID{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62}, nil, - &bsonrwtest.ValueReaderWriter{ - BSONType: bsontype.String, + &valueReaderWriter{ + BSONType: TypeString, Return: "303132333435363738396162", }, - bsonrwtest.ReadString, + readString, nil, }, { "decode null", - primitive.ObjectID{}, + ObjectID{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", - primitive.ObjectID{}, + ObjectID{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -1155,56 +1150,56 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Decimal128}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeDecimal128}, + nothing, ValueDecoderError{Name: "Decimal128DecodeValue", Types: []reflect.Type{tDecimal}, Received: reflect.ValueOf(wrong)}, }, { "type not decimal128", - primitive.Decimal128{}, + Decimal128{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a primitive.Decimal128", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into a Decimal128", TypeString), }, { "ReadDecimal128 Error", - primitive.Decimal128{}, + Decimal128{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Decimal128, Err: errors.New("rd128 error"), ErrAfter: bsonrwtest.ReadDecimal128}, - bsonrwtest.ReadDecimal128, + &valueReaderWriter{BSONType: TypeDecimal128, Err: errors.New("rd128 error"), ErrAfter: readDecimal128}, + readDecimal128, errors.New("rd128 error"), }, { "can set false", cansettest, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Decimal128, Return: d128}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeDecimal128, Return: d128}, + nothing, ValueDecoderError{Name: "Decimal128DecodeValue", Types: []reflect.Type{tDecimal}}, }, { "success", d128, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Decimal128, Return: d128}, - bsonrwtest.ReadDecimal128, + &valueReaderWriter{BSONType: TypeDecimal128, Return: d128}, + readDecimal128, nil, }, { "decode null", - primitive.Decimal128{}, + Decimal128{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", - primitive.Decimal128{}, + Decimal128{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -1217,88 +1212,88 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.ObjectID}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeObjectID}, + nothing, ValueDecoderError{Name: "JSONNumberDecodeValue", Types: []reflect.Type{tJSONNumber}, Received: reflect.ValueOf(wrong)}, }, { "type not double/int32/int64", json.Number(""), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a json.Number", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into a json.Number", TypeString), }, { "ReadDouble Error", json.Number(""), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Err: errors.New("rd error"), ErrAfter: bsonrwtest.ReadDouble}, - bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Err: errors.New("rd error"), ErrAfter: readDouble}, + readDouble, errors.New("rd error"), }, { "ReadInt32 Error", json.Number(""), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Err: errors.New("ri32 error"), ErrAfter: bsonrwtest.ReadInt32}, - bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Err: errors.New("ri32 error"), ErrAfter: readInt32}, + readInt32, errors.New("ri32 error"), }, { "ReadInt64 Error", json.Number(""), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Err: errors.New("ri64 error"), ErrAfter: bsonrwtest.ReadInt64}, - bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Err: errors.New("ri64 error"), ErrAfter: readInt64}, + readInt64, errors.New("ri64 error"), }, { "can set false", cansettest, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.ObjectID, Return: primitive.ObjectID{}}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeObjectID, Return: ObjectID{}}, + nothing, ValueDecoderError{Name: "JSONNumberDecodeValue", Types: []reflect.Type{tJSONNumber}}, }, { "success/double", json.Number("3.14159"), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.14159)}, - bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.14159)}, + readDouble, nil, }, { "success/int32", json.Number("12345"), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32, Return: int32(12345)}, - bsonrwtest.ReadInt32, + &valueReaderWriter{BSONType: TypeInt32, Return: int32(12345)}, + readInt32, nil, }, { "success/int64", json.Number("1234567890"), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: int64(1234567890)}, - bsonrwtest.ReadInt64, + &valueReaderWriter{BSONType: TypeInt64, Return: int64(1234567890)}, + readInt64, nil, }, { "decode null", json.Number(""), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", json.Number(""), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -1311,32 +1306,32 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", url.URL{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a *url.URL", bsontype.Int32), + &valueReaderWriter{BSONType: TypeInt32}, + nothing, + fmt.Errorf("cannot decode %v into a *url.URL", TypeInt32), }, { "type not *url.URL", int64(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String, Return: "http://example.com"}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeString, Return: "http://example.com"}, + nothing, ValueDecoderError{Name: "URLDecodeValue", Types: []reflect.Type{tURL}, Received: reflect.ValueOf(int64(0))}, }, { "ReadString error", url.URL{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String, Err: errors.New("rs error"), ErrAfter: bsonrwtest.ReadString}, - bsonrwtest.ReadString, + &valueReaderWriter{BSONType: TypeString, Err: errors.New("rs error"), ErrAfter: readString}, + readString, errors.New("rs error"), }, { "url.Parse error", url.URL{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String, Return: "not-valid-%%%%://"}, - bsonrwtest.ReadString, + &valueReaderWriter{BSONType: TypeString, Return: "not-valid-%%%%://"}, + readString, &url.Error{ Op: "parse", URL: "not-valid-%%%%://", @@ -1347,32 +1342,32 @@ func TestDefaultValueDecoders(t *testing.T) { "can set false", cansettest, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String, Return: "http://example.com"}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeString, Return: "http://example.com"}, + nothing, ValueDecoderError{Name: "URLDecodeValue", Types: []reflect.Type{tURL}}, }, { "url.URL", url.URL{Scheme: "http", Host: "example.com"}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String, Return: "http://example.com"}, - bsonrwtest.ReadString, + &valueReaderWriter{BSONType: TypeString, Return: "http://example.com"}, + readString, nil, }, { "decode null", url.URL{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", url.URL{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -1385,62 +1380,62 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", []byte{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a []byte", bsontype.Int32), + &valueReaderWriter{BSONType: TypeInt32}, + nothing, + fmt.Errorf("cannot decode %v into a []byte", TypeInt32), }, { "type not []byte", int64(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Binary, Return: bsoncore.Value{Type: bsontype.Binary}}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeBinary, Return: bsoncore.Value{Type: bsoncore.TypeBinary}}, + nothing, ValueDecoderError{Name: "ByteSliceDecodeValue", Types: []reflect.Type{tByteSlice}, Received: reflect.ValueOf(int64(0))}, }, { "ReadBinary error", []byte{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Binary, Err: errors.New("rb error"), ErrAfter: bsonrwtest.ReadBinary}, - bsonrwtest.ReadBinary, + &valueReaderWriter{BSONType: TypeBinary, Err: errors.New("rb error"), ErrAfter: readBinary}, + readBinary, errors.New("rb error"), }, { "incorrect subtype", []byte{}, nil, - &bsonrwtest.ValueReaderWriter{ - BSONType: bsontype.Binary, + &valueReaderWriter{ + BSONType: TypeBinary, Return: bsoncore.Value{ - Type: bsontype.Binary, + Type: bsoncore.TypeBinary, Data: bsoncore.AppendBinary(nil, 0xFF, []byte{0x01, 0x02, 0x03}), }, }, - bsonrwtest.ReadBinary, + readBinary, decodeBinaryError{subtype: byte(0xFF), typeName: "[]byte"}, }, { "can set false", cansettest, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Binary, Return: bsoncore.AppendBinary(nil, 0x00, []byte{0x01, 0x02, 0x03})}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeBinary, Return: bsoncore.AppendBinary(nil, 0x00, []byte{0x01, 0x02, 0x03})}, + nothing, ValueDecoderError{Name: "ByteSliceDecodeValue", Types: []reflect.Type{tByteSlice}}, }, { "decode null", ([]byte)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", ([]byte)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -1453,24 +1448,24 @@ func TestDefaultValueDecoders(t *testing.T) { "symbol", "var hello = 'world';", nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Symbol, Return: "var hello = 'world';"}, - bsonrwtest.ReadSymbol, + &valueReaderWriter{BSONType: TypeSymbol, Return: "var hello = 'world';"}, + readSymbol, nil, }, { "decode null", "", nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", "", nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -1484,7 +1479,7 @@ func TestDefaultValueDecoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueDecoderError{ Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, @@ -1495,16 +1490,16 @@ func TestDefaultValueDecoders(t *testing.T) { "copy error", &testValueUnmarshaler{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String, Err: errors.New("copy error"), ErrAfter: bsonrwtest.ReadString}, - bsonrwtest.ReadString, + &valueReaderWriter{BSONType: TypeString, Err: errors.New("copy error"), ErrAfter: readString}, + readString, errors.New("copy error"), }, { "ValueUnmarshaler", - &testValueUnmarshaler{t: bsontype.String, val: bsoncore.AppendString(nil, "hello, world")}, + &testValueUnmarshaler{t: TypeString, val: bsoncore.AppendString(nil, "hello, world")}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String, Return: "hello, world"}, - bsonrwtest.ReadString, + &valueReaderWriter{BSONType: TypeString, Return: "hello, world"}, + readString, nil, }, }, @@ -1518,32 +1513,38 @@ func TestDefaultValueDecoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueDecoderError{Name: "UnmarshalerDecodeValue", Types: []reflect.Type{tUnmarshaler}, Received: reflect.ValueOf(wrong)}, }, { "copy error", &testUnmarshaler{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String, Err: errors.New("copy error"), ErrAfter: bsonrwtest.ReadString}, - bsonrwtest.ReadString, + &valueReaderWriter{BSONType: TypeString, Err: errors.New("copy error"), ErrAfter: readString}, + readString, errors.New("copy error"), }, { // Only the pointer form of testUnmarshaler implements Unmarshaler "value does not implement Unmarshaler", - testUnmarshaler{Val: bsoncore.AppendDouble(nil, 3.14159)}, + &testUnmarshaler{ + Invoked: true, + Val: bsoncore.AppendDouble(nil, 3.14159), + }, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.14159)}, - bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.14159)}, + readDouble, nil, }, { "Unmarshaler", - &testUnmarshaler{Val: bsoncore.AppendDouble(nil, 3.14159)}, + &testUnmarshaler{ + Invoked: true, + Val: bsoncore.AppendDouble(nil, 3.14159), + }, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double, Return: float64(3.14159)}, - bsonrwtest.ReadDouble, + &valueReaderWriter{BSONType: TypeDouble, Return: float64(3.14159)}, + readDouble, nil, }, }, @@ -1553,31 +1554,31 @@ func TestDefaultValueDecoders(t *testing.T) { NewPointerCodec(), []subtest{ { - "not valid", nil, nil, nil, bsonrwtest.Nothing, + "not valid", nil, nil, nil, nothing, ValueDecoderError{Name: "PointerCodec.DecodeValue", Kinds: []reflect.Kind{reflect.Ptr}, Received: reflect.Value{}}, }, { - "can set", cansettest, nil, nil, bsonrwtest.Nothing, + "can set", cansettest, nil, nil, nothing, ValueDecoderError{Name: "PointerCodec.DecodeValue", Kinds: []reflect.Kind{reflect.Ptr}}, }, { - "No Decoder", &wrong, &DecodeContext{Registry: buildDefaultRegistry()}, nil, bsonrwtest.Nothing, + "No Decoder", &wrong, &DecodeContext{Registry: buildDefaultRegistry()}, nil, nothing, ErrNoDecoder{Type: reflect.TypeOf(wrong)}, }, { "decode null", (*mystruct)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", (*mystruct)(nil), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -1590,54 +1591,54 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.Nothing, + &valueReaderWriter{}, + nothing, ValueDecoderError{Name: "BinaryDecodeValue", Types: []reflect.Type{tBinary}, Received: reflect.ValueOf(wrong)}, }, { "type not binary", - primitive.Binary{}, + Binary{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a Binary", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into a Binary", TypeString), }, { "ReadBinary Error", - primitive.Binary{}, + Binary{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Binary, Err: errors.New("rb error"), ErrAfter: bsonrwtest.ReadBinary}, - bsonrwtest.ReadBinary, + &valueReaderWriter{BSONType: TypeBinary, Err: errors.New("rb error"), ErrAfter: readBinary}, + readBinary, errors.New("rb error"), }, { "Binary/success", - primitive.Binary{Data: []byte{0x01, 0x02, 0x03}, Subtype: 0xFF}, + Binary{Data: []byte{0x01, 0x02, 0x03}, Subtype: 0xFF}, nil, - &bsonrwtest.ValueReaderWriter{ - BSONType: bsontype.Binary, + &valueReaderWriter{ + BSONType: TypeBinary, Return: bsoncore.Value{ - Type: bsontype.Binary, + Type: bsoncore.TypeBinary, Data: bsoncore.AppendBinary(nil, 0xFF, []byte{0x01, 0x02, 0x03}), }, }, - bsonrwtest.ReadBinary, + readBinary, nil, }, { "decode null", - primitive.Binary{}, + Binary{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", - primitive.Binary{}, + Binary{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -1650,40 +1651,40 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeUndefined}, + nothing, ValueDecoderError{Name: "UndefinedDecodeValue", Types: []reflect.Type{tUndefined}, Received: reflect.ValueOf(wrong)}, }, { "type not undefined", - primitive.Undefined{}, + Undefined{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into an Undefined", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into an Undefined", TypeString), }, { "ReadUndefined Error", - primitive.Undefined{}, + Undefined{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined, Err: errors.New("ru error"), ErrAfter: bsonrwtest.ReadUndefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined, Err: errors.New("ru error"), ErrAfter: readUndefined}, + readUndefined, errors.New("ru error"), }, { "ReadUndefined/success", - primitive.Undefined{}, + Undefined{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, { "decode null", - primitive.Undefined{}, + Undefined{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, }, @@ -1696,48 +1697,48 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.DateTime}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeDateTime}, + nothing, ValueDecoderError{Name: "DateTimeDecodeValue", Types: []reflect.Type{tDateTime}, Received: reflect.ValueOf(wrong)}, }, { "type not datetime", - primitive.DateTime(0), + DateTime(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a DateTime", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into a DateTime", TypeString), }, { "ReadDateTime Error", - primitive.DateTime(0), + DateTime(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.DateTime, Err: errors.New("rdt error"), ErrAfter: bsonrwtest.ReadDateTime}, - bsonrwtest.ReadDateTime, + &valueReaderWriter{BSONType: TypeDateTime, Err: errors.New("rdt error"), ErrAfter: readDateTime}, + readDateTime, errors.New("rdt error"), }, { "success", - primitive.DateTime(1234567890), + DateTime(1234567890), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.DateTime, Return: int64(1234567890)}, - bsonrwtest.ReadDateTime, + &valueReaderWriter{BSONType: TypeDateTime, Return: int64(1234567890)}, + readDateTime, nil, }, { "decode null", - primitive.DateTime(0), + DateTime(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", - primitive.DateTime(0), + DateTime(0), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -1750,32 +1751,32 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeNull}, + nothing, ValueDecoderError{Name: "NullDecodeValue", Types: []reflect.Type{tNull}, Received: reflect.ValueOf(wrong)}, }, { "type not null", - primitive.Null{}, + Null{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a Null", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into a Null", TypeString), }, { "ReadNull Error", - primitive.Null{}, + Null{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null, Err: errors.New("rn error"), ErrAfter: bsonrwtest.ReadNull}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull, Err: errors.New("rn error"), ErrAfter: readNull}, + readNull, errors.New("rn error"), }, { "success", - primitive.Null{}, + Null{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, }, @@ -1788,54 +1789,54 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Regex}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeRegex}, + nothing, ValueDecoderError{Name: "RegexDecodeValue", Types: []reflect.Type{tRegex}, Received: reflect.ValueOf(wrong)}, }, { "type not regex", - primitive.Regex{}, + Regex{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a Regex", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into a Regex", TypeString), }, { "ReadRegex Error", - primitive.Regex{}, + Regex{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Regex, Err: errors.New("rr error"), ErrAfter: bsonrwtest.ReadRegex}, - bsonrwtest.ReadRegex, + &valueReaderWriter{BSONType: TypeRegex, Err: errors.New("rr error"), ErrAfter: readRegex}, + readRegex, errors.New("rr error"), }, { "success", - primitive.Regex{Pattern: "foo", Options: "bar"}, + Regex{Pattern: "foo", Options: "bar"}, nil, - &bsonrwtest.ValueReaderWriter{ - BSONType: bsontype.Regex, + &valueReaderWriter{ + BSONType: TypeRegex, Return: bsoncore.Value{ - Type: bsontype.Regex, + Type: bsoncore.TypeRegex, Data: bsoncore.AppendRegex(nil, "foo", "bar"), }, }, - bsonrwtest.ReadRegex, + readRegex, nil, }, { "decode null", - primitive.Regex{}, + Regex{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", - primitive.Regex{}, + Regex{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -1848,59 +1849,59 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.DBPointer}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeDBPointer}, + nothing, ValueDecoderError{Name: "DBPointerDecodeValue", Types: []reflect.Type{tDBPointer}, Received: reflect.ValueOf(wrong)}, }, { "type not dbpointer", - primitive.DBPointer{}, + DBPointer{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a DBPointer", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into a DBPointer", TypeString), }, { "ReadDBPointer Error", - primitive.DBPointer{}, + DBPointer{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.DBPointer, Err: errors.New("rdbp error"), ErrAfter: bsonrwtest.ReadDBPointer}, - bsonrwtest.ReadDBPointer, + &valueReaderWriter{BSONType: TypeDBPointer, Err: errors.New("rdbp error"), ErrAfter: readDBPointer}, + readDBPointer, errors.New("rdbp error"), }, { "success", - primitive.DBPointer{ + DBPointer{ DB: "foobar", - Pointer: primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + Pointer: ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, }, nil, - &bsonrwtest.ValueReaderWriter{ - BSONType: bsontype.DBPointer, + &valueReaderWriter{ + BSONType: TypeDBPointer, Return: bsoncore.Value{ - Type: bsontype.DBPointer, + Type: bsoncore.TypeDBPointer, Data: bsoncore.AppendDBPointer( - nil, "foobar", primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + nil, "foobar", ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, ), }, }, - bsonrwtest.ReadDBPointer, + readDBPointer, nil, }, { "decode null", - primitive.DBPointer{}, + DBPointer{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", - primitive.DBPointer{}, + DBPointer{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -1913,54 +1914,54 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Timestamp}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeTimestamp}, + nothing, ValueDecoderError{Name: "TimestampDecodeValue", Types: []reflect.Type{tTimestamp}, Received: reflect.ValueOf(wrong)}, }, { "type not timestamp", - primitive.Timestamp{}, + Timestamp{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a Timestamp", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into a Timestamp", TypeString), }, { "ReadTimestamp Error", - primitive.Timestamp{}, + Timestamp{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Timestamp, Err: errors.New("rt error"), ErrAfter: bsonrwtest.ReadTimestamp}, - bsonrwtest.ReadTimestamp, + &valueReaderWriter{BSONType: TypeTimestamp, Err: errors.New("rt error"), ErrAfter: readTimestamp}, + readTimestamp, errors.New("rt error"), }, { "success", - primitive.Timestamp{T: 12345, I: 67890}, + Timestamp{T: 12345, I: 67890}, nil, - &bsonrwtest.ValueReaderWriter{ - BSONType: bsontype.Timestamp, + &valueReaderWriter{ + BSONType: TypeTimestamp, Return: bsoncore.Value{ - Type: bsontype.Timestamp, + Type: bsoncore.TypeTimestamp, Data: bsoncore.AppendTimestamp(nil, 12345, 67890), }, }, - bsonrwtest.ReadTimestamp, + readTimestamp, nil, }, { "decode null", - primitive.Timestamp{}, + Timestamp{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", - primitive.Timestamp{}, + Timestamp{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -1973,48 +1974,48 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.MinKey}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeMinKey}, + nothing, ValueDecoderError{Name: "MinKeyDecodeValue", Types: []reflect.Type{tMinKey}, Received: reflect.ValueOf(wrong)}, }, { "type not null", - primitive.MinKey{}, + MinKey{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a MinKey", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into a MinKey", TypeString), }, { "ReadMinKey Error", - primitive.MinKey{}, + MinKey{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.MinKey, Err: errors.New("rn error"), ErrAfter: bsonrwtest.ReadMinKey}, - bsonrwtest.ReadMinKey, + &valueReaderWriter{BSONType: TypeMinKey, Err: errors.New("rn error"), ErrAfter: readMinKey}, + readMinKey, errors.New("rn error"), }, { "success", - primitive.MinKey{}, + MinKey{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.MinKey}, - bsonrwtest.ReadMinKey, + &valueReaderWriter{BSONType: TypeMinKey}, + readMinKey, nil, }, { "decode null", - primitive.MinKey{}, + MinKey{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", - primitive.MinKey{}, + MinKey{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -2027,48 +2028,48 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.MaxKey}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeMaxKey}, + nothing, ValueDecoderError{Name: "MaxKeyDecodeValue", Types: []reflect.Type{tMaxKey}, Received: reflect.ValueOf(wrong)}, }, { "type not null", - primitive.MaxKey{}, + MaxKey{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a MaxKey", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into a MaxKey", TypeString), }, { "ReadMaxKey Error", - primitive.MaxKey{}, + MaxKey{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.MaxKey, Err: errors.New("rn error"), ErrAfter: bsonrwtest.ReadMaxKey}, - bsonrwtest.ReadMaxKey, + &valueReaderWriter{BSONType: TypeMaxKey, Err: errors.New("rn error"), ErrAfter: readMaxKey}, + readMaxKey, errors.New("rn error"), }, { "success", - primitive.MaxKey{}, + MaxKey{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.MaxKey}, - bsonrwtest.ReadMaxKey, + &valueReaderWriter{BSONType: TypeMaxKey}, + readMaxKey, nil, }, { "decode null", - primitive.MaxKey{}, + MaxKey{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", - primitive.MaxKey{}, + MaxKey{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -2081,48 +2082,48 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.JavaScript, Return: ""}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeJavaScript, Return: ""}, + nothing, ValueDecoderError{Name: "JavaScriptDecodeValue", Types: []reflect.Type{tJavaScript}, Received: reflect.ValueOf(wrong)}, }, { "type not Javascript", - primitive.JavaScript(""), + JavaScript(""), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a primitive.JavaScript", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into a JavaScript", TypeString), }, { "ReadJavascript Error", - primitive.JavaScript(""), + JavaScript(""), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.JavaScript, Err: errors.New("rjs error"), ErrAfter: bsonrwtest.ReadJavascript}, - bsonrwtest.ReadJavascript, + &valueReaderWriter{BSONType: TypeJavaScript, Err: errors.New("rjs error"), ErrAfter: readJavascript}, + readJavascript, errors.New("rjs error"), }, { "JavaScript/success", - primitive.JavaScript("var hello = 'world';"), + JavaScript("var hello = 'world';"), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.JavaScript, Return: "var hello = 'world';"}, - bsonrwtest.ReadJavascript, + &valueReaderWriter{BSONType: TypeJavaScript, Return: "var hello = 'world';"}, + readJavascript, nil, }, { "decode null", - primitive.JavaScript(""), + JavaScript(""), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", - primitive.JavaScript(""), + JavaScript(""), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -2135,48 +2136,48 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Symbol, Return: ""}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeSymbol, Return: ""}, + nothing, ValueDecoderError{Name: "SymbolDecodeValue", Types: []reflect.Type{tSymbol}, Received: reflect.ValueOf(wrong)}, }, { "type not Symbol", - primitive.Symbol(""), + Symbol(""), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int32}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a primitive.Symbol", bsontype.Int32), + &valueReaderWriter{BSONType: TypeInt32}, + nothing, + fmt.Errorf("cannot decode %v into a Symbol", TypeInt32), }, { "ReadSymbol Error", - primitive.Symbol(""), + Symbol(""), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Symbol, Err: errors.New("rjs error"), ErrAfter: bsonrwtest.ReadSymbol}, - bsonrwtest.ReadSymbol, + &valueReaderWriter{BSONType: TypeSymbol, Err: errors.New("rjs error"), ErrAfter: readSymbol}, + readSymbol, errors.New("rjs error"), }, { "Symbol/success", - primitive.Symbol("var hello = 'world';"), + Symbol("var hello = 'world';"), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Symbol, Return: "var hello = 'world';"}, - bsonrwtest.ReadSymbol, + &valueReaderWriter{BSONType: TypeSymbol, Return: "var hello = 'world';"}, + readSymbol, nil, }, { "decode null", - primitive.Symbol(""), + Symbol(""), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", - primitive.Symbol(""), + Symbol(""), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -2189,8 +2190,8 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.Nothing, + &valueReaderWriter{}, + nothing, ValueDecoderError{ Name: "CoreDocumentDecodeValue", Types: []reflect.Type{tCoreDocument}, @@ -2202,7 +2203,7 @@ func TestDefaultValueDecoders(t *testing.T) { (*bsoncore.Document)(nil), nil, nil, - bsonrwtest.Nothing, + nothing, ValueDecoderError{ Name: "CoreDocumentDecodeValue", Types: []reflect.Type{tCoreDocument}, @@ -2213,8 +2214,8 @@ func TestDefaultValueDecoders(t *testing.T) { "Copy error", bsoncore.Document{}, nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("copy error"), ErrAfter: bsonrwtest.ReadDocument}, - bsonrwtest.ReadDocument, + &valueReaderWriter{Err: errors.New("copy error"), ErrAfter: readDocument}, + readDocument, errors.New("copy error"), }, }, @@ -2227,24 +2228,24 @@ func TestDefaultValueDecoders(t *testing.T) { "Not struct", reflect.New(reflect.TypeOf(struct{ Foo string }{})).Elem().Interface(), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeString}, + nothing, errors.New("cannot decode string into a struct { Foo string }"), }, { "decode null", reflect.New(reflect.TypeOf(struct{ Foo string }{})).Elem().Interface(), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", reflect.New(reflect.TypeOf(struct{ Foo string }{})).Elem().Interface(), nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -2257,8 +2258,8 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.CodeWithScope}, - bsonrwtest.Nothing, + &valueReaderWriter{BSONType: TypeCodeWithScope}, + nothing, ValueDecoderError{ Name: "CodeWithScopeDecodeValue", Types: []reflect.Type{tCodeWithScope}, @@ -2267,45 +2268,45 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "type not codewithscope", - primitive.CodeWithScope{}, + CodeWithScope{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String}, - bsonrwtest.Nothing, - fmt.Errorf("cannot decode %v into a primitive.CodeWithScope", bsontype.String), + &valueReaderWriter{BSONType: TypeString}, + nothing, + fmt.Errorf("cannot decode %v into a CodeWithScope", TypeString), }, { "ReadCodeWithScope Error", - primitive.CodeWithScope{}, + CodeWithScope{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.CodeWithScope, Err: errors.New("rcws error"), ErrAfter: bsonrwtest.ReadCodeWithScope}, - bsonrwtest.ReadCodeWithScope, + &valueReaderWriter{BSONType: TypeCodeWithScope, Err: errors.New("rcws error"), ErrAfter: readCodeWithScope}, + readCodeWithScope, errors.New("rcws error"), }, { "decodeDocument Error", - primitive.CodeWithScope{ + CodeWithScope{ Code: "var hello = 'world';", - Scope: primitive.D{{"foo", nil}}, + Scope: D{{"foo", nil}}, }, &DecodeContext{Registry: buildDefaultRegistry()}, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.CodeWithScope, Err: errors.New("dd error"), ErrAfter: bsonrwtest.ReadElement}, - bsonrwtest.ReadElement, + &valueReaderWriter{BSONType: TypeCodeWithScope, Err: errors.New("dd error"), ErrAfter: readElement}, + readElement, errors.New("dd error"), }, { "decode null", - primitive.CodeWithScope{}, + CodeWithScope{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Null}, - bsonrwtest.ReadNull, + &valueReaderWriter{BSONType: TypeNull}, + readNull, nil, }, { "decode undefined", - primitive.CodeWithScope{}, + CodeWithScope{}, nil, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Undefined}, - bsonrwtest.ReadUndefined, + &valueReaderWriter{BSONType: TypeUndefined}, + readUndefined, nil, }, }, @@ -2318,8 +2319,8 @@ func TestDefaultValueDecoders(t *testing.T) { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.Nothing, + &valueReaderWriter{}, + nothing, ValueDecoderError{ Name: "CoreArrayDecodeValue", Types: []reflect.Type{tCoreArray}, @@ -2331,7 +2332,7 @@ func TestDefaultValueDecoders(t *testing.T) { (*bsoncore.Array)(nil), nil, nil, - bsonrwtest.Nothing, + nothing, ValueDecoderError{ Name: "CoreArrayDecodeValue", Types: []reflect.Type{tCoreArray}, @@ -2350,7 +2351,7 @@ func TestDefaultValueDecoders(t *testing.T) { if rc.dctx != nil { dc = *rc.dctx } - llvrw := new(bsonrwtest.ValueReaderWriter) + llvrw := new(valueReaderWriter) if rc.llvrw != nil { llvrw = rc.llvrw } @@ -2358,13 +2359,13 @@ func TestDefaultValueDecoders(t *testing.T) { // var got interface{} if rc.val == cansetreflectiontest { // We're doing a CanSet reflection test err := tc.vd.DecodeValue(dc, llvrw, reflect.Value{}) - if !compareErrors(err, rc.err) { + if !assert.CompareErrors(err, rc.err) { t.Errorf("Errors do not match. got %v; want %v", err, rc.err) } val := reflect.New(reflect.TypeOf(rc.val)).Elem() err = tc.vd.DecodeValue(dc, llvrw, val) - if !compareErrors(err, rc.err) { + if !assert.CompareErrors(err, rc.err) { t.Errorf("Errors do not match. got %v; want %v", err, rc.err) } return @@ -2377,13 +2378,13 @@ func TestDefaultValueDecoders(t *testing.T) { err := tc.vd.DecodeValue(dc, llvrw, reflect.Value{}) wanterr.Received = reflect.ValueOf(nil) - if !compareErrors(err, wanterr) { + if !assert.CompareErrors(err, wanterr) { t.Errorf("Errors do not match. got %v; want %v", err, wanterr) } err = tc.vd.DecodeValue(dc, llvrw, reflect.ValueOf(int(12345))) wanterr.Received = reflect.ValueOf(int(12345)) - if !compareErrors(err, wanterr) { + if !assert.CompareErrors(err, wanterr) { t.Errorf("Errors do not match. got %v; want %v", err, wanterr) } return @@ -2400,10 +2401,10 @@ func TestDefaultValueDecoders(t *testing.T) { } }() err := tc.vd.DecodeValue(dc, llvrw, val) - if !compareErrors(err, rc.err) { + if !assert.CompareErrors(err, rc.err) { t.Errorf("Errors do not match. got %v; want %v", err, rc.err) } - invoked := llvrw.Invoked + invoked := llvrw.invoked if !cmp.Equal(invoked, rc.invoke) { t.Errorf("Incorrect method invoked. got %v; want %v", invoked, rc.invoke) } @@ -2427,46 +2428,46 @@ func TestDefaultValueDecoders(t *testing.T) { buildDocument(bsoncore.AppendNullElement(nil, "bar")), ), ) - dvr := bsonrw.NewValueReader(b) + dvr := NewValueReader(b) dr, err := dvr.ReadDocument() noerr(t, err) _, vr, err := dr.ReadElement() noerr(t, err) - want := primitive.CodeWithScope{ + want := CodeWithScope{ Code: "var hello = 'world';", - Scope: primitive.D{{"bar", nil}}, + Scope: D{{"bar", nil}}, } val := reflect.New(tCodeWithScope).Elem() err = dvd.CodeWithScopeDecodeValue(dc, vr, val) noerr(t, err) - got := val.Interface().(primitive.CodeWithScope) + got := val.Interface().(CodeWithScope) if got.Code != want.Code && !cmp.Equal(got.Scope, want.Scope) { t.Errorf("CodeWithScopes do not match. got %v; want %v", got, want) } }) t.Run("ValueUnmarshalerDecodeValue/UnmarshalBSONValue error", func(t *testing.T) { var dc DecodeContext - llvrw := &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String, Return: string("hello, world!")} + llvrw := &valueReaderWriter{BSONType: TypeString, Return: string("hello, world!")} llvrw.T = t want := errors.New("ubsonv error") valUnmarshaler := &testValueUnmarshaler{err: want} got := dvd.ValueUnmarshalerDecodeValue(dc, llvrw, reflect.ValueOf(valUnmarshaler)) - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Errors do not match. got %v; want %v", got, want) } }) t.Run("ValueUnmarshalerDecodeValue/Unaddressable value", func(t *testing.T) { var dc DecodeContext - llvrw := &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String, Return: string("hello, world!")} + llvrw := &valueReaderWriter{BSONType: TypeString, Return: string("hello, world!")} llvrw.T = t val := reflect.ValueOf(testValueUnmarshaler{}) want := ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val} got := dvd.ValueUnmarshalerDecodeValue(dc, llvrw, val) - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Errors do not match. got %v; want %v", got, want) } }) @@ -2475,7 +2476,7 @@ func TestDefaultValueDecoders(t *testing.T) { var val []string want := ValueDecoderError{Name: "SliceDecodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: reflect.ValueOf(val)} got := dvd.SliceDecodeValue(DecodeContext{}, nil, reflect.ValueOf(val)) - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Errors do not match. got %v; want %v", got, want) } }) @@ -2488,7 +2489,7 @@ func TestDefaultValueDecoders(t *testing.T) { noerr(t, err) doc, err = bsoncore.AppendDocumentEnd(doc, idx) noerr(t, err) - dvr := bsonrw.NewValueReader(doc) + dvr := NewValueReader(doc) noerr(t, err) dr, err := dvr.ReadDocument() noerr(t, err) @@ -2499,14 +2500,14 @@ func TestDefaultValueDecoders(t *testing.T) { dc := DecodeContext{Registry: buildDefaultRegistry()} got := dvd.ArrayDecodeValue(dc, vr, reflect.ValueOf(val)) - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Errors do not match. got %v; want %v", got, want) } }) t.Run("success path", func(t *testing.T) { - oid := primitive.NewObjectID() - oids := []primitive.ObjectID{primitive.NewObjectID(), primitive.NewObjectID(), primitive.NewObjectID()} + oid := NewObjectID() + oids := []ObjectID{NewObjectID(), NewObjectID(), NewObjectID()} var str = new(string) *str = "bar" now := time.Now().Truncate(time.Millisecond).UTC() @@ -2515,7 +2516,7 @@ func TestDefaultValueDecoders(t *testing.T) { t.Errorf("Error parsing URL: %v", err) t.FailNow() } - decimal128, err := primitive.ParseDecimal128("1.5e10") + decimal128, err := ParseDecimal128("1.5e10") if err != nil { t.Errorf("Error parsing decimal128: %v", err) t.FailNow() @@ -2539,8 +2540,8 @@ func TestDefaultValueDecoders(t *testing.T) { nil, }, { - "map[string]primitive.ObjectID", - map[string]primitive.ObjectID{"foo": oid}, + "map[string]ObjectID", + map[string]ObjectID{"foo": oid}, func() []byte { idx, doc := bsoncore.AppendDocumentStart(nil) doc = bsoncore.AppendObjectIDElement(doc, "foo", oid) @@ -2560,8 +2561,8 @@ func TestDefaultValueDecoders(t *testing.T) { nil, }, { - "map[string][]primitive.ObjectID", - map[string][]primitive.ObjectID{"Z": oids}, + "map[string][]ObjectID", + map[string][]ObjectID{"Z": oids}, buildDocumentArray(func(doc []byte) []byte { doc = bsoncore.AppendObjectIDElement(doc, "0", oids[0]) doc = bsoncore.AppendObjectIDElement(doc, "1", oids[1]) @@ -2596,10 +2597,10 @@ func TestDefaultValueDecoders(t *testing.T) { nil, }, { - "map[string][]primitive.Decimal128", - map[string][]primitive.Decimal128{"Z": {decimal128}}, + "map[string][]Decimal128", + map[string][]Decimal128{"Z": {decimal128}}, buildDocumentArray(func(doc []byte) []byte { - return bsoncore.AppendDecimal128Element(doc, "0", decimal128) + return bsoncore.AppendDecimal128Element(doc, "0", decimal128.h, decimal128.l) }), nil, }, @@ -2832,35 +2833,35 @@ func TestDefaultValueDecoders(t *testing.T) { L struct { M string } - Q primitive.ObjectID + Q ObjectID T []struct{} Y json.Number Z time.Time AA json.Number AB *url.URL - AC primitive.Decimal128 + AC Decimal128 AD *time.Time AE *testValueUnmarshaler AF *bool AG *bool AH *int32 AI *int64 - AJ *primitive.ObjectID - AK *primitive.ObjectID + AJ *ObjectID + AK *ObjectID AL testValueUnmarshaler AM interface{} AN interface{} AO interface{} - AP primitive.D - AQ primitive.A - AR [2]primitive.E + AP D + AQ A + AR [2]E AS []byte AT map[string]interface{} - AU primitive.CodeWithScope - AV primitive.M - AW primitive.D + AU CodeWithScope + AV M + AW D AX map[string]interface{} - AY []primitive.E + AY []E AZ interface{} }{ A: true, @@ -2886,28 +2887,28 @@ func TestDefaultValueDecoders(t *testing.T) { AB: murl, AC: decimal128, AD: &now, - AE: &testValueUnmarshaler{t: bsontype.String, val: bsoncore.AppendString(nil, "hello, world!")}, + AE: &testValueUnmarshaler{t: TypeString, val: bsoncore.AppendString(nil, "hello, world!")}, AF: func(b bool) *bool { return &b }(true), AG: nil, AH: func(i32 int32) *int32 { return &i32 }(12345), AI: func(i64 int64) *int64 { return &i64 }(1234567890), AJ: &oid, AK: nil, - AL: testValueUnmarshaler{t: bsontype.String, val: bsoncore.AppendString(nil, "hello, world!")}, + AL: testValueUnmarshaler{t: TypeString, val: bsoncore.AppendString(nil, "hello, world!")}, AM: "hello, world", AN: int32(12345), AO: oid, - AP: primitive.D{{"foo", "bar"}}, - AQ: primitive.A{"foo", "bar"}, - AR: [2]primitive.E{{"hello", "world"}, {"pi", 3.14159}}, + AP: D{{"foo", "bar"}}, + AQ: A{"foo", "bar"}, + AR: [2]E{{"hello", "world"}, {"pi", 3.14159}}, AS: nil, AT: nil, - AU: primitive.CodeWithScope{Code: "var hello = 'world';", Scope: primitive.D{{"pi", 3.14159}}}, - AV: primitive.M{"foo": primitive.M{"bar": "baz"}}, - AW: primitive.D{{"foo", primitive.D{{"bar", "baz"}}}}, + AU: CodeWithScope{Code: "var hello = 'world';", Scope: D{{"pi", 3.14159}}}, + AV: M{"foo": M{"bar": "baz"}}, + AW: D{{"foo", D{{"bar", "baz"}}}}, AX: map[string]interface{}{"foo": map[string]interface{}{"bar": "baz"}}, - AY: []primitive.E{{"foo", []primitive.E{{"bar", "baz"}}}}, - AZ: primitive.D{{"foo", primitive.D{{"bar", "baz"}}}}, + AY: []E{{"foo", []E{{"bar", "baz"}}}}, + AZ: D{{"foo", D{{"bar", "baz"}}}}, }, buildDocument(func(doc []byte) []byte { doc = bsoncore.AppendBooleanElement(doc, "a", true) @@ -2929,7 +2930,7 @@ func TestDefaultValueDecoders(t *testing.T) { doc = bsoncore.AppendDateTimeElement(doc, "z", now.UnixNano()/int64(time.Millisecond)) doc = bsoncore.AppendDoubleElement(doc, "aa", 10.1) doc = bsoncore.AppendStringElement(doc, "ab", murl.String()) - doc = bsoncore.AppendDecimal128Element(doc, "ac", decimal128) + doc = bsoncore.AppendDecimal128Element(doc, "ac", decimal128.h, decimal128.l) doc = bsoncore.AppendDateTimeElement(doc, "ad", now.UnixNano()/int64(time.Millisecond)) doc = bsoncore.AppendStringElement(doc, "ae", "hello, world!") doc = bsoncore.AppendBooleanElement(doc, "af", true) @@ -2982,7 +2983,7 @@ func TestDefaultValueDecoders(t *testing.T) { M string } N [][]string - R []primitive.ObjectID + R []ObjectID T []struct{} W []map[string]struct{} X []map[string]struct{} @@ -2990,16 +2991,16 @@ func TestDefaultValueDecoders(t *testing.T) { Z []time.Time AA []json.Number AB []*url.URL - AC []primitive.Decimal128 + AC []Decimal128 AD []*time.Time AE []*testValueUnmarshaler AF []*bool AG []*int32 AH []*int64 - AI []*primitive.ObjectID - AJ []primitive.D - AK []primitive.A - AL [][2]primitive.E + AI []*ObjectID + AJ []D + AK []A + AL [][2]E }{ A: []bool{true}, B: []int32{123}, @@ -3027,19 +3028,19 @@ func TestDefaultValueDecoders(t *testing.T) { Z: []time.Time{now, now}, AA: []json.Number{json.Number("5"), json.Number("10.1")}, AB: []*url.URL{murl}, - AC: []primitive.Decimal128{decimal128}, + AC: []Decimal128{decimal128}, AD: []*time.Time{&now, &now}, AE: []*testValueUnmarshaler{ - {t: bsontype.String, val: bsoncore.AppendString(nil, "hello")}, - {t: bsontype.String, val: bsoncore.AppendString(nil, "world")}, + {t: TypeString, val: bsoncore.AppendString(nil, "hello")}, + {t: TypeString, val: bsoncore.AppendString(nil, "world")}, }, AF: []*bool{pbool(true), nil}, AG: []*int32{pi32(12345), nil}, AH: []*int64{pi64(1234567890), nil, pi64(9012345678)}, - AI: []*primitive.ObjectID{&oid, nil}, - AJ: []primitive.D{{{"foo", "bar"}}, nil}, - AK: []primitive.A{{"foo", "bar"}, nil}, - AL: [][2]primitive.E{{{"hello", "world"}, {"pi", 3.14159}}}, + AI: []*ObjectID{&oid, nil}, + AJ: []D{{{"foo", "bar"}}, nil}, + AK: []A{{"foo", "bar"}, nil}, + AL: [][2]E{{{"hello", "world"}, {"pi", 3.14159}}}, }, buildDocument(func(doc []byte) []byte { doc = appendArrayElement(doc, "a", bsoncore.AppendBooleanElement(nil, "0", true)) @@ -3080,7 +3081,7 @@ func TestDefaultValueDecoders(t *testing.T) { ) doc = appendArrayElement(doc, "aa", bsoncore.AppendDoubleElement(bsoncore.AppendInt64Element(nil, "0", 5), "1", 10.10)) doc = appendArrayElement(doc, "ab", bsoncore.AppendStringElement(nil, "0", murl.String())) - doc = appendArrayElement(doc, "ac", bsoncore.AppendDecimal128Element(nil, "0", decimal128)) + doc = appendArrayElement(doc, "ac", bsoncore.AppendDecimal128Element(nil, "0", decimal128.h, decimal128.l)) doc = appendArrayElement(doc, "ad", bsoncore.AppendDateTimeElement( bsoncore.AppendDateTimeElement(nil, "0", now.UnixNano()/int64(time.Millisecond)), @@ -3130,9 +3131,16 @@ func TestDefaultValueDecoders(t *testing.T) { } t.Run("Decode", func(t *testing.T) { + compareTime := func(t1, t2 time.Time) bool { + if t1.Location() != t2.Location() { + return false + } + return t1.Equal(t2) + } + for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - vr := bsonrw.NewValueReader(tc.b) + vr := NewValueReader(tc.b) reg := buildDefaultRegistry() vtype := reflect.TypeOf(tc.value) dec, err := reg.LookupDecoder(vtype) @@ -3181,7 +3189,7 @@ func TestDefaultValueDecoders(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - vr := bsonrw.NewValueReader(tc.b) + vr := NewValueReader(tc.b) reg := buildDefaultRegistry() vtype := reflect.TypeOf(tc.value) dec, err := reg.LookupDecoder(vtype) @@ -3201,155 +3209,155 @@ func TestDefaultValueDecoders(t *testing.T) { testCases := []struct { name string val interface{} - bsontype bsontype.Type + bsontype Type }{ { "Double - float64", float64(3.14159), - bsontype.Double, + TypeDouble, }, { "String - string", "foo bar baz", - bsontype.String, + TypeString, }, { - "Array - primitive.A", - primitive.A{3.14159}, - bsontype.Array, + "Array - A", + A{3.14159}, + TypeArray, }, { "Binary - Binary", - primitive.Binary{Subtype: 0xFF, Data: []byte{0x01, 0x02, 0x03}}, - bsontype.Binary, + Binary{Subtype: 0xFF, Data: []byte{0x01, 0x02, 0x03}}, + TypeBinary, }, { "Undefined - Undefined", - primitive.Undefined{}, - bsontype.Undefined, + Undefined{}, + TypeUndefined, }, { - "ObjectID - primitive.ObjectID", - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, - bsontype.ObjectID, + "ObjectID - ObjectID", + ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + TypeObjectID, }, { "Boolean - bool", bool(true), - bsontype.Boolean, + TypeBoolean, }, { "DateTime - DateTime", - primitive.DateTime(1234567890), - bsontype.DateTime, + DateTime(1234567890), + TypeDateTime, }, { "Null - Null", nil, - bsontype.Null, + TypeNull, }, { "Regex - Regex", - primitive.Regex{Pattern: "foo", Options: "bar"}, - bsontype.Regex, + Regex{Pattern: "foo", Options: "bar"}, + TypeRegex, }, { "DBPointer - DBPointer", - primitive.DBPointer{ + DBPointer{ DB: "foobar", - Pointer: primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + Pointer: ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, }, - bsontype.DBPointer, + TypeDBPointer, }, { "JavaScript - JavaScript", - primitive.JavaScript("var foo = 'bar';"), - bsontype.JavaScript, + JavaScript("var foo = 'bar';"), + TypeJavaScript, }, { "Symbol - Symbol", - primitive.Symbol("foobarbazlolz"), - bsontype.Symbol, + Symbol("foobarbazlolz"), + TypeSymbol, }, { "Int32 - int32", int32(123456), - bsontype.Int32, + TypeInt32, }, { "Int64 - int64", int64(1234567890), - bsontype.Int64, + TypeInt64, }, { "Timestamp - Timestamp", - primitive.Timestamp{T: 12345, I: 67890}, - bsontype.Timestamp, + Timestamp{T: 12345, I: 67890}, + TypeTimestamp, }, { "Decimal128 - decimal.Decimal128", - primitive.NewDecimal128(12345, 67890), - bsontype.Decimal128, + NewDecimal128(12345, 67890), + TypeDecimal128, }, { "MinKey - MinKey", - primitive.MinKey{}, - bsontype.MinKey, + MinKey{}, + TypeMinKey, }, { "MaxKey - MaxKey", - primitive.MaxKey{}, - bsontype.MaxKey, + MaxKey{}, + TypeMaxKey, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - llvr := &bsonrwtest.ValueReaderWriter{BSONType: tc.bsontype} + llvr := &valueReaderWriter{BSONType: tc.bsontype} t.Run("Type Map failure", func(t *testing.T) { - if tc.bsontype == bsontype.Null { + if tc.bsontype == TypeNull { t.Skip() } val := reflect.New(tEmpty).Elem() - dc := DecodeContext{Registry: NewRegistryBuilder().Build()} + dc := DecodeContext{Registry: newTestRegistryBuilder().Build()} want := ErrNoTypeMapEntry{Type: tc.bsontype} got := defaultEmptyInterfaceCodec.DecodeValue(dc, llvr, val) - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Errors are not equal. got %v; want %v", got, want) } }) t.Run("Lookup failure", func(t *testing.T) { - if tc.bsontype == bsontype.Null { + if tc.bsontype == TypeNull { t.Skip() } val := reflect.New(tEmpty).Elem() dc := DecodeContext{ - Registry: NewRegistryBuilder(). + Registry: newTestRegistryBuilder(). RegisterTypeMapEntry(tc.bsontype, reflect.TypeOf(tc.val)). Build(), } want := ErrNoDecoder{Type: reflect.TypeOf(tc.val)} got := defaultEmptyInterfaceCodec.DecodeValue(dc, llvr, val) - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Errors are not equal. got %v; want %v", got, want) } }) t.Run("DecodeValue failure", func(t *testing.T) { - if tc.bsontype == bsontype.Null { + if tc.bsontype == TypeNull { t.Skip() } want := errors.New("DecodeValue failure error") llc := &llCodec{t: t, err: want} dc := DecodeContext{ - Registry: NewRegistryBuilder(). + Registry: newTestRegistryBuilder(). RegisterTypeDecoder(reflect.TypeOf(tc.val), llc). RegisterTypeMapEntry(tc.bsontype, reflect.TypeOf(tc.val)). Build(), } got := defaultEmptyInterfaceCodec.DecodeValue(dc, llvr, reflect.New(tEmpty).Elem()) - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Errors are not equal. got %v; want %v", got, want) } }) @@ -3358,7 +3366,7 @@ func TestDefaultValueDecoders(t *testing.T) { want := tc.val llc := &llCodec{t: t, decodeval: tc.val} dc := DecodeContext{ - Registry: NewRegistryBuilder(). + Registry: newTestRegistryBuilder(). RegisterTypeDecoder(reflect.TypeOf(tc.val), llc). RegisterTypeMapEntry(tc.bsontype, reflect.TypeOf(tc.val)). Build(), @@ -3378,7 +3386,7 @@ func TestDefaultValueDecoders(t *testing.T) { val := uint64(1234567890) want := ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: reflect.ValueOf(val)} got := defaultEmptyInterfaceCodec.DecodeValue(DecodeContext{}, nil, reflect.ValueOf(val)) - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Errors are not equal. got %v; want %v", got, want) } }) @@ -3387,24 +3395,24 @@ func TestDefaultValueDecoders(t *testing.T) { var val interface{} want := ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: reflect.ValueOf(val)} got := defaultEmptyInterfaceCodec.DecodeValue(DecodeContext{}, nil, reflect.ValueOf(val)) - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Errors are not equal. got %v; want %v", got, want) } }) t.Run("no type registered", func(t *testing.T) { - llvr := &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Double} - want := ErrNoTypeMapEntry{Type: bsontype.Double} + llvr := &valueReaderWriter{BSONType: TypeDouble} + want := ErrNoTypeMapEntry{Type: TypeDouble} val := reflect.New(tEmpty).Elem() - got := defaultEmptyInterfaceCodec.DecodeValue(DecodeContext{Registry: NewRegistryBuilder().Build()}, llvr, val) - if !compareErrors(got, want) { + got := defaultEmptyInterfaceCodec.DecodeValue(DecodeContext{Registry: newTestRegistryBuilder().Build()}, llvr, val) + if !assert.CompareErrors(got, want) { t.Errorf("Errors are not equal. got %v; want %v", got, want) } }) t.Run("top level document", func(t *testing.T) { data := bsoncore.BuildDocument(nil, bsoncore.AppendDoubleElement(nil, "pi", 3.14159)) - vr := bsonrw.NewValueReader(data) - want := primitive.D{{"pi", 3.14159}} + vr := NewValueReader(data) + want := D{{"pi", 3.14159}} var got interface{} val := reflect.ValueOf(&got).Elem() err := defaultEmptyInterfaceCodec.DecodeValue(DecodeContext{Registry: buildDefaultRegistry()}, vr, val) @@ -3414,18 +3422,18 @@ func TestDefaultValueDecoders(t *testing.T) { } }) t.Run("custom type map entry", func(t *testing.T) { - // registering a custom type map entry for both bsontype.Type(0) anad bsontype.EmbeddedDocument should cause + // registering a custom type map entry for both Type(0) anad TypeEmbeddedDocument should cause // both top-level and embedded documents to decode to registered type when unmarshalling to interface{} - topLevelRb := NewRegistryBuilder() + topLevelRb := newTestRegistryBuilder() defaultValueEncoders.RegisterDefaultEncoders(topLevelRb) defaultValueDecoders.RegisterDefaultDecoders(topLevelRb) - topLevelRb.RegisterTypeMapEntry(bsontype.Type(0), reflect.TypeOf(primitive.M{})) + topLevelRb.RegisterTypeMapEntry(Type(0), reflect.TypeOf(M{})) - embeddedRb := NewRegistryBuilder() + embeddedRb := newTestRegistryBuilder() defaultValueEncoders.RegisterDefaultEncoders(embeddedRb) defaultValueDecoders.RegisterDefaultDecoders(embeddedRb) - embeddedRb.RegisterTypeMapEntry(bsontype.Type(0), reflect.TypeOf(primitive.M{})) + embeddedRb.RegisterTypeMapEntry(Type(0), reflect.TypeOf(M{})) // create doc {"nested": {"foo": 1}} innerDoc := bsoncore.BuildDocument( @@ -3436,8 +3444,8 @@ func TestDefaultValueDecoders(t *testing.T) { nil, bsoncore.AppendDocumentElement(nil, "nested", innerDoc), ) - want := primitive.M{ - "nested": primitive.M{ + want := M{ + "nested": M{ "foo": int32(1), }, } @@ -3451,7 +3459,7 @@ func TestDefaultValueDecoders(t *testing.T) { } for _, tc := range testCases { var got interface{} - vr := bsonrw.NewValueReader(doc) + vr := NewValueReader(doc) val := reflect.ValueOf(&got).Elem() err := defaultEmptyInterfaceCodec.DecodeValue(DecodeContext{Registry: tc.registry}, vr, val) @@ -3462,13 +3470,13 @@ func TestDefaultValueDecoders(t *testing.T) { } }) t.Run("ancestor info is used over custom type map entry", func(t *testing.T) { - // If a type map entry is registered for bsontype.EmbeddedDocument, the decoder should use ancestor + // If a type map entry is registered for TypeEmbeddedDocument, the decoder should use ancestor // information if available instead of the registered entry. - rb := NewRegistryBuilder() + rb := newTestRegistryBuilder() defaultValueEncoders.RegisterDefaultEncoders(rb) defaultValueDecoders.RegisterDefaultDecoders(rb) - rb.RegisterTypeMapEntry(bsontype.EmbeddedDocument, reflect.TypeOf(primitive.M{})) + rb.RegisterTypeMapEntry(TypeEmbeddedDocument, reflect.TypeOf(M{})) reg := rb.Build() // build document {"nested": {"foo": 10}} @@ -3480,14 +3488,14 @@ func TestDefaultValueDecoders(t *testing.T) { nil, bsoncore.AppendDocumentElement(nil, "nested", inner), ) - want := primitive.D{ - {"nested", primitive.D{ + want := D{ + {"nested", D{ {"foo", int32(10)}, }}, } - var got primitive.D - vr := bsonrw.NewValueReader(doc) + var got D + vr := NewValueReader(doc) val := reflect.ValueOf(&got).Elem() err := defaultSliceCodec.DecodeValue(DecodeContext{Registry: reg}, vr, val) noerr(t, err) @@ -3499,10 +3507,10 @@ func TestDefaultValueDecoders(t *testing.T) { t.Run("decode errors contain key information", func(t *testing.T) { decodeValueError := errors.New("decode value error") - emptyInterfaceErrorDecode := func(DecodeContext, bsonrw.ValueReader, reflect.Value) error { + emptyInterfaceErrorDecode := func(DecodeContext, ValueReader, reflect.Value) error { return decodeValueError } - emptyInterfaceErrorRegistry := NewRegistryBuilder(). + emptyInterfaceErrorRegistry := newTestRegistryBuilder(). RegisterTypeDecoder(tEmpty, ValueDecoderFunc(emptyInterfaceErrorDecode)).Build() // Set up a document {foo: 10} and an error that would happen if the value were decoded into interface{} @@ -3555,7 +3563,7 @@ func TestDefaultValueDecoders(t *testing.T) { outerDoc := buildDocument(bsoncore.AppendDocumentElement(nil, "first", inner1Doc)) // Use a registry that has all default decoders with the custom interface{} decoder that always errors. - nestedRegistryBuilder := NewRegistryBuilder() + nestedRegistryBuilder := newTestRegistryBuilder() defaultValueDecoders.RegisterDefaultDecoders(nestedRegistryBuilder) nestedRegistry := nestedRegistryBuilder. RegisterTypeDecoder(tEmpty, ValueDecoderFunc(emptyInterfaceErrorDecode)). @@ -3568,16 +3576,16 @@ func TestDefaultValueDecoders(t *testing.T) { testCases := []struct { name string val interface{} - vr bsonrw.ValueReader + vr ValueReader registry *Registry // buildDefaultRegistry will be used if this is nil decoder ValueDecoder err error }{ { - // DecodeValue error when decoding into a primitive.D. - "primitive.D slice", - primitive.D{}, - bsonrw.NewValueReader(docBytes), + // DecodeValue error when decoding into a D. + "D slice", + D{}, + NewValueReader(docBytes), emptyInterfaceErrorRegistry, defaultSliceCodec, docEmptyInterfaceErr, @@ -3586,7 +3594,7 @@ func TestDefaultValueDecoders(t *testing.T) { // DecodeValue error when decoding into a []string. "string slice", []string{}, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Array}, + &valueReaderWriter{BSONType: TypeArray}, nil, defaultSliceCodec, &DecodeError{ @@ -3595,23 +3603,23 @@ func TestDefaultValueDecoders(t *testing.T) { }, }, { - // DecodeValue error when decoding into a primitive.E array. This should have the same behavior as - // the "primitive.D slice" test above because both the defaultSliceCodec and ArrayDecodeValue use + // DecodeValue error when decoding into a E array. This should have the same behavior as + // the "D slice" test above because both the defaultSliceCodec and ArrayDecodeValue use // the decodeD helper function. - "primitive.D array", - [1]primitive.E{}, - bsonrw.NewValueReader(docBytes), + "D array", + [1]E{}, + NewValueReader(docBytes), emptyInterfaceErrorRegistry, ValueDecoderFunc(dvd.ArrayDecodeValue), docEmptyInterfaceErr, }, { // DecodeValue error when decoding into a string array. This should have the same behavior as - // the "primitive.D slice" test above because both the defaultSliceCodec and ArrayDecodeValue use + // the "D slice" test above because both the defaultSliceCodec and ArrayDecodeValue use // the decodeDefault helper function. "string array", [1]string{}, - &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Array}, + &valueReaderWriter{BSONType: TypeArray}, nil, ValueDecoderFunc(dvd.ArrayDecodeValue), &DecodeError{ @@ -3623,7 +3631,7 @@ func TestDefaultValueDecoders(t *testing.T) { // DecodeValue error when decoding into a map. "map", map[string]interface{}{}, - bsonrw.NewValueReader(docBytes), + NewValueReader(docBytes), emptyInterfaceErrorRegistry, defaultMapCodec, docEmptyInterfaceErr, @@ -3632,7 +3640,7 @@ func TestDefaultValueDecoders(t *testing.T) { // DecodeValue error when decoding into a struct. "struct - DecodeValue error", emptyInterfaceStruct{}, - bsonrw.NewValueReader(docBytes), + NewValueReader(docBytes), emptyInterfaceErrorRegistry, defaultTestStructCodec, emptyInterfaceStructErr, @@ -3643,15 +3651,15 @@ func TestDefaultValueDecoders(t *testing.T) { // no decoder for strings. "struct - no decoder found", stringStruct{}, - bsonrw.NewValueReader(docBytes), - NewRegistryBuilder().Build(), + NewValueReader(docBytes), + newTestRegistryBuilder().Build(), defaultTestStructCodec, stringStructErr, }, { "deeply nested struct", outer{}, - bsonrw.NewValueReader(outerDoc), + NewValueReader(outerDoc), nestedRegistry, defaultTestStructCodec, nestedErr, @@ -3681,7 +3689,7 @@ func TestDefaultValueDecoders(t *testing.T) { type outer struct{ Foo inner } dc := DecodeContext{Registry: buildDefaultRegistry()} - vr := bsonrw.NewValueReader(outerBytes) + vr := NewValueReader(outerBytes) val := reflect.New(reflect.TypeOf(outer{})).Elem() err := defaultTestStructCodec.DecodeValue(dc, vr, val) @@ -3701,7 +3709,7 @@ func TestDefaultValueDecoders(t *testing.T) { t.Run("D", func(t *testing.T) { trueValue := bsoncore.Value{ - Type: bsontype.Boolean, + Type: bsoncore.TypeBoolean, Data: bsoncore.AppendBoolean(nil, true), } docBytes := bsoncore.BuildDocumentFromElements(nil, @@ -3709,21 +3717,21 @@ func TestDefaultValueDecoders(t *testing.T) { bsoncore.BuildArrayElement(nil, "boolArray", trueValue), ) - rb := NewRegistryBuilder() + rb := newTestRegistryBuilder() defaultValueDecoders.RegisterDefaultDecoders(rb) - reg := rb.RegisterTypeMapEntry(bsontype.Boolean, reflect.TypeOf(mybool(true))).Build() + reg := rb.RegisterTypeMapEntry(TypeBoolean, reflect.TypeOf(mybool(true))).Build() dc := DecodeContext{Registry: reg} - vr := bsonrw.NewValueReader(docBytes) + vr := NewValueReader(docBytes) val := reflect.New(tD).Elem() err := defaultValueDecoders.DDecodeValue(dc, vr, val) assert.Nil(t, err, "DDecodeValue error: %v", err) - want := primitive.D{ + want := D{ {"bool", mybool(true)}, - {"boolArray", primitive.A{mybool(true)}}, + {"boolArray", A{mybool(true)}}, } - got := val.Interface().(primitive.D) + got := val.Interface().(D) assert.Equal(t, want, got, "want document %v, got %v", want, got) }) t.Run("M", func(t *testing.T) { @@ -3733,7 +3741,7 @@ func TestDefaultValueDecoders(t *testing.T) { type myMap map[string]mybool dc := DecodeContext{Registry: buildDefaultRegistry()} - vr := bsonrw.NewValueReader(docBytes) + vr := NewValueReader(docBytes) val := reflect.New(reflect.TypeOf(myMap{})).Elem() err := defaultMapCodec.DecodeValue(dc, vr, val) assert.Nil(t, err, "DecodeValue error: %v", err) @@ -3747,31 +3755,6 @@ func TestDefaultValueDecoders(t *testing.T) { }) } -type testValueUnmarshaler struct { - t bsontype.Type - val []byte - err error -} - -func (tvu *testValueUnmarshaler) UnmarshalBSONValue(t bsontype.Type, val []byte) error { - tvu.t, tvu.val = t, val - return tvu.err -} - -type testUnmarshaler struct { - Val []byte - Err error -} - -func (tvu *testUnmarshaler) UnmarshalBSON(val []byte) error { - tvu.Val = val - return tvu.Err -} - -func (tvu testValueUnmarshaler) Equal(tvu2 testValueUnmarshaler) bool { - return tvu.t == tvu2.t && bytes.Equal(tvu.val, tvu2.val) -} - // buildDocumentArray inserts vals inside of an array inside of a document. func buildDocumentArray(fn func([]byte) []byte) []byte { aix, doc := bsoncore.AppendArrayElementStart(nil, "Z") @@ -3803,7 +3786,7 @@ func buildDocument(elems []byte) []byte { } func buildDefaultRegistry() *Registry { - rb := NewRegistryBuilder() + rb := newTestRegistryBuilder() defaultValueEncoders.RegisterDefaultEncoders(rb) defaultValueDecoders.RegisterDefaultDecoders(rb) return rb.Build() diff --git a/bson/bsoncodec/default_value_encoders.go b/bson/default_value_encoders.go similarity index 89% rename from bson/bsoncodec/default_value_encoders.go rename to bson/default_value_encoders.go index 4751ae995e..f2773c36e5 100644 --- a/bson/bsoncodec/default_value_encoders.go +++ b/bson/default_value_encoders.go @@ -4,7 +4,7 @@ // 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 +package bson import ( "encoding/json" @@ -16,26 +16,23 @@ import ( "sync" "time" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) var defaultValueEncoders DefaultValueEncoders -var bvwPool = bsonrw.NewBSONValueWriterPool() +var bvwPool = NewValueWriterPool() var errInvalidValue = errors.New("cannot encode invalid element") var sliceWriterPool = sync.Pool{ New: func() interface{} { - sw := make(bsonrw.SliceWriter, 0) + sw := make(SliceWriter, 0) return &sw }, } -func encodeElement(ec EncodeContext, dw bsonrw.DocumentWriter, e primitive.E) error { +func encodeElement(ec EncodeContext, dw DocumentWriter, e E) error { vw, err := dw.WriteDocumentElement(e.Key) if err != nil { return err @@ -122,7 +119,7 @@ func (dve DefaultValueEncoders) RegisterDefaultEncoders(rb *RegistryBuilder) { // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (dve DefaultValueEncoders) BooleanEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) BooleanEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Kind() != reflect.Bool { return ValueEncoderError{Name: "BooleanEncodeValue", Kinds: []reflect.Kind{reflect.Bool}, Received: val} } @@ -137,7 +134,7 @@ func fitsIn32Bits(i int64) bool { // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (dve DefaultValueEncoders) IntEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) IntEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { switch val.Kind() { case reflect.Int8, reflect.Int16, reflect.Int32: return vw.WriteInt32(int32(val.Int())) @@ -165,7 +162,7 @@ func (dve DefaultValueEncoders) IntEncodeValue(ec EncodeContext, vw bsonrw.Value // UintEncodeValue is the ValueEncoderFunc for uint types. // // Deprecated: UintEncodeValue is not registered by default. Use UintCodec.EncodeValue instead. -func (dve DefaultValueEncoders) UintEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) UintEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { switch val.Kind() { case reflect.Uint8, reflect.Uint16: return vw.WriteInt32(int32(val.Uint())) @@ -191,7 +188,7 @@ func (dve DefaultValueEncoders) UintEncodeValue(ec EncodeContext, vw bsonrw.Valu // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (dve DefaultValueEncoders) FloatEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) FloatEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { switch val.Kind() { case reflect.Float32, reflect.Float64: return vw.WriteDouble(val.Float()) @@ -203,7 +200,7 @@ func (dve DefaultValueEncoders) FloatEncodeValue(_ EncodeContext, vw bsonrw.Valu // StringEncodeValue is the ValueEncoderFunc for string types. // // Deprecated: StringEncodeValue is not registered by default. Use StringCodec.EncodeValue instead. -func (dve DefaultValueEncoders) StringEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) StringEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if val.Kind() != reflect.String { return ValueEncoderError{ Name: "StringEncodeValue", @@ -215,33 +212,33 @@ func (dve DefaultValueEncoders) StringEncodeValue(_ EncodeContext, vw bsonrw.Val return vw.WriteString(val.String()) } -// ObjectIDEncodeValue is the ValueEncoderFunc for primitive.ObjectID. +// ObjectIDEncodeValue is the ValueEncoderFunc for ObjectID. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (dve DefaultValueEncoders) ObjectIDEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) ObjectIDEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tOID { return ValueEncoderError{Name: "ObjectIDEncodeValue", Types: []reflect.Type{tOID}, Received: val} } - return vw.WriteObjectID(val.Interface().(primitive.ObjectID)) + return vw.WriteObjectID(val.Interface().(ObjectID)) } -// Decimal128EncodeValue is the ValueEncoderFunc for primitive.Decimal128. +// Decimal128EncodeValue is the ValueEncoderFunc for Decimal128. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (dve DefaultValueEncoders) Decimal128EncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) Decimal128EncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tDecimal { return ValueEncoderError{Name: "Decimal128EncodeValue", Types: []reflect.Type{tDecimal}, Received: val} } - return vw.WriteDecimal128(val.Interface().(primitive.Decimal128)) + return vw.WriteDecimal128(val.Interface().(Decimal128)) } // JSONNumberEncodeValue is the ValueEncoderFunc for json.Number. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (dve DefaultValueEncoders) JSONNumberEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) JSONNumberEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tJSONNumber { return ValueEncoderError{Name: "JSONNumberEncodeValue", Types: []reflect.Type{tJSONNumber}, Received: val} } @@ -264,7 +261,7 @@ func (dve DefaultValueEncoders) JSONNumberEncodeValue(ec EncodeContext, vw bsonr // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (dve DefaultValueEncoders) URLEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) URLEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tURL { return ValueEncoderError{Name: "URLEncodeValue", Types: []reflect.Type{tURL}, Received: val} } @@ -275,19 +272,19 @@ func (dve DefaultValueEncoders) URLEncodeValue(_ EncodeContext, vw bsonrw.ValueW // TimeEncodeValue is the ValueEncoderFunc for time.TIme. // // Deprecated: TimeEncodeValue is not registered by default. Use TimeCodec.EncodeValue instead. -func (dve DefaultValueEncoders) TimeEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) TimeEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tTime { return ValueEncoderError{Name: "TimeEncodeValue", Types: []reflect.Type{tTime}, Received: val} } tt := val.Interface().(time.Time) - dt := primitive.NewDateTimeFromTime(tt) + dt := NewDateTimeFromTime(tt) return vw.WriteDateTime(int64(dt)) } // ByteSliceEncodeValue is the ValueEncoderFunc for []byte. // // Deprecated: ByteSliceEncodeValue is not registered by default. Use ByteSliceCodec.EncodeValue instead. -func (dve DefaultValueEncoders) ByteSliceEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) ByteSliceEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tByteSlice { return ValueEncoderError{Name: "ByteSliceEncodeValue", Types: []reflect.Type{tByteSlice}, Received: val} } @@ -300,7 +297,7 @@ func (dve DefaultValueEncoders) ByteSliceEncodeValue(_ EncodeContext, vw bsonrw. // MapEncodeValue is the ValueEncoderFunc for map[string]* types. // // Deprecated: MapEncodeValue is not registered by default. Use MapCodec.EncodeValue instead. -func (dve DefaultValueEncoders) MapEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) MapEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Kind() != reflect.Map || val.Type().Key().Kind() != reflect.String { return ValueEncoderError{Name: "MapEncodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val} } @@ -328,7 +325,7 @@ func (dve DefaultValueEncoders) MapEncodeValue(ec EncodeContext, vw bsonrw.Value // mapEncodeValue handles encoding of the values of a map. The collisionFn returns // true if the provided key exists, this is mainly used for inline maps in the // struct codec. -func (dve DefaultValueEncoders) mapEncodeValue(ec EncodeContext, dw bsonrw.DocumentWriter, val reflect.Value, collisionFn func(string) bool) error { +func (dve DefaultValueEncoders) mapEncodeValue(ec EncodeContext, dw DocumentWriter, val reflect.Value, collisionFn func(string) bool) error { elemType := val.Type().Elem() encoder, err := ec.LookupEncoder(elemType) @@ -373,12 +370,12 @@ func (dve DefaultValueEncoders) mapEncodeValue(ec EncodeContext, dw bsonrw.Docum // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (dve DefaultValueEncoders) ArrayEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) ArrayEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Kind() != reflect.Array { return ValueEncoderError{Name: "ArrayEncodeValue", Kinds: []reflect.Kind{reflect.Array}, Received: val} } - // If we have a []primitive.E we want to treat it as a document instead of as an array. + // If we have a []E we want to treat it as a document instead of as an array. if val.Type().Elem() == tE { dw, err := vw.WriteDocument() if err != nil { @@ -386,7 +383,7 @@ func (dve DefaultValueEncoders) ArrayEncodeValue(ec EncodeContext, vw bsonrw.Val } for idx := 0; idx < val.Len(); idx++ { - e := val.Index(idx).Interface().(primitive.E) + e := val.Index(idx).Interface().(E) err = encodeElement(ec, dw, e) if err != nil { return err @@ -446,7 +443,7 @@ func (dve DefaultValueEncoders) ArrayEncodeValue(ec EncodeContext, vw bsonrw.Val // SliceEncodeValue is the ValueEncoderFunc for slice types. // // Deprecated: SliceEncodeValue is not registered by default. Use SliceCodec.EncodeValue instead. -func (dve DefaultValueEncoders) SliceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) SliceEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Kind() != reflect.Slice { return ValueEncoderError{Name: "SliceEncodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val} } @@ -455,9 +452,9 @@ func (dve DefaultValueEncoders) SliceEncodeValue(ec EncodeContext, vw bsonrw.Val return vw.WriteNull() } - // If we have a []primitive.E we want to treat it as a document instead of as an array. + // If we have a []E we want to treat it as a document instead of as an array. if val.Type().ConvertibleTo(tD) { - d := val.Convert(tD).Interface().(primitive.D) + d := val.Convert(tD).Interface().(D) dw, err := vw.WriteDocument() if err != nil { @@ -528,7 +525,7 @@ func (dve DefaultValueEncoders) lookupElementEncoder(ec EncodeContext, origEncod // EmptyInterfaceEncodeValue is the ValueEncoderFunc for interface{}. // // Deprecated: EmptyInterfaceEncodeValue is not registered by default. Use EmptyInterfaceCodec.EncodeValue instead. -func (dve DefaultValueEncoders) EmptyInterfaceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) EmptyInterfaceEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tEmpty { return ValueEncoderError{Name: "EmptyInterfaceEncodeValue", Types: []reflect.Type{tEmpty}, Received: val} } @@ -548,7 +545,7 @@ func (dve DefaultValueEncoders) EmptyInterfaceEncodeValue(ec EncodeContext, vw b // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (dve DefaultValueEncoders) ValueMarshalerEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) ValueMarshalerEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { // Either val or a pointer to val must implement ValueMarshaler switch { case !val.IsValid(): @@ -572,14 +569,14 @@ func (dve DefaultValueEncoders) ValueMarshalerEncodeValue(_ EncodeContext, vw bs if err != nil { return err } - return bsonrw.Copier{}.CopyValueFromBytes(vw, t, data) + return copyValueFromBytes(vw, t, data) } // MarshalerEncodeValue is the ValueEncoderFunc for Marshaler implementations. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (dve DefaultValueEncoders) MarshalerEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) MarshalerEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { // Either val or a pointer to val must implement Marshaler switch { case !val.IsValid(): @@ -603,14 +600,14 @@ func (dve DefaultValueEncoders) MarshalerEncodeValue(_ EncodeContext, vw bsonrw. if err != nil { return err } - return bsonrw.Copier{}.CopyValueFromBytes(vw, bsontype.EmbeddedDocument, data) + return copyValueFromBytes(vw, TypeEmbeddedDocument, data) } // ProxyEncodeValue is the ValueEncoderFunc for Proxy implementations. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (dve DefaultValueEncoders) ProxyEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) ProxyEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { // Either val or a pointer to val must implement Proxy switch { case !val.IsValid(): @@ -653,11 +650,11 @@ func (dve DefaultValueEncoders) ProxyEncodeValue(ec EncodeContext, vw bsonrw.Val return encoder.EncodeValue(ec, vw, vv) } -// JavaScriptEncodeValue is the ValueEncoderFunc for the primitive.JavaScript type. +// JavaScriptEncodeValue is the ValueEncoderFunc for the JavaScript type. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (DefaultValueEncoders) JavaScriptEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (DefaultValueEncoders) JavaScriptEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tJavaScript { return ValueEncoderError{Name: "JavaScriptEncodeValue", Types: []reflect.Type{tJavaScript}, Received: val} } @@ -665,11 +662,11 @@ func (DefaultValueEncoders) JavaScriptEncodeValue(_ EncodeContext, vw bsonrw.Val return vw.WriteJavascript(val.String()) } -// SymbolEncodeValue is the ValueEncoderFunc for the primitive.Symbol type. +// SymbolEncodeValue is the ValueEncoderFunc for the Symbol type. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (DefaultValueEncoders) SymbolEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (DefaultValueEncoders) SymbolEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tSymbol { return ValueEncoderError{Name: "SymbolEncodeValue", Types: []reflect.Type{tSymbol}, Received: val} } @@ -681,11 +678,11 @@ func (DefaultValueEncoders) SymbolEncodeValue(_ EncodeContext, vw bsonrw.ValueWr // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (DefaultValueEncoders) BinaryEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (DefaultValueEncoders) BinaryEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tBinary { return ValueEncoderError{Name: "BinaryEncodeValue", Types: []reflect.Type{tBinary}, Received: val} } - b := val.Interface().(primitive.Binary) + b := val.Interface().(Binary) return vw.WriteBinaryWithSubtype(b.Data, b.Subtype) } @@ -694,7 +691,7 @@ func (DefaultValueEncoders) BinaryEncodeValue(_ EncodeContext, vw bsonrw.ValueWr // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (DefaultValueEncoders) UndefinedEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (DefaultValueEncoders) UndefinedEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tUndefined { return ValueEncoderError{Name: "UndefinedEncodeValue", Types: []reflect.Type{tUndefined}, Received: val} } @@ -706,7 +703,7 @@ func (DefaultValueEncoders) UndefinedEncodeValue(_ EncodeContext, vw bsonrw.Valu // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (DefaultValueEncoders) DateTimeEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (DefaultValueEncoders) DateTimeEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tDateTime { return ValueEncoderError{Name: "DateTimeEncodeValue", Types: []reflect.Type{tDateTime}, Received: val} } @@ -718,7 +715,7 @@ func (DefaultValueEncoders) DateTimeEncodeValue(_ EncodeContext, vw bsonrw.Value // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (DefaultValueEncoders) NullEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (DefaultValueEncoders) NullEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tNull { return ValueEncoderError{Name: "NullEncodeValue", Types: []reflect.Type{tNull}, Received: val} } @@ -730,12 +727,12 @@ func (DefaultValueEncoders) NullEncodeValue(_ EncodeContext, vw bsonrw.ValueWrit // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (DefaultValueEncoders) RegexEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (DefaultValueEncoders) RegexEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tRegex { return ValueEncoderError{Name: "RegexEncodeValue", Types: []reflect.Type{tRegex}, Received: val} } - regex := val.Interface().(primitive.Regex) + regex := val.Interface().(Regex) return vw.WriteRegex(regex.Pattern, regex.Options) } @@ -744,12 +741,12 @@ func (DefaultValueEncoders) RegexEncodeValue(_ EncodeContext, vw bsonrw.ValueWri // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (DefaultValueEncoders) DBPointerEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (DefaultValueEncoders) DBPointerEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tDBPointer { return ValueEncoderError{Name: "DBPointerEncodeValue", Types: []reflect.Type{tDBPointer}, Received: val} } - dbp := val.Interface().(primitive.DBPointer) + dbp := val.Interface().(DBPointer) return vw.WriteDBPointer(dbp.DB, dbp.Pointer) } @@ -758,12 +755,12 @@ func (DefaultValueEncoders) DBPointerEncodeValue(_ EncodeContext, vw bsonrw.Valu // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (DefaultValueEncoders) TimestampEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (DefaultValueEncoders) TimestampEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tTimestamp { return ValueEncoderError{Name: "TimestampEncodeValue", Types: []reflect.Type{tTimestamp}, Received: val} } - ts := val.Interface().(primitive.Timestamp) + ts := val.Interface().(Timestamp) return vw.WriteTimestamp(ts.T, ts.I) } @@ -772,7 +769,7 @@ func (DefaultValueEncoders) TimestampEncodeValue(_ EncodeContext, vw bsonrw.Valu // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (DefaultValueEncoders) MinKeyEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (DefaultValueEncoders) MinKeyEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tMinKey { return ValueEncoderError{Name: "MinKeyEncodeValue", Types: []reflect.Type{tMinKey}, Received: val} } @@ -784,7 +781,7 @@ func (DefaultValueEncoders) MinKeyEncodeValue(_ EncodeContext, vw bsonrw.ValueWr // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (DefaultValueEncoders) MaxKeyEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (DefaultValueEncoders) MaxKeyEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tMaxKey { return ValueEncoderError{Name: "MaxKeyEncodeValue", Types: []reflect.Type{tMaxKey}, Received: val} } @@ -796,33 +793,33 @@ func (DefaultValueEncoders) MaxKeyEncodeValue(_ EncodeContext, vw bsonrw.ValueWr // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (DefaultValueEncoders) CoreDocumentEncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (DefaultValueEncoders) CoreDocumentEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tCoreDocument { return ValueEncoderError{Name: "CoreDocumentEncodeValue", Types: []reflect.Type{tCoreDocument}, Received: val} } cdoc := val.Interface().(bsoncore.Document) - return bsonrw.Copier{}.CopyDocumentFromBytes(vw, cdoc) + return copyDocumentFromBytes(vw, cdoc) } // CodeWithScopeEncodeValue is the ValueEncoderFunc for CodeWithScope. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default // value encoders registered. -func (dve DefaultValueEncoders) CodeWithScopeEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (dve DefaultValueEncoders) CodeWithScopeEncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tCodeWithScope { return ValueEncoderError{Name: "CodeWithScopeEncodeValue", Types: []reflect.Type{tCodeWithScope}, Received: val} } - cws := val.Interface().(primitive.CodeWithScope) + cws := val.Interface().(CodeWithScope) dw, err := vw.WriteCodeWithScope(string(cws.Code)) if err != nil { return err } - sw := sliceWriterPool.Get().(*bsonrw.SliceWriter) + sw := sliceWriterPool.Get().(*SliceWriter) defer sliceWriterPool.Put(sw) *sw = (*sw)[:0] @@ -839,7 +836,7 @@ func (dve DefaultValueEncoders) CodeWithScopeEncodeValue(ec EncodeContext, vw bs return err } - err = bsonrw.Copier{}.CopyBytesToDocumentWriter(dw, *sw) + err = copyBytesToDocumentWriter(dw, *sw) if err != nil { return err } diff --git a/bson/bsoncodec/default_value_encoders_test.go b/bson/default_value_encoders_test.go similarity index 74% rename from bson/bsoncodec/default_value_encoders_test.go rename to bson/default_value_encoders_test.go index 81f6d84f0f..481c6cb1a1 100644 --- a/bson/bsoncodec/default_value_encoders_test.go +++ b/bson/default_value_encoders_test.go @@ -4,7 +4,7 @@ // 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 +package bson import ( "encoding/json" @@ -18,10 +18,7 @@ import ( "time" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsonrw/bsonrwtest" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -58,12 +55,12 @@ func TestDefaultValueEncoders(t *testing.T) { now := time.Now().Truncate(time.Millisecond) pjsnum := new(json.Number) *pjsnum = json.Number("3.14159") - d128 := primitive.NewDecimal128(12345, 67890) + d128 := NewDecimal128(12345, 67890) var nilValueMarshaler *testValueMarshaler var nilMarshaler *testMarshaler var nilProxy *testProxy - vmStruct := struct{ V testValueMarshalPtr }{testValueMarshalPtr{t: bsontype.String, buf: []byte{0x04, 0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00}}} + vmStruct := struct{ V testValueMarshalPtr }{testValueMarshalPtr{t: TypeString, buf: []byte{0x04, 0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00}}} mStruct := struct{ V testMarshalPtr }{testMarshalPtr{buf: bsoncore.BuildDocument(nil, bsoncore.AppendDoubleElement(nil, "pi", 3.14159))}} pStruct := struct{ V testProxyPtr }{testProxyPtr{ret: int64(1234567890)}} @@ -71,8 +68,8 @@ func TestDefaultValueEncoders(t *testing.T) { name string val interface{} ectx *EncodeContext - llvrw *bsonrwtest.ValueReaderWriter - invoke bsonrwtest.Invoked + llvrw *valueReaderWriter + invoke invoked err error } @@ -90,11 +87,11 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "BooleanEncodeValue", Kinds: []reflect.Kind{reflect.Bool}, Received: reflect.ValueOf(wrong)}, }, - {"fast path", bool(true), nil, nil, bsonrwtest.WriteBoolean, nil}, - {"reflection path", mybool(true), nil, nil, bsonrwtest.WriteBoolean, nil}, + {"fast path", bool(true), nil, nil, writeBoolean, nil}, + {"reflection path", mybool(true), nil, nil, writeBoolean, nil}, }, }, { @@ -106,35 +103,35 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{ Name: "IntEncodeValue", Kinds: []reflect.Kind{reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int}, Received: reflect.ValueOf(wrong), }, }, - {"int8/fast path", int8(127), nil, nil, bsonrwtest.WriteInt32, nil}, - {"int16/fast path", int16(32767), nil, nil, bsonrwtest.WriteInt32, nil}, - {"int32/fast path", int32(2147483647), nil, nil, bsonrwtest.WriteInt32, nil}, - {"int64/fast path", int64(1234567890987), nil, nil, bsonrwtest.WriteInt64, nil}, - {"int64/fast path - minsize", int64(math.MaxInt32), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt32, nil}, - {"int64/fast path - minsize too large", int64(math.MaxInt32 + 1), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt64, nil}, - {"int64/fast path - minsize too small", int64(math.MinInt32 - 1), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt64, nil}, - {"int/fast path - positive int32", int(math.MaxInt32 - 1), nil, nil, bsonrwtest.WriteInt32, nil}, - {"int/fast path - negative int32", int(math.MinInt32 + 1), nil, nil, bsonrwtest.WriteInt32, nil}, - {"int/fast path - MaxInt32", int(math.MaxInt32), nil, nil, bsonrwtest.WriteInt32, nil}, - {"int/fast path - MinInt32", int(math.MinInt32), nil, nil, bsonrwtest.WriteInt32, nil}, - {"int8/reflection path", myint8(127), nil, nil, bsonrwtest.WriteInt32, nil}, - {"int16/reflection path", myint16(32767), nil, nil, bsonrwtest.WriteInt32, nil}, - {"int32/reflection path", myint32(2147483647), nil, nil, bsonrwtest.WriteInt32, nil}, - {"int64/reflection path", myint64(1234567890987), nil, nil, bsonrwtest.WriteInt64, nil}, - {"int64/reflection path - minsize", myint64(math.MaxInt32), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt32, nil}, - {"int64/reflection path - minsize too large", myint64(math.MaxInt32 + 1), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt64, nil}, - {"int64/reflection path - minsize too small", myint64(math.MinInt32 - 1), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt64, nil}, - {"int/reflection path - positive int32", myint(math.MaxInt32 - 1), nil, nil, bsonrwtest.WriteInt32, nil}, - {"int/reflection path - negative int32", myint(math.MinInt32 + 1), nil, nil, bsonrwtest.WriteInt32, nil}, - {"int/reflection path - MaxInt32", myint(math.MaxInt32), nil, nil, bsonrwtest.WriteInt32, nil}, - {"int/reflection path - MinInt32", myint(math.MinInt32), nil, nil, bsonrwtest.WriteInt32, nil}, + {"int8/fast path", int8(127), nil, nil, writeInt32, nil}, + {"int16/fast path", int16(32767), nil, nil, writeInt32, nil}, + {"int32/fast path", int32(2147483647), nil, nil, writeInt32, nil}, + {"int64/fast path", int64(1234567890987), nil, nil, writeInt64, nil}, + {"int64/fast path - minsize", int64(math.MaxInt32), &EncodeContext{MinSize: true}, nil, writeInt32, nil}, + {"int64/fast path - minsize too large", int64(math.MaxInt32 + 1), &EncodeContext{MinSize: true}, nil, writeInt64, nil}, + {"int64/fast path - minsize too small", int64(math.MinInt32 - 1), &EncodeContext{MinSize: true}, nil, writeInt64, nil}, + {"int/fast path - positive int32", int(math.MaxInt32 - 1), nil, nil, writeInt32, nil}, + {"int/fast path - negative int32", int(math.MinInt32 + 1), nil, nil, writeInt32, nil}, + {"int/fast path - MaxInt32", int(math.MaxInt32), nil, nil, writeInt32, nil}, + {"int/fast path - MinInt32", int(math.MinInt32), nil, nil, writeInt32, nil}, + {"int8/reflection path", myint8(127), nil, nil, writeInt32, nil}, + {"int16/reflection path", myint16(32767), nil, nil, writeInt32, nil}, + {"int32/reflection path", myint32(2147483647), nil, nil, writeInt32, nil}, + {"int64/reflection path", myint64(1234567890987), nil, nil, writeInt64, nil}, + {"int64/reflection path - minsize", myint64(math.MaxInt32), &EncodeContext{MinSize: true}, nil, writeInt32, nil}, + {"int64/reflection path - minsize too large", myint64(math.MaxInt32 + 1), &EncodeContext{MinSize: true}, nil, writeInt64, nil}, + {"int64/reflection path - minsize too small", myint64(math.MinInt32 - 1), &EncodeContext{MinSize: true}, nil, writeInt64, nil}, + {"int/reflection path - positive int32", myint(math.MaxInt32 - 1), nil, nil, writeInt32, nil}, + {"int/reflection path - negative int32", myint(math.MinInt32 + 1), nil, nil, writeInt32, nil}, + {"int/reflection path - MaxInt32", myint(math.MaxInt32), nil, nil, writeInt32, nil}, + {"int/reflection path - MinInt32", myint(math.MinInt32), nil, nil, writeInt32, nil}, }, }, { @@ -146,36 +143,36 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{ Name: "UintEncodeValue", Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint}, Received: reflect.ValueOf(wrong), }, }, - {"uint8/fast path", uint8(127), nil, nil, bsonrwtest.WriteInt32, nil}, - {"uint16/fast path", uint16(32767), nil, nil, bsonrwtest.WriteInt32, nil}, - {"uint32/fast path", uint32(2147483647), nil, nil, bsonrwtest.WriteInt64, nil}, - {"uint64/fast path", uint64(1234567890987), nil, nil, bsonrwtest.WriteInt64, nil}, - {"uint/fast path", uint(1234567), nil, nil, bsonrwtest.WriteInt64, nil}, - {"uint32/fast path - minsize", uint32(2147483647), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt32, nil}, - {"uint64/fast path - minsize", uint64(2147483647), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt32, nil}, - {"uint/fast path - minsize", uint(2147483647), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt32, nil}, - {"uint32/fast path - minsize too large", uint32(2147483648), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt64, nil}, - {"uint64/fast path - minsize too large", uint64(2147483648), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt64, nil}, - {"uint/fast path - minsize too large", uint(2147483648), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt64, nil}, - {"uint64/fast path - overflow", uint64(1 << 63), nil, nil, bsonrwtest.Nothing, fmt.Errorf("%d overflows int64", uint64(1<<63))}, - {"uint8/reflection path", myuint8(127), nil, nil, bsonrwtest.WriteInt32, nil}, - {"uint16/reflection path", myuint16(32767), nil, nil, bsonrwtest.WriteInt32, nil}, - {"uint32/reflection path", myuint32(2147483647), nil, nil, bsonrwtest.WriteInt64, nil}, - {"uint64/reflection path", myuint64(1234567890987), nil, nil, bsonrwtest.WriteInt64, nil}, - {"uint32/reflection path - minsize", myuint32(2147483647), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt32, nil}, - {"uint64/reflection path - minsize", myuint64(2147483647), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt32, nil}, - {"uint/reflection path - minsize", myuint(2147483647), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt32, nil}, - {"uint32/reflection path - minsize too large", myuint(1 << 31), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt64, nil}, - {"uint64/reflection path - minsize too large", myuint64(1 << 31), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt64, nil}, - {"uint/reflection path - minsize too large", myuint(2147483648), &EncodeContext{MinSize: true}, nil, bsonrwtest.WriteInt64, nil}, - {"uint64/reflection path - overflow", myuint64(1 << 63), nil, nil, bsonrwtest.Nothing, fmt.Errorf("%d overflows int64", uint64(1<<63))}, + {"uint8/fast path", uint8(127), nil, nil, writeInt32, nil}, + {"uint16/fast path", uint16(32767), nil, nil, writeInt32, nil}, + {"uint32/fast path", uint32(2147483647), nil, nil, writeInt64, nil}, + {"uint64/fast path", uint64(1234567890987), nil, nil, writeInt64, nil}, + {"uint/fast path", uint(1234567), nil, nil, writeInt64, nil}, + {"uint32/fast path - minsize", uint32(2147483647), &EncodeContext{MinSize: true}, nil, writeInt32, nil}, + {"uint64/fast path - minsize", uint64(2147483647), &EncodeContext{MinSize: true}, nil, writeInt32, nil}, + {"uint/fast path - minsize", uint(2147483647), &EncodeContext{MinSize: true}, nil, writeInt32, nil}, + {"uint32/fast path - minsize too large", uint32(2147483648), &EncodeContext{MinSize: true}, nil, writeInt64, nil}, + {"uint64/fast path - minsize too large", uint64(2147483648), &EncodeContext{MinSize: true}, nil, writeInt64, nil}, + {"uint/fast path - minsize too large", uint(2147483648), &EncodeContext{MinSize: true}, nil, writeInt64, nil}, + {"uint64/fast path - overflow", uint64(1 << 63), nil, nil, nothing, fmt.Errorf("%d overflows int64", uint64(1<<63))}, + {"uint8/reflection path", myuint8(127), nil, nil, writeInt32, nil}, + {"uint16/reflection path", myuint16(32767), nil, nil, writeInt32, nil}, + {"uint32/reflection path", myuint32(2147483647), nil, nil, writeInt64, nil}, + {"uint64/reflection path", myuint64(1234567890987), nil, nil, writeInt64, nil}, + {"uint32/reflection path - minsize", myuint32(2147483647), &EncodeContext{MinSize: true}, nil, writeInt32, nil}, + {"uint64/reflection path - minsize", myuint64(2147483647), &EncodeContext{MinSize: true}, nil, writeInt32, nil}, + {"uint/reflection path - minsize", myuint(2147483647), &EncodeContext{MinSize: true}, nil, writeInt32, nil}, + {"uint32/reflection path - minsize too large", myuint(1 << 31), &EncodeContext{MinSize: true}, nil, writeInt64, nil}, + {"uint64/reflection path - minsize too large", myuint64(1 << 31), &EncodeContext{MinSize: true}, nil, writeInt64, nil}, + {"uint/reflection path - minsize too large", myuint(2147483648), &EncodeContext{MinSize: true}, nil, writeInt64, nil}, + {"uint64/reflection path - overflow", myuint64(1 << 63), nil, nil, nothing, fmt.Errorf("%d overflows int64", uint64(1<<63))}, }, }, { @@ -187,17 +184,17 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{ Name: "FloatEncodeValue", Kinds: []reflect.Kind{reflect.Float32, reflect.Float64}, Received: reflect.ValueOf(wrong), }, }, - {"float32/fast path", float32(3.14159), nil, nil, bsonrwtest.WriteDouble, nil}, - {"float64/fast path", float64(3.14159), nil, nil, bsonrwtest.WriteDouble, nil}, - {"float32/reflection path", myfloat32(3.14159), nil, nil, bsonrwtest.WriteDouble, nil}, - {"float64/reflection path", myfloat64(3.14159), nil, nil, bsonrwtest.WriteDouble, nil}, + {"float32/fast path", float32(3.14159), nil, nil, writeDouble, nil}, + {"float64/fast path", float64(3.14159), nil, nil, writeDouble, nil}, + {"float32/reflection path", myfloat32(3.14159), nil, nil, writeDouble, nil}, + {"float64/reflection path", myfloat64(3.14159), nil, nil, writeDouble, nil}, }, }, { @@ -209,10 +206,10 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "TimeEncodeValue", Types: []reflect.Type{tTime}, Received: reflect.ValueOf(wrong)}, }, - {"time.Time", now, nil, nil, bsonrwtest.WriteDateTime, nil}, + {"time.Time", now, nil, nil, writeDateTime, nil}, }, }, { @@ -224,47 +221,47 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "MapEncodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: reflect.ValueOf(wrong)}, }, { "WriteDocument Error", map[string]interface{}{}, nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("wd error"), ErrAfter: bsonrwtest.WriteDocument}, - bsonrwtest.WriteDocument, + &valueReaderWriter{Err: errors.New("wd error"), ErrAfter: writeDocument}, + writeDocument, errors.New("wd error"), }, { "Lookup Error", map[string]int{"foo": 1}, - &EncodeContext{Registry: NewRegistryBuilder().Build()}, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.WriteDocument, + &EncodeContext{Registry: newTestRegistryBuilder().Build()}, + &valueReaderWriter{}, + writeDocument, fmt.Errorf("no encoder found for int"), }, { "WriteDocumentElement Error", map[string]interface{}{"foo": "bar"}, &EncodeContext{Registry: buildDefaultRegistry()}, - &bsonrwtest.ValueReaderWriter{Err: errors.New("wde error"), ErrAfter: bsonrwtest.WriteDocumentElement}, - bsonrwtest.WriteDocumentElement, + &valueReaderWriter{Err: errors.New("wde error"), ErrAfter: writeDocumentElement}, + writeDocumentElement, errors.New("wde error"), }, { "EncodeValue Error", map[string]interface{}{"foo": "bar"}, &EncodeContext{Registry: buildDefaultRegistry()}, - &bsonrwtest.ValueReaderWriter{Err: errors.New("ev error"), ErrAfter: bsonrwtest.WriteString}, - bsonrwtest.WriteString, + &valueReaderWriter{Err: errors.New("ev error"), ErrAfter: writeString}, + writeString, errors.New("ev error"), }, { "empty map/success", map[string]interface{}{}, - &EncodeContext{Registry: NewRegistryBuilder().Build()}, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.WriteDocumentEnd, + &EncodeContext{Registry: newTestRegistryBuilder().Build()}, + &valueReaderWriter{}, + writeDocumentEnd, nil, }, { @@ -272,7 +269,7 @@ func TestDefaultValueEncoders(t *testing.T) { map[string]myInterface{"foo": myStruct{1}}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteDocumentEnd, + writeDocumentEnd, nil, }, { @@ -280,7 +277,7 @@ func TestDefaultValueEncoders(t *testing.T) { map[string]myInterface{"foo": nil}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteDocumentEnd, + writeDocumentEnd, nil, }, { @@ -289,8 +286,8 @@ func TestDefaultValueEncoders(t *testing.T) { 1: "foobar", }, &EncodeContext{Registry: buildDefaultRegistry()}, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.WriteDocumentEnd, + &valueReaderWriter{}, + writeDocumentEnd, nil, }, }, @@ -304,55 +301,55 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "ArrayEncodeValue", Kinds: []reflect.Kind{reflect.Array}, Received: reflect.ValueOf(wrong)}, }, { "WriteArray Error", [1]string{}, nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("wa error"), ErrAfter: bsonrwtest.WriteArray}, - bsonrwtest.WriteArray, + &valueReaderWriter{Err: errors.New("wa error"), ErrAfter: writeArray}, + writeArray, errors.New("wa error"), }, { "Lookup Error", [1]int{1}, - &EncodeContext{Registry: NewRegistryBuilder().Build()}, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.WriteArray, + &EncodeContext{Registry: newTestRegistryBuilder().Build()}, + &valueReaderWriter{}, + writeArray, fmt.Errorf("no encoder found for int"), }, { "WriteArrayElement Error", [1]string{"foo"}, &EncodeContext{Registry: buildDefaultRegistry()}, - &bsonrwtest.ValueReaderWriter{Err: errors.New("wae error"), ErrAfter: bsonrwtest.WriteArrayElement}, - bsonrwtest.WriteArrayElement, + &valueReaderWriter{Err: errors.New("wae error"), ErrAfter: writeArrayElement}, + writeArrayElement, errors.New("wae error"), }, { "EncodeValue Error", [1]string{"foo"}, &EncodeContext{Registry: buildDefaultRegistry()}, - &bsonrwtest.ValueReaderWriter{Err: errors.New("ev error"), ErrAfter: bsonrwtest.WriteString}, - bsonrwtest.WriteString, + &valueReaderWriter{Err: errors.New("ev error"), ErrAfter: writeString}, + writeString, errors.New("ev error"), }, { - "[1]primitive.E/success", - [1]primitive.E{{"hello", "world"}}, + "[1]E/success", + [1]E{{"hello", "world"}}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteDocumentEnd, + writeDocumentEnd, nil, }, { - "[1]primitive.E/success", - [1]primitive.E{{"hello", nil}}, + "[1]E/success", + [1]E{{"hello", nil}}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteDocumentEnd, + writeDocumentEnd, nil, }, { @@ -360,7 +357,7 @@ func TestDefaultValueEncoders(t *testing.T) { [1]myInterface{myStruct{1}}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteArrayEnd, + writeArrayEnd, nil, }, { @@ -368,7 +365,7 @@ func TestDefaultValueEncoders(t *testing.T) { [1]myInterface{nil}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteArrayEnd, + writeArrayEnd, nil, }, }, @@ -382,63 +379,63 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "SliceEncodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: reflect.ValueOf(wrong)}, }, { "WriteArray Error", []string{}, nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("wa error"), ErrAfter: bsonrwtest.WriteArray}, - bsonrwtest.WriteArray, + &valueReaderWriter{Err: errors.New("wa error"), ErrAfter: writeArray}, + writeArray, errors.New("wa error"), }, { "Lookup Error", []int{1}, - &EncodeContext{Registry: NewRegistryBuilder().Build()}, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.WriteArray, + &EncodeContext{Registry: newTestRegistryBuilder().Build()}, + &valueReaderWriter{}, + writeArray, fmt.Errorf("no encoder found for int"), }, { "WriteArrayElement Error", []string{"foo"}, &EncodeContext{Registry: buildDefaultRegistry()}, - &bsonrwtest.ValueReaderWriter{Err: errors.New("wae error"), ErrAfter: bsonrwtest.WriteArrayElement}, - bsonrwtest.WriteArrayElement, + &valueReaderWriter{Err: errors.New("wae error"), ErrAfter: writeArrayElement}, + writeArrayElement, errors.New("wae error"), }, { "EncodeValue Error", []string{"foo"}, &EncodeContext{Registry: buildDefaultRegistry()}, - &bsonrwtest.ValueReaderWriter{Err: errors.New("ev error"), ErrAfter: bsonrwtest.WriteString}, - bsonrwtest.WriteString, + &valueReaderWriter{Err: errors.New("ev error"), ErrAfter: writeString}, + writeString, errors.New("ev error"), }, { "D/success", - primitive.D{{"hello", "world"}}, + D{{"hello", "world"}}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteDocumentEnd, + writeDocumentEnd, nil, }, { "D/success", - primitive.D{{"hello", nil}}, + D{{"hello", nil}}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteDocumentEnd, + writeDocumentEnd, nil, }, { "empty slice/success", []interface{}{}, - &EncodeContext{Registry: NewRegistryBuilder().Build()}, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.WriteArrayEnd, + &EncodeContext{Registry: newTestRegistryBuilder().Build()}, + &valueReaderWriter{}, + writeArrayEnd, nil, }, { @@ -446,7 +443,7 @@ func TestDefaultValueEncoders(t *testing.T) { []myInterface{myStruct{1}}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteArrayEnd, + writeArrayEnd, nil, }, { @@ -454,7 +451,7 @@ func TestDefaultValueEncoders(t *testing.T) { []myInterface{nil}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteArrayEnd, + writeArrayEnd, nil, }, }, @@ -468,13 +465,13 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "ObjectIDEncodeValue", Types: []reflect.Type{tOID}, Received: reflect.ValueOf(wrong)}, }, { - "primitive.ObjectID/success", - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, - nil, nil, bsonrwtest.WriteObjectID, nil, + "ObjectID/success", + ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + nil, nil, writeObjectID, nil, }, }, }, @@ -487,10 +484,10 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "Decimal128EncodeValue", Types: []reflect.Type{tDecimal}, Received: reflect.ValueOf(wrong)}, }, - {"Decimal128/success", d128, nil, nil, bsonrwtest.WriteDecimal128, nil}, + {"Decimal128/success", d128, nil, nil, writeDecimal128, nil}, }, }, { @@ -502,23 +499,23 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "JSONNumberEncodeValue", Types: []reflect.Type{tJSONNumber}, Received: reflect.ValueOf(wrong)}, }, { "json.Number/invalid", json.Number("hello world"), - nil, nil, bsonrwtest.Nothing, errors.New(`strconv.ParseFloat: parsing "hello world": invalid syntax`), + nil, nil, nothing, errors.New(`strconv.ParseFloat: parsing "hello world": invalid syntax`), }, { "json.Number/int64/success", json.Number("1234567890"), - nil, nil, bsonrwtest.WriteInt64, nil, + nil, nil, writeInt64, nil, }, { "json.Number/float64/success", json.Number("3.14159"), - nil, nil, bsonrwtest.WriteDouble, nil, + nil, nil, writeDouble, nil, }, }, }, @@ -531,10 +528,10 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "URLEncodeValue", Types: []reflect.Type{tURL}, Received: reflect.ValueOf(wrong)}, }, - {"url.URL", url.URL{Scheme: "http", Host: "example.com"}, nil, nil, bsonrwtest.WriteString, nil}, + {"url.URL", url.URL{Scheme: "http", Host: "example.com"}, nil, nil, writeString, nil}, }, }, { @@ -546,11 +543,11 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "ByteSliceEncodeValue", Types: []reflect.Type{tByteSlice}, Received: reflect.ValueOf(wrong)}, }, - {"[]byte", []byte{0x01, 0x02, 0x03}, nil, nil, bsonrwtest.WriteBinary, nil}, - {"[]byte/nil", []byte(nil), nil, nil, bsonrwtest.WriteNull, nil}, + {"[]byte", []byte{0x01, 0x02, 0x03}, nil, nil, writeBinary, nil}, + {"[]byte/nil", []byte(nil), nil, nil, writeNull, nil}, }, }, { @@ -562,7 +559,7 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "EmptyInterfaceEncodeValue", Types: []reflect.Type{tEmpty}, Received: reflect.ValueOf(wrong)}, }, }, @@ -576,7 +573,7 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{ Name: "ValueMarshalerEncodeValue", Types: []reflect.Type{tValueMarshaler}, @@ -588,7 +585,7 @@ func TestDefaultValueEncoders(t *testing.T) { testValueMarshaler{err: errors.New("mbsonv error")}, nil, nil, - bsonrwtest.Nothing, + nothing, errors.New("mbsonv error"), }, { @@ -596,23 +593,23 @@ func TestDefaultValueEncoders(t *testing.T) { testValueMarshaler{}, nil, nil, - bsonrwtest.Nothing, - fmt.Errorf("Cannot copy unknown BSON type %s", bsontype.Type(0)), + nothing, + fmt.Errorf("cannot copy unknown BSON type %s", Type(0)), }, { "success struct implementation", - testValueMarshaler{t: bsontype.String, buf: []byte{0x04, 0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00}}, + testValueMarshaler{t: TypeString, buf: []byte{0x04, 0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00}}, nil, nil, - bsonrwtest.WriteString, + writeString, nil, }, { "success ptr to struct implementation", - &testValueMarshaler{t: bsontype.String, buf: []byte{0x04, 0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00}}, + &testValueMarshaler{t: TypeString, buf: []byte{0x04, 0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00}}, nil, nil, - bsonrwtest.WriteString, + writeString, nil, }, { @@ -620,23 +617,23 @@ func TestDefaultValueEncoders(t *testing.T) { nilValueMarshaler, nil, nil, - bsonrwtest.WriteNull, + writeNull, nil, }, { "success ptr to ptr implementation", - &testValueMarshalPtr{t: bsontype.String, buf: []byte{0x04, 0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00}}, + &testValueMarshalPtr{t: TypeString, buf: []byte{0x04, 0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00}}, nil, nil, - bsonrwtest.WriteString, + writeString, nil, }, { "unaddressable ptr implementation", - testValueMarshalPtr{t: bsontype.String, buf: []byte{0x04, 0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00}}, + testValueMarshalPtr{t: TypeString, buf: []byte{0x04, 0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00}}, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{ Name: "ValueMarshalerEncodeValue", Types: []reflect.Type{tValueMarshaler}, @@ -654,7 +651,7 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "MarshalerEncodeValue", Types: []reflect.Type{tMarshaler}, Received: reflect.ValueOf(wrong)}, }, { @@ -662,7 +659,7 @@ func TestDefaultValueEncoders(t *testing.T) { testMarshaler{err: errors.New("mbson error")}, nil, nil, - bsonrwtest.Nothing, + nothing, errors.New("mbson error"), }, { @@ -670,7 +667,7 @@ func TestDefaultValueEncoders(t *testing.T) { testMarshaler{buf: bsoncore.BuildDocument(nil, bsoncore.AppendDoubleElement(nil, "pi", 3.14159))}, nil, nil, - bsonrwtest.WriteDocumentEnd, + writeDocumentEnd, nil, }, { @@ -678,7 +675,7 @@ func TestDefaultValueEncoders(t *testing.T) { &testMarshaler{buf: bsoncore.BuildDocument(nil, bsoncore.AppendDoubleElement(nil, "pi", 3.14159))}, nil, nil, - bsonrwtest.WriteDocumentEnd, + writeDocumentEnd, nil, }, { @@ -686,7 +683,7 @@ func TestDefaultValueEncoders(t *testing.T) { nilMarshaler, nil, nil, - bsonrwtest.WriteNull, + writeNull, nil, }, { @@ -694,7 +691,7 @@ func TestDefaultValueEncoders(t *testing.T) { &testMarshalPtr{buf: bsoncore.BuildDocument(nil, bsoncore.AppendDoubleElement(nil, "pi", 3.14159))}, nil, nil, - bsonrwtest.WriteDocumentEnd, + writeDocumentEnd, nil, }, { @@ -702,7 +699,7 @@ func TestDefaultValueEncoders(t *testing.T) { testMarshalPtr{buf: bsoncore.BuildDocument(nil, bsoncore.AppendDoubleElement(nil, "pi", 3.14159))}, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "MarshalerEncodeValue", Types: []reflect.Type{tMarshaler}, Received: reflect.ValueOf(testMarshalPtr{})}, }, }, @@ -716,7 +713,7 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "ProxyEncodeValue", Types: []reflect.Type{tProxy}, Received: reflect.ValueOf(wrong)}, }, { @@ -724,7 +721,7 @@ func TestDefaultValueEncoders(t *testing.T) { testProxy{err: errors.New("proxy error")}, nil, nil, - bsonrwtest.Nothing, + nothing, errors.New("proxy error"), }, { @@ -732,7 +729,7 @@ func TestDefaultValueEncoders(t *testing.T) { testProxy{ret: nil}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.Nothing, + nothing, ErrNoEncoder{Type: nil}, }, { @@ -740,7 +737,7 @@ func TestDefaultValueEncoders(t *testing.T) { testProxy{ret: int64(1234567890)}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteInt64, + writeInt64, nil, }, { @@ -748,7 +745,7 @@ func TestDefaultValueEncoders(t *testing.T) { &testProxy{ret: int64(1234567890)}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteInt64, + writeInt64, nil, }, { @@ -756,7 +753,7 @@ func TestDefaultValueEncoders(t *testing.T) { nilProxy, nil, nil, - bsonrwtest.WriteNull, + writeNull, nil, }, { @@ -764,7 +761,7 @@ func TestDefaultValueEncoders(t *testing.T) { &testProxyPtr{ret: int64(1234567890)}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteInt64, + writeInt64, nil, }, { @@ -772,7 +769,7 @@ func TestDefaultValueEncoders(t *testing.T) { testProxyPtr{ret: int64(1234567890)}, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "ProxyEncodeValue", Types: []reflect.Type{tProxy}, Received: reflect.ValueOf(testProxyPtr{})}, }, }, @@ -786,7 +783,7 @@ func TestDefaultValueEncoders(t *testing.T) { nil, nil, nil, - bsonrwtest.WriteNull, + writeNull, nil, }, { @@ -794,7 +791,7 @@ func TestDefaultValueEncoders(t *testing.T) { int32(123456), nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "PointerCodec.EncodeValue", Kinds: []reflect.Kind{reflect.Ptr}, Received: reflect.ValueOf(int32(123456))}, }, { @@ -802,7 +799,7 @@ func TestDefaultValueEncoders(t *testing.T) { (*int32)(nil), nil, nil, - bsonrwtest.WriteNull, + writeNull, nil, }, { @@ -810,7 +807,7 @@ func TestDefaultValueEncoders(t *testing.T) { &wrong, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.Nothing, + nothing, ErrNoEncoder{Type: reflect.TypeOf(wrong)}, }, }, @@ -824,7 +821,7 @@ func TestDefaultValueEncoders(t *testing.T) { &vmStruct, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteDocumentEnd, + writeDocumentEnd, nil, }, { @@ -832,7 +829,7 @@ func TestDefaultValueEncoders(t *testing.T) { &mStruct, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteDocumentEnd, + writeDocumentEnd, nil, }, { @@ -840,7 +837,7 @@ func TestDefaultValueEncoders(t *testing.T) { &pStruct, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteDocumentEnd, + writeDocumentEnd, nil, }, }, @@ -854,10 +851,10 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "JavaScriptEncodeValue", Types: []reflect.Type{tJavaScript}, Received: reflect.ValueOf(wrong)}, }, - {"JavaScript", primitive.JavaScript("foobar"), nil, nil, bsonrwtest.WriteJavascript, nil}, + {"JavaScript", JavaScript("foobar"), nil, nil, writeJavascript, nil}, }, }, { @@ -869,10 +866,10 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "SymbolEncodeValue", Types: []reflect.Type{tSymbol}, Received: reflect.ValueOf(wrong)}, }, - {"Symbol", primitive.Symbol("foobar"), nil, nil, bsonrwtest.WriteSymbol, nil}, + {"Symbol", Symbol("foobar"), nil, nil, writeSymbol, nil}, }, }, { @@ -884,10 +881,10 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "BinaryEncodeValue", Types: []reflect.Type{tBinary}, Received: reflect.ValueOf(wrong)}, }, - {"Binary/success", primitive.Binary{Data: []byte{0x01, 0x02}, Subtype: 0xFF}, nil, nil, bsonrwtest.WriteBinaryWithSubtype, nil}, + {"Binary/success", Binary{Data: []byte{0x01, 0x02}, Subtype: 0xFF}, nil, nil, writeBinaryWithSubtype, nil}, }, }, { @@ -899,10 +896,10 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "UndefinedEncodeValue", Types: []reflect.Type{tUndefined}, Received: reflect.ValueOf(wrong)}, }, - {"Undefined/success", primitive.Undefined{}, nil, nil, bsonrwtest.WriteUndefined, nil}, + {"Undefined/success", Undefined{}, nil, nil, writeUndefined, nil}, }, }, { @@ -914,10 +911,10 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "DateTimeEncodeValue", Types: []reflect.Type{tDateTime}, Received: reflect.ValueOf(wrong)}, }, - {"DateTime/success", primitive.DateTime(1234567890), nil, nil, bsonrwtest.WriteDateTime, nil}, + {"DateTime/success", DateTime(1234567890), nil, nil, writeDateTime, nil}, }, }, { @@ -929,10 +926,10 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "NullEncodeValue", Types: []reflect.Type{tNull}, Received: reflect.ValueOf(wrong)}, }, - {"Null/success", primitive.Null{}, nil, nil, bsonrwtest.WriteNull, nil}, + {"Null/success", Null{}, nil, nil, writeNull, nil}, }, }, { @@ -944,10 +941,10 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "RegexEncodeValue", Types: []reflect.Type{tRegex}, Received: reflect.ValueOf(wrong)}, }, - {"Regex/success", primitive.Regex{Pattern: "foo", Options: "bar"}, nil, nil, bsonrwtest.WriteRegex, nil}, + {"Regex/success", Regex{Pattern: "foo", Options: "bar"}, nil, nil, writeRegex, nil}, }, }, { @@ -959,16 +956,16 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "DBPointerEncodeValue", Types: []reflect.Type{tDBPointer}, Received: reflect.ValueOf(wrong)}, }, { "DBPointer/success", - primitive.DBPointer{ + DBPointer{ DB: "foobar", - Pointer: primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + Pointer: ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, }, - nil, nil, bsonrwtest.WriteDBPointer, nil, + nil, nil, writeDBPointer, nil, }, }, }, @@ -981,10 +978,10 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "TimestampEncodeValue", Types: []reflect.Type{tTimestamp}, Received: reflect.ValueOf(wrong)}, }, - {"Timestamp/success", primitive.Timestamp{T: 12345, I: 67890}, nil, nil, bsonrwtest.WriteTimestamp, nil}, + {"Timestamp/success", Timestamp{T: 12345, I: 67890}, nil, nil, writeTimestamp, nil}, }, }, { @@ -996,10 +993,10 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "MinKeyEncodeValue", Types: []reflect.Type{tMinKey}, Received: reflect.ValueOf(wrong)}, }, - {"MinKey/success", primitive.MinKey{}, nil, nil, bsonrwtest.WriteMinKey, nil}, + {"MinKey/success", MinKey{}, nil, nil, writeMinKey, nil}, }, }, { @@ -1011,10 +1008,10 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{Name: "MaxKeyEncodeValue", Types: []reflect.Type{tMaxKey}, Received: reflect.ValueOf(wrong)}, }, - {"MaxKey/success", primitive.MaxKey{}, nil, nil, bsonrwtest.WriteMaxKey, nil}, + {"MaxKey/success", MaxKey{}, nil, nil, writeMaxKey, nil}, }, }, { @@ -1026,7 +1023,7 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{ Name: "CoreDocumentEncodeValue", Types: []reflect.Type{tCoreDocument}, @@ -1037,40 +1034,40 @@ func TestDefaultValueEncoders(t *testing.T) { "WriteDocument Error", bsoncore.Document{}, nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("wd error"), ErrAfter: bsonrwtest.WriteDocument}, - bsonrwtest.WriteDocument, + &valueReaderWriter{Err: errors.New("wd error"), ErrAfter: writeDocument}, + writeDocument, errors.New("wd error"), }, { "bsoncore.Document.Elements Error", bsoncore.Document{0xFF, 0x00, 0x00, 0x00, 0x00}, nil, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.WriteDocument, + &valueReaderWriter{}, + writeDocument, errors.New("length read exceeds number of bytes available. length=5 bytes=255"), }, { "WriteDocumentElement Error", bsoncore.Document(buildDocument(bsoncore.AppendNullElement(nil, "foo"))), nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("wde error"), ErrAfter: bsonrwtest.WriteDocumentElement}, - bsonrwtest.WriteDocumentElement, + &valueReaderWriter{Err: errors.New("wde error"), ErrAfter: writeDocumentElement}, + writeDocumentElement, errors.New("wde error"), }, { "encodeValue error", bsoncore.Document(buildDocument(bsoncore.AppendNullElement(nil, "foo"))), nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("ev error"), ErrAfter: bsonrwtest.WriteNull}, - bsonrwtest.WriteNull, + &valueReaderWriter{Err: errors.New("ev error"), ErrAfter: writeNull}, + writeNull, errors.New("ev error"), }, { "iterator error", bsoncore.Document{0x0C, 0x00, 0x00, 0x00, 0x01, 'f', 'o', 'o', 0x00, 0x01, 0x02, 0x03}, nil, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.WriteDocumentElement, + &valueReaderWriter{}, + writeDocumentElement, errors.New("not enough bytes available to read type. bytes=3 type=double"), }, }, @@ -1084,7 +1081,7 @@ func TestDefaultValueEncoders(t *testing.T) { struct{ Foo myInterface }{Foo: myStruct{1}}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteDocumentEnd, + writeDocumentEnd, nil, }, { @@ -1092,7 +1089,7 @@ func TestDefaultValueEncoders(t *testing.T) { struct{ Foo myInterface }{Foo: nil}, &EncodeContext{Registry: buildDefaultRegistry()}, nil, - bsonrwtest.WriteDocumentEnd, + writeDocumentEnd, nil, }, }, @@ -1106,7 +1103,7 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{ Name: "CodeWithScopeEncodeValue", Types: []reflect.Type{tCodeWithScope}, @@ -1115,20 +1112,20 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "WriteCodeWithScope error", - primitive.CodeWithScope{}, + CodeWithScope{}, nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("wcws error"), ErrAfter: bsonrwtest.WriteCodeWithScope}, - bsonrwtest.WriteCodeWithScope, + &valueReaderWriter{Err: errors.New("wcws error"), ErrAfter: writeCodeWithScope}, + writeCodeWithScope, errors.New("wcws error"), }, { "CodeWithScope/success", - primitive.CodeWithScope{ + CodeWithScope{ Code: "var hello = 'world';", - Scope: primitive.D{}, + Scope: D{}, }, &EncodeContext{Registry: buildDefaultRegistry()}, - nil, bsonrwtest.WriteDocumentEnd, nil, + nil, writeDocumentEnd, nil, }, }, }, @@ -1141,7 +1138,7 @@ func TestDefaultValueEncoders(t *testing.T) { wrong, nil, nil, - bsonrwtest.Nothing, + nothing, ValueEncoderError{ Name: "CoreArrayEncodeValue", Types: []reflect.Type{tCoreArray}, @@ -1153,8 +1150,8 @@ func TestDefaultValueEncoders(t *testing.T) { "WriteArray Error", bsoncore.Array{}, nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("wa error"), ErrAfter: bsonrwtest.WriteArray}, - bsonrwtest.WriteArray, + &valueReaderWriter{Err: errors.New("wa error"), ErrAfter: writeArray}, + writeArray, errors.New("wa error"), }, { @@ -1163,8 +1160,8 @@ func TestDefaultValueEncoders(t *testing.T) { return bsoncore.AppendNullElement(nil, "foo") })), nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("wae error"), ErrAfter: bsonrwtest.WriteArrayElement}, - bsonrwtest.WriteArrayElement, + &valueReaderWriter{Err: errors.New("wae error"), ErrAfter: writeArrayElement}, + writeArrayElement, errors.New("wae error"), }, { @@ -1173,8 +1170,8 @@ func TestDefaultValueEncoders(t *testing.T) { return bsoncore.AppendNullElement(nil, "foo") })), nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("ev error"), ErrAfter: bsonrwtest.WriteNull}, - bsonrwtest.WriteNull, + &valueReaderWriter{Err: errors.New("ev error"), ErrAfter: writeNull}, + writeNull, errors.New("ev error"), }, }, @@ -1189,16 +1186,16 @@ func TestDefaultValueEncoders(t *testing.T) { if subtest.ectx != nil { ec = *subtest.ectx } - llvrw := new(bsonrwtest.ValueReaderWriter) + llvrw := new(valueReaderWriter) if subtest.llvrw != nil { llvrw = subtest.llvrw } llvrw.T = t err := tc.ve.EncodeValue(ec, llvrw, reflect.ValueOf(subtest.val)) - if !compareErrors(err, subtest.err) { + if !assert.CompareErrors(err, subtest.err) { t.Errorf("Errors do not match. got %v; want %v", err, subtest.err) } - invoked := llvrw.Invoked + invoked := llvrw.invoked if !cmp.Equal(invoked, subtest.invoke) { t.Errorf("Incorrect method invoked. got %v; want %v", invoked, subtest.invoke) } @@ -1208,8 +1205,8 @@ func TestDefaultValueEncoders(t *testing.T) { } t.Run("success path", func(t *testing.T) { - oid := primitive.NewObjectID() - oids := []primitive.ObjectID{primitive.NewObjectID(), primitive.NewObjectID(), primitive.NewObjectID()} + oid := NewObjectID() + oids := []ObjectID{NewObjectID(), NewObjectID(), NewObjectID()} var str = new(string) *str = "bar" now := time.Now().Truncate(time.Millisecond) @@ -1218,7 +1215,7 @@ func TestDefaultValueEncoders(t *testing.T) { t.Errorf("Error parsing URL: %v", err) t.FailNow() } - decimal128, err := primitive.ParseDecimal128("1.5e10") + decimal128, err := ParseDecimal128("1.5e10") if err != nil { t.Errorf("Error parsing decimal128: %v", err) t.FailNow() @@ -1242,8 +1239,8 @@ func TestDefaultValueEncoders(t *testing.T) { nil, }, { - "map[string]primitive.ObjectID", - map[string]primitive.ObjectID{"foo": oid}, + "map[string]ObjectID", + map[string]ObjectID{"foo": oid}, buildDocument(bsoncore.AppendObjectIDElement(nil, "foo", oid)), nil, }, @@ -1258,8 +1255,8 @@ func TestDefaultValueEncoders(t *testing.T) { nil, }, { - "map[string][]primitive.ObjectID", - map[string][]primitive.ObjectID{"Z": oids}, + "map[string][]ObjectID", + map[string][]ObjectID{"Z": oids}, buildDocumentArray(func(doc []byte) []byte { doc = bsoncore.AppendObjectIDElement(doc, "0", oids[0]) doc = bsoncore.AppendObjectIDElement(doc, "1", oids[1]) @@ -1294,10 +1291,10 @@ func TestDefaultValueEncoders(t *testing.T) { nil, }, { - "map[string][]primitive.Decimal128", - map[string][]primitive.Decimal128{"Z": {decimal128}}, + "map[string][]Decimal128", + map[string][]Decimal128{"Z": {decimal128}}, buildDocumentArray(func(doc []byte) []byte { - return bsoncore.AppendDecimal128Element(doc, "0", decimal128) + return bsoncore.AppendDecimal128Element(doc, "0", decimal128.h, decimal128.l) }), nil, }, @@ -1549,19 +1546,19 @@ func TestDefaultValueEncoders(t *testing.T) { L struct { M string } - Q primitive.ObjectID + Q ObjectID T []struct{} Y json.Number Z time.Time AA json.Number AB *url.URL - AC primitive.Decimal128 + AC Decimal128 AD *time.Time AE testValueMarshaler AF Proxy AG testProxy AH map[string]interface{} - AI primitive.CodeWithScope + AI CodeWithScope }{ A: true, B: 123, @@ -1586,11 +1583,11 @@ func TestDefaultValueEncoders(t *testing.T) { AB: murl, AC: decimal128, AD: &now, - AE: testValueMarshaler{t: bsontype.String, buf: bsoncore.AppendString(nil, "hello, world")}, + AE: testValueMarshaler{t: TypeString, buf: bsoncore.AppendString(nil, "hello, world")}, AF: testProxy{ret: struct{ Hello string }{Hello: "world!"}}, AG: testProxy{ret: struct{ Pi float64 }{Pi: 3.14159}}, AH: nil, - AI: primitive.CodeWithScope{Code: "var hello = 'world';", Scope: primitive.D{{"pi", 3.14159}}}, + AI: CodeWithScope{Code: "var hello = 'world';", Scope: D{{"pi", 3.14159}}}, }, buildDocument(func(doc []byte) []byte { doc = bsoncore.AppendBooleanElement(doc, "a", true) @@ -1612,7 +1609,7 @@ func TestDefaultValueEncoders(t *testing.T) { doc = bsoncore.AppendDateTimeElement(doc, "z", now.UnixNano()/int64(time.Millisecond)) doc = bsoncore.AppendDoubleElement(doc, "aa", 10.1) doc = bsoncore.AppendStringElement(doc, "ab", murl.String()) - doc = bsoncore.AppendDecimal128Element(doc, "ac", decimal128) + doc = bsoncore.AppendDecimal128Element(doc, "ac", decimal128.h, decimal128.l) doc = bsoncore.AppendDateTimeElement(doc, "ad", now.UnixNano()/int64(time.Millisecond)) doc = bsoncore.AppendStringElement(doc, "ae", "hello, world") doc = bsoncore.AppendDocumentElement(doc, "af", buildDocument(bsoncore.AppendStringElement(nil, "hello", "world!"))) @@ -1642,7 +1639,7 @@ func TestDefaultValueEncoders(t *testing.T) { M string } N [][]string - R []primitive.ObjectID + R []ObjectID T []struct{} W []map[string]struct{} X []map[string]struct{} @@ -1650,7 +1647,7 @@ func TestDefaultValueEncoders(t *testing.T) { Z []time.Time AA []json.Number AB []*url.URL - AC []primitive.Decimal128 + AC []Decimal128 AD []*time.Time AE []testValueMarshaler AF []Proxy @@ -1682,11 +1679,11 @@ func TestDefaultValueEncoders(t *testing.T) { Z: []time.Time{now, now}, AA: []json.Number{json.Number("5"), json.Number("10.1")}, AB: []*url.URL{murl}, - AC: []primitive.Decimal128{decimal128}, + AC: []Decimal128{decimal128}, AD: []*time.Time{&now, &now}, AE: []testValueMarshaler{ - {t: bsontype.String, buf: bsoncore.AppendString(nil, "hello")}, - {t: bsontype.String, buf: bsoncore.AppendString(nil, "world")}, + {t: TypeString, buf: bsoncore.AppendString(nil, "hello")}, + {t: TypeString, buf: bsoncore.AppendString(nil, "world")}, }, AF: []Proxy{ testProxy{ret: struct{ Hello string }{Hello: "world!"}}, @@ -1736,7 +1733,7 @@ func TestDefaultValueEncoders(t *testing.T) { ) doc = appendArrayElement(doc, "aa", bsoncore.AppendDoubleElement(bsoncore.AppendInt64Element(nil, "0", 5), "1", 10.10)) doc = appendArrayElement(doc, "ab", bsoncore.AppendStringElement(nil, "0", murl.String())) - doc = appendArrayElement(doc, "ac", bsoncore.AppendDecimal128Element(nil, "0", decimal128)) + doc = appendArrayElement(doc, "ac", bsoncore.AppendDecimal128Element(nil, "0", decimal128.h, decimal128.l)) doc = appendArrayElement(doc, "ad", bsoncore.AppendDateTimeElement( bsoncore.AppendDateTimeElement(nil, "0", now.UnixNano()/int64(time.Millisecond)), @@ -1769,8 +1766,8 @@ func TestDefaultValueEncoders(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - b := make(bsonrw.SliceWriter, 0, 512) - vw := bsonrw.NewValueWriter(&b) + b := make(SliceWriter, 0, 512) + vw := NewValueWriter(&b) reg := buildDefaultRegistry() enc, err := reg.LookupEncoder(reflect.TypeOf(tc.value)) noerr(t, err) @@ -1819,8 +1816,8 @@ func TestDefaultValueEncoders(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - b := make(bsonrw.SliceWriter, 0, 512) - vw := bsonrw.NewValueWriter(&b) + b := make(SliceWriter, 0, 512) + vw := NewValueWriter(&b) reg := buildDefaultRegistry() enc, err := reg.LookupEncoder(reflect.TypeOf(tc.value)) noerr(t, err) @@ -1834,55 +1831,36 @@ func TestDefaultValueEncoders(t *testing.T) { t.Run("EmptyInterfaceEncodeValue/nil", func(t *testing.T) { val := reflect.New(tEmpty).Elem() - llvrw := new(bsonrwtest.ValueReaderWriter) - err := dve.EmptyInterfaceEncodeValue(EncodeContext{Registry: NewRegistryBuilder().Build()}, llvrw, val) + llvrw := new(valueReaderWriter) + err := dve.EmptyInterfaceEncodeValue(EncodeContext{Registry: newTestRegistryBuilder().Build()}, llvrw, val) noerr(t, err) - if llvrw.Invoked != bsonrwtest.WriteNull { - t.Errorf("Incorrect method called. got %v; want %v", llvrw.Invoked, bsonrwtest.WriteNull) + if llvrw.invoked != writeNull { + t.Errorf("Incorrect method called. got %v; want %v", llvrw.invoked, writeNull) } }) t.Run("EmptyInterfaceEncodeValue/LookupEncoder error", func(t *testing.T) { val := reflect.New(tEmpty).Elem() val.Set(reflect.ValueOf(int64(1234567890))) - llvrw := new(bsonrwtest.ValueReaderWriter) - got := dve.EmptyInterfaceEncodeValue(EncodeContext{Registry: NewRegistryBuilder().Build()}, llvrw, val) + llvrw := new(valueReaderWriter) + got := dve.EmptyInterfaceEncodeValue(EncodeContext{Registry: newTestRegistryBuilder().Build()}, llvrw, val) want := ErrNoEncoder{Type: tInt64} - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not receive expected error. got %v; want %v", got, want) } }) } -type testValueMarshaler struct { - t bsontype.Type - buf []byte - err error -} - -func (tvm testValueMarshaler) MarshalBSONValue() (bsontype.Type, []byte, error) { - return tvm.t, tvm.buf, tvm.err -} - type testValueMarshalPtr struct { - t bsontype.Type + t Type buf []byte err error } -func (tvm *testValueMarshalPtr) MarshalBSONValue() (bsontype.Type, []byte, error) { +func (tvm *testValueMarshalPtr) MarshalBSONValue() (Type, []byte, error) { return tvm.t, tvm.buf, tvm.err } -type testMarshaler struct { - buf []byte - err error -} - -func (tvm testMarshaler) MarshalBSON() ([]byte, error) { - return tvm.buf, tvm.err -} - type testMarshalPtr struct { buf []byte err error diff --git a/bson/doc.go b/bson/doc.go index af6098475e..2344c3672e 100644 --- a/bson/doc.go +++ b/bson/doc.go @@ -135,5 +135,18 @@ // // Manually marshaling and unmarshaling can be done with the Marshal and Unmarshal family of functions. // +// bsoncodec code provides a system for encoding values to BSON representations and decoding +// values from BSON representations. This package considers both binary BSON and ExtendedJSON as +// BSON representations. The types in this package enable a flexible system for handling this +// encoding and decoding. +// +// The codec system is composed of two parts: +// +// 1) [ValueEncoder] and [ValueDecoder] that handle encoding and decoding Go values to and from BSON +// representations. +// +// 2) A [Registry] that holds these ValueEncoders and ValueDecoders and provides methods for +// retrieving them. +// // [Work with BSON]: https://www.mongodb.com/docs/drivers/go/current/fundamentals/bson/ package bson diff --git a/bson/bsoncodec/empty_interface_codec.go b/bson/empty_interface_codec.go similarity index 81% rename from bson/bsoncodec/empty_interface_codec.go rename to bson/empty_interface_codec.go index 94f7dcf1eb..56468e3068 100644 --- a/bson/bsoncodec/empty_interface_codec.go +++ b/bson/empty_interface_codec.go @@ -4,15 +4,12 @@ // 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 +package bson import ( "reflect" "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" ) // EmptyInterfaceCodec is the Codec used for interface{} values. @@ -21,7 +18,7 @@ import ( // EmptyInterfaceCodec registered. 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 primitive.Binary. + // "Generic" or "Old" BSON binary subtype as a Go byte slice instead of a Binary. // // Deprecated: Use bson.Decoder.BinaryAsSlice instead. DecodeBinaryAsSlice bool @@ -51,7 +48,7 @@ func NewEmptyInterfaceCodec(opts ...*bsonoptions.EmptyInterfaceCodecOptions) *Em } // EncodeValue is the ValueEncoderFunc for interface{}. -func (eic EmptyInterfaceCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +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} } @@ -67,8 +64,8 @@ func (eic EmptyInterfaceCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWrit return encoder.EncodeValue(ec, vw, val.Elem()) } -func (eic EmptyInterfaceCodec) getEmptyInterfaceDecodeType(dc DecodeContext, valueType bsontype.Type) (reflect.Type, error) { - isDocument := valueType == bsontype.Type(0) || valueType == bsontype.EmbeddedDocument +func (eic EmptyInterfaceCodec) getEmptyInterfaceDecodeType(dc DecodeContext, valueType Type) (reflect.Type, error) { + isDocument := valueType == Type(0) || valueType == TypeEmbeddedDocument if isDocument { if dc.defaultDocumentType != nil { // If the bsontype is an embedded document and the DocumentType is set on the DecodeContext, then return @@ -89,14 +86,14 @@ func (eic EmptyInterfaceCodec) getEmptyInterfaceDecodeType(dc DecodeContext, val } if isDocument { - // For documents, fallback to looking up a type map entry for bsontype.Type(0) or bsontype.EmbeddedDocument, + // For documents, fallback to looking up a type map entry for Type(0) or TypeEmbeddedDocument, // depending on the original valueType. - var lookupType bsontype.Type + var lookupType Type switch valueType { - case bsontype.Type(0): - lookupType = bsontype.EmbeddedDocument - case bsontype.EmbeddedDocument: - lookupType = bsontype.Type(0) + case Type(0): + lookupType = TypeEmbeddedDocument + case TypeEmbeddedDocument: + lookupType = Type(0) } rtype, err = dc.LookupTypeMapEntry(lookupType) @@ -108,7 +105,7 @@ func (eic EmptyInterfaceCodec) getEmptyInterfaceDecodeType(dc DecodeContext, val return nil, err } -func (eic EmptyInterfaceCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (eic EmptyInterfaceCodec) decodeType(dc DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tEmpty { return emptyValue, ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: reflect.Zero(t)} } @@ -116,7 +113,7 @@ func (eic EmptyInterfaceCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReade rtype, err := eic.getEmptyInterfaceDecodeType(dc, vr.Type()) if err != nil { switch vr.Type() { - case bsontype.Null: + case TypeNull: return reflect.Zero(t), vr.ReadNull() default: return emptyValue, err @@ -134,8 +131,8 @@ func (eic EmptyInterfaceCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReade } if (eic.DecodeBinaryAsSlice || dc.binaryAsSlice) && rtype == tBinary { - binElem := elem.Interface().(primitive.Binary) - if binElem.Subtype == bsontype.BinaryGeneric || binElem.Subtype == bsontype.BinaryBinaryOld { + binElem := elem.Interface().(Binary) + if binElem.Subtype == TypeBinaryGeneric || binElem.Subtype == TypeBinaryBinaryOld { elem = reflect.ValueOf(binElem.Data) } } @@ -144,7 +141,7 @@ func (eic EmptyInterfaceCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReade } // DecodeValue is the ValueDecoderFunc for interface{}. -func (eic EmptyInterfaceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +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 4d22c7fbd4..fb865cd285 100644 --- a/bson/encoder.go +++ b/bson/encoder.go @@ -9,9 +9,6 @@ package bson import ( "reflect" "sync" - - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" ) // This pool is used to keep the allocations of Encoders down. This is only used for the Marshal* @@ -23,11 +20,11 @@ var encPool = sync.Pool{ }, } -// An Encoder writes a serialization format to an output stream. It writes to a bsonrw.ValueWriter +// An Encoder writes a serialization format to an output stream. It writes to a ValueWriter // as the destination of BSON data. type Encoder struct { - ec bsoncodec.EncodeContext - vw bsonrw.ValueWriter + ec EncodeContext + vw ValueWriter errorOnInlineDuplicates bool intMinSize bool @@ -40,9 +37,9 @@ type Encoder struct { } // NewEncoder returns a new encoder that uses the DefaultRegistry to write to vw. -func NewEncoder(vw bsonrw.ValueWriter) *Encoder { +func NewEncoder(vw ValueWriter) *Encoder { return &Encoder{ - ec: bsoncodec.EncodeContext{Registry: DefaultRegistry}, + ec: EncodeContext{Registry: DefaultRegistry}, vw: vw, } } @@ -57,7 +54,7 @@ func (e *Encoder) Encode(val interface{}) error { if err != nil { return err } - return bsonrw.Copier{}.CopyDocumentFromBytes(e.vw, buf) + return copyDocumentFromBytes(e.vw, buf) } encoder, err := e.ec.LookupEncoder(reflect.TypeOf(val)) @@ -97,12 +94,12 @@ func (e *Encoder) Encode(val interface{}) error { // Reset will reset the state of the Encoder, using the same *EncodeContext used in // the original construction but using vw. -func (e *Encoder) Reset(vw bsonrw.ValueWriter) { +func (e *Encoder) Reset(vw ValueWriter) { e.vw = vw } // SetRegistry replaces the current registry of the Encoder with r. -func (e *Encoder) SetRegistry(r *bsoncodec.Registry) { +func (e *Encoder) SetRegistry(r *Registry) { e.ec.Registry = r } diff --git a/bson/encoder_example_test.go b/bson/encoder_example_test.go index 7cac909af9..5c34192db4 100644 --- a/bson/encoder_example_test.go +++ b/bson/encoder_example_test.go @@ -13,13 +13,12 @@ import ( "io" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsonrw" ) func ExampleEncoder() { // Create an Encoder that writes BSON values to a bytes.Buffer. buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) encoder := bson.NewEncoder(vw) type Product struct { @@ -57,7 +56,7 @@ func (k CityState) String() string { func ExampleEncoder_StringifyMapKeysWithFmt() { // Create an Encoder that writes BSON values to a bytes.Buffer. buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) encoder := bson.NewEncoder(vw) // Configure the Encoder to convert Go map keys to BSON document field names @@ -82,7 +81,7 @@ func ExampleEncoder_StringifyMapKeysWithFmt() { func ExampleEncoder_UseJSONStructTags() { // Create an Encoder that writes BSON values to a bytes.Buffer. buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) encoder := bson.NewEncoder(vw) type Product struct { @@ -115,7 +114,7 @@ func ExampleEncoder_UseJSONStructTags() { func ExampleEncoder_multipleBSONDocuments() { // Create an Encoder that writes BSON values to a bytes.Buffer. buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) encoder := bson.NewEncoder(vw) type Coordinate struct { @@ -159,7 +158,7 @@ func ExampleEncoder_extendedJSON() { // Create an Encoder that writes canonical Extended JSON values to a // bytes.Buffer. buf := new(bytes.Buffer) - vw := bsonrw.NewExtJSONValueWriter(buf, true, false) + vw := bson.NewExtJSONValueWriter(buf, true, false) encoder := bson.NewEncoder(vw) type Product struct { @@ -188,7 +187,7 @@ func ExampleEncoder_multipleExtendedJSONDocuments() { // Create an Encoder that writes canonical Extended JSON values to a // bytes.Buffer. buf := new(bytes.Buffer) - vw := bsonrw.NewExtJSONValueWriter(buf, true, false) + vw := bson.NewExtJSONValueWriter(buf, true, false) encoder := bson.NewEncoder(vw) type Coordinate struct { @@ -225,7 +224,7 @@ func ExampleEncoder_IntMinSize() { } buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.IntMinSize() diff --git a/bson/encoder_test.go b/bson/encoder_test.go index 05e3341de0..999b9962ef 100644 --- a/bson/encoder_test.go +++ b/bson/encoder_test.go @@ -12,10 +12,6 @@ import ( "reflect" "testing" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsonrw/bsonrwtest" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/require" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" @@ -24,12 +20,12 @@ import ( func TestBasicEncode(t *testing.T) { for _, tc := range marshalingTestCases { t.Run(tc.name, func(t *testing.T) { - got := make(bsonrw.SliceWriter, 0, 1024) - vw := bsonrw.NewValueWriter(&got) + got := make(SliceWriter, 0, 1024) + vw := NewValueWriter(&got) reg := DefaultRegistry encoder, err := reg.LookupEncoder(reflect.TypeOf(tc.val)) noerr(t, err) - err = encoder.EncodeValue(bsoncodec.EncodeContext{Registry: reg}, vw, reflect.ValueOf(tc.val)) + err = encoder.EncodeValue(EncodeContext{Registry: reg}, vw, reflect.ValueOf(tc.val)) noerr(t, err) if !bytes.Equal(got, tc.want) { @@ -43,8 +39,8 @@ func TestBasicEncode(t *testing.T) { func TestEncoderEncode(t *testing.T) { for _, tc := range marshalingTestCases { t.Run(tc.name, func(t *testing.T) { - got := make(bsonrw.SliceWriter, 0, 1024) - vw := bsonrw.NewValueWriter(&got) + got := make(SliceWriter, 0, 1024) + vw := NewValueWriter(&got) enc := NewEncoder(vw) err := enc.Encode(tc.val) noerr(t, err) @@ -62,21 +58,21 @@ func TestEncoderEncode(t *testing.T) { buf []byte err error wanterr error - vw bsonrw.ValueWriter + vw ValueWriter }{ { "error", nil, errors.New("Marshaler error"), errors.New("Marshaler error"), - &bsonrwtest.ValueReaderWriter{}, + &valueReaderWriter{}, }, { "copy error", []byte{0x05, 0x00, 0x00, 0x00, 0x00}, nil, errors.New("copy error"), - &bsonrwtest.ValueReaderWriter{Err: errors.New("copy error"), ErrAfter: bsonrwtest.WriteDocument}, + &valueReaderWriter{Err: errors.New("copy error"), ErrAfter: writeDocument}, }, { "success", @@ -91,19 +87,19 @@ func TestEncoderEncode(t *testing.T) { t.Run(tc.name, func(t *testing.T) { marshaler := testMarshaler{buf: tc.buf, err: tc.err} - var vw bsonrw.ValueWriter - b := make(bsonrw.SliceWriter, 0, 100) + var vw ValueWriter + b := make(SliceWriter, 0, 100) compareVW := false if tc.vw != nil { vw = tc.vw } else { compareVW = true - vw = bsonrw.NewValueWriter(&b) + vw = NewValueWriter(&b) } enc := NewEncoder(vw) got := enc.Encode(marshaler) want := tc.wanterr - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not receive expected error. got %v; want %v", got, want) } if compareVW { @@ -237,7 +233,7 @@ func TestEncoderConfiguration(t *testing.T) { }, input: D{{Key: "myBytes", Value: []byte(nil)}}, want: bsoncore.NewDocumentBuilder(). - AppendBinary("myBytes", bsontype.BinaryGeneric, []byte{}). + AppendBinary("myBytes", TypeBinaryGeneric, []byte{}). Build(), }, // Test that OmitZeroStruct omits empty structs from the marshaled document if the @@ -277,7 +273,7 @@ func TestEncoderConfiguration(t *testing.T) { t.Parallel() got := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(got) + vw := NewValueWriter(got) enc := NewEncoder(vw) tc.configure(enc) diff --git a/bson/bsonrw/extjson_parser.go b/bson/extjson_parser.go similarity index 88% rename from bson/bsonrw/extjson_parser.go rename to bson/extjson_parser.go index bb52a0ec3d..540416cbec 100644 --- a/bson/bsonrw/extjson_parser.go +++ b/bson/extjson_parser.go @@ -4,7 +4,7 @@ // 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 bsonrw +package bson import ( "encoding/base64" @@ -13,8 +13,6 @@ import ( "fmt" "io" "strings" - - "go.mongodb.org/mongo-driver/bson/bsontype" ) const maxNestingDepth = 200 @@ -47,7 +45,7 @@ const ( ) type extJSONValue struct { - t bsontype.Type + t Type v interface{} } @@ -87,8 +85,8 @@ func newExtJSONParser(r io.Reader, canonical bool) *extJSONParser { } // peekType examines the next value and returns its BSON Type -func (ejp *extJSONParser) peekType() (bsontype.Type, error) { - var t bsontype.Type +func (ejp *extJSONParser) peekType() (Type, error) { + var t Type var err error initialState := ejp.s @@ -97,7 +95,7 @@ func (ejp *extJSONParser) peekType() (bsontype.Type, error) { case jpsSawValue: t = ejp.v.t case jpsSawBeginArray: - t = bsontype.Array + t = TypeArray case jpsInvalidState: err = ejp.err case jpsSawComma: @@ -113,26 +111,26 @@ func (ejp *extJSONParser) peekType() (bsontype.Type, error) { ejp.advanceState() switch ejp.s { case jpsSawEndObject: // empty embedded document - t = bsontype.EmbeddedDocument + t = TypeEmbeddedDocument ejp.emptyObject = true case jpsInvalidState: err = ejp.err case jpsSawKey: if initialState == jpsStartState { - return bsontype.EmbeddedDocument, nil + return TypeEmbeddedDocument, nil } t = wrapperKeyBSONType(ejp.k) // if $uuid is encountered, parse as binary subtype 4 if ejp.k == "$uuid" { ejp.relaxedUUID = true - t = bsontype.Binary + t = TypeBinary } switch t { - case bsontype.JavaScript: + case TypeJavaScript: // just saw $code, need to check for $scope at same level - _, err = ejp.readValue(bsontype.JavaScript) + _, err = ejp.readValue(TypeJavaScript) if err != nil { break } @@ -143,7 +141,7 @@ func (ejp *extJSONParser) peekType() (bsontype.Type, error) { ejp.advanceState() if ejp.s == jpsSawKey && ejp.k == "$scope" { - t = bsontype.CodeWithScope + t = TypeCodeWithScope } else { err = fmt.Errorf("invalid extended JSON: unexpected key %s in CodeWithScope object", ejp.k) } @@ -152,7 +150,7 @@ func (ejp *extJSONParser) peekType() (bsontype.Type, error) { default: err = ErrInvalidJSON } - case bsontype.CodeWithScope: + case TypeCodeWithScope: err = errors.New("invalid extended JSON: code with $scope must contain $code before $scope") } } @@ -162,7 +160,7 @@ func (ejp *extJSONParser) peekType() (bsontype.Type, error) { } // readKey parses the next key and its type and returns them -func (ejp *extJSONParser) readKey() (string, bsontype.Type, error) { +func (ejp *extJSONParser) readKey() (string, Type, error) { if ejp.emptyObject { ejp.emptyObject = false return "", 0, ErrEOD @@ -226,7 +224,7 @@ func (ejp *extJSONParser) readKey() (string, bsontype.Type, error) { } // readValue returns the value corresponding to the Type returned by peekType -func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { +func (ejp *extJSONParser) readValue(t Type) (*extJSONValue, error) { if ejp.s == jpsInvalidState { return nil, ejp.err } @@ -234,19 +232,19 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { var v *extJSONValue switch t { - case bsontype.Null, bsontype.Boolean, bsontype.String: + case TypeNull, TypeBoolean, TypeString: if ejp.s != jpsSawValue { return nil, invalidRequestError(t.String()) } v = ejp.v - case bsontype.Int32, bsontype.Int64, bsontype.Double: + case TypeInt32, TypeInt64, TypeDouble: // relaxed version allows these to be literal number values if ejp.s == jpsSawValue { v = ejp.v break } fallthrough - case bsontype.Decimal128, bsontype.Symbol, bsontype.ObjectID, bsontype.MinKey, bsontype.MaxKey, bsontype.Undefined: + case TypeDecimal128, TypeSymbol, TypeObjectID, TypeMinKey, TypeMaxKey, TypeUndefined: switch ejp.s { case jpsSawKey: // read colon @@ -271,7 +269,7 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { default: return nil, invalidRequestError(t.String()) } - case bsontype.Binary, bsontype.Regex, bsontype.Timestamp, bsontype.DBPointer: + case TypeBinary, TypeRegex, TypeTimestamp, TypeDBPointer: if ejp.s != jpsSawKey { return nil, invalidRequestError(t.String()) } @@ -282,7 +280,7 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { } ejp.advanceState() - if t == bsontype.Binary && ejp.s == jpsSawValue { + if t == TypeBinary && ejp.s == jpsSawValue { // convert relaxed $uuid format if ejp.relaxedUUID { defer func() { ejp.relaxedUUID = false }() @@ -318,20 +316,20 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { ejp.advanceState() if ejp.s != jpsSawEndObject { - return nil, invalidJSONErrorForType("$uuid and value and then }", bsontype.Binary) + return nil, invalidJSONErrorForType("$uuid and value and then }", TypeBinary) } base64 := &extJSONValue{ - t: bsontype.String, + t: TypeString, v: base64.StdEncoding.EncodeToString(bytes), } subType := &extJSONValue{ - t: bsontype.String, + t: TypeString, v: "04", } v = &extJSONValue{ - t: bsontype.EmbeddedDocument, + t: TypeEmbeddedDocument, v: &extJSONObject{ keys: []string{"base64", "subType"}, values: []*extJSONValue{base64, subType}, @@ -346,7 +344,7 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { ejp.advanceState() if ejp.s != jpsSawComma { - return nil, invalidJSONErrorForType(",", bsontype.Binary) + return nil, invalidJSONErrorForType(",", TypeBinary) } ejp.advanceState() @@ -355,7 +353,7 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { return nil, err } if key != "$type" { - return nil, invalidJSONErrorForType("$type", bsontype.Binary) + return nil, invalidJSONErrorForType("$type", TypeBinary) } subType, err := ejp.readValue(t) @@ -365,11 +363,11 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { ejp.advanceState() if ejp.s != jpsSawEndObject { - return nil, invalidJSONErrorForType("2 key-value pairs and then }", bsontype.Binary) + return nil, invalidJSONErrorForType("2 key-value pairs and then }", TypeBinary) } v = &extJSONValue{ - t: bsontype.EmbeddedDocument, + t: TypeEmbeddedDocument, v: &extJSONObject{ keys: []string{"base64", "subType"}, values: []*extJSONValue{base64, subType}, @@ -393,9 +391,9 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { return nil, invalidJSONErrorForType("2 key-value pairs and then }", t) } - v = &extJSONValue{t: bsontype.EmbeddedDocument, v: &extJSONObject{keys: keys, values: vals}} + v = &extJSONValue{t: TypeEmbeddedDocument, v: &extJSONObject{keys: keys, values: vals}} - case bsontype.DateTime: + case TypeDateTime: switch ejp.s { case jpsSawValue: v = ejp.v @@ -413,7 +411,7 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { if err != nil { return nil, err } - v = &extJSONValue{t: bsontype.EmbeddedDocument, v: &extJSONObject{keys: keys, values: vals}} + v = &extJSONValue{t: TypeEmbeddedDocument, v: &extJSONObject{keys: keys, values: vals}} case jpsSawValue: if ejp.canonical { return nil, invalidJSONError("{") @@ -433,7 +431,7 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { default: return nil, invalidRequestError(t.String()) } - case bsontype.JavaScript: + case TypeJavaScript: switch ejp.s { case jpsSawKey: // read colon @@ -456,7 +454,7 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { default: return nil, invalidRequestError(t.String()) } - case bsontype.CodeWithScope: + case TypeCodeWithScope: if ejp.s == jpsSawKey && ejp.k == "$scope" { v = ejp.v // this is the $code string from earlier @@ -474,7 +472,7 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { } else { return nil, invalidRequestError(t.String()) } - case bsontype.EmbeddedDocument, bsontype.Array: + case TypeEmbeddedDocument, TypeArray: return nil, invalidRequestError(t.String()) } @@ -703,14 +701,14 @@ func (ejp *extJSONParser) validateToken(jtt jsonTokenType) bool { // ensureExtValueType returns true if the current value has the expected // value type for single-key extended JSON types. For example, // {"$numberInt": v} v must be TypeString -func (ejp *extJSONParser) ensureExtValueType(t bsontype.Type) bool { +func (ejp *extJSONParser) ensureExtValueType(t Type) bool { switch t { - case bsontype.MinKey, bsontype.MaxKey: - return ejp.v.t == bsontype.Int32 - case bsontype.Undefined: - return ejp.v.t == bsontype.Boolean - case bsontype.Int32, bsontype.Int64, bsontype.Double, bsontype.Decimal128, bsontype.Symbol, bsontype.ObjectID: - return ejp.v.t == bsontype.String + case TypeMinKey, TypeMaxKey: + return ejp.v.t == TypeInt32 + case TypeUndefined: + return ejp.v.t == TypeBoolean + case TypeInt32, TypeInt64, TypeDouble, TypeDecimal128, TypeSymbol, TypeObjectID: + return ejp.v.t == TypeString default: return false } @@ -742,21 +740,21 @@ func (ejp *extJSONParser) peekMode() jsonParseMode { } func extendJSONToken(jt *jsonToken) *extJSONValue { - var t bsontype.Type + var t Type switch jt.t { case jttInt32: - t = bsontype.Int32 + t = TypeInt32 case jttInt64: - t = bsontype.Int64 + t = TypeInt64 case jttDouble: - t = bsontype.Double + t = TypeDouble case jttString: - t = bsontype.String + t = TypeString case jttBool: - t = bsontype.Boolean + t = TypeBoolean case jttNull: - t = bsontype.Null + t = TypeNull default: return nil } @@ -780,7 +778,7 @@ func invalidJSONError(expected string) error { return fmt.Errorf("invalid JSON input; expected %s", expected) } -func invalidJSONErrorForType(expected string, t bsontype.Type) error { +func invalidJSONErrorForType(expected string, t Type) error { return fmt.Errorf("invalid JSON input; expected %s for %s", expected, t) } diff --git a/bson/bsonrw/extjson_parser_test.go b/bson/extjson_parser_test.go similarity index 68% rename from bson/bsonrw/extjson_parser_test.go rename to bson/extjson_parser_test.go index 5da5326688..51a7de7aef 100644 --- a/bson/bsonrw/extjson_parser_test.go +++ b/bson/extjson_parser_test.go @@ -4,7 +4,7 @@ // 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 bsonrw +package bson import ( "errors" @@ -13,7 +13,6 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsontype" ) var ( @@ -31,7 +30,7 @@ type expectedErrorFunc func(t *testing.T, err error, desc string) type peekTypeTestCase struct { desc string input string - typs []bsontype.Type + typs []Type errFs []expectedErrorFunc } @@ -39,7 +38,7 @@ type readKeyValueTestCase struct { desc string input string keys []string - typs []bsontype.Type + typs []Type vals []*extJSONValue keyEFs []expectedErrorFunc @@ -69,7 +68,7 @@ func specificDiff(name string) func(t *testing.T, expected, actual interface{}, func expectErrorNOOP(_ *testing.T, _ error, _ string) { } -func readKeyDiff(t *testing.T, eKey, aKey string, eTyp, aTyp bsontype.Type, err error, errF expectedErrorFunc, desc string) { +func readKeyDiff(t *testing.T, eKey, aKey string, eTyp, aTyp Type, err error, errF expectedErrorFunc, desc string) { keyDiff(t, eKey, aKey, desc) typDiff(t, eTyp, aTyp, desc) errF(t, err, desc) @@ -87,17 +86,17 @@ func readValueDiff(t *testing.T, eVal, aVal *extJSONValue, err error, errF expec } func TestExtJSONParserPeekType(t *testing.T) { - makeValidPeekTypeTestCase := func(input string, typ bsontype.Type, desc string) peekTypeTestCase { + makeValidPeekTypeTestCase := func(input string, typ Type, desc string) peekTypeTestCase { return peekTypeTestCase{ desc: desc, input: input, - typs: []bsontype.Type{typ}, + typs: []Type{typ}, errFs: []expectedErrorFunc{expectNoError}, } } makeInvalidTestCase := func(desc, input string, lastEF expectedErrorFunc) peekTypeTestCase { return peekTypeTestCase{ desc: desc, input: input, - typs: []bsontype.Type{bsontype.Type(0)}, + typs: []Type{Type(0)}, errFs: []expectedErrorFunc{lastEF}, } } @@ -105,38 +104,38 @@ func TestExtJSONParserPeekType(t *testing.T) { makeInvalidPeekTypeTestCase := func(desc, input string, lastEF expectedErrorFunc) peekTypeTestCase { return peekTypeTestCase{ desc: desc, input: input, - typs: []bsontype.Type{bsontype.Array, bsontype.String, bsontype.Type(0)}, + typs: []Type{TypeArray, TypeString, Type(0)}, errFs: []expectedErrorFunc{expectNoError, expectNoError, lastEF}, } } cases := []peekTypeTestCase{ - makeValidPeekTypeTestCase(`null`, bsontype.Null, "Null"), - makeValidPeekTypeTestCase(`"string"`, bsontype.String, "String"), - makeValidPeekTypeTestCase(`true`, bsontype.Boolean, "Boolean--true"), - makeValidPeekTypeTestCase(`false`, bsontype.Boolean, "Boolean--false"), - makeValidPeekTypeTestCase(`{"$minKey": 1}`, bsontype.MinKey, "MinKey"), - makeValidPeekTypeTestCase(`{"$maxKey": 1}`, bsontype.MaxKey, "MaxKey"), - makeValidPeekTypeTestCase(`{"$numberInt": "42"}`, bsontype.Int32, "Int32"), - makeValidPeekTypeTestCase(`{"$numberLong": "42"}`, bsontype.Int64, "Int64"), - makeValidPeekTypeTestCase(`{"$symbol": "symbol"}`, bsontype.Symbol, "Symbol"), - makeValidPeekTypeTestCase(`{"$numberDouble": "42.42"}`, bsontype.Double, "Double"), - makeValidPeekTypeTestCase(`{"$undefined": true}`, bsontype.Undefined, "Undefined"), - makeValidPeekTypeTestCase(`{"$numberDouble": "NaN"}`, bsontype.Double, "Double--NaN"), - makeValidPeekTypeTestCase(`{"$numberDecimal": "1234"}`, bsontype.Decimal128, "Decimal"), - makeValidPeekTypeTestCase(`{"foo": "bar"}`, bsontype.EmbeddedDocument, "Toplevel document"), - makeValidPeekTypeTestCase(`{"$date": {"$numberLong": "0"}}`, bsontype.DateTime, "Datetime"), - makeValidPeekTypeTestCase(`{"$code": "function() {}"}`, bsontype.JavaScript, "Code no scope"), - makeValidPeekTypeTestCase(`[{"$numberInt": "1"},{"$numberInt": "2"}]`, bsontype.Array, "Array"), - makeValidPeekTypeTestCase(`{"$timestamp": {"t": 42, "i": 1}}`, bsontype.Timestamp, "Timestamp"), - makeValidPeekTypeTestCase(`{"$oid": "57e193d7a9cc81b4027498b5"}`, bsontype.ObjectID, "Object ID"), - makeValidPeekTypeTestCase(`{"$binary": {"base64": "AQIDBAU=", "subType": "80"}}`, bsontype.Binary, "Binary"), - makeValidPeekTypeTestCase(`{"$code": "function() {}", "$scope": {}}`, bsontype.CodeWithScope, "Code With Scope"), - makeValidPeekTypeTestCase(`{"$binary": {"base64": "o0w498Or7cijeBSpkquNtg==", "subType": "03"}}`, bsontype.Binary, "Binary"), - makeValidPeekTypeTestCase(`{"$binary": "o0w498Or7cijeBSpkquNtg==", "$type": "03"}`, bsontype.Binary, "Binary"), - makeValidPeekTypeTestCase(`{"$regularExpression": {"pattern": "foo*", "options": "ix"}}`, bsontype.Regex, "Regular expression"), - makeValidPeekTypeTestCase(`{"$dbPointer": {"$ref": "db.collection", "$id": {"$oid": "57e193d7a9cc81b4027498b1"}}}`, bsontype.DBPointer, "DBPointer"), - makeValidPeekTypeTestCase(`{"$ref": "collection", "$id": {"$oid": "57fd71e96e32ab4225b723fb"}, "$db": "database"}`, bsontype.EmbeddedDocument, "DBRef"), + makeValidPeekTypeTestCase(`null`, TypeNull, "Null"), + makeValidPeekTypeTestCase(`"string"`, TypeString, "String"), + makeValidPeekTypeTestCase(`true`, TypeBoolean, "Boolean--true"), + makeValidPeekTypeTestCase(`false`, TypeBoolean, "Boolean--false"), + makeValidPeekTypeTestCase(`{"$minKey": 1}`, TypeMinKey, "MinKey"), + makeValidPeekTypeTestCase(`{"$maxKey": 1}`, TypeMaxKey, "MaxKey"), + makeValidPeekTypeTestCase(`{"$numberInt": "42"}`, TypeInt32, "Int32"), + makeValidPeekTypeTestCase(`{"$numberLong": "42"}`, TypeInt64, "Int64"), + makeValidPeekTypeTestCase(`{"$symbol": "symbol"}`, TypeSymbol, "Symbol"), + makeValidPeekTypeTestCase(`{"$numberDouble": "42.42"}`, TypeDouble, "Double"), + makeValidPeekTypeTestCase(`{"$undefined": true}`, TypeUndefined, "Undefined"), + makeValidPeekTypeTestCase(`{"$numberDouble": "NaN"}`, TypeDouble, "Double--NaN"), + makeValidPeekTypeTestCase(`{"$numberDecimal": "1234"}`, TypeDecimal128, "Decimal"), + makeValidPeekTypeTestCase(`{"foo": "bar"}`, TypeEmbeddedDocument, "Toplevel document"), + makeValidPeekTypeTestCase(`{"$date": {"$numberLong": "0"}}`, TypeDateTime, "Datetime"), + makeValidPeekTypeTestCase(`{"$code": "function() {}"}`, TypeJavaScript, "Code no scope"), + makeValidPeekTypeTestCase(`[{"$numberInt": "1"},{"$numberInt": "2"}]`, TypeArray, "Array"), + makeValidPeekTypeTestCase(`{"$timestamp": {"t": 42, "i": 1}}`, TypeTimestamp, "Timestamp"), + makeValidPeekTypeTestCase(`{"$oid": "57e193d7a9cc81b4027498b5"}`, TypeObjectID, "Object ID"), + makeValidPeekTypeTestCase(`{"$binary": {"base64": "AQIDBAU=", "subType": "80"}}`, TypeBinary, "Binary"), + makeValidPeekTypeTestCase(`{"$code": "function() {}", "$scope": {}}`, TypeCodeWithScope, "Code With Scope"), + makeValidPeekTypeTestCase(`{"$binary": {"base64": "o0w498Or7cijeBSpkquNtg==", "subType": "03"}}`, TypeBinary, "Binary"), + makeValidPeekTypeTestCase(`{"$binary": "o0w498Or7cijeBSpkquNtg==", "$type": "03"}`, TypeBinary, "Binary"), + makeValidPeekTypeTestCase(`{"$regularExpression": {"pattern": "foo*", "options": "ix"}}`, TypeRegex, "Regular expression"), + makeValidPeekTypeTestCase(`{"$dbPointer": {"$ref": "db.collection", "$id": {"$oid": "57e193d7a9cc81b4027498b1"}}}`, TypeDBPointer, "DBPointer"), + makeValidPeekTypeTestCase(`{"$ref": "collection", "$id": {"$oid": "57fd71e96e32ab4225b723fb"}, "$db": "database"}`, TypeEmbeddedDocument, "DBRef"), makeInvalidPeekTypeTestCase("invalid array--missing ]", `["a"`, expectError), makeInvalidPeekTypeTestCase("invalid array--colon in array", `["a":`, expectError), makeInvalidPeekTypeTestCase("invalid array--extra comma", `["a",,`, expectError), @@ -145,7 +144,7 @@ func TestExtJSONParserPeekType(t *testing.T) { { desc: "invalid array--leading comma", input: `[,`, - typs: []bsontype.Type{bsontype.Array, bsontype.Type(0)}, + typs: []Type{TypeArray, Type(0)}, errFs: []expectedErrorFunc{expectNoError, expectError}, }, makeInvalidTestCase("lone $scope", `{"$scope": {}}`, expectError), @@ -181,15 +180,15 @@ func TestExtJSONParserReadKeyReadValue(t *testing.T) { // several test cases will use the same keys, types, and values, and only differ on input structure keys := []string{"_id", "Symbol", "String", "Int32", "Int64", "Int", "MinKey"} - types := []bsontype.Type{bsontype.ObjectID, bsontype.Symbol, bsontype.String, bsontype.Int32, bsontype.Int64, bsontype.Int32, bsontype.MinKey} + types := []Type{TypeObjectID, TypeSymbol, TypeString, TypeInt32, TypeInt64, TypeInt32, TypeMinKey} values := []*extJSONValue{ - {t: bsontype.String, v: "57e193d7a9cc81b4027498b5"}, - {t: bsontype.String, v: "symbol"}, - {t: bsontype.String, v: "string"}, - {t: bsontype.String, v: "42"}, - {t: bsontype.String, v: "42"}, - {t: bsontype.Int32, v: int32(42)}, - {t: bsontype.Int32, v: int32(1)}, + {t: TypeString, v: "57e193d7a9cc81b4027498b5"}, + {t: TypeString, v: "symbol"}, + {t: TypeString, v: "string"}, + {t: TypeString, v: "42"}, + {t: TypeString, v: "42"}, + {t: TypeInt32, v: int32(42)}, + {t: TypeInt32, v: int32(1)}, } errFuncs := make([]expectedErrorFunc, 7) @@ -202,19 +201,19 @@ func TestExtJSONParserReadKeyReadValue(t *testing.T) { desc: desc, input: input, keys: []string{""}, - typs: []bsontype.Type{bsontype.Type(0)}, + typs: []Type{Type(0)}, vals: []*extJSONValue{nil}, keyEFs: []expectedErrorFunc{expectError}, valEFs: []expectedErrorFunc{expectErrorNOOP}, } } - secondKeyError := func(desc, input, firstKey string, firstType bsontype.Type, firstValue *extJSONValue) readKeyValueTestCase { + secondKeyError := func(desc, input, firstKey string, firstType Type, firstValue *extJSONValue) readKeyValueTestCase { return readKeyValueTestCase{ desc: desc, input: input, keys: []string{firstKey, ""}, - typs: []bsontype.Type{firstType, bsontype.Type(0)}, + typs: []Type{firstType, Type(0)}, vals: []*extJSONValue{firstValue, nil}, keyEFs: []expectedErrorFunc{expectNoError, expectError}, valEFs: []expectedErrorFunc{expectNoError, expectErrorNOOP}, @@ -286,9 +285,9 @@ func TestExtJSONParserReadKeyReadValue(t *testing.T) { desc: "nested object", input: `{"k1": 1, "k2": { "k3": { "k4": 4 } }, "k5": 5}`, keys: []string{"k1", "k2", "k3", "k4", "", "", "k5", ""}, - typs: []bsontype.Type{bsontype.Int32, bsontype.EmbeddedDocument, bsontype.EmbeddedDocument, bsontype.Int32, bsontype.Type(0), bsontype.Type(0), bsontype.Int32, bsontype.Type(0)}, + typs: []Type{TypeInt32, TypeEmbeddedDocument, TypeEmbeddedDocument, TypeInt32, Type(0), Type(0), TypeInt32, Type(0)}, vals: []*extJSONValue{ - {t: bsontype.Int32, v: int32(1)}, nil, nil, {t: bsontype.Int32, v: int32(4)}, nil, nil, {t: bsontype.Int32, v: int32(5)}, nil, + {t: TypeInt32, v: int32(1)}, nil, nil, {t: TypeInt32, v: int32(4)}, nil, nil, {t: TypeInt32, v: int32(5)}, nil, }, keyEFs: []expectedErrorFunc{ expectNoError, expectNoError, expectNoError, expectNoError, expectErrEOD, @@ -303,7 +302,7 @@ func TestExtJSONParserReadKeyReadValue(t *testing.T) { desc: "invalid input: invalid values for extended type", input: `{"a": {"$numberInt": "1", "x"`, keys: []string{"a"}, - typs: []bsontype.Type{bsontype.Int32}, + typs: []Type{TypeInt32}, vals: []*extJSONValue{nil}, keyEFs: []expectedErrorFunc{expectNoError}, valEFs: []expectedErrorFunc{expectError}, @@ -313,16 +312,16 @@ func TestExtJSONParserReadKeyReadValue(t *testing.T) { firstKeyError("invalid input: missing value", `{"a":`), firstKeyError("invalid input: missing colon", `{"a" 1`), firstKeyError("invalid input: extra colon", `{"a"::`), - secondKeyError("invalid input: missing }", `{"a": 1`, "a", bsontype.Int32, &extJSONValue{t: bsontype.Int32, v: int32(1)}), - secondKeyError("invalid input: missing comma", `{"a": 1 "b"`, "a", bsontype.Int32, &extJSONValue{t: bsontype.Int32, v: int32(1)}), - secondKeyError("invalid input: extra comma", `{"a": 1,, "b"`, "a", bsontype.Int32, &extJSONValue{t: bsontype.Int32, v: int32(1)}), - secondKeyError("invalid input: trailing comma in object", `{"a": 1,}`, "a", bsontype.Int32, &extJSONValue{t: bsontype.Int32, v: int32(1)}), + secondKeyError("invalid input: missing }", `{"a": 1`, "a", TypeInt32, &extJSONValue{t: TypeInt32, v: int32(1)}), + secondKeyError("invalid input: missing comma", `{"a": 1 "b"`, "a", TypeInt32, &extJSONValue{t: TypeInt32, v: int32(1)}), + secondKeyError("invalid input: extra comma", `{"a": 1,, "b"`, "a", TypeInt32, &extJSONValue{t: TypeInt32, v: int32(1)}), + secondKeyError("invalid input: trailing comma in object", `{"a": 1,}`, "a", TypeInt32, &extJSONValue{t: TypeInt32, v: int32(1)}), { desc: "invalid input: lone scope after a complete value", input: `{"a": "", "b": {"$scope: ""}}`, keys: []string{"a"}, - typs: []bsontype.Type{bsontype.String}, - vals: []*extJSONValue{{bsontype.String, ""}}, + typs: []Type{TypeString}, + vals: []*extJSONValue{{TypeString, ""}}, keyEFs: []expectedErrorFunc{expectNoError, expectNoError}, valEFs: []expectedErrorFunc{expectNoError, expectError}, }, @@ -330,7 +329,7 @@ func TestExtJSONParserReadKeyReadValue(t *testing.T) { desc: "invalid input: lone scope nested", input: `{"a":{"b":{"$scope":{`, keys: []string{}, - typs: []bsontype.Type{}, + typs: []Type{}, vals: []*extJSONValue{nil}, keyEFs: []expectedErrorFunc{expectNoError}, valEFs: []expectedErrorFunc{expectError}, @@ -358,19 +357,19 @@ func TestExtJSONParserReadKeyReadValue(t *testing.T) { } } -type ejpExpectationTest func(t *testing.T, p *extJSONParser, expectedKey string, expectedType bsontype.Type, expectedValue interface{}) +type ejpExpectationTest func(t *testing.T, p *extJSONParser, expectedKey string, expectedType Type, expectedValue interface{}) type ejpTestCase struct { f ejpExpectationTest p *extJSONParser k string - t bsontype.Type + t Type v interface{} } // 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 bsontype.Type, expectedValue interface{}) { +func expectSingleValue(t *testing.T, p *extJSONParser, expectedKey string, expectedType Type, expectedValue interface{}) { eVal := expectedValue.(*extJSONValue) k, typ, err := p.readKey() @@ -382,13 +381,13 @@ 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 bsontype.Type, expectedValue interface{}) { +func expectMultipleValues(t *testing.T, p *extJSONParser, expectedKey string, expectedType Type, expectedValue interface{}) { k, typ, err := p.readKey() readKeyDiff(t, expectedKey, k, expectedType, typ, err, expectNoError, expectedKey) v, err := p.readValue(typ) expectNoError(t, err, "") - typDiff(t, bsontype.EmbeddedDocument, v.t, expectedKey) + typDiff(t, TypeEmbeddedDocument, v.t, expectedKey) actObj := v.v.(*extJSONObject) expObj := expectedValue.(*extJSONObject) @@ -406,7 +405,7 @@ func expectMultipleValues(t *testing.T, p *extJSONParser, expectedKey string, ex type ejpKeyTypValTriple struct { key string - typ bsontype.Type + typ Type val *extJSONValue } @@ -418,15 +417,15 @@ 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 bsontype.Type, expectedValue interface{}) { +func expectSubDocument(t *testing.T, p *extJSONParser, expectedKey string, expectedType Type, expectedValue interface{}) { subdoc := expectedValue.(ejpSubDocumentTestValue) k, typ, err := p.readKey() readKeyDiff(t, expectedKey, k, expectedType, typ, err, expectNoError, expectedKey) - if expectedType == bsontype.CodeWithScope { + if expectedType == TypeCodeWithScope { v, err := p.readValue(typ) - readValueDiff(t, &extJSONValue{t: bsontype.String, v: subdoc.code}, v, err, expectNoError, expectedKey) + readValueDiff(t, &extJSONValue{t: TypeString, v: subdoc.code}, v, err, expectNoError, expectedKey) } for _, ktv := range subdoc.ktvs { @@ -441,24 +440,24 @@ func expectSubDocument(t *testing.T, p *extJSONParser, expectedKey string, expec readValueDiff(t, eVal, v, err, expectNoError, expectedKey) } - if expectedType == bsontype.CodeWithScope { + if expectedType == TypeCodeWithScope { // expect scope doc to close k, typ, err = p.readKey() - readKeyDiff(t, "", k, bsontype.Type(0), typ, err, expectErrEOD, expectedKey) + readKeyDiff(t, "", k, Type(0), typ, err, expectErrEOD, expectedKey) } // expect subdoc to close k, typ, err = p.readKey() - readKeyDiff(t, "", k, bsontype.Type(0), typ, err, expectErrEOD, expectedKey) + readKeyDiff(t, "", k, Type(0), typ, err, expectErrEOD, expectedKey) } // 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, _ bsontype.Type, expectedValue interface{}) { +func expectArray(t *testing.T, p *extJSONParser, expectedKey string, _ Type, expectedValue interface{}) { ktvs := expectedValue.([]ejpKeyTypValTriple) k, typ, err := p.readKey() - readKeyDiff(t, expectedKey, k, bsontype.Array, typ, err, expectNoError, expectedKey) + readKeyDiff(t, expectedKey, k, TypeArray, typ, err, expectNoError, expectedKey) for _, ktv := range ktvs { eTyp := ktv.typ @@ -474,7 +473,7 @@ func expectArray(t *testing.T, p *extJSONParser, expectedKey string, _ bsontype. // expect array to end typ, err = p.peekType() - typDiff(t, bsontype.Type(0), typ, expectedKey) + typDiff(t, Type(0), typ, expectedKey) expectErrEOA(t, err, expectedKey) } @@ -517,76 +516,76 @@ func TestExtJSONParserAllTypes(t *testing.T) { cases := []ejpTestCase{ { f: expectSingleValue, p: ejp, - k: "_id", t: bsontype.ObjectID, v: &extJSONValue{t: bsontype.String, v: "57e193d7a9cc81b4027498b5"}, + k: "_id", t: TypeObjectID, v: &extJSONValue{t: TypeString, v: "57e193d7a9cc81b4027498b5"}, }, { f: expectSingleValue, p: ejp, - k: "Symbol", t: bsontype.Symbol, v: &extJSONValue{t: bsontype.String, v: "symbol"}, + k: "Symbol", t: TypeSymbol, v: &extJSONValue{t: TypeString, v: "symbol"}, }, { f: expectSingleValue, p: ejp, - k: "String", t: bsontype.String, v: &extJSONValue{t: bsontype.String, v: "string"}, + k: "String", t: TypeString, v: &extJSONValue{t: TypeString, v: "string"}, }, { f: expectSingleValue, p: ejp, - k: "Int32", t: bsontype.Int32, v: &extJSONValue{t: bsontype.String, v: "42"}, + k: "Int32", t: TypeInt32, v: &extJSONValue{t: TypeString, v: "42"}, }, { f: expectSingleValue, p: ejp, - k: "Int64", t: bsontype.Int64, v: &extJSONValue{t: bsontype.String, v: "42"}, + k: "Int64", t: TypeInt64, v: &extJSONValue{t: TypeString, v: "42"}, }, { f: expectSingleValue, p: ejp, - k: "Double", t: bsontype.Double, v: &extJSONValue{t: bsontype.String, v: "42.42"}, + k: "Double", t: TypeDouble, v: &extJSONValue{t: TypeString, v: "42.42"}, }, { f: expectSingleValue, p: ejp, - k: "SpecialFloat", t: bsontype.Double, v: &extJSONValue{t: bsontype.String, v: "NaN"}, + k: "SpecialFloat", t: TypeDouble, v: &extJSONValue{t: TypeString, v: "NaN"}, }, { f: expectSingleValue, p: ejp, - k: "Decimal", t: bsontype.Decimal128, v: &extJSONValue{t: bsontype.String, v: "1234"}, + k: "Decimal", t: TypeDecimal128, v: &extJSONValue{t: TypeString, v: "1234"}, }, { f: expectMultipleValues, p: ejp, - k: "Binary", t: bsontype.Binary, + k: "Binary", t: TypeBinary, v: &extJSONObject{ keys: []string{"base64", "subType"}, values: []*extJSONValue{ - {t: bsontype.String, v: "o0w498Or7cijeBSpkquNtg=="}, - {t: bsontype.String, v: "03"}, + {t: TypeString, v: "o0w498Or7cijeBSpkquNtg=="}, + {t: TypeString, v: "03"}, }, }, }, { f: expectMultipleValues, p: ejp, - k: "BinaryLegacy", t: bsontype.Binary, + k: "BinaryLegacy", t: TypeBinary, v: &extJSONObject{ keys: []string{"base64", "subType"}, values: []*extJSONValue{ - {t: bsontype.String, v: "o0w498Or7cijeBSpkquNtg=="}, - {t: bsontype.String, v: "03"}, + {t: TypeString, v: "o0w498Or7cijeBSpkquNtg=="}, + {t: TypeString, v: "03"}, }, }, }, { f: expectMultipleValues, p: ejp, - k: "BinaryUserDefined", t: bsontype.Binary, + k: "BinaryUserDefined", t: TypeBinary, v: &extJSONObject{ keys: []string{"base64", "subType"}, values: []*extJSONValue{ - {t: bsontype.String, v: "AQIDBAU="}, - {t: bsontype.String, v: "80"}, + {t: TypeString, v: "AQIDBAU="}, + {t: TypeString, v: "80"}, }, }, }, { f: expectSingleValue, p: ejp, - k: "Code", t: bsontype.JavaScript, v: &extJSONValue{t: bsontype.String, v: "function() {}"}, + k: "Code", t: TypeJavaScript, v: &extJSONValue{t: TypeString, v: "function() {}"}, }, { f: expectSubDocument, p: ejp, - k: "CodeWithEmptyScope", t: bsontype.CodeWithScope, + k: "CodeWithEmptyScope", t: TypeCodeWithScope, v: ejpSubDocumentTestValue{ code: "function() {}", ktvs: []ejpKeyTypValTriple{}, @@ -594,150 +593,150 @@ func TestExtJSONParserAllTypes(t *testing.T) { }, { f: expectSubDocument, p: ejp, - k: "CodeWithScope", t: bsontype.CodeWithScope, + k: "CodeWithScope", t: TypeCodeWithScope, v: ejpSubDocumentTestValue{ code: "function() {}", ktvs: []ejpKeyTypValTriple{ - {"x", bsontype.Int32, &extJSONValue{t: bsontype.Int32, v: int32(1)}}, + {"x", TypeInt32, &extJSONValue{t: TypeInt32, v: int32(1)}}, }, }, }, { f: expectSubDocument, p: ejp, - k: "EmptySubdocument", t: bsontype.EmbeddedDocument, + k: "EmptySubdocument", t: TypeEmbeddedDocument, v: ejpSubDocumentTestValue{ ktvs: []ejpKeyTypValTriple{}, }, }, { f: expectSubDocument, p: ejp, - k: "Subdocument", t: bsontype.EmbeddedDocument, + k: "Subdocument", t: TypeEmbeddedDocument, v: ejpSubDocumentTestValue{ ktvs: []ejpKeyTypValTriple{ - {"foo", bsontype.String, &extJSONValue{t: bsontype.String, v: "bar"}}, - {"baz", bsontype.Int32, &extJSONValue{t: bsontype.String, v: "42"}}, + {"foo", TypeString, &extJSONValue{t: TypeString, v: "bar"}}, + {"baz", TypeInt32, &extJSONValue{t: TypeString, v: "42"}}, }, }, }, { f: expectArray, p: ejp, - k: "Array", t: bsontype.Array, + k: "Array", t: TypeArray, v: []ejpKeyTypValTriple{ - {typ: bsontype.Int32, val: &extJSONValue{t: bsontype.String, v: "1"}}, - {typ: bsontype.Int64, val: &extJSONValue{t: bsontype.String, v: "2"}}, - {typ: bsontype.Double, val: &extJSONValue{t: bsontype.String, v: "3"}}, - {typ: bsontype.Int32, val: &extJSONValue{t: bsontype.Int32, v: int32(4)}}, - {typ: bsontype.String, val: &extJSONValue{t: bsontype.String, v: "string"}}, - {typ: bsontype.Double, val: &extJSONValue{t: bsontype.Double, v: 5.0}}, + {typ: TypeInt32, val: &extJSONValue{t: TypeString, v: "1"}}, + {typ: TypeInt64, val: &extJSONValue{t: TypeString, v: "2"}}, + {typ: TypeDouble, val: &extJSONValue{t: TypeString, v: "3"}}, + {typ: TypeInt32, val: &extJSONValue{t: TypeInt32, v: int32(4)}}, + {typ: TypeString, val: &extJSONValue{t: TypeString, v: "string"}}, + {typ: TypeDouble, val: &extJSONValue{t: TypeDouble, v: 5.0}}, }, }, { f: expectMultipleValues, p: ejp, - k: "Timestamp", t: bsontype.Timestamp, + k: "Timestamp", t: TypeTimestamp, v: &extJSONObject{ keys: []string{"t", "i"}, values: []*extJSONValue{ - {t: bsontype.Int32, v: int32(42)}, - {t: bsontype.Int32, v: int32(1)}, + {t: TypeInt32, v: int32(42)}, + {t: TypeInt32, v: int32(1)}, }, }, }, { f: expectMultipleValues, p: ejp, - k: "RegularExpression", t: bsontype.Regex, + k: "RegularExpression", t: TypeRegex, v: &extJSONObject{ keys: []string{"pattern", "options"}, values: []*extJSONValue{ - {t: bsontype.String, v: "foo*"}, - {t: bsontype.String, v: "ix"}, + {t: TypeString, v: "foo*"}, + {t: TypeString, v: "ix"}, }, }, }, { f: expectMultipleValues, p: ejp, - k: "DatetimeEpoch", t: bsontype.DateTime, + k: "DatetimeEpoch", t: TypeDateTime, v: &extJSONObject{ keys: []string{"$numberLong"}, values: []*extJSONValue{ - {t: bsontype.String, v: "0"}, + {t: TypeString, v: "0"}, }, }, }, { f: expectMultipleValues, p: ejp, - k: "DatetimePositive", t: bsontype.DateTime, + k: "DatetimePositive", t: TypeDateTime, v: &extJSONObject{ keys: []string{"$numberLong"}, values: []*extJSONValue{ - {t: bsontype.String, v: "9223372036854775807"}, + {t: TypeString, v: "9223372036854775807"}, }, }, }, { f: expectMultipleValues, p: ejp, - k: "DatetimeNegative", t: bsontype.DateTime, + k: "DatetimeNegative", t: TypeDateTime, v: &extJSONObject{ keys: []string{"$numberLong"}, values: []*extJSONValue{ - {t: bsontype.String, v: "-9223372036854775808"}, + {t: TypeString, v: "-9223372036854775808"}, }, }, }, { f: expectSingleValue, p: ejp, - k: "True", t: bsontype.Boolean, v: &extJSONValue{t: bsontype.Boolean, v: true}, + k: "True", t: TypeBoolean, v: &extJSONValue{t: TypeBoolean, v: true}, }, { f: expectSingleValue, p: ejp, - k: "False", t: bsontype.Boolean, v: &extJSONValue{t: bsontype.Boolean, v: false}, + k: "False", t: TypeBoolean, v: &extJSONValue{t: TypeBoolean, v: false}, }, { f: expectMultipleValues, p: ejp, - k: "DBPointer", t: bsontype.DBPointer, + k: "DBPointer", t: TypeDBPointer, v: &extJSONObject{ keys: []string{"$ref", "$id"}, values: []*extJSONValue{ - {t: bsontype.String, v: "db.collection"}, - {t: bsontype.String, v: "57e193d7a9cc81b4027498b1"}, + {t: TypeString, v: "db.collection"}, + {t: TypeString, v: "57e193d7a9cc81b4027498b1"}, }, }, }, { f: expectSubDocument, p: ejp, - k: "DBRef", t: bsontype.EmbeddedDocument, + k: "DBRef", t: TypeEmbeddedDocument, v: ejpSubDocumentTestValue{ ktvs: []ejpKeyTypValTriple{ - {"$ref", bsontype.String, &extJSONValue{t: bsontype.String, v: "collection"}}, - {"$id", bsontype.ObjectID, &extJSONValue{t: bsontype.String, v: "57fd71e96e32ab4225b723fb"}}, - {"$db", bsontype.String, &extJSONValue{t: bsontype.String, v: "database"}}, + {"$ref", TypeString, &extJSONValue{t: TypeString, v: "collection"}}, + {"$id", TypeObjectID, &extJSONValue{t: TypeString, v: "57fd71e96e32ab4225b723fb"}}, + {"$db", TypeString, &extJSONValue{t: TypeString, v: "database"}}, }, }, }, { f: expectSubDocument, p: ejp, - k: "DBRefNoDB", t: bsontype.EmbeddedDocument, + k: "DBRefNoDB", t: TypeEmbeddedDocument, v: ejpSubDocumentTestValue{ ktvs: []ejpKeyTypValTriple{ - {"$ref", bsontype.String, &extJSONValue{t: bsontype.String, v: "collection"}}, - {"$id", bsontype.ObjectID, &extJSONValue{t: bsontype.String, v: "57fd71e96e32ab4225b723fb"}}, + {"$ref", TypeString, &extJSONValue{t: TypeString, v: "collection"}}, + {"$id", TypeObjectID, &extJSONValue{t: TypeString, v: "57fd71e96e32ab4225b723fb"}}, }, }, }, { f: expectSingleValue, p: ejp, - k: "MinKey", t: bsontype.MinKey, v: &extJSONValue{t: bsontype.Int32, v: int32(1)}, + k: "MinKey", t: TypeMinKey, v: &extJSONValue{t: TypeInt32, v: int32(1)}, }, { f: expectSingleValue, p: ejp, - k: "MaxKey", t: bsontype.MaxKey, v: &extJSONValue{t: bsontype.Int32, v: int32(1)}, + k: "MaxKey", t: TypeMaxKey, v: &extJSONValue{t: TypeInt32, v: int32(1)}, }, { f: expectSingleValue, p: ejp, - k: "Null", t: bsontype.Null, v: &extJSONValue{t: bsontype.Null, v: nil}, + k: "Null", t: TypeNull, v: &extJSONValue{t: TypeNull, v: nil}, }, { f: expectSingleValue, p: ejp, - k: "Undefined", t: bsontype.Undefined, v: &extJSONValue{t: bsontype.Boolean, v: true}, + k: "Undefined", t: TypeUndefined, v: &extJSONValue{t: TypeBoolean, v: true}, }, } @@ -748,11 +747,11 @@ func TestExtJSONParserAllTypes(t *testing.T) { // expect end of whole document: read final } k, typ, err := ejp.readKey() - readKeyDiff(t, "", k, bsontype.Type(0), typ, err, expectErrEOD, "") + readKeyDiff(t, "", k, Type(0), typ, err, expectErrEOD, "") // expect end of whole document: read EOF k, typ, err = ejp.readKey() - readKeyDiff(t, "", k, bsontype.Type(0), typ, err, expectErrEOF, "") + readKeyDiff(t, "", k, Type(0), typ, err, expectErrEOF, "") if diff := cmp.Diff(jpsDoneState, ejp.s); diff != "" { t.Errorf("expected parser to be in done state but instead is in %v\n", ejp.s) t.FailNow() @@ -762,7 +761,7 @@ func TestExtJSONParserAllTypes(t *testing.T) { func TestExtJSONValue(t *testing.T) { t.Run("Large Date", func(t *testing.T) { val := &extJSONValue{ - t: bsontype.String, + t: TypeString, v: "3001-01-01T00:00:00Z", } @@ -777,7 +776,7 @@ func TestExtJSONValue(t *testing.T) { }) t.Run("fallback time format", func(t *testing.T) { val := &extJSONValue{ - t: bsontype.String, + t: TypeString, v: "2019-06-04T14:54:31.416+0000", } diff --git a/bson/extjson_prose_test.go b/bson/extjson_prose_test.go index 704cc82894..9177a4e3fe 100644 --- a/bson/extjson_prose_test.go +++ b/bson/extjson_prose_test.go @@ -10,7 +10,6 @@ import ( "fmt" "testing" - "go.mongodb.org/mongo-driver/bson/bsonrw" "go.mongodb.org/mongo-driver/internal/assert" ) @@ -29,7 +28,7 @@ func TestExtJSON(t *testing.T) { {"timestamp - negative int64 value", `{"":{"$timestamp":{"t":0,"i":-2147483649}}}`, false, timestampNegativeInt64Err}, {"timestamp - value overflows uint32", `{"":{"$timestamp":{"t":0,"i":4294967296}}}`, false, timestampLargeValueErr}, {"top level key is not treated as special", `{"$code": "foo"}`, false, nil}, - {"escaped single quote errors", `{"f\'oo": "bar"}`, false, bsonrw.ErrInvalidJSON}, + {"escaped single quote errors", `{"f\'oo": "bar"}`, false, ErrInvalidJSON}, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { diff --git a/bson/bsonrw/extjson_reader.go b/bson/extjson_reader.go similarity index 74% rename from bson/bsonrw/extjson_reader.go rename to bson/extjson_reader.go index 59ddfc4485..7395cc5d0c 100644 --- a/bson/bsonrw/extjson_reader.go +++ b/bson/extjson_reader.go @@ -4,16 +4,13 @@ // 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 bsonrw +package bson import ( "errors" "fmt" "io" "sync" - - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" ) // ExtJSONValueReaderPool is a pool for ValueReaders that read ExtJSON. @@ -61,7 +58,7 @@ func (bvrp *ExtJSONValueReaderPool) Put(vr ValueReader) (ok bool) { type ejvrState struct { mode mode - vType bsontype.Type + vType Type depth int } @@ -95,9 +92,9 @@ func (ejvr *extJSONValueReader) reset(r io.Reader, canonical bool) (*extJSONValu var m mode switch typ { - case bsontype.EmbeddedDocument: + case TypeEmbeddedDocument: m = mTopLevel - case bsontype.Array: + case TypeArray: m = mArray default: m = mValue @@ -152,7 +149,7 @@ func (ejvr *extJSONValueReader) pushArray() { ejvr.stack[ejvr.frame].mode = mArray } -func (ejvr *extJSONValueReader) push(m mode, t bsontype.Type) { +func (ejvr *extJSONValueReader) push(m mode, t Type) { ejvr.advanceFrame() ejvr.stack[ejvr.frame].mode = m @@ -213,11 +210,11 @@ func (ejvr *extJSONValueReader) invalidTransitionErr(destination mode, name stri return te } -func (ejvr *extJSONValueReader) typeError(t bsontype.Type) error { +func (ejvr *extJSONValueReader) typeError(t Type) error { return fmt.Errorf("positioned on %s, but attempted to read %s", ejvr.stack[ejvr.frame].vType, t) } -func (ejvr *extJSONValueReader) ensureElementValue(t bsontype.Type, destination mode, callerName string, addModes ...mode) error { +func (ejvr *extJSONValueReader) ensureElementValue(t Type, destination mode, callerName string, addModes ...mode) error { switch ejvr.stack[ejvr.frame].mode { case mElement, mValue: if ejvr.stack[ejvr.frame].vType != t { @@ -234,7 +231,7 @@ func (ejvr *extJSONValueReader) ensureElementValue(t bsontype.Type, destination return nil } -func (ejvr *extJSONValueReader) Type() bsontype.Type { +func (ejvr *extJSONValueReader) Type() Type { return ejvr.stack[ejvr.frame].vType } @@ -249,7 +246,7 @@ func (ejvr *extJSONValueReader) Skip() error { t := ejvr.stack[ejvr.frame].vType switch t { - case bsontype.Array, bsontype.EmbeddedDocument, bsontype.CodeWithScope: + case TypeArray, TypeEmbeddedDocument, TypeCodeWithScope: // read entire array, doc or CodeWithScope ejvr.skipObject() default: @@ -268,7 +265,7 @@ func (ejvr *extJSONValueReader) ReadArray() (ArrayReader, error) { case mArray: return ejvr, nil default: - if err := ejvr.ensureElementValue(bsontype.Array, mArray, "ReadArray", mTopLevel, mArray); err != nil { + if err := ejvr.ensureElementValue(TypeArray, mArray, "ReadArray", mTopLevel, mArray); err != nil { return nil, err } } @@ -279,11 +276,11 @@ func (ejvr *extJSONValueReader) ReadArray() (ArrayReader, error) { } func (ejvr *extJSONValueReader) ReadBinary() (b []byte, btype byte, err error) { - if err := ejvr.ensureElementValue(bsontype.Binary, 0, "ReadBinary"); err != nil { + if err := ejvr.ensureElementValue(TypeBinary, 0, "ReadBinary"); err != nil { return nil, 0, err } - v, err := ejvr.p.readValue(bsontype.Binary) + v, err := ejvr.p.readValue(TypeBinary) if err != nil { return nil, 0, err } @@ -295,16 +292,16 @@ func (ejvr *extJSONValueReader) ReadBinary() (b []byte, btype byte, err error) { } func (ejvr *extJSONValueReader) ReadBoolean() (bool, error) { - if err := ejvr.ensureElementValue(bsontype.Boolean, 0, "ReadBoolean"); err != nil { + if err := ejvr.ensureElementValue(TypeBoolean, 0, "ReadBoolean"); err != nil { return false, err } - v, err := ejvr.p.readValue(bsontype.Boolean) + v, err := ejvr.p.readValue(TypeBoolean) if err != nil { return false, err } - if v.t != bsontype.Boolean { + if v.t != TypeBoolean { return false, fmt.Errorf("expected type bool, but got type %s", v.t) } @@ -317,8 +314,8 @@ func (ejvr *extJSONValueReader) ReadDocument() (DocumentReader, error) { case mTopLevel: return ejvr, nil case mElement, mValue: - if ejvr.stack[ejvr.frame].vType != bsontype.EmbeddedDocument { - return nil, ejvr.typeError(bsontype.EmbeddedDocument) + if ejvr.stack[ejvr.frame].vType != TypeEmbeddedDocument { + return nil, ejvr.typeError(TypeEmbeddedDocument) } ejvr.pushDocument() @@ -329,11 +326,11 @@ func (ejvr *extJSONValueReader) ReadDocument() (DocumentReader, error) { } func (ejvr *extJSONValueReader) ReadCodeWithScope() (code string, dr DocumentReader, err error) { - if err = ejvr.ensureElementValue(bsontype.CodeWithScope, 0, "ReadCodeWithScope"); err != nil { + if err = ejvr.ensureElementValue(TypeCodeWithScope, 0, "ReadCodeWithScope"); err != nil { return "", nil, err } - v, err := ejvr.p.readValue(bsontype.CodeWithScope) + v, err := ejvr.p.readValue(TypeCodeWithScope) if err != nil { return "", nil, err } @@ -344,14 +341,14 @@ func (ejvr *extJSONValueReader) ReadCodeWithScope() (code string, dr DocumentRea return code, ejvr, err } -func (ejvr *extJSONValueReader) ReadDBPointer() (ns string, oid primitive.ObjectID, err error) { - if err = ejvr.ensureElementValue(bsontype.DBPointer, 0, "ReadDBPointer"); err != nil { - return "", primitive.NilObjectID, err +func (ejvr *extJSONValueReader) ReadDBPointer() (ns string, oid ObjectID, err error) { + if err = ejvr.ensureElementValue(TypeDBPointer, 0, "ReadDBPointer"); err != nil { + return "", NilObjectID, err } - v, err := ejvr.p.readValue(bsontype.DBPointer) + v, err := ejvr.p.readValue(TypeDBPointer) if err != nil { - return "", primitive.NilObjectID, err + return "", NilObjectID, err } ns, oid, err = v.parseDBPointer() @@ -361,11 +358,11 @@ func (ejvr *extJSONValueReader) ReadDBPointer() (ns string, oid primitive.Object } func (ejvr *extJSONValueReader) ReadDateTime() (int64, error) { - if err := ejvr.ensureElementValue(bsontype.DateTime, 0, "ReadDateTime"); err != nil { + if err := ejvr.ensureElementValue(TypeDateTime, 0, "ReadDateTime"); err != nil { return 0, err } - v, err := ejvr.p.readValue(bsontype.DateTime) + v, err := ejvr.p.readValue(TypeDateTime) if err != nil { return 0, err } @@ -376,14 +373,14 @@ func (ejvr *extJSONValueReader) ReadDateTime() (int64, error) { return d, err } -func (ejvr *extJSONValueReader) ReadDecimal128() (primitive.Decimal128, error) { - if err := ejvr.ensureElementValue(bsontype.Decimal128, 0, "ReadDecimal128"); err != nil { - return primitive.Decimal128{}, err +func (ejvr *extJSONValueReader) ReadDecimal128() (Decimal128, error) { + if err := ejvr.ensureElementValue(TypeDecimal128, 0, "ReadDecimal128"); err != nil { + return Decimal128{}, err } - v, err := ejvr.p.readValue(bsontype.Decimal128) + v, err := ejvr.p.readValue(TypeDecimal128) if err != nil { - return primitive.Decimal128{}, err + return Decimal128{}, err } d, err := v.parseDecimal128() @@ -393,11 +390,11 @@ func (ejvr *extJSONValueReader) ReadDecimal128() (primitive.Decimal128, error) { } func (ejvr *extJSONValueReader) ReadDouble() (float64, error) { - if err := ejvr.ensureElementValue(bsontype.Double, 0, "ReadDouble"); err != nil { + if err := ejvr.ensureElementValue(TypeDouble, 0, "ReadDouble"); err != nil { return 0, err } - v, err := ejvr.p.readValue(bsontype.Double) + v, err := ejvr.p.readValue(TypeDouble) if err != nil { return 0, err } @@ -409,11 +406,11 @@ func (ejvr *extJSONValueReader) ReadDouble() (float64, error) { } func (ejvr *extJSONValueReader) ReadInt32() (int32, error) { - if err := ejvr.ensureElementValue(bsontype.Int32, 0, "ReadInt32"); err != nil { + if err := ejvr.ensureElementValue(TypeInt32, 0, "ReadInt32"); err != nil { return 0, err } - v, err := ejvr.p.readValue(bsontype.Int32) + v, err := ejvr.p.readValue(TypeInt32) if err != nil { return 0, err } @@ -425,11 +422,11 @@ func (ejvr *extJSONValueReader) ReadInt32() (int32, error) { } func (ejvr *extJSONValueReader) ReadInt64() (int64, error) { - if err := ejvr.ensureElementValue(bsontype.Int64, 0, "ReadInt64"); err != nil { + if err := ejvr.ensureElementValue(TypeInt64, 0, "ReadInt64"); err != nil { return 0, err } - v, err := ejvr.p.readValue(bsontype.Int64) + v, err := ejvr.p.readValue(TypeInt64) if err != nil { return 0, err } @@ -441,11 +438,11 @@ func (ejvr *extJSONValueReader) ReadInt64() (int64, error) { } func (ejvr *extJSONValueReader) ReadJavascript() (code string, err error) { - if err = ejvr.ensureElementValue(bsontype.JavaScript, 0, "ReadJavascript"); err != nil { + if err = ejvr.ensureElementValue(TypeJavaScript, 0, "ReadJavascript"); err != nil { return "", err } - v, err := ejvr.p.readValue(bsontype.JavaScript) + v, err := ejvr.p.readValue(TypeJavaScript) if err != nil { return "", err } @@ -457,11 +454,11 @@ func (ejvr *extJSONValueReader) ReadJavascript() (code string, err error) { } func (ejvr *extJSONValueReader) ReadMaxKey() error { - if err := ejvr.ensureElementValue(bsontype.MaxKey, 0, "ReadMaxKey"); err != nil { + if err := ejvr.ensureElementValue(TypeMaxKey, 0, "ReadMaxKey"); err != nil { return err } - v, err := ejvr.p.readValue(bsontype.MaxKey) + v, err := ejvr.p.readValue(TypeMaxKey) if err != nil { return err } @@ -473,11 +470,11 @@ func (ejvr *extJSONValueReader) ReadMaxKey() error { } func (ejvr *extJSONValueReader) ReadMinKey() error { - if err := ejvr.ensureElementValue(bsontype.MinKey, 0, "ReadMinKey"); err != nil { + if err := ejvr.ensureElementValue(TypeMinKey, 0, "ReadMinKey"); err != nil { return err } - v, err := ejvr.p.readValue(bsontype.MinKey) + v, err := ejvr.p.readValue(TypeMinKey) if err != nil { return err } @@ -489,16 +486,16 @@ func (ejvr *extJSONValueReader) ReadMinKey() error { } func (ejvr *extJSONValueReader) ReadNull() error { - if err := ejvr.ensureElementValue(bsontype.Null, 0, "ReadNull"); err != nil { + if err := ejvr.ensureElementValue(TypeNull, 0, "ReadNull"); err != nil { return err } - v, err := ejvr.p.readValue(bsontype.Null) + v, err := ejvr.p.readValue(TypeNull) if err != nil { return err } - if v.t != bsontype.Null { + if v.t != TypeNull { return fmt.Errorf("expected type null but got type %s", v.t) } @@ -506,14 +503,14 @@ func (ejvr *extJSONValueReader) ReadNull() error { return nil } -func (ejvr *extJSONValueReader) ReadObjectID() (primitive.ObjectID, error) { - if err := ejvr.ensureElementValue(bsontype.ObjectID, 0, "ReadObjectID"); err != nil { - return primitive.ObjectID{}, err +func (ejvr *extJSONValueReader) ReadObjectID() (ObjectID, error) { + if err := ejvr.ensureElementValue(TypeObjectID, 0, "ReadObjectID"); err != nil { + return ObjectID{}, err } - v, err := ejvr.p.readValue(bsontype.ObjectID) + v, err := ejvr.p.readValue(TypeObjectID) if err != nil { - return primitive.ObjectID{}, err + return ObjectID{}, err } oid, err := v.parseObjectID() @@ -523,11 +520,11 @@ func (ejvr *extJSONValueReader) ReadObjectID() (primitive.ObjectID, error) { } func (ejvr *extJSONValueReader) ReadRegex() (pattern string, options string, err error) { - if err = ejvr.ensureElementValue(bsontype.Regex, 0, "ReadRegex"); err != nil { + if err = ejvr.ensureElementValue(TypeRegex, 0, "ReadRegex"); err != nil { return "", "", err } - v, err := ejvr.p.readValue(bsontype.Regex) + v, err := ejvr.p.readValue(TypeRegex) if err != nil { return "", "", err } @@ -539,16 +536,16 @@ func (ejvr *extJSONValueReader) ReadRegex() (pattern string, options string, err } func (ejvr *extJSONValueReader) ReadString() (string, error) { - if err := ejvr.ensureElementValue(bsontype.String, 0, "ReadString"); err != nil { + if err := ejvr.ensureElementValue(TypeString, 0, "ReadString"); err != nil { return "", err } - v, err := ejvr.p.readValue(bsontype.String) + v, err := ejvr.p.readValue(TypeString) if err != nil { return "", err } - if v.t != bsontype.String { + if v.t != TypeString { return "", fmt.Errorf("expected type string but got type %s", v.t) } @@ -557,11 +554,11 @@ func (ejvr *extJSONValueReader) ReadString() (string, error) { } func (ejvr *extJSONValueReader) ReadSymbol() (symbol string, err error) { - if err = ejvr.ensureElementValue(bsontype.Symbol, 0, "ReadSymbol"); err != nil { + if err = ejvr.ensureElementValue(TypeSymbol, 0, "ReadSymbol"); err != nil { return "", err } - v, err := ejvr.p.readValue(bsontype.Symbol) + v, err := ejvr.p.readValue(TypeSymbol) if err != nil { return "", err } @@ -573,11 +570,11 @@ func (ejvr *extJSONValueReader) ReadSymbol() (symbol string, err error) { } func (ejvr *extJSONValueReader) ReadTimestamp() (t uint32, i uint32, err error) { - if err = ejvr.ensureElementValue(bsontype.Timestamp, 0, "ReadTimestamp"); err != nil { + if err = ejvr.ensureElementValue(TypeTimestamp, 0, "ReadTimestamp"); err != nil { return 0, 0, err } - v, err := ejvr.p.readValue(bsontype.Timestamp) + v, err := ejvr.p.readValue(TypeTimestamp) if err != nil { return 0, 0, err } @@ -589,11 +586,11 @@ func (ejvr *extJSONValueReader) ReadTimestamp() (t uint32, i uint32, err error) } func (ejvr *extJSONValueReader) ReadUndefined() error { - if err := ejvr.ensureElementValue(bsontype.Undefined, 0, "ReadUndefined"); err != nil { + if err := ejvr.ensureElementValue(TypeUndefined, 0, "ReadUndefined"); err != nil { return err } - v, err := ejvr.p.readValue(bsontype.Undefined) + v, err := ejvr.p.readValue(TypeUndefined) if err != nil { return err } diff --git a/bson/bsonrw/extjson_reader_test.go b/bson/extjson_reader_test.go similarity index 92% rename from bson/bsonrw/extjson_reader_test.go rename to bson/extjson_reader_test.go index 4f790033a1..a3a2d67cd5 100644 --- a/bson/bsonrw/extjson_reader_test.go +++ b/bson/extjson_reader_test.go @@ -4,7 +4,7 @@ // 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 bsonrw +package bson import ( "errors" @@ -14,7 +14,7 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/internal/assert" ) func TestExtJSONReader(t *testing.T) { @@ -23,7 +23,7 @@ func TestExtJSONReader(t *testing.T) { ejvr := &extJSONValueReader{ stack: []ejvrState{ {mode: mTopLevel}, - {mode: mElement, vType: bsontype.Boolean}, + {mode: mElement, vType: TypeBoolean}, }, frame: 1, } @@ -43,7 +43,7 @@ func TestExtJSONReader(t *testing.T) { ejvr := &extJSONValueReader{stack: []ejvrState{{mode: mTopLevel}}} wanterr := (&extJSONValueReader{stack: []ejvrState{{mode: mTopLevel}}}).invalidTransitionErr(0, "Skip", []mode{mElement, mValue}) goterr := ejvr.Skip() - if !cmp.Equal(goterr, wanterr, cmp.Comparer(compareErrors)) { + if !cmp.Equal(goterr, wanterr, cmp.Comparer(assert.CompareErrors)) { t.Errorf("Expected correct invalid transition error. got %v; want %v", goterr, wanterr) } }) @@ -124,13 +124,12 @@ func TestReadMultipleTopLevelDocuments(t *testing.T) { } func readAllDocuments(vr ValueReader) ([][]byte, error) { - c := NewCopier() var actual [][]byte switch vr.Type() { - case bsontype.EmbeddedDocument: + case TypeEmbeddedDocument: for { - result, err := c.CopyDocumentToBytes(vr) + result, err := copyDocumentToBytes(vr) if err != nil { if errors.Is(err, io.EOF) { break @@ -140,7 +139,7 @@ func readAllDocuments(vr ValueReader) ([][]byte, error) { actual = append(actual, result) } - case bsontype.Array: + case TypeArray: ar, err := vr.ReadArray() if err != nil { return nil, err @@ -154,7 +153,7 @@ func readAllDocuments(vr ValueReader) ([][]byte, error) { return nil, err } - result, err := c.CopyDocumentToBytes(evr) + result, err := copyDocumentToBytes(evr) if err != nil { return nil, err } diff --git a/bson/bsonrw/extjson_tables.go b/bson/extjson_tables.go similarity index 99% rename from bson/bsonrw/extjson_tables.go rename to bson/extjson_tables.go index ba39c9601f..5384db225d 100644 --- a/bson/bsonrw/extjson_tables.go +++ b/bson/extjson_tables.go @@ -7,7 +7,7 @@ // Based on github.com/golang/go by The Go Authors // See THIRD-PARTY-NOTICES for original license terms. -package bsonrw +package bson import "unicode/utf8" diff --git a/bson/bsonrw/extjson_wrappers.go b/bson/extjson_wrappers.go similarity index 75% rename from bson/bsonrw/extjson_wrappers.go rename to bson/extjson_wrappers.go index 9695704246..69ac78ccb5 100644 --- a/bson/bsonrw/extjson_wrappers.go +++ b/bson/extjson_wrappers.go @@ -4,7 +4,7 @@ // 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 bsonrw +package bson import ( "encoding/base64" @@ -13,52 +13,49 @@ import ( "math" "strconv" "time" - - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" ) -func wrapperKeyBSONType(key string) bsontype.Type { +func wrapperKeyBSONType(key string) Type { switch key { case "$numberInt": - return bsontype.Int32 + return TypeInt32 case "$numberLong": - return bsontype.Int64 + return TypeInt64 case "$oid": - return bsontype.ObjectID + return TypeObjectID case "$symbol": - return bsontype.Symbol + return TypeSymbol case "$numberDouble": - return bsontype.Double + return TypeDouble case "$numberDecimal": - return bsontype.Decimal128 + return TypeDecimal128 case "$binary": - return bsontype.Binary + return TypeBinary case "$code": - return bsontype.JavaScript + return TypeJavaScript case "$scope": - return bsontype.CodeWithScope + return TypeCodeWithScope case "$timestamp": - return bsontype.Timestamp + return TypeTimestamp case "$regularExpression": - return bsontype.Regex + return TypeRegex case "$dbPointer": - return bsontype.DBPointer + return TypeDBPointer case "$date": - return bsontype.DateTime + return TypeDateTime case "$minKey": - return bsontype.MinKey + return TypeMinKey case "$maxKey": - return bsontype.MaxKey + return TypeMaxKey case "$undefined": - return bsontype.Undefined + return TypeUndefined } - return bsontype.EmbeddedDocument + return TypeEmbeddedDocument } func (ejv *extJSONValue) parseBinary() (b []byte, subType byte, err error) { - if ejv.t != bsontype.EmbeddedDocument { + if ejv.t != TypeEmbeddedDocument { return nil, 0, fmt.Errorf("$binary value should be object, but instead is %s", ejv.t) } @@ -75,7 +72,7 @@ func (ejv *extJSONValue) parseBinary() (b []byte, subType byte, err error) { return nil, 0, errors.New("duplicate base64 key in $binary") } - if val.t != bsontype.String { + if val.t != TypeString { return nil, 0, fmt.Errorf("$binary base64 value should be string, but instead is %s", val.t) } @@ -91,7 +88,7 @@ func (ejv *extJSONValue) parseBinary() (b []byte, subType byte, err error) { return nil, 0, errors.New("duplicate subType key in $binary") } - if val.t != bsontype.String { + if val.t != TypeString { return nil, 0, fmt.Errorf("$binary subType value should be string, but instead is %s", val.t) } @@ -119,9 +116,9 @@ func (ejv *extJSONValue) parseBinary() (b []byte, subType byte, err error) { return b, subType, nil } -func (ejv *extJSONValue) parseDBPointer() (ns string, oid primitive.ObjectID, err error) { - if ejv.t != bsontype.EmbeddedDocument { - return "", primitive.NilObjectID, fmt.Errorf("$dbPointer value should be object, but instead is %s", ejv.t) +func (ejv *extJSONValue) parseDBPointer() (ns string, oid ObjectID, err error) { + if ejv.t != TypeEmbeddedDocument { + return "", NilObjectID, fmt.Errorf("$dbPointer value should be object, but instead is %s", ejv.t) } dbpObj := ejv.v.(*extJSONObject) @@ -134,32 +131,32 @@ func (ejv *extJSONValue) parseDBPointer() (ns string, oid primitive.ObjectID, er switch key { case "$ref": if nsFound { - return "", primitive.NilObjectID, errors.New("duplicate $ref key in $dbPointer") + return "", NilObjectID, errors.New("duplicate $ref key in $dbPointer") } - if val.t != bsontype.String { - return "", primitive.NilObjectID, fmt.Errorf("$dbPointer $ref value should be string, but instead is %s", val.t) + if val.t != TypeString { + return "", NilObjectID, fmt.Errorf("$dbPointer $ref value should be string, but instead is %s", val.t) } ns = val.v.(string) nsFound = true case "$id": if oidFound { - return "", primitive.NilObjectID, errors.New("duplicate $id key in $dbPointer") + return "", NilObjectID, errors.New("duplicate $id key in $dbPointer") } - if val.t != bsontype.String { - return "", primitive.NilObjectID, fmt.Errorf("$dbPointer $id value should be string, but instead is %s", val.t) + if val.t != TypeString { + return "", NilObjectID, fmt.Errorf("$dbPointer $id value should be string, but instead is %s", val.t) } - oid, err = primitive.ObjectIDFromHex(val.v.(string)) + oid, err = ObjectIDFromHex(val.v.(string)) if err != nil { - return "", primitive.NilObjectID, err + return "", NilObjectID, err } oidFound = true default: - return "", primitive.NilObjectID, fmt.Errorf("invalid key in $dbPointer object: %s", key) + return "", NilObjectID, fmt.Errorf("invalid key in $dbPointer object: %s", key) } } @@ -184,13 +181,13 @@ var ( func (ejv *extJSONValue) parseDateTime() (int64, error) { switch ejv.t { - case bsontype.Int32: + case TypeInt32: return int64(ejv.v.(int32)), nil - case bsontype.Int64: + case TypeInt64: return ejv.v.(int64), nil - case bsontype.String: + case TypeString: return parseDatetimeString(ejv.v.(string)) - case bsontype.EmbeddedDocument: + case TypeEmbeddedDocument: return parseDatetimeObject(ejv.v.(*extJSONObject)) default: return 0, fmt.Errorf("$date value should be string or object, but instead is %s", ejv.t) @@ -211,7 +208,7 @@ func parseDatetimeString(data string) (int64, error) { return 0, fmt.Errorf("invalid $date value string: %s", data) } - return int64(primitive.NewDateTimeFromTime(t)), nil + return int64(NewDateTimeFromTime(t)), nil } func parseDatetimeObject(data *extJSONObject) (d int64, err error) { @@ -226,7 +223,7 @@ func parseDatetimeObject(data *extJSONObject) (d int64, err error) { return 0, errors.New("duplicate $numberLong key in $date") } - if val.t != bsontype.String { + if val.t != TypeString { return 0, fmt.Errorf("$date $numberLong field should be string, but instead is %s", val.t) } @@ -247,25 +244,25 @@ func parseDatetimeObject(data *extJSONObject) (d int64, err error) { return d, nil } -func (ejv *extJSONValue) parseDecimal128() (primitive.Decimal128, error) { - if ejv.t != bsontype.String { - return primitive.Decimal128{}, fmt.Errorf("$numberDecimal value should be string, but instead is %s", ejv.t) +func (ejv *extJSONValue) parseDecimal128() (Decimal128, error) { + if ejv.t != TypeString { + return Decimal128{}, fmt.Errorf("$numberDecimal value should be string, but instead is %s", ejv.t) } - d, err := primitive.ParseDecimal128(ejv.v.(string)) + d, err := ParseDecimal128(ejv.v.(string)) if err != nil { - return primitive.Decimal128{}, fmt.Errorf("$invalid $numberDecimal string: %s", ejv.v.(string)) + return Decimal128{}, fmt.Errorf("$invalid $numberDecimal string: %s", ejv.v.(string)) } return d, nil } func (ejv *extJSONValue) parseDouble() (float64, error) { - if ejv.t == bsontype.Double { + if ejv.t == TypeDouble { return ejv.v.(float64), nil } - if ejv.t != bsontype.String { + if ejv.t != TypeString { return 0, fmt.Errorf("$numberDouble value should be string, but instead is %s", ejv.t) } @@ -287,11 +284,11 @@ func (ejv *extJSONValue) parseDouble() (float64, error) { } func (ejv *extJSONValue) parseInt32() (int32, error) { - if ejv.t == bsontype.Int32 { + if ejv.t == TypeInt32 { return ejv.v.(int32), nil } - if ejv.t != bsontype.String { + if ejv.t != TypeString { return 0, fmt.Errorf("$numberInt value should be string, but instead is %s", ejv.t) } @@ -308,11 +305,11 @@ func (ejv *extJSONValue) parseInt32() (int32, error) { } func (ejv *extJSONValue) parseInt64() (int64, error) { - if ejv.t == bsontype.Int64 { + if ejv.t == TypeInt64 { return ejv.v.(int64), nil } - if ejv.t != bsontype.String { + if ejv.t != TypeString { return 0, fmt.Errorf("$numberLong value should be string, but instead is %s", ejv.t) } @@ -325,7 +322,7 @@ func (ejv *extJSONValue) parseInt64() (int64, error) { } func (ejv *extJSONValue) parseJavascript() (code string, err error) { - if ejv.t != bsontype.String { + if ejv.t != TypeString { return "", fmt.Errorf("$code value should be string, but instead is %s", ejv.t) } @@ -333,7 +330,7 @@ func (ejv *extJSONValue) parseJavascript() (code string, err error) { } func (ejv *extJSONValue) parseMinMaxKey(minmax string) error { - if ejv.t != bsontype.Int32 { + if ejv.t != TypeInt32 { return fmt.Errorf("$%sKey value should be int32, but instead is %s", minmax, ejv.t) } @@ -344,16 +341,16 @@ func (ejv *extJSONValue) parseMinMaxKey(minmax string) error { return nil } -func (ejv *extJSONValue) parseObjectID() (primitive.ObjectID, error) { - if ejv.t != bsontype.String { - return primitive.NilObjectID, fmt.Errorf("$oid value should be string, but instead is %s", ejv.t) +func (ejv *extJSONValue) parseObjectID() (ObjectID, error) { + if ejv.t != TypeString { + return NilObjectID, fmt.Errorf("$oid value should be string, but instead is %s", ejv.t) } - return primitive.ObjectIDFromHex(ejv.v.(string)) + return ObjectIDFromHex(ejv.v.(string)) } func (ejv *extJSONValue) parseRegex() (pattern, options string, err error) { - if ejv.t != bsontype.EmbeddedDocument { + if ejv.t != TypeEmbeddedDocument { return "", "", fmt.Errorf("$regularExpression value should be object, but instead is %s", ejv.t) } @@ -370,7 +367,7 @@ func (ejv *extJSONValue) parseRegex() (pattern, options string, err error) { return "", "", errors.New("duplicate pattern key in $regularExpression") } - if val.t != bsontype.String { + if val.t != TypeString { return "", "", fmt.Errorf("$regularExpression pattern value should be string, but instead is %s", val.t) } @@ -381,7 +378,7 @@ func (ejv *extJSONValue) parseRegex() (pattern, options string, err error) { return "", "", errors.New("duplicate options key in $regularExpression") } - if val.t != bsontype.String { + if val.t != TypeString { return "", "", fmt.Errorf("$regularExpression options value should be string, but instead is %s", val.t) } @@ -405,7 +402,7 @@ func (ejv *extJSONValue) parseRegex() (pattern, options string, err error) { } func (ejv *extJSONValue) parseSymbol() (string, error) { - if ejv.t != bsontype.String { + if ejv.t != TypeString { return "", fmt.Errorf("$symbol value should be string, but instead is %s", ejv.t) } @@ -413,7 +410,7 @@ func (ejv *extJSONValue) parseSymbol() (string, error) { } func (ejv *extJSONValue) parseTimestamp() (t, i uint32, err error) { - if ejv.t != bsontype.EmbeddedDocument { + if ejv.t != TypeEmbeddedDocument { return 0, 0, fmt.Errorf("$timestamp value should be object, but instead is %s", ejv.t) } @@ -423,7 +420,7 @@ func (ejv *extJSONValue) parseTimestamp() (t, i uint32, err error) { } switch val.t { - case bsontype.Int32: + case TypeInt32: value := val.v.(int32) if value < 0 { @@ -431,7 +428,7 @@ func (ejv *extJSONValue) parseTimestamp() (t, i uint32, err error) { } return uint32(value), nil - case bsontype.Int64: + case TypeInt64: value := val.v.(int64) if value < 0 || value > int64(math.MaxUint32) { return 0, fmt.Errorf("$timestamp %s number should be uint32: %d", key, value) @@ -480,7 +477,7 @@ func (ejv *extJSONValue) parseTimestamp() (t, i uint32, err error) { } func (ejv *extJSONValue) parseUndefined() error { - if ejv.t != bsontype.Boolean { + if ejv.t != TypeBoolean { return fmt.Errorf("undefined value should be boolean, but instead is %s", ejv.t) } diff --git a/bson/bsonrw/extjson_writer.go b/bson/extjson_writer.go similarity index 97% rename from bson/bsonrw/extjson_writer.go rename to bson/extjson_writer.go index 78f9fa6173..a060aeed75 100644 --- a/bson/bsonrw/extjson_writer.go +++ b/bson/extjson_writer.go @@ -4,7 +4,7 @@ // 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 bsonrw +package bson import ( "bytes" @@ -18,8 +18,6 @@ import ( "sync" "time" "unicode/utf8" - - "go.mongodb.org/mongo-driver/bson/primitive" ) // ExtJSONValueWriterPool is a pool for ExtJSON ValueWriters. @@ -266,7 +264,7 @@ func (ejvw *extJSONValueWriter) WriteCodeWithScope(code string) (DocumentWriter, return ejvw, nil } -func (ejvw *extJSONValueWriter) WriteDBPointer(ns string, oid primitive.ObjectID) error { +func (ejvw *extJSONValueWriter) WriteDBPointer(ns string, oid ObjectID) error { if err := ejvw.ensureElementValue(mode(0), "WriteDBPointer"); err != nil { return err } @@ -304,7 +302,7 @@ func (ejvw *extJSONValueWriter) WriteDateTime(dt int64) error { return nil } -func (ejvw *extJSONValueWriter) WriteDecimal128(d primitive.Decimal128) error { +func (ejvw *extJSONValueWriter) WriteDecimal128(d Decimal128) error { if err := ejvw.ensureElementValue(mode(0), "WriteDecimal128"); err != nil { return err } @@ -447,7 +445,7 @@ func (ejvw *extJSONValueWriter) WriteNull() error { return nil } -func (ejvw *extJSONValueWriter) WriteObjectID(oid primitive.ObjectID) error { +func (ejvw *extJSONValueWriter) WriteObjectID(oid ObjectID) error { if err := ejvw.ensureElementValue(mode(0), "WriteObjectID"); err != nil { return err } @@ -575,7 +573,7 @@ func (ejvw *extJSONValueWriter) WriteDocumentEnd() error { case mTopLevel: // If the value writer has newlines enabled, end top-level documents with a newline so that // multiple documents encoded to the same writer are separated by newlines. That matches the - // Go json.Encoder behavior and also works with bsonrw.NewExtJSONValueReader. + // Go json.Encoder behavior and also works with NewExtJSONValueReader. if ejvw.newlines { ejvw.buf = append(ejvw.buf, '\n') } diff --git a/bson/bsonrw/extjson_writer_test.go b/bson/extjson_writer_test.go similarity index 91% rename from bson/bsonrw/extjson_writer_test.go rename to bson/extjson_writer_test.go index 50ba32371e..e5fe87bf73 100644 --- a/bson/bsonrw/extjson_writer_test.go +++ b/bson/extjson_writer_test.go @@ -4,7 +4,7 @@ // 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 bsonrw +package bson import ( "fmt" @@ -13,12 +13,11 @@ import ( "strings" "testing" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/internal/assert" ) func TestExtJSONValueWriter(t *testing.T) { - oid := primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C} + oid := ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C} testCases := []struct { name string fn interface{} @@ -57,7 +56,7 @@ func TestExtJSONValueWriter(t *testing.T) { { "WriteDecimal128", (*extJSONValueWriter).WriteDecimal128, - []interface{}{primitive.NewDecimal128(10, 20)}, + []interface{}{NewDecimal128(10, 20)}, }, { "WriteDouble", @@ -154,7 +153,7 @@ func TestExtJSONValueWriter(t *testing.T) { } want := TransitionError{current: mTopLevel, name: fnName, modes: []mode{mElement, mValue}, action: "write"} - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Errors do not match. got %v; want %v", got, want) } }) @@ -167,7 +166,7 @@ func TestExtJSONValueWriter(t *testing.T) { want := TransitionError{current: mArray, destination: mArray, parent: mTopLevel, name: "WriteArray", modes: []mode{mElement, mValue}, action: "write"} _, got := ejvw.WriteArray() - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -177,7 +176,7 @@ func TestExtJSONValueWriter(t *testing.T) { want := TransitionError{current: mArray, destination: mCodeWithScope, parent: mTopLevel, name: "WriteCodeWithScope", modes: []mode{mElement, mValue}, action: "write"} _, got := ejvw.WriteCodeWithScope("") - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -187,7 +186,7 @@ func TestExtJSONValueWriter(t *testing.T) { want := TransitionError{current: mArray, destination: mDocument, parent: mTopLevel, name: "WriteDocument", modes: []mode{mElement, mValue, mTopLevel}, action: "write"} _, got := ejvw.WriteDocument() - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -201,7 +200,7 @@ func TestExtJSONValueWriter(t *testing.T) { modes: []mode{mDocument, mTopLevel, mCodeWithScope}, action: "write"} _, got := ejvw.WriteDocumentElement("") - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -210,7 +209,7 @@ func TestExtJSONValueWriter(t *testing.T) { ejvw.push(mElement) want := fmt.Errorf("incorrect mode to end document: %s", mElement) got := ejvw.WriteDocumentEnd() - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -224,7 +223,7 @@ func TestExtJSONValueWriter(t *testing.T) { modes: []mode{mArray}, action: "write"} _, got := ejvw.WriteArrayElement() - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -233,7 +232,7 @@ func TestExtJSONValueWriter(t *testing.T) { ejvw.push(mElement) want := fmt.Errorf("incorrect mode to end array: %s", mElement) got := ejvw.WriteArrayEnd() - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -243,8 +242,8 @@ func TestExtJSONValueWriter(t *testing.T) { ejvw := newExtJSONWriterFromSlice(nil, true, true) want := TransitionError{current: mTopLevel, destination: mode(0), name: "WriteBinaryWithSubtype", modes: []mode{mElement, mValue}, action: "write"} - got := ejvw.WriteBinaryWithSubtype(nil, (byte)(bsontype.EmbeddedDocument)) - if !compareErrors(got, want) { + got := ejvw.WriteBinaryWithSubtype(nil, (byte)(TypeEmbeddedDocument)) + if !assert.CompareErrors(got, want) { t.Errorf("Did not received expected error. got %v; want %v", got, want) } }) diff --git a/bson/bsonrw/json_scanner.go b/bson/json_scanner.go similarity index 99% rename from bson/bsonrw/json_scanner.go rename to bson/json_scanner.go index 43f3e4f383..a0a840c6cc 100644 --- a/bson/bsonrw/json_scanner.go +++ b/bson/json_scanner.go @@ -4,7 +4,7 @@ // 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 bsonrw +package bson import ( "bytes" diff --git a/bson/bsonrw/json_scanner_test.go b/bson/json_scanner_test.go similarity index 97% rename from bson/bsonrw/json_scanner_test.go rename to bson/json_scanner_test.go index abbf7d3fe5..58f6e64594 100644 --- a/bson/bsonrw/json_scanner_test.go +++ b/bson/json_scanner_test.go @@ -4,7 +4,7 @@ // 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 bsonrw +package bson import ( "strings" @@ -38,22 +38,6 @@ func expectNilToken(t *testing.T, v *jsonToken, desc string) { } } -func expectError(t *testing.T, err error, desc string) { - if err == nil { - t.Helper() - t.Errorf("%s: Expected error", desc) - t.FailNow() - } -} - -func expectNoError(t *testing.T, err error, desc string) { - if err != nil { - t.Helper() - t.Errorf("%s: Unepexted error: %v", desc, err) - t.FailNow() - } -} - type jsonScannerTestCase struct { desc string input string diff --git a/bson/bsoncodec/map_codec.go b/bson/map_codec.go similarity index 94% rename from bson/bsoncodec/map_codec.go rename to bson/map_codec.go index fe304b2e03..9592957db4 100644 --- a/bson/bsoncodec/map_codec.go +++ b/bson/map_codec.go @@ -4,7 +4,7 @@ // 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 +package bson import ( "encoding" @@ -14,8 +14,6 @@ import ( "strconv" "go.mongodb.org/mongo-driver/bson/bsonoptions" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" ) var defaultMapCodec = NewMapCodec() @@ -81,7 +79,7 @@ func NewMapCodec(opts ...*bsonoptions.MapCodecOptions) *MapCodec { } // EncodeValue is the ValueEncoder for map[*]* types. -func (mc *MapCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (mc *MapCodec) EncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Kind() != reflect.Map { return ValueEncoderError{Name: "MapEncodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val} } @@ -109,7 +107,7 @@ func (mc *MapCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val ref // mapEncodeValue handles encoding of the values of a map. The collisionFn returns // true if the provided key exists, this is mainly used for inline maps in the // struct codec. -func (mc *MapCodec) mapEncodeValue(ec EncodeContext, dw bsonrw.DocumentWriter, val reflect.Value, collisionFn func(string) bool) error { +func (mc *MapCodec) mapEncodeValue(ec EncodeContext, dw DocumentWriter, val reflect.Value, collisionFn func(string) bool) error { elemType := val.Type().Elem() encoder, err := ec.LookupEncoder(elemType) @@ -156,17 +154,17 @@ func (mc *MapCodec) mapEncodeValue(ec EncodeContext, dw bsonrw.DocumentWriter, v } // DecodeValue is the ValueDecoder for map[string/decimal]* types. -func (mc *MapCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (mc *MapCodec) DecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if val.Kind() != reflect.Map || (!val.CanSet() && val.IsNil()) { return ValueDecoderError{Name: "MapDecodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val} } switch vrType := vr.Type(); vrType { - case bsontype.Type(0), bsontype.EmbeddedDocument: - case bsontype.Null: + case Type(0), TypeEmbeddedDocument: + case TypeNull: val.Set(reflect.Zero(val.Type())) return vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: val.Set(reflect.Zero(val.Type())) return vr.ReadUndefined() default: @@ -201,7 +199,7 @@ func (mc *MapCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val ref for { key, vr, err := dr.ReadElement() - if errors.Is(err, bsonrw.ErrEOD) { + if errors.Is(err, ErrEOD) { break } if err != nil { diff --git a/bson/marshal.go b/bson/marshal.go index abe5b9a874..573de16398 100644 --- a/bson/marshal.go +++ b/bson/marshal.go @@ -10,16 +10,11 @@ import ( "bytes" "encoding/json" "sync" - - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" ) const defaultDstCap = 256 -var bvwPool = bsonrw.NewBSONValueWriterPool() -var extjPool = bsonrw.NewExtJSONValueWriterPool() +var extjPool = NewExtJSONValueWriterPool() // Marshaler is the interface implemented by types that can marshal themselves // into a valid BSON document. @@ -39,7 +34,7 @@ type Marshaler interface { // create custom BSON marshaling behavior for an entire BSON document, implement // the Marshaler interface instead. type ValueMarshaler interface { - MarshalBSONValue() (bsontype.Type, []byte, error) + MarshalBSONValue() (Type, []byte, error) } // Pool of buffers for marshalling BSON. @@ -75,7 +70,7 @@ func Marshal(val interface{}) ([]byte, error) { } }() sw.Reset() - vw := bsonrw.NewValueWriter(sw) + vw := NewValueWriter(sw) enc := encPool.Get().(*Encoder) defer encPool.Put(enc) enc.Reset(vw) @@ -92,7 +87,7 @@ func Marshal(val interface{}) ([]byte, error) { // // MarshalValue will use bson.DefaultRegistry 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{}) (bsontype.Type, []byte, error) { +func MarshalValue(val interface{}) (Type, []byte, error) { return MarshalValueWithRegistry(DefaultRegistry, val) } @@ -100,15 +95,15 @@ func MarshalValue(val interface{}) (bsontype.Type, []byte, error) { // // Deprecated: Using a custom registry to marshal individual BSON values will not be supported in Go // Driver 2.0. -func MarshalValueWithRegistry(r *bsoncodec.Registry, val interface{}) (bsontype.Type, []byte, error) { - sw := bsonrw.SliceWriter(make([]byte, 0)) +func MarshalValueWithRegistry(r *Registry, val interface{}) (Type, []byte, error) { + sw := SliceWriter(make([]byte, 0)) vwFlusher := bvwPool.GetAtModeElement(&sw) // get an Encoder and encode the value enc := encPool.Get().(*Encoder) defer encPool.Put(enc) enc.Reset(vwFlusher) - enc.ec = bsoncodec.EncodeContext{Registry: r} + enc.ec = EncodeContext{Registry: r} if err := enc.Encode(val); err != nil { return 0, nil, err } @@ -119,12 +114,12 @@ func MarshalValueWithRegistry(r *bsoncodec.Registry, val interface{}) (bsontype. if err := vwFlusher.Flush(); err != nil { return 0, nil, err } - return bsontype.Type(sw[0]), sw[2:], nil + return Type(sw[0]), sw[2:], nil } // MarshalExtJSON returns the extended JSON encoding of val. func MarshalExtJSON(val interface{}, canonical, escapeHTML bool) ([]byte, error) { - sw := bsonrw.SliceWriter(make([]byte, 0, defaultDstCap)) + sw := SliceWriter(make([]byte, 0, defaultDstCap)) ejvw := extjPool.Get(&sw, canonical, escapeHTML) defer extjPool.Put(ejvw) @@ -132,7 +127,7 @@ func MarshalExtJSON(val interface{}, canonical, escapeHTML bool) ([]byte, error) defer encPool.Put(enc) enc.Reset(ejvw) - enc.ec = bsoncodec.EncodeContext{Registry: DefaultRegistry} + enc.ec = EncodeContext{Registry: DefaultRegistry} err := enc.Encode(val) if err != nil { diff --git a/bson/marshal_test.go b/bson/marshal_test.go index 8b20c3ab27..ecf67d8493 100644 --- a/bson/marshal_test.go +++ b/bson/marshal_test.go @@ -16,27 +16,22 @@ import ( "time" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/require" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) -var tInt32 = reflect.TypeOf(int32(0)) - func TestMarshalWithRegistry(t *testing.T) { for _, tc := range marshalingTestCases { t.Run(tc.name, func(t *testing.T) { - var reg *bsoncodec.Registry + var reg *Registry if tc.reg != nil { reg = tc.reg } else { reg = DefaultRegistry } buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := NewValueWriter(buf) enc := NewEncoder(vw) enc.SetRegistry(reg) err := enc.Encode(tc.val) @@ -53,14 +48,14 @@ func TestMarshalWithRegistry(t *testing.T) { func TestMarshalWithContext(t *testing.T) { for _, tc := range marshalingTestCases { t.Run(tc.name, func(t *testing.T) { - var reg *bsoncodec.Registry + var reg *Registry if tc.reg != nil { reg = tc.reg } else { reg = DefaultRegistry } buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := NewValueWriter(buf) enc := NewEncoder(vw) enc.IntMinSize() enc.SetRegistry(reg) @@ -134,7 +129,7 @@ func TestMarshal_roundtripFromDoc(t *testing.T) { before := D{ {"foo", "bar"}, {"baz", int64(-27)}, - {"bing", A{nil, primitive.Regex{Pattern: "word", Options: "i"}}}, + {"bing", A{nil, Regex{Pattern: "word", Options: "i"}}}, } b, err := Marshal(before) @@ -154,7 +149,7 @@ func TestCachingEncodersNotSharedAcrossRegistries(t *testing.T) { // different Registry is used. // Create a custom Registry that negates int32 values when encoding. - var encodeInt32 bsoncodec.ValueEncoderFunc = func(_ bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + var encodeInt32 ValueEncoderFunc = func(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if val.Kind() != reflect.Int32 { return fmt.Errorf("expected kind to be int32, got %v", val.Kind()) } @@ -178,7 +173,7 @@ func TestCachingEncodersNotSharedAcrossRegistries(t *testing.T) { assert.Equal(t, expectedFirst, Raw(first), "expected document %v, got %v", expectedFirst, Raw(first)) buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := NewValueWriter(buf) enc := NewEncoder(vw) enc.SetRegistry(customReg) err = enc.Encode(original) @@ -228,7 +223,7 @@ func TestNullBytes(t *testing.T) { } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - regex := primitive.Regex{ + regex := Regex{ Pattern: tc.pattern, Options: tc.options, } diff --git a/bson/marshal_value_cases_test.go b/bson/marshal_value_cases_test.go index a889cc5845..29356ece67 100644 --- a/bson/marshal_value_cases_test.go +++ b/bson/marshal_value_cases_test.go @@ -10,8 +10,6 @@ import ( "io" "testing" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -39,13 +37,13 @@ type marshalValueMarshaler struct { var _ ValueMarshaler = marshalValueMarshaler{} -func (mvi marshalValueMarshaler) MarshalBSONValue() (bsontype.Type, []byte, error) { - return bsontype.Int32, bsoncore.AppendInt32(nil, int32(mvi.Foo)), nil +func (mvi marshalValueMarshaler) MarshalBSONValue() (Type, []byte, error) { + return TypeInt32, bsoncore.AppendInt32(nil, int32(mvi.Foo)), nil } var _ ValueUnmarshaler = &marshalValueMarshaler{} -func (mvi *marshalValueMarshaler) UnmarshalBSONValue(_ bsontype.Type, b []byte) error { +func (mvi *marshalValueMarshaler) UnmarshalBSONValue(_ Type, b []byte) error { v, _, _ := bsoncore.ReadInt32(b) mvi.Foo = int(v) return nil @@ -58,7 +56,7 @@ type marshalValueStruct struct { type marshalValueTestCase struct { name string val interface{} - bsontype bsontype.Type + bsontype Type bytes []byte } @@ -66,12 +64,12 @@ func newMarshalValueTestCases(t *testing.T) []marshalValueTestCase { t.Helper() var ( - oid = primitive.NewObjectID() - regex = primitive.Regex{Pattern: "pattern", Options: "imx"} - dbPointer = primitive.DBPointer{DB: "db", Pointer: primitive.NewObjectID()} - codeWithScope = primitive.CodeWithScope{Code: "code", Scope: D{{"a", "b"}}} - decimal128 = primitive.NewDecimal128(5, 10) - structTest = marshalValueStruct{Foo: 10} + oid = NewObjectID() + regex = Regex{Pattern: "pattern", Options: "imx"} + dbPointer = DBPointer{DB: "db", Pointer: NewObjectID()} + codeWithScope = CodeWithScope{Code: "code", Scope: D{{"a", "b"}}} + decimal128h, decimal128l = NewDecimal128(5, 10).GetBytes() + structTest = marshalValueStruct{Foo: 10} ) idx, scopeCore := bsoncore.AppendDocumentStart(nil) scopeCore = bsoncore.AppendStringElement(scopeCore, "a", "b") @@ -81,29 +79,29 @@ func newMarshalValueTestCases(t *testing.T) []marshalValueTestCase { assert.Nil(t, err, "Marshal error: %v", err) return []marshalValueTestCase{ - {"double", 3.14, bsontype.Double, bsoncore.AppendDouble(nil, 3.14)}, - {"string", "hello world", bsontype.String, bsoncore.AppendString(nil, "hello world")}, - {"binary", primitive.Binary{1, []byte{1, 2}}, bsontype.Binary, bsoncore.AppendBinary(nil, 1, []byte{1, 2})}, - {"undefined", primitive.Undefined{}, bsontype.Undefined, []byte{}}, - {"object id", oid, bsontype.ObjectID, bsoncore.AppendObjectID(nil, oid)}, - {"boolean", true, bsontype.Boolean, bsoncore.AppendBoolean(nil, true)}, - {"datetime", primitive.DateTime(5), bsontype.DateTime, bsoncore.AppendDateTime(nil, 5)}, - {"null", primitive.Null{}, bsontype.Null, []byte{}}, - {"regex", regex, bsontype.Regex, bsoncore.AppendRegex(nil, regex.Pattern, regex.Options)}, - {"dbpointer", dbPointer, bsontype.DBPointer, bsoncore.AppendDBPointer(nil, dbPointer.DB, dbPointer.Pointer)}, - {"javascript", primitive.JavaScript("js"), bsontype.JavaScript, bsoncore.AppendJavaScript(nil, "js")}, - {"symbol", primitive.Symbol("symbol"), bsontype.Symbol, bsoncore.AppendSymbol(nil, "symbol")}, - {"code with scope", codeWithScope, bsontype.CodeWithScope, bsoncore.AppendCodeWithScope(nil, "code", scopeCore)}, - {"int32", 5, bsontype.Int32, bsoncore.AppendInt32(nil, 5)}, - {"int64", int64(5), bsontype.Int64, bsoncore.AppendInt64(nil, 5)}, - {"timestamp", primitive.Timestamp{T: 1, I: 5}, bsontype.Timestamp, bsoncore.AppendTimestamp(nil, 1, 5)}, - {"decimal128", decimal128, bsontype.Decimal128, bsoncore.AppendDecimal128(nil, decimal128)}, - {"min key", primitive.MinKey{}, bsontype.MinKey, []byte{}}, - {"max key", primitive.MaxKey{}, bsontype.MaxKey, []byte{}}, - {"struct", structTest, bsontype.EmbeddedDocument, structCore}, - {"D", D{{"foo", int32(10)}}, bsontype.EmbeddedDocument, structCore}, - {"M", M{"foo": int32(10)}, bsontype.EmbeddedDocument, structCore}, - {"ValueMarshaler", marshalValueMarshaler{Foo: 10}, bsontype.Int32, bsoncore.AppendInt32(nil, 10)}, + {"double", 3.14, TypeDouble, bsoncore.AppendDouble(nil, 3.14)}, + {"string", "hello world", TypeString, bsoncore.AppendString(nil, "hello world")}, + {"binary", Binary{1, []byte{1, 2}}, TypeBinary, bsoncore.AppendBinary(nil, 1, []byte{1, 2})}, + {"undefined", Undefined{}, TypeUndefined, []byte{}}, + {"object id", oid, TypeObjectID, bsoncore.AppendObjectID(nil, oid)}, + {"boolean", true, TypeBoolean, bsoncore.AppendBoolean(nil, true)}, + {"datetime", DateTime(5), TypeDateTime, bsoncore.AppendDateTime(nil, 5)}, + {"null", Null{}, TypeNull, []byte{}}, + {"regex", regex, TypeRegex, bsoncore.AppendRegex(nil, regex.Pattern, regex.Options)}, + {"dbpointer", dbPointer, TypeDBPointer, bsoncore.AppendDBPointer(nil, dbPointer.DB, dbPointer.Pointer)}, + {"javascript", JavaScript("js"), TypeJavaScript, bsoncore.AppendJavaScript(nil, "js")}, + {"symbol", Symbol("symbol"), TypeSymbol, bsoncore.AppendSymbol(nil, "symbol")}, + {"code with scope", codeWithScope, TypeCodeWithScope, bsoncore.AppendCodeWithScope(nil, "code", scopeCore)}, + {"int32", 5, TypeInt32, bsoncore.AppendInt32(nil, 5)}, + {"int64", int64(5), TypeInt64, bsoncore.AppendInt64(nil, 5)}, + {"timestamp", Timestamp{T: 1, I: 5}, TypeTimestamp, bsoncore.AppendTimestamp(nil, 1, 5)}, + {"decimal128", NewDecimal128(decimal128h, decimal128l), TypeDecimal128, bsoncore.AppendDecimal128(nil, decimal128h, decimal128l)}, + {"min key", MinKey{}, TypeMinKey, []byte{}}, + {"max key", MaxKey{}, TypeMaxKey, []byte{}}, + {"struct", structTest, TypeEmbeddedDocument, structCore}, + {"D", D{{"foo", int32(10)}}, TypeEmbeddedDocument, structCore}, + {"M", M{"foo": int32(10)}, TypeEmbeddedDocument, structCore}, + {"ValueMarshaler", marshalValueMarshaler{Foo: 10}, TypeInt32, bsoncore.AppendInt32(nil, 10)}, } } @@ -123,7 +121,7 @@ func newMarshalValueTestCasesWithInterfaceCore(t *testing.T) []marshalValueTestC marshalValueTestCases = append( marshalValueTestCases, - marshalValueTestCase{"interface", interfaceTest, bsontype.EmbeddedDocument, interfaceCore}, + marshalValueTestCase{"interface", interfaceTest, TypeEmbeddedDocument, interfaceCore}, ) return marshalValueTestCases diff --git a/bson/marshal_value_test.go b/bson/marshal_value_test.go index 66dec6c186..1cfd20fd49 100644 --- a/bson/marshal_value_test.go +++ b/bson/marshal_value_test.go @@ -10,7 +10,6 @@ import ( "strings" "testing" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/assert" ) @@ -36,7 +35,7 @@ func TestMarshalValue(t *testing.T) { }) } -func compareMarshalValueResults(t *testing.T, tc marshalValueTestCase, gotType bsontype.Type, gotBytes []byte) { +func compareMarshalValueResults(t *testing.T, tc marshalValueTestCase, gotType Type, gotBytes []byte) { t.Helper() expectedValue := RawValue{Type: tc.bsontype, Value: tc.bytes} gotValue := RawValue{Type: gotType, Value: gotBytes} diff --git a/bson/marshaling_cases_test.go b/bson/marshaling_cases_test.go index 4ed95d6759..8e63ee5d41 100644 --- a/bson/marshaling_cases_test.go +++ b/bson/marshaling_cases_test.go @@ -6,13 +6,9 @@ package bson -import ( - "go.mongodb.org/mongo-driver/bson/bsoncodec" -) - type marshalingTestCase struct { name string - reg *bsoncodec.Registry + reg *Registry val interface{} want []byte } diff --git a/bson/mgocompat/bson_test.go b/bson/mgocompat/bson_test.go index b5cf096176..6651509983 100644 --- a/bson/mgocompat/bson_test.go +++ b/bson/mgocompat/bson_test.go @@ -22,10 +22,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/assert" ) @@ -89,7 +85,7 @@ func TestMarshalSampleItems(t *testing.T) { for i, item := range sampleItems { t.Run(strconv.Itoa(i), func(t *testing.T) { buf.Reset() - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc.Reset(vw) enc.SetRegistry(Registry) err := enc.Encode(item.obj) @@ -129,13 +125,13 @@ var allItems = []testItemType{ "\x04_\x00\r\x00\x00\x00\x080\x00\x01\x081\x00\x00\x00"}, {bson.M{"_": []byte("yo")}, "\x05_\x00\x02\x00\x00\x00\x00yo"}, - {bson.M{"_": primitive.Binary{Subtype: 0x80, Data: []byte("udef")}}, + {bson.M{"_": bson.Binary{Subtype: 0x80, Data: []byte("udef")}}, "\x05_\x00\x04\x00\x00\x00\x80udef"}, - {bson.M{"_": primitive.Undefined{}}, // Obsolete, but still seen in the wild. + {bson.M{"_": bson.Undefined{}}, // Obsolete, but still seen in the wild. "\x06_\x00"}, - {bson.M{"_": primitive.ObjectID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B}}, + {bson.M{"_": bson.ObjectID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B}}, "\x07_\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B"}, //technically this is not the same as the original mgo test - {bson.M{"_": primitive.DBPointer{DB: "testnamespace", Pointer: primitive.ObjectID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B}}}, + {bson.M{"_": bson.DBPointer{DB: "testnamespace", Pointer: bson.ObjectID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B}}}, "\x0C_\x00\x0e\x00\x00\x00testnamespace\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B"}, {bson.M{"_": false}, "\x08_\x00\x00"}, @@ -145,26 +141,26 @@ var allItems = []testItemType{ "\x09_\x00\x02\x01\x00\x00\x00\x00\x00\x00"}, {bson.M{"_": nil}, "\x0A_\x00"}, - {bson.M{"_": primitive.Regex{Pattern: "ab", Options: "cd"}}, + {bson.M{"_": bson.Regex{Pattern: "ab", Options: "cd"}}, "\x0B_\x00ab\x00cd\x00"}, - {bson.M{"_": primitive.JavaScript("code")}, + {bson.M{"_": bson.JavaScript("code")}, "\x0D_\x00\x05\x00\x00\x00code\x00"}, - {bson.M{"_": primitive.Symbol("sym")}, + {bson.M{"_": bson.Symbol("sym")}, "\x0E_\x00\x04\x00\x00\x00sym\x00"}, - {bson.M{"_": primitive.CodeWithScope{Code: "code", Scope: primitive.D{{"", nil}}}}, + {bson.M{"_": bson.CodeWithScope{Code: "code", Scope: bson.D{{"", nil}}}}, "\x0F_\x00\x14\x00\x00\x00\x05\x00\x00\x00code\x00" + "\x07\x00\x00\x00\x0A\x00\x00"}, {bson.M{"_": 258}, "\x10_\x00\x02\x01\x00\x00"}, - {bson.M{"_": primitive.Timestamp{0, 258}}, + {bson.M{"_": bson.Timestamp{0, 258}}, "\x11_\x00\x02\x01\x00\x00\x00\x00\x00\x00"}, {bson.M{"_": int64(258)}, "\x12_\x00\x02\x01\x00\x00\x00\x00\x00\x00"}, {bson.M{"_": int64(258 << 32)}, "\x12_\x00\x00\x00\x00\x00\x02\x01\x00\x00"}, - {bson.M{"_": primitive.MaxKey{}}, + {bson.M{"_": bson.MaxKey{}}, "\x7F_\x00"}, - {bson.M{"_": primitive.MinKey{}}, + {bson.M{"_": bson.MinKey{}}, "\xFF_\x00"}, } @@ -174,7 +170,7 @@ func TestMarshalAllItems(t *testing.T) { for i, item := range allItems { t.Run(strconv.Itoa(i), func(t *testing.T) { buf.Reset() - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc.Reset(vw) enc.SetRegistry(Registry) err := enc.Encode(item.obj) @@ -207,7 +203,7 @@ func TestUnmarshalRawAllItems(t *testing.T) { } t.Run(strconv.Itoa(i), func(t *testing.T) { pv := reflect.New(reflect.ValueOf(value).Type()) - raw := bson.RawValue{Type: bsontype.Type(item.data[0]), Value: []byte(item.data[3:])} + raw := bson.RawValue{Type: bson.Type(item.data[0]), Value: []byte(item.data[3:])} err := raw.UnmarshalWithRegistry(Registry, pv.Interface()) assert.Nil(t, err, "expected nil error, got: %v", err) assert.True(t, reflect.DeepEqual(value, pv.Elem().Interface()), "expected: %v, got: %v", value, pv.Elem().Interface()) @@ -223,7 +219,7 @@ func TestUnmarshalRawIncompatible(t *testing.T) { func TestUnmarshalZeroesStruct(t *testing.T) { buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(Registry) err := enc.Encode(bson.M{"b": 2}) @@ -238,7 +234,7 @@ func TestUnmarshalZeroesStruct(t *testing.T) { func TestUnmarshalZeroesMap(t *testing.T) { buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(Registry) err := enc.Encode(bson.M{"b": 2}) @@ -253,7 +249,7 @@ func TestUnmarshalZeroesMap(t *testing.T) { func TestUnmarshalNonNilInterface(t *testing.T) { buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(Registry) err := enc.Encode(bson.M{"b": 2}) @@ -296,7 +292,7 @@ func TestPtrInline(t *testing.T) { for i, cs := range cases { t.Run(strconv.Itoa(i), func(t *testing.T) { buf.Reset() - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc.Reset(vw) enc.SetRegistry(Registry) err := enc.Encode(cs.In) @@ -313,19 +309,19 @@ func TestPtrInline(t *testing.T) { // -------------------------------------------------------------------------- // Some one way marshaling operations which would unmarshal differently. -var js = primitive.JavaScript("code") +var js = bson.JavaScript("code") var oneWayMarshalItems = []testItemType{ // These are being passed as pointers, and will unmarshal as values. - {bson.M{"": &primitive.Binary{Subtype: 0x02, Data: []byte("old")}}, + {bson.M{"": &bson.Binary{Subtype: 0x02, Data: []byte("old")}}, "\x05\x00\x07\x00\x00\x00\x02\x03\x00\x00\x00old"}, - {bson.M{"": &primitive.Binary{Subtype: 0x80, Data: []byte("udef")}}, + {bson.M{"": &bson.Binary{Subtype: 0x80, Data: []byte("udef")}}, "\x05\x00\x04\x00\x00\x00\x80udef"}, - {bson.M{"": &primitive.Regex{Pattern: "ab", Options: "cd"}}, + {bson.M{"": &bson.Regex{Pattern: "ab", Options: "cd"}}, "\x0B\x00ab\x00cd\x00"}, {bson.M{"": &js}, "\x0D\x00\x05\x00\x00\x00code\x00"}, - {bson.M{"": &primitive.CodeWithScope{Code: "code", Scope: bson.M{"": nil}}}, + {bson.M{"": &bson.CodeWithScope{Code: "code", Scope: bson.M{"": nil}}}, "\x0F\x00\x14\x00\x00\x00\x05\x00\x00\x00code\x00" + "\x07\x00\x00\x00\x0A\x00\x00"}, @@ -342,9 +338,9 @@ var oneWayMarshalItems = []testItemType{ "\x04\x00\r\x00\x00\x00\x080\x00\x01\x081\x00\x00\x00"}, // Will unmarshal as a []byte. - {bson.M{"": primitive.Binary{Subtype: 0x00, Data: []byte("yo")}}, + {bson.M{"": bson.Binary{Subtype: 0x00, Data: []byte("yo")}}, "\x05\x00\x02\x00\x00\x00\x00yo"}, - {bson.M{"": primitive.Binary{Subtype: 0x02, Data: []byte("old")}}, + {bson.M{"": bson.Binary{Subtype: 0x02, Data: []byte("old")}}, "\x05\x00\x07\x00\x00\x00\x02\x03\x00\x00\x00old"}, // No way to preserve the type information here. We might encode as a zero @@ -385,7 +381,7 @@ func TestOneWayMarshalItems(t *testing.T) { for i, item := range oneWayMarshalItems { t.Run(strconv.Itoa(i), func(t *testing.T) { buf.Reset() - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc.Reset(vw) enc.SetRegistry(Registry) err := enc.Encode(item.obj) @@ -422,7 +418,7 @@ func TestMarshalStructSampleItems(t *testing.T) { for i, item := range structSampleItems { t.Run(strconv.Itoa(i), func(t *testing.T) { buf.Reset() - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc.Reset(vw) enc.SetRegistry(Registry) err := enc.Encode(item.obj) @@ -444,7 +440,7 @@ func Test64bitInt(t *testing.T) { var i int64 = (1 << 31) if int(i) > 0 { buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(Registry) err := enc.Encode(bson.M{"i": int(i)}) @@ -482,8 +478,8 @@ func (t *prefixPtr) SetBSON(raw bson.RawValue) error { if err != nil { return err } - vr := bsonrw.NewBSONValueReader(raw.Type, raw.Value) - err = decoder.DecodeValue(bsoncodec.DecodeContext{Registry: Registry}, vr, rval) + vr := bson.NewBSONValueReader(raw.Type, raw.Value) + err = decoder.DecodeValue(bson.DecodeContext{Registry: Registry}, vr, rval) if err != nil { return err } @@ -509,8 +505,8 @@ func (t *prefixVal) SetBSON(raw bson.RawValue) error { if err != nil { return err } - vr := bsonrw.NewBSONValueReader(raw.Type, raw.Value) - err = decoder.DecodeValue(bsoncodec.DecodeContext{Registry: Registry}, vr, rval) + vr := bson.NewBSONValueReader(raw.Type, raw.Value) + err = decoder.DecodeValue(bson.DecodeContext{Registry: Registry}, vr, rval) if err != nil { return err } @@ -588,7 +584,7 @@ func TestMarshalStructItems(t *testing.T) { for i, item := range structItems { t.Run(strconv.Itoa(i), func(t *testing.T) { buf.Reset() - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc.Reset(vw) enc.SetRegistry(Registry) err := enc.Encode(item.obj) @@ -664,7 +660,7 @@ func TestMarshalOneWayItems(t *testing.T) { for i, item := range marshalItems { t.Run(strconv.Itoa(i), func(t *testing.T) { buf.Reset() - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc.Reset(vw) enc.SetRegistry(Registry) err := enc.Encode(item.obj) @@ -698,10 +694,6 @@ var unmarshalItems = []testItemType{ {&struct{ bson.D }{bson.D{{"a", nil}, {"c", nil}, {"b", nil}, {"d", true}}}, "\x03d\x00" + wrapInDoc("\x0Aa\x00\x0Ac\x00\x0Ab\x00\x08d\x00\x01")}, - // Raw document. - // {&bson.RawValue{Type: 0x03, Value: []byte(wrapInDoc("\x10byte\x00\x08\x00\x00\x00"))}, - // "\x10byte\x00\x08\x00\x00\x00"}, - // Decode old binary. {bson.M{"_": []byte("old")}, "\x05_\x00\x07\x00\x00\x00\x02\x03\x00\x00\x00old"}, @@ -777,7 +769,7 @@ func TestMarshalErrorItems(t *testing.T) { for i, item := range marshalErrorItems { t.Run(strconv.Itoa(i), func(t *testing.T) { buf.Reset() - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc.Reset(vw) enc.SetRegistry(Registry) err := enc.Encode(item.obj) @@ -935,10 +927,10 @@ func (o *setterType) SetBSON(raw bson.RawValue) error { return err } if raw.Type == 0x00 { - raw.Type = bsontype.EmbeddedDocument + raw.Type = bson.TypeEmbeddedDocument } - vr := bsonrw.NewBSONValueReader(raw.Type, raw.Value) - err = decoder.DecodeValue(bsoncodec.DecodeContext{Registry: Registry}, vr, rval) + vr := bson.NewBSONValueReader(raw.Type, raw.Value) + err = decoder.DecodeValue(bson.DecodeContext{Registry: Registry}, vr, rval) if err != nil { return err } @@ -1038,7 +1030,7 @@ func TestUnmarshalSetterErrSetZero(t *testing.T) { defer delete(setterResult, "field") buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(Registry) err := enc.Encode(bson.M{"field": "foo"}) @@ -1083,7 +1075,7 @@ func TestMarshalAllItemsWithGetter(t *testing.T) { buf.Reset() obj := &docWithGetterField{} obj.Field = &typeWithGetter{result: item.obj.(bson.M)["_"]} - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc.Reset(vw) enc.SetRegistry(Registry) err := enc.Encode(obj) @@ -1097,7 +1089,7 @@ func TestMarshalAllItemsWithGetter(t *testing.T) { func TestMarshalWholeDocumentWithGetter(t *testing.T) { obj := &typeWithGetter{result: sampleItems[0].obj} buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(Registry) err := enc.Encode(obj) @@ -1112,7 +1104,7 @@ func TestGetterErrors(t *testing.T) { obj1 := &docWithGetterField{} obj1.Field = &typeWithGetter{sampleItems[0].obj, e} buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(Registry) err := enc.Encode(obj1) @@ -1121,7 +1113,7 @@ func TestGetterErrors(t *testing.T) { obj2 := &typeWithGetter{sampleItems[0].obj, e} buf.Reset() - vw = bsonrw.NewValueWriter(buf) + vw = bson.NewValueWriter(buf) enc = bson.NewEncoder(vw) enc.SetRegistry(Registry) err = enc.Encode(obj2) @@ -1142,7 +1134,7 @@ type typeWithIntGetter struct { func TestMarshalShortWithGetter(t *testing.T) { obj := typeWithIntGetter{42} buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(Registry) err := enc.Encode(obj) @@ -1156,7 +1148,7 @@ func TestMarshalShortWithGetter(t *testing.T) { func TestMarshalWithGetterNil(t *testing.T) { obj := docWithGetterField{} buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(Registry) err := enc.Encode(obj) @@ -1294,10 +1286,10 @@ func (s *getterSetterD) SetBSON(raw bson.RawValue) error { return err } if raw.Type == 0x00 { - raw.Type = bsontype.EmbeddedDocument + raw.Type = bson.TypeEmbeddedDocument } - vr := bsonrw.NewBSONValueReader(raw.Type, raw.Value) - err = decoder.DecodeValue(bsoncodec.DecodeContext{Registry: Registry}, vr, rval) + vr := bson.NewBSONValueReader(raw.Type, raw.Value) + err = decoder.DecodeValue(bson.DecodeContext{Registry: Registry}, vr, rval) if err != nil { return err } @@ -1320,10 +1312,10 @@ func (i *getterSetterInt) SetBSON(raw bson.RawValue) error { return err } if raw.Type == 0x00 { - raw.Type = bsontype.EmbeddedDocument + raw.Type = bson.TypeEmbeddedDocument } - vr := bsonrw.NewBSONValueReader(raw.Type, raw.Value) - err = decoder.DecodeValue(bsoncodec.DecodeContext{Registry: Registry}, vr, rval) + vr := bson.NewBSONValueReader(raw.Type, raw.Value) + err = decoder.DecodeValue(bson.DecodeContext{Registry: Registry}, vr, rval) if err != nil { return err } @@ -1344,8 +1336,8 @@ func (s *ifaceSlice) SetBSON(raw bson.RawValue) error { if err != nil { return err } - vr := bsonrw.NewBSONValueReader(raw.Type, raw.Value) - err = decoder.DecodeValue(bsoncodec.DecodeContext{Registry: Registry}, vr, rval) + vr := bson.NewBSONValueReader(raw.Type, raw.Value) + err = decoder.DecodeValue(bson.DecodeContext{Registry: Registry}, vr, rval) if err != nil { return err } @@ -1447,11 +1439,11 @@ var twoWayCrossItems = []crossTypeItem{ // string <=> string and string <=> []byte {&struct{ S []byte }{[]byte("abc")}, &struct{ S string }{"abc"}}, - {&struct{ S []byte }{[]byte("def")}, &struct{ S primitive.Symbol }{"def"}}, - {&struct{ S string }{"ghi"}, &struct{ S primitive.Symbol }{"ghi"}}, + {&struct{ S []byte }{[]byte("def")}, &struct{ S bson.Symbol }{"def"}}, + {&struct{ S string }{"ghi"}, &struct{ S bson.Symbol }{"ghi"}}, {&struct{ S string }{"0123456789ab"}, - &struct{ S primitive.ObjectID }{primitive.ObjectID{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62}}}, + &struct{ S bson.ObjectID }{bson.ObjectID{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62}}}, // map <=> struct {&struct { @@ -1461,8 +1453,8 @@ var twoWayCrossItems = []crossTypeItem{ }{struct{ B, C int }{1, 2}}, map[string]map[string]int{"a": {"b": 1, "c": 2}}}, - {&struct{ A primitive.Symbol }{"abc"}, map[string]string{"a": "abc"}}, - {&struct{ A primitive.Symbol }{"abc"}, map[string][]byte{"a": []byte("abc")}}, + {&struct{ A bson.Symbol }{"abc"}, map[string]string{"a": "abc"}}, + {&struct{ A bson.Symbol }{"abc"}, map[string][]byte{"a": []byte("abc")}}, {&struct{ A []byte }{[]byte("abc")}, map[string]string{"a": "abc"}}, {&struct{ A uint }{42}, map[string]int{"a": 42}}, {&struct{ A uint }{42}, map[string]float64{"a": 42}}, @@ -1516,9 +1508,6 @@ var twoWayCrossItems = []crossTypeItem{ {&condStruct{struct{ A []int }{[]int{1}}}, bson.M{"v": bson.M{"a": []interface{}{1}}}}, {&condStruct{struct{ A []int }{}}, bson.M{}}, - // {&condRaw{bson.RawValue{Type: 0x0A, Value: []byte{}}},bson.M{"v": nil}}, - // {&condRaw{bson.RawValue{Type: 0x00}}, bson.M{}}, - {&namedCondStr{"yo"}, map[string]string{"myv": "yo"}}, {&namedCondStr{}, map[string]string{}}, @@ -1543,7 +1532,7 @@ var twoWayCrossItems = []crossTypeItem{ {&inlineUnexported{M: map[string]interface{}{"b": 1}, unexported: unexported{A: 2}}, map[string]interface{}{"b": 1, "a": 2}}, // []byte <=> Binary - {&struct{ B []byte }{[]byte("abc")}, map[string]primitive.Binary{"b": {Data: []byte("abc")}}}, + {&struct{ B []byte }{[]byte("abc")}, map[string]bson.Binary{"b": {Data: []byte("abc")}}}, // []byte <=> MyBytes {&struct{ B MyBytes }{[]byte("abc")}, &map[string]string{"b": "abc"}}, @@ -1607,7 +1596,7 @@ var oneWayCrossItems = []crossTypeItem{ func testCrossPair(t *testing.T, dump interface{}, load interface{}) { zero := makeZeroDoc(load) buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(Registry) err := enc.Encode(dump) @@ -1639,11 +1628,11 @@ func TestOneWayCrossPairs(t *testing.T) { // ObjectId JSON marshalling. type jsonType struct { - ID primitive.ObjectID + ID bson.ObjectID } -func objectIDHex(s string) primitive.ObjectID { - oid, _ := primitive.ObjectIDFromHex(s) +func objectIDHex(s string) bson.ObjectID { + oid, _ := bson.ObjectIDFromHex(s) return oid } @@ -1721,7 +1710,7 @@ func TestMarshalNotRespectNil(t *testing.T) { assert.Nil(t, testStruct1.Map, "expected nil map, got: %v", testStruct1.Map) buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(Registry) err := enc.Encode(testStruct1) @@ -1754,7 +1743,7 @@ func TestMarshalRespectNil(t *testing.T) { assert.Nil(t, testStruct1.Ptr, "expected nil ptr, got: %v", testStruct1.Ptr) buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(Registry) err := enc.Encode(testStruct1) @@ -1762,7 +1751,7 @@ func TestMarshalRespectNil(t *testing.T) { testStruct2 := T{} - _ = bson.UnmarshalWithRegistry(RegistryRespectNilValues, buf.Bytes(), &testStruct2) + _ = bson.UnmarshalWithRegistry(RespectNilValuesRegistry, buf.Bytes(), &testStruct2) assert.Len(t, testStruct2.Slice, 0, "expected empty slice, got: %v", testStruct2.Slice) assert.Nil(t, testStruct2.SlicePtr, "expected nil slice ptr, got: %v", testStruct2.SlicePtr) @@ -1783,7 +1772,7 @@ func TestMarshalRespectNil(t *testing.T) { assert.NotNil(t, testStruct1.MapPtr, "expected non-nil map ptr") buf.Reset() - vw = bsonrw.NewValueWriter(buf) + vw = bson.NewValueWriter(buf) enc = bson.NewEncoder(vw) enc.SetRegistry(Registry) err = enc.Encode(testStruct1) @@ -1791,7 +1780,7 @@ func TestMarshalRespectNil(t *testing.T) { testStruct2 = T{} - _ = bson.UnmarshalWithRegistry(RegistryRespectNilValues, buf.Bytes(), &testStruct2) + _ = bson.UnmarshalWithRegistry(RespectNilValuesRegistry, buf.Bytes(), &testStruct2) assert.NotNil(t, testStruct2.Slice, "expected non-nil slice") assert.NotNil(t, testStruct2.SlicePtr, "expected non-nil slice ptr") @@ -1819,7 +1808,7 @@ func TestInlineWithPointerToSelf(t *testing.T) { } buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(Registry) err := enc.Encode(x1) diff --git a/bson/mgocompat/doc.go b/bson/mgocompat/doc.go index 43ff5423da..8a9434b1d1 100644 --- a/bson/mgocompat/doc.go +++ b/bson/mgocompat/doc.go @@ -7,12 +7,12 @@ // Package mgocompat provides Registry, a BSON registry compatible with globalsign/mgo's BSON, // with some remaining differences. It also provides RegistryRespectNilValues for compatibility // with mgo's BSON with RespectNilValues set to true. A registry can be configured on a -// mongo.Client with the SetRegistry option. See the bsoncodec docs for more details on registries. +// mongo.Client with the SetRegistry option. See the bson docs for more details on registries. // // Registry supports Getter and Setter equivalents by registering hooks. Note that if a value -// matches the hook for bsoncodec.Marshaler, bsoncodec.ValueMarshaler, or bsoncodec.Proxy, that +// matches the hook for bson.Marshaler, bson.ValueMarshaler, or bson.Proxy, that // hook will take priority over the Getter hook. The same is true for the hooks for -// bsoncodec.Unmarshaler and bsoncodec.ValueUnmarshaler and the Setter hook. +// bson.Unmarshaler and bson.ValueUnmarshaler and the Setter hook. // // The functional differences between Registry and globalsign/mgo's BSON library are: // @@ -25,31 +25,31 @@ // 1. The driver's bson.RawValue is equivalent to mgo's bson.Raw, but uses Value instead of Data and uses Type, // which is a bsontype.Type object that wraps a byte, instead of bson.Raw's Kind, a byte. // -// 2. The driver uses primitive.ObjectID, which is a [12]byte instead of mgo's +// 2. The driver uses bson.ObjectID, which is a [12]byte instead of mgo's // bson.ObjectId, a string. Due to this, the zero value marshals and unmarshals differently // for Extended JSON, with the driver marshaling as {"ID":"000000000000000000000000"} and -// mgo as {"Id":""}. The driver can unmarshal {"ID":""} to a primitive.ObjectID. +// mgo as {"Id":""}. The driver can unmarshal {"ID":""} to a bson.ObjectID. // -// 3. The driver's primitive.Symbol is equivalent to mgo's bson.Symbol. +// 3. The driver's bson.Symbol is equivalent to mgo's bson.Symbol. // -// 4. The driver uses primitive.Timestamp instead of mgo's bson.MongoTimestamp. While -// MongoTimestamp is an int64, primitive.Timestamp stores the time and counter as two separate +// 4. The driver uses bson.Timestamp instead of mgo's bson.MongoTimestamp. While +// MongoTimestamp is an int64, bson.Timestamp stores the time and counter as two separate // uint32 values, T and I respectively. // -// 5. The driver uses primitive.MinKey and primitive.MaxKey, which are struct{}, instead +// 5. The driver uses bson.MinKey and bson.MaxKey, which are struct{}, instead // of mgo's bson.MinKey and bson.MaxKey, which are int64. // -// 6. The driver's primitive.Undefined is equivalent to mgo's bson.Undefined. +// 6. The driver's bson.Undefined is equivalent to mgo's bson.Undefined. // -// 7. The driver's primitive.Binary is equivalent to mgo's bson.Binary, with variables named Subtype +// 7. The driver's bson.Binary is equivalent to mgo's bson.Binary, with variables named Subtype // and Data instead of Kind and Data. // -// 8. The driver's primitive.Regex is equivalent to mgo's bson.RegEx. +// 8. The driver's bson.Regex is equivalent to mgo's bson.RegEx. // -// 9. The driver's primitive.JavaScript is equivalent to mgo's bson.JavaScript with no -// scope and primitive.CodeWithScope is equivalent to mgo's bson.JavaScript with scope. +// 9. The driver's bson.JavaScript is equivalent to mgo's bson.JavaScript with no +// scope and bson.CodeWithScope is equivalent to mgo's bson.JavaScript with scope. // -// 10. The driver's primitive.DBPointer is equivalent to mgo's bson.DBPointer, with variables +// 10. The driver's bson.DBPointer is equivalent to mgo's bson.DBPointer, with variables // named DB and Pointer instead of Namespace and Id. // // 11. When implementing the Setter interface, mgocompat.ErrSetZero is equivalent to mgo's diff --git a/bson/mgocompat/registry.go b/bson/mgocompat/registry.go index fc051f466d..7024ab9fdc 100644 --- a/bson/mgocompat/registry.go +++ b/bson/mgocompat/registry.go @@ -12,9 +12,7 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" "go.mongodb.org/mongo-driver/bson/bsonoptions" - "go.mongodb.org/mongo-driver/bson/bsontype" ) var ( @@ -31,83 +29,83 @@ var ( tSetter = reflect.TypeOf((*Setter)(nil)).Elem() ) -// Registry is the mgo compatible bsoncodec.Registry. It contains the default and +// Registry is the mgo compatible bson.Registry. It contains the default and // primitive codecs with mgo compatible options. var Registry = NewRegistryBuilder().Build() -// RegistryRespectNilValues is the bsoncodec.Registry compatible with mgo withSetRespectNilValues set to true. -var RegistryRespectNilValues = NewRespectNilValuesRegistryBuilder().Build() +// RespectNilValuesRegistry is the bson.Registry compatible with mgo withSetRespectNilValues set to true. +var RespectNilValuesRegistry = NewRespectNilValuesRegistryBuilder().Build() -// NewRegistryBuilder creates a new bsoncodec.RegistryBuilder configured with the default encoders and -// decoders from the bsoncodec.DefaultValueEncoders and bsoncodec.DefaultValueDecoders types and the +// NewRegistryBuilder creates a new bson.RegistryBuilder configured with the default encoders and +// decoders from the bson.DefaultValueEncoders and bson.DefaultValueDecoders types and the // PrimitiveCodecs type in this package. -func NewRegistryBuilder() *bsoncodec.RegistryBuilder { - rb := bsoncodec.NewRegistryBuilder() - bsoncodec.DefaultValueEncoders{}.RegisterDefaultEncoders(rb) - bsoncodec.DefaultValueDecoders{}.RegisterDefaultDecoders(rb) +func NewRegistryBuilder() *bson.RegistryBuilder { + rb := bson.NewRegistryBuilder() + bson.DefaultValueEncoders{}.RegisterDefaultEncoders(rb) + bson.DefaultValueDecoders{}.RegisterDefaultDecoders(rb) bson.PrimitiveCodecs{}.RegisterPrimitiveCodecs(rb) - structcodec, _ := bsoncodec.NewStructCodec(bsoncodec.DefaultStructTagParser, + structcodec, _ := bson.NewStructCodec(bson.DefaultStructTagParser, bsonoptions.StructCodec(). SetDecodeZeroStruct(true). SetEncodeOmitDefaultStruct(true). SetOverwriteDuplicatedInlinedFields(false). SetAllowUnexportedFields(true)) - emptyInterCodec := bsoncodec.NewEmptyInterfaceCodec( + emptyInterCodec := bson.NewEmptyInterfaceCodec( bsonoptions.EmptyInterfaceCodec(). SetDecodeBinaryAsSlice(true)) - mapCodec := bsoncodec.NewMapCodec( + mapCodec := bson.NewMapCodec( bsonoptions.MapCodec(). SetDecodeZerosMap(true). SetEncodeNilAsEmpty(true). SetEncodeKeysWithStringer(true)) - uintcodec := bsoncodec.NewUIntCodec(bsonoptions.UIntCodec().SetEncodeToMinSize(true)) + uintcodec := bson.NewUIntCodec(bsonoptions.UIntCodec().SetEncodeToMinSize(true)) rb.RegisterTypeDecoder(tEmpty, emptyInterCodec). - RegisterDefaultDecoder(reflect.String, bsoncodec.NewStringCodec(bsonoptions.StringCodec().SetDecodeObjectIDAsHex(false))). + RegisterDefaultDecoder(reflect.String, bson.NewStringCodec(bsonoptions.StringCodec().SetDecodeObjectIDAsHex(false))). RegisterDefaultDecoder(reflect.Struct, structcodec). RegisterDefaultDecoder(reflect.Map, mapCodec). - RegisterTypeEncoder(tByteSlice, bsoncodec.NewByteSliceCodec(bsonoptions.ByteSliceCodec().SetEncodeNilAsEmpty(true))). + RegisterTypeEncoder(tByteSlice, bson.NewByteSliceCodec(bsonoptions.ByteSliceCodec().SetEncodeNilAsEmpty(true))). RegisterDefaultEncoder(reflect.Struct, structcodec). - RegisterDefaultEncoder(reflect.Slice, bsoncodec.NewSliceCodec(bsonoptions.SliceCodec().SetEncodeNilAsEmpty(true))). + RegisterDefaultEncoder(reflect.Slice, bson.NewSliceCodec(bsonoptions.SliceCodec().SetEncodeNilAsEmpty(true))). RegisterDefaultEncoder(reflect.Map, mapCodec). RegisterDefaultEncoder(reflect.Uint, uintcodec). RegisterDefaultEncoder(reflect.Uint8, uintcodec). RegisterDefaultEncoder(reflect.Uint16, uintcodec). RegisterDefaultEncoder(reflect.Uint32, uintcodec). RegisterDefaultEncoder(reflect.Uint64, uintcodec). - RegisterTypeMapEntry(bsontype.Int32, tInt). - RegisterTypeMapEntry(bsontype.DateTime, tTime). - RegisterTypeMapEntry(bsontype.Array, tInterfaceSlice). - RegisterTypeMapEntry(bsontype.Type(0), tM). - RegisterTypeMapEntry(bsontype.EmbeddedDocument, tM). - RegisterHookEncoder(tGetter, bsoncodec.ValueEncoderFunc(GetterEncodeValue)). - RegisterHookDecoder(tSetter, bsoncodec.ValueDecoderFunc(SetterDecodeValue)) + RegisterTypeMapEntry(bson.TypeInt32, tInt). + RegisterTypeMapEntry(bson.TypeDateTime, tTime). + RegisterTypeMapEntry(bson.TypeArray, tInterfaceSlice). + RegisterTypeMapEntry(bson.Type(0), tM). + RegisterTypeMapEntry(bson.TypeEmbeddedDocument, tM). + RegisterHookEncoder(tGetter, bson.ValueEncoderFunc(GetterEncodeValue)). + RegisterHookDecoder(tSetter, bson.ValueDecoderFunc(SetterDecodeValue)) return rb } -// NewRespectNilValuesRegistryBuilder creates a new bsoncodec.RegistryBuilder configured to behave like mgo/bson +// NewRespectNilValuesRegistryBuilder creates a new bson.RegistryBuilder configured to behave like mgo/bson // with RespectNilValues set to true. -func NewRespectNilValuesRegistryBuilder() *bsoncodec.RegistryBuilder { +func NewRespectNilValuesRegistryBuilder() *bson.RegistryBuilder { rb := NewRegistryBuilder() - structcodec, _ := bsoncodec.NewStructCodec(bsoncodec.DefaultStructTagParser, + structcodec, _ := bson.NewStructCodec(bson.DefaultStructTagParser, bsonoptions.StructCodec(). SetDecodeZeroStruct(true). SetEncodeOmitDefaultStruct(true). SetOverwriteDuplicatedInlinedFields(false). SetAllowUnexportedFields(true)) - mapCodec := bsoncodec.NewMapCodec( + mapCodec := bson.NewMapCodec( bsonoptions.MapCodec(). SetDecodeZerosMap(true). SetEncodeNilAsEmpty(false)) rb.RegisterDefaultDecoder(reflect.Struct, structcodec). RegisterDefaultDecoder(reflect.Map, mapCodec). - RegisterTypeEncoder(tByteSlice, bsoncodec.NewByteSliceCodec(bsonoptions.ByteSliceCodec().SetEncodeNilAsEmpty(false))). + RegisterTypeEncoder(tByteSlice, bson.NewByteSliceCodec(bsonoptions.ByteSliceCodec().SetEncodeNilAsEmpty(false))). RegisterDefaultEncoder(reflect.Struct, structcodec). - RegisterDefaultEncoder(reflect.Slice, bsoncodec.NewSliceCodec(bsonoptions.SliceCodec().SetEncodeNilAsEmpty(false))). + RegisterDefaultEncoder(reflect.Slice, bson.NewSliceCodec(bsonoptions.SliceCodec().SetEncodeNilAsEmpty(false))). RegisterDefaultEncoder(reflect.Map, mapCodec) return rb diff --git a/bson/mgocompat/setter_getter.go b/bson/mgocompat/setter_getter.go index e9c9cae834..fc620fbba8 100644 --- a/bson/mgocompat/setter_getter.go +++ b/bson/mgocompat/setter_getter.go @@ -11,8 +11,6 @@ import ( "reflect" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" ) // Setter interface: a value implementing the bson.Setter interface will receive the BSON @@ -50,33 +48,33 @@ type Getter interface { } // SetterDecodeValue is the ValueDecoderFunc for Setter types. -func SetterDecodeValue(_ bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func SetterDecodeValue(_ bson.DecodeContext, vr bson.ValueReader, val reflect.Value) error { if !val.IsValid() || (!val.Type().Implements(tSetter) && !reflect.PtrTo(val.Type()).Implements(tSetter)) { - return bsoncodec.ValueDecoderError{Name: "SetterDecodeValue", Types: []reflect.Type{tSetter}, Received: val} + return bson.ValueDecoderError{Name: "SetterDecodeValue", Types: []reflect.Type{tSetter}, Received: val} } if val.Kind() == reflect.Ptr && val.IsNil() { if !val.CanSet() { - return bsoncodec.ValueDecoderError{Name: "SetterDecodeValue", Types: []reflect.Type{tSetter}, Received: val} + return bson.ValueDecoderError{Name: "SetterDecodeValue", Types: []reflect.Type{tSetter}, Received: val} } val.Set(reflect.New(val.Type().Elem())) } if !val.Type().Implements(tSetter) { if !val.CanAddr() { - return bsoncodec.ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tSetter}, Received: val} + return bson.ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tSetter}, Received: val} } val = val.Addr() // If the type doesn't implement the interface, a pointer to it must. } - t, src, err := bsonrw.Copier{}.CopyValueToBytes(vr) + t, src, err := bson.CopyValueToBytes(vr) if err != nil { return err } m, ok := val.Interface().(Setter) if !ok { - return bsoncodec.ValueDecoderError{Name: "SetterDecodeValue", Types: []reflect.Type{tSetter}, Received: val} + return bson.ValueDecoderError{Name: "SetterDecodeValue", Types: []reflect.Type{tSetter}, Received: val} } if err := m.SetBSON(bson.RawValue{Type: t, Value: src}); err != nil { if !errors.Is(err, ErrSetZero) { @@ -88,11 +86,11 @@ func SetterDecodeValue(_ bsoncodec.DecodeContext, vr bsonrw.ValueReader, val ref } // GetterEncodeValue is the ValueEncoderFunc for Getter types. -func GetterEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func GetterEncodeValue(ec bson.EncodeContext, vw bson.ValueWriter, val reflect.Value) error { // Either val or a pointer to val must implement Getter switch { case !val.IsValid(): - return bsoncodec.ValueEncoderError{Name: "GetterEncodeValue", Types: []reflect.Type{tGetter}, Received: val} + return bson.ValueEncoderError{Name: "GetterEncodeValue", Types: []reflect.Type{tGetter}, Received: val} case val.Type().Implements(tGetter): // If Getter is implemented on a concrete type, make sure that val isn't a nil pointer if isImplementationNil(val, tGetter) { @@ -101,7 +99,7 @@ func GetterEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val re case reflect.PtrTo(val.Type()).Implements(tGetter) && val.CanAddr(): val = val.Addr() default: - return bsoncodec.ValueEncoderError{Name: "GetterEncodeValue", Types: []reflect.Type{tGetter}, Received: val} + return bson.ValueEncoderError{Name: "GetterEncodeValue", Types: []reflect.Type{tGetter}, Received: val} } m, ok := val.Interface().(Getter) diff --git a/bson/bsonrw/mode.go b/bson/mode.go similarity index 71% rename from bson/bsonrw/mode.go rename to bson/mode.go index 617b5e2212..a4563892ac 100644 --- a/bson/bsonrw/mode.go +++ b/bson/mode.go @@ -4,7 +4,7 @@ // 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 bsonrw +package bson import ( "fmt" @@ -26,31 +26,6 @@ const ( func (m mode) String() string { var str string - switch m { - case mTopLevel: - str = "TopLevel" - case mDocument: - str = "DocumentMode" - case mArray: - str = "ArrayMode" - case mValue: - str = "ValueMode" - case mElement: - str = "ElementMode" - case mCodeWithScope: - str = "CodeWithScopeMode" - case mSpacer: - str = "CodeWithScopeSpacerFrame" - default: - str = "UnknownMode" - } - - return str -} - -func (m mode) TypeString() string { - var str string - switch m { case mTopLevel: str = "TopLevel" @@ -75,7 +50,6 @@ func (m mode) TypeString() string { // TransitionError is an error returned when an invalid progressing a // ValueReader or ValueWriter state machine occurs. -// If read is false, the error is for writing type TransitionError struct { name string parent mode @@ -88,7 +62,7 @@ type TransitionError struct { func (te TransitionError) Error() string { errString := fmt.Sprintf("%s can only %s", te.name, te.action) if te.destination != mode(0) { - errString = fmt.Sprintf("%s a %s", errString, te.destination.TypeString()) + errString = fmt.Sprintf("%s a %s", errString, te.destination) } errString = fmt.Sprintf("%s while positioned on a", errString) for ind, m := range te.modes { @@ -98,11 +72,11 @@ func (te TransitionError) Error() string { if ind == len(te.modes)-1 && len(te.modes) > 1 { errString = fmt.Sprintf("%s or", errString) } - errString = fmt.Sprintf("%s %s", errString, m.TypeString()) + errString = fmt.Sprintf("%s %s", errString, m) } - errString = fmt.Sprintf("%s but is positioned on a %s", errString, te.current.TypeString()) + errString = fmt.Sprintf("%s but is positioned on a %s", errString, te.current) if te.parent != mode(0) { - errString = fmt.Sprintf("%s with parent %s", errString, te.parent.TypeString()) + errString = fmt.Sprintf("%s with parent %s", errString, te.parent) } return errString } diff --git a/bson/primitive/objectid.go b/bson/objectid.go similarity index 99% rename from bson/primitive/objectid.go rename to bson/objectid.go index c130e3ff19..b2f345a344 100644 --- a/bson/primitive/objectid.go +++ b/bson/objectid.go @@ -7,7 +7,7 @@ // Based on gopkg.in/mgo.v2/bson by Gustavo Niemeyer // See THIRD-PARTY-NOTICES for original license terms. -package primitive +package bson import ( "crypto/rand" diff --git a/bson/primitive/objectid_test.go b/bson/objectid_test.go similarity index 99% rename from bson/primitive/objectid_test.go rename to bson/objectid_test.go index 5ed296120b..178fb9ffa4 100644 --- a/bson/primitive/objectid_test.go +++ b/bson/objectid_test.go @@ -4,7 +4,7 @@ // 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 primitive +package bson import ( "encoding/binary" diff --git a/bson/bsoncodec/pointer_codec.go b/bson/pointer_codec.go similarity index 87% rename from bson/bsoncodec/pointer_codec.go rename to bson/pointer_codec.go index e5923230b0..5946b9cc9f 100644 --- a/bson/bsoncodec/pointer_codec.go +++ b/bson/pointer_codec.go @@ -4,13 +4,10 @@ // 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 +package bson import ( "reflect" - - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" ) var _ ValueEncoder = &PointerCodec{} @@ -35,7 +32,7 @@ func NewPointerCodec() *PointerCodec { // EncodeValue handles encoding a pointer by either encoding it to BSON Null if the pointer is nil // or looking up an encoder for the type of value the pointer points to. -func (pc *PointerCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (pc *PointerCodec) EncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if val.Kind() != reflect.Ptr { if !val.IsValid() { return vw.WriteNull() @@ -65,17 +62,17 @@ func (pc *PointerCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val // DecodeValue handles decoding a pointer by looking up a decoder for the type it points to and // using that to decode. If the BSON value is Null, this method will set the pointer to nil. -func (pc *PointerCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (pc *PointerCodec) DecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Kind() != reflect.Ptr { return ValueDecoderError{Name: "PointerCodec.DecodeValue", Kinds: []reflect.Kind{reflect.Ptr}, Received: val} } typ := val.Type() - if vr.Type() == bsontype.Null { + if vr.Type() == TypeNull { val.Set(reflect.Zero(typ)) return vr.ReadNull() } - if vr.Type() == bsontype.Undefined { + if vr.Type() == TypeUndefined { val.Set(reflect.Zero(typ)) return vr.ReadUndefined() } diff --git a/bson/primitive/primitive.go b/bson/primitive.go similarity index 92% rename from bson/primitive/primitive.go rename to bson/primitive.go index 65f4fbb949..bf644fa338 100644 --- a/bson/primitive/primitive.go +++ b/bson/primitive.go @@ -3,10 +3,11 @@ // 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 +// +// Based on gopkg.in/mgo.v2/bson by Gustavo Niemeyer +// See THIRD-PARTY-NOTICES for original license terms. -// Package primitive contains types similar to Go primitives for BSON types that do not have direct -// Go primitive representations. -package primitive // import "go.mongodb.org/mongo-driver/bson/primitive" +package bson // import "go.mongodb.org/mongo-driver/bson" import ( "bytes" @@ -15,6 +16,16 @@ import ( "time" ) +// Zeroer allows custom struct types to implement a report of zero +// state. All struct types that don't implement Zeroer or where IsZero +// returns false are considered to be not zero. +type Zeroer interface { + IsZero() bool +} + +// The following primitive types are similar to Go primitives for BSON types that +// do not have direct Go primitive representations. + // Binary represents a BSON binary value. type Binary struct { Subtype byte diff --git a/bson/primitive/primitive_test.go b/bson/primitive/primitive_test.go deleted file mode 100644 index 821d651ae4..0000000000 --- a/bson/primitive/primitive_test.go +++ /dev/null @@ -1,201 +0,0 @@ -// 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 primitive - -import ( - "encoding/json" - "testing" - "time" - - "go.mongodb.org/mongo-driver/internal/assert" - "go.mongodb.org/mongo-driver/internal/require" -) - -// The same interface as bsoncodec.Zeroer implemented for tests. -type zeroer interface { - IsZero() bool -} - -func TestCompareTimestamp(t *testing.T) { - testcases := []struct { - name string - tp Timestamp - tp2 Timestamp - expected int - }{ - {"equal", Timestamp{T: 12345, I: 67890}, Timestamp{T: 12345, I: 67890}, 0}, - {"T greater than", Timestamp{T: 12345, I: 67890}, Timestamp{T: 2345, I: 67890}, 1}, - {"I greater than", Timestamp{T: 12345, I: 67890}, Timestamp{T: 12345, I: 7890}, 1}, - {"T less than", Timestamp{T: 12345, I: 67890}, Timestamp{T: 112345, I: 67890}, -1}, - {"I less than", Timestamp{T: 12345, I: 67890}, Timestamp{T: 12345, I: 167890}, -1}, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - result := CompareTimestamp(tc.tp, tc.tp2) - require.Equal(t, tc.expected, result) - }) - } -} - -func TestTimestamp(t *testing.T) { - t.Parallel() - - testCases := []struct { - description string - tp Timestamp - tp2 Timestamp - expectedAfter bool - expectedBefore bool - expectedEqual bool - expectedCompare int - }{ - { - description: "equal", - tp: Timestamp{T: 12345, I: 67890}, - tp2: Timestamp{T: 12345, I: 67890}, - expectedBefore: false, - expectedAfter: false, - expectedEqual: true, - expectedCompare: 0, - }, - { - description: "T greater than", - tp: Timestamp{T: 12345, I: 67890}, - tp2: Timestamp{T: 2345, I: 67890}, - expectedBefore: false, - expectedAfter: true, - expectedEqual: false, - expectedCompare: 1, - }, - { - description: "I greater than", - tp: Timestamp{T: 12345, I: 67890}, - tp2: Timestamp{T: 12345, I: 7890}, - expectedBefore: false, - expectedAfter: true, - expectedEqual: false, - expectedCompare: 1, - }, - { - description: "T less than", - tp: Timestamp{T: 12345, I: 67890}, - tp2: Timestamp{T: 112345, I: 67890}, - expectedBefore: true, - expectedAfter: false, - expectedEqual: false, - expectedCompare: -1, - }, - { - description: "I less than", - tp: Timestamp{T: 12345, I: 67890}, - tp2: Timestamp{T: 12345, I: 167890}, - expectedBefore: true, - expectedAfter: false, - expectedEqual: false, - expectedCompare: -1, - }, - } - - for _, tc := range testCases { - tc := tc // Capture range variable. - - t.Run(tc.description, func(t *testing.T) { - t.Parallel() - - assert.Equal(t, tc.expectedAfter, tc.tp.After(tc.tp2), "expected After results to be the same") - assert.Equal(t, tc.expectedBefore, tc.tp.Before(tc.tp2), "expected Before results to be the same") - assert.Equal(t, tc.expectedEqual, tc.tp.Equal(tc.tp2), "expected Equal results to be the same") - assert.Equal(t, tc.expectedCompare, tc.tp.Compare(tc.tp2), "expected Compare result to be the same") - }) - } -} - -func TestPrimitiveIsZero(t *testing.T) { - testcases := []struct { - name string - zero zeroer - nonzero zeroer - }{ - {"binary", Binary{}, Binary{Data: []byte{0x01, 0x02, 0x03}, Subtype: 0xFF}}, - {"decimal128", Decimal128{}, NewDecimal128(1, 2)}, - {"objectID", ObjectID{}, NewObjectID()}, - {"regex", Regex{}, Regex{Pattern: "foo", Options: "bar"}}, - {"dbPointer", DBPointer{}, DBPointer{DB: "foobar", Pointer: ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}}}, - {"timestamp", Timestamp{}, Timestamp{T: 12345, I: 67890}}, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - require.True(t, tc.zero.IsZero()) - require.False(t, tc.nonzero.IsZero()) - }) - } -} - -func TestRegexCompare(t *testing.T) { - testcases := []struct { - name string - r1 Regex - r2 Regex - eq bool - }{ - {"equal", Regex{Pattern: "foo1", Options: "bar1"}, Regex{Pattern: "foo1", Options: "bar1"}, true}, - {"not equal", Regex{Pattern: "foo1", Options: "bar1"}, Regex{Pattern: "foo2", Options: "bar2"}, false}, - {"not equal", Regex{Pattern: "foo1", Options: "bar1"}, Regex{Pattern: "foo1", Options: "bar2"}, false}, - {"not equal", Regex{Pattern: "foo1", Options: "bar1"}, Regex{Pattern: "foo2", Options: "bar1"}, false}, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - require.True(t, tc.r1.Equal(tc.r2) == tc.eq) - }) - } -} - -func TestDateTime(t *testing.T) { - t.Run("json", func(t *testing.T) { - t.Run("round trip", func(t *testing.T) { - original := DateTime(1000) - jsonBytes, err := json.Marshal(original) - assert.Nil(t, err, "Marshal error: %v", err) - - var unmarshalled DateTime - err = json.Unmarshal(jsonBytes, &unmarshalled) - assert.Nil(t, err, "Unmarshal error: %v", err) - - assert.Equal(t, original, unmarshalled, "expected DateTime %v, got %v", original, unmarshalled) - }) - t.Run("decode null", func(t *testing.T) { - jsonBytes := []byte("null") - var dt DateTime - err := json.Unmarshal(jsonBytes, &dt) - assert.Nil(t, err, "Unmarshal error: %v", err) - assert.Equal(t, DateTime(0), dt, "expected DateTime value to be 0, got %v", dt) - }) - t.Run("UTC", func(t *testing.T) { - dt := DateTime(1681145535123) - jsonBytes, err := json.Marshal(dt) - assert.Nil(t, err, "Marshal error: %v", err) - assert.Equal(t, `"2023-04-10T16:52:15.123Z"`, string(jsonBytes)) - }) - }) - t.Run("NewDateTimeFromTime", func(t *testing.T) { - t.Run("range is not limited", func(t *testing.T) { - // If the implementation internally calls time.Time.UnixNano(), the constructor cannot handle times after - // the year 2262. - - timeFormat := "2006-01-02T15:04:05.999Z07:00" - timeString := "3001-01-01T00:00:00Z" - tt, err := time.Parse(timeFormat, timeString) - assert.Nil(t, err, "Parse error: %v", err) - - dt := NewDateTimeFromTime(tt) - assert.True(t, dt > 0, "expected a valid DateTime greater than 0, got %v", dt) - }) - }) -} diff --git a/bson/primitive_codecs.go b/bson/primitive_codecs.go index ff32a87a79..262645ce4c 100644 --- a/bson/primitive_codecs.go +++ b/bson/primitive_codecs.go @@ -10,17 +10,12 @@ import ( "errors" "fmt" "reflect" - - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" ) var tRawValue = reflect.TypeOf(RawValue{}) var tRaw = reflect.TypeOf(Raw(nil)) -var primitiveCodecs PrimitiveCodecs - -// PrimitiveCodecs is a namespace for all of the default bsoncodec.Codecs for the primitive types +// PrimitiveCodecs is a namespace for all of the default Codecs for the primitive types // defined in this package. // // Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders @@ -32,16 +27,16 @@ type PrimitiveCodecs struct{} // // Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders // registered. -func (pc PrimitiveCodecs) RegisterPrimitiveCodecs(rb *bsoncodec.RegistryBuilder) { +func (pc PrimitiveCodecs) RegisterPrimitiveCodecs(rb *RegistryBuilder) { if rb == nil { panic(errors.New("argument to RegisterPrimitiveCodecs must not be nil")) } rb. - RegisterTypeEncoder(tRawValue, bsoncodec.ValueEncoderFunc(pc.RawValueEncodeValue)). - RegisterTypeEncoder(tRaw, bsoncodec.ValueEncoderFunc(pc.RawEncodeValue)). - RegisterTypeDecoder(tRawValue, bsoncodec.ValueDecoderFunc(pc.RawValueDecodeValue)). - RegisterTypeDecoder(tRaw, bsoncodec.ValueDecoderFunc(pc.RawDecodeValue)) + RegisterTypeEncoder(tRawValue, ValueEncoderFunc(pc.RawValueEncodeValue)). + RegisterTypeEncoder(tRaw, ValueEncoderFunc(pc.RawEncodeValue)). + RegisterTypeDecoder(tRawValue, ValueDecoderFunc(pc.RawValueDecodeValue)). + RegisterTypeDecoder(tRaw, ValueDecoderFunc(pc.RawDecodeValue)) } // RawValueEncodeValue is the ValueEncoderFunc for RawValue. @@ -51,9 +46,9 @@ func (pc PrimitiveCodecs) RegisterPrimitiveCodecs(rb *bsoncodec.RegistryBuilder) // // Deprecated: Use bson.NewRegistry to get a registry with all primitive // encoders and decoders registered. -func (PrimitiveCodecs) RawValueEncodeValue(_ bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (PrimitiveCodecs) RawValueEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tRawValue { - return bsoncodec.ValueEncoderError{ + return ValueEncoderError{ Name: "RawValueEncodeValue", Types: []reflect.Type{tRawValue}, Received: val, @@ -66,19 +61,19 @@ func (PrimitiveCodecs) RawValueEncodeValue(_ bsoncodec.EncodeContext, vw bsonrw. return fmt.Errorf("the RawValue Type specifies an invalid BSON type: %#x", byte(rawvalue.Type)) } - return bsonrw.Copier{}.CopyValueFromBytes(vw, rawvalue.Type, rawvalue.Value) + return copyValueFromBytes(vw, rawvalue.Type, rawvalue.Value) } // RawValueDecodeValue is the ValueDecoderFunc for RawValue. // // Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders // registered. -func (PrimitiveCodecs) RawValueDecodeValue(_ bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (PrimitiveCodecs) RawValueDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tRawValue { - return bsoncodec.ValueDecoderError{Name: "RawValueDecodeValue", Types: []reflect.Type{tRawValue}, Received: val} + return ValueDecoderError{Name: "RawValueDecodeValue", Types: []reflect.Type{tRawValue}, Received: val} } - t, value, err := bsonrw.Copier{}.CopyValueToBytes(vr) + t, value, err := CopyValueToBytes(vr) if err != nil { return err } @@ -91,23 +86,23 @@ func (PrimitiveCodecs) RawValueDecodeValue(_ bsoncodec.DecodeContext, vr bsonrw. // // Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders // registered. -func (PrimitiveCodecs) RawEncodeValue(_ bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (PrimitiveCodecs) RawEncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tRaw { - return bsoncodec.ValueEncoderError{Name: "RawEncodeValue", Types: []reflect.Type{tRaw}, Received: val} + return ValueEncoderError{Name: "RawEncodeValue", Types: []reflect.Type{tRaw}, Received: val} } rdr := val.Interface().(Raw) - return bsonrw.Copier{}.CopyDocumentFromBytes(vw, rdr) + return copyDocumentFromBytes(vw, rdr) } // RawDecodeValue is the ValueDecoderFunc for Reader. // // Deprecated: Use bson.NewRegistry to get a registry with all primitive encoders and decoders // registered. -func (PrimitiveCodecs) RawDecodeValue(_ bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (PrimitiveCodecs) RawDecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tRaw { - return bsoncodec.ValueDecoderError{Name: "RawDecodeValue", Types: []reflect.Type{tRaw}, Received: val} + return ValueDecoderError{Name: "RawDecodeValue", Types: []reflect.Type{tRaw}, Received: val} } if val.IsNil() { @@ -116,7 +111,7 @@ func (PrimitiveCodecs) RawDecodeValue(_ bsoncodec.DecodeContext, vr bsonrw.Value val.SetLen(0) - rdr, err := bsonrw.Copier{}.AppendDocumentBytes(val.Interface().(Raw), vr) + rdr, err := appendDocumentBytes(val.Interface().(Raw), vr) val.Set(reflect.ValueOf(rdr)) return err } diff --git a/bson/primitive_codecs_test.go b/bson/primitive_codecs_test.go index 0d9dc6169c..be3aeab978 100644 --- a/bson/primitive_codecs_test.go +++ b/bson/primitive_codecs_test.go @@ -17,11 +17,7 @@ import ( "time" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsonrw/bsonrwtest" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -33,38 +29,7 @@ func bytesFromDoc(doc interface{}) []byte { return b } -func compareDecimal128(d1, d2 primitive.Decimal128) bool { - d1H, d1L := d1.GetBytes() - d2H, d2L := d2.GetBytes() - - if d1H != d2H { - return false - } - - if d1L != d2L { - return false - } - - return true -} - -func compareErrors(err1, err2 error) bool { - if err1 == nil && err2 == nil { - return true - } - - if err1 == nil || err2 == nil { - return false - } - - if err1.Error() != err2.Error() { - return false - } - - return true -} - -func TestDefaultValueEncoders(t *testing.T) { +func TestPrimitiveValueEncoders(t *testing.T) { t.Parallel() var pc PrimitiveCodecs @@ -74,28 +39,28 @@ func TestDefaultValueEncoders(t *testing.T) { type subtest struct { name string val interface{} - ectx *bsoncodec.EncodeContext - llvrw *bsonrwtest.ValueReaderWriter - invoke bsonrwtest.Invoked + ectx *EncodeContext + llvrw *valueReaderWriter + invoke invoked err error } testCases := []struct { name string - ve bsoncodec.ValueEncoder + ve ValueEncoder subtests []subtest }{ { "RawValueEncodeValue", - bsoncodec.ValueEncoderFunc(pc.RawValueEncodeValue), + ValueEncoderFunc(pc.RawValueEncodeValue), []subtest{ { "wrong type", wrong, nil, nil, - bsonrwtest.Nothing, - bsoncodec.ValueEncoderError{ + nothing, + ValueEncoderError{ Name: "RawValueEncodeValue", Types: []reflect.Type{tRawValue}, Received: reflect.ValueOf(wrong), @@ -103,10 +68,10 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "RawValue/success", - RawValue{Type: bsontype.Double, Value: bsoncore.AppendDouble(nil, 3.14159)}, + RawValue{Type: TypeDouble, Value: bsoncore.AppendDouble(nil, 3.14159)}, nil, nil, - bsonrwtest.WriteDouble, + writeDouble, nil, }, { @@ -117,7 +82,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, nil, nil, - bsonrwtest.Nothing, + nothing, fmt.Errorf("the RawValue Type specifies an invalid BSON type: 0x0"), }, { @@ -128,61 +93,61 @@ func TestDefaultValueEncoders(t *testing.T) { }, nil, nil, - bsonrwtest.Nothing, + nothing, fmt.Errorf("the RawValue Type specifies an invalid BSON type: 0x8f"), }, }, }, { "RawEncodeValue", - bsoncodec.ValueEncoderFunc(pc.RawEncodeValue), + ValueEncoderFunc(pc.RawEncodeValue), []subtest{ { "wrong type", wrong, nil, nil, - bsonrwtest.Nothing, - bsoncodec.ValueEncoderError{Name: "RawEncodeValue", Types: []reflect.Type{tRaw}, Received: reflect.ValueOf(wrong)}, + nothing, + ValueEncoderError{Name: "RawEncodeValue", Types: []reflect.Type{tRaw}, Received: reflect.ValueOf(wrong)}, }, { "WriteDocument Error", Raw{}, nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("wd error"), ErrAfter: bsonrwtest.WriteDocument}, - bsonrwtest.WriteDocument, + &valueReaderWriter{Err: errors.New("wd error"), ErrAfter: writeDocument}, + writeDocument, errors.New("wd error"), }, { "Raw.Elements Error", Raw{0xFF, 0x00, 0x00, 0x00, 0x00}, nil, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.WriteDocument, + &valueReaderWriter{}, + writeDocument, errors.New("length read exceeds number of bytes available. length=5 bytes=255"), }, { "WriteDocumentElement Error", Raw(bytesFromDoc(D{{"foo", nil}})), nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("wde error"), ErrAfter: bsonrwtest.WriteDocumentElement}, - bsonrwtest.WriteDocumentElement, + &valueReaderWriter{Err: errors.New("wde error"), ErrAfter: writeDocumentElement}, + writeDocumentElement, errors.New("wde error"), }, { "encodeValue error", Raw(bytesFromDoc(D{{"foo", nil}})), nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("ev error"), ErrAfter: bsonrwtest.WriteNull}, - bsonrwtest.WriteNull, + &valueReaderWriter{Err: errors.New("ev error"), ErrAfter: writeNull}, + writeNull, errors.New("ev error"), }, { "iterator error", Raw{0x0C, 0x00, 0x00, 0x00, 0x01, 'f', 'o', 'o', 0x00, 0x01, 0x02, 0x03}, nil, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.WriteDocumentElement, + &valueReaderWriter{}, + writeDocumentElement, errors.New("not enough bytes available to read type. bytes=3 type=double"), }, }, @@ -201,20 +166,20 @@ func TestDefaultValueEncoders(t *testing.T) { t.Run(subtest.name, func(t *testing.T) { t.Parallel() - var ec bsoncodec.EncodeContext + var ec EncodeContext if subtest.ectx != nil { ec = *subtest.ectx } - llvrw := new(bsonrwtest.ValueReaderWriter) + llvrw := new(valueReaderWriter) if subtest.llvrw != nil { llvrw = subtest.llvrw } llvrw.T = t err := tc.ve.EncodeValue(ec, llvrw, reflect.ValueOf(subtest.val)) - if !compareErrors(err, subtest.err) { + if !assert.CompareErrors(err, subtest.err) { t.Errorf("Errors do not match. got %v; want %v", err, subtest.err) } - invoked := llvrw.Invoked + invoked := llvrw.invoked if !cmp.Equal(invoked, subtest.invoke) { t.Errorf("Incorrect method invoked. got %v; want %v", invoked, subtest.invoke) } @@ -226,8 +191,8 @@ func TestDefaultValueEncoders(t *testing.T) { t.Run("success path", func(t *testing.T) { t.Parallel() - oid := primitive.NewObjectID() - oids := []primitive.ObjectID{primitive.NewObjectID(), primitive.NewObjectID(), primitive.NewObjectID()} + oid := NewObjectID() + oids := []ObjectID{NewObjectID(), NewObjectID(), NewObjectID()} var str = new(string) *str = "bar" now := time.Now().Truncate(time.Millisecond) @@ -236,7 +201,7 @@ func TestDefaultValueEncoders(t *testing.T) { t.Errorf("Error parsing URL: %v", err) t.FailNow() } - decimal128, err := primitive.ParseDecimal128("1.5e10") + decimal128, err := ParseDecimal128("1.5e10") if err != nil { t.Errorf("Error parsing decimal128: %v", err) t.FailNow() @@ -250,14 +215,14 @@ func TestDefaultValueEncoders(t *testing.T) { }{ { "D to JavaScript", - D{{"a", primitive.JavaScript(`function() { var hello = "world"; }`)}}, - docToBytes(D{{"a", primitive.JavaScript(`function() { var hello = "world"; }`)}}), + D{{"a", JavaScript(`function() { var hello = "world"; }`)}}, + docToBytes(D{{"a", JavaScript(`function() { var hello = "world"; }`)}}), nil, }, { "D to Symbol", - D{{"a", primitive.Symbol("foobarbaz")}}, - docToBytes(D{{"a", primitive.Symbol("foobarbaz")}}), + D{{"a", Symbol("foobarbaz")}}, + docToBytes(D{{"a", Symbol("foobarbaz")}}), nil, }, { @@ -307,13 +272,13 @@ func TestDefaultValueEncoders(t *testing.T) { M string } P Raw - Q primitive.ObjectID + Q ObjectID T []struct{} Y json.Number Z time.Time AA json.Number AB *url.URL - AC primitive.Decimal128 + AC Decimal128 AD *time.Time AE testValueMarshaler AF RawValue @@ -347,8 +312,8 @@ func TestDefaultValueEncoders(t *testing.T) { AC: decimal128, AD: &now, AE: testValueMarshaler{t: TypeString, buf: bsoncore.AppendString(nil, "hello, world")}, - AF: RawValue{Type: bsontype.String, Value: bsoncore.AppendString(nil, "hello, raw value")}, - AG: &RawValue{Type: bsontype.Double, Value: bsoncore.AppendDouble(nil, 3.14159)}, + AF: RawValue{Type: TypeString, Value: bsoncore.AppendString(nil, "hello, raw value")}, + AG: &RawValue{Type: TypeDouble, Value: bsoncore.AppendDouble(nil, 3.14159)}, AH: D{{"foo", "bar"}}, AI: &D{{"pi", 3.14159}}, AJ: nil, @@ -362,18 +327,18 @@ func TestDefaultValueEncoders(t *testing.T) { {"f", float64(3.14159)}, {"g", "Hello, world"}, {"h", D{{"foo", "bar"}}}, - {"i", primitive.Binary{Subtype: 0x00, Data: []byte{0x01, 0x02, 0x03}}}, + {"i", Binary{Subtype: 0x00, Data: []byte{0x01, 0x02, 0x03}}}, {"k", A{"baz", "qux"}}, {"l", D{{"m", "foobar"}}}, {"p", D{}}, {"q", oid}, {"t", nil}, {"y", int64(5)}, - {"z", primitive.DateTime(now.UnixNano() / int64(time.Millisecond))}, + {"z", DateTime(now.UnixNano() / int64(time.Millisecond))}, {"aa", float64(10.1)}, {"ab", murl.String()}, {"ac", decimal128}, - {"ad", primitive.DateTime(now.UnixNano() / int64(time.Millisecond))}, + {"ad", DateTime(now.UnixNano() / int64(time.Millisecond))}, {"ae", "hello, world"}, {"af", "hello, raw value"}, {"ag", 3.14159}, @@ -401,7 +366,7 @@ func TestDefaultValueEncoders(t *testing.T) { } N [][]string Q []Raw - R []primitive.ObjectID + R []ObjectID T []struct{} W []map[string]struct{} X []map[string]struct{} @@ -409,7 +374,7 @@ func TestDefaultValueEncoders(t *testing.T) { Z []time.Time AA []json.Number AB []*url.URL - AC []primitive.Decimal128 + AC []Decimal128 AD []*time.Time AE []testValueMarshaler AF []D @@ -442,7 +407,7 @@ func TestDefaultValueEncoders(t *testing.T) { Z: []time.Time{now, now}, AA: []json.Number{json.Number("5"), json.Number("10.1")}, AB: []*url.URL{murl}, - AC: []primitive.Decimal128{decimal128}, + AC: []Decimal128{decimal128}, AD: []*time.Time{&now, &now}, AE: []testValueMarshaler{ {t: TypeString, buf: bsoncore.AppendString(nil, "hello")}, @@ -460,7 +425,7 @@ func TestDefaultValueEncoders(t *testing.T) { {"f", A{float64(3.14159)}}, {"g", A{"Hello, world"}}, {"h", A{D{{"foo", "bar"}}}}, - {"i", A{primitive.Binary{Subtype: 0x00, Data: []byte{0x01, 0x02, 0x03}}}}, + {"i", A{Binary{Subtype: 0x00, Data: []byte{0x01, 0x02, 0x03}}}}, {"k", A{A{"baz", "qux"}}}, {"l", A{D{{"m", "foobar"}}}}, {"n", A{A{"foo", "bar"}}}, @@ -471,15 +436,15 @@ func TestDefaultValueEncoders(t *testing.T) { {"x", A{}}, {"y", A{D{}}}, {"z", A{ - primitive.DateTime(now.UnixNano() / int64(time.Millisecond)), - primitive.DateTime(now.UnixNano() / int64(time.Millisecond)), + DateTime(now.UnixNano() / int64(time.Millisecond)), + DateTime(now.UnixNano() / int64(time.Millisecond)), }}, {"aa", A{int64(5), float64(10.10)}}, {"ab", A{murl.String()}}, {"ac", A{decimal128}}, {"ad", A{ - primitive.DateTime(now.UnixNano() / int64(time.Millisecond)), - primitive.DateTime(now.UnixNano() / int64(time.Millisecond)), + DateTime(now.UnixNano() / int64(time.Millisecond)), + DateTime(now.UnixNano() / int64(time.Millisecond)), }}, {"ae", A{"hello", "world"}}, {"af", A{D{{"foo", "bar"}}, D{{"hello", "world"}, {"number", int32(12345)}}}}, @@ -495,8 +460,8 @@ func TestDefaultValueEncoders(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() - b := make(bsonrw.SliceWriter, 0, 512) - vw := bsonrw.NewValueWriter(&b) + b := make(SliceWriter, 0, 512) + vw := NewValueWriter(&b) enc := NewEncoder(vw) err := enc.Encode(tc.value) if !errors.Is(err, tc.err) { @@ -512,7 +477,7 @@ func TestDefaultValueEncoders(t *testing.T) { }) } -func TestDefaultValueDecoders(t *testing.T) { +func TestPrimitiveValueDecoders(t *testing.T) { var pc PrimitiveCodecs var wrong = func(string, string) string { return "wrong" } @@ -522,28 +487,28 @@ func TestDefaultValueDecoders(t *testing.T) { type subtest struct { name string val interface{} - dctx *bsoncodec.DecodeContext - llvrw *bsonrwtest.ValueReaderWriter - invoke bsonrwtest.Invoked + dctx *DecodeContext + llvrw *valueReaderWriter + invoke invoked err error } testCases := []struct { name string - vd bsoncodec.ValueDecoder + vd ValueDecoder subtests []subtest }{ { "RawValueDecodeValue", - bsoncodec.ValueDecoderFunc(pc.RawValueDecodeValue), + ValueDecoderFunc(pc.RawValueDecodeValue), []subtest{ { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.Nothing, - bsoncodec.ValueDecoderError{ + &valueReaderWriter{}, + nothing, + ValueDecoderError{ Name: "RawValueDecodeValue", Types: []reflect.Type{tRawValue}, Received: reflect.ValueOf(wrong), @@ -553,49 +518,49 @@ func TestDefaultValueDecoders(t *testing.T) { "ReadValue Error", RawValue{}, nil, - &bsonrwtest.ValueReaderWriter{ - BSONType: bsontype.Binary, + &valueReaderWriter{ + BSONType: TypeBinary, Err: errors.New("rb error"), - ErrAfter: bsonrwtest.ReadBinary, + ErrAfter: readBinary, }, - bsonrwtest.ReadBinary, + readBinary, errors.New("rb error"), }, { "RawValue/success", - RawValue{Type: bsontype.Binary, Value: bsoncore.AppendBinary(nil, 0xFF, []byte{0x01, 0x02, 0x03})}, + RawValue{Type: TypeBinary, Value: bsoncore.AppendBinary(nil, 0xFF, []byte{0x01, 0x02, 0x03})}, nil, - &bsonrwtest.ValueReaderWriter{ - BSONType: bsontype.Binary, + &valueReaderWriter{ + BSONType: TypeBinary, Return: bsoncore.Value{ - Type: bsontype.Binary, + Type: bsoncore.TypeBinary, Data: bsoncore.AppendBinary(nil, 0xFF, []byte{0x01, 0x02, 0x03}), }, }, - bsonrwtest.ReadBinary, + readBinary, nil, }, }, }, { "RawDecodeValue", - bsoncodec.ValueDecoderFunc(pc.RawDecodeValue), + ValueDecoderFunc(pc.RawDecodeValue), []subtest{ { "wrong type", wrong, nil, - &bsonrwtest.ValueReaderWriter{}, - bsonrwtest.Nothing, - bsoncodec.ValueDecoderError{Name: "RawDecodeValue", Types: []reflect.Type{tRaw}, Received: reflect.ValueOf(wrong)}, + &valueReaderWriter{}, + nothing, + ValueDecoderError{Name: "RawDecodeValue", Types: []reflect.Type{tRaw}, Received: reflect.ValueOf(wrong)}, }, { "*Raw is nil", (*Raw)(nil), nil, nil, - bsonrwtest.Nothing, - bsoncodec.ValueDecoderError{ + nothing, + ValueDecoderError{ Name: "RawDecodeValue", Types: []reflect.Type{tRaw}, Received: reflect.ValueOf((*Raw)(nil)), @@ -605,8 +570,8 @@ func TestDefaultValueDecoders(t *testing.T) { "Copy error", Raw{}, nil, - &bsonrwtest.ValueReaderWriter{Err: errors.New("copy error"), ErrAfter: bsonrwtest.ReadDocument}, - bsonrwtest.ReadDocument, + &valueReaderWriter{Err: errors.New("copy error"), ErrAfter: readDocument}, + readDocument, errors.New("copy error"), }, }, @@ -617,24 +582,24 @@ func TestDefaultValueDecoders(t *testing.T) { t.Run(tc.name, func(t *testing.T) { for _, rc := range tc.subtests { t.Run(rc.name, func(t *testing.T) { - var dc bsoncodec.DecodeContext + var dc DecodeContext if rc.dctx != nil { dc = *rc.dctx } - llvrw := new(bsonrwtest.ValueReaderWriter) + llvrw := new(valueReaderWriter) if rc.llvrw != nil { llvrw = rc.llvrw } llvrw.T = t if rc.val == cansetreflectiontest { // We're doing a CanSet reflection test err := tc.vd.DecodeValue(dc, llvrw, reflect.Value{}) - if !compareErrors(err, rc.err) { + if !assert.CompareErrors(err, rc.err) { t.Errorf("Errors do not match. got %v; want %v", err, rc.err) } val := reflect.New(reflect.TypeOf(rc.val)).Elem() err = tc.vd.DecodeValue(dc, llvrw, val) - if !compareErrors(err, rc.err) { + if !assert.CompareErrors(err, rc.err) { t.Errorf("Errors do not match. got %v; want %v", err, rc.err) } return @@ -651,10 +616,10 @@ func TestDefaultValueDecoders(t *testing.T) { } }() err := tc.vd.DecodeValue(dc, llvrw, val) - if !compareErrors(err, rc.err) { + if !assert.CompareErrors(err, rc.err) { t.Errorf("Errors do not match. got %v; want %v", err, rc.err) } - invoked := llvrw.Invoked + invoked := llvrw.invoked if !cmp.Equal(invoked, rc.invoke) { t.Errorf("Incorrect method invoked. got %v; want %v", invoked, rc.invoke) } @@ -671,8 +636,8 @@ func TestDefaultValueDecoders(t *testing.T) { } t.Run("success path", func(t *testing.T) { - oid := primitive.NewObjectID() - oids := []primitive.ObjectID{primitive.NewObjectID(), primitive.NewObjectID(), primitive.NewObjectID()} + oid := NewObjectID() + oids := []ObjectID{NewObjectID(), NewObjectID(), NewObjectID()} var str = new(string) *str = "bar" now := time.Now().Truncate(time.Millisecond) @@ -681,7 +646,7 @@ func TestDefaultValueDecoders(t *testing.T) { t.Errorf("Error parsing URL: %v", err) t.FailNow() } - decimal128, err := primitive.ParseDecimal128("1.5e10") + decimal128, err := ParseDecimal128("1.5e10") if err != nil { t.Errorf("Error parsing decimal128: %v", err) t.FailNow() @@ -705,8 +670,8 @@ func TestDefaultValueDecoders(t *testing.T) { nil, }, { - "map[string]primitive.ObjectID", - map[string]primitive.ObjectID{"foo": oid}, + "map[string]ObjectID", + map[string]ObjectID{"foo": oid}, docToBytes(D{{"foo", oid}}), nil, }, @@ -723,8 +688,8 @@ func TestDefaultValueDecoders(t *testing.T) { nil, }, { - "map[string][]primitive.ObjectID", - map[string][]primitive.ObjectID{"Z": oids}, + "map[string][]ObjectID", + map[string][]ObjectID{"Z": oids}, docToBytes(D{{"Z", A{oids[0], oids[1], oids[2]}}}), nil, }, @@ -747,8 +712,8 @@ func TestDefaultValueDecoders(t *testing.T) { nil, }, { - "map[string][]primitive.Decimal128", - map[string][]primitive.Decimal128{"Z": {decimal128}}, + "map[string][]Decimal128", + map[string][]Decimal128{"Z": {decimal128}}, docToBytes(D{{"Z", A{decimal128}}}), nil, }, @@ -858,14 +823,14 @@ func TestDefaultValueDecoders(t *testing.T) { }, { "JavaScript to D", - D{{"a", primitive.JavaScript(`function() { var hello = "world"; }`)}}, - docToBytes(D{{"a", primitive.JavaScript(`function() { var hello = "world"; }`)}}), + D{{"a", JavaScript(`function() { var hello = "world"; }`)}}, + docToBytes(D{{"a", JavaScript(`function() { var hello = "world"; }`)}}), nil, }, { "Symbol to D", - D{{"a", primitive.Symbol("foobarbaz")}}, - docToBytes(D{{"a", primitive.Symbol("foobarbaz")}}), + D{{"a", Symbol("foobarbaz")}}, + docToBytes(D{{"a", Symbol("foobarbaz")}}), nil, }, { @@ -885,13 +850,13 @@ func TestDefaultValueDecoders(t *testing.T) { M string } P Raw - Q primitive.ObjectID + Q ObjectID T []struct{} Y json.Number Z time.Time AA json.Number AB *url.URL - AC primitive.Decimal128 + AC Decimal128 AD *time.Time AE *testValueUnmarshaler AF RawValue @@ -924,9 +889,9 @@ func TestDefaultValueDecoders(t *testing.T) { AB: murl, AC: decimal128, AD: &now, - AE: &testValueUnmarshaler{t: bsontype.String, val: bsoncore.AppendString(nil, "hello, world!")}, - AF: RawValue{Type: bsontype.Double, Value: bsoncore.AppendDouble(nil, 3.14159)}, - AG: &RawValue{Type: bsontype.Binary, Value: bsoncore.AppendBinary(nil, 0xFF, []byte{0x01, 0x02, 0x03})}, + AE: &testValueUnmarshaler{t: TypeString, val: bsoncore.AppendString(nil, "hello, world!")}, + AF: RawValue{Type: TypeDouble, Value: bsoncore.AppendDouble(nil, 3.14159)}, + AG: &RawValue{Type: TypeBinary, Value: bsoncore.AppendBinary(nil, 0xFF, []byte{0x01, 0x02, 0x03})}, AH: D{{"foo", "bar"}}, AI: &D{{"pi", 3.14159}}, AJ: nil, @@ -940,21 +905,21 @@ func TestDefaultValueDecoders(t *testing.T) { {"f", float64(3.14159)}, {"g", "Hello, world"}, {"h", D{{"foo", "bar"}}}, - {"i", primitive.Binary{Subtype: 0x00, Data: []byte{0x01, 0x02, 0x03}}}, + {"i", Binary{Subtype: 0x00, Data: []byte{0x01, 0x02, 0x03}}}, {"k", A{"baz", "qux"}}, {"l", D{{"m", "foobar"}}}, {"p", D{}}, {"q", oid}, {"t", nil}, {"y", int64(5)}, - {"z", primitive.DateTime(now.UnixNano() / int64(time.Millisecond))}, + {"z", DateTime(now.UnixNano() / int64(time.Millisecond))}, {"aa", float64(10.1)}, {"ab", murl.String()}, {"ac", decimal128}, - {"ad", primitive.DateTime(now.UnixNano() / int64(time.Millisecond))}, + {"ad", DateTime(now.UnixNano() / int64(time.Millisecond))}, {"ae", "hello, world!"}, {"af", float64(3.14159)}, - {"ag", primitive.Binary{Subtype: 0xFF, Data: []byte{0x01, 0x02, 0x03}}}, + {"ag", Binary{Subtype: 0xFF, Data: []byte{0x01, 0x02, 0x03}}}, {"ah", D{{"foo", "bar"}}}, {"ai", D{{"pi", float64(3.14159)}}}, {"aj", nil}, @@ -979,7 +944,7 @@ func TestDefaultValueDecoders(t *testing.T) { } N [][]string Q []Raw - R []primitive.ObjectID + R []ObjectID T []struct{} W []map[string]struct{} X []map[string]struct{} @@ -987,7 +952,7 @@ func TestDefaultValueDecoders(t *testing.T) { Z []time.Time AA []json.Number AB []*url.URL - AC []primitive.Decimal128 + AC []Decimal128 AD []*time.Time AE []*testValueUnmarshaler AF []D @@ -1020,11 +985,11 @@ func TestDefaultValueDecoders(t *testing.T) { Z: []time.Time{now, now}, AA: []json.Number{json.Number("5"), json.Number("10.1")}, AB: []*url.URL{murl}, - AC: []primitive.Decimal128{decimal128}, + AC: []Decimal128{decimal128}, AD: []*time.Time{&now, &now}, AE: []*testValueUnmarshaler{ - {t: bsontype.String, val: bsoncore.AppendString(nil, "hello")}, - {t: bsontype.String, val: bsoncore.AppendString(nil, "world")}, + {t: TypeString, val: bsoncore.AppendString(nil, "hello")}, + {t: TypeString, val: bsoncore.AppendString(nil, "world")}, }, AF: []D{{{"foo", "bar"}}, {{"hello", "world"}, {"number", int64(12345)}}}, AG: []*D{{{"pi", 3.14159}}, nil}, @@ -1038,7 +1003,7 @@ func TestDefaultValueDecoders(t *testing.T) { {"f", A{float64(3.14159)}}, {"g", A{"Hello, world"}}, {"h", A{D{{"foo", "bar"}}}}, - {"i", A{primitive.Binary{Subtype: 0x00, Data: []byte{0x01, 0x02, 0x03}}}}, + {"i", A{Binary{Subtype: 0x00, Data: []byte{0x01, 0x02, 0x03}}}}, {"k", A{A{"baz", "qux"}}}, {"l", A{D{{"m", "foobar"}}}}, {"n", A{A{"foo", "bar"}}}, @@ -1049,15 +1014,15 @@ func TestDefaultValueDecoders(t *testing.T) { {"x", A{}}, {"y", A{D{}}}, {"z", A{ - primitive.DateTime(now.UnixNano() / int64(time.Millisecond)), - primitive.DateTime(now.UnixNano() / int64(time.Millisecond)), + DateTime(now.UnixNano() / int64(time.Millisecond)), + DateTime(now.UnixNano() / int64(time.Millisecond)), }}, {"aa", A{int64(5), float64(10.10)}}, {"ab", A{murl.String()}}, {"ac", A{decimal128}}, {"ad", A{ - primitive.DateTime(now.UnixNano() / int64(time.Millisecond)), - primitive.DateTime(now.UnixNano() / int64(time.Millisecond)), + DateTime(now.UnixNano() / int64(time.Millisecond)), + DateTime(now.UnixNano() / int64(time.Millisecond)), }}, {"ae", A{"hello", "world"}}, {"af", A{ @@ -1073,7 +1038,7 @@ func TestDefaultValueDecoders(t *testing.T) { t.Run("Decode", func(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - vr := bsonrw.NewValueReader(tc.b) + vr := NewValueReader(tc.b) dec := NewDecoder(vr) gotVal := reflect.New(reflect.TypeOf(tc.value)) err := dec.Decode(gotVal.Interface()) @@ -1096,22 +1061,22 @@ func TestDefaultValueDecoders(t *testing.T) { } type testValueMarshaler struct { - t bsontype.Type + t Type buf []byte err error } -func (tvm testValueMarshaler) MarshalBSONValue() (bsontype.Type, []byte, error) { +func (tvm testValueMarshaler) MarshalBSONValue() (Type, []byte, error) { return tvm.t, tvm.buf, tvm.err } type testValueUnmarshaler struct { - t bsontype.Type + t Type val []byte err error } -func (tvu *testValueUnmarshaler) UnmarshalBSONValue(t bsontype.Type, val []byte) error { +func (tvu *testValueUnmarshaler) UnmarshalBSONValue(t Type, val []byte) error { tvu.t, tvu.val = t, val return tvu.err } @@ -1134,3 +1099,18 @@ type zeroTest struct { func (z zeroTest) IsZero() bool { return z.reportZero } func compareZeroTest(_, _ zeroTest) bool { return true } + +func compareDecimal128(d1, d2 Decimal128) bool { + d1H, d1L := d1.GetBytes() + d2H, d2L := d2.GetBytes() + + if d1H != d2H { + return false + } + + if d1L != d2L { + return false + } + + return true +} diff --git a/bson/bsoncodec/proxy.go b/bson/proxy.go similarity index 96% rename from bson/bsoncodec/proxy.go rename to bson/proxy.go index 4cf2b01ab4..1ccca6c2d1 100644 --- a/bson/bsoncodec/proxy.go +++ b/bson/proxy.go @@ -4,7 +4,7 @@ // 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 +package bson // Proxy is an interface implemented by types that cannot themselves be directly encoded. Types // that implement this interface with have ProxyBSON called during the encoding process and that diff --git a/bson/raw_test.go b/bson/raw_test.go index d078012290..bb65f0ccb2 100644 --- a/bson/raw_test.go +++ b/bson/raw_test.go @@ -16,7 +16,7 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/require" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -44,7 +44,7 @@ func TestRaw(t *testing.T) { t.Run("TooShort", func(t *testing.T) { want := bsoncore.NewInsufficientBytesError(nil, nil) got := Raw{'\x00', '\x00'}.Validate() - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -83,7 +83,7 @@ func TestRaw(t *testing.T) { binary.LittleEndian.PutUint32(r[0:4], 11) r[4], r[5], r[6], r[7], r[8], r[9], r[10] = '\x01', 'f', 'o', 'o', '\x00', '\x01', '\x02' got := r.Validate() - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -143,7 +143,7 @@ func TestRaw(t *testing.T) { } _, err := rdr.LookupErr("x", "y") want := bsoncore.NewInsufficientBytesError(nil, nil) - if !compareErrors(err, want) { + if !assert.CompareErrors(err, want) { t.Errorf("Empty key lookup did not return expected result. got %v; want %v", err, want) } }) @@ -158,15 +158,15 @@ func TestRaw(t *testing.T) { } _, err := rdr.LookupErr("x", "y") want := bsoncore.NewInsufficientBytesError(nil, nil) - if !compareErrors(err, want) { + if !assert.CompareErrors(err, want) { t.Errorf("Empty key lookup did not return expected result. got %v; want %v", err, want) } }) t.Run("invalid-traversal", func(t *testing.T) { rdr := Raw{'\x08', '\x00', '\x00', '\x00', '\x0A', 'x', '\x00', '\x00'} _, err := rdr.LookupErr("x", "y") - want := bsoncore.InvalidDepthTraversalError{Key: "x", Type: bsontype.Null} - if !compareErrors(err, want) { + want := bsoncore.InvalidDepthTraversalError{Key: "x", Type: bsoncore.TypeNull} + if !assert.CompareErrors(err, want) { t.Errorf("Empty key lookup did not return expected result. got %v; want %v", err, want) } }) @@ -182,7 +182,7 @@ func TestRaw(t *testing.T) { '\x08', '\x00', '\x00', '\x00', '\x0A', 'x', '\x00', '\x00', }, []string{"x"}, - RawValue{Type: bsontype.Null}, nil, + RawValue{Type: TypeNull}, nil, }, {"first-second", Raw{ @@ -193,7 +193,7 @@ func TestRaw(t *testing.T) { '\x0A', 'b', '\x00', '\x00', '\x00', }, []string{"foo", "b"}, - RawValue{Type: bsontype.Null}, nil, + RawValue{Type: TypeNull}, nil, }, {"first-second-array", Raw{ @@ -204,7 +204,7 @@ func TestRaw(t *testing.T) { '\x0A', '2', '\x00', '\x00', '\x00', }, []string{"foo", "2"}, - RawValue{Type: bsontype.Null}, nil, + RawValue{Type: TypeNull}, nil, }, } @@ -232,7 +232,7 @@ func TestRaw(t *testing.T) { rdr := Raw{0x07, 0x00, 0x00, 0x00, 0x00} _, err := rdr.IndexErr(1) want := bsoncore.NewInsufficientBytesError(nil, nil) - if !compareErrors(err, want) { + if !assert.CompareErrors(err, want) { t.Errorf("Did not receive expected error. got %v; want %v", err, want) } }) diff --git a/bson/raw_value.go b/bson/raw_value.go index b5855f62e4..f53d5bc940 100644 --- a/bson/raw_value.go +++ b/bson/raw_value.go @@ -13,10 +13,6 @@ import ( "reflect" "time" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -31,10 +27,10 @@ var ErrNilRegistry = errors.New("Registry cannot be nil") // // A RawValue must be an individual BSON value. Use the Raw type for full BSON documents. type RawValue struct { - Type bsontype.Type + Type Type Value []byte - r *bsoncodec.Registry + r *Registry } // IsZero reports whether the RawValue is zero, i.e. no data is present on @@ -70,12 +66,12 @@ 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 *bsoncodec.Registry, val interface{}) error { +func (rv RawValue) UnmarshalWithRegistry(r *Registry, val interface{}) error { if r == nil { return ErrNilRegistry } - vr := bsonrw.NewBSONValueReader(rv.Type, rv.Value) + vr := NewBSONValueReader(rv.Type, rv.Value) rval := reflect.ValueOf(val) if rval.Kind() != reflect.Ptr { return fmt.Errorf("argument to Unmarshal* must be a pointer to a type, but got %v", rval) @@ -85,17 +81,17 @@ func (rv RawValue) UnmarshalWithRegistry(r *bsoncodec.Registry, val interface{}) if err != nil { return err } - return dec.DecodeValue(bsoncodec.DecodeContext{Registry: r}, vr, rval) + return dec.DecodeValue(DecodeContext{Registry: r}, vr, rval) } // 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 *bsoncodec.DecodeContext, val interface{}) error { +func (rv RawValue) UnmarshalWithContext(dc *DecodeContext, val interface{}) error { if dc == nil { return ErrNilContext } - vr := bsonrw.NewBSONValueReader(rv.Type, rv.Value) + vr := NewBSONValueReader(rv.Type, rv.Value) rval := reflect.ValueOf(val) if rval.Kind() != reflect.Ptr { return fmt.Errorf("argument to Unmarshal* must be a pointer to a type, but got %v", rval) @@ -108,9 +104,11 @@ func (rv RawValue) UnmarshalWithContext(dc *bsoncodec.DecodeContext, val interfa return dec.DecodeValue(*dc, vr, rval) } -func convertFromCoreValue(v bsoncore.Value) RawValue { return RawValue{Type: v.Type, Value: v.Data} } +func convertFromCoreValue(v bsoncore.Value) RawValue { + return RawValue{Type: Type(v.Type), Value: v.Data} +} func convertToCoreValue(v RawValue) bsoncore.Value { - return bsoncore.Value{Type: v.Type, Data: v.Value} + return bsoncore.Value{Type: bsoncore.Type(v.Type), Data: v.Value} } // Validate ensures the value is a valid BSON value. @@ -128,14 +126,14 @@ func (rv RawValue) String() string { return convertToCoreValue(rv).String() } func (rv RawValue) DebugString() string { return convertToCoreValue(rv).DebugString() } // Double returns the float64 value for this element. -// It panics if e's BSON type is not bsontype.Double. +// It panics if e's BSON type is not bson.TypeDouble. func (rv RawValue) Double() float64 { return convertToCoreValue(rv).Double() } // DoubleOK is the same as Double, but returns a boolean instead of panicking. func (rv RawValue) DoubleOK() (float64, bool) { return convertToCoreValue(rv).DoubleOK() } // StringValue returns the string value for this element. -// It panics if e's BSON type is not bsontype.String. +// It panics if e's BSON type is not bson.TypeString. // // NOTE: This method is called StringValue to avoid a collision with the String method which // implements the fmt.Stringer interface. @@ -179,11 +177,11 @@ func (rv RawValue) BinaryOK() (subtype byte, data []byte, ok bool) { // ObjectID returns the BSON objectid value the Value represents. It panics if the value is a BSON // type other than objectid. -func (rv RawValue) ObjectID() primitive.ObjectID { return convertToCoreValue(rv).ObjectID() } +func (rv RawValue) ObjectID() ObjectID { return convertToCoreValue(rv).ObjectID() } // ObjectIDOK is the same as ObjectID, except it returns a boolean instead of // panicking. -func (rv RawValue) ObjectIDOK() (primitive.ObjectID, bool) { +func (rv RawValue) ObjectIDOK() (ObjectID, bool) { return convertToCoreValue(rv).ObjectIDOK() } @@ -223,13 +221,13 @@ func (rv RawValue) RegexOK() (pattern, options string, ok bool) { // DBPointer returns the BSON dbpointer value the Value represents. It panics if the value is a BSON // type other than DBPointer. -func (rv RawValue) DBPointer() (string, primitive.ObjectID) { +func (rv RawValue) DBPointer() (string, ObjectID) { return convertToCoreValue(rv).DBPointer() } // DBPointerOK is the same as DBPoitner, except that it returns a boolean // instead of panicking. -func (rv RawValue) DBPointerOK() (string, primitive.ObjectID, bool) { +func (rv RawValue) DBPointerOK() (string, ObjectID, bool) { return convertToCoreValue(rv).DBPointerOK() } @@ -297,10 +295,11 @@ func (rv RawValue) AsInt64OK() (int64, bool) { return convertToCoreValue(rv).AsI // Decimal128 returns the decimal the Value represents. It panics if the value is a BSON type other than // decimal. -func (rv RawValue) Decimal128() primitive.Decimal128 { return convertToCoreValue(rv).Decimal128() } +func (rv RawValue) Decimal128() Decimal128 { return NewDecimal128(convertToCoreValue(rv).Decimal128()) } // Decimal128OK is the same as Decimal128, except that it returns a boolean // instead of panicking. -func (rv RawValue) Decimal128OK() (primitive.Decimal128, bool) { - return convertToCoreValue(rv).Decimal128OK() +func (rv RawValue) Decimal128OK() (Decimal128, bool) { + h, l, ok := convertToCoreValue(rv).Decimal128OK() + return NewDecimal128(h, l), ok } diff --git a/bson/raw_value_test.go b/bson/raw_value_test.go index f6081ef489..f02fe8f326 100644 --- a/bson/raw_value_test.go +++ b/bson/raw_value_test.go @@ -12,8 +12,6 @@ import ( "reflect" "testing" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -27,12 +25,12 @@ func TestRawValue(t *testing.T) { t.Run("Uses registry attached to value", func(t *testing.T) { t.Parallel() - reg := bsoncodec.NewRegistry() - val := RawValue{Type: bsontype.String, Value: bsoncore.AppendString(nil, "foobar"), r: reg} + reg := newTestRegistryBuilder().Build() + val := RawValue{Type: TypeString, Value: bsoncore.AppendString(nil, "foobar"), r: reg} var s string - want := bsoncodec.ErrNoDecoder{Type: reflect.TypeOf(s)} + want := ErrNoDecoder{Type: reflect.TypeOf(s)} got := val.Unmarshal(&s) - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Expected errors to match. got %v; want %v", got, want) } }) @@ -40,7 +38,7 @@ func TestRawValue(t *testing.T) { t.Parallel() want := "foobar" - val := RawValue{Type: bsontype.String, Value: bsoncore.AppendString(nil, want)} + val := RawValue{Type: TypeString, Value: bsoncore.AppendString(nil, want)} var got string err := val.Unmarshal(&got) noerr(t, err) @@ -65,12 +63,12 @@ func TestRawValue(t *testing.T) { t.Run("Returns lookup error", func(t *testing.T) { t.Parallel() - reg := bsoncodec.NewRegistry() + reg := newTestRegistryBuilder().Build() var val RawValue var s string - want := bsoncodec.ErrNoDecoder{Type: reflect.TypeOf(s)} + want := ErrNoDecoder{Type: reflect.TypeOf(s)} got := val.UnmarshalWithRegistry(reg, &s) - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Expected errors to match. got %v; want %v", got, want) } }) @@ -78,11 +76,11 @@ func TestRawValue(t *testing.T) { t.Parallel() reg := NewRegistry() - val := RawValue{Type: bsontype.Double, Value: bsoncore.AppendDouble(nil, 3.14159)} + val := RawValue{Type: TypeDouble, Value: bsoncore.AppendDouble(nil, 3.14159)} var s string - want := fmt.Errorf("cannot decode %v into a string type", bsontype.Double) + want := fmt.Errorf("cannot decode %v into a string type", TypeDouble) got := val.UnmarshalWithRegistry(reg, &s) - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Expected errors to match. got %v; want %v", got, want) } }) @@ -91,7 +89,7 @@ func TestRawValue(t *testing.T) { reg := NewRegistry() want := float64(3.14159) - val := RawValue{Type: bsontype.Double, Value: bsoncore.AppendDouble(nil, want)} + val := RawValue{Type: TypeDouble, Value: bsoncore.AppendDouble(nil, want)} var got float64 err := val.UnmarshalWithRegistry(reg, &got) noerr(t, err) @@ -116,33 +114,33 @@ func TestRawValue(t *testing.T) { t.Run("Returns lookup error", func(t *testing.T) { t.Parallel() - dc := bsoncodec.DecodeContext{Registry: bsoncodec.NewRegistry()} + dc := DecodeContext{Registry: newTestRegistryBuilder().Build()} var val RawValue var s string - want := bsoncodec.ErrNoDecoder{Type: reflect.TypeOf(s)} + want := ErrNoDecoder{Type: reflect.TypeOf(s)} got := val.UnmarshalWithContext(&dc, &s) - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Expected errors to match. got %v; want %v", got, want) } }) t.Run("Returns DecodeValue error", func(t *testing.T) { t.Parallel() - dc := bsoncodec.DecodeContext{Registry: NewRegistry()} - val := RawValue{Type: bsontype.Double, Value: bsoncore.AppendDouble(nil, 3.14159)} + dc := DecodeContext{Registry: NewRegistry()} + val := RawValue{Type: TypeDouble, Value: bsoncore.AppendDouble(nil, 3.14159)} var s string - want := fmt.Errorf("cannot decode %v into a string type", bsontype.Double) + want := fmt.Errorf("cannot decode %v into a string type", TypeDouble) got := val.UnmarshalWithContext(&dc, &s) - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Expected errors to match. got %v; want %v", got, want) } }) t.Run("Success", func(t *testing.T) { t.Parallel() - dc := bsoncodec.DecodeContext{Registry: NewRegistry()} + dc := DecodeContext{Registry: NewRegistry()} want := float64(3.14159) - val := RawValue{Type: bsontype.Double, Value: bsoncore.AppendDouble(nil, want)} + val := RawValue{Type: TypeDouble, Value: bsoncore.AppendDouble(nil, want)} var got float64 err := val.UnmarshalWithContext(&dc, &got) noerr(t, err) @@ -183,7 +181,7 @@ func TestRawValue(t *testing.T) { { name: "non-zero type and non-zero value", val: RawValue{ - Type: bsontype.String, + Type: TypeString, Value: bsoncore.AppendString(nil, "foobar"), }, want: false, @@ -191,7 +189,7 @@ func TestRawValue(t *testing.T) { { name: "non-zero type and zero value", val: RawValue{ - Type: bsontype.String, + Type: TypeString, Value: bsoncore.AppendString(nil, "foobar"), }, }, diff --git a/bson/bsonrw/reader.go b/bson/reader.go similarity index 84% rename from bson/bsonrw/reader.go rename to bson/reader.go index 324b10b616..6d7cac48b0 100644 --- a/bson/bsonrw/reader.go +++ b/bson/reader.go @@ -4,12 +4,7 @@ // 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 bsonrw - -import ( - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" -) +package bson // ArrayReader is implemented by types that allow reading values from a BSON // array. @@ -27,7 +22,7 @@ type DocumentReader interface { // is implemented by several types with different underlying representations of // BSON, such as a bson.Document, raw BSON bytes, or extended JSON. type ValueReader interface { - Type() bsontype.Type + Type() Type Skip() error ReadArray() (ArrayReader, error) @@ -35,9 +30,9 @@ type ValueReader interface { ReadBoolean() (bool, error) ReadDocument() (DocumentReader, error) ReadCodeWithScope() (code string, dr DocumentReader, err error) - ReadDBPointer() (ns string, oid primitive.ObjectID, err error) + ReadDBPointer() (ns string, oid ObjectID, err error) ReadDateTime() (int64, error) - ReadDecimal128() (primitive.Decimal128, error) + ReadDecimal128() (Decimal128, error) ReadDouble() (float64, error) ReadInt32() (int32, error) ReadInt64() (int64, error) @@ -45,7 +40,7 @@ type ValueReader interface { ReadMaxKey() error ReadMinKey() error ReadNull() error - ReadObjectID() (primitive.ObjectID, error) + ReadObjectID() (ObjectID, error) ReadRegex() (pattern, options string, err error) ReadString() (string, error) ReadSymbol() (symbol string, err error) @@ -61,5 +56,5 @@ type ValueReader interface { // // Deprecated: BytesReader will not be supported in Go Driver 2.0. type BytesReader interface { - ReadValueBytes(dst []byte) (bsontype.Type, []byte, error) + ReadValueBytes(dst []byte) (Type, []byte, error) } diff --git a/bson/registry.go b/bson/registry.go index b5b0f35687..74b99e93ab 100644 --- a/bson/registry.go +++ b/bson/registry.go @@ -7,29 +7,563 @@ package bson import ( - "go.mongodb.org/mongo-driver/bson/bsoncodec" + "errors" + "fmt" + "reflect" + "sync" ) -// DefaultRegistry is the default bsoncodec.Registry. It contains the default codecs and the +// DefaultRegistry is the default Registry. It contains the default codecs and the // primitive codecs. var DefaultRegistry = NewRegistry() -// NewRegistryBuilder creates a new RegistryBuilder configured with the default encoders and -// decoders from the bsoncodec.DefaultValueEncoders and bsoncodec.DefaultValueDecoders types and the -// PrimitiveCodecs type in this package. +// ErrNilType is returned when nil is passed to either LookupEncoder or LookupDecoder. +// +// Deprecated: ErrNilType will not be supported in Go Driver 2.0. +var ErrNilType = errors.New("cannot perform a decoder lookup on ") + +// ErrNotPointer is returned when a non-pointer type is provided to LookupDecoder. +// +// Deprecated: ErrNotPointer will not be supported in Go Driver 2.0. +var ErrNotPointer = errors.New("non-pointer provided to LookupDecoder") + +// ErrNoEncoder is returned when there wasn't an encoder available for a type. +// +// Deprecated: ErrNoEncoder will not be supported in Go Driver 2.0. +type ErrNoEncoder struct { + Type reflect.Type +} + +func (ene ErrNoEncoder) Error() string { + if ene.Type == nil { + return "no encoder found for " + } + return "no encoder found for " + ene.Type.String() +} + +// ErrNoDecoder is returned when there wasn't a decoder available for a type. +// +// Deprecated: ErrNoDecoder will not be supported in Go Driver 2.0. +type ErrNoDecoder struct { + Type reflect.Type +} + +func (end ErrNoDecoder) Error() string { + return "no decoder found for " + end.Type.String() +} + +// ErrNoTypeMapEntry is returned when there wasn't a type available for the provided BSON type. +// +// Deprecated: ErrNoTypeMapEntry will not be supported in Go Driver 2.0. +type ErrNoTypeMapEntry struct { + Type Type +} + +func (entme ErrNoTypeMapEntry) Error() string { + return "no type map entry found for " + entme.Type.String() +} + +// ErrNotInterface is returned when the provided type is not an interface. +// +// Deprecated: ErrNotInterface will not be supported in Go Driver 2.0. +var ErrNotInterface = errors.New("The provided type is not an interface") + +// A RegistryBuilder is used to build a Registry. This type is not goroutine +// safe. +// +// Deprecated: Use Registry instead. +type RegistryBuilder struct { + registry *Registry +} + +// NewRegistryBuilder creates a new empty RegistryBuilder. // // Deprecated: Use NewRegistry instead. -func NewRegistryBuilder() *bsoncodec.RegistryBuilder { - rb := bsoncodec.NewRegistryBuilder() - bsoncodec.DefaultValueEncoders{}.RegisterDefaultEncoders(rb) - bsoncodec.DefaultValueDecoders{}.RegisterDefaultDecoders(rb) - primitiveCodecs.RegisterPrimitiveCodecs(rb) +func NewRegistryBuilder() *RegistryBuilder { + rb := &RegistryBuilder{ + registry: &Registry{ + typeEncoders: new(typeEncoderCache), + typeDecoders: new(typeDecoderCache), + kindEncoders: new(kindEncoderCache), + kindDecoders: new(kindDecoderCache), + }, + } + DefaultValueEncoders{}.RegisterDefaultEncoders(rb) + DefaultValueDecoders{}.RegisterDefaultDecoders(rb) + PrimitiveCodecs{}.RegisterPrimitiveCodecs(rb) + return rb +} + +// RegisterCodec will register the provided ValueCodec for the provided type. +// +// Deprecated: Use Registry.RegisterTypeEncoder and Registry.RegisterTypeDecoder instead. +func (rb *RegistryBuilder) RegisterCodec(t reflect.Type, codec ValueCodec) *RegistryBuilder { + rb.RegisterTypeEncoder(t, codec) + rb.RegisterTypeDecoder(t, codec) + return rb +} + +// RegisterTypeEncoder will register the provided ValueEncoder for the provided type. +// +// The type will be used directly, so an encoder can be registered for a type and a different encoder can be registered +// for a pointer to that type. +// +// If the given type is an interface, the encoder will be called when marshaling a type that is that interface. It +// will not be called when marshaling a non-interface type that implements the interface. +// +// Deprecated: Use Registry.RegisterTypeEncoder instead. +func (rb *RegistryBuilder) RegisterTypeEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder { + rb.registry.RegisterTypeEncoder(t, enc) + return rb +} + +// RegisterHookEncoder will register an encoder for the provided interface type t. This encoder will be called when +// marshaling a type if the type implements t or a pointer to the type implements t. If the provided type is not +// an interface (i.e. t.Kind() != reflect.Interface), this method will panic. +// +// Deprecated: Use Registry.RegisterInterfaceEncoder instead. +func (rb *RegistryBuilder) RegisterHookEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder { + rb.registry.RegisterInterfaceEncoder(t, enc) + return rb +} + +// RegisterTypeDecoder will register the provided ValueDecoder for the provided type. +// +// The type will be used directly, so a decoder can be registered for a type and a different decoder can be registered +// for a pointer to that type. +// +// If the given type is an interface, the decoder will be called when unmarshaling into a type that is that interface. +// It will not be called when unmarshaling into a non-interface type that implements the interface. +// +// Deprecated: Use Registry.RegisterTypeDecoder instead. +func (rb *RegistryBuilder) RegisterTypeDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder { + rb.registry.RegisterTypeDecoder(t, dec) + return rb +} + +// RegisterHookDecoder will register an decoder for the provided interface type t. This decoder will be called when +// unmarshaling into a type if the type implements t or a pointer to the type implements t. If the provided type is not +// an interface (i.e. t.Kind() != reflect.Interface), this method will panic. +// +// Deprecated: Use Registry.RegisterInterfaceDecoder instead. +func (rb *RegistryBuilder) RegisterHookDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder { + rb.registry.RegisterInterfaceDecoder(t, dec) + return rb +} + +// RegisterEncoder registers the provided type and encoder pair. +// +// Deprecated: Use Registry.RegisterTypeEncoder or Registry.RegisterInterfaceEncoder instead. +func (rb *RegistryBuilder) RegisterEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder { + if t == tEmpty { + rb.registry.RegisterTypeEncoder(t, enc) + return rb + } + switch t.Kind() { + case reflect.Interface: + rb.registry.RegisterInterfaceEncoder(t, enc) + default: + rb.registry.RegisterTypeEncoder(t, enc) + } + return rb +} + +// RegisterDecoder registers the provided type and decoder pair. +// +// Deprecated: Use Registry.RegisterTypeDecoder or Registry.RegisterInterfaceDecoder instead. +func (rb *RegistryBuilder) RegisterDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder { + if t == nil { + rb.registry.RegisterTypeDecoder(t, dec) + return rb + } + if t == tEmpty { + rb.registry.RegisterTypeDecoder(t, dec) + return rb + } + switch t.Kind() { + case reflect.Interface: + rb.registry.RegisterInterfaceDecoder(t, dec) + default: + rb.registry.RegisterTypeDecoder(t, dec) + } return rb } -// NewRegistry creates a new Registry configured with the default encoders and decoders from the -// bsoncodec.DefaultValueEncoders and bsoncodec.DefaultValueDecoders types and the PrimitiveCodecs -// type in this package. -func NewRegistry() *bsoncodec.Registry { +// RegisterDefaultEncoder will register the provided ValueEncoder to the provided +// kind. +// +// Deprecated: Use Registry.RegisterKindEncoder instead. +func (rb *RegistryBuilder) RegisterDefaultEncoder(kind reflect.Kind, enc ValueEncoder) *RegistryBuilder { + rb.registry.RegisterKindEncoder(kind, enc) + return rb +} + +// RegisterDefaultDecoder will register the provided ValueDecoder to the +// provided kind. +// +// Deprecated: Use Registry.RegisterKindDecoder instead. +func (rb *RegistryBuilder) RegisterDefaultDecoder(kind reflect.Kind, dec ValueDecoder) *RegistryBuilder { + rb.registry.RegisterKindDecoder(kind, dec) + return rb +} + +// RegisterTypeMapEntry will register the provided type to the BSON type. The primary usage for this +// mapping is decoding situations where an empty interface is used and a default type needs to be +// created and decoded into. +// +// By default, BSON documents will decode into interface{} values as bson.D. To change the default type for BSON +// documents, a type map entry for TypeEmbeddedDocument should be registered. For example, to force BSON documents +// to decode to bson.Raw, use the following code: +// +// rb.RegisterTypeMapEntry(TypeEmbeddedDocument, reflect.TypeOf(bson.Raw{})) +// +// Deprecated: Use Registry.RegisterTypeMapEntry instead. +func (rb *RegistryBuilder) RegisterTypeMapEntry(bt Type, rt reflect.Type) *RegistryBuilder { + rb.registry.RegisterTypeMapEntry(bt, rt) + return rb +} + +// Build creates a Registry from the current state of this RegistryBuilder. +// +// Deprecated: Use NewRegistry instead. +func (rb *RegistryBuilder) Build() *Registry { + r := &Registry{ + interfaceEncoders: append([]interfaceValueEncoder(nil), rb.registry.interfaceEncoders...), + interfaceDecoders: append([]interfaceValueDecoder(nil), rb.registry.interfaceDecoders...), + typeEncoders: rb.registry.typeEncoders.Clone(), + typeDecoders: rb.registry.typeDecoders.Clone(), + kindEncoders: rb.registry.kindEncoders.Clone(), + kindDecoders: rb.registry.kindDecoders.Clone(), + } + rb.registry.typeMap.Range(func(k, v interface{}) bool { + if k != nil && v != nil { + r.typeMap.Store(k, v) + } + return true + }) + return r +} + +// A Registry is a store for ValueEncoders, ValueDecoders, and a type map. See the Registry type +// documentation for examples of registering various custom encoders and decoders. A Registry can +// have four main types of codecs: +// +// 1. Type encoders/decoders - These can be registered using the RegisterTypeEncoder and +// RegisterTypeDecoder methods. The registered codec will be invoked when encoding/decoding a value +// whose type matches the registered type exactly. +// If the registered type is an interface, the codec will be invoked when encoding or decoding +// values whose type is the interface, but not for values with concrete types that implement the +// interface. +// +// 2. Interface encoders/decoders - These can be registered using the RegisterInterfaceEncoder and +// RegisterInterfaceDecoder methods. These methods only accept interface types and the registered codecs +// will be invoked when encoding or decoding values whose types implement the interface. An example +// of an interface defined by the driver is bson.Marshaler. The driver will call the MarshalBSON method +// for any value whose type implements bson.Marshaler, regardless of the value's concrete type. +// +// 3. Type map entries - This can be used to associate a BSON type with a Go type. These type +// associations are used when decoding into a bson.D/bson.M or a struct field of type interface{}. +// For example, by default, BSON int32 and int64 values decode as Go int32 and int64 instances, +// respectively, when decoding into a bson.D. The following code would change the behavior so these +// values decode as Go int instances instead: +// +// intType := reflect.TypeOf(int(0)) +// registry.RegisterTypeMapEntry(bson.TypeInt32, intType).RegisterTypeMapEntry(bson.TypeInt64, 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 interface encoder/decoder first. These methods should be used to change the +// behavior for all values for a specific kind. +// +// Read [Registry.LookupDecoder] and [Registry.LookupEncoder] for Registry lookup procedure. +type Registry struct { + interfaceEncoders []interfaceValueEncoder + interfaceDecoders []interfaceValueDecoder + typeEncoders *typeEncoderCache + typeDecoders *typeDecoderCache + kindEncoders *kindEncoderCache + kindDecoders *kindDecoderCache + typeMap sync.Map // map[Type]reflect.Type +} + +// NewRegistry creates a new empty Registry. +func NewRegistry() *Registry { return NewRegistryBuilder().Build() } + +// RegisterTypeEncoder registers the provided ValueEncoder for the provided type. +// +// The type will be used as provided, so an encoder can be registered for a type and a different +// encoder can be registered for a pointer to that type. +// +// If the given type is an interface, the encoder will be called when marshaling a type that is +// that interface. It will not be called when marshaling a non-interface type that implements the +// interface. To get the latter behavior, call RegisterHookEncoder instead. +// +// RegisterTypeEncoder should not be called concurrently with any other Registry method. +func (r *Registry) RegisterTypeEncoder(valueType reflect.Type, enc ValueEncoder) { + r.typeEncoders.Store(valueType, enc) +} + +// RegisterTypeDecoder registers the provided ValueDecoder for the provided type. +// +// The type will be used as provided, so a decoder can be registered for a type and a different +// decoder can be registered for a pointer to that type. +// +// If the given type is an interface, the decoder will be called when unmarshaling into a type that +// is that interface. It will not be called when unmarshaling into a non-interface type that +// implements the interface. To get the latter behavior, call RegisterHookDecoder instead. +// +// RegisterTypeDecoder should not be called concurrently with any other Registry method. +func (r *Registry) RegisterTypeDecoder(valueType reflect.Type, dec ValueDecoder) { + r.typeDecoders.Store(valueType, dec) +} + +// RegisterKindEncoder registers the provided ValueEncoder for the provided kind. +// +// Use RegisterKindEncoder to register an encoder for any type with the same underlying kind. For +// example, consider the type MyInt defined as +// +// type MyInt int32 +// +// To define an encoder for MyInt and int32, use RegisterKindEncoder like +// +// reg.RegisterKindEncoder(reflect.Int32, myEncoder) +// +// RegisterKindEncoder should not be called concurrently with any other Registry method. +func (r *Registry) RegisterKindEncoder(kind reflect.Kind, enc ValueEncoder) { + r.kindEncoders.Store(kind, enc) +} + +// RegisterKindDecoder registers the provided ValueDecoder for the provided kind. +// +// Use RegisterKindDecoder to register a decoder for any type with the same underlying kind. For +// example, consider the type MyInt defined as +// +// type MyInt int32 +// +// To define an decoder for MyInt and int32, use RegisterKindDecoder like +// +// reg.RegisterKindDecoder(reflect.Int32, myDecoder) +// +// RegisterKindDecoder should not be called concurrently with any other Registry method. +func (r *Registry) RegisterKindDecoder(kind reflect.Kind, dec ValueDecoder) { + r.kindDecoders.Store(kind, dec) +} + +// RegisterInterfaceEncoder registers an encoder for the provided interface type iface. This encoder will +// be called when marshaling a type if the type implements iface or a pointer to the type +// implements iface. If the provided type is not an interface +// (i.e. iface.Kind() != reflect.Interface), this method will panic. +// +// RegisterInterfaceEncoder should not be called concurrently with any other Registry method. +func (r *Registry) RegisterInterfaceEncoder(iface reflect.Type, enc ValueEncoder) { + if iface.Kind() != reflect.Interface { + panicStr := fmt.Errorf("RegisterInterfaceEncoder expects a type with kind reflect.Interface, "+ + "got type %s with kind %s", iface, iface.Kind()) + panic(panicStr) + } + + for idx, encoder := range r.interfaceEncoders { + if encoder.i == iface { + r.interfaceEncoders[idx].ve = enc + return + } + } + + r.interfaceEncoders = append(r.interfaceEncoders, interfaceValueEncoder{i: iface, ve: enc}) +} + +// RegisterInterfaceDecoder registers an decoder for the provided interface type iface. This decoder will +// be called when unmarshaling into a type if the type implements iface or a pointer to the type +// implements iface. If the provided type is not an interface (i.e. iface.Kind() != reflect.Interface), +// this method will panic. +// +// RegisterInterfaceDecoder should not be called concurrently with any other Registry method. +func (r *Registry) RegisterInterfaceDecoder(iface reflect.Type, dec ValueDecoder) { + if iface.Kind() != reflect.Interface { + panicStr := fmt.Errorf("RegisterInterfaceDecoder expects a type with kind reflect.Interface, "+ + "got type %s with kind %s", iface, iface.Kind()) + panic(panicStr) + } + + for idx, decoder := range r.interfaceDecoders { + if decoder.i == iface { + r.interfaceDecoders[idx].vd = dec + return + } + } + + r.interfaceDecoders = append(r.interfaceDecoders, interfaceValueDecoder{i: iface, vd: dec}) +} + +// RegisterTypeMapEntry will register the provided type to the BSON type. The primary usage for this +// mapping is decoding situations where an empty interface is used and a default type needs to be +// created and decoded into. +// +// By default, BSON documents will decode into interface{} values as bson.D. To change the default type for BSON +// documents, a type map entry for TypeEmbeddedDocument should be registered. For example, to force BSON documents +// to decode to bson.Raw, use the following code: +// +// reg.RegisterTypeMapEntry(TypeEmbeddedDocument, reflect.TypeOf(bson.Raw{})) +func (r *Registry) RegisterTypeMapEntry(bt Type, rt reflect.Type) { + r.typeMap.Store(bt, rt) +} + +// LookupEncoder returns the first matching encoder in the Registry. It uses the following lookup +// order: +// +// 1. An encoder registered for the exact type. If the given type is an interface, an encoder +// registered using RegisterTypeEncoder for that interface will be selected. +// +// 2. An encoder registered using RegisterInterfaceEncoder for an interface implemented by the type +// or by a pointer to the type. If the value matches multiple interfaces (e.g. the type implements +// bson.Marshaler and bson.ValueMarshaler), the first one registered will be selected. +// Note that registries constructed using bson.NewRegistry have driver-defined interfaces registered +// for the bson.Marshaler, bson.ValueMarshaler, and bson.Proxy interfaces, so those will take +// precedence over any new interfaces. +// +// 3. An encoder registered using RegisterKindEncoder for the kind of value. +// +// If no encoder is found, an error of type ErrNoEncoder is returned. LookupEncoder is safe for +// concurrent use by multiple goroutines after all codecs and encoders are registered. +func (r *Registry) LookupEncoder(valueType reflect.Type) (ValueEncoder, error) { + if valueType == nil { + return nil, ErrNoEncoder{Type: valueType} + } + enc, found := r.lookupTypeEncoder(valueType) + if found { + if enc == nil { + return nil, ErrNoEncoder{Type: valueType} + } + return enc, nil + } + + enc, found = r.lookupInterfaceEncoder(valueType, true) + if found { + return r.typeEncoders.LoadOrStore(valueType, enc), nil + } + + if v, ok := r.kindEncoders.Load(valueType.Kind()); ok { + return r.storeTypeEncoder(valueType, v), nil + } + return nil, ErrNoEncoder{Type: valueType} +} + +func (r *Registry) storeTypeEncoder(rt reflect.Type, enc ValueEncoder) ValueEncoder { + return r.typeEncoders.LoadOrStore(rt, enc) +} + +func (r *Registry) lookupTypeEncoder(rt reflect.Type) (ValueEncoder, bool) { + return r.typeEncoders.Load(rt) +} + +func (r *Registry) lookupInterfaceEncoder(valueType reflect.Type, allowAddr bool) (ValueEncoder, bool) { + if valueType == nil { + return nil, false + } + for _, ienc := range r.interfaceEncoders { + if valueType.Implements(ienc.i) { + return ienc.ve, true + } + if allowAddr && valueType.Kind() != reflect.Ptr && reflect.PtrTo(valueType).Implements(ienc.i) { + // if *t implements an interface, this will catch if t implements an interface further + // ahead in interfaceEncoders + defaultEnc, found := r.lookupInterfaceEncoder(valueType, false) + if !found { + defaultEnc, _ = r.kindEncoders.Load(valueType.Kind()) + } + return newCondAddrEncoder(ienc.ve, defaultEnc), true + } + } + return nil, false +} + +// LookupDecoder returns the first matching decoder in the Registry. It uses the following lookup +// order: +// +// 1. A decoder registered for the exact type. If the given type is an interface, a decoder +// registered using RegisterTypeDecoder for that interface will be selected. +// +// 2. A decoder registered using RegisterInterfaceDecoder for an interface implemented by the type or by +// a pointer to the type. If the value matches multiple interfaces (e.g. the type implements +// bson.Unmarshaler and bson.ValueUnmarshaler), the first one registered will be selected. +// Note that registries constructed using bson.NewRegistry have driver-defined interfaces registered +// for the bson.Unmarshaler and bson.ValueUnmarshaler interfaces, so those will take +// precedence over any new interfaces. +// +// 3. A decoder registered using RegisterKindDecoder for the kind of value. +// +// If no decoder is found, an error of type ErrNoDecoder is returned. LookupDecoder is safe for +// concurrent use by multiple goroutines after all codecs and decoders are registered. +func (r *Registry) LookupDecoder(valueType reflect.Type) (ValueDecoder, error) { + if valueType == nil { + return nil, ErrNilType + } + dec, found := r.lookupTypeDecoder(valueType) + if found { + if dec == nil { + return nil, ErrNoDecoder{Type: valueType} + } + return dec, nil + } + + dec, found = r.lookupInterfaceDecoder(valueType, true) + if found { + return r.storeTypeDecoder(valueType, dec), nil + } + + if v, ok := r.kindDecoders.Load(valueType.Kind()); ok { + return r.storeTypeDecoder(valueType, v), nil + } + return nil, ErrNoDecoder{Type: valueType} +} + +func (r *Registry) lookupTypeDecoder(valueType reflect.Type) (ValueDecoder, bool) { + return r.typeDecoders.Load(valueType) +} + +func (r *Registry) storeTypeDecoder(typ reflect.Type, dec ValueDecoder) ValueDecoder { + return r.typeDecoders.LoadOrStore(typ, dec) +} + +func (r *Registry) lookupInterfaceDecoder(valueType reflect.Type, allowAddr bool) (ValueDecoder, bool) { + for _, idec := range r.interfaceDecoders { + if valueType.Implements(idec.i) { + return idec.vd, true + } + if allowAddr && valueType.Kind() != reflect.Ptr && reflect.PtrTo(valueType).Implements(idec.i) { + // if *t implements an interface, this will catch if t implements an interface further + // ahead in interfaceDecoders + defaultDec, found := r.lookupInterfaceDecoder(valueType, false) + if !found { + defaultDec, _ = r.kindDecoders.Load(valueType.Kind()) + } + return newCondAddrDecoder(idec.vd, defaultDec), true + } + } + return nil, false +} + +// LookupTypeMapEntry inspects the registry's type map for a Go type for the corresponding BSON +// type. If no type is found, ErrNoTypeMapEntry is returned. +// +// LookupTypeMapEntry should not be called concurrently with any other Registry method. +func (r *Registry) LookupTypeMapEntry(bt Type) (reflect.Type, error) { + v, ok := r.typeMap.Load(bt) + if v == nil || !ok { + return nil, ErrNoTypeMapEntry{Type: bt} + } + return v.(reflect.Type), nil +} + +type interfaceValueEncoder struct { + i reflect.Type + ve ValueEncoder +} + +type interfaceValueDecoder struct { + i reflect.Type + vd ValueDecoder +} diff --git a/bson/bsoncodec/registry_examples_test.go b/bson/registry_examples_test.go similarity index 88% rename from bson/bsoncodec/registry_examples_test.go rename to bson/registry_examples_test.go index c8b28fb103..39214f1b65 100644 --- a/bson/bsoncodec/registry_examples_test.go +++ b/bson/registry_examples_test.go @@ -4,7 +4,7 @@ // 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_test +package bson_test import ( "bytes" @@ -13,9 +13,6 @@ import ( "reflect" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" ) func ExampleRegistry_customEncoder() { @@ -26,14 +23,14 @@ func ExampleRegistry_customEncoder() { negatedIntType := reflect.TypeOf(negatedInt(0)) negatedIntEncoder := func( - ec bsoncodec.EncodeContext, - vw bsonrw.ValueWriter, + ec bson.EncodeContext, + vw bson.ValueWriter, val reflect.Value, ) error { // All encoder implementations should check that val is valid and is of // the correct type before proceeding. if !val.IsValid() || val.Type() != negatedIntType { - return bsoncodec.ValueEncoderError{ + return bson.ValueEncoderError{ Name: "negatedIntEncoder", Types: []reflect.Type{negatedIntType}, Received: val, @@ -52,7 +49,7 @@ func ExampleRegistry_customEncoder() { reg := bson.NewRegistry() reg.RegisterTypeEncoder( negatedIntType, - bsoncodec.ValueEncoderFunc(negatedIntEncoder)) + bson.ValueEncoderFunc(negatedIntEncoder)) // Define a document that includes both int and negatedInt fields with the // same value. @@ -68,7 +65,7 @@ func ExampleRegistry_customEncoder() { // Marshal the document as BSON. Expect that the int field is encoded to the // same value and that the negatedInt field is encoded as the negated value. buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(reg) err := enc.Encode(doc) @@ -88,14 +85,14 @@ func ExampleRegistry_customDecoder() { lenientBoolType := reflect.TypeOf(lenientBool(true)) lenientBoolDecoder := func( - dc bsoncodec.DecodeContext, - vr bsonrw.ValueReader, + dc bson.DecodeContext, + vr bson.ValueReader, val reflect.Value, ) error { // All decoder implementations should check that val is valid, settable, // and is of the correct kind before proceeding. if !val.IsValid() || !val.CanSet() || val.Type() != lenientBoolType { - return bsoncodec.ValueDecoderError{ + return bson.ValueDecoderError{ Name: "lenientBoolDecoder", Types: []reflect.Type{lenientBoolType}, Received: val, @@ -104,19 +101,19 @@ func ExampleRegistry_customDecoder() { var result bool switch vr.Type() { - case bsontype.Boolean: + case bson.TypeBoolean: b, err := vr.ReadBoolean() if err != nil { return err } result = b - case bsontype.Int32: + case bson.TypeInt32: i32, err := vr.ReadInt32() if err != nil { return err } result = i32 != 0 - case bsontype.Int64: + case bson.TypeInt64: i64, err := vr.ReadInt64() if err != nil { return err @@ -135,7 +132,7 @@ func ExampleRegistry_customDecoder() { reg := bson.NewRegistry() reg.RegisterTypeDecoder( lenientBoolType, - bsoncodec.ValueDecoderFunc(lenientBoolDecoder)) + bson.ValueDecoderFunc(lenientBoolDecoder)) // Marshal a BSON document with a single field "isOK" that is a non-zero // integer value. @@ -165,14 +162,14 @@ func ExampleRegistry_RegisterKindEncoder() { // encoder for kind reflect.Int32. That way, even user-defined types with // underlying type int32 will be encoded as a BSON int64. int32To64Encoder := func( - ec bsoncodec.EncodeContext, - vw bsonrw.ValueWriter, + ec bson.EncodeContext, + vw bson.ValueWriter, val reflect.Value, ) error { // All encoder implementations should check that val is valid and is of // the correct type or kind before proceeding. if !val.IsValid() || val.Kind() != reflect.Int32 { - return bsoncodec.ValueEncoderError{ + return bson.ValueEncoderError{ Name: "int32To64Encoder", Kinds: []reflect.Kind{reflect.Int32}, Received: val, @@ -187,7 +184,7 @@ func ExampleRegistry_RegisterKindEncoder() { reg := bson.NewRegistry() reg.RegisterKindEncoder( reflect.Int32, - bsoncodec.ValueEncoderFunc(int32To64Encoder)) + bson.ValueEncoderFunc(int32To64Encoder)) // Define a document that includes an int32, an int64, and a user-defined // type "myInt" that has underlying type int32. @@ -206,7 +203,7 @@ func ExampleRegistry_RegisterKindEncoder() { // Marshal the document as BSON. Expect that all fields are encoded as BSON // int64 (represented as "$numberLong" when encoded as Extended JSON). buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(reg) err := enc.Encode(doc) @@ -224,14 +221,14 @@ func ExampleRegistry_RegisterKindDecoder() { // "kind" decoder for kind reflect.Int64. That way, we can even decode to // user-defined types with underlying type int64. flexibleInt64KindDecoder := func( - dc bsoncodec.DecodeContext, - vr bsonrw.ValueReader, + dc bson.DecodeContext, + vr bson.ValueReader, val reflect.Value, ) error { // All decoder implementations should check that val is valid, settable, // and is of the correct kind before proceeding. if !val.IsValid() || !val.CanSet() || val.Kind() != reflect.Int64 { - return bsoncodec.ValueDecoderError{ + return bson.ValueDecoderError{ Name: "flexibleInt64KindDecoder", Kinds: []reflect.Kind{reflect.Int64}, Received: val, @@ -240,19 +237,19 @@ func ExampleRegistry_RegisterKindDecoder() { var result int64 switch vr.Type() { - case bsontype.Int64: + case bson.TypeInt64: i64, err := vr.ReadInt64() if err != nil { return err } result = i64 - case bsontype.Int32: + case bson.TypeInt32: i32, err := vr.ReadInt32() if err != nil { return err } result = int64(i32) - case bsontype.Double: + case bson.TypeDouble: d, err := vr.ReadDouble() if err != nil { return err @@ -276,7 +273,7 @@ func ExampleRegistry_RegisterKindDecoder() { reg := bson.NewRegistry() reg.RegisterKindDecoder( reflect.Int64, - bsoncodec.ValueDecoderFunc(flexibleInt64KindDecoder)) + bson.ValueDecoderFunc(flexibleInt64KindDecoder)) // Marshal a BSON document with fields that are mixed numeric types but all // hold integer values (i.e. values with no fractional part). diff --git a/bson/bsoncodec/registry_test.go b/bson/registry_test.go similarity index 92% rename from bson/bsoncodec/registry_test.go rename to bson/registry_test.go index 03500dca44..2bc87364d3 100644 --- a/bson/bsoncodec/registry_test.go +++ b/bson/registry_test.go @@ -4,7 +4,7 @@ // 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 +package bson import ( "errors" @@ -12,11 +12,21 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/assert" ) +// newTestRegistryBuilder creates a new empty Registry. +func newTestRegistryBuilder() *RegistryBuilder { + return &RegistryBuilder{ + registry: &Registry{ + typeEncoders: new(typeEncoderCache), + typeDecoders: new(typeDecoderCache), + kindEncoders: new(kindEncoderCache), + kindDecoders: new(kindDecoderCache), + }, + } +} + func TestRegistryBuilder(t *testing.T) { t.Run("Register", func(t *testing.T) { fc1, fc2, fc3, fc4 := new(fakeCodec), new(fakeCodec), new(fakeCodec), new(fakeCodec) @@ -35,7 +45,7 @@ func TestRegistryBuilder(t *testing.T) { {i: reflect.TypeOf(t2f).Elem(), ve: fc2}, {i: reflect.TypeOf(t4f).Elem(), ve: fc4}, } - rb := NewRegistryBuilder() + rb := newTestRegistryBuilder() for _, ip := range ips { rb.RegisterHookEncoder(ip.i, ip.ve) } @@ -48,7 +58,7 @@ func TestRegistryBuilder(t *testing.T) { }) t.Run("type", func(t *testing.T) { ft1, ft2, ft4 := fakeType1{}, fakeType2{}, fakeType4{} - rb := NewRegistryBuilder(). + rb := newTestRegistryBuilder(). RegisterTypeEncoder(reflect.TypeOf(ft1), fc1). RegisterTypeEncoder(reflect.TypeOf(ft2), fc2). RegisterTypeEncoder(reflect.TypeOf(ft1), fc3). @@ -77,7 +87,7 @@ func TestRegistryBuilder(t *testing.T) { }) t.Run("kind", func(t *testing.T) { k1, k2, k4 := reflect.Struct, reflect.Slice, reflect.Map - rb := NewRegistryBuilder(). + rb := newTestRegistryBuilder(). RegisterDefaultEncoder(k1, fc1). RegisterDefaultEncoder(k2, fc2). RegisterDefaultEncoder(k1, fc3). @@ -108,7 +118,7 @@ func TestRegistryBuilder(t *testing.T) { t.Run("MapCodec", func(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - rb := NewRegistryBuilder() + rb := newTestRegistryBuilder() rb.RegisterDefaultEncoder(reflect.Map, codec) reg := rb.Build() @@ -125,7 +135,7 @@ func TestRegistryBuilder(t *testing.T) { t.Run("StructCodec", func(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - rb := NewRegistryBuilder() + rb := newTestRegistryBuilder() rb.RegisterDefaultEncoder(reflect.Struct, codec) reg := rb.Build() @@ -142,7 +152,7 @@ func TestRegistryBuilder(t *testing.T) { t.Run("SliceCodec", func(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - rb := NewRegistryBuilder() + rb := newTestRegistryBuilder() rb.RegisterDefaultEncoder(reflect.Slice, codec) reg := rb.Build() @@ -159,7 +169,7 @@ func TestRegistryBuilder(t *testing.T) { t.Run("ArrayCodec", func(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - rb := NewRegistryBuilder() + rb := newTestRegistryBuilder() rb.RegisterDefaultEncoder(reflect.Array, codec) reg := rb.Build() @@ -201,7 +211,7 @@ func TestRegistryBuilder(t *testing.T) { pc = NewPointerCodec() ) - reg := NewRegistryBuilder(). + reg := newTestRegistryBuilder(). RegisterTypeEncoder(ft1, fc1). RegisterTypeEncoder(ft2, fc2). RegisterTypeEncoder(ti1, fc1). @@ -343,7 +353,7 @@ func TestRegistryBuilder(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Run("Encoder", func(t *testing.T) { gotcodec, goterr := reg.LookupEncoder(tc.t) - if !cmp.Equal(goterr, tc.wanterr, cmp.Comparer(compareErrors)) { + if !cmp.Equal(goterr, tc.wanterr, cmp.Comparer(assert.CompareErrors)) { t.Errorf("errors did not match: got %#v, want %#v", goterr, tc.wanterr) } if !cmp.Equal(gotcodec, tc.wantcodec, allowunexported, cmp.Comparer(comparepc)) { @@ -357,7 +367,7 @@ func TestRegistryBuilder(t *testing.T) { } gotcodec, goterr := reg.LookupDecoder(tc.t) - if !cmp.Equal(goterr, wanterr, cmp.Comparer(compareErrors)) { + if !cmp.Equal(goterr, wanterr, cmp.Comparer(assert.CompareErrors)) { t.Errorf("errors did not match: got %#v, want %#v", goterr, wanterr) } if !cmp.Equal(gotcodec, tc.wantcodec, allowunexported, cmp.Comparer(comparepc)) { @@ -399,30 +409,30 @@ func TestRegistryBuilder(t *testing.T) { }) }) t.Run("Type Map", func(t *testing.T) { - reg := NewRegistryBuilder(). - RegisterTypeMapEntry(bsontype.String, reflect.TypeOf("")). - RegisterTypeMapEntry(bsontype.Int32, reflect.TypeOf(int(0))). + reg := newTestRegistryBuilder(). + RegisterTypeMapEntry(TypeString, reflect.TypeOf("")). + RegisterTypeMapEntry(TypeInt32, reflect.TypeOf(int(0))). Build() var got, want reflect.Type want = reflect.TypeOf("") - got, err := reg.LookupTypeMapEntry(bsontype.String) + got, err := reg.LookupTypeMapEntry(TypeString) noerr(t, err) if got != want { t.Errorf("unexpected type: got %#v, want %#v", got, want) } want = reflect.TypeOf(int(0)) - got, err = reg.LookupTypeMapEntry(bsontype.Int32) + got, err = reg.LookupTypeMapEntry(TypeInt32) noerr(t, err) if got != want { t.Errorf("unexpected type: got %#v, want %#v", got, want) } want = nil - wanterr := ErrNoTypeMapEntry{Type: bsontype.ObjectID} - got, err = reg.LookupTypeMapEntry(bsontype.ObjectID) + wanterr := ErrNoTypeMapEntry{Type: TypeObjectID} + got, err = reg.LookupTypeMapEntry(TypeObjectID) if !errors.Is(err, wanterr) { t.Errorf("did not get expected error: got %#v, want %#v", err, wanterr) } @@ -456,7 +466,7 @@ func TestRegistry(t *testing.T) { {i: reflect.TypeOf(t2f).Elem(), ve: fc2}, {i: reflect.TypeOf(t4f).Elem(), ve: fc4}, } - reg := NewRegistry() + reg := newTestRegistryBuilder().Build() for _, ip := range ips { reg.RegisterInterfaceEncoder(ip.i, ip.ve) } @@ -469,7 +479,7 @@ func TestRegistry(t *testing.T) { t.Parallel() ft1, ft2, ft4 := fakeType1{}, fakeType2{}, fakeType4{} - reg := NewRegistry() + reg := newTestRegistryBuilder().Build() reg.RegisterTypeEncoder(reflect.TypeOf(ft1), fc1) reg.RegisterTypeEncoder(reflect.TypeOf(ft2), fc2) reg.RegisterTypeEncoder(reflect.TypeOf(ft1), fc3) @@ -499,7 +509,7 @@ func TestRegistry(t *testing.T) { t.Parallel() k1, k2, k4 := reflect.Struct, reflect.Slice, reflect.Map - reg := NewRegistry() + reg := newTestRegistryBuilder().Build() reg.RegisterKindEncoder(k1, fc1) reg.RegisterKindEncoder(k2, fc2) reg.RegisterKindEncoder(k1, fc3) @@ -533,7 +543,7 @@ func TestRegistry(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - reg := NewRegistry() + reg := newTestRegistryBuilder().Build() reg.RegisterKindEncoder(reflect.Map, codec) if reg.kindEncoders.get(reflect.Map) != codec { t.Errorf("map codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Map), codec) @@ -548,7 +558,7 @@ func TestRegistry(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - reg := NewRegistry() + reg := newTestRegistryBuilder().Build() reg.RegisterKindEncoder(reflect.Struct, codec) if reg.kindEncoders.get(reflect.Struct) != codec { t.Errorf("struct codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Struct), codec) @@ -563,7 +573,7 @@ func TestRegistry(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - reg := NewRegistry() + reg := newTestRegistryBuilder().Build() reg.RegisterKindEncoder(reflect.Slice, codec) if reg.kindEncoders.get(reflect.Slice) != codec { t.Errorf("slice codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Slice), codec) @@ -578,7 +588,7 @@ func TestRegistry(t *testing.T) { codec := &fakeCodec{num: 1} codec2 := &fakeCodec{num: 2} - reg := NewRegistry() + reg := newTestRegistryBuilder().Build() reg.RegisterKindEncoder(reflect.Array, codec) if reg.kindEncoders.get(reflect.Array) != codec { t.Errorf("slice codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Array), codec) @@ -618,7 +628,7 @@ func TestRegistry(t *testing.T) { pc = NewPointerCodec() ) - reg := NewRegistry() + reg := newTestRegistryBuilder().Build() reg.RegisterTypeEncoder(ft1, fc1) reg.RegisterTypeEncoder(ft2, fc2) reg.RegisterTypeEncoder(ti1, fc1) @@ -765,7 +775,7 @@ func TestRegistry(t *testing.T) { t.Parallel() gotcodec, goterr := reg.LookupEncoder(tc.t) - if !cmp.Equal(goterr, tc.wanterr, cmp.Comparer(compareErrors)) { + if !cmp.Equal(goterr, tc.wanterr, cmp.Comparer(assert.CompareErrors)) { t.Errorf("errors did not match: got %#v, want %#v", goterr, tc.wanterr) } if !cmp.Equal(gotcodec, tc.wantcodec, allowunexported, cmp.Comparer(comparepc)) { @@ -781,7 +791,7 @@ func TestRegistry(t *testing.T) { } gotcodec, goterr := reg.LookupDecoder(tc.t) - if !cmp.Equal(goterr, wanterr, cmp.Comparer(compareErrors)) { + if !cmp.Equal(goterr, wanterr, cmp.Comparer(assert.CompareErrors)) { t.Errorf("errors did not match: got %#v, want %#v", goterr, wanterr) } if !cmp.Equal(gotcodec, tc.wantcodec, allowunexported, cmp.Comparer(comparepc)) { @@ -799,7 +809,7 @@ func TestRegistry(t *testing.T) { wanterr := ErrNoEncoder{Type: reflect.TypeOf(nil)} gotcodec, goterr := reg.LookupEncoder(nil) - if !cmp.Equal(goterr, wanterr, cmp.Comparer(compareErrors)) { + if !cmp.Equal(goterr, wanterr, cmp.Comparer(assert.CompareErrors)) { t.Errorf("errors did not match: got %#v, want %#v", goterr, wanterr) } if !cmp.Equal(gotcodec, nil, allowunexported, cmp.Comparer(comparepc)) { @@ -812,7 +822,7 @@ func TestRegistry(t *testing.T) { wanterr := ErrNilType gotcodec, goterr := reg.LookupDecoder(nil) - if !cmp.Equal(goterr, wanterr, cmp.Comparer(compareErrors)) { + if !cmp.Equal(goterr, wanterr, cmp.Comparer(assert.CompareErrors)) { t.Errorf("errors did not match: got %#v, want %#v", goterr, wanterr) } if !cmp.Equal(gotcodec, nil, allowunexported, cmp.Comparer(comparepc)) { @@ -859,29 +869,29 @@ func TestRegistry(t *testing.T) { }) t.Run("Type Map", func(t *testing.T) { t.Parallel() - reg := NewRegistry() - reg.RegisterTypeMapEntry(bsontype.String, reflect.TypeOf("")) - reg.RegisterTypeMapEntry(bsontype.Int32, reflect.TypeOf(int(0))) + reg := newTestRegistryBuilder().Build() + reg.RegisterTypeMapEntry(TypeString, reflect.TypeOf("")) + reg.RegisterTypeMapEntry(TypeInt32, reflect.TypeOf(int(0))) var got, want reflect.Type want = reflect.TypeOf("") - got, err := reg.LookupTypeMapEntry(bsontype.String) + got, err := reg.LookupTypeMapEntry(TypeString) noerr(t, err) if got != want { t.Errorf("unexpected type: got %#v, want %#v", got, want) } want = reflect.TypeOf(int(0)) - got, err = reg.LookupTypeMapEntry(bsontype.Int32) + got, err = reg.LookupTypeMapEntry(TypeInt32) noerr(t, err) if got != want { t.Errorf("unexpected type: got %#v, want %#v", got, want) } want = nil - wanterr := ErrNoTypeMapEntry{Type: bsontype.ObjectID} - got, err = reg.LookupTypeMapEntry(bsontype.ObjectID) + wanterr := ErrNoTypeMapEntry{Type: TypeObjectID} + got, err = reg.LookupTypeMapEntry(TypeObjectID) if !errors.Is(err, wanterr) { t.Errorf("unexpected error: got %#v, want %#v", err, wanterr) } @@ -953,10 +963,10 @@ type fakeCodec struct { num int } -func (*fakeCodec) EncodeValue(EncodeContext, bsonrw.ValueWriter, reflect.Value) error { +func (*fakeCodec) EncodeValue(EncodeContext, ValueWriter, reflect.Value) error { return nil } -func (*fakeCodec) DecodeValue(DecodeContext, bsonrw.ValueReader, reflect.Value) error { +func (*fakeCodec) DecodeValue(DecodeContext, ValueReader, reflect.Value) error { return nil } diff --git a/bson/bsoncodec/slice_codec.go b/bson/slice_codec.go similarity index 83% rename from bson/bsoncodec/slice_codec.go rename to bson/slice_codec.go index 0ffd92d92b..52449239b9 100644 --- a/bson/bsoncodec/slice_codec.go +++ b/bson/slice_codec.go @@ -4,7 +4,7 @@ // 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 +package bson import ( "errors" @@ -12,9 +12,6 @@ import ( "reflect" "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" ) var defaultSliceCodec = NewSliceCodec() @@ -46,7 +43,7 @@ func NewSliceCodec(opts ...*bsonoptions.SliceCodecOptions) *SliceCodec { } // EncodeValue is the ValueEncoder for slice types. -func (sc SliceCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (sc SliceCodec) EncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Kind() != reflect.Slice { return ValueEncoderError{Name: "SliceEncodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val} } @@ -62,9 +59,9 @@ func (sc SliceCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val re return vw.WriteBinary(byteSlice) } - // If we have a []primitive.E we want to treat it as a document instead of as an array. + // If we have a []E we want to treat it as a document instead of as an array. if val.Type() == tD || val.Type().ConvertibleTo(tD) { - d := val.Convert(tD).Interface().(primitive.D) + d := val.Convert(tD).Interface().(D) dw, err := vw.WriteDocument() if err != nil { @@ -120,24 +117,24 @@ func (sc SliceCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val re } // DecodeValue is the ValueDecoder for slice types. -func (sc *SliceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (sc *SliceCodec) DecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Kind() != reflect.Slice { return ValueDecoderError{Name: "SliceDecodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val} } switch vrType := vr.Type(); vrType { - case bsontype.Array: - case bsontype.Null: + case TypeArray: + case TypeNull: val.Set(reflect.Zero(val.Type())) return vr.ReadNull() - case bsontype.Undefined: + case TypeUndefined: val.Set(reflect.Zero(val.Type())) return vr.ReadUndefined() - case bsontype.Type(0), bsontype.EmbeddedDocument: + case Type(0), TypeEmbeddedDocument: if val.Type().Elem() != tE { return fmt.Errorf("cannot decode document into %s", val.Type()) } - case bsontype.Binary: + case TypeBinary: if val.Type().Elem() != tByte { return fmt.Errorf("SliceDecodeValue can only decode a binary into a byte array, got %v", vrType) } @@ -145,8 +142,8 @@ func (sc *SliceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val r if err != nil { return 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) + if subtype != TypeBinaryGeneric && subtype != TypeBinaryBinaryOld { + return fmt.Errorf("SliceDecodeValue can only be used to decode subtype 0x00 or 0x02 for %s, got %v", TypeBinary, subtype) } if val.IsNil() { @@ -155,7 +152,7 @@ func (sc *SliceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val r val.SetLen(0) val.Set(reflect.AppendSlice(val, reflect.ValueOf(data))) return nil - case bsontype.String: + case TypeString: if sliceType := val.Type().Elem(); sliceType != tByte { return fmt.Errorf("SliceDecodeValue can only decode a string into a byte array, got %v", sliceType) } @@ -175,7 +172,7 @@ func (sc *SliceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val r return fmt.Errorf("cannot decode %v into a slice", vrType) } - var elemsFunc func(DecodeContext, bsonrw.ValueReader, reflect.Value) ([]reflect.Value, error) + var elemsFunc func(DecodeContext, ValueReader, reflect.Value) ([]reflect.Value, error) switch val.Type().Elem() { case tE: dc.Ancestor = val.Type() diff --git a/bson/bsoncodec/string_codec.go b/bson/string_codec.go similarity index 83% rename from bson/bsoncodec/string_codec.go rename to bson/string_codec.go index ff931b7253..50fb9229fe 100644 --- a/bson/bsoncodec/string_codec.go +++ b/bson/string_codec.go @@ -4,15 +4,13 @@ // 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 +package bson import ( "fmt" "reflect" "go.mongodb.org/mongo-driver/bson/bsonoptions" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" ) // StringCodec is the Codec used for string values. @@ -46,7 +44,7 @@ func NewStringCodec(opts ...*bsonoptions.StringCodecOptions) *StringCodec { } // EncodeValue is the ValueEncoder for string types. -func (sc *StringCodec) EncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (sc *StringCodec) EncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if val.Kind() != reflect.String { return ValueEncoderError{ Name: "StringEncodeValue", @@ -58,7 +56,7 @@ func (sc *StringCodec) EncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val r return vw.WriteString(val.String()) } -func (sc *StringCodec) decodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (sc *StringCodec) decodeType(_ DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t.Kind() != reflect.String { return emptyValue, ValueDecoderError{ Name: "StringDecodeValue", @@ -70,12 +68,12 @@ func (sc *StringCodec) decodeType(_ DecodeContext, vr bsonrw.ValueReader, t refl var str string var err error switch vr.Type() { - case bsontype.String: + case TypeString: str, err = vr.ReadString() if err != nil { return emptyValue, err } - case bsontype.ObjectID: + case TypeObjectID: oid, err := vr.ReadObjectID() if err != nil { return emptyValue, err @@ -87,25 +85,25 @@ func (sc *StringCodec) decodeType(_ DecodeContext, vr bsonrw.ValueReader, t refl byteArray := [12]byte(oid) str = string(byteArray[:]) } - case bsontype.Symbol: + case TypeSymbol: str, err = vr.ReadSymbol() if err != nil { return emptyValue, err } - case bsontype.Binary: + case TypeBinary: data, subtype, err := vr.ReadBinary() if err != nil { return emptyValue, err } - if subtype != bsontype.BinaryGeneric && subtype != bsontype.BinaryBinaryOld { + if subtype != TypeBinaryGeneric && subtype != TypeBinaryBinaryOld { return emptyValue, decodeBinaryError{subtype: subtype, typeName: "string"} } str = string(data) - case bsontype.Null: + case TypeNull: if err = vr.ReadNull(); err != nil { return emptyValue, err } - case bsontype.Undefined: + case TypeUndefined: if err = vr.ReadUndefined(); err != nil { return emptyValue, err } @@ -117,7 +115,7 @@ func (sc *StringCodec) decodeType(_ DecodeContext, vr bsonrw.ValueReader, t refl } // DecodeValue is the ValueDecoder for string types. -func (sc *StringCodec) DecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (sc *StringCodec) DecodeValue(dctx DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Kind() != reflect.String { return ValueDecoderError{Name: "StringDecodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val} } diff --git a/bson/bsoncodec/string_codec_test.go b/bson/string_codec_test.go similarity index 82% rename from bson/bsoncodec/string_codec_test.go rename to bson/string_codec_test.go index 4e544f4727..75ace60c5d 100644 --- a/bson/bsoncodec/string_codec_test.go +++ b/bson/string_codec_test.go @@ -4,24 +4,21 @@ // 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 +package bson import ( "reflect" "testing" "go.mongodb.org/mongo-driver/bson/bsonoptions" - "go.mongodb.org/mongo-driver/bson/bsonrw/bsonrwtest" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/assert" ) func TestStringCodec(t *testing.T) { t.Run("ObjectIDAsHex", func(t *testing.T) { - oid := primitive.NewObjectID() + oid := NewObjectID() byteArray := [12]byte(oid) - reader := &bsonrwtest.ValueReaderWriter{BSONType: bsontype.ObjectID, Return: oid} + reader := &valueReaderWriter{BSONType: TypeObjectID, Return: oid} testCases := []struct { name string opts *bsonoptions.StringCodecOptions diff --git a/bson/bsoncodec/struct_codec.go b/bson/struct_codec.go similarity index 96% rename from bson/bsoncodec/struct_codec.go rename to bson/struct_codec.go index bbf6378ff5..917ac17bfd 100644 --- a/bson/bsoncodec/struct_codec.go +++ b/bson/struct_codec.go @@ -4,7 +4,7 @@ // 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 +package bson import ( "errors" @@ -16,8 +16,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson/bsonoptions" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" ) // DecodeError represents an error that occurs when unmarshalling BSON bytes into a native Go type. @@ -51,13 +49,6 @@ func (de *DecodeError) Keys() []string { return reversedKeys } -// Zeroer allows custom struct types to implement a report of zero -// state. All struct types that don't implement Zeroer or where IsZero -// returns false are considered to be not zero. -type Zeroer interface { - IsZero() bool -} - // StructCodec is the Codec used for struct values. // // Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with the @@ -137,7 +128,7 @@ func NewStructCodec(p StructTagParser, opts ...*bsonoptions.StructCodecOptions) } // EncodeValue handles encoding generic struct types. -func (sc *StructCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (sc *StructCodec) EncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Kind() != reflect.Struct { return ValueEncoderError{Name: "StructCodec.EncodeValue", Kinds: []reflect.Kind{reflect.Struct}, Received: val} } @@ -254,21 +245,21 @@ func newDecodeError(key string, original error) error { // DecodeValue implements the Codec interface. // By default, map types in val will not be cleared. If a map has existing key/value pairs, it will be extended with the new ones from vr. // For slices, the decoder will set the length of the slice to zero and append all elements. The underlying array will not be cleared. -func (sc *StructCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (sc *StructCodec) DecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Kind() != reflect.Struct { return ValueDecoderError{Name: "StructCodec.DecodeValue", Kinds: []reflect.Kind{reflect.Struct}, Received: val} } switch vrType := vr.Type(); vrType { - case bsontype.Type(0), bsontype.EmbeddedDocument: - case bsontype.Null: + case Type(0), TypeEmbeddedDocument: + case TypeNull: if err := vr.ReadNull(); err != nil { return err } val.Set(reflect.Zero(val.Type())) return nil - case bsontype.Undefined: + case TypeUndefined: if err := vr.ReadUndefined(); err != nil { return err } @@ -308,7 +299,7 @@ func (sc *StructCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val for { name, vr, err := dr.ReadElement() - if errors.Is(err, bsonrw.ErrEOD) { + if errors.Is(err, ErrEOD) { break } if err != nil { diff --git a/bson/bsoncodec/struct_codec_test.go b/bson/struct_codec_test.go similarity index 99% rename from bson/bsoncodec/struct_codec_test.go rename to bson/struct_codec_test.go index f42b9a53ef..d1f7e5373a 100644 --- a/bson/bsoncodec/struct_codec_test.go +++ b/bson/struct_codec_test.go @@ -4,7 +4,7 @@ // 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 +package bson import ( "reflect" diff --git a/bson/bsoncodec/struct_tag_parser.go b/bson/struct_tag_parser.go similarity index 99% rename from bson/bsoncodec/struct_tag_parser.go rename to bson/struct_tag_parser.go index 18d85bfb03..d116c14040 100644 --- a/bson/bsoncodec/struct_tag_parser.go +++ b/bson/struct_tag_parser.go @@ -4,7 +4,7 @@ // 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 +package bson import ( "reflect" diff --git a/bson/bsoncodec/struct_tag_parser_test.go b/bson/struct_tag_parser_test.go similarity index 99% rename from bson/bsoncodec/struct_tag_parser_test.go rename to bson/struct_tag_parser_test.go index c60d8f95a3..b03815488a 100644 --- a/bson/bsoncodec/struct_tag_parser_test.go +++ b/bson/struct_tag_parser_test.go @@ -4,7 +4,7 @@ // 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 +package bson import ( "reflect" diff --git a/bson/bsoncodec/time_codec.go b/bson/time_codec.go similarity index 83% rename from bson/bsoncodec/time_codec.go rename to bson/time_codec.go index 7b005a9958..a168d1e769 100644 --- a/bson/bsoncodec/time_codec.go +++ b/bson/time_codec.go @@ -4,7 +4,7 @@ // 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 +package bson import ( "fmt" @@ -12,9 +12,6 @@ import ( "time" "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 ( @@ -54,7 +51,7 @@ func NewTimeCodec(opts ...*bsonoptions.TimeCodecOptions) *TimeCodec { return &codec } -func (tc *TimeCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { +func (tc *TimeCodec) decodeType(dc DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { if t != tTime { return emptyValue, ValueDecoderError{ Name: "TimeDecodeValue", @@ -65,13 +62,13 @@ func (tc *TimeCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t refle var timeVal time.Time switch vrType := vr.Type(); vrType { - case bsontype.DateTime: + case TypeDateTime: dt, err := vr.ReadDateTime() if err != nil { return emptyValue, err } timeVal = time.Unix(dt/1000, dt%1000*1000000) - case bsontype.String: + case TypeString: // assume strings are in the isoTimeFormat timeStr, err := vr.ReadString() if err != nil { @@ -81,23 +78,23 @@ func (tc *TimeCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t refle if err != nil { return emptyValue, err } - case bsontype.Int64: + case TypeInt64: i64, err := vr.ReadInt64() if err != nil { return emptyValue, err } timeVal = time.Unix(i64/1000, i64%1000*1000000) - case bsontype.Timestamp: + case TypeTimestamp: t, _, err := vr.ReadTimestamp() if err != nil { return emptyValue, err } timeVal = time.Unix(int64(t), 0) - case bsontype.Null: + case TypeNull: if err := vr.ReadNull(); err != nil { return emptyValue, err } - case bsontype.Undefined: + case TypeUndefined: if err := vr.ReadUndefined(); err != nil { return emptyValue, err } @@ -112,7 +109,7 @@ func (tc *TimeCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t refle } // DecodeValue is the ValueDecoderFunc for time.Time. -func (tc *TimeCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (tc *TimeCodec) DecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tTime { return ValueDecoderError{Name: "TimeDecodeValue", Types: []reflect.Type{tTime}, Received: val} } @@ -127,11 +124,11 @@ func (tc *TimeCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val re } // EncodeValue is the ValueEncoderFunc for time.TIme. -func (tc *TimeCodec) EncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (tc *TimeCodec) EncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tTime { return ValueEncoderError{Name: "TimeEncodeValue", Types: []reflect.Type{tTime}, Received: val} } tt := val.Interface().(time.Time) - dt := primitive.NewDateTimeFromTime(tt) + dt := NewDateTimeFromTime(tt) return vw.WriteDateTime(int64(dt)) } diff --git a/bson/bsoncodec/time_codec_test.go b/bson/time_codec_test.go similarity index 78% rename from bson/bsoncodec/time_codec_test.go rename to bson/time_codec_test.go index 3bb9f51ea7..1f185692da 100644 --- a/bson/bsoncodec/time_codec_test.go +++ b/bson/time_codec_test.go @@ -4,7 +4,7 @@ // 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 +package bson import ( "reflect" @@ -12,8 +12,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson/bsonoptions" - "go.mongodb.org/mongo-driver/bson/bsonrw/bsonrwtest" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -22,7 +20,7 @@ func TestTimeCodec(t *testing.T) { now := time.Now().Truncate(time.Millisecond) t.Run("UseLocalTimeZone", func(t *testing.T) { - reader := &bsonrwtest.ValueReaderWriter{BSONType: bsontype.DateTime, Return: now.UnixNano() / int64(time.Millisecond)} + reader := &valueReaderWriter{BSONType: TypeDateTime, Return: now.UnixNano() / int64(time.Millisecond)} testCases := []struct { name string opts *bsonoptions.TimeCodecOptions @@ -57,13 +55,13 @@ func TestTimeCodec(t *testing.T) { t.Run("DecodeFromBsontype", func(t *testing.T) { testCases := []struct { name string - reader *bsonrwtest.ValueReaderWriter + reader *valueReaderWriter }{ - {"string", &bsonrwtest.ValueReaderWriter{BSONType: bsontype.String, Return: now.Format(timeFormatString)}}, - {"int64", &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Int64, Return: now.Unix()*1000 + int64(now.Nanosecond()/1e6)}}, - {"timestamp", &bsonrwtest.ValueReaderWriter{BSONType: bsontype.Timestamp, + {"string", &valueReaderWriter{BSONType: TypeString, Return: now.Format(timeFormatString)}}, + {"int64", &valueReaderWriter{BSONType: TypeInt64, Return: now.Unix()*1000 + int64(now.Nanosecond()/1e6)}}, + {"timestamp", &valueReaderWriter{BSONType: TypeTimestamp, Return: bsoncore.Value{ - Type: bsontype.Timestamp, + Type: bsoncore.TypeTimestamp, Data: bsoncore.AppendTimestamp(nil, uint32(now.Unix()), 0), }}, }, diff --git a/bson/truncation_test.go b/bson/truncation_test.go index 9237f96b32..865917cfe4 100644 --- a/bson/truncation_test.go +++ b/bson/truncation_test.go @@ -10,8 +10,6 @@ import ( "bytes" "testing" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" "go.mongodb.org/mongo-driver/internal/assert" ) @@ -33,7 +31,7 @@ func TestTruncation(t *testing.T) { input := inputArgs{Name: inputName, Val: &inputVal} buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := NewValueWriter(buf) enc := NewEncoder(vw) enc.IntMinSize() enc.SetRegistry(DefaultRegistry) @@ -41,7 +39,7 @@ func TestTruncation(t *testing.T) { assert.Nil(t, err) var output outputArgs - dc := bsoncodec.DecodeContext{ + dc := DecodeContext{ Registry: DefaultRegistry, Truncate: true, } @@ -59,7 +57,7 @@ func TestTruncation(t *testing.T) { input := inputArgs{Name: inputName, Val: &inputVal} buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := NewValueWriter(buf) enc := NewEncoder(vw) enc.IntMinSize() enc.SetRegistry(DefaultRegistry) @@ -67,7 +65,7 @@ func TestTruncation(t *testing.T) { assert.Nil(t, err) var output outputArgs - dc := bsoncodec.DecodeContext{ + dc := DecodeContext{ Registry: DefaultRegistry, Truncate: false, } diff --git a/bson/type_test.go b/bson/type_test.go new file mode 100644 index 0000000000..3ad8b7cb2f --- /dev/null +++ b/bson/type_test.go @@ -0,0 +1,51 @@ +// 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 bson + +import ( + "testing" +) + +func TestType(t *testing.T) { + testCases := []struct { + name string + t Type + want string + }{ + {"double", TypeDouble, "double"}, + {"string", TypeString, "string"}, + {"embedded document", TypeEmbeddedDocument, "embedded document"}, + {"array", TypeArray, "array"}, + {"binary", TypeBinary, "binary"}, + {"undefined", TypeUndefined, "undefined"}, + {"objectID", TypeObjectID, "objectID"}, + {"boolean", TypeBoolean, "boolean"}, + {"UTC datetime", TypeDateTime, "UTC datetime"}, + {"null", TypeNull, "null"}, + {"regex", TypeRegex, "regex"}, + {"dbPointer", TypeDBPointer, "dbPointer"}, + {"javascript", TypeJavaScript, "javascript"}, + {"symbol", TypeSymbol, "symbol"}, + {"code with scope", TypeCodeWithScope, "code with scope"}, + {"32-bit integer", TypeInt32, "32-bit integer"}, + {"timestamp", TypeTimestamp, "timestamp"}, + {"64-bit integer", TypeInt64, "64-bit integer"}, + {"128-bit decimal", TypeDecimal128, "128-bit decimal"}, + {"max key", TypeMaxKey, "max key"}, + {"min key", TypeMinKey, "min key"}, + {"invalid", (0), "invalid"}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := tc.t.String() + if got != tc.want { + t.Errorf("String outputs do not match. got %s; want %s", got, tc.want) + } + }) + } +} diff --git a/bson/types.go b/bson/types.go index ef39812467..981a121356 100644 --- a/bson/types.go +++ b/bson/types.go @@ -7,44 +7,111 @@ package bson import ( - "go.mongodb.org/mongo-driver/bson/bsontype" + "encoding/json" + "net/url" + "reflect" + "time" + + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) +// Type represents a BSON type. +type Type byte + +// String returns the string representation of the BSON type's name. +func (bt Type) String() string { + return bsoncore.Type(bt).String() +} + +// IsValid will return true if the Type is valid. +func (bt Type) IsValid() bool { + switch bt { + case TypeDouble, TypeString, TypeEmbeddedDocument, TypeArray, TypeBinary, + TypeUndefined, TypeObjectID, TypeBoolean, TypeDateTime, TypeNull, TypeRegex, + TypeDBPointer, TypeJavaScript, TypeSymbol, TypeCodeWithScope, TypeInt32, + TypeTimestamp, TypeInt64, TypeDecimal128, TypeMinKey, TypeMaxKey: + return true + default: + return false + } +} + // BSON element types as described in https://bsonspec.org/spec.html. const ( - TypeDouble = bsontype.Double - TypeString = bsontype.String - TypeEmbeddedDocument = bsontype.EmbeddedDocument - TypeArray = bsontype.Array - TypeBinary = bsontype.Binary - TypeUndefined = bsontype.Undefined - TypeObjectID = bsontype.ObjectID - TypeBoolean = bsontype.Boolean - TypeDateTime = bsontype.DateTime - TypeNull = bsontype.Null - TypeRegex = bsontype.Regex - TypeDBPointer = bsontype.DBPointer - TypeJavaScript = bsontype.JavaScript - TypeSymbol = bsontype.Symbol - TypeCodeWithScope = bsontype.CodeWithScope - TypeInt32 = bsontype.Int32 - TypeTimestamp = bsontype.Timestamp - TypeInt64 = bsontype.Int64 - TypeDecimal128 = bsontype.Decimal128 - TypeMinKey = bsontype.MinKey - TypeMaxKey = bsontype.MaxKey + TypeDouble Type = 0x01 + TypeString Type = 0x02 + TypeEmbeddedDocument Type = 0x03 + TypeArray Type = 0x04 + TypeBinary Type = 0x05 + TypeUndefined Type = 0x06 + TypeObjectID Type = 0x07 + TypeBoolean Type = 0x08 + TypeDateTime Type = 0x09 + TypeNull Type = 0x0A + TypeRegex Type = 0x0B + TypeDBPointer Type = 0x0C + TypeJavaScript Type = 0x0D + TypeSymbol Type = 0x0E + TypeCodeWithScope Type = 0x0F + TypeInt32 Type = 0x10 + TypeTimestamp Type = 0x11 + TypeInt64 Type = 0x12 + TypeDecimal128 Type = 0x13 + TypeMaxKey Type = 0x7F + TypeMinKey Type = 0xFF ) // BSON binary element subtypes as described in https://bsonspec.org/spec.html. const ( - TypeBinaryGeneric = bsontype.BinaryGeneric - TypeBinaryFunction = bsontype.BinaryFunction - TypeBinaryBinaryOld = bsontype.BinaryBinaryOld - TypeBinaryUUIDOld = bsontype.BinaryUUIDOld - TypeBinaryUUID = bsontype.BinaryUUID - TypeBinaryMD5 = bsontype.BinaryMD5 - TypeBinaryEncrypted = bsontype.BinaryEncrypted - TypeBinaryColumn = bsontype.BinaryColumn - TypeBinarySensitive = bsontype.BinarySensitive - TypeBinaryUserDefined = bsontype.BinaryUserDefined + TypeBinaryGeneric byte = 0x00 + TypeBinaryFunction byte = 0x01 + TypeBinaryBinaryOld byte = 0x02 + TypeBinaryUUIDOld byte = 0x03 + TypeBinaryUUID byte = 0x04 + TypeBinaryMD5 byte = 0x05 + TypeBinaryEncrypted byte = 0x06 + TypeBinaryColumn byte = 0x07 + TypeBinarySensitive byte = 0x08 + TypeBinaryUserDefined byte = 0x80 ) + +var tBool = reflect.TypeOf(false) +var tFloat64 = reflect.TypeOf(float64(0)) +var tInt32 = reflect.TypeOf(int32(0)) +var tInt64 = reflect.TypeOf(int64(0)) +var tString = reflect.TypeOf("") +var tTime = reflect.TypeOf(time.Time{}) + +var tEmpty = reflect.TypeOf((*interface{})(nil)).Elem() +var tByteSlice = reflect.TypeOf([]byte(nil)) +var tByte = reflect.TypeOf(byte(0x00)) +var tURL = reflect.TypeOf(url.URL{}) +var tJSONNumber = reflect.TypeOf(json.Number("")) + +var tValueMarshaler = reflect.TypeOf((*ValueMarshaler)(nil)).Elem() +var tValueUnmarshaler = reflect.TypeOf((*ValueUnmarshaler)(nil)).Elem() +var tMarshaler = reflect.TypeOf((*Marshaler)(nil)).Elem() +var tUnmarshaler = reflect.TypeOf((*Unmarshaler)(nil)).Elem() +var tProxy = reflect.TypeOf((*Proxy)(nil)).Elem() +var tZeroer = reflect.TypeOf((*Zeroer)(nil)).Elem() + +var tBinary = reflect.TypeOf(Binary{}) +var tUndefined = reflect.TypeOf(Undefined{}) +var tOID = reflect.TypeOf(ObjectID{}) +var tDateTime = reflect.TypeOf(DateTime(0)) +var tNull = reflect.TypeOf(Null{}) +var tRegex = reflect.TypeOf(Regex{}) +var tCodeWithScope = reflect.TypeOf(CodeWithScope{}) +var tDBPointer = reflect.TypeOf(DBPointer{}) +var tJavaScript = reflect.TypeOf(JavaScript("")) +var tSymbol = reflect.TypeOf(Symbol("")) +var tTimestamp = reflect.TypeOf(Timestamp{}) +var tDecimal = reflect.TypeOf(Decimal128{}) +var tMinKey = reflect.TypeOf(MinKey{}) +var tMaxKey = reflect.TypeOf(MaxKey{}) +var tD = reflect.TypeOf(D{}) +var tA = reflect.TypeOf(A{}) +var tE = reflect.TypeOf(E{}) + +var tCoreDocument = reflect.TypeOf(bsoncore.Document{}) +var tCoreArray = reflect.TypeOf(bsoncore.Array{}) diff --git a/bson/bsoncodec/uint_codec.go b/bson/uint_codec.go similarity index 89% rename from bson/bsoncodec/uint_codec.go rename to bson/uint_codec.go index 7eb1069050..73bc01966e 100644 --- a/bson/bsoncodec/uint_codec.go +++ b/bson/uint_codec.go @@ -4,7 +4,7 @@ // 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 +package bson import ( "fmt" @@ -12,8 +12,6 @@ import ( "reflect" "go.mongodb.org/mongo-driver/bson/bsonoptions" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" ) // UIntCodec is the Codec used for uint values. @@ -51,7 +49,7 @@ func NewUIntCodec(opts ...*bsonoptions.UIntCodecOptions) *UIntCodec { } // EncodeValue is the ValueEncoder for uint types. -func (uic *UIntCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (uic *UIntCodec) EncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { switch val.Kind() { case reflect.Uint8, reflect.Uint16: return vw.WriteInt32(int32(val.Uint())) @@ -77,22 +75,22 @@ 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) { +func (uic *UIntCodec) decodeType(dc DecodeContext, vr ValueReader, t reflect.Type) (reflect.Value, error) { var i64 int64 var err error switch vrType := vr.Type(); vrType { - case bsontype.Int32: + case TypeInt32: i32, err := vr.ReadInt32() if err != nil { return emptyValue, err } i64 = int64(i32) - case bsontype.Int64: + case TypeInt64: i64, err = vr.ReadInt64() if err != nil { return emptyValue, err } - case bsontype.Double: + case TypeDouble: f64, err := vr.ReadDouble() if err != nil { return emptyValue, err @@ -104,7 +102,7 @@ func (uic *UIntCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t refl return emptyValue, fmt.Errorf("%g overflows int64", f64) } i64 = int64(f64) - case bsontype.Boolean: + case TypeBoolean: b, err := vr.ReadBoolean() if err != nil { return emptyValue, err @@ -112,11 +110,11 @@ func (uic *UIntCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t refl if b { i64 = 1 } - case bsontype.Null: + case TypeNull: if err = vr.ReadNull(); err != nil { return emptyValue, err } - case bsontype.Undefined: + case TypeUndefined: if err = vr.ReadUndefined(); err != nil { return emptyValue, err } @@ -165,7 +163,7 @@ func (uic *UIntCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t refl } // DecodeValue is the ValueDecoder for uint types. -func (uic *UIntCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (uic *UIntCodec) DecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() { return ValueDecoderError{ Name: "UintDecodeValue", diff --git a/bson/unmarshal.go b/bson/unmarshal.go index e3e163699b..7caadc5dbc 100644 --- a/bson/unmarshal.go +++ b/bson/unmarshal.go @@ -8,10 +8,6 @@ package bson import ( "bytes" - - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" ) // Unmarshaler is the interface implemented by types that can unmarshal a BSON @@ -35,7 +31,7 @@ type Unmarshaler interface { // document. To create custom BSON unmarshaling behavior for an entire BSON // document, implement the Unmarshaler interface instead. type ValueUnmarshaler interface { - UnmarshalBSONValue(bsontype.Type, []byte) error + UnmarshalBSONValue(Type, []byte) error } // Unmarshal parses the BSON-encoded data and stores the result in the value @@ -51,16 +47,16 @@ func Unmarshal(data []byte, val interface{}) error { // // Deprecated: Use [NewDecoder] and specify the Registry by calling [Decoder.SetRegistry] instead: // -// dec, err := bson.NewDecoder(bsonrw.NewBSONDocumentReader(data)) +// dec, err := bson.NewDecoder(NewBSONDocumentReader(data)) // if err != nil { // panic(err) // } // dec.SetRegistry(reg) // // See [Decoder] for more examples. -func UnmarshalWithRegistry(r *bsoncodec.Registry, data []byte, val interface{}) error { - vr := bsonrw.NewValueReader(data) - return unmarshalFromReader(bsoncodec.DecodeContext{Registry: r}, vr, val) +func UnmarshalWithRegistry(r *Registry, data []byte, val interface{}) error { + vr := NewValueReader(data) + return unmarshalFromReader(DecodeContext{Registry: r}, vr, val) } // UnmarshalWithContext parses the BSON-encoded data using DecodeContext dc and @@ -70,22 +66,22 @@ func UnmarshalWithRegistry(r *bsoncodec.Registry, data []byte, val interface{}) // Deprecated: Use [NewDecoder] and use the Decoder configuration methods to set the desired unmarshal // behavior instead: // -// dec, err := bson.NewDecoder(bsonrw.NewBSONDocumentReader(data)) +// dec, err := bson.NewDecoder(NewBSONDocumentReader(data)) // if err != nil { // panic(err) // } // dec.DefaultDocumentM() // // See [Decoder] for more examples. -func UnmarshalWithContext(dc bsoncodec.DecodeContext, data []byte, val interface{}) error { - vr := bsonrw.NewValueReader(data) +func UnmarshalWithContext(dc DecodeContext, data []byte, val interface{}) error { + vr := NewValueReader(data) return unmarshalFromReader(dc, vr, val) } // UnmarshalValue parses the BSON value of type t with bson.DefaultRegistry 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 bsontype.Type, data []byte, val interface{}) error { +func UnmarshalValue(t Type, data []byte, val interface{}) error { return UnmarshalValueWithRegistry(DefaultRegistry, t, data, val) } @@ -95,9 +91,9 @@ func UnmarshalValue(t bsontype.Type, data []byte, val interface{}) error { // // Deprecated: Using a custom registry to unmarshal individual BSON values will not be supported in // Go Driver 2.0. -func UnmarshalValueWithRegistry(r *bsoncodec.Registry, t bsontype.Type, data []byte, val interface{}) error { - vr := bsonrw.NewBSONValueReader(t, data) - return unmarshalFromReader(bsoncodec.DecodeContext{Registry: r}, vr, val) +func UnmarshalValueWithRegistry(r *Registry, t Type, data []byte, val interface{}) error { + vr := NewBSONValueReader(t, data) + return unmarshalFromReader(DecodeContext{Registry: r}, vr, val) } // UnmarshalExtJSON parses the extended JSON-encoded data and stores the result @@ -113,7 +109,7 @@ func UnmarshalExtJSON(data []byte, canonical bool, val interface{}) error { // // Deprecated: Use [NewDecoder] and specify the Registry by calling [Decoder.SetRegistry] instead: // -// vr, err := bsonrw.NewExtJSONValueReader(bytes.NewReader(data), true) +// vr, err := NewExtJSONValueReader(bytes.NewReader(data), true) // if err != nil { // panic(err) // } @@ -124,13 +120,13 @@ func UnmarshalExtJSON(data []byte, canonical bool, val interface{}) error { // dec.SetRegistry(reg) // // See [Decoder] for more examples. -func UnmarshalExtJSONWithRegistry(r *bsoncodec.Registry, data []byte, canonical bool, val interface{}) error { - ejvr, err := bsonrw.NewExtJSONValueReader(bytes.NewReader(data), canonical) +func UnmarshalExtJSONWithRegistry(r *Registry, data []byte, canonical bool, val interface{}) error { + ejvr, err := NewExtJSONValueReader(bytes.NewReader(data), canonical) if err != nil { return err } - return unmarshalFromReader(bsoncodec.DecodeContext{Registry: r}, ejvr, val) + return unmarshalFromReader(DecodeContext{Registry: r}, ejvr, val) } // UnmarshalExtJSONWithContext parses the extended JSON-encoded data using @@ -140,7 +136,7 @@ func UnmarshalExtJSONWithRegistry(r *bsoncodec.Registry, data []byte, canonical // Deprecated: Use [NewDecoder] and use the Decoder configuration methods to set the desired unmarshal // behavior instead: // -// vr, err := bsonrw.NewExtJSONValueReader(bytes.NewReader(data), true) +// vr, err := NewExtJSONValueReader(bytes.NewReader(data), true) // if err != nil { // panic(err) // } @@ -151,8 +147,8 @@ func UnmarshalExtJSONWithRegistry(r *bsoncodec.Registry, data []byte, canonical // dec.DefaultDocumentM() // // See [Decoder] for more examples. -func UnmarshalExtJSONWithContext(dc bsoncodec.DecodeContext, data []byte, canonical bool, val interface{}) error { - ejvr, err := bsonrw.NewExtJSONValueReader(bytes.NewReader(data), canonical) +func UnmarshalExtJSONWithContext(dc DecodeContext, data []byte, canonical bool, val interface{}) error { + ejvr, err := NewExtJSONValueReader(bytes.NewReader(data), canonical) if err != nil { return err } @@ -160,7 +156,7 @@ func UnmarshalExtJSONWithContext(dc bsoncodec.DecodeContext, data []byte, canoni return unmarshalFromReader(dc, ejvr, val) } -func unmarshalFromReader(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val interface{}) error { +func unmarshalFromReader(dc DecodeContext, vr ValueReader, val interface{}) error { dec := decPool.Get().(*Decoder) defer decPool.Put(dec) diff --git a/bson/unmarshal_test.go b/bson/unmarshal_test.go index c5bb0f2074..0871237386 100644 --- a/bson/unmarshal_test.go +++ b/bson/unmarshal_test.go @@ -13,9 +13,6 @@ import ( "sync" "testing" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -72,7 +69,7 @@ func TestUnmarshalWithContext(t *testing.T) { copy(data, tc.data) // Assert that unmarshaling the input data results in the expected value. - dc := bsoncodec.DecodeContext{Registry: DefaultRegistry} + dc := DecodeContext{Registry: DefaultRegistry} got := reflect.New(tc.sType).Interface() err := UnmarshalWithContext(dc, data, got) noerr(t, err) @@ -101,7 +98,7 @@ func TestUnmarshalExtJSONWithRegistry(t *testing.T) { t.Run("UnmarshalExtJSONInvalidInput", func(t *testing.T) { data := []byte("invalid") err := UnmarshalExtJSONWithRegistry(DefaultRegistry, data, true, &M{}) - if !errors.Is(err, bsonrw.ErrInvalidJSON) { + if !errors.Is(err, ErrInvalidJSON) { t.Fatalf("wanted ErrInvalidJSON, got %v", err) } }) @@ -181,7 +178,7 @@ func TestUnmarshalExtJSONWithContext(t *testing.T) { name: "bson.D with binary", sType: reflect.TypeOf(D{}), data: []byte(`{"foo": {"$binary": {"subType": "0", "base64": "AAECAwQF"}}}`), - want: &D{{"foo", primitive.Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}}}, + want: &D{{"foo", Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}}}, }, // GODRIVER-2311 // Test that ExtJSON-encoded binary unmarshals correctly to a struct and that the @@ -202,7 +199,7 @@ func TestUnmarshalExtJSONWithContext(t *testing.T) { // Assert that unmarshaling the input data results in the expected value. got := reflect.New(tc.sType).Interface() - dc := bsoncodec.DecodeContext{Registry: DefaultRegistry} + dc := DecodeContext{Registry: DefaultRegistry} err := UnmarshalExtJSONWithContext(dc, data, true, got) noerr(t, err) assert.Equal(t, tc.want, got, "Did not unmarshal as expected.") @@ -222,7 +219,7 @@ func TestCachingDecodersNotSharedAcrossRegistries(t *testing.T) { // different Registry is used. // Create a custom Registry that negates BSON int32 values when decoding. - var decodeInt32 bsoncodec.ValueDecoderFunc = func(_ bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + var decodeInt32 ValueDecoderFunc = func(_ DecodeContext, vr ValueReader, val reflect.Value) error { i32, err := vr.ReadInt32() if err != nil { return err @@ -580,15 +577,15 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { } type fooBinary struct { - Foo primitive.Binary + Foo Binary } type fooObjectID struct { - Foo primitive.ObjectID + Foo ObjectID } type fooDBPointer struct { - Foo primitive.DBPointer + Foo DBPointer } testCases := []struct { @@ -621,10 +618,10 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { }), sType: reflect.TypeOf(D{}), want: &D{ - {"foo", primitive.Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}}, + {"foo", Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}}, }, getByteSlice: func(val interface{}) []byte { - return (*(val.(*D)))[0].Value.(primitive.Binary).Data + return (*(val.(*D)))[0].Value.(Binary).Data }, }, { @@ -647,78 +644,78 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { }), sType: reflect.TypeOf(D{}), want: &D{ - {"foo", primitive.Binary{Subtype: 0, Data: myBytes{0, 1, 2, 3, 4, 5}}}, + {"foo", Binary{Subtype: 0, Data: myBytes{0, 1, 2, 3, 4, 5}}}, }, getByteSlice: func(val interface{}) []byte { - return (*(val.(*D)))[0].Value.(primitive.Binary).Data + return (*(val.(*D)))[0].Value.(Binary).Data }, }, { - description: "struct with primitive.Binary", + description: "struct with Binary", data: docToBytes(fooBinary{ - Foo: primitive.Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}, + Foo: Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}, }), sType: reflect.TypeOf(fooBinary{}), want: &fooBinary{ - Foo: primitive.Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}, + Foo: Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}, }, getByteSlice: func(val interface{}) []byte { return (*(val.(*fooBinary))).Foo.Data }, }, { - description: "bson.D with primitive.Binary", + description: "bson.D with Binary", data: docToBytes(D{ - {"foo", primitive.Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}}, + {"foo", Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}}, }), sType: reflect.TypeOf(D{}), want: &D{ - {"foo", primitive.Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}}, + {"foo", Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}}, }, getByteSlice: func(val interface{}) []byte { - return (*(val.(*D)))[0].Value.(primitive.Binary).Data + return (*(val.(*D)))[0].Value.(Binary).Data }, }, { - description: "struct with primitive.ObjectID", + description: "struct with ObjectID", data: docToBytes(fooObjectID{ - Foo: primitive.ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + Foo: ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, }), sType: reflect.TypeOf(fooObjectID{}), want: &fooObjectID{ - Foo: primitive.ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + Foo: ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, }, getByteSlice: func(val interface{}) []byte { return (*(val.(*fooObjectID))).Foo[:] }, }, { - description: "bson.D with primitive.ObjectID", + description: "bson.D with ObjectID", data: docToBytes(D{ - {"foo", primitive.ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}}, + {"foo", ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}}, }), sType: reflect.TypeOf(D{}), want: &D{ - {"foo", primitive.ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}}, + {"foo", ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}}, }, getByteSlice: func(val interface{}) []byte { - oid := (*(val.(*D)))[0].Value.(primitive.ObjectID) + oid := (*(val.(*D)))[0].Value.(ObjectID) return oid[:] }, }, { - description: "struct with primitive.DBPointer", + description: "struct with DBPointer", data: docToBytes(fooDBPointer{ - Foo: primitive.DBPointer{ + Foo: DBPointer{ DB: "test", - Pointer: primitive.ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + Pointer: ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, }, }), sType: reflect.TypeOf(fooDBPointer{}), want: &fooDBPointer{ - Foo: primitive.DBPointer{ + Foo: DBPointer{ DB: "test", - Pointer: primitive.ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + Pointer: ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, }, }, getByteSlice: func(val interface{}) []byte { @@ -726,22 +723,22 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { }, }, { - description: "bson.D with primitive.DBPointer", + description: "bson.D with DBPointer", data: docToBytes(D{ - {"foo", primitive.DBPointer{ + {"foo", DBPointer{ DB: "test", - Pointer: primitive.ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + Pointer: ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, }}, }), sType: reflect.TypeOf(D{}), want: &D{ - {"foo", primitive.DBPointer{ + {"foo", DBPointer{ DB: "test", - Pointer: primitive.ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + Pointer: ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, }}, }, getByteSlice: func(val interface{}) []byte { - oid := (*(val.(*D)))[0].Value.(primitive.DBPointer).Pointer + oid := (*(val.(*D)))[0].Value.(DBPointer).Pointer return oid[:] }, }, diff --git a/bson/unmarshal_value_test.go b/bson/unmarshal_value_test.go index f25e25ba8b..8d9dfb5351 100644 --- a/bson/unmarshal_value_test.go +++ b/bson/unmarshal_value_test.go @@ -11,8 +11,6 @@ import ( "strings" "testing" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -61,24 +59,24 @@ func TestUnmarshalValue(t *testing.T) { testCases := []struct { name string val interface{} - bsontype bsontype.Type + bsontype Type bytes []byte }{ { name: "SliceCodec binary", val: []byte("hello world"), - bsontype: bsontype.Binary, - bytes: bsoncore.AppendBinary(nil, bsontype.BinaryGeneric, []byte("hello world")), + bsontype: TypeBinary, + bytes: bsoncore.AppendBinary(nil, TypeBinaryGeneric, []byte("hello world")), }, { name: "SliceCodec string", val: []byte("hello world"), - bsontype: bsontype.String, + bsontype: TypeString, bytes: bsoncore.AppendString(nil, "hello world"), }, } reg := NewRegistry() - reg.RegisterTypeDecoder(reflect.TypeOf([]byte{}), bsoncodec.NewSliceCodec()) + reg.RegisterTypeDecoder(reflect.TypeOf([]byte{}), NewSliceCodec()) for _, tc := range testCases { tc := tc @@ -98,22 +96,22 @@ func TestUnmarshalValue(t *testing.T) { func BenchmarkSliceCodecUnmarshal(b *testing.B) { benchmarks := []struct { name string - bsontype bsontype.Type + bsontype Type bytes []byte }{ { name: "SliceCodec binary", - bsontype: bsontype.Binary, - bytes: bsoncore.AppendBinary(nil, bsontype.BinaryGeneric, []byte(strings.Repeat("t", 4096))), + bsontype: TypeBinary, + bytes: bsoncore.AppendBinary(nil, TypeBinaryGeneric, []byte(strings.Repeat("t", 4096))), }, { name: "SliceCodec string", - bsontype: bsontype.String, + bsontype: TypeString, bytes: bsoncore.AppendString(nil, strings.Repeat("t", 4096)), }, } reg := NewRegistry() - reg.RegisterTypeDecoder(reflect.TypeOf([]byte{}), bsoncodec.NewSliceCodec()) + reg.RegisterTypeDecoder(reflect.TypeOf([]byte{}), NewSliceCodec()) for _, bm := range benchmarks { b.Run(bm.name, func(b *testing.B) { b.RunParallel(func(pb *testing.PB) { diff --git a/bson/unmarshaling_cases_test.go b/bson/unmarshaling_cases_test.go index 37d9ded318..4b8210415e 100644 --- a/bson/unmarshaling_cases_test.go +++ b/bson/unmarshaling_cases_test.go @@ -8,9 +8,6 @@ package bson import ( "reflect" - - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" ) type unmarshalingTestCase struct { @@ -203,7 +200,7 @@ func (mi *myInt64) UnmarshalBSON(bytes []byte) error { if len(bytes) == 0 { return nil } - i, err := bsonrw.NewBSONValueReader(bsontype.Int64, bytes).ReadInt64() + i, err := NewBSONValueReader(TypeInt64, bytes).ReadInt64() if err != nil { return err } @@ -229,7 +226,7 @@ func (mb *myBytes) UnmarshalBSON(bytes []byte) error { if len(bytes) == 0 { return nil } - b, _, err := bsonrw.NewBSONValueReader(bsontype.Binary, bytes).ReadBinary() + b, _, err := NewBSONValueReader(TypeBinary, bytes).ReadBinary() if err != nil { return err } @@ -243,7 +240,7 @@ func (ms *myString) UnmarshalBSON(bytes []byte) error { if len(bytes) == 0 { return nil } - s, err := bsonrw.NewBSONValueReader(bsontype.String, bytes).ReadString() + s, err := NewBSONValueReader(TypeString, bytes).ReadString() if err != nil { return err } diff --git a/bson/bsonrw/value_reader.go b/bson/value_reader.go similarity index 79% rename from bson/bsonrw/value_reader.go rename to bson/value_reader.go index bf37e0cff2..2726541305 100644 --- a/bson/bsonrw/value_reader.go +++ b/bson/value_reader.go @@ -4,7 +4,7 @@ // 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 bsonrw +package bson import ( "bytes" @@ -14,9 +14,6 @@ import ( "io" "math" "sync" - - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" ) var _ ValueReader = (*valueReader)(nil) @@ -27,18 +24,18 @@ var vrPool = sync.Pool{ }, } -// BSONValueReaderPool is a pool for ValueReaders that read BSON. +// ValueReaderPool is a pool for ValueReaders that read BSON. // -// Deprecated: BSONValueReaderPool will not be supported in Go Driver 2.0. -type BSONValueReaderPool struct { +// Deprecated: ValueReaderPool will not be supported in Go Driver 2.0. +type ValueReaderPool struct { pool sync.Pool } -// NewBSONValueReaderPool instantiates a new BSONValueReaderPool. +// NewValueReaderPool instantiates a new ValueReaderPool. // -// Deprecated: BSONValueReaderPool will not be supported in Go Driver 2.0. -func NewBSONValueReaderPool() *BSONValueReaderPool { - return &BSONValueReaderPool{ +// Deprecated: ValueReaderPool will not be supported in Go Driver 2.0. +func NewValueReaderPool() *ValueReaderPool { + return &ValueReaderPool{ pool: sync.Pool{ New: func() interface{} { return new(valueReader) @@ -49,8 +46,8 @@ func NewBSONValueReaderPool() *BSONValueReaderPool { // Get retrieves a ValueReader from the pool and uses src as the underlying BSON. // -// Deprecated: BSONValueReaderPool will not be supported in Go Driver 2.0. -func (bvrp *BSONValueReaderPool) Get(src []byte) ValueReader { +// Deprecated: ValueReaderPool will not be supported in Go Driver 2.0. +func (bvrp *ValueReaderPool) Get(src []byte) ValueReader { vr := bvrp.pool.Get().(*valueReader) vr.reset(src) return vr @@ -59,8 +56,8 @@ func (bvrp *BSONValueReaderPool) Get(src []byte) ValueReader { // Put inserts a ValueReader into the pool. If the ValueReader is not a BSON ValueReader nothing // is inserted into the pool and ok will be false. // -// Deprecated: BSONValueReaderPool will not be supported in Go Driver 2.0. -func (bvrp *BSONValueReaderPool) Put(vr ValueReader) (ok bool) { +// Deprecated: ValueReaderPool will not be supported in Go Driver 2.0. +func (bvrp *ValueReaderPool) Put(vr ValueReader) (ok bool) { bvr, ok := vr.(*valueReader) if !ok { return false @@ -79,7 +76,7 @@ var ErrEOD = errors.New("end of document") type vrState struct { mode mode - vType bsontype.Type + vType Type end int64 } @@ -104,7 +101,7 @@ func NewValueReader(b []byte) ValueReader { // NewBSONValueReader returns a ValueReader that starts in the Value mode instead of in top // level document mode. This enables the creation of a ValueReader for a single BSON value. -func NewBSONValueReader(t bsontype.Type, val []byte) ValueReader { +func NewBSONValueReader(t Type, val []byte) ValueReader { stack := make([]vrState, 1, 5) stack[0] = vrState{ mode: mValue, @@ -185,14 +182,14 @@ func (vr *valueReader) pushArray() error { return nil } -func (vr *valueReader) pushElement(t bsontype.Type) { +func (vr *valueReader) pushElement(t Type) { vr.advanceFrame() vr.stack[vr.frame].mode = mElement vr.stack[vr.frame].vType = t } -func (vr *valueReader) pushValue(t bsontype.Type) { +func (vr *valueReader) pushValue(t Type) { vr.advanceFrame() vr.stack[vr.frame].mode = mValue @@ -236,7 +233,7 @@ func (vr *valueReader) invalidTransitionErr(destination mode, name string, modes return te } -func (vr *valueReader) typeError(t bsontype.Type) error { +func (vr *valueReader) typeError(t Type) error { return fmt.Errorf("positioned on %s, but attempted to read %s", vr.stack[vr.frame].vType, t) } @@ -244,7 +241,7 @@ func (vr *valueReader) invalidDocumentLengthError() error { return fmt.Errorf("document is invalid, end byte is at %d, but null byte found at %d", vr.stack[vr.frame].end, vr.offset) } -func (vr *valueReader) ensureElementValue(t bsontype.Type, destination mode, callerName string) error { +func (vr *valueReader) ensureElementValue(t Type, destination mode, callerName string) error { switch vr.stack[vr.frame].mode { case mElement, mValue: if vr.stack[vr.frame].vType != t { @@ -257,7 +254,7 @@ func (vr *valueReader) ensureElementValue(t bsontype.Type, destination mode, cal return nil } -func (vr *valueReader) Type() bsontype.Type { +func (vr *valueReader) Type() Type { return vr.stack[vr.frame].vType } @@ -265,30 +262,30 @@ func (vr *valueReader) nextElementLength() (int32, error) { var length int32 var err error switch vr.stack[vr.frame].vType { - case bsontype.Array, bsontype.EmbeddedDocument, bsontype.CodeWithScope: + case TypeArray, TypeEmbeddedDocument, TypeCodeWithScope: length, err = vr.peekLength() - case bsontype.Binary: + case TypeBinary: length, err = vr.peekLength() length += 4 + 1 // binary length + subtype byte - case bsontype.Boolean: + case TypeBoolean: length = 1 - case bsontype.DBPointer: + case TypeDBPointer: length, err = vr.peekLength() length += 4 + 12 // string length + ObjectID length - case bsontype.DateTime, bsontype.Double, bsontype.Int64, bsontype.Timestamp: + case TypeDateTime, TypeDouble, TypeInt64, TypeTimestamp: length = 8 - case bsontype.Decimal128: + case TypeDecimal128: length = 16 - case bsontype.Int32: + case TypeInt32: length = 4 - case bsontype.JavaScript, bsontype.String, bsontype.Symbol: + case TypeJavaScript, TypeString, TypeSymbol: length, err = vr.peekLength() length += 4 - case bsontype.MaxKey, bsontype.MinKey, bsontype.Null, bsontype.Undefined: + case TypeMaxKey, TypeMinKey, TypeNull, TypeUndefined: length = 0 - case bsontype.ObjectID: + case TypeObjectID: length = 12 - case bsontype.Regex: + case TypeRegex: regex := bytes.IndexByte(vr.d[vr.offset:], 0x00) if regex < 0 { err = io.EOF @@ -307,22 +304,22 @@ func (vr *valueReader) nextElementLength() (int32, error) { return length, err } -func (vr *valueReader) ReadValueBytes(dst []byte) (bsontype.Type, []byte, error) { +func (vr *valueReader) ReadValueBytes(dst []byte) (Type, []byte, error) { switch vr.stack[vr.frame].mode { case mTopLevel: length, err := vr.peekLength() if err != nil { - return bsontype.Type(0), nil, err + return Type(0), nil, err } dst, err = vr.appendBytes(dst, length) if err != nil { - return bsontype.Type(0), nil, err + return Type(0), nil, err } - return bsontype.Type(0), dst, nil + return Type(0), dst, nil case mElement, mValue: length, err := vr.nextElementLength() if err != nil { - return bsontype.Type(0), dst, err + return Type(0), dst, err } dst, err = vr.appendBytes(dst, length) @@ -330,7 +327,7 @@ func (vr *valueReader) ReadValueBytes(dst []byte) (bsontype.Type, []byte, error) vr.pop() return t, dst, err default: - return bsontype.Type(0), nil, vr.invalidTransitionErr(0, "ReadValueBytes", []mode{mElement, mValue}) + return Type(0), nil, vr.invalidTransitionErr(0, "ReadValueBytes", []mode{mElement, mValue}) } } @@ -352,7 +349,7 @@ func (vr *valueReader) Skip() error { } func (vr *valueReader) ReadArray() (ArrayReader, error) { - if err := vr.ensureElementValue(bsontype.Array, mArray, "ReadArray"); err != nil { + if err := vr.ensureElementValue(TypeArray, mArray, "ReadArray"); err != nil { return nil, err } @@ -365,7 +362,7 @@ func (vr *valueReader) ReadArray() (ArrayReader, error) { } func (vr *valueReader) ReadBinary() (b []byte, btype byte, err error) { - if err := vr.ensureElementValue(bsontype.Binary, 0, "ReadBinary"); err != nil { + if err := vr.ensureElementValue(TypeBinary, 0, "ReadBinary"); err != nil { return nil, 0, err } @@ -401,7 +398,7 @@ func (vr *valueReader) ReadBinary() (b []byte, btype byte, err error) { } func (vr *valueReader) ReadBoolean() (bool, error) { - if err := vr.ensureElementValue(bsontype.Boolean, 0, "ReadBoolean"); err != nil { + if err := vr.ensureElementValue(TypeBoolean, 0, "ReadBoolean"); err != nil { return false, err } @@ -432,8 +429,8 @@ func (vr *valueReader) ReadDocument() (DocumentReader, error) { vr.stack[vr.frame].end = int64(size) + vr.offset - 4 return vr, nil case mElement, mValue: - if vr.stack[vr.frame].vType != bsontype.EmbeddedDocument { - return nil, vr.typeError(bsontype.EmbeddedDocument) + if vr.stack[vr.frame].vType != TypeEmbeddedDocument { + return nil, vr.typeError(TypeEmbeddedDocument) } default: return nil, vr.invalidTransitionErr(mDocument, "ReadDocument", []mode{mTopLevel, mElement, mValue}) @@ -448,7 +445,7 @@ func (vr *valueReader) ReadDocument() (DocumentReader, error) { } func (vr *valueReader) ReadCodeWithScope() (code string, dr DocumentReader, err error) { - if err := vr.ensureElementValue(bsontype.CodeWithScope, 0, "ReadCodeWithScope"); err != nil { + if err := vr.ensureElementValue(TypeCodeWithScope, 0, "ReadCodeWithScope"); err != nil { return "", nil, err } @@ -486,8 +483,8 @@ func (vr *valueReader) ReadCodeWithScope() (code string, dr DocumentReader, err return code, vr, nil } -func (vr *valueReader) ReadDBPointer() (ns string, oid primitive.ObjectID, err error) { - if err := vr.ensureElementValue(bsontype.DBPointer, 0, "ReadDBPointer"); err != nil { +func (vr *valueReader) ReadDBPointer() (ns string, oid ObjectID, err error) { + if err := vr.ensureElementValue(TypeDBPointer, 0, "ReadDBPointer"); err != nil { return "", oid, err } @@ -508,7 +505,7 @@ func (vr *valueReader) ReadDBPointer() (ns string, oid primitive.ObjectID, err e } func (vr *valueReader) ReadDateTime() (int64, error) { - if err := vr.ensureElementValue(bsontype.DateTime, 0, "ReadDateTime"); err != nil { + if err := vr.ensureElementValue(TypeDateTime, 0, "ReadDateTime"); err != nil { return 0, err } @@ -521,25 +518,25 @@ func (vr *valueReader) ReadDateTime() (int64, error) { return i, nil } -func (vr *valueReader) ReadDecimal128() (primitive.Decimal128, error) { - if err := vr.ensureElementValue(bsontype.Decimal128, 0, "ReadDecimal128"); err != nil { - return primitive.Decimal128{}, err +func (vr *valueReader) ReadDecimal128() (Decimal128, error) { + if err := vr.ensureElementValue(TypeDecimal128, 0, "ReadDecimal128"); err != nil { + return Decimal128{}, err } b, err := vr.readBytes(16) if err != nil { - return primitive.Decimal128{}, err + return Decimal128{}, err } l := binary.LittleEndian.Uint64(b[0:8]) h := binary.LittleEndian.Uint64(b[8:16]) vr.pop() - return primitive.NewDecimal128(h, l), nil + return NewDecimal128(h, l), nil } func (vr *valueReader) ReadDouble() (float64, error) { - if err := vr.ensureElementValue(bsontype.Double, 0, "ReadDouble"); err != nil { + if err := vr.ensureElementValue(TypeDouble, 0, "ReadDouble"); err != nil { return 0, err } @@ -553,7 +550,7 @@ func (vr *valueReader) ReadDouble() (float64, error) { } func (vr *valueReader) ReadInt32() (int32, error) { - if err := vr.ensureElementValue(bsontype.Int32, 0, "ReadInt32"); err != nil { + if err := vr.ensureElementValue(TypeInt32, 0, "ReadInt32"); err != nil { return 0, err } @@ -562,7 +559,7 @@ func (vr *valueReader) ReadInt32() (int32, error) { } func (vr *valueReader) ReadInt64() (int64, error) { - if err := vr.ensureElementValue(bsontype.Int64, 0, "ReadInt64"); err != nil { + if err := vr.ensureElementValue(TypeInt64, 0, "ReadInt64"); err != nil { return 0, err } @@ -571,7 +568,7 @@ func (vr *valueReader) ReadInt64() (int64, error) { } func (vr *valueReader) ReadJavascript() (code string, err error) { - if err := vr.ensureElementValue(bsontype.JavaScript, 0, "ReadJavascript"); err != nil { + if err := vr.ensureElementValue(TypeJavaScript, 0, "ReadJavascript"); err != nil { return "", err } @@ -580,7 +577,7 @@ func (vr *valueReader) ReadJavascript() (code string, err error) { } func (vr *valueReader) ReadMaxKey() error { - if err := vr.ensureElementValue(bsontype.MaxKey, 0, "ReadMaxKey"); err != nil { + if err := vr.ensureElementValue(TypeMaxKey, 0, "ReadMaxKey"); err != nil { return err } @@ -589,7 +586,7 @@ func (vr *valueReader) ReadMaxKey() error { } func (vr *valueReader) ReadMinKey() error { - if err := vr.ensureElementValue(bsontype.MinKey, 0, "ReadMinKey"); err != nil { + if err := vr.ensureElementValue(TypeMinKey, 0, "ReadMinKey"); err != nil { return err } @@ -598,7 +595,7 @@ func (vr *valueReader) ReadMinKey() error { } func (vr *valueReader) ReadNull() error { - if err := vr.ensureElementValue(bsontype.Null, 0, "ReadNull"); err != nil { + if err := vr.ensureElementValue(TypeNull, 0, "ReadNull"); err != nil { return err } @@ -606,17 +603,17 @@ func (vr *valueReader) ReadNull() error { return nil } -func (vr *valueReader) ReadObjectID() (primitive.ObjectID, error) { - if err := vr.ensureElementValue(bsontype.ObjectID, 0, "ReadObjectID"); err != nil { - return primitive.ObjectID{}, err +func (vr *valueReader) ReadObjectID() (ObjectID, error) { + if err := vr.ensureElementValue(TypeObjectID, 0, "ReadObjectID"); err != nil { + return ObjectID{}, err } oidbytes, err := vr.readBytes(12) if err != nil { - return primitive.ObjectID{}, err + return ObjectID{}, err } - var oid primitive.ObjectID + var oid ObjectID copy(oid[:], oidbytes) vr.pop() @@ -624,7 +621,7 @@ func (vr *valueReader) ReadObjectID() (primitive.ObjectID, error) { } func (vr *valueReader) ReadRegex() (string, string, error) { - if err := vr.ensureElementValue(bsontype.Regex, 0, "ReadRegex"); err != nil { + if err := vr.ensureElementValue(TypeRegex, 0, "ReadRegex"); err != nil { return "", "", err } @@ -643,7 +640,7 @@ func (vr *valueReader) ReadRegex() (string, string, error) { } func (vr *valueReader) ReadString() (string, error) { - if err := vr.ensureElementValue(bsontype.String, 0, "ReadString"); err != nil { + if err := vr.ensureElementValue(TypeString, 0, "ReadString"); err != nil { return "", err } @@ -652,7 +649,7 @@ func (vr *valueReader) ReadString() (string, error) { } func (vr *valueReader) ReadSymbol() (symbol string, err error) { - if err := vr.ensureElementValue(bsontype.Symbol, 0, "ReadSymbol"); err != nil { + if err := vr.ensureElementValue(TypeSymbol, 0, "ReadSymbol"); err != nil { return "", err } @@ -661,7 +658,7 @@ func (vr *valueReader) ReadSymbol() (symbol string, err error) { } func (vr *valueReader) ReadTimestamp() (t uint32, i uint32, err error) { - if err := vr.ensureElementValue(bsontype.Timestamp, 0, "ReadTimestamp"); err != nil { + if err := vr.ensureElementValue(TypeTimestamp, 0, "ReadTimestamp"); err != nil { return 0, 0, err } @@ -680,7 +677,7 @@ func (vr *valueReader) ReadTimestamp() (t uint32, i uint32, err error) { } func (vr *valueReader) ReadUndefined() error { - if err := vr.ensureElementValue(bsontype.Undefined, 0, "ReadUndefined"); err != nil { + if err := vr.ensureElementValue(TypeUndefined, 0, "ReadUndefined"); err != nil { return err } @@ -714,7 +711,7 @@ func (vr *valueReader) ReadElement() (string, ValueReader, error) { return "", nil, err } - vr.pushElement(bsontype.Type(t)) + vr.pushElement(Type(t)) return name, vr, nil } @@ -743,7 +740,7 @@ func (vr *valueReader) ReadValue() (ValueReader, error) { return nil, err } - vr.pushValue(bsontype.Type(t)) + vr.pushValue(Type(t)) return vr, nil } diff --git a/bson/bsonrw/value_reader_test.go b/bson/value_reader_test.go similarity index 78% rename from bson/bsonrw/value_reader_test.go rename to bson/value_reader_test.go index 0617acf930..21d42e74db 100644 --- a/bson/bsonrw/value_reader_test.go +++ b/bson/value_reader_test.go @@ -4,7 +4,7 @@ // 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 bsonrw +package bson import ( "bytes" @@ -15,8 +15,7 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -29,7 +28,7 @@ func TestValueReader(t *testing.T) { btype byte b []byte err error - vType bsontype.Type + vType Type }{ { "incorrect type", @@ -37,8 +36,8 @@ func TestValueReader(t *testing.T) { 0, 0, nil, - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.Binary), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeBinary), + TypeEmbeddedDocument, }, { "length too short", @@ -47,7 +46,7 @@ func TestValueReader(t *testing.T) { 0, nil, io.EOF, - bsontype.Binary, + TypeBinary, }, { "no byte available", @@ -56,7 +55,7 @@ func TestValueReader(t *testing.T) { 0, nil, io.EOF, - bsontype.Binary, + TypeBinary, }, { "not enough bytes for binary", @@ -65,7 +64,7 @@ func TestValueReader(t *testing.T) { 0, nil, io.EOF, - bsontype.Binary, + TypeBinary, }, { "success", @@ -74,7 +73,7 @@ func TestValueReader(t *testing.T) { 0xEA, []byte{0x01, 0x02, 0x03}, nil, - bsontype.Binary, + TypeBinary, }, } @@ -113,15 +112,15 @@ func TestValueReader(t *testing.T) { offset int64 boolean bool err error - vType bsontype.Type + vType Type }{ { "incorrect type", []byte{}, 0, false, - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.Boolean), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeBoolean), + TypeEmbeddedDocument, }, { "no byte available", @@ -129,7 +128,7 @@ func TestValueReader(t *testing.T) { 0, false, io.EOF, - bsontype.Boolean, + TypeBoolean, }, { "invalid byte for boolean", @@ -137,7 +136,7 @@ func TestValueReader(t *testing.T) { 0, false, fmt.Errorf("invalid byte for boolean, %b", 0x03), - bsontype.Boolean, + TypeBoolean, }, { "success", @@ -145,7 +144,7 @@ func TestValueReader(t *testing.T) { 0, true, nil, - bsontype.Boolean, + TypeBoolean, }, } @@ -202,12 +201,12 @@ func TestValueReader(t *testing.T) { offset: 0, stack: []vrState{ {mode: mTopLevel}, - {mode: mElement, vType: bsontype.Boolean}, + {mode: mElement, vType: TypeBoolean}, }, frame: 1, } - var wanterr = (&valueReader{stack: []vrState{{mode: mElement, vType: bsontype.Boolean}}}).typeError(bsontype.EmbeddedDocument) + var wanterr = (&valueReader{stack: []vrState{{mode: mElement, vType: TypeBoolean}}}).typeError(TypeEmbeddedDocument) _, err := vr.ReadDocument() if err == nil || err.Error() != wanterr.Error() { t.Errorf("Incorrect returned error. got %v; want %v", err, wanterr) @@ -220,7 +219,7 @@ func TestValueReader(t *testing.T) { t.Errorf("Incorrect returned error. got %v; want %v", err, wanterr) } - vr.stack[1].mode, vr.stack[1].vType = mElement, bsontype.EmbeddedDocument + vr.stack[1].mode, vr.stack[1].vType = mElement, TypeEmbeddedDocument vr.d = []byte{0x0A, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00} vr.offset = 4 _, err = vr.ReadDocument() @@ -270,56 +269,56 @@ func TestValueReader(t *testing.T) { data []byte offset int64 err error - vType bsontype.Type + vType Type }{ { "incorrect type", []byte{}, 0, - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.CodeWithScope), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeCodeWithScope), + TypeEmbeddedDocument, }, { "total length not enough bytes", []byte{}, 0, io.EOF, - bsontype.CodeWithScope, + TypeCodeWithScope, }, { "string length not enough bytes", codeWithScope[:4], 0, io.EOF, - bsontype.CodeWithScope, + TypeCodeWithScope, }, { "not enough string bytes", codeWithScope[:8], 0, io.EOF, - bsontype.CodeWithScope, + TypeCodeWithScope, }, { "document length not enough bytes", codeWithScope[:12], 0, io.EOF, - bsontype.CodeWithScope, + TypeCodeWithScope, }, { "length mismatch", mismatchCodeWithScope, 0, fmt.Errorf("length of CodeWithScope does not match lengths of components; total: %d; components: %d", 17, 19), - bsontype.CodeWithScope, + TypeCodeWithScope, }, { "invalid strLength", invalidCodeWithScope, 0, fmt.Errorf("invalid string length: %d", 0), - bsontype.CodeWithScope, + TypeCodeWithScope, }, } @@ -354,7 +353,7 @@ func TestValueReader(t *testing.T) { d: doc, stack: []vrState{ {mode: mTopLevel}, - {mode: mElement, vType: bsontype.CodeWithScope}, + {mode: mElement, vType: TypeCodeWithScope}, }, frame: 1, } @@ -384,45 +383,45 @@ func TestValueReader(t *testing.T) { data []byte offset int64 ns string - oid primitive.ObjectID + oid ObjectID err error - vType bsontype.Type + vType Type }{ { "incorrect type", []byte{}, 0, "", - primitive.ObjectID{}, - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.DBPointer), - bsontype.EmbeddedDocument, + ObjectID{}, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeDBPointer), + TypeEmbeddedDocument, }, { "length too short", []byte{}, 0, "", - primitive.ObjectID{}, + ObjectID{}, io.EOF, - bsontype.DBPointer, + TypeDBPointer, }, { "not enough bytes for namespace", []byte{0x04, 0x00, 0x00, 0x00}, 0, "", - primitive.ObjectID{}, + ObjectID{}, io.EOF, - bsontype.DBPointer, + TypeDBPointer, }, { "not enough bytes for objectID", []byte{0x04, 0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00}, 0, "", - primitive.ObjectID{}, + ObjectID{}, io.EOF, - bsontype.DBPointer, + TypeDBPointer, }, { "success", @@ -432,9 +431,9 @@ func TestValueReader(t *testing.T) { }, 0, "foo", - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, nil, - bsontype.DBPointer, + TypeDBPointer, }, } @@ -473,15 +472,15 @@ func TestValueReader(t *testing.T) { offset int64 dt int64 err error - vType bsontype.Type + vType Type }{ { "incorrect type", []byte{}, 0, 0, - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.DateTime), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeDateTime), + TypeEmbeddedDocument, }, { "length too short", @@ -489,7 +488,7 @@ func TestValueReader(t *testing.T) { 0, 0, io.EOF, - bsontype.DateTime, + TypeDateTime, }, { "success", @@ -497,7 +496,7 @@ func TestValueReader(t *testing.T) { 0, 255, nil, - bsontype.DateTime, + TypeDateTime, }, } @@ -531,25 +530,25 @@ func TestValueReader(t *testing.T) { name string data []byte offset int64 - dc128 primitive.Decimal128 + dc128 Decimal128 err error - vType bsontype.Type + vType Type }{ { "incorrect type", []byte{}, 0, - primitive.Decimal128{}, - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.Decimal128), - bsontype.EmbeddedDocument, + Decimal128{}, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeDecimal128), + TypeEmbeddedDocument, }, { "length too short", []byte{}, 0, - primitive.Decimal128{}, + Decimal128{}, io.EOF, - bsontype.Decimal128, + TypeDecimal128, }, { "success", @@ -558,9 +557,9 @@ func TestValueReader(t *testing.T) { 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // High }, 0, - primitive.NewDecimal128(65280, 255), + NewDecimal128(65280, 255), nil, - bsontype.Decimal128, + TypeDecimal128, }, } @@ -601,15 +600,15 @@ func TestValueReader(t *testing.T) { offset int64 double float64 err error - vType bsontype.Type + vType Type }{ { "incorrect type", []byte{}, 0, 0, - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.Double), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeDouble), + TypeEmbeddedDocument, }, { "length too short", @@ -617,7 +616,7 @@ func TestValueReader(t *testing.T) { 0, 0, io.EOF, - bsontype.Double, + TypeDouble, }, { "success", @@ -625,7 +624,7 @@ func TestValueReader(t *testing.T) { 0, math.Float64frombits(255), nil, - bsontype.Double, + TypeDouble, }, } @@ -661,15 +660,15 @@ func TestValueReader(t *testing.T) { offset int64 i32 int32 err error - vType bsontype.Type + vType Type }{ { "incorrect type", []byte{}, 0, 0, - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.Int32), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeInt32), + TypeEmbeddedDocument, }, { "length too short", @@ -677,7 +676,7 @@ func TestValueReader(t *testing.T) { 0, 0, io.EOF, - bsontype.Int32, + TypeInt32, }, { "success", @@ -685,7 +684,7 @@ func TestValueReader(t *testing.T) { 0, 255, nil, - bsontype.Int32, + TypeInt32, }, } @@ -721,15 +720,15 @@ func TestValueReader(t *testing.T) { offset int64 i64 int64 err error - vType bsontype.Type + vType Type }{ { "incorrect type", []byte{}, 0, 0, - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.Int64), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeInt64), + TypeEmbeddedDocument, }, { "length too short", @@ -737,7 +736,7 @@ func TestValueReader(t *testing.T) { 0, 0, io.EOF, - bsontype.Int64, + TypeInt64, }, { "success", @@ -745,7 +744,7 @@ func TestValueReader(t *testing.T) { 0, 255, nil, - bsontype.Int64, + TypeInt64, }, } @@ -782,7 +781,7 @@ func TestValueReader(t *testing.T) { fn func(*valueReader) (string, error) css string // code, string, symbol :P err error - vType bsontype.Type + vType Type }{ { "ReadJavascript/incorrect type", @@ -790,8 +789,8 @@ func TestValueReader(t *testing.T) { 0, (*valueReader).ReadJavascript, "", - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.JavaScript), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeJavaScript), + TypeEmbeddedDocument, }, { "ReadString/incorrect type", @@ -799,8 +798,8 @@ func TestValueReader(t *testing.T) { 0, (*valueReader).ReadString, "", - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.String), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeString), + TypeEmbeddedDocument, }, { "ReadSymbol/incorrect type", @@ -808,8 +807,8 @@ func TestValueReader(t *testing.T) { 0, (*valueReader).ReadSymbol, "", - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.Symbol), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeSymbol), + TypeEmbeddedDocument, }, { "ReadJavascript/length too short", @@ -818,7 +817,7 @@ func TestValueReader(t *testing.T) { (*valueReader).ReadJavascript, "", io.EOF, - bsontype.JavaScript, + TypeJavaScript, }, { "ReadString/length too short", @@ -827,7 +826,7 @@ func TestValueReader(t *testing.T) { (*valueReader).ReadString, "", io.EOF, - bsontype.String, + TypeString, }, { "ReadSymbol/length too short", @@ -836,7 +835,7 @@ func TestValueReader(t *testing.T) { (*valueReader).ReadSymbol, "", io.EOF, - bsontype.Symbol, + TypeSymbol, }, { "ReadJavascript/incorrect end byte", @@ -845,7 +844,7 @@ func TestValueReader(t *testing.T) { (*valueReader).ReadJavascript, "", fmt.Errorf("string does not end with null byte, but with %v", 0x05), - bsontype.JavaScript, + TypeJavaScript, }, { "ReadString/incorrect end byte", @@ -854,7 +853,7 @@ func TestValueReader(t *testing.T) { (*valueReader).ReadString, "", fmt.Errorf("string does not end with null byte, but with %v", 0x05), - bsontype.String, + TypeString, }, { "ReadSymbol/incorrect end byte", @@ -863,7 +862,7 @@ func TestValueReader(t *testing.T) { (*valueReader).ReadSymbol, "", fmt.Errorf("string does not end with null byte, but with %v", 0x05), - bsontype.Symbol, + TypeSymbol, }, { "ReadJavascript/success", @@ -872,7 +871,7 @@ func TestValueReader(t *testing.T) { (*valueReader).ReadJavascript, "foo", nil, - bsontype.JavaScript, + TypeJavaScript, }, { "ReadString/success", @@ -881,7 +880,7 @@ func TestValueReader(t *testing.T) { (*valueReader).ReadString, "foo", nil, - bsontype.String, + TypeString, }, { "ReadSymbol/success", @@ -890,7 +889,7 @@ func TestValueReader(t *testing.T) { (*valueReader).ReadSymbol, "foo", nil, - bsontype.Symbol, + TypeSymbol, }, } @@ -924,55 +923,55 @@ func TestValueReader(t *testing.T) { name string fn func(*valueReader) error err error - vType bsontype.Type + vType Type }{ { "ReadMaxKey/incorrect type", (*valueReader).ReadMaxKey, - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.MaxKey), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeMaxKey), + TypeEmbeddedDocument, }, { "ReadMaxKey/success", (*valueReader).ReadMaxKey, nil, - bsontype.MaxKey, + TypeMaxKey, }, { "ReadMinKey/incorrect type", (*valueReader).ReadMinKey, - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.MinKey), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeMinKey), + TypeEmbeddedDocument, }, { "ReadMinKey/success", (*valueReader).ReadMinKey, nil, - bsontype.MinKey, + TypeMinKey, }, { "ReadNull/incorrect type", (*valueReader).ReadNull, - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.Null), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeNull), + TypeEmbeddedDocument, }, { "ReadNull/success", (*valueReader).ReadNull, nil, - bsontype.Null, + TypeNull, }, { "ReadUndefined/incorrect type", (*valueReader).ReadUndefined, - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.Undefined), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeUndefined), + TypeEmbeddedDocument, }, { "ReadUndefined/success", (*valueReader).ReadUndefined, nil, - bsontype.Undefined, + TypeUndefined, }, } @@ -1001,33 +1000,33 @@ func TestValueReader(t *testing.T) { name string data []byte offset int64 - oid primitive.ObjectID + oid ObjectID err error - vType bsontype.Type + vType Type }{ { "incorrect type", []byte{}, 0, - primitive.ObjectID{}, - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.ObjectID), - bsontype.EmbeddedDocument, + ObjectID{}, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeObjectID), + TypeEmbeddedDocument, }, { "not enough bytes for objectID", []byte{}, 0, - primitive.ObjectID{}, + ObjectID{}, io.EOF, - bsontype.ObjectID, + TypeObjectID, }, { "success", []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, 0, - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, nil, - bsontype.ObjectID, + TypeObjectID, }, } @@ -1064,7 +1063,7 @@ func TestValueReader(t *testing.T) { pattern string options string err error - vType bsontype.Type + vType Type }{ { "incorrect type", @@ -1072,8 +1071,8 @@ func TestValueReader(t *testing.T) { 0, "", "", - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.Regex), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeRegex), + TypeEmbeddedDocument, }, { "length too short", @@ -1082,7 +1081,7 @@ func TestValueReader(t *testing.T) { "", "", io.EOF, - bsontype.Regex, + TypeRegex, }, { "not enough bytes for options", @@ -1091,7 +1090,7 @@ func TestValueReader(t *testing.T) { "", "", io.EOF, - bsontype.Regex, + TypeRegex, }, { "success", @@ -1100,7 +1099,7 @@ func TestValueReader(t *testing.T) { "foo", "bar", nil, - bsontype.Regex, + TypeRegex, }, } @@ -1140,7 +1139,7 @@ func TestValueReader(t *testing.T) { ts uint32 incr uint32 err error - vType bsontype.Type + vType Type }{ { "incorrect type", @@ -1148,8 +1147,8 @@ func TestValueReader(t *testing.T) { 0, 0, 0, - (&valueReader{stack: []vrState{{vType: bsontype.EmbeddedDocument}}, frame: 0}).typeError(bsontype.Timestamp), - bsontype.EmbeddedDocument, + (&valueReader{stack: []vrState{{vType: TypeEmbeddedDocument}}, frame: 0}).typeError(TypeTimestamp), + TypeEmbeddedDocument, }, { "not enough bytes for increment", @@ -1158,7 +1157,7 @@ func TestValueReader(t *testing.T) { 0, 0, io.EOF, - bsontype.Timestamp, + TypeTimestamp, }, { "not enough bytes for timestamp", @@ -1167,7 +1166,7 @@ func TestValueReader(t *testing.T) { 0, 0, io.EOF, - bsontype.Timestamp, + TypeTimestamp, }, { "success", @@ -1176,7 +1175,7 @@ func TestValueReader(t *testing.T) { 256, 255, nil, - bsontype.Timestamp, + TypeTimestamp, }, } @@ -1218,7 +1217,7 @@ func TestValueReader(t *testing.T) { strbytes := []byte{0x04, 0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00} testCases := []struct { name string - t bsontype.Type + t Type data []byte err error offset int64 @@ -1226,176 +1225,176 @@ func TestValueReader(t *testing.T) { }{ { "Array/invalid length", - bsontype.Array, + TypeArray, []byte{0x01, 0x02, 0x03}, io.EOF, 0, 0, }, { "Array/not enough bytes", - bsontype.Array, + TypeArray, []byte{0x0F, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03}, io.EOF, 0, 0, }, { "Array/success", - bsontype.Array, + TypeArray, []byte{0x08, 0x00, 0x00, 0x00, 0x0A, '1', 0x00, 0x00}, nil, 8, 0, }, { "EmbeddedDocument/invalid length", - bsontype.EmbeddedDocument, + TypeEmbeddedDocument, []byte{0x01, 0x02, 0x03}, io.EOF, 0, 0, }, { "EmbeddedDocument/not enough bytes", - bsontype.EmbeddedDocument, + TypeEmbeddedDocument, []byte{0x0F, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03}, io.EOF, 0, 0, }, { "EmbeddedDocument/success", - bsontype.EmbeddedDocument, + TypeEmbeddedDocument, []byte{0x08, 0x00, 0x00, 0x00, 0x0A, 'A', 0x00, 0x00}, nil, 8, 0, }, { "CodeWithScope/invalid length", - bsontype.CodeWithScope, + TypeCodeWithScope, []byte{0x01, 0x02, 0x03}, io.EOF, 0, 0, }, { "CodeWithScope/not enough bytes", - bsontype.CodeWithScope, + TypeCodeWithScope, []byte{0x0F, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03}, io.EOF, 0, 0, }, { "CodeWithScope/success", - bsontype.CodeWithScope, + TypeCodeWithScope, cwsbytes, nil, 41, 0, }, { "Binary/invalid length", - bsontype.Binary, + TypeBinary, []byte{0x01, 0x02, 0x03}, io.EOF, 0, 0, }, { "Binary/not enough bytes", - bsontype.Binary, + TypeBinary, []byte{0x0F, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03}, io.EOF, 0, 0, }, { "Binary/success", - bsontype.Binary, + TypeBinary, []byte{0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03}, nil, 8, 0, }, { "Boolean/invalid length", - bsontype.Boolean, + TypeBoolean, []byte{}, io.EOF, 0, 0, }, { "Boolean/success", - bsontype.Boolean, + TypeBoolean, []byte{0x01}, nil, 1, 0, }, { "DBPointer/invalid length", - bsontype.DBPointer, + TypeDBPointer, []byte{0x01, 0x02, 0x03}, io.EOF, 0, 0, }, { "DBPointer/not enough bytes", - bsontype.DBPointer, + TypeDBPointer, []byte{0x0F, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03}, io.EOF, 0, 0, }, { "DBPointer/success", - bsontype.DBPointer, + TypeDBPointer, []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, nil, 17, 0, }, - {"DBPointer/not enough bytes", bsontype.DateTime, []byte{0x01, 0x02, 0x03, 0x04}, io.EOF, 0, 0}, - {"DBPointer/success", bsontype.DateTime, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, nil, 8, 0}, - {"Double/not enough bytes", bsontype.Double, []byte{0x01, 0x02, 0x03, 0x04}, io.EOF, 0, 0}, - {"Double/success", bsontype.Double, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, nil, 8, 0}, - {"Int64/not enough bytes", bsontype.Int64, []byte{0x01, 0x02, 0x03, 0x04}, io.EOF, 0, 0}, - {"Int64/success", bsontype.Int64, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, nil, 8, 0}, - {"Timestamp/not enough bytes", bsontype.Timestamp, []byte{0x01, 0x02, 0x03, 0x04}, io.EOF, 0, 0}, - {"Timestamp/success", bsontype.Timestamp, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, nil, 8, 0}, + {"DBPointer/not enough bytes", TypeDateTime, []byte{0x01, 0x02, 0x03, 0x04}, io.EOF, 0, 0}, + {"DBPointer/success", TypeDateTime, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, nil, 8, 0}, + {"Double/not enough bytes", TypeDouble, []byte{0x01, 0x02, 0x03, 0x04}, io.EOF, 0, 0}, + {"Double/success", TypeDouble, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, nil, 8, 0}, + {"Int64/not enough bytes", TypeInt64, []byte{0x01, 0x02, 0x03, 0x04}, io.EOF, 0, 0}, + {"Int64/success", TypeInt64, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, nil, 8, 0}, + {"Timestamp/not enough bytes", TypeTimestamp, []byte{0x01, 0x02, 0x03, 0x04}, io.EOF, 0, 0}, + {"Timestamp/success", TypeTimestamp, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, nil, 8, 0}, { "Decimal128/not enough bytes", - bsontype.Decimal128, + TypeDecimal128, []byte{0x01, 0x02, 0x03, 0x04}, io.EOF, 0, 0, }, { "Decimal128/success", - bsontype.Decimal128, + TypeDecimal128, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10}, nil, 16, 0, }, - {"Int32/not enough bytes", bsontype.Int32, []byte{0x01, 0x02}, io.EOF, 0, 0}, - {"Int32/success", bsontype.Int32, []byte{0x01, 0x02, 0x03, 0x04}, nil, 4, 0}, - {"Javascript/invalid length", bsontype.JavaScript, strbytes[:2], io.EOF, 0, 0}, - {"Javascript/not enough bytes", bsontype.JavaScript, strbytes[:5], io.EOF, 0, 0}, - {"Javascript/success", bsontype.JavaScript, strbytes, nil, 8, 0}, - {"String/invalid length", bsontype.String, strbytes[:2], io.EOF, 0, 0}, - {"String/not enough bytes", bsontype.String, strbytes[:5], io.EOF, 0, 0}, - {"String/success", bsontype.String, strbytes, nil, 8, 0}, - {"Symbol/invalid length", bsontype.Symbol, strbytes[:2], io.EOF, 0, 0}, - {"Symbol/not enough bytes", bsontype.Symbol, strbytes[:5], io.EOF, 0, 0}, - {"Symbol/success", bsontype.Symbol, strbytes, nil, 8, 0}, - {"MaxKey/success", bsontype.MaxKey, []byte{}, nil, 0, 0}, - {"MinKey/success", bsontype.MinKey, []byte{}, nil, 0, 0}, - {"Null/success", bsontype.Null, []byte{}, nil, 0, 0}, - {"Undefined/success", bsontype.Undefined, []byte{}, nil, 0, 0}, + {"Int32/not enough bytes", TypeInt32, []byte{0x01, 0x02}, io.EOF, 0, 0}, + {"Int32/success", TypeInt32, []byte{0x01, 0x02, 0x03, 0x04}, nil, 4, 0}, + {"Javascript/invalid length", TypeJavaScript, strbytes[:2], io.EOF, 0, 0}, + {"Javascript/not enough bytes", TypeJavaScript, strbytes[:5], io.EOF, 0, 0}, + {"Javascript/success", TypeJavaScript, strbytes, nil, 8, 0}, + {"String/invalid length", TypeString, strbytes[:2], io.EOF, 0, 0}, + {"String/not enough bytes", TypeString, strbytes[:5], io.EOF, 0, 0}, + {"String/success", TypeString, strbytes, nil, 8, 0}, + {"Symbol/invalid length", TypeSymbol, strbytes[:2], io.EOF, 0, 0}, + {"Symbol/not enough bytes", TypeSymbol, strbytes[:5], io.EOF, 0, 0}, + {"Symbol/success", TypeSymbol, strbytes, nil, 8, 0}, + {"MaxKey/success", TypeMaxKey, []byte{}, nil, 0, 0}, + {"MinKey/success", TypeMinKey, []byte{}, nil, 0, 0}, + {"Null/success", TypeNull, []byte{}, nil, 0, 0}, + {"Undefined/success", TypeUndefined, []byte{}, nil, 0, 0}, { "ObjectID/not enough bytes", - bsontype.ObjectID, + TypeObjectID, []byte{0x01, 0x02, 0x03, 0x04}, io.EOF, 0, 0, }, { "ObjectID/success", - bsontype.ObjectID, + TypeObjectID, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, nil, 12, 0, }, { "Regex/not enough bytes (first string)", - bsontype.Regex, + TypeRegex, []byte{'f', 'o', 'o'}, io.EOF, 0, 0, }, { "Regex/not enough bytes (second string)", - bsontype.Regex, + TypeRegex, []byte{'f', 'o', 'o', 0x00, 'b', 'a', 'r'}, io.EOF, 0, 0, }, { "Regex/success", - bsontype.Regex, + TypeRegex, []byte{0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00, 'i', 0x00}, nil, 9, 3, }, { "Unknown Type", - bsontype.Type(0), + Type(0), nil, - fmt.Errorf("attempted to read bytes of unknown BSON type %v", bsontype.Type(0)), 0, 0, + fmt.Errorf("attempted to read bytes of unknown BSON type %v", Type(0)), 0, 0, }, } @@ -1448,25 +1447,25 @@ func TestValueReader(t *testing.T) { testCases := []struct { name string want []byte - wantType bsontype.Type + wantType Type wantErr error }{ { "success", bsoncore.BuildDocument(nil, bsoncore.AppendDoubleElement(nil, "pi", 3.14159)), - bsontype.Type(0), + Type(0), nil, }, { "wrong length", []byte{0x01, 0x02, 0x03}, - bsontype.Type(0), + Type(0), io.EOF, }, { "append bytes", []byte{0x01, 0x02, 0x03, 0x04}, - bsontype.Type(0), + Type(0), io.EOF, }, } @@ -1502,7 +1501,7 @@ func TestValueReader(t *testing.T) { vr := &valueReader{stack: []vrState{{mode: mTopLevel}}} wanterr := (&valueReader{stack: []vrState{{mode: mTopLevel}}}).invalidTransitionErr(0, "Skip", []mode{mElement, mValue}) goterr := vr.Skip() - if !cmp.Equal(goterr, wanterr, cmp.Comparer(compareErrors)) { + if !cmp.Equal(goterr, wanterr, cmp.Comparer(assert.CompareErrors)) { t.Errorf("Expected correct invalid transition error. got %v; want %v", goterr, wanterr) } }) @@ -1512,7 +1511,7 @@ func TestValueReader(t *testing.T) { wanterr := (&valueReader{stack: []vrState{{mode: mTopLevel}, {mode: mDocument}}, frame: 1}). invalidTransitionErr(0, "ReadValueBytes", []mode{mElement, mValue}) _, _, goterr := vr.ReadValueBytes(nil) - if !cmp.Equal(goterr, wanterr, cmp.Comparer(compareErrors)) { + if !cmp.Equal(goterr, wanterr, cmp.Comparer(assert.CompareErrors)) { t.Errorf("Expected correct invalid transition error. got %v; want %v", goterr, wanterr) } }) diff --git a/bson/bsonrw/value_reader_writer_test.go b/bson/value_reader_writer_test.go similarity index 92% rename from bson/bsonrw/value_reader_writer_test.go rename to bson/value_reader_writer_test.go index 0f5d3a53dd..d5b3edb697 100644 --- a/bson/bsonrw/value_reader_writer_test.go +++ b/bson/value_reader_writer_test.go @@ -4,13 +4,11 @@ // 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 bsonrw +package bson import ( "testing" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -73,12 +71,12 @@ type TestValueReaderWriter struct { t *testing.T invoked VRWInvoked readval interface{} - bsontype bsontype.Type + bsontype Type err error errAfter VRWInvoked // error after this method is called } -func (llvrw *TestValueReaderWriter) Type() bsontype.Type { +func (llvrw *TestValueReaderWriter) Type() Type { return llvrw.bsontype } @@ -148,10 +146,10 @@ func (llvrw *TestValueReaderWriter) ReadCodeWithScope() (code string, dr Documen return "", llvrw, nil } -func (llvrw *TestValueReaderWriter) ReadDBPointer() (ns string, oid primitive.ObjectID, err error) { +func (llvrw *TestValueReaderWriter) ReadDBPointer() (ns string, oid ObjectID, err error) { llvrw.invoked = llvrwReadDBPointer if llvrw.errAfter == llvrw.invoked { - return "", primitive.ObjectID{}, llvrw.err + return "", ObjectID{}, llvrw.err } switch tt := llvrw.readval.(type) { @@ -159,12 +157,12 @@ func (llvrw *TestValueReaderWriter) ReadDBPointer() (ns string, oid primitive.Ob ns, oid, _, ok := bsoncore.ReadDBPointer(tt.Data) if !ok { llvrw.t.Error("Invalid Value instance provided for return value of ReadDBPointer") - return "", primitive.ObjectID{}, nil + return "", ObjectID{}, nil } return ns, oid, nil default: llvrw.t.Errorf("Incorrect type provided for return value of ReadDBPointer: %T", llvrw.readval) - return "", primitive.ObjectID{}, nil + return "", ObjectID{}, nil } } @@ -183,16 +181,16 @@ func (llvrw *TestValueReaderWriter) ReadDateTime() (int64, error) { return dt, nil } -func (llvrw *TestValueReaderWriter) ReadDecimal128() (primitive.Decimal128, error) { +func (llvrw *TestValueReaderWriter) ReadDecimal128() (Decimal128, error) { llvrw.invoked = llvrwReadDecimal128 if llvrw.errAfter == llvrw.invoked { - return primitive.Decimal128{}, llvrw.err + return Decimal128{}, llvrw.err } - d128, ok := llvrw.readval.(primitive.Decimal128) + d128, ok := llvrw.readval.(Decimal128) if !ok { llvrw.t.Errorf("Incorrect type provided for return value of ReadDecimal128: %T", llvrw.readval) - return primitive.Decimal128{}, nil + return Decimal128{}, nil } return d128, nil @@ -283,15 +281,15 @@ func (llvrw *TestValueReaderWriter) ReadNull() error { return nil } -func (llvrw *TestValueReaderWriter) ReadObjectID() (primitive.ObjectID, error) { +func (llvrw *TestValueReaderWriter) ReadObjectID() (ObjectID, error) { llvrw.invoked = llvrwReadObjectID if llvrw.errAfter == llvrw.invoked { - return primitive.ObjectID{}, llvrw.err + return ObjectID{}, llvrw.err } - oid, ok := llvrw.readval.(primitive.ObjectID) + oid, ok := llvrw.readval.(ObjectID) if !ok { llvrw.t.Errorf("Incorrect type provided for return value of ReadObjectID: %T", llvrw.readval) - return primitive.ObjectID{}, nil + return ObjectID{}, nil } return oid, nil @@ -417,7 +415,7 @@ func (llvrw *TestValueReaderWriter) WriteCodeWithScope(string) (DocumentWriter, return llvrw, nil } -func (llvrw *TestValueReaderWriter) WriteDBPointer(string, primitive.ObjectID) error { +func (llvrw *TestValueReaderWriter) WriteDBPointer(string, ObjectID) error { llvrw.invoked = llvrwWriteDBPointer if llvrw.errAfter == llvrw.invoked { return llvrw.err @@ -433,7 +431,7 @@ func (llvrw *TestValueReaderWriter) WriteDateTime(int64) error { return nil } -func (llvrw *TestValueReaderWriter) WriteDecimal128(primitive.Decimal128) error { +func (llvrw *TestValueReaderWriter) WriteDecimal128(Decimal128) error { llvrw.invoked = llvrwWriteDecimal128 if llvrw.errAfter == llvrw.invoked { return llvrw.err @@ -497,7 +495,7 @@ func (llvrw *TestValueReaderWriter) WriteNull() error { return nil } -func (llvrw *TestValueReaderWriter) WriteObjectID(primitive.ObjectID) error { +func (llvrw *TestValueReaderWriter) WriteObjectID(ObjectID) error { llvrw.invoked = llvrwWriteObjectID if llvrw.errAfter == llvrw.invoked { return llvrw.err diff --git a/bson/bsonrw/value_writer.go b/bson/value_writer.go similarity index 76% rename from bson/bsonrw/value_writer.go rename to bson/value_writer.go index c3f4adf2e9..4ae756d216 100644 --- a/bson/bsonrw/value_writer.go +++ b/bson/value_writer.go @@ -4,7 +4,7 @@ // 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 bsonrw +package bson import ( "errors" @@ -15,8 +15,6 @@ import ( "strings" "sync" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -35,18 +33,18 @@ func putValueWriter(vw *valueWriter) { } } -// BSONValueWriterPool is a pool for BSON ValueWriters. +// ValueWriterPool is a pool for BSON ValueWriters. // -// Deprecated: BSONValueWriterPool will not be supported in Go Driver 2.0. -type BSONValueWriterPool struct { +// Deprecated: ValueWriterPool will not be supported in Go Driver 2.0. +type ValueWriterPool struct { pool sync.Pool } -// NewBSONValueWriterPool creates a new pool for ValueWriter instances that write to BSON. +// NewValueWriterPool creates a new pool for ValueWriter instances that write to BSON. // -// Deprecated: BSONValueWriterPool will not be supported in Go Driver 2.0. -func NewBSONValueWriterPool() *BSONValueWriterPool { - return &BSONValueWriterPool{ +// Deprecated: ValueWriterPool will not be supported in Go Driver 2.0. +func NewValueWriterPool() *ValueWriterPool { + return &ValueWriterPool{ pool: sync.Pool{ New: func() interface{} { return new(valueWriter) @@ -57,8 +55,8 @@ func NewBSONValueWriterPool() *BSONValueWriterPool { // Get retrieves a BSON ValueWriter from the pool and resets it to use w as the destination. // -// Deprecated: BSONValueWriterPool will not be supported in Go Driver 2.0. -func (bvwp *BSONValueWriterPool) Get(w io.Writer) ValueWriter { +// Deprecated: ValueWriterPool will not be supported in Go Driver 2.0. +func (bvwp *ValueWriterPool) Get(w io.Writer) ValueWriter { vw := bvwp.pool.Get().(*valueWriter) // TODO: Having to call reset here with the same buffer doesn't really make sense. @@ -70,8 +68,8 @@ func (bvwp *BSONValueWriterPool) Get(w io.Writer) ValueWriter { // GetAtModeElement retrieves a ValueWriterFlusher from the pool and resets it to use w as the destination. // -// Deprecated: BSONValueWriterPool will not be supported in Go Driver 2.0. -func (bvwp *BSONValueWriterPool) GetAtModeElement(w io.Writer) ValueWriterFlusher { +// Deprecated: ValueWriterPool will not be supported in Go Driver 2.0. +func (bvwp *ValueWriterPool) GetAtModeElement(w io.Writer) ValueWriterFlusher { vw := bvwp.Get(w).(*valueWriter) vw.push(mElement) return vw @@ -80,8 +78,8 @@ func (bvwp *BSONValueWriterPool) GetAtModeElement(w io.Writer) ValueWriterFlushe // Put inserts a ValueWriter into the pool. If the ValueWriter is not a BSON ValueWriter, nothing // happens and ok will be false. // -// Deprecated: BSONValueWriterPool will not be supported in Go Driver 2.0. -func (bvwp *BSONValueWriterPool) Put(vw ValueWriter) (ok bool) { +// Deprecated: ValueWriterPool will not be supported in Go Driver 2.0. +func (bvwp *ValueWriterPool) Put(vw ValueWriter) (ok bool) { bvw, ok := vw.(*valueWriter) if !ok { return false @@ -240,7 +238,7 @@ func (vw *valueWriter) invalidTransitionError(destination mode, name string, mod return te } -func (vw *valueWriter) writeElementHeader(t bsontype.Type, destination mode, callerName string, addmodes ...mode) error { +func (vw *valueWriter) writeElementHeader(t Type, destination mode, callerName string, addmodes ...mode) error { frame := &vw.stack[vw.frame] switch frame.mode { case mElement: @@ -262,7 +260,7 @@ func (vw *valueWriter) writeElementHeader(t bsontype.Type, destination mode, cal return nil } -func (vw *valueWriter) WriteValueBytes(t bsontype.Type, b []byte) error { +func (vw *valueWriter) WriteValueBytes(t Type, b []byte) error { if err := vw.writeElementHeader(t, mode(0), "WriteValueBytes"); err != nil { return err } @@ -272,7 +270,7 @@ func (vw *valueWriter) WriteValueBytes(t bsontype.Type, b []byte) error { } func (vw *valueWriter) WriteArray() (ArrayWriter, error) { - if err := vw.writeElementHeader(bsontype.Array, mArray, "WriteArray"); err != nil { + if err := vw.writeElementHeader(TypeArray, mArray, "WriteArray"); err != nil { return nil, err } @@ -286,7 +284,7 @@ func (vw *valueWriter) WriteBinary(b []byte) error { } func (vw *valueWriter) WriteBinaryWithSubtype(b []byte, btype byte) error { - if err := vw.writeElementHeader(bsontype.Binary, mode(0), "WriteBinaryWithSubtype"); err != nil { + if err := vw.writeElementHeader(TypeBinary, mode(0), "WriteBinaryWithSubtype"); err != nil { return err } @@ -296,7 +294,7 @@ func (vw *valueWriter) WriteBinaryWithSubtype(b []byte, btype byte) error { } func (vw *valueWriter) WriteBoolean(b bool) error { - if err := vw.writeElementHeader(bsontype.Boolean, mode(0), "WriteBoolean"); err != nil { + if err := vw.writeElementHeader(TypeBoolean, mode(0), "WriteBoolean"); err != nil { return err } @@ -306,7 +304,7 @@ func (vw *valueWriter) WriteBoolean(b bool) error { } func (vw *valueWriter) WriteCodeWithScope(code string) (DocumentWriter, error) { - if err := vw.writeElementHeader(bsontype.CodeWithScope, mCodeWithScope, "WriteCodeWithScope"); err != nil { + if err := vw.writeElementHeader(TypeCodeWithScope, mCodeWithScope, "WriteCodeWithScope"); err != nil { return nil, err } @@ -322,8 +320,8 @@ func (vw *valueWriter) WriteCodeWithScope(code string) (DocumentWriter, error) { return vw, nil } -func (vw *valueWriter) WriteDBPointer(ns string, oid primitive.ObjectID) error { - if err := vw.writeElementHeader(bsontype.DBPointer, mode(0), "WriteDBPointer"); err != nil { +func (vw *valueWriter) WriteDBPointer(ns string, oid ObjectID) error { + if err := vw.writeElementHeader(TypeDBPointer, mode(0), "WriteDBPointer"); err != nil { return err } @@ -333,7 +331,7 @@ func (vw *valueWriter) WriteDBPointer(ns string, oid primitive.ObjectID) error { } func (vw *valueWriter) WriteDateTime(dt int64) error { - if err := vw.writeElementHeader(bsontype.DateTime, mode(0), "WriteDateTime"); err != nil { + if err := vw.writeElementHeader(TypeDateTime, mode(0), "WriteDateTime"); err != nil { return err } @@ -342,18 +340,19 @@ func (vw *valueWriter) WriteDateTime(dt int64) error { return nil } -func (vw *valueWriter) WriteDecimal128(d128 primitive.Decimal128) error { - if err := vw.writeElementHeader(bsontype.Decimal128, mode(0), "WriteDecimal128"); err != nil { +func (vw *valueWriter) WriteDecimal128(d128 Decimal128) error { + if err := vw.writeElementHeader(TypeDecimal128, mode(0), "WriteDecimal128"); err != nil { return err } - vw.buf = bsoncore.AppendDecimal128(vw.buf, d128) + h, l := d128.GetBytes() + vw.buf = bsoncore.AppendDecimal128(vw.buf, h, l) vw.pop() return nil } func (vw *valueWriter) WriteDouble(f float64) error { - if err := vw.writeElementHeader(bsontype.Double, mode(0), "WriteDouble"); err != nil { + if err := vw.writeElementHeader(TypeDouble, mode(0), "WriteDouble"); err != nil { return err } @@ -363,7 +362,7 @@ func (vw *valueWriter) WriteDouble(f float64) error { } func (vw *valueWriter) WriteInt32(i32 int32) error { - if err := vw.writeElementHeader(bsontype.Int32, mode(0), "WriteInt32"); err != nil { + if err := vw.writeElementHeader(TypeInt32, mode(0), "WriteInt32"); err != nil { return err } @@ -373,7 +372,7 @@ func (vw *valueWriter) WriteInt32(i32 int32) error { } func (vw *valueWriter) WriteInt64(i64 int64) error { - if err := vw.writeElementHeader(bsontype.Int64, mode(0), "WriteInt64"); err != nil { + if err := vw.writeElementHeader(TypeInt64, mode(0), "WriteInt64"); err != nil { return err } @@ -383,7 +382,7 @@ func (vw *valueWriter) WriteInt64(i64 int64) error { } func (vw *valueWriter) WriteJavascript(code string) error { - if err := vw.writeElementHeader(bsontype.JavaScript, mode(0), "WriteJavascript"); err != nil { + if err := vw.writeElementHeader(TypeJavaScript, mode(0), "WriteJavascript"); err != nil { return err } @@ -393,7 +392,7 @@ func (vw *valueWriter) WriteJavascript(code string) error { } func (vw *valueWriter) WriteMaxKey() error { - if err := vw.writeElementHeader(bsontype.MaxKey, mode(0), "WriteMaxKey"); err != nil { + if err := vw.writeElementHeader(TypeMaxKey, mode(0), "WriteMaxKey"); err != nil { return err } @@ -402,7 +401,7 @@ func (vw *valueWriter) WriteMaxKey() error { } func (vw *valueWriter) WriteMinKey() error { - if err := vw.writeElementHeader(bsontype.MinKey, mode(0), "WriteMinKey"); err != nil { + if err := vw.writeElementHeader(TypeMinKey, mode(0), "WriteMinKey"); err != nil { return err } @@ -411,7 +410,7 @@ func (vw *valueWriter) WriteMinKey() error { } func (vw *valueWriter) WriteNull() error { - if err := vw.writeElementHeader(bsontype.Null, mode(0), "WriteNull"); err != nil { + if err := vw.writeElementHeader(TypeNull, mode(0), "WriteNull"); err != nil { return err } @@ -419,8 +418,8 @@ func (vw *valueWriter) WriteNull() error { return nil } -func (vw *valueWriter) WriteObjectID(oid primitive.ObjectID) error { - if err := vw.writeElementHeader(bsontype.ObjectID, mode(0), "WriteObjectID"); err != nil { +func (vw *valueWriter) WriteObjectID(oid ObjectID) error { + if err := vw.writeElementHeader(TypeObjectID, mode(0), "WriteObjectID"); err != nil { return err } @@ -433,7 +432,7 @@ func (vw *valueWriter) WriteRegex(pattern string, options string) error { if !isValidCString(pattern) || !isValidCString(options) { return errors.New("BSON regex values cannot contain null bytes") } - if err := vw.writeElementHeader(bsontype.Regex, mode(0), "WriteRegex"); err != nil { + if err := vw.writeElementHeader(TypeRegex, mode(0), "WriteRegex"); err != nil { return err } @@ -443,7 +442,7 @@ func (vw *valueWriter) WriteRegex(pattern string, options string) error { } func (vw *valueWriter) WriteString(s string) error { - if err := vw.writeElementHeader(bsontype.String, mode(0), "WriteString"); err != nil { + if err := vw.writeElementHeader(TypeString, mode(0), "WriteString"); err != nil { return err } @@ -457,7 +456,7 @@ func (vw *valueWriter) WriteDocument() (DocumentWriter, error) { vw.reserveLength() return vw, nil } - if err := vw.writeElementHeader(bsontype.EmbeddedDocument, mDocument, "WriteDocument", mTopLevel); err != nil { + if err := vw.writeElementHeader(TypeEmbeddedDocument, mDocument, "WriteDocument", mTopLevel); err != nil { return nil, err } @@ -466,7 +465,7 @@ func (vw *valueWriter) WriteDocument() (DocumentWriter, error) { } func (vw *valueWriter) WriteSymbol(symbol string) error { - if err := vw.writeElementHeader(bsontype.Symbol, mode(0), "WriteSymbol"); err != nil { + if err := vw.writeElementHeader(TypeSymbol, mode(0), "WriteSymbol"); err != nil { return err } @@ -476,7 +475,7 @@ func (vw *valueWriter) WriteSymbol(symbol string) error { } func (vw *valueWriter) WriteTimestamp(t uint32, i uint32) error { - if err := vw.writeElementHeader(bsontype.Timestamp, mode(0), "WriteTimestamp"); err != nil { + if err := vw.writeElementHeader(TypeTimestamp, mode(0), "WriteTimestamp"); err != nil { return err } @@ -486,7 +485,7 @@ func (vw *valueWriter) WriteTimestamp(t uint32, i uint32) error { } func (vw *valueWriter) WriteUndefined() error { - if err := vw.writeElementHeader(bsontype.Undefined, mode(0), "WriteUndefined"); err != nil { + if err := vw.writeElementHeader(TypeUndefined, mode(0), "WriteUndefined"); err != nil { return err } @@ -622,14 +621,14 @@ func isValidCString(cs string) bool { // key is a valid C string since the caller has already checked for that. // // The caller of this function must check if key is a valid C string. -func (vw *valueWriter) appendHeader(t bsontype.Type, key string) { - vw.buf = bsoncore.AppendType(vw.buf, t) +func (vw *valueWriter) appendHeader(t Type, key string) { + vw.buf = bsoncore.AppendType(vw.buf, bsoncore.Type(t)) vw.buf = append(vw.buf, key...) vw.buf = append(vw.buf, 0x00) } -func (vw *valueWriter) appendIntHeader(t bsontype.Type, key int) { - vw.buf = bsoncore.AppendType(vw.buf, t) +func (vw *valueWriter) appendIntHeader(t Type, key int) { + vw.buf = bsoncore.AppendType(vw.buf, bsoncore.Type(t)) vw.buf = strconv.AppendInt(vw.buf, int64(key), 10) vw.buf = append(vw.buf, 0x00) } diff --git a/bson/bsonrw/value_writer_test.go b/bson/value_writer_test.go similarity index 92% rename from bson/bsonrw/value_writer_test.go rename to bson/value_writer_test.go index 486efe1470..99e3b7d1dc 100644 --- a/bson/bsonrw/value_writer_test.go +++ b/bson/value_writer_test.go @@ -4,7 +4,7 @@ // 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 bsonrw +package bson import ( "bytes" @@ -16,8 +16,7 @@ import ( "strings" "testing" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -30,7 +29,7 @@ func TestNewValueWriter(t *testing.T) { func TestValueWriter(t *testing.T) { header := []byte{0x00, 0x00, 0x00, 0x00} - oid := primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C} + oid := ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C} testCases := []struct { name string fn interface{} @@ -76,8 +75,8 @@ func TestValueWriter(t *testing.T) { { "WriteDecimal128", (*valueWriter).WriteDecimal128, - []interface{}{primitive.NewDecimal128(10, 20)}, - bsoncore.AppendDecimal128Element(header, "foo", primitive.NewDecimal128(10, 20)), + []interface{}{NewDecimal128(10, 20)}, + bsoncore.AppendDecimal128Element(header, "foo", 10, 20), }, { "WriteDouble", @@ -205,7 +204,7 @@ func TestValueWriter(t *testing.T) { } want := TransitionError{current: mTopLevel, name: fnName, modes: []mode{mElement, mValue}, action: "write"} - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Errors do not match. got %v; want %v", got, want) } }) @@ -218,7 +217,7 @@ func TestValueWriter(t *testing.T) { want := TransitionError{current: mArray, destination: mArray, parent: mTopLevel, name: "WriteArray", modes: []mode{mElement, mValue}, action: "write"} _, got := vw.WriteArray() - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -228,7 +227,7 @@ func TestValueWriter(t *testing.T) { want := TransitionError{current: mArray, destination: mCodeWithScope, parent: mTopLevel, name: "WriteCodeWithScope", modes: []mode{mElement, mValue}, action: "write"} _, got := vw.WriteCodeWithScope("") - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -238,7 +237,7 @@ func TestValueWriter(t *testing.T) { want := TransitionError{current: mArray, destination: mDocument, parent: mTopLevel, name: "WriteDocument", modes: []mode{mElement, mValue, mTopLevel}, action: "write"} _, got := vw.WriteDocument() - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -252,7 +251,7 @@ func TestValueWriter(t *testing.T) { modes: []mode{mTopLevel, mDocument}, action: "write"} _, got := vw.WriteDocumentElement("") - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -261,7 +260,7 @@ func TestValueWriter(t *testing.T) { vw.push(mElement) want := fmt.Errorf("incorrect mode to end document: %s", mElement) got := vw.WriteDocumentEnd() - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } vw.pop() @@ -269,14 +268,14 @@ func TestValueWriter(t *testing.T) { maxSize = 512 want = errMaxDocumentSizeExceeded{size: 1024} got = vw.WriteDocumentEnd() - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } maxSize = math.MaxInt32 want = errors.New("what a nice fake error we have here") vw.w = errWriter{err: want} got = vw.WriteDocumentEnd() - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -290,7 +289,7 @@ func TestValueWriter(t *testing.T) { modes: []mode{mArray}, action: "write"} _, got := vw.WriteArrayElement() - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -299,7 +298,7 @@ func TestValueWriter(t *testing.T) { vw.push(mElement) want := fmt.Errorf("incorrect mode to end array: %s", mElement) got := vw.WriteArrayEnd() - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } vw.push(mArray) @@ -307,7 +306,7 @@ func TestValueWriter(t *testing.T) { maxSize = 512 want = errMaxDocumentSizeExceeded{size: 1024} got = vw.WriteArrayEnd() - if !compareErrors(got, want) { + if !assert.CompareErrors(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } maxSize = math.MaxInt32 @@ -318,8 +317,8 @@ func TestValueWriter(t *testing.T) { vw := newValueWriterFromSlice(nil) want := TransitionError{current: mTopLevel, destination: mode(0), name: "WriteValueBytes", modes: []mode{mElement, mValue}, action: "write"} - got := vw.WriteValueBytes(bsontype.EmbeddedDocument, nil) - if !compareErrors(got, want) { + got := vw.WriteValueBytes(TypeEmbeddedDocument, nil) + if !assert.CompareErrors(got, want) { t.Errorf("Did not received expected error. got %v; want %v", got, want) } }) @@ -339,7 +338,7 @@ func TestValueWriter(t *testing.T) { noerr(t, err) _, err = vw.WriteDocumentElement("foo") noerr(t, err) - err = vw.WriteValueBytes(bsontype.EmbeddedDocument, doc) + err = vw.WriteValueBytes(TypeEmbeddedDocument, doc) noerr(t, err) err = vw.WriteDocumentEnd() noerr(t, err) diff --git a/bson/bsonrw/writer.go b/bson/writer.go similarity index 89% rename from bson/bsonrw/writer.go rename to bson/writer.go index 628f452932..08ff44e466 100644 --- a/bson/bsonrw/writer.go +++ b/bson/writer.go @@ -4,12 +4,7 @@ // 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 bsonrw - -import ( - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" -) +package bson // ArrayWriter is the interface used to create a BSON or BSON adjacent array. // Callers must ensure they call WriteArrayEnd when they have finished creating @@ -36,9 +31,9 @@ type ValueWriter interface { WriteBinaryWithSubtype(b []byte, btype byte) error WriteBoolean(bool) error WriteCodeWithScope(code string) (DocumentWriter, error) - WriteDBPointer(ns string, oid primitive.ObjectID) error + WriteDBPointer(ns string, oid ObjectID) error WriteDateTime(dt int64) error - WriteDecimal128(primitive.Decimal128) error + WriteDecimal128(Decimal128) error WriteDouble(float64) error WriteInt32(int32) error WriteInt64(int64) error @@ -46,7 +41,7 @@ type ValueWriter interface { WriteMaxKey() error WriteMinKey() error WriteNull() error - WriteObjectID(primitive.ObjectID) error + WriteObjectID(ObjectID) error WriteRegex(pattern, options string) error WriteString(string) error WriteDocument() (DocumentWriter, error) @@ -69,7 +64,7 @@ type ValueWriterFlusher interface { // // Deprecated: BytesWriter will not be supported in Go Driver 2.0. type BytesWriter interface { - WriteValueBytes(t bsontype.Type, b []byte) error + WriteValueBytes(t Type, b []byte) error } // SliceWriter allows a pointer to a slice of bytes to be used as an io.Writer. diff --git a/event/monitoring.go b/event/monitoring.go index e064ee0e57..f51ed70559 100644 --- a/event/monitoring.go +++ b/event/monitoring.go @@ -11,7 +11,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo/address" "go.mongodb.org/mongo-driver/mongo/description" ) @@ -28,7 +27,7 @@ type CommandStartedEvent struct { ServerConnectionID *int64 // ServiceID contains the ID of the server to which the command was sent if it is running behind a load balancer. // Otherwise, it is unset. - ServiceID *primitive.ObjectID + ServiceID *bson.ObjectID } // CommandFinishedEvent represents a generic command finishing. @@ -43,7 +42,7 @@ type CommandFinishedEvent struct { ServerConnectionID *int64 // ServiceID contains the ID of the server to which the command was sent if it is running behind a load balancer. // Otherwise, it is unset. - ServiceID *primitive.ObjectID + ServiceID *bson.ObjectID } // CommandSucceededEvent represents an event generated when a command's execution succeeds. @@ -106,9 +105,9 @@ type PoolEvent struct { Reason string `json:"reason"` // ServiceID is only set if the Type is PoolCleared and the server is deployed behind a load balancer. This field // can be used to distinguish between individual servers in a load balanced deployment. - ServiceID *primitive.ObjectID `json:"serviceId"` - Interruption bool `json:"interruptInUseConnections"` - Error error `json:"error"` + ServiceID *bson.ObjectID `json:"serviceId"` + Interruption bool `json:"interruptInUseConnections"` + Error error `json:"error"` } // PoolMonitor is a function that allows the user to gain access to events occurring in the pool @@ -119,7 +118,7 @@ type PoolMonitor struct { // ServerDescriptionChangedEvent represents a server description change. type ServerDescriptionChangedEvent struct { Address address.Address - TopologyID primitive.ObjectID // A unique identifier for the topology this server is a part of + TopologyID bson.ObjectID // A unique identifier for the topology this server is a part of PreviousDescription description.Server NewDescription description.Server } @@ -127,30 +126,30 @@ type ServerDescriptionChangedEvent struct { // ServerOpeningEvent is an event generated when the server is initialized. type ServerOpeningEvent struct { Address address.Address - TopologyID primitive.ObjectID // A unique identifier for the topology this server is a part of + TopologyID bson.ObjectID // A unique identifier for the topology this server is a part of } // ServerClosedEvent is an event generated when the server is closed. type ServerClosedEvent struct { Address address.Address - TopologyID primitive.ObjectID // A unique identifier for the topology this server is a part of + TopologyID bson.ObjectID // A unique identifier for the topology this server is a part of } // TopologyDescriptionChangedEvent represents a topology description change. type TopologyDescriptionChangedEvent struct { - TopologyID primitive.ObjectID // A unique identifier for the topology this server is a part of + TopologyID bson.ObjectID // A unique identifier for the topology this server is a part of PreviousDescription description.Topology NewDescription description.Topology } // TopologyOpeningEvent is an event generated when the topology is initialized. type TopologyOpeningEvent struct { - TopologyID primitive.ObjectID // A unique identifier for the topology this server is a part of + TopologyID bson.ObjectID // A unique identifier for the topology this server is a part of } // TopologyClosedEvent is an event generated when the topology is closed. type TopologyClosedEvent struct { - TopologyID primitive.ObjectID // A unique identifier for the topology this server is a part of + TopologyID bson.ObjectID // A unique identifier for the topology this server is a part of } // ServerHeartbeatStartedEvent is an event generated when the heartbeat is started. diff --git a/internal/assert/assertion_compare.go b/internal/assert/assertion_compare.go index b7b7249874..0a8307d573 100644 --- a/internal/assert/assertion_compare.go +++ b/internal/assert/assertion_compare.go @@ -462,3 +462,20 @@ func containsValue(values []CompareType, value CompareType) bool { return false } + +// CompareErrors asserts two errors +func CompareErrors(err1, err2 error) bool { + if err1 == nil && err2 == nil { + return true + } + + if err1 == nil || err2 == nil { + return false + } + + if err1.Error() != err2.Error() { + return false + } + + return true +} diff --git a/internal/benchmark/bson_map.go b/internal/benchmark/bson_map.go index c42af6a263..92bf2640b3 100644 --- a/internal/benchmark/bson_map.go +++ b/internal/benchmark/bson_map.go @@ -13,7 +13,6 @@ import ( "fmt" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsonrw" ) func bsonMapDecoding(tm TimerManager, iters int, dataSet string) error { @@ -53,7 +52,7 @@ func bsonMapEncoding(tm TimerManager, iters int, dataSet string) error { buf := new(bytes.Buffer) for i := 0; i < iters; i++ { buf.Reset() - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) err = bson.NewEncoder(vw).Encode(doc) if err != nil { return err diff --git a/internal/benchmark/bson_struct.go b/internal/benchmark/bson_struct.go index 8c26393d7f..eb6677f5f9 100644 --- a/internal/benchmark/bson_struct.go +++ b/internal/benchmark/bson_struct.go @@ -12,7 +12,6 @@ import ( "errors" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsonrw" ) func BSONFlatStructDecoding(_ context.Context, tm TimerManager, iters int) error { @@ -77,7 +76,7 @@ func BSONFlatStructTagsEncoding(_ context.Context, tm TimerManager, iters int) e tm.ResetTimer() for i := 0; i < iters; i++ { buf.Reset() - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) err = bson.NewEncoder(vw).Encode(doc) if err != nil { return err diff --git a/internal/benchmark/bson_types.go b/internal/benchmark/bson_types.go index 9d46cbcb03..3502af23cd 100644 --- a/internal/benchmark/bson_types.go +++ b/internal/benchmark/bson_types.go @@ -6,10 +6,12 @@ package benchmark -import "go.mongodb.org/mongo-driver/bson/primitive" +import ( + "go.mongodb.org/mongo-driver/bson" +) type flatBSONTags struct { - ID primitive.ObjectID `bson:"_id"` + ID bson.ObjectID `bson:"_id"` AA int64 `bson:"AAgSNVyBb"` AI bool `bson:"aicoMxZq"` @@ -233,7 +235,7 @@ type flatBSON struct { XxvXmHiQ int YDHWnEXV string ZmtEJFSO string - ID primitive.ObjectID `bson:"_id"` + ID bson.ObjectID `bson:"_id"` AhFCBmqT int64 AicoMxZq bool BkuaZWRT int64 diff --git a/internal/cmd/testkms/main.go b/internal/cmd/testkms/main.go index 2151201d33..3e83072e1e 100644 --- a/internal/cmd/testkms/main.go +++ b/internal/cmd/testkms/main.go @@ -13,12 +13,11 @@ import ( "strings" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) -var datakeyopts = map[string]primitive.M{ +var datakeyopts = map[string]bson.M{ "aws": bson.M{ "region": "us-east-1", "key": "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0", diff --git a/internal/codecutil/encoding_test.go b/internal/codecutil/encoding_test.go index d936f35202..adbb2e5363 100644 --- a/internal/codecutil/encoding_test.go +++ b/internal/codecutil/encoding_test.go @@ -11,8 +11,6 @@ import ( "testing" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" "go.mongodb.org/mongo-driver/internal/assert" ) @@ -20,7 +18,7 @@ func testEncFn(t *testing.T) EncoderFn { t.Helper() return func(w io.Writer) (*bson.Encoder, error) { - rw := bsonrw.NewValueWriter(w) + rw := bson.NewValueWriter(w) enc := bson.NewEncoder(rw) return enc, nil @@ -33,7 +31,7 @@ func TestMarshalValue(t *testing.T) { tests := []struct { name string val interface{} - registry *bsoncodec.Registry + registry *bson.Registry encFn EncoderFn want string wantErr error diff --git a/internal/decimal128/decinal128.go b/internal/decimal128/decinal128.go new file mode 100644 index 0000000000..337ed366ae --- /dev/null +++ b/internal/decimal128/decinal128.go @@ -0,0 +1,118 @@ +// 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 decimal128 + +import ( + "strconv" +) + +// These constants are the maximum and minimum values for the exponent field in a decimal128 value. +const ( + MaxDecimal128Exp = 6111 + MinDecimal128Exp = -6176 +) + +func divmod(h, l uint64, div uint32) (qh, ql uint64, rem uint32) { + div64 := uint64(div) + a := h >> 32 + aq := a / div64 + ar := a % div64 + b := ar<<32 + h&(1<<32-1) + bq := b / div64 + br := b % div64 + c := br<<32 + l>>32 + cq := c / div64 + cr := c % div64 + d := cr<<32 + l&(1<<32-1) + dq := d / div64 + dr := d % div64 + return (aq<<32 | bq), (cq<<32 | dq), uint32(dr) +} + +// String returns a string representation of the decimal value. +func String(h, l uint64) string { + var posSign int // positive sign + var exp int // exponent + var high, low uint64 // significand high/low + + if h>>63&1 == 0 { + posSign = 1 + } + + switch h >> 58 & (1<<5 - 1) { + case 0x1F: + return "NaN" + case 0x1E: + return "-Infinity"[posSign:] + } + + low = l + if h>>61&3 == 3 { + // Bits: 1*sign 2*ignored 14*exponent 111*significand. + // Implicit 0b100 prefix in significand. + exp = int(h >> 47 & (1<<14 - 1)) + //high = 4<<47 | d.h&(1<<47-1) + // Spec says all of these values are out of range. + high, low = 0, 0 + } else { + // Bits: 1*sign 14*exponent 113*significand + exp = int(h >> 49 & (1<<14 - 1)) + high = h & (1<<49 - 1) + } + exp += MinDecimal128Exp + + // Would be handled by the logic below, but that's trivial and common. + if high == 0 && low == 0 && exp == 0 { + return "-0"[posSign:] + } + + var repr [48]byte // Loop 5 times over 9 digits plus dot, negative sign, and leading zero. + var last = len(repr) + var i = len(repr) + var dot = len(repr) + exp + var rem uint32 +Loop: + for d9 := 0; d9 < 5; d9++ { + high, low, rem = divmod(high, low, 1e9) + for d1 := 0; d1 < 9; d1++ { + // Handle "-0.0", "0.00123400", "-1.00E-6", "1.050E+3", etc. + if i < len(repr) && (dot == i || low == 0 && high == 0 && rem > 0 && rem < 10 && (dot < i-6 || exp > 0)) { + exp += len(repr) - i + i-- + repr[i] = '.' + last = i - 1 + dot = len(repr) // Unmark. + } + c := '0' + byte(rem%10) + rem /= 10 + i-- + repr[i] = c + // Handle "0E+3", "1E+3", etc. + if low == 0 && high == 0 && rem == 0 && i == len(repr)-1 && (dot < i-5 || exp > 0) { + last = i + break Loop + } + if c != '0' { + last = i + } + // Break early. Works without it, but why. + if dot > i && low == 0 && high == 0 && rem == 0 { + break Loop + } + } + } + repr[last-1] = '-' + last-- + + if exp > 0 { + return string(repr[last+posSign:]) + "E+" + strconv.Itoa(exp) + } + if exp < 0 { + return string(repr[last+posSign:]) + "E" + strconv.Itoa(exp) + } + return string(repr[last+posSign:]) +} diff --git a/internal/docexamples/examples.go b/internal/docexamples/examples.go index b08447c15c..df1ccae692 100644 --- a/internal/docexamples/examples.go +++ b/internal/docexamples/examples.go @@ -17,7 +17,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/integration/mtest" "go.mongodb.org/mongo-driver/mongo" @@ -296,7 +295,7 @@ func QueryToplevelFieldsExamples(t *testing.T, db *mongo.Database) { {"status", "A"}, {"$or", bson.A{ bson.D{{"qty", bson.D{{"$lt", 30}}}}, - bson.D{{"item", primitive.Regex{Pattern: "^p", Options: ""}}}, + bson.D{{"item", bson.Regex{Pattern: "^p", Options: ""}}}, }}, }) diff --git a/internal/integration/causal_consistency_test.go b/internal/integration/causal_consistency_test.go index 33581c538a..f48c5b75b7 100644 --- a/internal/integration/causal_consistency_test.go +++ b/internal/integration/causal_consistency_test.go @@ -11,7 +11,6 @@ import ( "testing" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/integration/mtest" "go.mongodb.org/mongo-driver/mongo" @@ -66,7 +65,7 @@ func TestCausalConsistency_Supported(t *testing.T) { evt := mt.GetSucceededEvent() assert.Equal(mt, "find", evt.CommandName, "expected 'find' event, got '%v'", evt.CommandName) serverT, serverI := evt.Reply.Lookup("operationTime").Timestamp() - serverTs := &primitive.Timestamp{serverT, serverI} + serverTs := &bson.Timestamp{serverT, serverI} sessionTs := sess.OperationTime() assert.NotNil(mt, sessionTs, "expected session operation time, got nil") assert.True(mt, serverTs.Equal(*sessionTs), "expected operation time %v, got %v", serverTs, sessionTs) @@ -247,7 +246,7 @@ func checkOperationTime(mt *mtest.T, cmd bson.Raw, shouldInclude bool) { assert.Nil(mt, optime, "did not expect operation time, got %v", optime) } -func getReadConcernFields(mt *mtest.T, cmd bson.Raw) (string, *primitive.Timestamp) { +func getReadConcernFields(mt *mtest.T, cmd bson.Raw) (string, *bson.Timestamp) { mt.Helper() rc, err := cmd.LookupErr("readConcern") @@ -257,14 +256,14 @@ func getReadConcernFields(mt *mtest.T, cmd bson.Raw) (string, *primitive.Timesta rcDoc := rc.Document() var level string - var clusterTime *primitive.Timestamp + var clusterTime *bson.Timestamp if levelVal, err := rcDoc.LookupErr("level"); err == nil { level = levelVal.StringValue() } if ctVal, err := rcDoc.LookupErr("afterClusterTime"); err == nil { t, i := ctVal.Timestamp() - clusterTime = &primitive.Timestamp{t, i} + clusterTime = &bson.Timestamp{t, i} } return level, clusterTime } diff --git a/internal/integration/change_stream_test.go b/internal/integration/change_stream_test.go index ee5670e2bb..ca3e14041d 100644 --- a/internal/integration/change_stream_test.go +++ b/internal/integration/change_stream_test.go @@ -14,7 +14,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/eventtest" @@ -836,7 +835,7 @@ func killChangeStreamCursor(mt *mtest.T, cs *mongo.ChangeStream) { } // returns pbrt, operationTime from aggregate command response -func getAggregateResponseInfo(mt *mtest.T) (bson.Raw, primitive.Timestamp) { +func getAggregateResponseInfo(mt *mtest.T) (bson.Raw, bson.Timestamp) { mt.Helper() succeeded := mt.GetSucceededEvent() @@ -845,7 +844,7 @@ func getAggregateResponseInfo(mt *mtest.T) (bson.Raw, primitive.Timestamp) { pbrt := succeeded.Reply.Lookup("cursor", "postBatchResumeToken").Document() optimeT, optimeI := succeeded.Reply.Lookup("operationTime").Timestamp() - return pbrt, primitive.Timestamp{T: optimeT, I: optimeI} + return pbrt, bson.Timestamp{T: optimeT, I: optimeI} } func compareResumeTokens(mt *mtest.T, cs *mongo.ChangeStream, expected bson.Raw) { diff --git a/internal/integration/client_side_encryption_prose_test.go b/internal/integration/client_side_encryption_prose_test.go index 599e0d1e8f..ff83ccbb60 100644 --- a/internal/integration/client_side_encryption_prose_test.go +++ b/internal/integration/client_side_encryption_prose_test.go @@ -25,9 +25,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/handshake" @@ -166,7 +163,7 @@ func TestClientSideEncryptionProse(t *testing.T) { `UpAuNnkUhnIXM3PjrA==` empty = [16]byte{} - keyid := primitive.Binary{Subtype: 0x04, Data: empty[:]} + keyid := bson.Binary{Subtype: 0x04, Data: empty[:]} encOpts := options.Encrypt().SetAlgorithm(deterministicAlgorithm).SetKeyID(keyid) testVal := bson.RawValue{ @@ -176,7 +173,7 @@ func TestClientSideEncryptionProse(t *testing.T) { actual, err := cse.clientEnc.Encrypt(context.Background(), testVal, encOpts) assert.Nil(mt, err, "error encrypting data: %v", err) - expected := primitive.Binary{Subtype: 0x06} + expected := bson.Binary{Subtype: 0x06} expected.Data, _ = base64.StdEncoding.DecodeString(b642) assert.Equal(t, actual, expected, "expected: %v, got: %v", actual, expected) @@ -367,7 +364,7 @@ func TestClientSideEncryptionProse(t *testing.T) { _, err := cpt.keyVaultColl.InsertOne(context.Background(), key) assert.Nil(mt, err, "InsertOne error for data key: %v", err) subtype, data := key.Lookup("_id").Binary() - dataKeyID := primitive.Binary{Subtype: subtype, Data: data} + dataKeyID := bson.Binary{Subtype: subtype, Data: data} doc := bson.D{{"encrypted", "test"}} _, insertErr := cpt.cseClient.Database("db").Collection("coll").InsertOne(context.Background(), doc) @@ -656,7 +653,7 @@ func TestClientSideEncryptionProse(t *testing.T) { keyIDBytes, err := base64.StdEncoding.DecodeString(keyID) assert.Nil(mt, err, "base64 DecodeString error: %v", err) - eo.SetKeyID(primitive.Binary{Subtype: 4, Data: keyIDBytes}) + eo.SetKeyID(bson.Binary{Subtype: 4, Data: keyIDBytes}) case "altname": eo.SetKeyAltName(kms) // alt name for a key is the same as the KMS name default: @@ -739,10 +736,10 @@ func TestClientSideEncryptionProse(t *testing.T) { // if allowed is true, decrypt both values with clientEnc and validate equality if allowed { sub, data := expectedVal.Binary() - expectedDecrypted, err := cpt.clientEnc.Decrypt(context.Background(), primitive.Binary{Subtype: sub, Data: data}) + expectedDecrypted, err := cpt.clientEnc.Decrypt(context.Background(), bson.Binary{Subtype: sub, Data: data}) assert.Nil(mt, err, "Decrypt error: %v", err) sub, data = foundVal.Binary() - actualDecrypted, err := cpt.clientEnc.Decrypt(context.Background(), primitive.Binary{Subtype: sub, Data: data}) + actualDecrypted, err := cpt.clientEnc.Decrypt(context.Background(), bson.Binary{Subtype: sub, Data: data}) assert.Nil(mt, err, "Decrypt error: %v", err) assert.True(mt, expectedDecrypted.Equal(actualDecrypted), @@ -1675,10 +1672,10 @@ func TestClientSideEncryptionProse(t *testing.T) { // Test Setup ... begin encryptedFields := readJSONFile(mt, "encrypted-fields.json") key1Document := readJSONFile(mt, "key1-document.json") - var key1ID primitive.Binary + var key1ID bson.Binary { subtype, data := key1Document.Lookup("_id").Binary() - key1ID = primitive.Binary{Subtype: subtype, Data: data} + key1ID = bson.Binary{Subtype: subtype, Data: data} } testSetup := func() (*mongo.Client, *mongo.ClientEncryption) { @@ -1866,7 +1863,7 @@ func TestClientSideEncryptionProse(t *testing.T) { var cse *cseProseTest - var initialize = func() primitive.Binary { + var initialize = func() bson.Binary { // Create a ClientEncryption object (referred to as client_encryption) with client set as the keyVaultClient. // Using client, drop the collection keyvault.datakeys. cse = setup(mt, nil, defaultKvClientOptions, options.ClientEncryption(). @@ -1910,7 +1907,7 @@ func TestClientSideEncryptionProse(t *testing.T) { resbytes, err := res.Raw() assert.Nil(mt, err, "error decoding result bytes: %v", err) - idsubtype, iddata := bson.RawValue{Type: bsontype.EmbeddedDocument, Value: resbytes}. + idsubtype, iddata := bson.RawValue{Type: bson.TypeEmbeddedDocument, Value: resbytes}. Document().Lookup("_id").Binary() filter := bsoncore.NewDocumentBuilder().AppendBinary("_id", idsubtype, iddata).Build() @@ -1918,7 +1915,7 @@ func TestClientSideEncryptionProse(t *testing.T) { updatedData, err := cse.keyVaultColl.FindOne(ctx, filter).Raw() assert.Nil(mt, err, "error decoding result bytes: %v", err) - updated := bson.RawValue{Type: bsontype.EmbeddedDocument, Value: updatedData} + updated := bson.RawValue{Type: bson.TypeEmbeddedDocument, Value: updatedData} updatedKeyAltNames, err := updated.Document().Lookup("keyAltNames").Array().Values() assert.Nil(mt, err, "error looking up raw keyAltNames: %v", err) assert.Equal(mt, len(updatedKeyAltNames), len(expected), "expected raw keyAltNames length to be 1") @@ -1961,7 +1958,7 @@ func TestClientSideEncryptionProse(t *testing.T) { mt.Run("case 2: addKeyAltName()", func(t *mtest.T) { defKeyID := initialize() - var someNewKeyID primitive.Binary + var someNewKeyID bson.Binary // Use client_encryption to create a new local data key and assert the operation does not fail. var err error someNewKeyID, err = cse.clientEnc.CreateDataKey(context.Background(), "local") @@ -2057,7 +2054,7 @@ func TestClientSideEncryptionProse(t *testing.T) { } // Call ``clientEncryption1.createDataKey``. - var keyID primitive.Binary + var keyID bson.Binary { dkOpts := options.DataKey() if val, ok := dataKeyMap[srcProvider]; ok { @@ -2068,7 +2065,7 @@ func TestClientSideEncryptionProse(t *testing.T) { } // Call ``clientEncryption1.encrypt`` with the value "test". - var ciphertext primitive.Binary + var ciphertext bson.Binary { t, value, err := bson.MarshalValue("test") assert.Nil(mt, err, "error in MarshalValue: %v", err) @@ -2157,7 +2154,7 @@ func TestClientSideEncryptionProse(t *testing.T) { kmsProvidersMap := map[string]map[string]interface{}{ "azure": {}, } - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) err := bson.NewEncoder(vw).Encode(kmsProvidersMap) assert.Nil(mt, err, "error in Encode: %v", err) @@ -2442,7 +2439,7 @@ func TestClientSideEncryptionProse(t *testing.T) { ) assert.Nil(mt, err, "CreateCollection error: %v", err) - keyid := ef["fields"].(bson.A)[0].(bson.M)["keyId"].(primitive.Binary) + keyid := ef["fields"].(bson.A)[0].(bson.M)["keyId"].(bson.Binary) rawValueType, rawValueData, err := bson.MarshalValue("123-45-6789") assert.Nil(mt, err, "MarshalValue error: %v", err) rawValue := bson.RawValue{Type: rawValueType, Value: rawValueData} @@ -2468,7 +2465,7 @@ func TestClientSideEncryptionProse(t *testing.T) { type testcase struct { typeStr string field string - typeBson bsontype.Type + typeBson bson.Type rangeOpts options.RangeOptions zero bson.RawValue six bson.RawValue @@ -2479,16 +2476,25 @@ func TestClientSideEncryptionProse(t *testing.T) { precision := int32(2) - d128_0, err := primitive.ParseDecimal128("0") + d128_0, err := bson.ParseDecimal128("0") assert.Nil(mt, err) - d128_6, err := primitive.ParseDecimal128("6") + d128_0h, d128_0l := d128_0.GetBytes() + + d128_6, err := bson.ParseDecimal128("6") assert.Nil(mt, err) - d128_30, err := primitive.ParseDecimal128("30") + d128_6h, d128_6l := d128_6.GetBytes() + + d128_30, err := bson.ParseDecimal128("30") assert.Nil(mt, err) - d128_200, err := primitive.ParseDecimal128("200") + d128_30h, d128_30l := d128_30.GetBytes() + + d128_200, err := bson.ParseDecimal128("200") assert.Nil(mt, err) - d128_201, err := primitive.ParseDecimal128("201") + d128_200h, d128_200l := d128_200.GetBytes() + + d128_201, err := bson.ParseDecimal128("201") assert.Nil(mt, err) + d128_201h, d128_201l := d128_201.GetBytes() tests := []testcase{ { @@ -2498,27 +2504,27 @@ func TestClientSideEncryptionProse(t *testing.T) { rangeOpts: options.RangeOptions{ Sparsity: 1, }, - zero: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_0)}, - six: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_6)}, - thirty: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_30)}, - twoHundred: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_200)}, - twoHundredOne: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_201)}, + zero: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_0h, d128_0l)}, + six: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_6h, d128_6l)}, + thirty: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_30h, d128_30l)}, + twoHundred: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_200h, d128_200l)}, + twoHundredOne: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_201h, d128_201l)}, }, { typeStr: "DecimalPrecision", field: "encryptedDecimalPrecision", typeBson: bson.TypeDecimal128, rangeOpts: options.RangeOptions{ - Min: &bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_0)}, - Max: &bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_200)}, + Min: &bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_0h, d128_0l)}, + Max: &bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_200h, d128_200l)}, Sparsity: 1, Precision: &precision, }, - zero: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_0)}, - six: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_6)}, - thirty: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_30)}, - twoHundred: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_200)}, - twoHundredOne: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_201)}, + zero: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_0h, d128_0l)}, + six: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_6h, d128_6l)}, + thirty: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_30h, d128_30l)}, + twoHundred: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_200h, d128_200l)}, + twoHundredOne: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_201h, d128_201l)}, }, { typeStr: "DoubleNoPrecision", @@ -2605,10 +2611,10 @@ func TestClientSideEncryptionProse(t *testing.T) { // Test Setup ... begin encryptedFields := readJSONFile(mt, fmt.Sprintf("range-encryptedFields-%v.json", test.typeStr)) key1Document := readJSONFile(mt, "key1-document.json") - var key1ID primitive.Binary + var key1ID bson.Binary { subtype, data := key1Document.Lookup("_id").Binary() - key1ID = primitive.Binary{Subtype: subtype, Data: data} + key1ID = bson.Binary{Subtype: subtype, Data: data} } testSetup := func() (*mongo.Client, *mongo.ClientEncryption) { @@ -3020,7 +3026,7 @@ func decodeJSONFile(mt *mtest.T, file string, val interface{}) bson.Raw { } func rawValueToCoreValue(rv bson.RawValue) bsoncore.Value { - return bsoncore.Value{Type: rv.Type, Data: rv.Value} + return bsoncore.Value{Type: bsoncore.Type(rv.Type), Data: rv.Value} } type deadlockTest struct { @@ -3028,7 +3034,7 @@ type deadlockTest struct { clientKeyVaultOpts *options.ClientOptions clientKeyVaultEvents []startedEvent clientEncryption *mongo.ClientEncryption - ciphertext primitive.Binary + ciphertext bson.Binary } type startedEvent struct { diff --git a/internal/integration/client_side_encryption_test.go b/internal/integration/client_side_encryption_test.go index 49af404e08..10041a9bc6 100644 --- a/internal/integration/client_side_encryption_test.go +++ b/internal/integration/client_side_encryption_test.go @@ -14,8 +14,6 @@ import ( "testing" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/integration/mtest" @@ -29,7 +27,7 @@ import ( // createDataKeyAndEncrypt creates a data key with the alternate name @keyName. // Returns a ciphertext encrypted with the data key as test data. -func createDataKeyAndEncrypt(mt *mtest.T, keyName string) primitive.Binary { +func createDataKeyAndEncrypt(mt *mtest.T, keyName string) bson.Binary { mt.Helper() kvClientOpts := options.Client(). @@ -61,7 +59,7 @@ func createDataKeyAndEncrypt(mt *mtest.T, keyName string) primitive.Binary { _, err = ce.CreateDataKey(context.Background(), "local", dkOpts) assert.Nil(mt, err, "CreateDataKey error: %v", err) - in := bson.RawValue{Type: bsontype.String, Value: bsoncore.AppendString(nil, "test")} + in := bson.RawValue{Type: bson.TypeString, Value: bsoncore.AppendString(nil, "test")} eOpts := options.Encrypt(). SetAlgorithm("AEAD_AES_256_CBC_HMAC_SHA_512-Random"). SetKeyAltName(keyName) @@ -499,8 +497,8 @@ func TestFLE2DocsExample(t *testing.T) { "local": {"key": localMasterKey}, } - var key1ID primitive.Binary - var key2ID primitive.Binary + var key1ID bson.Binary + var key2ID bson.Binary // Create two data keys. { @@ -591,9 +589,9 @@ func TestFLE2DocsExample(t *testing.T) { assert.Nil(mt, err, "error in Raw: %v", err) val := resBSON.Lookup("encryptedIndexed") - assert.Equal(mt, val.Type, bsontype.Binary, "expected encryptedIndexed to be Binary, got %v", val.Type) + assert.Equal(mt, val.Type, bson.TypeBinary, "expected encryptedIndexed to be Binary, got %v", val.Type) val = resBSON.Lookup("encryptedUnindexed") - assert.Equal(mt, val.Type, bsontype.Binary, "expected encryptedUnindexed to be Binary, got %v", val.Type) + assert.Equal(mt, val.Type, bson.TypeBinary, "expected encryptedUnindexed to be Binary, got %v", val.Type) } }) } diff --git a/internal/integration/client_test.go b/internal/integration/client_test.go index 8350db58e0..6af8f29252 100644 --- a/internal/integration/client_test.go +++ b/internal/integration/client_test.go @@ -17,9 +17,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/eventtest" @@ -42,12 +39,12 @@ type negateCodec struct { ID int64 `bson:"_id"` } -func (e *negateCodec) EncodeValue(_ bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { +func (e *negateCodec) EncodeValue(_ bson.EncodeContext, vw bson.ValueWriter, val reflect.Value) error { return vw.WriteInt64(val.Int()) } // DecodeValue negates the value of ID when reading -func (e *negateCodec) DecodeValue(_ bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func (e *negateCodec) DecodeValue(_ bson.DecodeContext, vr bson.ValueReader, val reflect.Value) error { i, err := vr.ReadInt64() if err != nil { return err @@ -787,7 +784,7 @@ func TestClientStress(t *testing.T) { // Test that a Client can recover from a massive traffic spike after the traffic spike is over. mt.Run("Client recovers from traffic spike", func(mt *mtest.T) { - oid := primitive.NewObjectID() + oid := bson.NewObjectID() doc := bson.D{{Key: "_id", Value: oid}, {Key: "key", Value: "value"}} _, err := mt.Coll.InsertOne(context.Background(), doc) assert.Nil(mt, err, "InsertOne error: %v", err) diff --git a/internal/integration/cmd_monitoring_helpers_test.go b/internal/integration/cmd_monitoring_helpers_test.go index 5deec645f1..dc8a5f9e3a 100644 --- a/internal/integration/cmd_monitoring_helpers_test.go +++ b/internal/integration/cmd_monitoring_helpers_test.go @@ -14,7 +14,6 @@ import ( "strings" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/integration/mtest" @@ -111,53 +110,53 @@ func compareValues(mt *mtest.T, key string, expected, actual bson.RawValue) erro } // helper for $$type assertions -func checkValueType(mt *mtest.T, key string, actual bsontype.Type, typeStr string) error { +func checkValueType(mt *mtest.T, key string, actual bson.Type, typeStr string) error { mt.Helper() - var expected bsontype.Type + var expected bson.Type switch typeStr { case "double": - expected = bsontype.Double + expected = bson.TypeDouble case "string": - expected = bsontype.String + expected = bson.TypeString case "object": - expected = bsontype.EmbeddedDocument + expected = bson.TypeEmbeddedDocument case "array": - expected = bsontype.Array + expected = bson.TypeArray case "binData": - expected = bsontype.Binary + expected = bson.TypeBinary case "undefined": - expected = bsontype.Undefined + expected = bson.TypeUndefined case "objectId": - expected = bsontype.ObjectID + expected = bson.TypeObjectID case "boolean": - expected = bsontype.Boolean + expected = bson.TypeBoolean case "date": - expected = bsontype.DateTime + expected = bson.TypeDateTime case "null": - expected = bsontype.Null + expected = bson.TypeNull case "regex": - expected = bsontype.Regex + expected = bson.TypeRegex case "dbPointer": - expected = bsontype.DBPointer + expected = bson.TypeDBPointer case "javascript": - expected = bsontype.JavaScript + expected = bson.TypeJavaScript case "symbol": - expected = bsontype.Symbol + expected = bson.TypeSymbol case "javascriptWithScope": - expected = bsontype.CodeWithScope + expected = bson.TypeCodeWithScope case "int": - expected = bsontype.Int32 + expected = bson.TypeInt32 case "timestamp": - expected = bsontype.Timestamp + expected = bson.TypeTimestamp case "long": - expected = bsontype.Int64 + expected = bson.TypeInt64 case "decimal": - expected = bsontype.Decimal128 + expected = bson.TypeDecimal128 case "minKey": - expected = bsontype.MinKey + expected = bson.TypeMinKey case "maxKey": - expected = bsontype.MaxKey + expected = bson.TypeMaxKey default: mt.Fatalf("unrecognized type string: %v", typeStr) } diff --git a/internal/integration/collection_test.go b/internal/integration/collection_test.go index bb665d0aa2..43dee0f2cc 100644 --- a/internal/integration/collection_test.go +++ b/internal/integration/collection_test.go @@ -14,7 +14,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/integration/mtest" @@ -47,7 +46,7 @@ func TestCollection(t *testing.T) { mt.RunOpts("insert one", noClientOpts, func(mt *mtest.T) { mt.Run("success", func(mt *mtest.T) { - id := primitive.NewObjectID() + id := bson.NewObjectID() doc := bson.D{{"_id", id}, {"x", 1}} res, err := mt.Coll.InsertOne(context.Background(), doc) assert.Nil(mt, err, "InsertOne error: %v", err) @@ -182,9 +181,9 @@ func TestCollection(t *testing.T) { mt.Parallel() docs := []interface{}{ - bson.D{{"_id", primitive.NewObjectID()}}, - bson.D{{"_id", primitive.NewObjectID()}}, - bson.D{{"_id", primitive.NewObjectID()}}, + bson.D{{"_id", bson.NewObjectID()}}, + bson.D{{"_id", bson.NewObjectID()}}, + bson.D{{"_id", bson.NewObjectID()}}, } testCases := []struct { @@ -499,7 +498,7 @@ func TestCollection(t *testing.T) { name string update interface{} }{ - {"bsoncore Document", bsoncore.Document(docBytes)}, + {"bson Document", bsoncore.Document(docBytes)}, {"bson Raw", bson.Raw(docBytes)}, {"bson D", doc}, {"byte slice", docBytes}, @@ -532,7 +531,7 @@ func TestCollection(t *testing.T) { name string id interface{} }{ - {"objectID", primitive.NewObjectID()}, + {"objectID", bson.NewObjectID()}, {"string", "foo"}, {"int", 11}, } @@ -553,7 +552,7 @@ func TestCollection(t *testing.T) { } }) mt.Run("not found", func(mt *mtest.T) { - id := primitive.NewObjectID() + id := bson.NewObjectID() doc := bson.D{{"_id", id}, {"x", 1}} _, err := mt.Coll.InsertOne(context.Background(), doc) assert.Nil(mt, err, "InsertOne error: %v", err) @@ -567,7 +566,7 @@ func TestCollection(t *testing.T) { assert.Nil(mt, res.UpsertedID, "expected upserted ID nil, got %v", res.UpsertedID) }) mt.Run("upsert", func(mt *mtest.T) { - doc := bson.D{{"_id", primitive.NewObjectID()}, {"x", 1}} + doc := bson.D{{"_id", bson.NewObjectID()}, {"x", 1}} _, err := mt.Coll.InsertOne(context.Background(), doc) assert.Nil(mt, err, "InsertOne error: %v", err) @@ -1783,7 +1782,7 @@ func TestCollection(t *testing.T) { // // The response from the first batch should look like: // {ok: 1, n: 100000, nModified: 99999, upserted: [{index: 0, _id: }]} - firstBatchUpserted := bson.A{bson.D{{"index", 0}, {"_id", primitive.NewObjectID()}}} + firstBatchUpserted := bson.A{bson.D{{"index", 0}, {"_id", bson.NewObjectID()}}} firstBatchResponse := mtest.CreateSuccessResponse( bson.E{"n", 100000}, bson.E{"nModified", 99999}, @@ -1791,13 +1790,13 @@ func TestCollection(t *testing.T) { ) // The response from the second batch should look like: // {ok: 1, n: 50, nModified: 49, upserted: [{index: 49, _id: }]} - secondBatchUpserted := bson.A{bson.D{{"index", 49}, {"_id", primitive.NewObjectID()}}} + secondBatchUpserted := bson.A{bson.D{{"index", 49}, {"_id", bson.NewObjectID()}}} secondBatchResponse := mtest.CreateSuccessResponse( bson.E{"n", 50}, bson.E{"nModified", 49}, bson.E{"upserted", secondBatchUpserted}, ) - mt.AddMockResponses([]primitive.D{firstBatchResponse, secondBatchResponse}...) + mt.AddMockResponses([]bson.D{firstBatchResponse, secondBatchResponse}...) mt.ClearEvents() res, err := mt.Coll.BulkWrite(context.Background(), models) @@ -1926,7 +1925,7 @@ func create16MBDocument(mt *mtest.T) bsoncore.Document { } idx, doc := bsoncore.AppendDocumentStart(nil) - doc = bsoncore.AppendObjectIDElement(doc, "_id", primitive.NewObjectID()) + doc = bsoncore.AppendObjectIDElement(doc, "_id", bson.NewObjectID()) doc = bsoncore.AppendStringElement(doc, "key", b.String()) doc, _ = bsoncore.AppendDocumentEnd(doc, idx) assert.Equal(mt, targetDocSize, len(doc), "expected document length %v, got %v", targetDocSize, len(doc)) diff --git a/internal/integration/crud_helpers_test.go b/internal/integration/crud_helpers_test.go index 80abf29231..fe9f009eaa 100644 --- a/internal/integration/crud_helpers_test.go +++ b/internal/integration/crud_helpers_test.go @@ -16,8 +16,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/bsonutil" "go.mongodb.org/mongo-driver/internal/integration/mtest" @@ -69,9 +67,9 @@ func createHint(mt *mtest.T, val bson.RawValue) interface{} { var hint interface{} switch val.Type { - case bsontype.String: + case bson.TypeString: hint = val.StringValue() - case bsontype.EmbeddedDocument: + case bson.TypeEmbeddedDocument: hint = val.Document() default: mt.Fatalf("unrecognized hint value type: %s\n", val.Type) @@ -1218,7 +1216,7 @@ func executeEstimatedDocumentCount(mt *mtest.T, sess mongo.Session, args bson.Ra func executeGridFSDownload(mt *mtest.T, bucket *mongo.GridFSBucket, args bson.Raw) (int64, error) { mt.Helper() - var fileID primitive.ObjectID + var fileID bson.ObjectID elems, _ := args.Elements() for _, elem := range elems { key := elem.Key() diff --git a/internal/integration/crud_spec_test.go b/internal/integration/crud_spec_test.go index f3347fa784..e6583f8ade 100644 --- a/internal/integration/crud_spec_test.go +++ b/internal/integration/crud_spec_test.go @@ -17,7 +17,6 @@ import ( "testing" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/bsonutil" "go.mongodb.org/mongo-driver/internal/integration/mtest" @@ -56,7 +55,7 @@ type crudOutcome struct { Collection *outcomeCollection `bson:"collection"` } -var crudRegistry = func() *bsoncodec.Registry { +var crudRegistry = func() *bson.Registry { reg := bson.NewRegistry() reg.RegisterTypeMapEntry(bson.TypeEmbeddedDocument, reflect.TypeOf(bson.Raw{})) return reg diff --git a/internal/integration/database_test.go b/internal/integration/database_test.go index 2c531e4360..12c2e0cd53 100644 --- a/internal/integration/database_test.go +++ b/internal/integration/database_test.go @@ -14,9 +14,6 @@ import ( "testing" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/handshake" "go.mongodb.org/mongo-driver/internal/integration/mtest" @@ -32,9 +29,9 @@ const ( ) var ( - interfaceAsMapRegistry = func() *bsoncodec.Registry { + interfaceAsMapRegistry = func() *bson.Registry { reg := bson.NewRegistry() - reg.RegisterTypeMapEntry(bsontype.EmbeddedDocument, reflect.TypeOf(bson.M{})) + reg.RegisterTypeMapEntry(bson.TypeEmbeddedDocument, reflect.TypeOf(bson.M{})) return reg }() ) @@ -309,7 +306,7 @@ func TestDatabase(t *testing.T) { } if mtest.CompareServerVersions(mtest.ServerVersion(), "3.6") >= 0 { uuidSubtype, uuidData := cursor.Current.Lookup("info", "uuid").Binary() - expectedSpec.UUID = &primitive.Binary{Subtype: uuidSubtype, Data: uuidData} + expectedSpec.UUID = &bson.Binary{Subtype: uuidSubtype, Data: uuidData} } if mtest.CompareServerVersions(mtest.ServerVersion(), "3.4") >= 0 { keysDoc := bsoncore.NewDocumentBuilder(). diff --git a/internal/integration/gridfs_test.go b/internal/integration/gridfs_test.go index 6fc0f85d1c..b1057b9468 100644 --- a/internal/integration/gridfs_test.go +++ b/internal/integration/gridfs_test.go @@ -16,7 +16,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/integration/mtest" @@ -348,7 +347,7 @@ func TestGridFS(x *testing.T) { // Test that opening a download returns ErrMissingChunkSize if the files collection document has no // chunk size field. - oid := primitive.NewObjectID() + oid := bson.NewObjectID() filesDoc := bson.D{ {"_id", oid}, {"length", 10}, diff --git a/internal/integration/mock_find_test.go b/internal/integration/mock_find_test.go index d246848778..37e42bfa62 100644 --- a/internal/integration/mock_find_test.go +++ b/internal/integration/mock_find_test.go @@ -11,7 +11,6 @@ import ( "testing" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/integration/mtest" "go.mongodb.org/mongo-driver/mongo" @@ -28,7 +27,7 @@ type finder interface { type mockFinder struct { docs []interface{} err error - registry *bsoncodec.Registry + registry *bson.Registry } // FindOne mocks a findOne operation using NewSingleResultFromDocument. diff --git a/internal/integration/retryable_writes_prose_test.go b/internal/integration/retryable_writes_prose_test.go index f415a0daa6..8f70354962 100644 --- a/internal/integration/retryable_writes_prose_test.go +++ b/internal/integration/retryable_writes_prose_test.go @@ -15,7 +15,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/eventtest" @@ -245,7 +244,7 @@ func TestRetryableWritesProse(t *testing.T) { //Set a command monitor on the client that configures a failpoint with a "NoWritesPerformed" monitor.Succeeded = func(_ context.Context, evt *event.CommandSucceededEvent) { var errorCode int32 - if wce := evt.Reply.Lookup("writeConcernError"); wce.Type == bsontype.EmbeddedDocument { + if wce := evt.Reply.Lookup("writeConcernError"); wce.Type == bson.TypeEmbeddedDocument { var ok bool errorCode, ok = wce.Document().Lookup("code").Int32OK() if !ok { diff --git a/internal/integration/sdam_prose_test.go b/internal/integration/sdam_prose_test.go index c4f839c4a3..79c35abf95 100644 --- a/internal/integration/sdam_prose_test.go +++ b/internal/integration/sdam_prose_test.go @@ -14,7 +14,7 @@ import ( "testing" "time" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/handshake" @@ -209,7 +209,7 @@ func TestServerHeartbeatStartedEvent(t *testing.T) { server := topology.NewServer( address, - primitive.NewObjectID(), + bson.NewObjectID(), topology.WithServerMonitor(func(*event.ServerMonitor) *event.ServerMonitor { return &event.ServerMonitor{ ServerHeartbeatStarted: func(e *event.ServerHeartbeatStartedEvent) { diff --git a/internal/integration/unified/bsonutil.go b/internal/integration/unified/bsonutil.go index e95af0b7cb..17ce19549a 100644 --- a/internal/integration/unified/bsonutil.go +++ b/internal/integration/unified/bsonutil.go @@ -10,7 +10,6 @@ import ( "sort" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -22,7 +21,7 @@ var ( func documentToRawValue(doc bson.Raw) bson.RawValue { return bson.RawValue{ - Type: bsontype.EmbeddedDocument, + Type: bson.TypeEmbeddedDocument, Value: doc, } } @@ -42,7 +41,7 @@ func removeFieldsFromDocument(doc bson.Raw, keys ...string) bson.Raw { } val := elem.Value() - newDoc.AppendValue(elem.Key(), bsoncore.Value{Type: val.Type, Data: val.Value}) + newDoc.AppendValue(elem.Key(), bsoncore.Value{Type: bsoncore.Type(val.Type), Data: val.Value}) } return bson.Raw(newDoc.Build()) } @@ -61,7 +60,7 @@ func sortDocument(doc bson.Raw) bson.Raw { sorted := bsoncore.NewDocumentBuilder() for _, key := range keys { val := valuesMap[key] - sorted.AppendValue(key, bsoncore.Value{Type: val.Type, Data: val.Value}) + sorted.AppendValue(key, bsoncore.Value{Type: bsoncore.Type(val.Type), Data: val.Value}) } return bson.Raw(sorted.Build()) } diff --git a/internal/integration/unified/client_encryption_operation_execution.go b/internal/integration/unified/client_encryption_operation_execution.go index d30087593d..9550026206 100644 --- a/internal/integration/unified/client_encryption_operation_execution.go +++ b/internal/integration/unified/client_encryption_operation_execution.go @@ -12,7 +12,6 @@ import ( "fmt" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" @@ -42,7 +41,7 @@ func parseDataKeyOptions(opts bson.Raw) (*options.DataKeyOptions, error) { } dko.SetKeyAltNames(keyAltNames) case "keyMaterial": - bin := primitive.Binary{} + bin := bson.Binary{} if err := val.Unmarshal(&bin); err != nil { return nil, fmt.Errorf("error unmarshaling 'keyMaterial': %w", err) } @@ -62,7 +61,7 @@ func executeAddKeyAltName(ctx context.Context, operation *operation) (*operation return nil, err } - var id primitive.Binary + var id bson.Binary var keyAltName string elems, err := operation.Arguments.Elements() @@ -76,7 +75,7 @@ func executeAddKeyAltName(ctx context.Context, operation *operation) (*operation switch key { case "id": subtype, data := val.Binary() - id = primitive.Binary{Subtype: subtype, Data: data} + id = bson.Binary{Subtype: subtype, Data: data} case "keyAltName": keyAltName = val.StringValue() default: @@ -146,7 +145,7 @@ func executeDeleteKey(ctx context.Context, operation *operation) (*operationResu return nil, err } - var id primitive.Binary + var id bson.Binary elems, err := operation.Arguments.Elements() if err != nil { @@ -159,7 +158,7 @@ func executeDeleteKey(ctx context.Context, operation *operation) (*operationResu switch key { case "id": subtype, data := val.Binary() - id = primitive.Binary{Subtype: subtype, Data: data} + id = bson.Binary{Subtype: subtype, Data: data} default: return nil, fmt.Errorf("unrecognized DeleteKey arg: %q", key) } @@ -217,7 +216,7 @@ func executeGetKey(ctx context.Context, operation *operation) (*operationResult, return nil, err } - var id primitive.Binary + var id bson.Binary elems, err := operation.Arguments.Elements() if err != nil { @@ -230,7 +229,7 @@ func executeGetKey(ctx context.Context, operation *operation) (*operationResult, switch key { case "id": subtype, data := val.Binary() - id = primitive.Binary{Subtype: subtype, Data: data} + id = bson.Binary{Subtype: subtype, Data: data} default: return nil, fmt.Errorf("unrecognized GetKey arg: %q", key) } @@ -270,7 +269,7 @@ func executeRemoveKeyAltName(ctx context.Context, operation *operation) (*operat return nil, err } - var id primitive.Binary + var id bson.Binary var keyAltName string elems, err := operation.Arguments.Elements() @@ -284,7 +283,7 @@ func executeRemoveKeyAltName(ctx context.Context, operation *operation) (*operat switch key { case "id": subtype, data := val.Binary() - id = primitive.Binary{Subtype: subtype, Data: data} + id = bson.Binary{Subtype: subtype, Data: data} case "keyAltName": keyAltName = val.StringValue() default: diff --git a/internal/integration/unified/client_operation_execution.go b/internal/integration/unified/client_operation_execution.go index 6fd96222fb..37b87c0d88 100644 --- a/internal/integration/unified/client_operation_execution.go +++ b/internal/integration/unified/client_operation_execution.go @@ -11,7 +11,7 @@ import ( "fmt" "time" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/internal/bsonutil" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" @@ -90,7 +90,7 @@ func executeCreateChangeStream(ctx context.Context, operation *operation) (*oper opts.SetStartAfter(val.Document()) case "startAtOperationTime": t, i := val.Timestamp() - opts.SetStartAtOperationTime(&primitive.Timestamp{T: t, I: i}) + opts.SetStartAtOperationTime(&bson.Timestamp{T: t, I: i}) default: return nil, fmt.Errorf("unrecognized createChangeStream option %q", key) } diff --git a/internal/integration/unified/collection_operation_execution.go b/internal/integration/unified/collection_operation_execution.go index a870d82d41..8f5fae8cae 100644 --- a/internal/integration/unified/collection_operation_execution.go +++ b/internal/integration/unified/collection_operation_execution.go @@ -13,7 +13,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/bsonutil" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" @@ -210,7 +209,7 @@ func executeCountDocuments(ctx context.Context, operation *operation) (*operatio if err != nil { return newErrorResult(err), nil } - return newValueResult(bsontype.Int64, bsoncore.AppendInt64(nil, count), nil), nil + return newValueResult(bson.TypeInt64, bsoncore.AppendInt64(nil, count), nil), nil } func executeCreateIndex(ctx context.Context, operation *operation) (*operationResult, error) { @@ -288,7 +287,7 @@ func executeCreateIndex(ctx context.Context, operation *operation) (*operationRe Options: indexOpts, } name, err := coll.Indexes().CreateOne(ctx, model) - return newValueResult(bsontype.String, bsoncore.AppendString(nil, name), err), nil + return newValueResult(bson.TypeString, bsoncore.AppendString(nil, name), err), nil } func executeCreateSearchIndex(ctx context.Context, operation *operation) (*operationResult, error) { @@ -326,7 +325,7 @@ func executeCreateSearchIndex(ctx context.Context, operation *operation) (*opera } name, err := coll.SearchIndexes().CreateOne(ctx, model) - return newValueResult(bsontype.String, bsoncore.AppendString(nil, name), err), nil + return newValueResult(bson.TypeString, bsoncore.AppendString(nil, name), err), nil } func executeCreateSearchIndexes(ctx context.Context, operation *operation) (*operationResult, error) { @@ -377,7 +376,7 @@ func executeCreateSearchIndexes(ctx context.Context, operation *operation) (*ope for _, name := range names { builder.AppendString(name) } - return newValueResult(bsontype.Array, builder.Build(), err), nil + return newValueResult(bson.TypeArray, builder.Build(), err), nil } func executeDeleteOne(ctx context.Context, operation *operation) (*operationResult, error) { @@ -540,7 +539,7 @@ func executeDistinct(ctx context.Context, operation *operation) (*operationResul if err != nil { return nil, fmt.Errorf("error converting Distinct result to raw BSON: %w", err) } - return newValueResult(bsontype.Array, rawRes, nil), nil + return newValueResult(bson.TypeArray, rawRes, nil), nil } func executeDropIndex(ctx context.Context, operation *operation) (*operationResult, error) { @@ -623,7 +622,7 @@ func executeDropSearchIndex(ctx context.Context, operation *operation) (*operati } err = coll.SearchIndexes().DropOne(ctx, name) - return newValueResult(bsontype.Null, nil, err), nil + return newValueResult(bson.TypeNull, nil, err), nil } func executeEstimatedDocumentCount(ctx context.Context, operation *operation) (*operationResult, error) { @@ -659,7 +658,7 @@ func executeEstimatedDocumentCount(ctx context.Context, operation *operation) (* if err != nil { return newErrorResult(err), nil } - return newValueResult(bsontype.Int64, bsoncore.AppendInt64(nil, count), nil), nil + return newValueResult(bson.TypeInt64, bsoncore.AppendInt64(nil, count), nil), nil } func executeCreateFindCursor(ctx context.Context, operation *operation) (*operationResult, error) { @@ -1068,7 +1067,7 @@ func executeInsertOne(ctx context.Context, operation *operation) (*operationResu return nil, fmt.Errorf("error converting InsertedID field to BSON: %w", err) } raw = bsoncore.NewDocumentBuilder(). - AppendValue("insertedId", bsoncore.Value{Type: t, Data: data}). + AppendValue("insertedId", bsoncore.Value{Type: bsoncore.Type(t), Data: data}). Build() } return newDocumentResult(raw, err), nil @@ -1148,7 +1147,7 @@ func executeListSearchIndexes(ctx context.Context, operation *operation) (*opera } _, err = coll.SearchIndexes().List(ctx, searchIdxOpts, opts...) - return newValueResult(bsontype.Null, nil, err), nil + return newValueResult(bson.TypeNull, nil, err), nil } func executeRenameCollection(ctx context.Context, operation *operation) (*operationResult, error) { @@ -1318,7 +1317,7 @@ func executeUpdateSearchIndex(ctx context.Context, operation *operation) (*opera } err = coll.SearchIndexes().UpdateOne(ctx, name, definition) - return newValueResult(bsontype.Null, nil, err), nil + return newValueResult(bson.TypeNull, nil, err), nil } func buildUpdateResultDocument(res *mongo.UpdateResult) (bsoncore.Document, error) { @@ -1336,7 +1335,7 @@ func buildUpdateResultDocument(res *mongo.UpdateResult) (bsoncore.Document, erro if err != nil { return nil, fmt.Errorf("error converting UpsertedID to BSON: %w", err) } - builder.AppendValue("upsertedId", bsoncore.Value{Type: t, Data: data}) + builder.AppendValue("upsertedId", bsoncore.Value{Type: bsoncore.Type(t), Data: data}) } return builder.Build(), nil } diff --git a/internal/integration/unified/crud_helpers.go b/internal/integration/unified/crud_helpers.go index 2abb1cd582..5246e88c20 100644 --- a/internal/integration/unified/crud_helpers.go +++ b/internal/integration/unified/crud_helpers.go @@ -10,7 +10,6 @@ import ( "fmt" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/bsonutil" "go.mongodb.org/mongo-driver/mongo/options" ) @@ -150,9 +149,9 @@ func createHint(val bson.RawValue) (interface{}, error) { var hint interface{} switch val.Type { - case bsontype.String: + case bson.TypeString: hint = val.StringValue() - case bsontype.EmbeddedDocument: + case bson.TypeEmbeddedDocument: hint = val.Document() default: return nil, fmt.Errorf("unrecognized hint value type %s", val.Type) diff --git a/internal/integration/unified/database_operation_execution.go b/internal/integration/unified/database_operation_execution.go index 675ab480b7..6effbd58e5 100644 --- a/internal/integration/unified/database_operation_execution.go +++ b/internal/integration/unified/database_operation_execution.go @@ -12,7 +12,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/bsonutil" "go.mongodb.org/mongo-driver/mongo/options" ) @@ -221,7 +220,7 @@ func executeListCollectionNames(ctx context.Context, operation *operation) (*ope if err != nil { return nil, fmt.Errorf("error converting collection names slice to BSON: %w", err) } - return newValueResult(bsontype.Array, data, nil), nil + return newValueResult(bson.TypeArray, data, nil), nil } func executeRunCommand(ctx context.Context, operation *operation) (*operationResult, error) { diff --git a/internal/integration/unified/event_verification.go b/internal/integration/unified/event_verification.go index f00a7b1505..784e8198cf 100644 --- a/internal/integration/unified/event_verification.go +++ b/internal/integration/unified/event_verification.go @@ -13,8 +13,6 @@ import ( "fmt" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/event" ) @@ -121,7 +119,7 @@ func (e *expectedEvents) UnmarshalBSON(data []byte) error { } e.ClientID = temp.ClientID - if temp.Events.Type != bsontype.Array { + if temp.Events.Type != bson.TypeArray { return fmt.Errorf("expected 'events' to be an array but got a %q", temp.Events.Type) } @@ -203,7 +201,7 @@ func verifyCommandEvents(ctx context.Context, client *clientEntity, expectedEven // In the case of an empty Command, hardcode an empty bson.RawValue document. if len(actual.Command) == 0 { emptyDoc := []byte{5, 0, 0, 0, 0} - actualDoc = bson.RawValue{Type: bsontype.EmbeddedDocument, Value: emptyDoc} + actualDoc = bson.RawValue{Type: bson.TypeEmbeddedDocument, Value: emptyDoc} } if err := verifyValuesMatch(ctx, expectedDoc, actualDoc, true); err != nil { @@ -247,7 +245,7 @@ func verifyCommandEvents(ctx context.Context, client *clientEntity, expectedEven // In the case of an empty Reply, hardcode an empty bson.RawValue document. if len(actual.Reply) == 0 { emptyDoc := []byte{5, 0, 0, 0, 0} - actualDoc = bson.RawValue{Type: bsontype.EmbeddedDocument, Value: emptyDoc} + actualDoc = bson.RawValue{Type: bson.TypeEmbeddedDocument, Value: emptyDoc} } if err := verifyValuesMatch(ctx, expectedDoc, actualDoc, true); err != nil { @@ -391,7 +389,7 @@ func getNextPoolEvent(events []*event.PoolEvent, expectedType string) (*event.Po return evt, events[1:], nil } -func verifyServiceID(expectServiceID bool, serviceID *primitive.ObjectID) error { +func verifyServiceID(expectServiceID bool, serviceID *bson.ObjectID) error { if eventHasID := serviceID != nil; expectServiceID != eventHasID { return fmt.Errorf("expected event to have server ID: %v, event has server ID %v", expectServiceID, serviceID) } diff --git a/internal/integration/unified/gridfs_bucket_operation_execution.go b/internal/integration/unified/gridfs_bucket_operation_execution.go index 17aa5b71b0..d2ca0f5652 100644 --- a/internal/integration/unified/gridfs_bucket_operation_execution.go +++ b/internal/integration/unified/gridfs_bucket_operation_execution.go @@ -16,7 +16,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -125,7 +124,7 @@ func executeBucketDownload(ctx context.Context, operation *operation) (*operatio return newErrorResult(err), nil } - return newValueResult(bsontype.Binary, bsoncore.AppendBinary(nil, 0, buffer.Bytes()), nil), nil + return newValueResult(bson.TypeBinary, bsoncore.AppendBinary(nil, 0, buffer.Bytes()), nil), nil } func executeBucketDownloadByName(ctx context.Context, operation *operation) (*operationResult, error) { @@ -168,7 +167,7 @@ func executeBucketDownloadByName(ctx context.Context, operation *operation) (*op return newErrorResult(err), nil } - return newValueResult(bsontype.Binary, bsoncore.AppendBinary(nil, 0, buf.Bytes()), nil), nil + return newValueResult(bson.TypeBinary, bsoncore.AppendBinary(nil, 0, buf.Bytes()), nil), nil } func executeBucketDrop(ctx context.Context, operation *operation) (*operationResult, error) { @@ -264,7 +263,7 @@ func executeBucketUpload(ctx context.Context, operation *operation) (*operationR if operation.ResultEntityID != nil { fileIDValue := bson.RawValue{ - Type: bsontype.ObjectID, + Type: bson.TypeObjectID, Value: fileID[:], } if err := entities(ctx).addBSONEntity(*operation.ResultEntityID, fileIDValue); err != nil { @@ -272,5 +271,5 @@ func executeBucketUpload(ctx context.Context, operation *operation) (*operationR } } - return newValueResult(bsontype.ObjectID, fileID[:], nil), nil + return newValueResult(bson.TypeObjectID, fileID[:], nil), nil } diff --git a/internal/integration/unified/matches.go b/internal/integration/unified/matches.go index 6968c00126..bd8a0f916e 100644 --- a/internal/integration/unified/matches.go +++ b/internal/integration/unified/matches.go @@ -14,7 +14,6 @@ import ( "strings" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" ) // keyPathCtxKey is used as a key for a Context object. The value conveys the BSON key path that is currently being @@ -243,10 +242,10 @@ func evaluateSpecialComparison(ctx context.Context, assertionDoc bson.Raw, actua return fmt.Errorf("expected lsid %v, got %v", expectedID, actualID) } case "$$lte": - if assertionVal.Type != bsontype.Int32 && assertionVal.Type != bsontype.Int64 { + if assertionVal.Type != bson.TypeInt32 && assertionVal.Type != bson.TypeInt64 { return fmt.Errorf("expected assertionVal to be an Int32 or Int64 but got a %s", assertionVal.Type) } - if actual.Type != bsontype.Int32 && actual.Type != bsontype.Int64 { + if actual.Type != bson.TypeInt32 && actual.Type != bson.TypeInt64 { return fmt.Errorf("expected value to be an Int32 or Int64 but got a %s", actual.Type) } @@ -290,22 +289,22 @@ func requiresSpecialMatching(doc bson.Raw) bool { return len(elems) == 1 && strings.HasPrefix(elems[0].Key(), "$$") } -func getTypesArray(val bson.RawValue) ([]bsontype.Type, error) { +func getTypesArray(val bson.RawValue) ([]bson.Type, error) { switch val.Type { - case bsontype.String: + case bson.TypeString: convertedType, err := convertStringToBSONType(val.StringValue()) if err != nil { return nil, err } - return []bsontype.Type{convertedType}, nil - case bsontype.Array: + return []bson.Type{convertedType}, nil + case bson.TypeArray: var typeStrings []string if err := val.Unmarshal(&typeStrings); err != nil { return nil, fmt.Errorf("error unmarshalling to slice of strings: %v", err) } - var types []bsontype.Type + var types []bson.Type for _, typeStr := range typeStrings { convertedType, err := convertStringToBSONType(typeStr) if err != nil { @@ -316,56 +315,56 @@ func getTypesArray(val bson.RawValue) ([]bsontype.Type, error) { } return types, nil default: - return nil, fmt.Errorf("invalid type to convert to bsontype.Type slice: %s", val.Type) + return nil, fmt.Errorf("invalid type to convert to bson.Type slice: %s", val.Type) } } -func convertStringToBSONType(typeStr string) (bsontype.Type, error) { +func convertStringToBSONType(typeStr string) (bson.Type, error) { switch typeStr { case "double": - return bsontype.Double, nil + return bson.TypeDouble, nil case "string": - return bsontype.String, nil + return bson.TypeString, nil case "object": - return bsontype.EmbeddedDocument, nil + return bson.TypeEmbeddedDocument, nil case "array": - return bsontype.Array, nil + return bson.TypeArray, nil case "binData": - return bsontype.Binary, nil + return bson.TypeBinary, nil case "undefined": - return bsontype.Undefined, nil + return bson.TypeUndefined, nil case "objectId": - return bsontype.ObjectID, nil + return bson.TypeObjectID, nil case "bool": - return bsontype.Boolean, nil + return bson.TypeBoolean, nil case "date": - return bsontype.DateTime, nil + return bson.TypeDateTime, nil case "null": - return bsontype.Null, nil + return bson.TypeNull, nil case "regex": - return bsontype.Regex, nil + return bson.TypeRegex, nil case "dbPointer": - return bsontype.DBPointer, nil + return bson.TypeDBPointer, nil case "javascript": - return bsontype.JavaScript, nil + return bson.TypeJavaScript, nil case "symbol": - return bsontype.Symbol, nil + return bson.TypeSymbol, nil case "javascriptWithScope": - return bsontype.CodeWithScope, nil + return bson.TypeCodeWithScope, nil case "int": - return bsontype.Int32, nil + return bson.TypeInt32, nil case "timestamp": - return bsontype.Timestamp, nil + return bson.TypeTimestamp, nil case "long": - return bsontype.Int64, nil + return bson.TypeInt64, nil case "decimal": - return bsontype.Decimal128, nil + return bson.TypeDecimal128, nil case "minKey": - return bsontype.MinKey, nil + return bson.TypeMinKey, nil case "maxKey": - return bsontype.MaxKey, nil + return bson.TypeMaxKey, nil default: - return bsontype.Type(0), fmt.Errorf("unrecognized BSON type string %q", typeStr) + return bson.Type(0), fmt.Errorf("unrecognized BSON type string %q", typeStr) } } diff --git a/internal/integration/unified/matches_test.go b/internal/integration/unified/matches_test.go index fed9ce925e..a9be9c6a88 100644 --- a/internal/integration/unified/matches_test.go +++ b/internal/integration/unified/matches_test.go @@ -12,7 +12,6 @@ import ( "testing" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -139,7 +138,7 @@ func TestMatches(t *testing.T) { hexBytes, err := hex.DecodeString(str) assert.Nil(t, err, "hex.DecodeString error: %v", err) return bson.RawValue{ - Type: bsontype.Binary, + Type: bson.TypeBinary, Value: bsoncore.AppendBinary(nil, 0, hexBytes), } } diff --git a/internal/integration/unified/result.go b/internal/integration/unified/result.go index 6c7a71a565..7aea2ae2ca 100644 --- a/internal/integration/unified/result.go +++ b/internal/integration/unified/result.go @@ -11,7 +11,6 @@ import ( "fmt" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" ) // operationResult holds the result and/or error returned by an op. @@ -35,13 +34,13 @@ func newEmptyResult() *operationResult { // newDocumentResult is a helper to create a value result where the value is a BSON document. func newDocumentResult(result []byte, err error) *operationResult { - return newValueResult(bsontype.EmbeddedDocument, result, err) + return newValueResult(bson.TypeEmbeddedDocument, result, err) } // newValueResult creates an operationResult where the result is a BSON value of an arbitrary type. Because some // operations can return both a result and an error (e.g. bulkWrite), the err parameter should be the error returned // by the op, if any. -func newValueResult(valueType bsontype.Type, data []byte, err error) *operationResult { +func newValueResult(valueType bson.Type, data []byte, err error) *operationResult { return &operationResult{ Result: bson.RawValue{Type: valueType, Value: data}, Err: err, @@ -80,7 +79,7 @@ func verifyOperationResult(ctx context.Context, expected bson.RawValue, actual * } actualVal = bson.RawValue{ - Type: bsontype.Array, + Type: bson.TypeArray, Value: data, } } @@ -88,6 +87,6 @@ func verifyOperationResult(ctx context.Context, expected bson.RawValue, actual * // For document results and arrays of root documents (i.e. cursor results), the actual value can have additional // top-level keys. Single-value array results (e.g. from distinct) must match exactly, so we set extraKeysAllowed to // false only for that case. - extraKeysAllowed := actual.Result.Type != bsontype.Array + extraKeysAllowed := actual.Result.Type != bson.TypeArray return verifyValuesMatch(ctx, expected, actualVal, extraKeysAllowed) } diff --git a/internal/integration/unified_spec_test.go b/internal/integration/unified_spec_test.go index c62de30698..c9199f6135 100644 --- a/internal/integration/unified_spec_test.go +++ b/internal/integration/unified_spec_test.go @@ -20,9 +20,6 @@ import ( "unsafe" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/bsonutil" @@ -80,9 +77,9 @@ type testData struct { } // custom decoder for testData type -func decodeTestData(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { +func decodeTestData(dc bson.DecodeContext, vr bson.ValueReader, val reflect.Value) error { switch vr.Type() { - case bsontype.Array: + case bson.TypeArray: docsVal := val.FieldByName("Documents") decoder, err := dc.Registry.LookupDecoder(docsVal.Type()) if err != nil { @@ -90,7 +87,7 @@ func decodeTestData(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val refle } return decoder.DecodeValue(dc, vr, docsVal) - case bsontype.EmbeddedDocument: + case bson.TypeEmbeddedDocument: gridfsDataVal := val.FieldByName("GridFSData") decoder, err := dc.Registry.LookupDecoder(gridfsDataVal.Type()) if err != nil { @@ -184,10 +181,10 @@ var directories = []string{ } var checkOutcomeOpts = options.Collection().SetReadPreference(readpref.Primary()).SetReadConcern(readconcern.Local()) -var specTestRegistry = func() *bsoncodec.Registry { +var specTestRegistry = func() *bson.Registry { reg := bson.NewRegistry() reg.RegisterTypeMapEntry(bson.TypeEmbeddedDocument, reflect.TypeOf(bson.Raw{})) - reg.RegisterTypeDecoder(reflect.TypeOf(testData{}), bsoncodec.ValueDecoderFunc(decodeTestData)) + reg.RegisterTypeDecoder(reflect.TypeOf(testData{}), bson.ValueDecoderFunc(decodeTestData)) return reg }() diff --git a/internal/logger/component.go b/internal/logger/component.go index 532162dcc3..b21209b3a4 100644 --- a/internal/logger/component.go +++ b/internal/logger/component.go @@ -10,7 +10,7 @@ import ( "os" "strconv" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" ) const ( @@ -144,16 +144,16 @@ func EnvHasComponentVariables() bool { // Command is a struct defining common fields that must be included in all // commands. type Command struct { - DriverConnectionID int64 // Driver's ID for the connection - Name string // Command name - DatabaseName string // Database name - Message string // Message associated with the command - OperationID int32 // Driver-generated operation ID - RequestID int64 // Driver-generated request ID - ServerConnectionID *int64 // Server's ID for the connection used for the command - ServerHost string // Hostname or IP address for the server - ServerPort string // Port for the server - ServiceID *primitive.ObjectID // ID for the command in load balancer mode + DriverConnectionID int64 // Driver's ID for the connection + Name string // Command name + DatabaseName string // Database name + Message string // Message associated with the command + OperationID int32 // Driver-generated operation ID + RequestID int64 // Driver-generated request ID + ServerConnectionID *int64 // Server's ID for the connection used for the command + ServerHost string // Hostname or IP address for the server + ServerPort string // Port for the server + ServiceID *bson.ObjectID // ID for the command in load balancer mode } // SerializeCommand takes a command and a variable number of key-value pairs and @@ -225,12 +225,12 @@ func SerializeConnection(conn Connection, extraKeysAndValues ...interface{}) Key // Server contains data that all server messages MAY contain. type Server struct { - DriverConnectionID int64 // Driver's ID for the connection - TopologyID primitive.ObjectID // Driver's unique ID for this topology - Message string // Message associated with the topology - ServerConnectionID *int64 // Server's ID for the connection - ServerHost string // Hostname or IP address for the server - ServerPort string // Port for the server + DriverConnectionID int64 // Driver's ID for the connection + TopologyID bson.ObjectID // Driver's unique ID for this topology + Message string // Message associated with the topology + ServerConnectionID *int64 // Server's ID for the connection + ServerHost string // Hostname or IP address for the server + ServerPort string // Port for the server } // SerializeServer serializes a Server message into a slice of keys and @@ -293,8 +293,8 @@ func SerializeServerSelection(srvSelection ServerSelection, extraKV ...interface // Topology contains data that all topology messages MAY contain. type Topology struct { - ID primitive.ObjectID // Driver's unique ID for this topology - Message string // Message associated with the topology + ID bson.ObjectID // Driver's unique ID for this topology + Message string // Message associated with the topology } // SerializeTopology serializes a Topology message into a slice of keys and diff --git a/internal/logger/component_test.go b/internal/logger/component_test.go index 91bd98dc8d..004f84e7fd 100644 --- a/internal/logger/component_test.go +++ b/internal/logger/component_test.go @@ -9,7 +9,7 @@ package logger import ( "testing" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/internal/assert" ) @@ -26,7 +26,7 @@ func TestSerializeCommand(t *testing.T) { t.Parallel() serverConnectionID := int64(100) - serviceID := primitive.NewObjectID() + serviceID := bson.NewObjectID() tests := []struct { name string @@ -133,7 +133,7 @@ func TestSerializeConnection(t *testing.T) { func TestSerializeServer(t *testing.T) { t.Parallel() - topologyID := primitive.NewObjectID() + topologyID := bson.NewObjectID() serverConnectionID := int64(100) tests := []struct { @@ -148,7 +148,7 @@ func TestSerializeServer(t *testing.T) { KeyDriverConnectionID, int64(0), KeyMessage, "", KeyServerHost, "", - KeyTopologyID, primitive.ObjectID{}.Hex(), + KeyTopologyID, bson.ObjectID{}.Hex(), }, }, { @@ -188,7 +188,7 @@ func TestSerializeServer(t *testing.T) { func TestSerializeTopology(t *testing.T) { t.Parallel() - topologyID := primitive.NewObjectID() + topologyID := bson.NewObjectID() tests := []struct { name string @@ -199,7 +199,7 @@ func TestSerializeTopology(t *testing.T) { { name: "empty", want: KeyValues{ - KeyTopologyID, primitive.ObjectID{}.Hex(), + KeyTopologyID, bson.ObjectID{}.Hex(), }, }, { diff --git a/mongo/bulk_write.go b/mongo/bulk_write.go index 3fdb67b9a2..0591dde6a3 100644 --- a/mongo/bulk_write.go +++ b/mongo/bulk_write.go @@ -10,8 +10,7 @@ import ( "context" "errors" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo/description" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/writeconcern" @@ -171,7 +170,7 @@ func (bw *bulkWrite) runInsert(ctx context.Context, batch bulkWriteBatch) (opera if err != nil { return operation.InsertResult{}, err } - doc, _, err = ensureID(doc, primitive.NilObjectID, bw.collection.bsonOpts, bw.collection.registry) + doc, _, err = ensureID(doc, bson.NilObjectID, bw.collection.bsonOpts, bw.collection.registry) if err != nil { return operation.InsertResult{}, err } @@ -291,7 +290,7 @@ func createDeleteDoc( hint interface{}, deleteOne bool, bsonOpts *options.BSONOptions, - registry *bsoncodec.Registry, + registry *bson.Registry, ) (bsoncore.Document, error) { f, err := marshal(filter, bsonOpts, registry) if err != nil { @@ -429,7 +428,7 @@ func createUpdateDoc( multi bool, checkDollarKey bool, bsonOpts *options.BSONOptions, - registry *bsoncodec.Registry, + registry *bson.Registry, ) (bsoncore.Document, error) { f, err := marshal(filter, bsonOpts, registry) if err != nil { diff --git a/mongo/change_stream.go b/mongo/change_stream.go index cfdbb1f2b8..d578abce63 100644 --- a/mongo/change_stream.go +++ b/mongo/change_stream.go @@ -15,8 +15,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/csot" "go.mongodb.org/mongo-driver/mongo/description" "go.mongodb.org/mongo-driver/mongo/options" @@ -82,11 +80,11 @@ type ChangeStream struct { sess *session.Client client *Client bsonOpts *options.BSONOptions - registry *bsoncodec.Registry + registry *bson.Registry streamType StreamType options *options.ChangeStreamOptions selector description.ServerSelector - operationTime *primitive.Timestamp + operationTime *bson.Timestamp wireVersion *description.VersionRange } @@ -95,7 +93,7 @@ type changeStreamConfig struct { readPreference *readpref.ReadPref client *Client bsonOpts *options.BSONOptions - registry *bsoncodec.Registry + registry *bson.Registry streamType StreamType collectionName string databaseName string @@ -219,7 +217,7 @@ func newChangeStream(ctx context.Context, config changeStreamConfig, pipeline in closeImplicitSession(cs.sess) return nil, cs.Err() } - optionValueBSON := bsoncore.Value{Type: bsonType, Data: bsonData} + optionValueBSON := bsoncore.Value{Type: bsoncore.Type(bsonType), Data: bsonData} customOptions[optionName] = optionValueBSON } cs.aggregate.CustomOptions(customOptions) @@ -235,7 +233,7 @@ func newChangeStream(ctx context.Context, config changeStreamConfig, pipeline in closeImplicitSession(cs.sess) return nil, cs.Err() } - optionValueBSON := bsoncore.Value{Type: bsonType, Data: bsonData} + optionValueBSON := bsoncore.Value{Type: bsoncore.Type(bsonType), Data: bsonData} cs.pipelineOptions[optionName] = optionValueBSON } } diff --git a/mongo/client.go b/mongo/client.go index 40c0b3c411..6cba70ce8d 100644 --- a/mongo/client.go +++ b/mongo/client.go @@ -14,7 +14,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/httputil" "go.mongodb.org/mongo-driver/internal/logger" @@ -62,7 +61,7 @@ type Client struct { readConcern *readconcern.ReadConcern writeConcern *writeconcern.WriteConcern bsonOpts *options.BSONOptions - registry *bsoncodec.Registry + registry *bson.Registry monitor *event.CommandMonitor serverAPI *driver.ServerAPIOptions serverMonitor *event.ServerMonitor diff --git a/mongo/client_encryption.go b/mongo/client_encryption.go index e62b872b27..97fe9b27b7 100644 --- a/mongo/client_encryption.go +++ b/mongo/client_encryption.go @@ -13,8 +13,6 @@ import ( "strings" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" "go.mongodb.org/mongo-driver/x/mongo/driver" @@ -108,7 +106,7 @@ func (ce *ClientEncryption) CreateEncryptedCollection(ctx context.Context, if err != nil { return nil, nil, err } - r := bsonrw.NewValueReader(efBSON) + r := bson.NewValueReader(efBSON) dec := bson.NewDecoder(r) var m bson.M err = dec.Decode(&m) @@ -146,7 +144,7 @@ func (ce *ClientEncryption) CreateEncryptedCollection(ctx context.Context, // AddKeyAltName adds a keyAltName to the keyAltNames array of the key document in the key vault collection with the // given UUID (BSON binary subtype 0x04). Returns the previous version of the key document. -func (ce *ClientEncryption) AddKeyAltName(ctx context.Context, id primitive.Binary, keyAltName string) *SingleResult { +func (ce *ClientEncryption) AddKeyAltName(ctx context.Context, id bson.Binary, keyAltName string) *SingleResult { filter := bsoncore.NewDocumentBuilder().AppendBinary("_id", id.Subtype, id.Data).Build() keyAltNameDoc := bsoncore.NewDocumentBuilder().AppendString("keyAltNames", keyAltName).Build() update := bsoncore.NewDocumentBuilder().AppendDocument("$addToSet", keyAltNameDoc).Build() @@ -156,7 +154,7 @@ func (ce *ClientEncryption) AddKeyAltName(ctx context.Context, id primitive.Bina // CreateDataKey creates a new key document and inserts into the key vault collection. Returns the _id of the created // document as a UUID (BSON binary subtype 0x04). func (ce *ClientEncryption) CreateDataKey(ctx context.Context, kmsProvider string, - opts ...*options.DataKeyOptions) (primitive.Binary, error) { + opts ...*options.DataKeyOptions) (bson.Binary, error) { // translate opts to mcopts.DataKeyOptions dko := options.DataKey() @@ -182,7 +180,7 @@ func (ce *ClientEncryption) CreateDataKey(ctx context.Context, kmsProvider strin ce.keyVaultClient.bsonOpts, ce.keyVaultClient.registry) if err != nil { - return primitive.Binary{}, err + return bson.Binary{}, err } co.SetMasterKey(keyDoc) } @@ -193,17 +191,17 @@ func (ce *ClientEncryption) CreateDataKey(ctx context.Context, kmsProvider strin // create data key document dataKeyDoc, err := ce.crypt.CreateDataKey(ctx, kmsProvider, co) if err != nil { - return primitive.Binary{}, err + return bson.Binary{}, err } // insert key into key vault _, err = ce.keyVaultColl.InsertOne(ctx, dataKeyDoc) if err != nil { - return primitive.Binary{}, err + return bson.Binary{}, err } subtype, data := bson.Raw(dataKeyDoc).Lookup("_id").Binary() - return primitive.Binary{Subtype: subtype, Data: data}, nil + return bson.Binary{Subtype: subtype, Data: data}, nil } // transformExplicitEncryptionOptions creates explicit encryption options to be passed to libmongocrypt. @@ -250,10 +248,10 @@ func transformExplicitEncryptionOptions(opts ...*options.EncryptOptions) *mcopts if eo.RangeOptions != nil { var transformedRange mcopts.ExplicitRangeOptions if eo.RangeOptions.Min != nil { - transformedRange.Min = &bsoncore.Value{Type: eo.RangeOptions.Min.Type, Data: eo.RangeOptions.Min.Value} + transformedRange.Min = &bsoncore.Value{Type: bsoncore.Type(eo.RangeOptions.Min.Type), Data: eo.RangeOptions.Min.Value} } if eo.RangeOptions.Max != nil { - transformedRange.Max = &bsoncore.Value{Type: eo.RangeOptions.Max.Type, Data: eo.RangeOptions.Max.Value} + transformedRange.Max = &bsoncore.Value{Type: bsoncore.Type(eo.RangeOptions.Max.Type), Data: eo.RangeOptions.Max.Value} } if eo.RangeOptions.Precision != nil { transformedRange.Precision = eo.RangeOptions.Precision @@ -266,14 +264,14 @@ func transformExplicitEncryptionOptions(opts ...*options.EncryptOptions) *mcopts // Encrypt encrypts a BSON value with the given key and algorithm. Returns an encrypted value (BSON binary of subtype 6). func (ce *ClientEncryption) Encrypt(ctx context.Context, val bson.RawValue, - opts ...*options.EncryptOptions) (primitive.Binary, error) { + opts ...*options.EncryptOptions) (bson.Binary, error) { transformed := transformExplicitEncryptionOptions(opts...) - subtype, data, err := ce.crypt.EncryptExplicit(ctx, bsoncore.Value{Type: val.Type, Data: val.Value}, transformed) + subtype, data, err := ce.crypt.EncryptExplicit(ctx, bsoncore.Value{Type: bsoncore.Type(val.Type), Data: val.Value}, transformed) if err != nil { - return primitive.Binary{}, err + return bson.Binary{}, err } - return primitive.Binary{Subtype: subtype, Data: data}, nil + return bson.Binary{Subtype: subtype, Data: data}, nil } // EncryptExpression encrypts an expression to query a range index. @@ -311,13 +309,13 @@ func (ce *ClientEncryption) EncryptExpression(ctx context.Context, expr interfac } // Decrypt decrypts an encrypted value (BSON binary of subtype 6) and returns the original BSON value. -func (ce *ClientEncryption) Decrypt(ctx context.Context, val primitive.Binary) (bson.RawValue, error) { +func (ce *ClientEncryption) Decrypt(ctx context.Context, val bson.Binary) (bson.RawValue, error) { decrypted, err := ce.crypt.DecryptExplicit(ctx, val.Subtype, val.Data) if err != nil { return bson.RawValue{}, err } - return bson.RawValue{Type: decrypted.Type, Value: decrypted.Data}, nil + return bson.RawValue{Type: bson.Type(decrypted.Type), Value: decrypted.Data}, nil } // Close cleans up any resources associated with the ClientEncryption instance. This includes disconnecting the @@ -329,7 +327,7 @@ func (ce *ClientEncryption) Close(ctx context.Context) error { // DeleteKey removes the key document with the given UUID (BSON binary subtype 0x04) from the key vault collection. // Returns the result of the internal deleteOne() operation on the key vault collection. -func (ce *ClientEncryption) DeleteKey(ctx context.Context, id primitive.Binary) (*DeleteResult, error) { +func (ce *ClientEncryption) DeleteKey(ctx context.Context, id bson.Binary) (*DeleteResult, error) { filter := bsoncore.NewDocumentBuilder().AppendBinary("_id", id.Subtype, id.Data).Build() return ce.keyVaultColl.DeleteOne(ctx, filter) } @@ -342,7 +340,7 @@ func (ce *ClientEncryption) GetKeyByAltName(ctx context.Context, keyAltName stri // GetKey finds a single key document with the given UUID (BSON binary subtype 0x04). Returns the result of the // internal find() operation on the key vault collection. -func (ce *ClientEncryption) GetKey(ctx context.Context, id primitive.Binary) *SingleResult { +func (ce *ClientEncryption) GetKey(ctx context.Context, id bson.Binary) *SingleResult { filter := bsoncore.NewDocumentBuilder().AppendBinary("_id", id.Subtype, id.Data).Build() return ce.keyVaultColl.FindOne(ctx, filter) } @@ -355,7 +353,7 @@ func (ce *ClientEncryption) GetKeys(ctx context.Context) (*Cursor, error) { // RemoveKeyAltName removes a keyAltName from the keyAltNames array of the key document in the key vault collection with // the given UUID (BSON binary subtype 0x04). Returns the previous version of the key document. -func (ce *ClientEncryption) RemoveKeyAltName(ctx context.Context, id primitive.Binary, keyAltName string) *SingleResult { +func (ce *ClientEncryption) RemoveKeyAltName(ctx context.Context, id bson.Binary, keyAltName string) *SingleResult { filter := bsoncore.NewDocumentBuilder().AppendBinary("_id", id.Subtype, id.Data).Build() update := bson.A{bson.D{{"$set", bson.D{{"keyAltNames", bson.D{{"$cond", bson.A{bson.D{{"$eq", bson.A{"$keyAltNames", bson.A{keyAltName}}}}, "$$REMOVE", bson.D{{"$filter", @@ -388,7 +386,7 @@ func setRewrapManyDataKeyWriteModels(rewrappedDocuments []bsoncore.Document, wri return err } keyMaterialSubtype, keyMaterialData := keyMaterialValue.Binary() - keyMaterialBinary := primitive.Binary{Subtype: keyMaterialSubtype, Data: keyMaterialData} + keyMaterialBinary := bson.Binary{Subtype: keyMaterialSubtype, Data: keyMaterialData} // Prepare the _id filter for documents to update. id, err := rewrappedDocument.LookupErr(idKey) @@ -400,7 +398,7 @@ func setRewrapManyDataKeyWriteModels(rewrappedDocuments []bsoncore.Document, wri if !ok { return fmt.Errorf("expected to assert %q as binary, got type %T", idKey, id) } - binaryID := primitive.Binary{Subtype: idSubtype, Data: idData} + binaryID := bson.Binary{Subtype: idSubtype, Data: idData} // Append the mutable document to the slice for bulk update. *writeModels = append(*writeModels, NewUpdateOneModel(). diff --git a/mongo/client_side_encryption_examples_test.go b/mongo/client_side_encryption_examples_test.go index d2e6449fe4..41b62cf3c5 100644 --- a/mongo/client_side_encryption_examples_test.go +++ b/mongo/client_side_encryption_examples_test.go @@ -14,7 +14,6 @@ import ( "log" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo/options" ) @@ -255,7 +254,7 @@ func Example_explictEncryption() { // Decrypt the encrypted field in the found document. decrypted, err := clientEncryption.Decrypt( context.TODO(), - foundDoc["encryptedField"].(primitive.Binary)) + foundDoc["encryptedField"].(bson.Binary)) if err != nil { panic(err) } diff --git a/mongo/collection.go b/mongo/collection.go index 477363b57a..fddfca9f9b 100644 --- a/mongo/collection.go +++ b/mongo/collection.go @@ -15,9 +15,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/csfle" "go.mongodb.org/mongo-driver/mongo/description" "go.mongodb.org/mongo-driver/mongo/options" @@ -41,7 +38,7 @@ type Collection struct { readSelector description.ServerSelector writeSelector description.ServerSelector bsonOpts *options.BSONOptions - registry *bsoncodec.Registry + registry *bson.Registry } // aggregateParams is used to store information to configure an Aggregate operation. @@ -50,7 +47,7 @@ type aggregateParams struct { pipeline interface{} client *Client bsonOpts *options.BSONOptions - registry *bsoncodec.Registry + registry *bson.Registry readConcern *readconcern.ReadConcern writeConcern *writeconcern.WriteConcern retryRead bool @@ -299,7 +296,7 @@ func (coll *Collection) insert(ctx context.Context, documents []interface{}, if err != nil { return nil, err } - bsoncoreDoc, id, err := ensureID(bsoncoreDoc, primitive.NilObjectID, coll.bsonOpts, coll.registry) + bsoncoreDoc, id, err := ensureID(bsoncoreDoc, bson.NilObjectID, coll.bsonOpts, coll.registry) if err != nil { return nil, err } @@ -1080,7 +1077,7 @@ func aggregate(a aggregateParams) (cur *Cursor, err error) { if err != nil { return nil, err } - optionValueBSON := bsoncore.Value{Type: bsonType, Data: bsonData} + optionValueBSON := bsoncore.Value{Type: bsoncore.Type(bsonType), Data: bsonData} customOptions[optionName] = optionValueBSON } op.CustomOptions(customOptions) @@ -1388,7 +1385,7 @@ func (coll *Collection) Distinct(ctx context.Context, fieldName string, filter i retArray := make([]interface{}, len(values)) for i, val := range values { - raw := bson.RawValue{Type: val.Type, Value: val.Data} + raw := bson.RawValue{Type: bson.Type(val.Type), Value: val.Data} err = raw.Unmarshal(&retArray[i]) if err != nil { return nil, err @@ -1930,7 +1927,7 @@ func (coll *Collection) FindOneAndReplace(ctx context.Context, filter interface{ } fo := mergeFindOneAndReplaceOptions(opts...) - op := operation.NewFindAndModify(f).Update(bsoncore.Value{Type: bsontype.EmbeddedDocument, Data: r}). + op := operation.NewFindAndModify(f).Update(bsoncore.Value{Type: bsoncore.TypeEmbeddedDocument, Data: r}). ServerAPI(coll.client.serverAPI).Timeout(coll.client.timeout).MaxTime(fo.MaxTime) if fo.BypassDocumentValidation != nil && *fo.BypassDocumentValidation { op = op.BypassDocumentValidation(*fo.BypassDocumentValidation) diff --git a/mongo/crud_examples_test.go b/mongo/crud_examples_test.go index 47127006f3..9e2290702b 100644 --- a/mongo/crud_examples_test.go +++ b/mongo/crud_examples_test.go @@ -15,7 +15,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readconcern" @@ -227,7 +226,7 @@ func ExampleCollection_Aggregate() { func ExampleCollection_BulkWrite() { var coll *mongo.Collection - var firstID, secondID primitive.ObjectID + var firstID, secondID bson.ObjectID // Update the "email" field for two users. // For each update, specify the Upsert option to insert a new document if a @@ -373,7 +372,7 @@ func ExampleCollection_Find() { func ExampleCollection_FindOne() { var coll *mongo.Collection - var id primitive.ObjectID + var id bson.ObjectID // Find the document for which the _id field matches id. // Specify the Sort option to sort the documents by age. @@ -398,7 +397,7 @@ func ExampleCollection_FindOne() { func ExampleCollection_FindOneAndDelete() { var coll *mongo.Collection - var id primitive.ObjectID + var id bson.ObjectID // Find and delete the document for which the _id field matches id. // Specify the Projection option to only include the name and age fields in @@ -424,7 +423,7 @@ func ExampleCollection_FindOneAndDelete() { func ExampleCollection_FindOneAndReplace() { var coll *mongo.Collection - var id primitive.ObjectID + var id bson.ObjectID // Find the document for which the _id field matches id and add a field // called "location". @@ -453,7 +452,7 @@ func ExampleCollection_FindOneAndReplace() { func ExampleCollection_FindOneAndUpdate() { var coll *mongo.Collection - var id primitive.ObjectID + var id bson.ObjectID // Find the document for which the _id field matches id and set the email to // "newemail@example.com". @@ -511,7 +510,7 @@ func ExampleCollection_InsertOne() { func ExampleCollection_ReplaceOne() { var coll *mongo.Collection - var id primitive.ObjectID + var id bson.ObjectID // Find the document for which the _id field matches id and add a field // called "location". @@ -555,7 +554,7 @@ func ExampleCollection_UpdateMany() { func ExampleCollection_UpdateOne() { var coll *mongo.Collection - var id primitive.ObjectID + var id bson.ObjectID // Find the document for which the _id field matches id and set the email to // "newemail@example.com". @@ -1109,7 +1108,7 @@ func ExampleCollection_Find_primitiveRegex() { // Create a filter to find a document with key "name" and any value that // starts with letter "m". Use the "i" option to indicate // case-insensitivity. - filter := bson.D{{"name", primitive.Regex{Pattern: "^m", Options: "i"}}} + filter := bson.D{{"name", bson.Regex{Pattern: "^m", Options: "i"}}} _, err = coll.Find(ctx, filter) if err != nil { diff --git a/mongo/cursor.go b/mongo/cursor.go index 34551e753a..8f07b1ee9b 100644 --- a/mongo/cursor.go +++ b/mongo/cursor.go @@ -16,8 +16,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" "go.mongodb.org/mongo-driver/x/mongo/driver" @@ -36,7 +34,7 @@ type Cursor struct { batch *bsoncore.Iterator batchLength int bsonOpts *options.BSONOptions - registry *bsoncodec.Registry + registry *bson.Registry clientSession *session.Client err error @@ -45,7 +43,7 @@ type Cursor struct { func newCursor( bc batchCursor, bsonOpts *options.BSONOptions, - registry *bsoncodec.Registry, + registry *bson.Registry, ) (*Cursor, error) { return newCursorWithSession(bc, bsonOpts, registry, nil) } @@ -53,7 +51,7 @@ func newCursor( func newCursorWithSession( bc batchCursor, bsonOpts *options.BSONOptions, - registry *bsoncodec.Registry, + registry *bson.Registry, clientSession *session.Client, ) (*Cursor, error) { if registry == nil { @@ -87,7 +85,7 @@ func newEmptyCursor() *Cursor { // bson.DefaultRegistry will be used. // // The documents parameter must be a slice of documents. The slice may be nil or empty, but all elements must be non-nil. -func NewCursorFromDocuments(documents []interface{}, preloadedErr error, registry *bsoncodec.Registry) (*Cursor, error) { +func NewCursorFromDocuments(documents []interface{}, preloadedErr error, registry *bson.Registry) (*Cursor, error) { if registry == nil { registry = bson.DefaultRegistry } @@ -105,7 +103,7 @@ func NewCursorFromDocuments(documents []interface{}, preloadedErr error, registr doc = bson.Raw(t) } - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc.Reset(vw) enc.SetRegistry(registry) @@ -117,7 +115,7 @@ func NewCursorFromDocuments(documents []interface{}, preloadedErr error, registr copy(dup, buf.Bytes()) values[i] = bsoncore.Value{ - Type: bson.TypeEmbeddedDocument, + Type: bsoncore.TypeEmbeddedDocument, Data: dup, } @@ -238,9 +236,9 @@ func (c *Cursor) next(ctx context.Context, nonBlocking bool) bool { func getDecoder( data []byte, opts *options.BSONOptions, - reg *bsoncodec.Registry, + reg *bson.Registry, ) *bson.Decoder { - dec := bson.NewDecoder(bsonrw.NewValueReader(data)) + dec := bson.NewDecoder(bson.NewValueReader(data)) if opts != nil { if opts.AllowTruncatingDoubles { diff --git a/mongo/cursor_test.go b/mongo/cursor_test.go index 1aaf41555b..be877b7a6c 100644 --- a/mongo/cursor_test.go +++ b/mongo/cursor_test.go @@ -13,7 +13,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/require" "go.mongodb.org/mongo-driver/mongo/options" @@ -42,7 +41,7 @@ func newTestBatchCursor(numBatches, batchSize int) *testBatchCursor { var doc []byte doc = bsoncore.BuildDocumentFromElements(doc, elem) val := bsoncore.Value{ - Type: bsontype.EmbeddedDocument, + Type: bsoncore.TypeEmbeddedDocument, Data: doc, } diff --git a/mongo/database.go b/mongo/database.go index 0123625761..814acb6f2b 100644 --- a/mongo/database.go +++ b/mongo/database.go @@ -13,8 +13,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/csfle" "go.mongodb.org/mongo-driver/mongo/description" "go.mongodb.org/mongo-driver/mongo/options" @@ -41,7 +39,7 @@ type Database struct { readSelector description.ServerSelector writeSelector description.ServerSelector bsonOpts *options.BSONOptions - registry *bsoncodec.Registry + registry *bson.Registry } func newDatabase(client *Client, name string, opts ...*options.DatabaseOptions) *Database { @@ -368,8 +366,8 @@ func (db *Database) ListCollectionSpecifications(ctx context.Context, filter int Name string `bson:"name"` Type string `bson:"type"` Info *struct { - ReadOnly bool `bson:"readOnly"` - UUID *primitive.Binary `bson:"uuid"` + ReadOnly bool `bson:"readOnly"` + UUID *bson.Binary `bson:"uuid"` } `bson:"info"` Options bson.Raw `bson:"options"` IDIndex indexListSpecificationResponse `bson:"idIndex"` diff --git a/mongo/database_test.go b/mongo/database_test.go index fb1ea3a426..31bd900439 100644 --- a/mongo/database_test.go +++ b/mongo/database_test.go @@ -13,7 +13,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readconcern" @@ -54,7 +53,7 @@ func TestDatabase(t *testing.T) { wc2 := &writeconcern.WriteConcern{W: 10} rcLocal := readconcern.Local() rcMajority := readconcern.Majority() - reg := bsoncodec.NewRegistry() + reg := bson.NewRegistry() opts := options.Database().SetReadPreference(rpPrimary).SetReadConcern(rcLocal).SetWriteConcern(wc1). SetReadPreference(rpSecondary).SetReadConcern(rcMajority).SetWriteConcern(wc2).SetRegistry(reg) @@ -71,7 +70,7 @@ func TestDatabase(t *testing.T) { rpPrimary := readpref.Primary() rcLocal := readconcern.Local() wc1 := &writeconcern.WriteConcern{W: 10} - reg := bsoncodec.NewRegistry() + reg := bson.NewRegistry() client := setupClient(options.Client().SetReadPreference(rpPrimary).SetReadConcern(rcLocal).SetRegistry(reg)) got := client.Database("foo", options.Database().SetWriteConcern(wc1)) diff --git a/mongo/description/server.go b/mongo/description/server.go index 0e2830608d..3080a43045 100644 --- a/mongo/description/server.go +++ b/mongo/description/server.go @@ -12,7 +12,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/bsonutil" "go.mongodb.org/mongo-driver/internal/handshake" "go.mongodb.org/mongo-driver/internal/ptrutil" @@ -38,7 +37,7 @@ type Server struct { AverageRTTSet bool Compression []string // compression methods returned by server CanonicalAddr address.Address - ElectionID primitive.ObjectID + ElectionID bson.ObjectID HeartbeatInterval time.Duration HelloOK bool Hosts []string @@ -54,7 +53,7 @@ type Server struct { Passive bool Primary address.Address ReadOnly bool - ServiceID *primitive.ObjectID // Only set for servers that are deployed behind a load balancer. + ServiceID *bson.ObjectID // Only set for servers that are deployed behind a load balancer. SessionTimeoutMinutes *int64 SetName string SetVersion uint32 diff --git a/mongo/description/server_test.go b/mongo/description/server_test.go index 74f02b6cd1..5712086d8e 100644 --- a/mongo/description/server_test.go +++ b/mongo/description/server_test.go @@ -11,7 +11,7 @@ import ( "testing" "time" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/mongo/address" "go.mongodb.org/mongo-driver/tag" @@ -34,7 +34,7 @@ func TestServer(t *testing.T) { {"rtt", Server{AverageRTT: time.Second}, true}, {"compression", Server{Compression: []string{"foo"}}, true}, {"canonicalAddr", Server{CanonicalAddr: address.Address("foo")}, false}, - {"electionID", Server{ElectionID: primitive.NewObjectID()}, false}, + {"electionID", Server{ElectionID: bson.NewObjectID()}, false}, {"heartbeatInterval", Server{HeartbeatInterval: time.Second}, true}, {"hosts", Server{Hosts: []string{"foo"}}, false}, {"lastError", Server{LastError: errors.New("foo")}, false}, @@ -58,7 +58,7 @@ func TestServer(t *testing.T) { {"setName", Server{SetName: "foo"}, false}, {"setVersion", Server{SetVersion: 1}, false}, {"tags", Server{Tags: tag.Set{tag.Tag{"foo", "bar"}}}, false}, - {"topologyVersion", Server{TopologyVersion: &TopologyVersion{primitive.NewObjectID(), 0}}, false}, + {"topologyVersion", Server{TopologyVersion: &TopologyVersion{bson.NewObjectID(), 0}}, false}, {"kind", Server{Kind: Standalone}, false}, {"wireVersion", Server{WireVersion: &VersionRange{1, 2}}, false}, } diff --git a/mongo/description/topology_version.go b/mongo/description/topology_version.go index e6674ea762..2e1b28d588 100644 --- a/mongo/description/topology_version.go +++ b/mongo/description/topology_version.go @@ -10,12 +10,11 @@ import ( "fmt" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" ) // TopologyVersion represents a software version. type TopologyVersion struct { - ProcessID primitive.ObjectID + ProcessID bson.ObjectID Counter int64 } diff --git a/mongo/gridfs_bucket.go b/mongo/gridfs_bucket.go index 8359d07729..7c2bbac64e 100644 --- a/mongo/gridfs_bucket.go +++ b/mongo/gridfs_bucket.go @@ -14,8 +14,6 @@ import ( "io" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/csot" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readconcern" @@ -69,7 +67,7 @@ func (b *GridFSBucket) OpenUploadStream( filename string, opts ...*options.UploadOptions, ) (*GridFSUploadStream, error) { - return b.OpenUploadStreamWithID(ctx, primitive.NewObjectID(), filename, opts...) + return b.OpenUploadStreamWithID(ctx, bson.NewObjectID(), filename, opts...) } // OpenUploadStreamWithID creates a new upload stream for a file given the file @@ -108,8 +106,8 @@ func (b *GridFSBucket) UploadFromStream( filename string, source io.Reader, opts ...*options.UploadOptions, -) (primitive.ObjectID, error) { - fileID := primitive.NewObjectID() +) (bson.ObjectID, error) { + fileID := bson.NewObjectID() err := b.UploadFromStreamWithID(ctx, fileID, filename, source, opts...) return fileID, err } @@ -621,7 +619,7 @@ func (b *GridFSBucket) parseUploadOptions(opts ...*options.UploadOptions) (*uplo // TODO(GODRIVER-2726): Replace with marshal() and unmarshal() once the // TODO gridfs package is merged into the mongo package. buf := new(bytes.Buffer) - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc := bson.NewEncoder(vw) enc.SetRegistry(uo.Registry) err := enc.Encode(uo.Metadata) diff --git a/mongo/gridfs_examples_test.go b/mongo/gridfs_examples_test.go index c3ff7892af..22b1eaf819 100644 --- a/mongo/gridfs_examples_test.go +++ b/mongo/gridfs_examples_test.go @@ -15,7 +15,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) @@ -71,7 +70,7 @@ func ExampleGridFSBucket_UploadFromStream() { func ExampleGridFSBucket_OpenDownloadStream() { var bucket *mongo.GridFSBucket - var fileID primitive.ObjectID + var fileID bson.ObjectID // Use WithContext to force a timeout if the download does not succeed in // 2 seconds. @@ -96,7 +95,7 @@ func ExampleGridFSBucket_OpenDownloadStream() { func ExampleGridFSBucket_DownloadToStream() { var bucket *mongo.GridFSBucket - var fileID primitive.ObjectID + var fileID bson.ObjectID ctx := context.Background() @@ -108,7 +107,7 @@ func ExampleGridFSBucket_DownloadToStream() { func ExampleGridFSBucket_Delete() { var bucket *mongo.GridFSBucket - var fileID primitive.ObjectID + var fileID bson.ObjectID if err := bucket.Delete(context.Background(), fileID); err != nil { log.Fatal(err) @@ -148,7 +147,7 @@ func ExampleGridFSBucket_Find() { func ExampleGridFSBucket_Rename() { var bucket *mongo.GridFSBucket - var fileID primitive.ObjectID + var fileID bson.ObjectID ctx := context.Background() diff --git a/mongo/gridfs_upload_stream.go b/mongo/gridfs_upload_stream.go index a83f250d01..9331e31e9e 100644 --- a/mongo/gridfs_upload_stream.go +++ b/mongo/gridfs_upload_stream.go @@ -15,7 +15,6 @@ import ( "math" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" ) // uploadBufferSize is the size in bytes of one stream batch. Chunks will be written to the db after the sum of chunk @@ -150,10 +149,10 @@ func (us *GridFSUploadStream) uploadChunks(ctx context.Context, uploadPartial bo } chunkData := us.buffer[i:endIndex] docs[us.chunkIndex-begChunkIndex] = bson.D{ - {"_id", primitive.NewObjectID()}, + {"_id", bson.NewObjectID()}, {"files_id", us.FileID}, {"n", int32(us.chunkIndex)}, - {"data", primitive.Binary{Subtype: 0x00, Data: chunkData}}, + {"data", bson.Binary{Subtype: 0x00, Data: chunkData}}, } us.chunkIndex++ us.fileLen += int64(len(chunkData)) @@ -178,7 +177,7 @@ func (us *GridFSUploadStream) createFilesCollDoc(ctx context.Context) error { {"_id", us.FileID}, {"length", us.fileLen}, {"chunkSize", us.chunkSize}, - {"uploadDate", primitive.DateTime(time.Now().UnixNano() / int64(time.Millisecond))}, + {"uploadDate", bson.DateTime(time.Now().UnixNano() / int64(time.Millisecond))}, {"filename", us.filename}, } diff --git a/mongo/index_view.go b/mongo/index_view.go index c6139b9f70..f9a9f8da49 100644 --- a/mongo/index_view.go +++ b/mongo/index_view.go @@ -14,7 +14,6 @@ import ( "strconv" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/mongo/description" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" @@ -500,11 +499,11 @@ func getOrGenerateIndexName(keySpecDocument bsoncore.Document, model IndexModel) bsonValue := elem.Value() switch bsonValue.Type { - case bsontype.Int32: + case bsoncore.TypeInt32: value = fmt.Sprintf("%d", bsonValue.Int32()) - case bsontype.Int64: + case bsoncore.TypeInt64: value = fmt.Sprintf("%d", bsonValue.Int64()) - case bsontype.String: + case bsoncore.TypeString: value = bsonValue.StringValue() default: return "", ErrInvalidIndexValue diff --git a/mongo/mongo.go b/mongo/mongo.go index e33cc44ea0..318c765000 100644 --- a/mongo/mongo.go +++ b/mongo/mongo.go @@ -22,10 +22,6 @@ import ( "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" ) // Dialer is used to make network connections. @@ -57,14 +53,14 @@ func (me MarshalError) Error() string { type Pipeline []bson.D // bvwPool is a pool of BSON value writers. BSON value writers -var bvwPool = bsonrw.NewBSONValueWriterPool() +var bvwPool = bson.NewValueWriterPool() // getEncoder takes a writer, BSON options, and a BSON registry and returns a properly configured // bson.Encoder that writes to the given writer. func getEncoder( w io.Writer, opts *options.BSONOptions, - reg *bsoncodec.Registry, + reg *bson.Registry, ) (*bson.Encoder, error) { vw := bvwPool.Get(w) enc := bson.NewEncoder(vw) @@ -105,7 +101,7 @@ func getEncoder( // newEncoderFn will return a function for constructing an encoder based on the // provided codec options. -func newEncoderFn(opts *options.BSONOptions, registry *bsoncodec.Registry) codecutil.EncoderFn { +func newEncoderFn(opts *options.BSONOptions, registry *bson.Registry) codecutil.EncoderFn { return func(w io.Writer) (*bson.Encoder, error) { return getEncoder(w, opts, registry) } @@ -119,7 +115,7 @@ func newEncoderFn(opts *options.BSONOptions, registry *bsoncodec.Registry) codec func marshal( val interface{}, bsonOpts *options.BSONOptions, - registry *bsoncodec.Registry, + registry *bson.Registry, ) (bsoncore.Document, error) { if registry == nil { registry = bson.DefaultRegistry @@ -148,16 +144,16 @@ func marshal( // ensureID inserts the given ObjectID as an element named "_id" at the // beginning of the given BSON document if there is not an "_id" already. -// If the given ObjectID is primitive.NilObjectID, a new object ID will be +// If the given ObjectID is bson.NilObjectID, a new object ID will be // generated with time.Now(). // // If there is already an element named "_id", the document is not modified. It // returns the resulting document and the decoded Go value of the "_id" element. func ensureID( doc bsoncore.Document, - oid primitive.ObjectID, + oid bson.ObjectID, bsonOpts *options.BSONOptions, - reg *bsoncodec.Registry, + reg *bson.Registry, ) (bsoncore.Document, interface{}, error) { if reg == nil { reg = bson.DefaultRegistry @@ -190,7 +186,7 @@ func ensureID( doc = make(bsoncore.Document, 0, len(olddoc)+extraSpace) _, doc = bsoncore.ReserveLength(doc) if oid.IsZero() { - oid = primitive.NewObjectID() + oid = bson.NewObjectID() } doc = bsoncore.AppendObjectIDElement(doc, "_id", oid) @@ -225,7 +221,7 @@ func ensureNoDollarKey(doc bsoncore.Document) error { func marshalAggregatePipeline( pipeline interface{}, bsonOpts *options.BSONOptions, - registry *bsoncodec.Registry, + registry *bson.Registry, ) (bsoncore.Document, bool, error) { switch t := pipeline.(type) { case bson.ValueMarshaler: @@ -233,8 +229,8 @@ func marshalAggregatePipeline( if err != nil { return nil, false, err } - if btype != bsontype.Array { - return nil, false, fmt.Errorf("ValueMarshaler returned a %v, but was expecting %v", btype, bsontype.Array) + if btype != bson.TypeArray { + return nil, false, fmt.Errorf("ValueMarshaler returned a %v, but was expecting %v", btype, bson.TypeArray) } var hasOutputStage bool @@ -313,7 +309,7 @@ func marshalAggregatePipeline( func marshalUpdateValue( update interface{}, bsonOpts *options.BSONOptions, - registry *bsoncodec.Registry, + registry *bson.Registry, dollarKeysAllowed bool, ) (bsoncore.Value, error) { documentCheckerFunc := ensureDollarKey @@ -326,8 +322,8 @@ func marshalUpdateValue( switch t := update.(type) { case nil: return u, ErrNilDocument - case primitive.D: - u.Type = bsontype.EmbeddedDocument + case bson.D: + u.Type = bsoncore.TypeEmbeddedDocument u.Data, err = marshal(update, bsonOpts, registry) if err != nil { return u, err @@ -335,19 +331,19 @@ func marshalUpdateValue( return u, documentCheckerFunc(u.Data) case bson.Raw: - u.Type = bsontype.EmbeddedDocument + u.Type = bsoncore.TypeEmbeddedDocument u.Data = t return u, documentCheckerFunc(u.Data) case bsoncore.Document: - u.Type = bsontype.EmbeddedDocument + u.Type = bsoncore.TypeEmbeddedDocument u.Data = t return u, documentCheckerFunc(u.Data) case []byte: - u.Type = bsontype.EmbeddedDocument + u.Type = bsoncore.TypeEmbeddedDocument u.Data = t return u, documentCheckerFunc(u.Data) case bson.Marshaler: - u.Type = bsontype.EmbeddedDocument + u.Type = bsoncore.TypeEmbeddedDocument u.Data, err = t.MarshalBSON() if err != nil { return u, err @@ -355,12 +351,14 @@ func marshalUpdateValue( return u, documentCheckerFunc(u.Data) case bson.ValueMarshaler: - u.Type, u.Data, err = t.MarshalBSONValue() + tt, data, err := t.MarshalBSONValue() + u.Type = bsoncore.Type(tt) + u.Data = data if err != nil { return u, err } - if u.Type != bsontype.Array && u.Type != bsontype.EmbeddedDocument { - return u, fmt.Errorf("ValueMarshaler returned a %v, but was expecting %v or %v", u.Type, bsontype.Array, bsontype.EmbeddedDocument) + if u.Type != bsoncore.TypeArray && u.Type != bsoncore.TypeEmbeddedDocument { + return u, fmt.Errorf("ValueMarshaler returned a %v, but was expecting %v or %v", u.Type, bsoncore.TypeArray, bsoncore.TypeEmbeddedDocument) } return u, err default: @@ -369,7 +367,7 @@ func marshalUpdateValue( return u, fmt.Errorf("can only marshal slices and arrays into update pipelines, but got %v", val.Kind()) } if val.Kind() != reflect.Slice && val.Kind() != reflect.Array { - u.Type = bsontype.EmbeddedDocument + u.Type = bsoncore.TypeEmbeddedDocument u.Data, err = marshal(update, bsonOpts, registry) if err != nil { return u, err @@ -378,7 +376,7 @@ func marshalUpdateValue( return u, documentCheckerFunc(u.Data) } - u.Type = bsontype.Array + u.Type = bsoncore.TypeArray aidx, arr := bsoncore.AppendArrayStart(nil) valLen := val.Len() for idx := 0; idx < valLen; idx++ { @@ -401,7 +399,7 @@ func marshalUpdateValue( func marshalValue( val interface{}, bsonOpts *options.BSONOptions, - registry *bsoncodec.Registry, + registry *bson.Registry, ) (bsoncore.Value, error) { return codecutil.MarshalValue(val, newEncoderFn(bsonOpts, registry)) } @@ -410,7 +408,7 @@ func marshalValue( func countDocumentsAggregatePipeline( filter interface{}, encOpts *options.BSONOptions, - registry *bsoncodec.Registry, + registry *bson.Registry, opts *options.CountOptions, ) (bsoncore.Document, error) { filterDoc, err := marshal(filter, encOpts, registry) diff --git a/mongo/mongo_test.go b/mongo/mongo_test.go index 238c75da9b..3c92fdb620 100644 --- a/mongo/mongo_test.go +++ b/mongo/mongo_test.go @@ -12,9 +12,6 @@ import ( "testing" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/codecutil" "go.mongodb.org/mongo-driver/internal/require" @@ -25,13 +22,13 @@ import ( func TestEnsureID(t *testing.T) { t.Parallel() - oid := primitive.NewObjectID() + oid := bson.NewObjectID() testCases := []struct { description string // TODO: Registry? DecodeOptions? doc bsoncore.Document - oid primitive.ObjectID + oid bson.ObjectID want bsoncore.Document wantID interface{} }{ @@ -125,9 +122,9 @@ func TestEnsureID(t *testing.T) { assert.Equal(t, tc.wantID, gotID, "expected and actual IDs are different") // Ensure that if the unmarshaled "_id" value is a - // primitive.ObjectID that it is a deep copy and does not share any + // bson.ObjectID that it is a deep copy and does not share any // memory with the document byte slice. - if oid, ok := gotID.(primitive.ObjectID); ok { + if oid, ok := gotID.(bson.ObjectID); ok { assert.DifferentAddressRanges(t, tc.doc, oid[:]) } }) @@ -141,13 +138,13 @@ func TestEnsureID_NilObjectID(t *testing.T) { AppendString("foo", "bar"). Build() - got, gotIDI, err := ensureID(doc, primitive.NilObjectID, nil, nil) + got, gotIDI, err := ensureID(doc, bson.NilObjectID, nil, nil) assert.NoError(t, err) - gotID, ok := gotIDI.(primitive.ObjectID) + gotID, ok := gotIDI.(bson.ObjectID) assert.True(t, ok) - assert.NotEqual(t, primitive.NilObjectID, gotID) + assert.NotEqual(t, bson.NilObjectID, gotID) want := bsoncore.NewDocumentBuilder(). AppendObjectID("_id", gotID). @@ -207,7 +204,7 @@ func TestMarshalAggregatePipeline(t *testing.T) { Pipeline{{{"hello", func() {}}}}, nil, false, - MarshalError{Value: primitive.D{}, Err: errors.New("no encoder found for func()")}, + MarshalError{Value: bson.D{}, Err: errors.New("no encoder found for func()")}, }, { "Pipeline/success", @@ -240,15 +237,15 @@ func TestMarshalAggregatePipeline(t *testing.T) { nil, }, { - "primitive.A/error", - primitive.A{"5"}, + "bson.A/error", + bson.A{"5"}, nil, false, MarshalError{Value: "", Err: errors.New("WriteString can only write while positioned on a Element or Value but is positioned on a TopLevel")}, }, { - "primitive.A/success", - primitive.A{bson.D{{"$limit", int32(12345)}}, map[string]interface{}{"$count": "foobar"}}, + "bson.A/success", + bson.A{bson.D{{"$limit", int32(12345)}}, map[string]interface{}{"$count": "foobar"}}, bson.A{ bson.D{{"$limit", int(12345)}}, bson.D{{"$count", "foobar"}}, @@ -291,29 +288,29 @@ func TestMarshalAggregatePipeline(t *testing.T) { nil, }, { - "bsoncodec.ValueMarshaler/MarshalBSONValue error", + "bson.ValueMarshaler/MarshalBSONValue error", bvMarsh{err: errors.New("MarshalBSONValue error")}, nil, false, errors.New("MarshalBSONValue error"), }, { - "bsoncodec.ValueMarshaler/not array", - bvMarsh{t: bsontype.String}, + "bson.ValueMarshaler/not array", + bvMarsh{t: bson.TypeString}, nil, false, - fmt.Errorf("ValueMarshaler returned a %v, but was expecting %v", bsontype.String, bsontype.Array), + fmt.Errorf("ValueMarshaler returned a %v, but was expecting %v", bson.TypeString, bson.TypeArray), }, { - "bsoncodec.ValueMarshaler/UnmarshalBSONValue error", + "bson.ValueMarshaler/UnmarshalBSONValue error", bvMarsh{err: errors.New("UnmarshalBSONValue error")}, nil, false, errors.New("UnmarshalBSONValue error"), }, { - "bsoncodec.ValueMarshaler/success", - bvMarsh{t: bsontype.Array, data: arr}, + "bson.ValueMarshaler/success", + bvMarsh{t: bson.TypeArray, data: arr}, bson.A{ bson.D{{"$limit", int32(12345)}}, }, @@ -321,8 +318,8 @@ func TestMarshalAggregatePipeline(t *testing.T) { nil, }, { - "bsoncodec.ValueMarshaler/success nil", - bvMarsh{t: bsontype.Array}, + "bson.ValueMarshaler/success nil", + bvMarsh{t: bson.TypeArray}, nil, false, nil, @@ -350,7 +347,7 @@ func TestMarshalAggregatePipeline(t *testing.T) { }, { "array/success", - [1]interface{}{primitive.D{{"$limit", int64(12345)}}}, + [1]interface{}{bson.D{{"$limit", int64(12345)}}}, bson.A{ bson.D{{"$limit", int64(12345)}}, }, @@ -366,7 +363,7 @@ func TestMarshalAggregatePipeline(t *testing.T) { }, { "slice/success", - []interface{}{primitive.D{{"$limit", int64(12345)}}}, + []interface{}{bson.D{{"$limit", int64(12345)}}}, bson.A{ bson.D{{"$limit", int64(12345)}}, }, @@ -416,7 +413,7 @@ func TestMarshalAggregatePipeline(t *testing.T) { bson.D{{"x", 1}}, nil, false, - errors.New("primitive.D is not an allowed pipeline type as it represents a single document. Use bson.A or mongo.Pipeline instead"), + errors.New("bson.D is not an allowed pipeline type as it represents a single document. Use bson.A or mongo.Pipeline instead"), }, { "semantic single document/bson.Raw", @@ -530,7 +527,7 @@ func TestMarshalValue(t *testing.T) { name string value interface{} bsonOpts *options.BSONOptions - registry *bsoncodec.Registry + registry *bson.Registry want bsoncore.Value wantErr error }{ @@ -543,7 +540,7 @@ func TestMarshalValue(t *testing.T) { name: "value marshaler", value: valueMarshaler, want: bsoncore.Value{ - Type: valueMarshaler.t, + Type: bsoncore.Type(valueMarshaler.t), Data: valueMarshaler.data, }, }, @@ -551,7 +548,7 @@ func TestMarshalValue(t *testing.T) { name: "document", value: bson.D{{Key: "x", Value: int64(1)}}, want: bsoncore.Value{ - Type: bson.TypeEmbeddedDocument, + Type: bsoncore.TypeEmbeddedDocument, Data: bsoncore.NewDocumentBuilder(). AppendInt64("x", 1). Build(), @@ -584,7 +581,7 @@ func TestMarshalValue(t *testing.T) { UseJSONStructTags: true, }, want: bsoncore.Value{ - Type: bson.TypeEmbeddedDocument, + Type: bsoncore.TypeEmbeddedDocument, Data: bsoncore.NewDocumentBuilder(). AppendInt32("int", 1). AppendBinary("nilbytes", 0, []byte{}). @@ -614,11 +611,11 @@ func TestMarshalValue(t *testing.T) { var _ bson.ValueMarshaler = bvMarsh{} type bvMarsh struct { - t bsontype.Type + t bson.Type data []byte err error } -func (b bvMarsh) MarshalBSONValue() (bsontype.Type, []byte, error) { +func (b bvMarsh) MarshalBSONValue() (bson.Type, []byte, error) { return b.t, b.data, b.err } diff --git a/mongo/options/changestreamoptions.go b/mongo/options/changestreamoptions.go index 060226f955..02140aaac1 100644 --- a/mongo/options/changestreamoptions.go +++ b/mongo/options/changestreamoptions.go @@ -10,7 +10,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" ) // ChangeStreamOptions represents options that can be used to configure a Watch operation. @@ -52,7 +51,7 @@ type ChangeStreamOptions struct { // If specified, the change stream will only return changes that occurred at or after the given timestamp. This // option is only valid for MongoDB versions >= 4.0. If this is specified, ResumeAfter and StartAfter must not be // set. - StartAtOperationTime *primitive.Timestamp + StartAtOperationTime *bson.Timestamp // A document specifying the logical starting point for the change stream. This is similar to the ResumeAfter // option, but allows a resume token from an "invalidate" notification to be used. This allows a change stream on a @@ -127,7 +126,7 @@ func (cso *ChangeStreamOptions) SetShowExpandedEvents(see bool) *ChangeStreamOpt } // SetStartAtOperationTime sets the value for the StartAtOperationTime field. -func (cso *ChangeStreamOptions) SetStartAtOperationTime(t *primitive.Timestamp) *ChangeStreamOptions { +func (cso *ChangeStreamOptions) SetStartAtOperationTime(t *bson.Timestamp) *ChangeStreamOptions { cso.StartAtOperationTime = t return cso } diff --git a/mongo/options/clientoptions.go b/mongo/options/clientoptions.go index 20299b6243..b5fe1931ea 100644 --- a/mongo/options/clientoptions.go +++ b/mongo/options/clientoptions.go @@ -21,7 +21,7 @@ import ( "time" "github.com/youmark/pkcs8" - "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/httputil" "go.mongodb.org/mongo-driver/mongo/readconcern" @@ -221,7 +221,7 @@ type ClientOptions struct { ReadConcern *readconcern.ReadConcern ReadPreference *readpref.ReadPref BSONOptions *BSONOptions - Registry *bsoncodec.Registry + Registry *bson.Registry ReplicaSet *string RetryReads *bool RetryWrites *bool @@ -778,7 +778,7 @@ func (c *ClientOptions) SetBSONOptions(opts *BSONOptions) *ClientOptions { // SetRegistry specifies the BSON registry to use for BSON marshalling/unmarshalling operations. The default is // bson.DefaultRegistry. -func (c *ClientOptions) SetRegistry(registry *bsoncodec.Registry) *ClientOptions { +func (c *ClientOptions) SetRegistry(registry *bson.Registry) *ClientOptions { c.Registry = registry return c } diff --git a/mongo/options/clientoptions_test.go b/mongo/options/clientoptions_test.go index f5e083a9e4..beba45514f 100644 --- a/mongo/options/clientoptions_test.go +++ b/mongo/options/clientoptions_test.go @@ -25,7 +25,6 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/httputil" @@ -148,7 +147,7 @@ func TestClientOptions(t *testing.T) { if !cmp.Equal( got.Interface(), want.Interface(), cmp.AllowUnexported(readconcern.ReadConcern{}, writeconcern.WriteConcern{}, readpref.ReadPref{}), - cmp.Comparer(func(r1, r2 *bsoncodec.Registry) bool { return r1 == r2 }), + cmp.Comparer(func(r1, r2 *bson.Registry) bool { return r1 == r2 }), cmp.Comparer(func(cfg1, cfg2 *tls.Config) bool { return cfg1 == cfg2 }), cmp.Comparer(func(fp1, fp2 *event.PoolMonitor) bool { return fp1 == fp2 }), ) { @@ -162,7 +161,7 @@ func TestClientOptions(t *testing.T) { if diff := cmp.Diff( got, want, cmp.AllowUnexported(readconcern.ReadConcern{}, writeconcern.WriteConcern{}, readpref.ReadPref{}), - cmp.Comparer(func(r1, r2 *bsoncodec.Registry) bool { return r1 == r2 }), + cmp.Comparer(func(r1, r2 *bson.Registry) bool { return r1 == r2 }), cmp.Comparer(func(cfg1, cfg2 *tls.Config) bool { return cfg1 == cfg2 }), cmp.Comparer(func(fp1, fp2 *event.PoolMonitor) bool { return fp1 == fp2 }), cmp.AllowUnexported(ClientOptions{}), @@ -586,7 +585,7 @@ func TestClientOptions(t *testing.T) { if diff := cmp.Diff( tc.result, result, cmp.AllowUnexported(ClientOptions{}, readconcern.ReadConcern{}, writeconcern.WriteConcern{}, readpref.ReadPref{}), - cmp.Comparer(func(r1, r2 *bsoncodec.Registry) bool { return r1 == r2 }), + cmp.Comparer(func(r1, r2 *bson.Registry) bool { return r1 == r2 }), cmp.Comparer(compareTLSConfig), cmp.Comparer(compareErrors), cmpopts.SortSlices(stringLess), diff --git a/mongo/options/collectionoptions.go b/mongo/options/collectionoptions.go index 14e93f8fac..d6e10713ef 100644 --- a/mongo/options/collectionoptions.go +++ b/mongo/options/collectionoptions.go @@ -7,7 +7,7 @@ package options import ( - "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo/readconcern" "go.mongodb.org/mongo-driver/mongo/readpref" "go.mongodb.org/mongo-driver/mongo/writeconcern" @@ -33,7 +33,7 @@ type CollectionOptions struct { // Registry is the BSON registry to marshal and unmarshal documents for operations executed on the Collection. The default value // is nil, which means that the registry of the Database used to configure the Collection will be used. - Registry *bsoncodec.Registry + Registry *bson.Registry } // Collection creates a new CollectionOptions instance. @@ -66,7 +66,7 @@ func (c *CollectionOptions) SetBSONOptions(opts *BSONOptions) *CollectionOptions } // SetRegistry sets the value for the Registry field. -func (c *CollectionOptions) SetRegistry(r *bsoncodec.Registry) *CollectionOptions { +func (c *CollectionOptions) SetRegistry(r *bson.Registry) *CollectionOptions { c.Registry = r return c } diff --git a/mongo/options/dboptions.go b/mongo/options/dboptions.go index 99c2d8fff2..3e1a7808b5 100644 --- a/mongo/options/dboptions.go +++ b/mongo/options/dboptions.go @@ -7,7 +7,7 @@ package options import ( - "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo/readconcern" "go.mongodb.org/mongo-driver/mongo/readpref" "go.mongodb.org/mongo-driver/mongo/writeconcern" @@ -33,7 +33,7 @@ type DatabaseOptions struct { // Registry is the BSON registry to marshal and unmarshal documents for operations executed on the Database. The default value // is nil, which means that the registry of the Client used to configure the Database will be used. - Registry *bsoncodec.Registry + Registry *bson.Registry } // Database creates a new DatabaseOptions instance. @@ -66,7 +66,7 @@ func (d *DatabaseOptions) SetBSONOptions(opts *BSONOptions) *DatabaseOptions { } // SetRegistry sets the value for the Registry field. -func (d *DatabaseOptions) SetRegistry(r *bsoncodec.Registry) *DatabaseOptions { +func (d *DatabaseOptions) SetRegistry(r *bson.Registry) *DatabaseOptions { d.Registry = r return d } diff --git a/mongo/options/encryptoptions.go b/mongo/options/encryptoptions.go index c11a541916..daebf45021 100644 --- a/mongo/options/encryptoptions.go +++ b/mongo/options/encryptoptions.go @@ -8,7 +8,6 @@ package options import ( "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" ) // These constants specify valid values for QueryType @@ -28,7 +27,7 @@ type RangeOptions struct { // EncryptOptions represents options to explicitly encrypt a value. type EncryptOptions struct { - KeyID *primitive.Binary + KeyID *bson.Binary KeyAltName *string Algorithm string QueryType string @@ -41,8 +40,8 @@ func Encrypt() *EncryptOptions { return &EncryptOptions{} } -// SetKeyID specifies an _id of a data key. This should be a UUID (a primitive.Binary with subtype 4). -func (e *EncryptOptions) SetKeyID(keyID primitive.Binary) *EncryptOptions { +// SetKeyID specifies an _id of a data key. This should be a UUID (a bson.Binary with subtype 4). +func (e *EncryptOptions) SetKeyID(keyID bson.Binary) *EncryptOptions { e.KeyID = &keyID return e } diff --git a/mongo/options/gridfsoptions.go b/mongo/options/gridfsoptions.go index ed525b34f4..10d454c89d 100644 --- a/mongo/options/gridfsoptions.go +++ b/mongo/options/gridfsoptions.go @@ -10,7 +10,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" "go.mongodb.org/mongo-driver/mongo/readconcern" "go.mongodb.org/mongo-driver/mongo/readpref" "go.mongodb.org/mongo-driver/mongo/writeconcern" @@ -95,7 +94,7 @@ type UploadOptions struct { Metadata interface{} // The BSON registry to use for converting filters to BSON documents. The default value is bson.DefaultRegistry. - Registry *bsoncodec.Registry + Registry *bson.Registry } // GridFSUpload creates a new UploadOptions instance. diff --git a/mongo/options/mongooptions.go b/mongo/options/mongooptions.go index a4bfc66254..2279f66d0d 100644 --- a/mongo/options/mongooptions.go +++ b/mongo/options/mongooptions.go @@ -11,8 +11,6 @@ import ( "strconv" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsonrw" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -119,7 +117,7 @@ type ArrayFilters struct { // Registry is the registry to use for converting filters. Defaults to bson.DefaultRegistry. // // Deprecated: Marshaling ArrayFilters to BSON will not be supported in Go Driver 2.0. - Registry *bsoncodec.Registry + Registry *bson.Registry Filters []interface{} // The filters to apply } @@ -137,7 +135,7 @@ func (af *ArrayFilters) ToArray() ([]bson.Raw, error) { enc := new(bson.Encoder) for _, f := range af.Filters { buf.Reset() - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc.Reset(vw) enc.SetRegistry(registry) err := enc.Encode(f) @@ -164,7 +162,7 @@ func (af *ArrayFilters) ToArrayDocument() (bson.Raw, error) { enc := new(bson.Encoder) for i, f := range af.Filters { buf.Reset() - vw := bsonrw.NewValueWriter(buf) + vw := bson.NewValueWriter(buf) enc.Reset(vw) enc.SetRegistry(registry) err := enc.Encode(f) diff --git a/mongo/read_write_concern_spec_test.go b/mongo/read_write_concern_spec_test.go index 45e290943c..ec49bb91db 100644 --- a/mongo/read_write_concern_spec_test.go +++ b/mongo/read_write_concern_spec_test.go @@ -16,8 +16,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/mongo/readconcern" "go.mongodb.org/mongo-driver/mongo/writeconcern" @@ -33,7 +31,7 @@ const ( var ( serverDefaultConcern = []byte{5, 0, 0, 0, 0} // server default read concern and write concern is empty document - specTestRegistry = func() *bsoncodec.Registry { + specTestRegistry = func() *bson.Registry { reg := bson.NewRegistry() reg.RegisterTypeMapEntry(bson.TypeEmbeddedDocument, reflect.TypeOf(bson.Raw{})) return reg @@ -241,10 +239,10 @@ func writeConcernFromRaw(t *testing.T, wcRaw bson.Raw) writeConcern { case "w": wc.wSet = true switch val.Type { - case bsontype.Int32: + case bson.TypeInt32: w := int(val.Int32()) wc.WriteConcern.W = w - case bsontype.String: + case bson.TypeString: wc.WriteConcern.W = val.StringValue() default: t.Fatalf("unexpected type for w: %v", val.Type) diff --git a/mongo/readconcern/readconcern.go b/mongo/readconcern/readconcern.go index 398d843012..b2ef19c96a 100644 --- a/mongo/readconcern/readconcern.go +++ b/mongo/readconcern/readconcern.go @@ -13,7 +13,7 @@ package readconcern import ( "errors" - "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -74,7 +74,7 @@ func Snapshot() *ReadConcern { // MarshalBSONValue implements the bson.ValueMarshaler interface. // // Deprecated: Marshaling a ReadConcern to BSON will not be supported in Go Driver 2.0. -func (rc *ReadConcern) MarshalBSONValue() (bsontype.Type, []byte, error) { +func (rc *ReadConcern) MarshalBSONValue() (bson.Type, []byte, error) { if rc == nil { return 0, nil, errors.New("cannot marshal nil ReadConcern") } @@ -85,5 +85,5 @@ func (rc *ReadConcern) MarshalBSONValue() (bsontype.Type, []byte, error) { elems = bsoncore.AppendStringElement(elems, "level", rc.Level) } - return bsontype.EmbeddedDocument, bsoncore.BuildDocument(nil, elems), nil + return bson.TypeEmbeddedDocument, bsoncore.BuildDocument(nil, elems), nil } diff --git a/mongo/results.go b/mongo/results.go index 14e09e0338..0dfe510440 100644 --- a/mongo/results.go +++ b/mongo/results.go @@ -8,7 +8,6 @@ package mongo import ( "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/x/mongo/driver/operation" ) @@ -35,13 +34,13 @@ type BulkWriteResult struct { // InsertOneResult is the result type returned by an InsertOne operation. type InsertOneResult struct { - // The _id of the inserted document. A value generated by the driver will be of type primitive.ObjectID. + // The _id of the inserted document. A value generated by the driver will be of type bson.ObjectID. InsertedID interface{} } // InsertManyResult is a result type returned by an InsertMany operation. type InsertManyResult struct { - // The _id values of the inserted documents. Values generated by the driver will be of type primitive.ObjectID. + // The _id values of the inserted documents. Values generated by the driver will be of type bson.ObjectID. InsertedIDs []interface{} } @@ -164,8 +163,8 @@ type CollectionSpecification struct { ReadOnly bool // The collection UUID. This field will be nil for MongoDB versions < 3.6. For versions 3.6 and higher, this will - // be a primitive.Binary with Subtype 4. - UUID *primitive.Binary + // be a bson.Binary with Subtype 4. + UUID *bson.Binary // A document containing the options used to construct the collection. Options bson.Raw diff --git a/mongo/session.go b/mongo/session.go index dcd83f650c..3af4452f5f 100644 --- a/mongo/session.go +++ b/mongo/session.go @@ -12,7 +12,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo/description" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" @@ -120,7 +119,7 @@ type Session interface { ClusterTime() bson.Raw // OperationTime returns the current operation time document associated with the session. - OperationTime() *primitive.Timestamp + OperationTime() *bson.Timestamp // Client the Client associated with the session. Client() *Client @@ -135,7 +134,7 @@ type Session interface { // AdvanceOperationTime advances the operation time for a session. This method returns an error // if the session has ended. - AdvanceOperationTime(*primitive.Timestamp) error + AdvanceOperationTime(*bson.Timestamp) error session() } @@ -376,12 +375,12 @@ func (s *sessionImpl) AdvanceClusterTime(d bson.Raw) error { } // OperationTime implements the Session interface. -func (s *sessionImpl) OperationTime() *primitive.Timestamp { +func (s *sessionImpl) OperationTime() *bson.Timestamp { return s.clientSession.OperationTime } // AdvanceOperationTime implements the Session interface. -func (s *sessionImpl) AdvanceOperationTime(ts *primitive.Timestamp) error { +func (s *sessionImpl) AdvanceOperationTime(ts *bson.Timestamp) error { return s.clientSession.AdvanceOperationTime(ts) } diff --git a/mongo/single_result.go b/mongo/single_result.go index 0c51f199ce..e0639e4069 100644 --- a/mongo/single_result.go +++ b/mongo/single_result.go @@ -11,7 +11,6 @@ import ( "errors" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" "go.mongodb.org/mongo-driver/mongo/options" ) @@ -28,7 +27,7 @@ type SingleResult struct { cur *Cursor rdr bson.Raw bsonOpts *options.BSONOptions - reg *bsoncodec.Registry + reg *bson.Registry } // NewSingleResultFromDocument creates a SingleResult with the provided error, registry, and an underlying Cursor pre-loaded with @@ -36,7 +35,7 @@ type SingleResult struct { // from the one provided occurs during creation of the SingleResult, that error will be stored on the returned SingleResult. // // The document parameter must be a non-nil document. -func NewSingleResultFromDocument(document interface{}, err error, registry *bsoncodec.Registry) *SingleResult { +func NewSingleResultFromDocument(document interface{}, err error, registry *bson.Registry) *SingleResult { if document == nil { return &SingleResult{err: ErrNilDocument} } diff --git a/mongo/writeconcern/writeconcern.go b/mongo/writeconcern/writeconcern.go index cf1e401284..abd85df195 100644 --- a/mongo/writeconcern/writeconcern.go +++ b/mongo/writeconcern/writeconcern.go @@ -16,7 +16,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -149,7 +148,7 @@ func Custom(tag string) *WriteConcern { // // Deprecated: Marshaling a WriteConcern to BSON will not be supported in Go // Driver 2.0. -func (wc *WriteConcern) MarshalBSONValue() (bsontype.Type, []byte, error) { +func (wc *WriteConcern) MarshalBSONValue() (bson.Type, []byte, error) { if wc == nil { return 0, nil, ErrEmptyWriteConcern } diff --git a/mongo/writeconcern/writeconcern_test.go b/mongo/writeconcern/writeconcern_test.go index 8f1da38499..b3486fe4f9 100644 --- a/mongo/writeconcern/writeconcern_test.go +++ b/mongo/writeconcern/writeconcern_test.go @@ -12,7 +12,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/require" "go.mongodb.org/mongo-driver/mongo/writeconcern" @@ -26,7 +25,7 @@ func TestWriteConcern_MarshalBSONValue(t *testing.T) { testCases := []struct { name string wc *writeconcern.WriteConcern - wantType bsontype.Type + wantType bson.Type wantValue bson.D wantError error }{ diff --git a/x/bsonx/bsoncore/array_test.go b/x/bsonx/bsoncore/array_test.go index 4171adade7..a6fa6fcd2c 100644 --- a/x/bsonx/bsoncore/array_test.go +++ b/x/bsonx/bsoncore/array_test.go @@ -14,7 +14,6 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsontype" ) func TestArray(t *testing.T) { @@ -151,21 +150,21 @@ func TestArray(t *testing.T) { {"first", 0, Value{ - Type: bsontype.String, + Type: TypeString, Data: []byte{0x04, 0x00, 0x00, 0x00, 0x62, 0x61, 0x72, 0x00}, }, }, {"second", 1, Value{ - Type: bsontype.String, + Type: TypeString, Data: []byte{0x04, 0x00, 0x00, 0x00, 0x62, 0x61, 0x7a, 0x00}, }, }, {"third", 2, Value{ - Type: bsontype.String, + Type: TypeString, Data: []byte{0x04, 0x00, 0x00, 0x00, 0x71, 0x75, 0x78, 0x00}, }, }, diff --git a/x/bsonx/bsoncore/bson_arraybuilder.go b/x/bsonx/bsoncore/bson_arraybuilder.go index 7e6937d896..8856c11330 100644 --- a/x/bsonx/bsoncore/bson_arraybuilder.go +++ b/x/bsonx/bsoncore/bson_arraybuilder.go @@ -8,9 +8,6 @@ package bsoncore import ( "strconv" - - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" ) // ArrayBuilder builds a bson array @@ -84,7 +81,7 @@ func (a *ArrayBuilder) AppendString(str string) *ArrayBuilder { } // AppendObjectID will append oid to ArrayBuilder.doc -func (a *ArrayBuilder) AppendObjectID(oid primitive.ObjectID) *ArrayBuilder { +func (a *ArrayBuilder) AppendObjectID(oid objectID) *ArrayBuilder { a.arr = AppendObjectIDElement(a.arr, a.incrementKey(), oid) return a } @@ -127,7 +124,7 @@ func (a *ArrayBuilder) AppendRegex(pattern, options string) *ArrayBuilder { } // AppendDBPointer will append ns and oid to a.arr -func (a *ArrayBuilder) AppendDBPointer(ns string, oid primitive.ObjectID) *ArrayBuilder { +func (a *ArrayBuilder) AppendDBPointer(ns string, oid objectID) *ArrayBuilder { a.arr = AppendDBPointerElement(a.arr, a.incrementKey(), ns, oid) return a } @@ -163,8 +160,8 @@ func (a *ArrayBuilder) AppendInt64(i64 int64) *ArrayBuilder { } // AppendDecimal128 will append d128 to a.arr -func (a *ArrayBuilder) AppendDecimal128(d128 primitive.Decimal128) *ArrayBuilder { - a.arr = AppendDecimal128Element(a.arr, a.incrementKey(), d128) +func (a *ArrayBuilder) AppendDecimal128(high, low uint64) *ArrayBuilder { + a.arr = AppendDecimal128Element(a.arr, a.incrementKey(), high, low) return a } @@ -189,7 +186,7 @@ func (a *ArrayBuilder) AppendValue(val Value) *ArrayBuilder { // StartArray starts building an inline Array. After this document is completed, // the user must call a.FinishArray func (a *ArrayBuilder) StartArray() *ArrayBuilder { - a.arr = AppendHeader(a.arr, bsontype.Array, a.incrementKey()) + a.arr = AppendHeader(a.arr, TypeArray, a.incrementKey()) a.startArray() return a } diff --git a/x/bsonx/bsoncore/bson_arraybuilder_test.go b/x/bsonx/bsoncore/bson_arraybuilder_test.go index 583e7e5136..7e35c49e72 100644 --- a/x/bsonx/bsoncore/bson_arraybuilder_test.go +++ b/x/bsonx/bsoncore/bson_arraybuilder_test.go @@ -12,8 +12,6 @@ import ( "math" "reflect" "testing" - - "go.mongodb.org/mongo-driver/bson/primitive" ) func TestArrayBuilder(t *testing.T) { @@ -67,10 +65,10 @@ func TestArrayBuilder(t *testing.T) { "AppendObjectID", NewArrayBuilder().AppendObjectID, []interface{}{ - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + [12]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, }, BuildDocumentFromElements(nil, AppendObjectIDElement(nil, "0", - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C})), + [12]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C})), }, { "AppendBoolean", @@ -123,8 +121,8 @@ func TestArrayBuilder(t *testing.T) { { "AppendDecimal128", NewArrayBuilder().AppendDecimal128, - []interface{}{primitive.NewDecimal128(4294967296, 65536)}, - BuildDocumentFromElements(nil, AppendDecimal128Element(nil, "0", primitive.NewDecimal128(4294967296, 65536))), + []interface{}{uint64(4294967296), uint64(65536)}, + BuildDocumentFromElements(nil, AppendDecimal128Element(nil, "0", 4294967296, 65536)), }, { "AppendMaxKey", @@ -148,9 +146,9 @@ func TestArrayBuilder(t *testing.T) { "AppendDBPointer", NewArrayBuilder().AppendDBPointer, []interface{}{"barbaz", - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}}, + [12]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}}, BuildDocumentFromElements(nil, AppendDBPointerElement(nil, "0", "barbaz", - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C})), + [12]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C})), }, { "AppendUndefined", diff --git a/x/bsonx/bsoncore/bson_documentbuilder.go b/x/bsonx/bsoncore/bson_documentbuilder.go index 52162f8aa0..931fc6bff0 100644 --- a/x/bsonx/bsoncore/bson_documentbuilder.go +++ b/x/bsonx/bsoncore/bson_documentbuilder.go @@ -6,11 +6,6 @@ package bsoncore -import ( - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" -) - // DocumentBuilder builds a bson document type DocumentBuilder struct { doc []byte @@ -54,7 +49,7 @@ func (db *DocumentBuilder) AppendDocument(key string, doc []byte) *DocumentBuild // AppendArray will append a bson array using key and arr to DocumentBuilder.doc func (db *DocumentBuilder) AppendArray(key string, arr []byte) *DocumentBuilder { - db.doc = AppendHeader(db.doc, bsontype.Array, key) + db.doc = AppendHeader(db.doc, TypeArray, key) db.doc = AppendArray(db.doc, arr) return db } @@ -72,7 +67,7 @@ func (db *DocumentBuilder) AppendString(key string, str string) *DocumentBuilder } // AppendObjectID will append oid to DocumentBuilder.doc with the given key -func (db *DocumentBuilder) AppendObjectID(key string, oid primitive.ObjectID) *DocumentBuilder { +func (db *DocumentBuilder) AppendObjectID(key string, oid objectID) *DocumentBuilder { db.doc = AppendObjectIDElement(db.doc, key, oid) return db } @@ -115,7 +110,7 @@ func (db *DocumentBuilder) AppendRegex(key, pattern, options string) *DocumentBu } // AppendDBPointer will append ns and oid to using key to db.doc -func (db *DocumentBuilder) AppendDBPointer(key string, ns string, oid primitive.ObjectID) *DocumentBuilder { +func (db *DocumentBuilder) AppendDBPointer(key string, ns string, oid objectID) *DocumentBuilder { db.doc = AppendDBPointerElement(db.doc, key, ns, oid) return db } @@ -151,8 +146,8 @@ func (db *DocumentBuilder) AppendInt64(key string, i64 int64) *DocumentBuilder { } // AppendDecimal128 will append d128 to db.doc using provided key -func (db *DocumentBuilder) AppendDecimal128(key string, d128 primitive.Decimal128) *DocumentBuilder { - db.doc = AppendDecimal128Element(db.doc, key, d128) +func (db *DocumentBuilder) AppendDecimal128(key string, high, low uint64) *DocumentBuilder { + db.doc = AppendDecimal128Element(db.doc, key, high, low) return db } @@ -177,7 +172,7 @@ func (db *DocumentBuilder) AppendValue(key string, val Value) *DocumentBuilder { // StartDocument starts building an inline document element with the provided key // After this document is completed, the user must call finishDocument func (db *DocumentBuilder) StartDocument(key string) *DocumentBuilder { - db.doc = AppendHeader(db.doc, bsontype.EmbeddedDocument, key) + db.doc = AppendHeader(db.doc, TypeEmbeddedDocument, key) db = db.startDocument() return db } diff --git a/x/bsonx/bsoncore/bson_documentbuilder_test.go b/x/bsonx/bsoncore/bson_documentbuilder_test.go index 021ff9d415..26f7521f0e 100644 --- a/x/bsonx/bsoncore/bson_documentbuilder_test.go +++ b/x/bsonx/bsoncore/bson_documentbuilder_test.go @@ -12,8 +12,6 @@ import ( "math" "reflect" "testing" - - "go.mongodb.org/mongo-driver/bson/primitive" ) func TestDocumentBuilder(t *testing.T) { @@ -68,10 +66,10 @@ func TestDocumentBuilder(t *testing.T) { NewDocumentBuilder().AppendObjectID, []interface{}{ "foobar", - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + [12]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, }, BuildDocumentFromElements(nil, AppendObjectIDElement(nil, "foobar", - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C})), + [12]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C})), }, { "AppendBoolean", @@ -124,8 +122,8 @@ func TestDocumentBuilder(t *testing.T) { { "AppendDecimal128", NewDocumentBuilder().AppendDecimal128, - []interface{}{"foobar", primitive.NewDecimal128(4294967296, 65536)}, - BuildDocumentFromElements(nil, AppendDecimal128Element(nil, "foobar", primitive.NewDecimal128(4294967296, 65536))), + []interface{}{"foobar", uint64(4294967296), uint64(65536)}, + BuildDocumentFromElements(nil, AppendDecimal128Element(nil, "foobar", 4294967296, 65536)), }, { "AppendMaxKey", @@ -149,9 +147,9 @@ func TestDocumentBuilder(t *testing.T) { "AppendDBPointer", NewDocumentBuilder().AppendDBPointer, []interface{}{"foobar", "barbaz", - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}}, + [12]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}}, BuildDocumentFromElements(nil, AppendDBPointerElement(nil, "foobar", "barbaz", - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C})), + [12]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C})), }, { "AppendUndefined", diff --git a/x/bsonx/bsoncore/bsoncore.go b/x/bsonx/bsoncore/bsoncore.go index 2421c8ea76..6dc520dcec 100644 --- a/x/bsonx/bsoncore/bsoncore.go +++ b/x/bsonx/bsoncore/bsoncore.go @@ -13,9 +13,6 @@ import ( "strconv" "strings" "time" - - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" ) const ( @@ -27,15 +24,17 @@ const ( invalidRegexPanicMsg = "BSON regex values cannot contain null bytes" ) +type objectID = [12]byte + // AppendType will append t to dst and return the extended buffer. -func AppendType(dst []byte, t bsontype.Type) []byte { return append(dst, byte(t)) } +func AppendType(dst []byte, t Type) []byte { return append(dst, byte(t)) } // AppendKey will append key to dst and return the extended buffer. func AppendKey(dst []byte, key string) []byte { return append(dst, key+nullTerminator...) } // AppendHeader will append Type t and key to dst and return the extended // buffer. -func AppendHeader(dst []byte, t bsontype.Type, key string) []byte { +func AppendHeader(dst []byte, t Type, key string) []byte { if !isValidCString(key) { panic(invalidKeyPanicMsg) } @@ -50,11 +49,11 @@ func AppendHeader(dst []byte, t bsontype.Type, key string) []byte { // ReadType will return the first byte of the provided []byte as a type. If // there is no available byte, false is returned. -func ReadType(src []byte) (bsontype.Type, []byte, bool) { +func ReadType(src []byte) (Type, []byte, bool) { if len(src) < 1 { return 0, src, false } - return bsontype.Type(src[0]), src[1:], true + return Type(src[0]), src[1:], true } // ReadKey will read a key from src. The 0x00 byte will not be present @@ -69,7 +68,7 @@ func ReadKeyBytes(src []byte) ([]byte, []byte, bool) { return readcstringbytes(s // ReadHeader will read a type byte and a key from src. If both of these // values cannot be read, false is returned. -func ReadHeader(src []byte) (t bsontype.Type, key string, rem []byte, ok bool) { +func ReadHeader(src []byte) (t Type, key string, rem []byte, ok bool) { t, rem, ok = ReadType(src) if !ok { return 0, "", src, false @@ -101,7 +100,7 @@ func ReadElement(src []byte) (Element, []byte, bool) { if len(src) < 1 { return nil, src, false } - t := bsontype.Type(src[0]) + t := Type(src[0]) idx := bytes.IndexByte(src[1:], 0x00) if idx == -1 { return nil, src, false @@ -129,7 +128,7 @@ func AppendValueElement(dst []byte, key string, value Value) []byte { // ReadValue reads the next value as the provided types and returns a Value, the remaining bytes, // and a boolean indicating if the read was successful. -func ReadValue(src []byte, t bsontype.Type) (Value, []byte, bool) { +func ReadValue(src []byte, t Type) (Value, []byte, bool) { data, rem, ok := readValue(src, t) if !ok { return Value{}, src, false @@ -145,7 +144,7 @@ func AppendDouble(dst []byte, f float64) []byte { // AppendDoubleElement will append a BSON double element using key and f to dst // and return the extended buffer. func AppendDoubleElement(dst []byte, key string, f float64) []byte { - return AppendDouble(AppendHeader(dst, bsontype.Double, key), f) + return AppendDouble(AppendHeader(dst, TypeDouble, key), f) } // ReadDouble will read a float64 from src. If there are not enough bytes it @@ -166,7 +165,7 @@ func AppendString(dst []byte, s string) []byte { // AppendStringElement will append a BSON string element using key and val to dst // and return the extended buffer. func AppendStringElement(dst []byte, key, val string) []byte { - return AppendString(AppendHeader(dst, bsontype.String, key), val) + return AppendString(AppendHeader(dst, TypeString, key), val) } // ReadString will read a string from src. If there are not enough bytes it @@ -195,7 +194,7 @@ func AppendDocumentStartInline(dst []byte, index *int32) []byte { // AppendDocumentElementStart writes a document element header and then reserves the length bytes. func AppendDocumentElementStart(dst []byte, key string) (index int32, b []byte) { - return AppendDocumentStart(AppendHeader(dst, bsontype.EmbeddedDocument, key)) + return AppendDocumentStart(AppendHeader(dst, TypeEmbeddedDocument, key)) } // AppendDocumentEnd writes the null byte for a document and updates the length of the document. @@ -215,7 +214,7 @@ func AppendDocument(dst []byte, doc []byte) []byte { return append(dst, doc...) // AppendDocumentElement will append a BSON embedded document element using key // and doc to dst and return the extended buffer. func AppendDocumentElement(dst []byte, key string, doc []byte) []byte { - return AppendDocument(AppendHeader(dst, bsontype.EmbeddedDocument, key), doc) + return AppendDocument(AppendHeader(dst, TypeEmbeddedDocument, key), doc) } // BuildDocument will create a document with the given slice of elements and will append @@ -232,13 +231,13 @@ func BuildDocument(dst []byte, elems ...[]byte) []byte { // BuildDocumentValue creates an Embedded Document value from the given elements. func BuildDocumentValue(elems ...[]byte) Value { - return Value{Type: bsontype.EmbeddedDocument, Data: BuildDocument(nil, elems...)} + return Value{Type: TypeEmbeddedDocument, Data: BuildDocument(nil, elems...)} } // BuildDocumentElement will append a BSON embedded document element using key and the provided // elements and return the extended buffer. func BuildDocumentElement(dst []byte, key string, elems ...[]byte) []byte { - return BuildDocument(AppendHeader(dst, bsontype.EmbeddedDocument, key), elems...) + return BuildDocument(AppendHeader(dst, TypeEmbeddedDocument, key), elems...) } // BuildDocumentFromElements is an alaias for the BuildDocument function. @@ -255,7 +254,7 @@ func AppendArrayStart(dst []byte) (index int32, b []byte) { return ReserveLength // AppendArrayElementStart appends an array element header and then the length bytes for an array, // returning the index where the length starts. func AppendArrayElementStart(dst []byte, key string) (index int32, b []byte) { - return AppendArrayStart(AppendHeader(dst, bsontype.Array, key)) + return AppendArrayStart(AppendHeader(dst, TypeArray, key)) } // AppendArrayEnd appends the null byte to an array and calculates the length, inserting that @@ -268,7 +267,7 @@ func AppendArray(dst []byte, arr []byte) []byte { return append(dst, arr...) } // AppendArrayElement will append a BSON array element using key and arr to dst // and return the extended buffer. func AppendArrayElement(dst []byte, key string, arr []byte) []byte { - return AppendArray(AppendHeader(dst, bsontype.Array, key), arr) + return AppendArray(AppendHeader(dst, TypeArray, key), arr) } // BuildArray will append a BSON array to dst built from values. @@ -284,7 +283,7 @@ func BuildArray(dst []byte, values ...Value) []byte { // BuildArrayElement will create an array element using the provided values. func BuildArrayElement(dst []byte, key string, values ...Value) []byte { - return BuildArray(AppendHeader(dst, bsontype.Array, key), values...) + return BuildArray(AppendHeader(dst, TypeArray, key), values...) } // ReadArray will read an array from src. If there are not enough bytes it @@ -303,7 +302,7 @@ func AppendBinary(dst []byte, subtype byte, b []byte) []byte { // AppendBinaryElement will append a BSON binary element using key, subtype, and // b to dst and return the extended buffer. func AppendBinaryElement(dst []byte, key string, subtype byte, b []byte) []byte { - return AppendBinary(AppendHeader(dst, bsontype.Binary, key), subtype, b) + return AppendBinary(AppendHeader(dst, TypeBinary, key), subtype, b) } // ReadBinary will read a subtype and bin from src. If there are not enough bytes it @@ -335,27 +334,28 @@ func ReadBinary(src []byte) (subtype byte, bin []byte, rem []byte, ok bool) { // AppendUndefinedElement will append a BSON undefined element using key to dst // and return the extended buffer. func AppendUndefinedElement(dst []byte, key string) []byte { - return AppendHeader(dst, bsontype.Undefined, key) + return AppendHeader(dst, TypeUndefined, key) } // AppendObjectID will append oid to dst and return the extended buffer. -func AppendObjectID(dst []byte, oid primitive.ObjectID) []byte { return append(dst, oid[:]...) } +func AppendObjectID(dst []byte, oid objectID) []byte { return append(dst, oid[:]...) } // AppendObjectIDElement will append a BSON ObjectID element using key and oid to dst // and return the extended buffer. -func AppendObjectIDElement(dst []byte, key string, oid primitive.ObjectID) []byte { - return AppendObjectID(AppendHeader(dst, bsontype.ObjectID, key), oid) +func AppendObjectIDElement(dst []byte, key string, oid objectID) []byte { + return AppendObjectID(AppendHeader(dst, TypeObjectID, key), oid) } // ReadObjectID will read an ObjectID from src. If there are not enough bytes it // will return false. -func ReadObjectID(src []byte) (primitive.ObjectID, []byte, bool) { - if len(src) < 12 { - return primitive.ObjectID{}, src, false +func ReadObjectID(src []byte) (objectID, []byte, bool) { + var oid objectID + idLen := cap(oid) + if len(src) < idLen { + return oid, src, false } - var oid primitive.ObjectID - copy(oid[:], src[0:12]) - return oid, src[12:], true + copy(oid[:], src[0:idLen]) + return oid, src[idLen:], true } // AppendBoolean will append b to dst and return the extended buffer. @@ -369,7 +369,7 @@ func AppendBoolean(dst []byte, b bool) []byte { // AppendBooleanElement will append a BSON boolean element using key and b to dst // and return the extended buffer. func AppendBooleanElement(dst []byte, key string, b bool) []byte { - return AppendBoolean(AppendHeader(dst, bsontype.Boolean, key), b) + return AppendBoolean(AppendHeader(dst, TypeBoolean, key), b) } // ReadBoolean will read a bool from src. If there are not enough bytes it @@ -388,7 +388,7 @@ func AppendDateTime(dst []byte, dt int64) []byte { return appendi64(dst, dt) } // AppendDateTimeElement will append a BSON datetime element using key and dt to dst // and return the extended buffer. func AppendDateTimeElement(dst []byte, key string, dt int64) []byte { - return AppendDateTime(AppendHeader(dst, bsontype.DateTime, key), dt) + return AppendDateTime(AppendHeader(dst, TypeDateTime, key), dt) } // ReadDateTime will read an int64 datetime from src. If there are not enough bytes it @@ -403,7 +403,7 @@ func AppendTime(dst []byte, t time.Time) []byte { // AppendTimeElement will append a BSON datetime element using key and dt to dst // and return the extended buffer. func AppendTimeElement(dst []byte, key string, t time.Time) []byte { - return AppendTime(AppendHeader(dst, bsontype.DateTime, key), t) + return AppendTime(AppendHeader(dst, TypeDateTime, key), t) } // ReadTime will read an time.Time datetime from src. If there are not enough bytes it @@ -415,7 +415,7 @@ func ReadTime(src []byte) (time.Time, []byte, bool) { // AppendNullElement will append a BSON null element using key to dst // and return the extended buffer. -func AppendNullElement(dst []byte, key string) []byte { return AppendHeader(dst, bsontype.Null, key) } +func AppendNullElement(dst []byte, key string) []byte { return AppendHeader(dst, TypeNull, key) } // AppendRegex will append pattern and options to dst and return the extended buffer. func AppendRegex(dst []byte, pattern, options string) []byte { @@ -429,7 +429,7 @@ func AppendRegex(dst []byte, pattern, options string) []byte { // AppendRegexElement will append a BSON regex element using key, pattern, and // options to dst and return the extended buffer. func AppendRegexElement(dst []byte, key, pattern, options string) []byte { - return AppendRegex(AppendHeader(dst, bsontype.Regex, key), pattern, options) + return AppendRegex(AppendHeader(dst, TypeRegex, key), pattern, options) } // ReadRegex will read a pattern and options from src. If there are not enough bytes it @@ -447,26 +447,26 @@ func ReadRegex(src []byte) (pattern, options string, rem []byte, ok bool) { } // AppendDBPointer will append ns and oid to dst and return the extended buffer. -func AppendDBPointer(dst []byte, ns string, oid primitive.ObjectID) []byte { +func AppendDBPointer(dst []byte, ns string, oid objectID) []byte { return append(appendstring(dst, ns), oid[:]...) } // AppendDBPointerElement will append a BSON DBPointer element using key, ns, // and oid to dst and return the extended buffer. -func AppendDBPointerElement(dst []byte, key, ns string, oid primitive.ObjectID) []byte { - return AppendDBPointer(AppendHeader(dst, bsontype.DBPointer, key), ns, oid) +func AppendDBPointerElement(dst []byte, key, ns string, oid objectID) []byte { + return AppendDBPointer(AppendHeader(dst, TypeDBPointer, key), ns, oid) } // ReadDBPointer will read a ns and oid from src. If there are not enough bytes it // will return false. -func ReadDBPointer(src []byte) (ns string, oid primitive.ObjectID, rem []byte, ok bool) { +func ReadDBPointer(src []byte) (ns string, oid objectID, rem []byte, ok bool) { ns, rem, ok = readstring(src) if !ok { - return "", primitive.ObjectID{}, src, false + return "", objectID{}, src, false } oid, rem, ok = ReadObjectID(rem) if !ok { - return "", primitive.ObjectID{}, src, false + return "", objectID{}, src, false } return ns, oid, rem, true } @@ -477,7 +477,7 @@ func AppendJavaScript(dst []byte, js string) []byte { return appendstring(dst, j // AppendJavaScriptElement will append a BSON JavaScript element using key and // js to dst and return the extended buffer. func AppendJavaScriptElement(dst []byte, key, js string) []byte { - return AppendJavaScript(AppendHeader(dst, bsontype.JavaScript, key), js) + return AppendJavaScript(AppendHeader(dst, TypeJavaScript, key), js) } // ReadJavaScript will read a js string from src. If there are not enough bytes it @@ -490,7 +490,7 @@ func AppendSymbol(dst []byte, symbol string) []byte { return appendstring(dst, s // AppendSymbolElement will append a BSON symbol element using key and symbol to dst // and return the extended buffer. func AppendSymbolElement(dst []byte, key, symbol string) []byte { - return AppendSymbol(AppendHeader(dst, bsontype.Symbol, key), symbol) + return AppendSymbol(AppendHeader(dst, TypeSymbol, key), symbol) } // ReadSymbol will read a symbol string from src. If there are not enough bytes it @@ -509,7 +509,7 @@ func AppendCodeWithScope(dst []byte, code string, scope []byte) []byte { // key, code, and scope to dst // and return the extended buffer. func AppendCodeWithScopeElement(dst []byte, key, code string, scope []byte) []byte { - return AppendCodeWithScope(AppendHeader(dst, bsontype.CodeWithScope, key), code, scope) + return AppendCodeWithScope(AppendHeader(dst, TypeCodeWithScope, key), code, scope) } // ReadCodeWithScope will read code and scope from src. If there are not enough bytes it @@ -538,7 +538,7 @@ func AppendInt32(dst []byte, i32 int32) []byte { return appendi32(dst, i32) } // AppendInt32Element will append a BSON int32 element using key and i32 to dst // and return the extended buffer. func AppendInt32Element(dst []byte, key string, i32 int32) []byte { - return AppendInt32(AppendHeader(dst, bsontype.Int32, key), i32) + return AppendInt32(AppendHeader(dst, TypeInt32, key), i32) } // ReadInt32 will read an int32 from src. If there are not enough bytes it @@ -553,7 +553,7 @@ func AppendTimestamp(dst []byte, t, i uint32) []byte { // AppendTimestampElement will append a BSON timestamp element using key, t, and // i to dst and return the extended buffer. func AppendTimestampElement(dst []byte, key string, t, i uint32) []byte { - return AppendTimestamp(AppendHeader(dst, bsontype.Timestamp, key), t, i) + return AppendTimestamp(AppendHeader(dst, TypeTimestamp, key), t, i) } // ReadTimestamp will read t and i from src. If there are not enough bytes it @@ -576,55 +576,54 @@ func AppendInt64(dst []byte, i64 int64) []byte { return appendi64(dst, i64) } // AppendInt64Element will append a BSON int64 element using key and i64 to dst // and return the extended buffer. func AppendInt64Element(dst []byte, key string, i64 int64) []byte { - return AppendInt64(AppendHeader(dst, bsontype.Int64, key), i64) + return AppendInt64(AppendHeader(dst, TypeInt64, key), i64) } // ReadInt64 will read an int64 from src. If there are not enough bytes it // will return false. func ReadInt64(src []byte) (int64, []byte, bool) { return readi64(src) } -// AppendDecimal128 will append d128 to dst and return the extended buffer. -func AppendDecimal128(dst []byte, d128 primitive.Decimal128) []byte { - high, low := d128.GetBytes() +// AppendDecimal128 will append high and low parts of a d128 to dst and return the extended buffer. +func AppendDecimal128(dst []byte, high, low uint64) []byte { return appendu64(appendu64(dst, low), high) } -// AppendDecimal128Element will append a BSON primitive.28 element using key and +// AppendDecimal128Element will append high and low parts of a BSON bson.Decimal128 element using key and // d128 to dst and return the extended buffer. -func AppendDecimal128Element(dst []byte, key string, d128 primitive.Decimal128) []byte { - return AppendDecimal128(AppendHeader(dst, bsontype.Decimal128, key), d128) +func AppendDecimal128Element(dst []byte, key string, high, low uint64) []byte { + return AppendDecimal128(AppendHeader(dst, TypeDecimal128, key), high, low) } -// ReadDecimal128 will read a primitive.Decimal128 from src. If there are not enough bytes it +// ReadDecimal128 will read high and low parts of a bson.Decimal128 from src. If there are not enough bytes it // will return false. -func ReadDecimal128(src []byte) (primitive.Decimal128, []byte, bool) { - l, rem, ok := readu64(src) +func ReadDecimal128(src []byte) (high uint64, low uint64, rem []byte, ok bool) { + low, rem, ok = readu64(src) if !ok { - return primitive.Decimal128{}, src, false + return 0, 0, src, false } - h, rem, ok := readu64(rem) + high, rem, ok = readu64(rem) if !ok { - return primitive.Decimal128{}, src, false + return 0, 0, src, false } - return primitive.NewDecimal128(h, l), rem, true + return high, low, rem, true } // AppendMaxKeyElement will append a BSON max key element using key to dst // and return the extended buffer. func AppendMaxKeyElement(dst []byte, key string) []byte { - return AppendHeader(dst, bsontype.MaxKey, key) + return AppendHeader(dst, TypeMaxKey, key) } // AppendMinKeyElement will append a BSON min key element using key to dst // and return the extended buffer. func AppendMinKeyElement(dst []byte, key string) []byte { - return AppendHeader(dst, bsontype.MinKey, key) + return AppendHeader(dst, TypeMinKey, key) } // EqualValue will return true if the two values are equal. -func EqualValue(t1, t2 bsontype.Type, v1, v2 []byte) bool { +func EqualValue(t1, t2 Type, v1, v2 []byte) bool { if t1 != t2 { return false } @@ -642,34 +641,34 @@ func EqualValue(t1, t2 bsontype.Type, v1, v2 []byte) bool { // valueLength will determine the length of the next value contained in src as if it // is type t. The returned bool will be false if there are not enough bytes in src for // a value of type t. -func valueLength(src []byte, t bsontype.Type) (int32, bool) { +func valueLength(src []byte, t Type) (int32, bool) { var length int32 ok := true switch t { - case bsontype.Array, bsontype.EmbeddedDocument, bsontype.CodeWithScope: + case TypeArray, TypeEmbeddedDocument, TypeCodeWithScope: length, _, ok = ReadLength(src) - case bsontype.Binary: + case TypeBinary: length, _, ok = ReadLength(src) length += 4 + 1 // binary length + subtype byte - case bsontype.Boolean: + case TypeBoolean: length = 1 - case bsontype.DBPointer: + case TypeDBPointer: length, _, ok = ReadLength(src) length += 4 + 12 // string length + ObjectID length - case bsontype.DateTime, bsontype.Double, bsontype.Int64, bsontype.Timestamp: + case TypeDateTime, TypeDouble, TypeInt64, TypeTimestamp: length = 8 - case bsontype.Decimal128: + case TypeDecimal128: length = 16 - case bsontype.Int32: + case TypeInt32: length = 4 - case bsontype.JavaScript, bsontype.String, bsontype.Symbol: + case TypeJavaScript, TypeString, TypeSymbol: length, _, ok = ReadLength(src) length += 4 - case bsontype.MaxKey, bsontype.MinKey, bsontype.Null, bsontype.Undefined: + case TypeMaxKey, TypeMinKey, TypeNull, TypeUndefined: length = 0 - case bsontype.ObjectID: + case TypeObjectID: length = 12 - case bsontype.Regex: + case TypeRegex: regex := bytes.IndexByte(src, 0x00) if regex < 0 { ok = false @@ -688,7 +687,7 @@ func valueLength(src []byte, t bsontype.Type) (int32, bool) { return length, ok } -func readValue(src []byte, t bsontype.Type) ([]byte, []byte, bool) { +func readValue(src []byte, t Type) ([]byte, []byte, bool) { length, ok := valueLength(src, t) if !ok || int(length) > len(src) { return nil, src, false diff --git a/x/bsonx/bsoncore/bsoncore_test.go b/x/bsonx/bsoncore/bsoncore_test.go index ace784c4a8..5e02ff0338 100644 --- a/x/bsonx/bsoncore/bsoncore_test.go +++ b/x/bsonx/bsoncore/bsoncore_test.go @@ -15,8 +15,6 @@ import ( "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/assert" ) @@ -50,8 +48,8 @@ func TestAppend(t *testing.T) { { "AppendType", AppendType, - []interface{}{make([]byte, 0), bsontype.Null}, - []byte{byte(bsontype.Null)}, + []interface{}{make([]byte, 0), TypeNull}, + []byte{byte(TypeNull)}, }, { "AppendKey", @@ -62,14 +60,14 @@ func TestAppend(t *testing.T) { { "AppendHeader", AppendHeader, - []interface{}{make([]byte, 0), bsontype.Null, "foobar"}, - []byte{byte(bsontype.Null), 'f', 'o', 'o', 'b', 'a', 'r', 0x00}, + []interface{}{make([]byte, 0), TypeNull, "foobar"}, + []byte{byte(TypeNull), 'f', 'o', 'o', 'b', 'a', 'r', 0x00}, }, { "AppendValueElement", AppendValueElement, - []interface{}{make([]byte, 0), "testing", Value{Type: bsontype.Boolean, Data: []byte{0x01}}}, - []byte{byte(bsontype.Boolean), 't', 'e', 's', 't', 'i', 'n', 'g', 0x00, 0x01}, + []interface{}{make([]byte, 0), "testing", Value{Type: TypeBoolean, Data: []byte{0x01}}}, + []byte{byte(TypeBoolean), 't', 'e', 's', 't', 'i', 'n', 'g', 0x00, 0x01}, }, { "AppendDouble", @@ -81,7 +79,7 @@ func TestAppend(t *testing.T) { "AppendDoubleElement", AppendDoubleElement, []interface{}{make([]byte, 0), "foobar", float64(3.14159)}, - append([]byte{byte(bsontype.Double), 'f', 'o', 'o', 'b', 'a', 'r', 0x00}, pi...), + append([]byte{byte(TypeDouble), 'f', 'o', 'o', 'b', 'a', 'r', 0x00}, pi...), }, { "AppendString", @@ -93,7 +91,7 @@ func TestAppend(t *testing.T) { "AppendStringElement", AppendStringElement, []interface{}{make([]byte, 0), "foobar", "barbaz"}, - []byte{byte(bsontype.String), + []byte{byte(TypeString), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x07, 0x00, 0x00, 0x00, 'b', 'a', 'r', 'b', 'a', 'z', 0x00, }, @@ -108,7 +106,7 @@ func TestAppend(t *testing.T) { "AppendDocumentElement", AppendDocumentElement, []interface{}{make([]byte, 0), "foobar", []byte{0x05, 0x00, 0x00, 0x00, 0x00}}, - []byte{byte(bsontype.EmbeddedDocument), + []byte{byte(TypeEmbeddedDocument), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, }, @@ -123,7 +121,7 @@ func TestAppend(t *testing.T) { "AppendArrayElement", AppendArrayElement, []interface{}{make([]byte, 0), "foobar", []byte{0x05, 0x00, 0x00, 0x00, 0x00}}, - []byte{byte(bsontype.Array), + []byte{byte(TypeArray), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, }, @@ -131,10 +129,10 @@ func TestAppend(t *testing.T) { { "BuildArray", BuildArray, - []interface{}{make([]byte, 0), Value{Type: bsontype.Double, Data: AppendDouble(nil, 3.14159)}}, + []interface{}{make([]byte, 0), Value{Type: TypeDouble, Data: AppendDouble(nil, 3.14159)}}, []byte{ 0x10, 0x00, 0x00, 0x00, - byte(bsontype.Double), '0', 0x00, + byte(TypeDouble), '0', 0x00, pi[0], pi[1], pi[2], pi[3], pi[4], pi[5], pi[6], pi[7], 0x00, }, @@ -142,11 +140,11 @@ func TestAppend(t *testing.T) { { "BuildArrayElement", BuildArrayElement, - []interface{}{make([]byte, 0), "foobar", Value{Type: bsontype.Double, Data: AppendDouble(nil, 3.14159)}}, - []byte{byte(bsontype.Array), + []interface{}{make([]byte, 0), "foobar", Value{Type: TypeDouble, Data: AppendDouble(nil, 3.14159)}}, + []byte{byte(TypeArray), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x10, 0x00, 0x00, 0x00, - byte(bsontype.Double), '0', 0x00, + byte(TypeDouble), '0', 0x00, pi[0], pi[1], pi[2], pi[3], pi[4], pi[5], pi[6], pi[7], 0x00, }, @@ -161,7 +159,7 @@ func TestAppend(t *testing.T) { "AppendBinaryElement Subtype 2", AppendBinaryElement, []interface{}{make([]byte, 0), "foobar", byte(0x02), []byte{0x01, 0x02, 0x03}}, - []byte{byte(bsontype.Binary), + []byte{byte(TypeBinary), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x07, 0x00, 0x00, 0x00, 0x02, @@ -178,7 +176,7 @@ func TestAppend(t *testing.T) { "AppendBinaryElement", AppendBinaryElement, []interface{}{make([]byte, 0), "foobar", byte(0xFF), []byte{0x01, 0x02, 0x03}}, - []byte{byte(bsontype.Binary), + []byte{byte(TypeBinary), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x03, 0x00, 0x00, 0x00, 0xFF, @@ -189,14 +187,14 @@ func TestAppend(t *testing.T) { "AppendUndefinedElement", AppendUndefinedElement, []interface{}{make([]byte, 0), "foobar"}, - []byte{byte(bsontype.Undefined), 'f', 'o', 'o', 'b', 'a', 'r', 0x00}, + []byte{byte(TypeUndefined), 'f', 'o', 'o', 'b', 'a', 'r', 0x00}, }, { "AppendObjectID", AppendObjectID, []interface{}{ make([]byte, 0), - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + [12]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, }, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, }, @@ -205,9 +203,9 @@ func TestAppend(t *testing.T) { AppendObjectIDElement, []interface{}{ make([]byte, 0), "foobar", - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + [12]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, }, - []byte{byte(bsontype.ObjectID), + []byte{byte(TypeObjectID), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, }, @@ -228,7 +226,7 @@ func TestAppend(t *testing.T) { "AppendBooleanElement", AppendBooleanElement, []interface{}{make([]byte, 0), "foobar", true}, - []byte{byte(bsontype.Boolean), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x01}, + []byte{byte(TypeBoolean), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x01}, }, { "AppendDateTime", @@ -240,13 +238,13 @@ func TestAppend(t *testing.T) { "AppendDateTimeElement", AppendDateTimeElement, []interface{}{make([]byte, 0), "foobar", int64(256)}, - []byte{byte(bsontype.DateTime), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + []byte{byte(TypeDateTime), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, }, { "AppendNullElement", AppendNullElement, []interface{}{make([]byte, 0), "foobar"}, - []byte{byte(bsontype.Null), 'f', 'o', 'o', 'b', 'a', 'r', 0x00}, + []byte{byte(TypeNull), 'f', 'o', 'o', 'b', 'a', 'r', 0x00}, }, { "AppendRegex", @@ -258,7 +256,7 @@ func TestAppend(t *testing.T) { "AppendRegexElement", AppendRegexElement, []interface{}{make([]byte, 0), "foobar", "bar", "baz"}, - []byte{byte(bsontype.Regex), + []byte{byte(TypeRegex), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 'b', 'a', 'r', 0x00, 'b', 'a', 'z', 0x00, }, @@ -269,7 +267,7 @@ func TestAppend(t *testing.T) { []interface{}{ make([]byte, 0), "foobar", - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + [12]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, }, []byte{ 0x07, 0x00, 0x00, 0x00, 'f', 'o', 'o', 'b', 'a', 'r', 0x00, @@ -282,9 +280,9 @@ func TestAppend(t *testing.T) { []interface{}{ make([]byte, 0), "foobar", "barbaz", - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + [12]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, }, - []byte{byte(bsontype.DBPointer), + []byte{byte(TypeDBPointer), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x07, 0x00, 0x00, 0x00, 'b', 'a', 'r', 'b', 'a', 'z', 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, @@ -300,7 +298,7 @@ func TestAppend(t *testing.T) { "AppendJavaScriptElement", AppendJavaScriptElement, []interface{}{make([]byte, 0), "foobar", "barbaz"}, - []byte{byte(bsontype.JavaScript), + []byte{byte(TypeJavaScript), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x07, 0x00, 0x00, 0x00, 'b', 'a', 'r', 'b', 'a', 'z', 0x00, }, @@ -315,7 +313,7 @@ func TestAppend(t *testing.T) { "AppendSymbolElement", AppendSymbolElement, []interface{}{make([]byte, 0), "foobar", "barbaz"}, - []byte{byte(bsontype.Symbol), + []byte{byte(TypeSymbol), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x07, 0x00, 0x00, 0x00, 'b', 'a', 'r', 'b', 'a', 'z', 0x00, }, @@ -334,7 +332,7 @@ func TestAppend(t *testing.T) { "AppendCodeWithScopeElement", AppendCodeWithScopeElement, []interface{}{make([]byte, 0), "foobar", "barbaz", []byte{0x05, 0x00, 0x00, 0x00, 0x00}}, - []byte{byte(bsontype.CodeWithScope), + []byte{byte(TypeCodeWithScope), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x14, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 'b', 'a', 'r', 'b', 'a', 'z', 0x00, @@ -351,7 +349,7 @@ func TestAppend(t *testing.T) { "AppendInt32Element", AppendInt32Element, []interface{}{make([]byte, 0), "foobar", int32(256)}, - []byte{byte(bsontype.Int32), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x00, 0x01, 0x00, 0x00}, + []byte{byte(TypeInt32), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x00, 0x01, 0x00, 0x00}, }, { "AppendTimestamp", @@ -363,7 +361,7 @@ func TestAppend(t *testing.T) { "AppendTimestampElement", AppendTimestampElement, []interface{}{make([]byte, 0), "foobar", uint32(65536), uint32(256)}, - []byte{byte(bsontype.Timestamp), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00}, + []byte{byte(TypeTimestamp), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00}, }, { "AppendInt64", @@ -375,12 +373,12 @@ func TestAppend(t *testing.T) { "AppendInt64Element", AppendInt64Element, []interface{}{make([]byte, 0), "foobar", int64(4294967296)}, - []byte{byte(bsontype.Int64), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00}, + []byte{byte(TypeInt64), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00}, }, { "AppendDecimal128", AppendDecimal128, - []interface{}{make([]byte, 0), primitive.NewDecimal128(4294967296, 65536)}, + []interface{}{make([]byte, 0), uint64(4294967296), uint64(65536)}, []byte{ 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, @@ -389,9 +387,9 @@ func TestAppend(t *testing.T) { { "AppendDecimal128Element", AppendDecimal128Element, - []interface{}{make([]byte, 0), "foobar", primitive.NewDecimal128(4294967296, 65536)}, + []interface{}{make([]byte, 0), "foobar", uint64(4294967296), uint64(65536)}, []byte{ - byte(bsontype.Decimal128), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, + byte(TypeDecimal128), 'f', 'o', 'o', 'b', 'a', 'r', 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, }, @@ -400,13 +398,13 @@ func TestAppend(t *testing.T) { "AppendMaxKeyElement", AppendMaxKeyElement, []interface{}{make([]byte, 0), "foobar"}, - []byte{byte(bsontype.MaxKey), 'f', 'o', 'o', 'b', 'a', 'r', 0x00}, + []byte{byte(TypeMaxKey), 'f', 'o', 'o', 'b', 'a', 'r', 0x00}, }, { "AppendMinKeyElement", AppendMinKeyElement, []interface{}{make([]byte, 0), "foobar"}, - []byte{byte(bsontype.MinKey), 'f', 'o', 'o', 'b', 'a', 'r', 0x00}, + []byte{byte(TypeMinKey), 'f', 'o', 'o', 'b', 'a', 'r', 0x00}, }, } @@ -451,13 +449,13 @@ func TestRead(t *testing.T) { "ReadType/not enough bytes", ReadType, []byte{}, - []interface{}{bsontype.Type(0), []byte{}, false}, + []interface{}{Type(0), []byte{}, false}, }, { "ReadType/success", ReadType, []byte{0x0A}, - []interface{}{bsontype.Null, []byte{}, true}, + []interface{}{TypeNull, []byte{}, true}, }, { "ReadKey/not enough bytes", @@ -475,19 +473,19 @@ func TestRead(t *testing.T) { "ReadHeader/not enough bytes (type)", ReadHeader, []byte{}, - []interface{}{bsontype.Type(0), "", []byte{}, false}, + []interface{}{Type(0), "", []byte{}, false}, }, { "ReadHeader/not enough bytes (key)", ReadHeader, []byte{0x0A, 'f', 'o', 'o'}, - []interface{}{bsontype.Type(0), "", []byte{0x0A, 'f', 'o', 'o'}, false}, + []interface{}{Type(0), "", []byte{0x0A, 'f', 'o', 'o'}, false}, }, { "ReadHeader/success", ReadHeader, []byte{0x0A, 'f', 'o', 'o', 'b', 'a', 'r', 0x00}, - []interface{}{bsontype.Null, "foobar", []byte{}, true}, + []interface{}{TypeNull, "foobar", []byte{}, true}, }, { "ReadDouble/not enough bytes", @@ -604,14 +602,14 @@ func TestRead(t *testing.T) { "ReadObjectID/not enough bytes", ReadObjectID, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, - []interface{}{primitive.ObjectID{}, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, false}, + []interface{}{[12]byte{}, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, false}, }, { "ReadObjectID/success", ReadObjectID, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, []interface{}{ - primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + [12]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, []byte{}, true, }, }, @@ -661,13 +659,13 @@ func TestRead(t *testing.T) { "ReadDBPointer/not enough bytes (ns)", ReadDBPointer, []byte{}, - []interface{}{"", primitive.ObjectID{}, []byte{}, false}, + []interface{}{"", [12]byte{}, []byte{}, false}, }, { "ReadDBPointer/not enough bytes (objectID)", ReadDBPointer, []byte{0x04, 0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00}, - []interface{}{"", primitive.ObjectID{}, []byte{0x04, 0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00}, false}, + []interface{}{"", [12]byte{}, []byte{0x04, 0x00, 0x00, 0x00, 'f', 'o', 'o', 0x00}, false}, }, { "ReadDBPointer/success", @@ -677,7 +675,7 @@ func TestRead(t *testing.T) { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, }, []interface{}{ - "foo", primitive.ObjectID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, + "foo", [12]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}, []byte{}, true, }, }, @@ -806,13 +804,13 @@ func TestRead(t *testing.T) { "ReadDecimal128/not enough bytes (low)", ReadDecimal128, []byte{}, - []interface{}{primitive.Decimal128{}, []byte{}, false}, + []interface{}{uint64(0), uint64(0), []byte{}, false}, }, { "ReadDecimal128/not enough bytes (high)", ReadDecimal128, []byte{0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00}, - []interface{}{primitive.Decimal128{}, []byte{0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00}, false}, + []interface{}{uint64(0), uint64(0), []byte{0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00}, false}, }, { "ReadDecimal128/success", @@ -821,7 +819,7 @@ func TestRead(t *testing.T) { 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, }, - []interface{}{primitive.NewDecimal128(4294967296, 16777216), []byte{}, true}, + []interface{}{uint64(4294967296), uint64(16777216), []byte{}, true}, }, } @@ -841,7 +839,7 @@ func TestRead(t *testing.T) { for idx := range results { got := results[idx].Interface() want := tc.expected[idx] - if !cmp.Equal(got, want, cmp.Comparer(compareDecimal128)) { + if !cmp.Equal(got, want) { t.Errorf("Result %d does not match. got %v; want %v", idx, got, want) } } @@ -955,18 +953,3 @@ func TestInvalidBytes(t *testing.T) { assert.Equal(t, 4, len(src), "expected src to contain the size parameter still") }) } - -func compareDecimal128(d1, d2 primitive.Decimal128) bool { - d1H, d1L := d1.GetBytes() - d2H, d2L := d2.GetBytes() - - if d1H != d2H { - return false - } - - if d1L != d2L { - return false - } - - return true -} diff --git a/x/bsonx/bsoncore/document.go b/x/bsonx/bsoncore/document.go index 3f360f1ae1..539fc69207 100644 --- a/x/bsonx/bsoncore/document.go +++ b/x/bsonx/bsoncore/document.go @@ -12,8 +12,6 @@ import ( "io" "strconv" "strings" - - "go.mongodb.org/mongo-driver/bson/bsontype" ) // ValidationError is an error type returned when attempting to validate a document or array. @@ -63,13 +61,13 @@ func (ibe InsufficientBytesError) Equal(err2 error) bool { // the path is neither an embedded document nor an array. type InvalidDepthTraversalError struct { Key string - Type bsontype.Type + Type Type } func (idte InvalidDepthTraversalError) Error() string { return fmt.Sprintf( "attempt to traverse into %s, but it's type is %s, not %s nor %s", - idte.Key, idte.Type, bsontype.EmbeddedDocument, bsontype.Array, + idte.Key, idte.Type, TypeEmbeddedDocument, TypeArray, ) } @@ -167,15 +165,15 @@ func (d Document) LookupErr(key ...string) (Value, error) { continue } if len(key) > 1 { - tt := bsontype.Type(elem[0]) + tt := Type(elem[0]) switch tt { - case bsontype.EmbeddedDocument: + case TypeEmbeddedDocument: val, err := elem.Value().Document().LookupErr(key[1:]...) if err != nil { return Value{}, err } return val, nil - case bsontype.Array: + case TypeArray: // Convert to Document to continue Lookup recursion. val, err := Document(elem.Value().Array()).LookupErr(key[1:]...) if err != nil { diff --git a/x/bsonx/bsoncore/document_test.go b/x/bsonx/bsoncore/document_test.go index a5609e689e..4013239b14 100644 --- a/x/bsonx/bsoncore/document_test.go +++ b/x/bsonx/bsoncore/document_test.go @@ -15,7 +15,6 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsontype" ) func ExampleDocument_Validate() { @@ -151,7 +150,7 @@ func TestDocument(t *testing.T) { t.Run("invalid-traversal", func(t *testing.T) { rdr := Document{'\x08', '\x00', '\x00', '\x00', '\x0A', 'x', '\x00', '\x00'} _, got := rdr.LookupErr("x", "y") - want := InvalidDepthTraversalError{Key: "x", Type: bsontype.Null} + want := InvalidDepthTraversalError{Key: "x", Type: TypeNull} if !compareErrors(got, want) { t.Errorf("Empty key lookup did not return expected result. got %v; want %v", got, want) } @@ -168,7 +167,7 @@ func TestDocument(t *testing.T) { '\x08', '\x00', '\x00', '\x00', '\x0A', 'x', '\x00', '\x00', }, []string{"x"}, - Value{Type: bsontype.Null, Data: []byte{}}, + Value{Type: TypeNull, Data: []byte{}}, nil, }, {"first-second", @@ -180,7 +179,7 @@ func TestDocument(t *testing.T) { '\x0A', 'b', '\x00', '\x00', '\x00', }, []string{"foo", "b"}, - Value{Type: bsontype.Null, Data: []byte{}}, + Value{Type: TypeNull, Data: []byte{}}, nil, }, {"first-second-array", @@ -192,7 +191,7 @@ func TestDocument(t *testing.T) { '\x0A', '2', '\x00', '\x00', '\x00', }, []string{"foo", "2"}, - Value{Type: bsontype.Null, Data: []byte{}}, + Value{Type: TypeNull, Data: []byte{}}, nil, }, } @@ -364,11 +363,11 @@ func TestDocument(t *testing.T) { } }) t.Run("Elements", func(t *testing.T) { - invalidElem := BuildDocument(nil, AppendHeader(nil, bsontype.Double, "foo")) + invalidElem := BuildDocument(nil, AppendHeader(nil, TypeDouble, "foo")) invalidTwoElem := BuildDocument(nil, AppendHeader( AppendDoubleElement(nil, "pi", 3.14159), - bsontype.Double, "foo", + TypeDouble, "foo", ), ) oneElem := BuildDocument(nil, AppendDoubleElement(nil, "pi", 3.14159)) diff --git a/x/bsonx/bsoncore/element.go b/x/bsonx/bsoncore/element.go index 1fe0897c91..6191744540 100644 --- a/x/bsonx/bsoncore/element.go +++ b/x/bsonx/bsoncore/element.go @@ -9,8 +9,6 @@ package bsoncore import ( "bytes" "fmt" - - "go.mongodb.org/mongo-driver/bson/bsontype" ) // MalformedElementError represents a class of errors that RawElement methods return. @@ -70,7 +68,7 @@ func (e Element) Validate() error { if idx == -1 { return ErrElementMissingKey } - return Value{Type: bsontype.Type(e[0]), Data: e[idx+2:]}.Validate() + return Value{Type: Type(e[0]), Data: e[idx+2:]}.Validate() } // CompareKey will compare this element's key to key. This method makes it easy to compare keys @@ -107,7 +105,7 @@ func (e Element) ValueErr() (Value, error) { return Value{}, ErrElementMissingKey } - val, rem, exists := ReadValue(e[idx+2:], bsontype.Type(e[0])) + val, rem, exists := ReadValue(e[idx+2:], Type(e[0])) if !exists { return Value{}, NewInsufficientBytesError(e, rem) } @@ -119,7 +117,7 @@ func (e Element) String() string { if len(e) <= 0 { return "" } - t := bsontype.Type(e[0]) + t := Type(e[0]) idx := bytes.IndexByte(e[1:], 0x00) if idx == -1 { return "" @@ -138,7 +136,7 @@ func (e Element) DebugString() string { if len(e) <= 0 { return "" } - t := bsontype.Type(e[0]) + t := Type(e[0]) idx := bytes.IndexByte(e[1:], 0x00) if idx == -1 { return fmt.Sprintf(`bson.Element{[%s]}`, t) diff --git a/x/bsonx/bsoncore/element_test.go b/x/bsonx/bsoncore/element_test.go index 7b2f9e5baf..e80701deb9 100644 --- a/x/bsonx/bsoncore/element_test.go +++ b/x/bsonx/bsoncore/element_test.go @@ -10,7 +10,6 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsontype" ) func TestElement(t *testing.T) { @@ -23,7 +22,7 @@ func TestElement(t *testing.T) { }{ {"No Type", Element{}, "", ErrElementMissingType}, {"No Key", Element{0x01, 'f', 'o', 'o'}, "", ErrElementMissingKey}, - {"Success", AppendHeader(nil, bsontype.Double, "foo"), "foo", nil}, + {"Success", AppendHeader(nil, TypeDouble, "foo"), "foo", nil}, } for _, tc := range testCases { @@ -54,7 +53,7 @@ func TestElement(t *testing.T) { }{ {"No Type", Element{}, ErrElementMissingType}, {"No Key", Element{0x01, 'f', 'o', 'o'}, ErrElementMissingKey}, - {"Insufficient Bytes", AppendHeader(nil, bsontype.Double, "foo"), NewInsufficientBytesError(nil, nil)}, + {"Insufficient Bytes", AppendHeader(nil, TypeDouble, "foo"), NewInsufficientBytesError(nil, nil)}, {"Success", AppendDoubleElement(nil, "foo", 3.14159), nil}, } @@ -76,10 +75,10 @@ func TestElement(t *testing.T) { }{ {"Element Too Short", Element{0x02}, nil, false}, {"Element Invalid Key", Element{0x02, 'f', 'o', 'o'}, nil, false}, - {"Key With Null Byte", AppendHeader(nil, bsontype.Double, "foo"), []byte{'f', 'o', 'o', 0x00}, true}, - {"Key Without Null Byte", AppendHeader(nil, bsontype.Double, "pi"), []byte{'p', 'i'}, true}, - {"Key With Null Byte With Extra", AppendHeader(nil, bsontype.Double, "foo"), []byte{'f', 'o', 'o', 0x00, 'b', 'a', 'r'}, true}, - {"Prefix Key No Match", AppendHeader(nil, bsontype.Double, "foo"), []byte{'f', 'o', 'o', 'b', 'a', 'r'}, false}, + {"Key With Null Byte", AppendHeader(nil, TypeDouble, "foo"), []byte{'f', 'o', 'o', 0x00}, true}, + {"Key Without Null Byte", AppendHeader(nil, TypeDouble, "pi"), []byte{'p', 'i'}, true}, + {"Key With Null Byte With Extra", AppendHeader(nil, TypeDouble, "foo"), []byte{'f', 'o', 'o', 0x00, 'b', 'a', 'r'}, true}, + {"Prefix Key No Match", AppendHeader(nil, TypeDouble, "foo"), []byte{'f', 'o', 'o', 'b', 'a', 'r'}, false}, } for _, tc := range testCases { @@ -100,8 +99,8 @@ func TestElement(t *testing.T) { }{ {"No Type", Element{}, Value{}, ErrElementMissingType}, {"No Key", Element{0x01, 'f', 'o', 'o'}, Value{}, ErrElementMissingKey}, - {"Insufficient Bytes", AppendHeader(nil, bsontype.Double, "foo"), Value{}, NewInsufficientBytesError(nil, nil)}, - {"Success", AppendDoubleElement(nil, "foo", 3.14159), Value{Type: bsontype.Double, Data: AppendDouble(nil, 3.14159)}, nil}, + {"Insufficient Bytes", AppendHeader(nil, TypeDouble, "foo"), Value{}, NewInsufficientBytesError(nil, nil)}, + {"Success", AppendDoubleElement(nil, "foo", 3.14159), Value{Type: TypeDouble, Data: AppendDouble(nil, 3.14159)}, nil}, } for _, tc := range testCases { diff --git a/x/bsonx/bsoncore/iterator.go b/x/bsonx/bsoncore/iterator.go index f4f6236d77..9c8ea5b87e 100644 --- a/x/bsonx/bsoncore/iterator.go +++ b/x/bsonx/bsoncore/iterator.go @@ -10,8 +10,6 @@ import ( "errors" "fmt" "io" - - "go.mongodb.org/mongo-driver/bson/bsontype" ) // errCorruptedDocument is returned when a full document couldn't be read from @@ -73,7 +71,7 @@ func (iter *Iterator) Documents() ([]Document, error) { docs := make([]Document, 0, len(vals)) for _, v := range vals { - if v.Type != bsontype.EmbeddedDocument { + if v.Type != TypeEmbeddedDocument { return nil, fmt.Errorf("invalid DocumentSequence: a non-document value was found in sequence") } diff --git a/x/bsonx/bsoncore/iterator_test.go b/x/bsonx/bsoncore/iterator_test.go index 1011f6033f..e58812e9d0 100644 --- a/x/bsonx/bsoncore/iterator_test.go +++ b/x/bsonx/bsoncore/iterator_test.go @@ -10,7 +10,6 @@ import ( "io" "testing" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/require" ) @@ -26,11 +25,11 @@ func TestIterator_Reset(t *testing.T) { name: "documents", values: []Value{ { - Type: bsontype.EmbeddedDocument, + Type: TypeEmbeddedDocument, Data: BuildDocument(nil, AppendDoubleElement(nil, "pi", 3.14159)), }, { - Type: bsontype.EmbeddedDocument, + Type: TypeEmbeddedDocument, Data: BuildDocument(nil, AppendDoubleElement(nil, "grav", 9.8)), }, }, @@ -39,11 +38,11 @@ func TestIterator_Reset(t *testing.T) { name: "strings", values: []Value{ { - Type: bsontype.String, + Type: TypeString, Data: AppendString(nil, "foo"), }, { - Type: bsontype.String, + Type: TypeString, Data: AppendString(nil, "bar"), }, }, @@ -52,15 +51,15 @@ func TestIterator_Reset(t *testing.T) { name: "type mixing", values: []Value{ { - Type: bsontype.String, + Type: TypeString, Data: AppendString(nil, "foo"), }, { - Type: bsontype.Boolean, + Type: TypeBoolean, Data: AppendBoolean(nil, true), }, { - Type: bsontype.EmbeddedDocument, + Type: TypeEmbeddedDocument, Data: BuildDocument(nil, AppendDoubleElement(nil, "pi", 3.14159)), }, }, @@ -116,7 +115,7 @@ func TestIterator_Count(t *testing.T) { name: "singleton", values: []Value{ { - Type: bsontype.String, + Type: TypeString, Data: AppendString(nil, "foo"), }, }, @@ -126,11 +125,11 @@ func TestIterator_Count(t *testing.T) { name: "non singleton", values: []Value{ { - Type: bsontype.String, + Type: TypeString, Data: AppendString(nil, "foo"), }, { - Type: bsontype.String, + Type: TypeString, Data: AppendString(nil, "bar"), }, }, @@ -140,7 +139,7 @@ func TestIterator_Count(t *testing.T) { name: "document bearing", values: []Value{ { - Type: bsontype.EmbeddedDocument, + Type: TypeEmbeddedDocument, Data: BuildDocument(nil, AppendDoubleElement(nil, "pi", 3.14159)), }, }, @@ -150,15 +149,15 @@ func TestIterator_Count(t *testing.T) { name: "type mixing", values: []Value{ { - Type: bsontype.String, + Type: TypeString, Data: AppendString(nil, "foo"), }, { - Type: bsontype.Boolean, + Type: TypeBoolean, Data: AppendBoolean(nil, true), }, { - Type: bsontype.EmbeddedDocument, + Type: TypeEmbeddedDocument, Data: BuildDocument(nil, AppendDoubleElement(nil, "pi", 3.14159)), }, }, @@ -205,7 +204,7 @@ func TestIterator_Next(t *testing.T) { name: "singleton", values: []Value{ { - Type: bsontype.String, + Type: TypeString, Data: AppendString(nil, "foo"), }, }, @@ -214,7 +213,7 @@ func TestIterator_Next(t *testing.T) { name: "document bearing", values: []Value{ { - Type: bsontype.EmbeddedDocument, + Type: TypeEmbeddedDocument, Data: BuildDocument(nil, AppendDoubleElement(nil, "pi", 3.14159)), }, }, @@ -223,15 +222,15 @@ func TestIterator_Next(t *testing.T) { name: "type mixing", values: []Value{ { - Type: bsontype.String, + Type: TypeString, Data: AppendString(nil, "foo"), }, { - Type: bsontype.Boolean, + Type: TypeBoolean, Data: AppendBoolean(nil, true), }, { - Type: bsontype.EmbeddedDocument, + Type: TypeEmbeddedDocument, Data: BuildDocument(nil, AppendDoubleElement(nil, "pi", 3.14159)), }, }, @@ -271,19 +270,19 @@ func TestIterator_Next(t *testing.T) { func BenchmarkIterator_Next(b *testing.B) { values := []Value{ { - Type: bsontype.Double, + Type: TypeDouble, Data: AppendDouble(nil, 3.14159), }, { - Type: bsontype.String, + Type: TypeString, Data: AppendString(nil, "foo"), }, { - Type: bsontype.EmbeddedDocument, + Type: TypeEmbeddedDocument, Data: BuildDocument(nil, AppendDoubleElement(nil, "pi", 3.14159)), }, { - Type: bsontype.Boolean, + Type: TypeBoolean, Data: AppendBoolean(nil, true), }, } diff --git a/x/bsonx/bsoncore/type.go b/x/bsonx/bsoncore/type.go new file mode 100644 index 0000000000..30b6cc437b --- /dev/null +++ b/x/bsonx/bsoncore/type.go @@ -0,0 +1,85 @@ +// 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 bsoncore + +// Type represents a BSON type. +type Type byte + +// String returns the string representation of the BSON type's name. +func (bt Type) String() string { + switch bt { + case '\x01': + return "double" + case '\x02': + return "string" + case '\x03': + return "embedded document" + case '\x04': + return "array" + case '\x05': + return "binary" + case '\x06': + return "undefined" + case '\x07': + return "objectID" + case '\x08': + return "boolean" + case '\x09': + return "UTC datetime" + case '\x0A': + return "null" + case '\x0B': + return "regex" + case '\x0C': + return "dbPointer" + case '\x0D': + return "javascript" + case '\x0E': + return "symbol" + case '\x0F': + return "code with scope" + case '\x10': + return "32-bit integer" + case '\x11': + return "timestamp" + case '\x12': + return "64-bit integer" + case '\x13': + return "128-bit decimal" + case '\x7F': + return "max key" + case '\xFF': + return "min key" + default: + return "invalid" + } +} + +// BSON element types as described in https://bsonspec.org/spec.html. +const ( + TypeDouble Type = 0x01 + TypeString Type = 0x02 + TypeEmbeddedDocument Type = 0x03 + TypeArray Type = 0x04 + TypeBinary Type = 0x05 + TypeUndefined Type = 0x06 + TypeObjectID Type = 0x07 + TypeBoolean Type = 0x08 + TypeDateTime Type = 0x09 + TypeNull Type = 0x0A + TypeRegex Type = 0x0B + TypeDBPointer Type = 0x0C + TypeJavaScript Type = 0x0D + TypeSymbol Type = 0x0E + TypeCodeWithScope Type = 0x0F + TypeInt32 Type = 0x10 + TypeTimestamp Type = 0x11 + TypeInt64 Type = 0x12 + TypeDecimal128 Type = 0x13 + TypeMaxKey Type = 0x7F + TypeMinKey Type = 0xFF +) diff --git a/x/bsonx/bsoncore/value.go b/x/bsonx/bsoncore/value.go index 69c1f9edbb..0d542deadb 100644 --- a/x/bsonx/bsoncore/value.go +++ b/x/bsonx/bsoncore/value.go @@ -9,6 +9,7 @@ package bsoncore import ( "bytes" "encoding/base64" + "encoding/hex" "fmt" "math" "sort" @@ -17,14 +18,13 @@ import ( "time" "unicode/utf8" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/internal/decimal128" ) // ElementTypeError specifies that a method to obtain a BSON value an incorrect type was called on a bson.Value. type ElementTypeError struct { Method string - Type bsontype.Type + Type Type } // Error implements the error interface. @@ -34,7 +34,7 @@ func (ete ElementTypeError) Error() string { // Value represents a BSON value with a type and raw bytes. type Value struct { - Type bsontype.Type + Type Type Data []byte } @@ -50,7 +50,7 @@ func (v Value) Validate() error { // IsNumber returns true if the type of v is a numeric BSON type. func (v Value) IsNumber() bool { switch v.Type { - case bsontype.Double, bsontype.Int32, bsontype.Int64, bsontype.Decimal128: + case TypeDouble, TypeInt32, TypeInt64, TypeDecimal128: return true default: return false @@ -65,25 +65,25 @@ func (v Value) AsInt32() int32 { } var i32 int32 switch v.Type { - case bsontype.Double: + case TypeDouble: f64, _, ok := ReadDouble(v.Data) if !ok { panic(NewInsufficientBytesError(v.Data, v.Data)) } i32 = int32(f64) - case bsontype.Int32: + case TypeInt32: var ok bool i32, _, ok = ReadInt32(v.Data) if !ok { panic(NewInsufficientBytesError(v.Data, v.Data)) } - case bsontype.Int64: + case TypeInt64: i64, _, ok := ReadInt64(v.Data) if !ok { panic(NewInsufficientBytesError(v.Data, v.Data)) } i32 = int32(i64) - case bsontype.Decimal128: + case TypeDecimal128: panic(ElementTypeError{"bsoncore.Value.AsInt32", v.Type}) } return i32 @@ -97,25 +97,25 @@ func (v Value) AsInt32OK() (int32, bool) { } var i32 int32 switch v.Type { - case bsontype.Double: + case TypeDouble: f64, _, ok := ReadDouble(v.Data) if !ok { return 0, false } i32 = int32(f64) - case bsontype.Int32: + case TypeInt32: var ok bool i32, _, ok = ReadInt32(v.Data) if !ok { return 0, false } - case bsontype.Int64: + case TypeInt64: i64, _, ok := ReadInt64(v.Data) if !ok { return 0, false } i32 = int32(i64) - case bsontype.Decimal128: + case TypeDecimal128: return 0, false } return i32, true @@ -129,26 +129,26 @@ func (v Value) AsInt64() int64 { } var i64 int64 switch v.Type { - case bsontype.Double: + case TypeDouble: f64, _, ok := ReadDouble(v.Data) if !ok { panic(NewInsufficientBytesError(v.Data, v.Data)) } i64 = int64(f64) - case bsontype.Int32: + case TypeInt32: var ok bool i32, _, ok := ReadInt32(v.Data) if !ok { panic(NewInsufficientBytesError(v.Data, v.Data)) } i64 = int64(i32) - case bsontype.Int64: + case TypeInt64: var ok bool i64, _, ok = ReadInt64(v.Data) if !ok { panic(NewInsufficientBytesError(v.Data, v.Data)) } - case bsontype.Decimal128: + case TypeDecimal128: panic(ElementTypeError{"bsoncore.Value.AsInt64", v.Type}) } return i64 @@ -162,26 +162,26 @@ func (v Value) AsInt64OK() (int64, bool) { } var i64 int64 switch v.Type { - case bsontype.Double: + case TypeDouble: f64, _, ok := ReadDouble(v.Data) if !ok { return 0, false } i64 = int64(f64) - case bsontype.Int32: + case TypeInt32: var ok bool i32, _, ok := ReadInt32(v.Data) if !ok { return 0, false } i64 = int64(i32) - case bsontype.Int64: + case TypeInt64: var ok bool i64, _, ok = ReadInt64(v.Data) if !ok { return 0, false } - case bsontype.Decimal128: + case TypeDecimal128: return 0, false } return i64, true @@ -208,63 +208,69 @@ func (v Value) Equal(v2 Value) bool { return bytes.Equal(v.Data, v2.Data) } +func idHex(id [12]byte) string { + var buf [24]byte + hex.Encode(buf[:], id[:]) + return string(buf[:]) +} + // String implements the fmt.String interface. This method will return values in extended JSON // format. If the value is not valid, this returns an empty string func (v Value) String() string { switch v.Type { - case bsontype.Double: + case TypeDouble: f64, ok := v.DoubleOK() if !ok { return "" } return fmt.Sprintf(`{"$numberDouble":"%s"}`, formatDouble(f64)) - case bsontype.String: + case TypeString: str, ok := v.StringValueOK() if !ok { return "" } return escapeString(str) - case bsontype.EmbeddedDocument: + case TypeEmbeddedDocument: doc, ok := v.DocumentOK() if !ok { return "" } return doc.String() - case bsontype.Array: + case TypeArray: arr, ok := v.ArrayOK() if !ok { return "" } return arr.String() - case bsontype.Binary: + case TypeBinary: subtype, data, ok := v.BinaryOK() if !ok { return "" } return fmt.Sprintf(`{"$binary":{"base64":"%s","subType":"%02x"}}`, base64.StdEncoding.EncodeToString(data), subtype) - case bsontype.Undefined: + case TypeUndefined: return `{"$undefined":true}` - case bsontype.ObjectID: + case TypeObjectID: oid, ok := v.ObjectIDOK() if !ok { return "" } - return fmt.Sprintf(`{"$oid":"%s"}`, oid.Hex()) - case bsontype.Boolean: + return fmt.Sprintf(`{"$oid":"%s"}`, idHex(oid)) + case TypeBoolean: b, ok := v.BooleanOK() if !ok { return "" } return strconv.FormatBool(b) - case bsontype.DateTime: + case TypeDateTime: dt, ok := v.DateTimeOK() if !ok { return "" } return fmt.Sprintf(`{"$date":{"$numberLong":"%d"}}`, dt) - case bsontype.Null: + case TypeNull: return "null" - case bsontype.Regex: + case TypeRegex: pattern, options, ok := v.RegexOK() if !ok { return "" @@ -273,57 +279,57 @@ func (v Value) String() string { `{"$regularExpression":{"pattern":%s,"options":"%s"}}`, escapeString(pattern), sortStringAlphebeticAscending(options), ) - case bsontype.DBPointer: + case TypeDBPointer: ns, pointer, ok := v.DBPointerOK() if !ok { return "" } - return fmt.Sprintf(`{"$dbPointer":{"$ref":%s,"$id":{"$oid":"%s"}}}`, escapeString(ns), pointer.Hex()) - case bsontype.JavaScript: + return fmt.Sprintf(`{"$dbPointer":{"$ref":%s,"$id":{"$oid":"%s"}}}`, escapeString(ns), idHex(pointer)) + case TypeJavaScript: js, ok := v.JavaScriptOK() if !ok { return "" } return fmt.Sprintf(`{"$code":%s}`, escapeString(js)) - case bsontype.Symbol: + case TypeSymbol: symbol, ok := v.SymbolOK() if !ok { return "" } return fmt.Sprintf(`{"$symbol":%s}`, escapeString(symbol)) - case bsontype.CodeWithScope: + case TypeCodeWithScope: code, scope, ok := v.CodeWithScopeOK() if !ok { return "" } return fmt.Sprintf(`{"$code":%s,"$scope":%s}`, code, scope) - case bsontype.Int32: + case TypeInt32: i32, ok := v.Int32OK() if !ok { return "" } return fmt.Sprintf(`{"$numberInt":"%d"}`, i32) - case bsontype.Timestamp: + case TypeTimestamp: t, i, ok := v.TimestampOK() if !ok { return "" } return fmt.Sprintf(`{"$timestamp":{"t":%v,"i":%v}}`, t, i) - case bsontype.Int64: + case TypeInt64: i64, ok := v.Int64OK() if !ok { return "" } return fmt.Sprintf(`{"$numberLong":"%d"}`, i64) - case bsontype.Decimal128: - d128, ok := v.Decimal128OK() + case TypeDecimal128: + h, l, ok := v.Decimal128OK() if !ok { return "" } - return fmt.Sprintf(`{"$numberDecimal":"%s"}`, d128.String()) - case bsontype.MinKey: + return fmt.Sprintf(`{"$numberDecimal":"%s"}`, decimal128.String(h, l)) + case TypeMinKey: return `{"$minKey":1}` - case bsontype.MaxKey: + case TypeMaxKey: return `{"$maxKey":1}` default: return "" @@ -334,25 +340,25 @@ func (v Value) String() string { // valid components of the document even if the entire document is not valid. func (v Value) DebugString() string { switch v.Type { - case bsontype.String: + case TypeString: str, ok := v.StringValueOK() if !ok { return "" } return escapeString(str) - case bsontype.EmbeddedDocument: + case TypeEmbeddedDocument: doc, ok := v.DocumentOK() if !ok { return "" } return doc.DebugString() - case bsontype.Array: + case TypeArray: arr, ok := v.ArrayOK() if !ok { return "" } return arr.DebugString() - case bsontype.CodeWithScope: + case TypeCodeWithScope: code, scope, ok := v.CodeWithScopeOK() if !ok { return "" @@ -368,9 +374,9 @@ func (v Value) DebugString() string { } // Double returns the float64 value for this element. -// It panics if e's BSON type is not bsontype.Double. +// It panics if e's BSON type is not TypeDouble. func (v Value) Double() float64 { - if v.Type != bsontype.Double { + if v.Type != TypeDouble { panic(ElementTypeError{"bsoncore.Value.Double", v.Type}) } f64, _, ok := ReadDouble(v.Data) @@ -382,7 +388,7 @@ func (v Value) Double() float64 { // DoubleOK is the same as Double, but returns a boolean instead of panicking. func (v Value) DoubleOK() (float64, bool) { - if v.Type != bsontype.Double { + if v.Type != TypeDouble { return 0, false } f64, _, ok := ReadDouble(v.Data) @@ -393,12 +399,12 @@ func (v Value) DoubleOK() (float64, bool) { } // StringValue returns the string balue for this element. -// It panics if e's BSON type is not bsontype.String. +// It panics if e's BSON type is not TypeString. // // NOTE: This method is called StringValue to avoid a collision with the String method which // implements the fmt.Stringer interface. func (v Value) StringValue() string { - if v.Type != bsontype.String { + if v.Type != TypeString { panic(ElementTypeError{"bsoncore.Value.StringValue", v.Type}) } str, _, ok := ReadString(v.Data) @@ -411,7 +417,7 @@ func (v Value) StringValue() string { // StringValueOK is the same as StringValue, but returns a boolean instead of // panicking. func (v Value) StringValueOK() (string, bool) { - if v.Type != bsontype.String { + if v.Type != TypeString { return "", false } str, _, ok := ReadString(v.Data) @@ -424,7 +430,7 @@ func (v Value) StringValueOK() (string, bool) { // Document returns the BSON document the Value represents as a Document. It panics if the // value is a BSON type other than document. func (v Value) Document() Document { - if v.Type != bsontype.EmbeddedDocument { + if v.Type != TypeEmbeddedDocument { panic(ElementTypeError{"bsoncore.Value.Document", v.Type}) } doc, _, ok := ReadDocument(v.Data) @@ -437,7 +443,7 @@ func (v Value) Document() Document { // DocumentOK is the same as Document, except it returns a boolean // instead of panicking. func (v Value) DocumentOK() (Document, bool) { - if v.Type != bsontype.EmbeddedDocument { + if v.Type != TypeEmbeddedDocument { return nil, false } doc, _, ok := ReadDocument(v.Data) @@ -450,7 +456,7 @@ func (v Value) DocumentOK() (Document, bool) { // Array returns the BSON array the Value represents as an Array. It panics if the // value is a BSON type other than array. func (v Value) Array() Array { - if v.Type != bsontype.Array { + if v.Type != TypeArray { panic(ElementTypeError{"bsoncore.Value.Array", v.Type}) } arr, _, ok := ReadArray(v.Data) @@ -463,7 +469,7 @@ func (v Value) Array() Array { // ArrayOK is the same as Array, except it returns a boolean instead // of panicking. func (v Value) ArrayOK() (Array, bool) { - if v.Type != bsontype.Array { + if v.Type != TypeArray { return nil, false } arr, _, ok := ReadArray(v.Data) @@ -476,7 +482,7 @@ func (v Value) ArrayOK() (Array, bool) { // Binary returns the BSON binary value the Value represents. It panics if the value is a BSON type // other than binary. func (v Value) Binary() (subtype byte, data []byte) { - if v.Type != bsontype.Binary { + if v.Type != TypeBinary { panic(ElementTypeError{"bsoncore.Value.Binary", v.Type}) } subtype, data, _, ok := ReadBinary(v.Data) @@ -489,7 +495,7 @@ func (v Value) Binary() (subtype byte, data []byte) { // BinaryOK is the same as Binary, except it returns a boolean instead of // panicking. func (v Value) BinaryOK() (subtype byte, data []byte, ok bool) { - if v.Type != bsontype.Binary { + if v.Type != TypeBinary { return 0x00, nil, false } subtype, data, _, ok = ReadBinary(v.Data) @@ -501,8 +507,8 @@ func (v Value) BinaryOK() (subtype byte, data []byte, ok bool) { // ObjectID returns the BSON objectid value the Value represents. It panics if the value is a BSON // type other than objectid. -func (v Value) ObjectID() primitive.ObjectID { - if v.Type != bsontype.ObjectID { +func (v Value) ObjectID() objectID { + if v.Type != TypeObjectID { panic(ElementTypeError{"bsoncore.Value.ObjectID", v.Type}) } oid, _, ok := ReadObjectID(v.Data) @@ -514,13 +520,13 @@ func (v Value) ObjectID() primitive.ObjectID { // ObjectIDOK is the same as ObjectID, except it returns a boolean instead of // panicking. -func (v Value) ObjectIDOK() (primitive.ObjectID, bool) { - if v.Type != bsontype.ObjectID { - return primitive.ObjectID{}, false +func (v Value) ObjectIDOK() (objectID, bool) { + if v.Type != TypeObjectID { + return objectID{}, false } oid, _, ok := ReadObjectID(v.Data) if !ok { - return primitive.ObjectID{}, false + return objectID{}, false } return oid, true } @@ -528,7 +534,7 @@ func (v Value) ObjectIDOK() (primitive.ObjectID, bool) { // Boolean returns the boolean value the Value represents. It panics if the // value is a BSON type other than boolean. func (v Value) Boolean() bool { - if v.Type != bsontype.Boolean { + if v.Type != TypeBoolean { panic(ElementTypeError{"bsoncore.Value.Boolean", v.Type}) } b, _, ok := ReadBoolean(v.Data) @@ -541,7 +547,7 @@ func (v Value) Boolean() bool { // BooleanOK is the same as Boolean, except it returns a boolean instead of // panicking. func (v Value) BooleanOK() (bool, bool) { - if v.Type != bsontype.Boolean { + if v.Type != TypeBoolean { return false, false } b, _, ok := ReadBoolean(v.Data) @@ -554,7 +560,7 @@ func (v Value) BooleanOK() (bool, bool) { // DateTime returns the BSON datetime value the Value represents as a // unix timestamp. It panics if the value is a BSON type other than datetime. func (v Value) DateTime() int64 { - if v.Type != bsontype.DateTime { + if v.Type != TypeDateTime { panic(ElementTypeError{"bsoncore.Value.DateTime", v.Type}) } dt, _, ok := ReadDateTime(v.Data) @@ -567,7 +573,7 @@ func (v Value) DateTime() int64 { // DateTimeOK is the same as DateTime, except it returns a boolean instead of // panicking. func (v Value) DateTimeOK() (int64, bool) { - if v.Type != bsontype.DateTime { + if v.Type != TypeDateTime { return 0, false } dt, _, ok := ReadDateTime(v.Data) @@ -580,7 +586,7 @@ func (v Value) DateTimeOK() (int64, bool) { // Time returns the BSON datetime value the Value represents. It panics if the value is a BSON // type other than datetime. func (v Value) Time() time.Time { - if v.Type != bsontype.DateTime { + if v.Type != TypeDateTime { panic(ElementTypeError{"bsoncore.Value.Time", v.Type}) } dt, _, ok := ReadDateTime(v.Data) @@ -593,7 +599,7 @@ func (v Value) Time() time.Time { // TimeOK is the same as Time, except it returns a boolean instead of // panicking. func (v Value) TimeOK() (time.Time, bool) { - if v.Type != bsontype.DateTime { + if v.Type != TypeDateTime { return time.Time{}, false } dt, _, ok := ReadDateTime(v.Data) @@ -606,7 +612,7 @@ func (v Value) TimeOK() (time.Time, bool) { // Regex returns the BSON regex value the Value represents. It panics if the value is a BSON // type other than regex. func (v Value) Regex() (pattern, options string) { - if v.Type != bsontype.Regex { + if v.Type != TypeRegex { panic(ElementTypeError{"bsoncore.Value.Regex", v.Type}) } pattern, options, _, ok := ReadRegex(v.Data) @@ -619,7 +625,7 @@ func (v Value) Regex() (pattern, options string) { // RegexOK is the same as Regex, except it returns a boolean instead of // panicking. func (v Value) RegexOK() (pattern, options string, ok bool) { - if v.Type != bsontype.Regex { + if v.Type != TypeRegex { return "", "", false } pattern, options, _, ok = ReadRegex(v.Data) @@ -631,8 +637,8 @@ func (v Value) RegexOK() (pattern, options string, ok bool) { // DBPointer returns the BSON dbpointer value the Value represents. It panics if the value is a BSON // type other than DBPointer. -func (v Value) DBPointer() (string, primitive.ObjectID) { - if v.Type != bsontype.DBPointer { +func (v Value) DBPointer() (string, objectID) { + if v.Type != TypeDBPointer { panic(ElementTypeError{"bsoncore.Value.DBPointer", v.Type}) } ns, pointer, _, ok := ReadDBPointer(v.Data) @@ -644,13 +650,13 @@ func (v Value) DBPointer() (string, primitive.ObjectID) { // DBPointerOK is the same as DBPoitner, except that it returns a boolean // instead of panicking. -func (v Value) DBPointerOK() (string, primitive.ObjectID, bool) { - if v.Type != bsontype.DBPointer { - return "", primitive.ObjectID{}, false +func (v Value) DBPointerOK() (string, objectID, bool) { + if v.Type != TypeDBPointer { + return "", objectID{}, false } ns, pointer, _, ok := ReadDBPointer(v.Data) if !ok { - return "", primitive.ObjectID{}, false + return "", objectID{}, false } return ns, pointer, true } @@ -658,7 +664,7 @@ func (v Value) DBPointerOK() (string, primitive.ObjectID, bool) { // JavaScript returns the BSON JavaScript code value the Value represents. It panics if the value is // a BSON type other than JavaScript code. func (v Value) JavaScript() string { - if v.Type != bsontype.JavaScript { + if v.Type != TypeJavaScript { panic(ElementTypeError{"bsoncore.Value.JavaScript", v.Type}) } js, _, ok := ReadJavaScript(v.Data) @@ -671,7 +677,7 @@ func (v Value) JavaScript() string { // JavaScriptOK is the same as Javascript, excepti that it returns a boolean // instead of panicking. func (v Value) JavaScriptOK() (string, bool) { - if v.Type != bsontype.JavaScript { + if v.Type != TypeJavaScript { return "", false } js, _, ok := ReadJavaScript(v.Data) @@ -684,7 +690,7 @@ func (v Value) JavaScriptOK() (string, bool) { // Symbol returns the BSON symbol value the Value represents. It panics if the value is a BSON // type other than symbol. func (v Value) Symbol() string { - if v.Type != bsontype.Symbol { + if v.Type != TypeSymbol { panic(ElementTypeError{"bsoncore.Value.Symbol", v.Type}) } symbol, _, ok := ReadSymbol(v.Data) @@ -697,7 +703,7 @@ func (v Value) Symbol() string { // SymbolOK is the same as Symbol, excepti that it returns a boolean // instead of panicking. func (v Value) SymbolOK() (string, bool) { - if v.Type != bsontype.Symbol { + if v.Type != TypeSymbol { return "", false } symbol, _, ok := ReadSymbol(v.Data) @@ -710,7 +716,7 @@ func (v Value) SymbolOK() (string, bool) { // CodeWithScope returns the BSON JavaScript code with scope the Value represents. // It panics if the value is a BSON type other than JavaScript code with scope. func (v Value) CodeWithScope() (string, Document) { - if v.Type != bsontype.CodeWithScope { + if v.Type != TypeCodeWithScope { panic(ElementTypeError{"bsoncore.Value.CodeWithScope", v.Type}) } code, scope, _, ok := ReadCodeWithScope(v.Data) @@ -723,7 +729,7 @@ func (v Value) CodeWithScope() (string, Document) { // CodeWithScopeOK is the same as CodeWithScope, except that it returns a boolean instead of // panicking. func (v Value) CodeWithScopeOK() (string, Document, bool) { - if v.Type != bsontype.CodeWithScope { + if v.Type != TypeCodeWithScope { return "", nil, false } code, scope, _, ok := ReadCodeWithScope(v.Data) @@ -736,7 +742,7 @@ func (v Value) CodeWithScopeOK() (string, Document, bool) { // Int32 returns the int32 the Value represents. It panics if the value is a BSON type other than // int32. func (v Value) Int32() int32 { - if v.Type != bsontype.Int32 { + if v.Type != TypeInt32 { panic(ElementTypeError{"bsoncore.Value.Int32", v.Type}) } i32, _, ok := ReadInt32(v.Data) @@ -749,7 +755,7 @@ func (v Value) Int32() int32 { // Int32OK is the same as Int32, except that it returns a boolean instead of // panicking. func (v Value) Int32OK() (int32, bool) { - if v.Type != bsontype.Int32 { + if v.Type != TypeInt32 { return 0, false } i32, _, ok := ReadInt32(v.Data) @@ -762,7 +768,7 @@ func (v Value) Int32OK() (int32, bool) { // Timestamp returns the BSON timestamp value the Value represents. It panics if the value is a // BSON type other than timestamp. func (v Value) Timestamp() (t, i uint32) { - if v.Type != bsontype.Timestamp { + if v.Type != TypeTimestamp { panic(ElementTypeError{"bsoncore.Value.Timestamp", v.Type}) } t, i, _, ok := ReadTimestamp(v.Data) @@ -775,7 +781,7 @@ func (v Value) Timestamp() (t, i uint32) { // TimestampOK is the same as Timestamp, except that it returns a boolean // instead of panicking. func (v Value) TimestampOK() (t, i uint32, ok bool) { - if v.Type != bsontype.Timestamp { + if v.Type != TypeTimestamp { return 0, 0, false } t, i, _, ok = ReadTimestamp(v.Data) @@ -788,7 +794,7 @@ func (v Value) TimestampOK() (t, i uint32, ok bool) { // Int64 returns the int64 the Value represents. It panics if the value is a BSON type other than // int64. func (v Value) Int64() int64 { - if v.Type != bsontype.Int64 { + if v.Type != TypeInt64 { panic(ElementTypeError{"bsoncore.Value.Int64", v.Type}) } i64, _, ok := ReadInt64(v.Data) @@ -801,7 +807,7 @@ func (v Value) Int64() int64 { // Int64OK is the same as Int64, except that it returns a boolean instead of // panicking. func (v Value) Int64OK() (int64, bool) { - if v.Type != bsontype.Int64 { + if v.Type != TypeInt64 { return 0, false } i64, _, ok := ReadInt64(v.Data) @@ -813,28 +819,28 @@ func (v Value) Int64OK() (int64, bool) { // Decimal128 returns the decimal the Value represents. It panics if the value is a BSON type other than // decimal. -func (v Value) Decimal128() primitive.Decimal128 { - if v.Type != bsontype.Decimal128 { +func (v Value) Decimal128() (uint64, uint64) { + if v.Type != TypeDecimal128 { panic(ElementTypeError{"bsoncore.Value.Decimal128", v.Type}) } - d128, _, ok := ReadDecimal128(v.Data) + h, l, _, ok := ReadDecimal128(v.Data) if !ok { panic(NewInsufficientBytesError(v.Data, v.Data)) } - return d128 + return h, l } // Decimal128OK is the same as Decimal128, except that it returns a boolean // instead of panicking. -func (v Value) Decimal128OK() (primitive.Decimal128, bool) { - if v.Type != bsontype.Decimal128 { - return primitive.Decimal128{}, false +func (v Value) Decimal128OK() (uint64, uint64, bool) { + if v.Type != TypeDecimal128 { + return 0, 0, false } - d128, _, ok := ReadDecimal128(v.Data) + h, l, _, ok := ReadDecimal128(v.Data) if !ok { - return primitive.Decimal128{}, false + return 0, 0, false } - return d128, true + return h, l, true } var hexChars = "0123456789abcdef" diff --git a/x/bsonx/bsoncore/value_test.go b/x/bsonx/bsoncore/value_test.go index a9fdfb6663..5e56d20512 100644 --- a/x/bsonx/bsoncore/value_test.go +++ b/x/bsonx/bsoncore/value_test.go @@ -12,8 +12,6 @@ import ( "time" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" ) func TestValue(t *testing.T) { @@ -25,7 +23,7 @@ func TestValue(t *testing.T) { t.Run("invalid", func(t *testing.T) { t.Parallel() - v := Value{Type: bsontype.Double, Data: []byte{0x01, 0x02, 0x03, 0x04}} + v := Value{Type: TypeDouble, Data: []byte{0x01, 0x02, 0x03, 0x04}} want := NewInsufficientBytesError(v.Data, v.Data) got := v.Validate() if !compareErrors(got, want) { @@ -35,7 +33,7 @@ func TestValue(t *testing.T) { t.Run("value", func(t *testing.T) { t.Parallel() - v := Value{Type: bsontype.Double, Data: AppendDouble(nil, 3.14159)} + v := Value{Type: TypeDouble, Data: AppendDouble(nil, 3.14159)} var want error got := v.Validate() if !compareErrors(got, want) { @@ -52,12 +50,12 @@ func TestValue(t *testing.T) { val Value isnum bool }{ - {"double", Value{Type: bsontype.Double}, true}, - {"int32", Value{Type: bsontype.Int32}, true}, - {"int64", Value{Type: bsontype.Int64}, true}, - {"decimal128", Value{Type: bsontype.Decimal128}, true}, - {"string", Value{Type: bsontype.String}, false}, - {"regex", Value{Type: bsontype.Regex}, false}, + {"double", Value{Type: TypeDouble}, true}, + {"int32", Value{Type: TypeInt32}, true}, + {"int64", Value{Type: TypeInt64}, true}, + {"decimal128", Value{Type: TypeDecimal128}, true}, + {"string", Value{Type: TypeString}, false}, + {"regex", Value{Type: TypeRegex}, false}, } for _, tc := range testCases { @@ -75,7 +73,7 @@ func TestValue(t *testing.T) { }) now := time.Now().Truncate(time.Millisecond) - oid := primitive.NewObjectID() + var oid [12]byte testCases := []struct { name string @@ -85,557 +83,557 @@ func TestValue(t *testing.T) { ret []interface{} }{ { - "Double/Not Double", Value.Double, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.Double", bsontype.String}, + "Double/Not Double", Value.Double, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.Double", TypeString}, nil, }, { - "Double/Insufficient Bytes", Value.Double, Value{Type: bsontype.Double, Data: []byte{0x01, 0x02, 0x03, 0x04}}, + "Double/Insufficient Bytes", Value.Double, Value{Type: TypeDouble, Data: []byte{0x01, 0x02, 0x03, 0x04}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03, 0x04}, []byte{0x01, 0x02, 0x03, 0x04}), nil, }, { - "Double/Success", Value.Double, Value{Type: bsontype.Double, Data: AppendDouble(nil, 3.14159)}, + "Double/Success", Value.Double, Value{Type: TypeDouble, Data: AppendDouble(nil, 3.14159)}, nil, []interface{}{float64(3.14159)}, }, { - "DoubleOK/Not Double", Value.DoubleOK, Value{Type: bsontype.String}, + "DoubleOK/Not Double", Value.DoubleOK, Value{Type: TypeString}, nil, []interface{}{float64(0), false}, }, { - "DoubleOK/Insufficient Bytes", Value.DoubleOK, Value{Type: bsontype.Double, Data: []byte{0x01, 0x02, 0x03, 0x04}}, + "DoubleOK/Insufficient Bytes", Value.DoubleOK, Value{Type: TypeDouble, Data: []byte{0x01, 0x02, 0x03, 0x04}}, nil, []interface{}{float64(0), false}, }, { - "DoubleOK/Success", Value.DoubleOK, Value{Type: bsontype.Double, Data: AppendDouble(nil, 3.14159)}, + "DoubleOK/Success", Value.DoubleOK, Value{Type: TypeDouble, Data: AppendDouble(nil, 3.14159)}, nil, []interface{}{float64(3.14159), true}, }, { - "StringValue/Not String", Value.StringValue, Value{Type: bsontype.Double}, - ElementTypeError{"bsoncore.Value.StringValue", bsontype.Double}, + "StringValue/Not String", Value.StringValue, Value{Type: TypeDouble}, + ElementTypeError{"bsoncore.Value.StringValue", TypeDouble}, nil, }, { - "StringValue/Insufficient Bytes", Value.StringValue, Value{Type: bsontype.String, Data: []byte{0x01, 0x02, 0x03, 0x04}}, + "StringValue/Insufficient Bytes", Value.StringValue, Value{Type: TypeString, Data: []byte{0x01, 0x02, 0x03, 0x04}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03, 0x04}, []byte{0x01, 0x02, 0x03, 0x04}), nil, }, { - "StringValue/Zero Length", Value.StringValue, Value{Type: bsontype.String, Data: []byte{0x00, 0x00, 0x00, 0x00}}, + "StringValue/Zero Length", Value.StringValue, Value{Type: TypeString, Data: []byte{0x00, 0x00, 0x00, 0x00}}, NewInsufficientBytesError([]byte{0x00, 0x00, 0x00, 0x00}, []byte{0x00, 0x00, 0x00, 0x00}), nil, }, { - "StringValue/Success", Value.StringValue, Value{Type: bsontype.String, Data: AppendString(nil, "hello, world!")}, + "StringValue/Success", Value.StringValue, Value{Type: TypeString, Data: AppendString(nil, "hello, world!")}, nil, []interface{}{"hello, world!"}, }, { - "StringValueOK/Not String", Value.StringValueOK, Value{Type: bsontype.Double}, + "StringValueOK/Not String", Value.StringValueOK, Value{Type: TypeDouble}, nil, []interface{}{"", false}, }, { - "StringValueOK/Insufficient Bytes", Value.StringValueOK, Value{Type: bsontype.String, Data: []byte{0x01, 0x02, 0x03, 0x04}}, + "StringValueOK/Insufficient Bytes", Value.StringValueOK, Value{Type: TypeString, Data: []byte{0x01, 0x02, 0x03, 0x04}}, nil, []interface{}{"", false}, }, { - "StringValueOK/Zero Length", Value.StringValueOK, Value{Type: bsontype.String, Data: []byte{0x00, 0x00, 0x00, 0x00}}, + "StringValueOK/Zero Length", Value.StringValueOK, Value{Type: TypeString, Data: []byte{0x00, 0x00, 0x00, 0x00}}, nil, []interface{}{"", false}, }, { - "StringValueOK/Success", Value.StringValueOK, Value{Type: bsontype.String, Data: AppendString(nil, "hello, world!")}, + "StringValueOK/Success", Value.StringValueOK, Value{Type: TypeString, Data: AppendString(nil, "hello, world!")}, nil, []interface{}{"hello, world!", true}, }, { - "Document/Not Document", Value.Document, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.Document", bsontype.String}, + "Document/Not Document", Value.Document, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.Document", TypeString}, nil, }, { - "Document/Insufficient Bytes", Value.Document, Value{Type: bsontype.EmbeddedDocument, Data: []byte{0x01, 0x02, 0x03, 0x04}}, + "Document/Insufficient Bytes", Value.Document, Value{Type: TypeEmbeddedDocument, Data: []byte{0x01, 0x02, 0x03, 0x04}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03, 0x04}, []byte{0x01, 0x02, 0x03, 0x04}), nil, }, { - "Document/Success", Value.Document, Value{Type: bsontype.EmbeddedDocument, Data: []byte{0x05, 0x00, 0x00, 0x00, 0x00}}, + "Document/Success", Value.Document, Value{Type: TypeEmbeddedDocument, Data: []byte{0x05, 0x00, 0x00, 0x00, 0x00}}, nil, []interface{}{Document{0x05, 0x00, 0x00, 0x00, 0x00}}, }, { - "DocumentOK/Not Document", Value.DocumentOK, Value{Type: bsontype.String}, + "DocumentOK/Not Document", Value.DocumentOK, Value{Type: TypeString}, nil, []interface{}{Document(nil), false}, }, { - "DocumentOK/Insufficient Bytes", Value.DocumentOK, Value{Type: bsontype.EmbeddedDocument, Data: []byte{0x01, 0x02, 0x03, 0x04}}, + "DocumentOK/Insufficient Bytes", Value.DocumentOK, Value{Type: TypeEmbeddedDocument, Data: []byte{0x01, 0x02, 0x03, 0x04}}, nil, []interface{}{Document(nil), false}, }, { - "DocumentOK/Success", Value.DocumentOK, Value{Type: bsontype.EmbeddedDocument, Data: []byte{0x05, 0x00, 0x00, 0x00, 0x00}}, + "DocumentOK/Success", Value.DocumentOK, Value{Type: TypeEmbeddedDocument, Data: []byte{0x05, 0x00, 0x00, 0x00, 0x00}}, nil, []interface{}{Document{0x05, 0x00, 0x00, 0x00, 0x00}, true}, }, { - "Array/Not Array", Value.Array, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.Array", bsontype.String}, + "Array/Not Array", Value.Array, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.Array", TypeString}, nil, }, { - "Array/Insufficient Bytes", Value.Array, Value{Type: bsontype.Array, Data: []byte{0x01, 0x02, 0x03, 0x04}}, + "Array/Insufficient Bytes", Value.Array, Value{Type: TypeArray, Data: []byte{0x01, 0x02, 0x03, 0x04}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03, 0x04}, []byte{0x01, 0x02, 0x03, 0x04}), nil, }, { - "Array/Success", Value.Array, Value{Type: bsontype.Array, Data: []byte{0x05, 0x00, 0x00, 0x00, 0x00}}, + "Array/Success", Value.Array, Value{Type: TypeArray, Data: []byte{0x05, 0x00, 0x00, 0x00, 0x00}}, nil, []interface{}{Array{0x05, 0x00, 0x00, 0x00, 0x00}}, }, { - "ArrayOK/Not Array", Value.ArrayOK, Value{Type: bsontype.String}, + "ArrayOK/Not Array", Value.ArrayOK, Value{Type: TypeString}, nil, []interface{}{Array(nil), false}, }, { - "ArrayOK/Insufficient Bytes", Value.ArrayOK, Value{Type: bsontype.Array, Data: []byte{0x01, 0x02, 0x03, 0x04}}, + "ArrayOK/Insufficient Bytes", Value.ArrayOK, Value{Type: TypeArray, Data: []byte{0x01, 0x02, 0x03, 0x04}}, nil, []interface{}{Array(nil), false}, }, { - "ArrayOK/Success", Value.ArrayOK, Value{Type: bsontype.Array, Data: []byte{0x05, 0x00, 0x00, 0x00, 0x00}}, + "ArrayOK/Success", Value.ArrayOK, Value{Type: TypeArray, Data: []byte{0x05, 0x00, 0x00, 0x00, 0x00}}, nil, []interface{}{Array{0x05, 0x00, 0x00, 0x00, 0x00}, true}, }, { - "Binary/Not Binary", Value.Binary, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.Binary", bsontype.String}, + "Binary/Not Binary", Value.Binary, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.Binary", TypeString}, nil, }, { - "Binary/Insufficient Bytes", Value.Binary, Value{Type: bsontype.Binary, Data: []byte{0x01, 0x02, 0x03, 0x04}}, + "Binary/Insufficient Bytes", Value.Binary, Value{Type: TypeBinary, Data: []byte{0x01, 0x02, 0x03, 0x04}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03, 0x04}, []byte{0x01, 0x02, 0x03, 0x04}), nil, }, { - "Binary/Success", Value.Binary, Value{Type: bsontype.Binary, Data: AppendBinary(nil, 0xFF, []byte{0x01, 0x02, 0x03})}, + "Binary/Success", Value.Binary, Value{Type: TypeBinary, Data: AppendBinary(nil, 0xFF, []byte{0x01, 0x02, 0x03})}, nil, []interface{}{byte(0xFF), []byte{0x01, 0x02, 0x03}}, }, { - "BinaryOK/Not Binary", Value.BinaryOK, Value{Type: bsontype.String}, + "BinaryOK/Not Binary", Value.BinaryOK, Value{Type: TypeString}, nil, []interface{}{byte(0x00), []byte(nil), false}, }, { - "BinaryOK/Insufficient Bytes", Value.BinaryOK, Value{Type: bsontype.Binary, Data: []byte{0x01, 0x02, 0x03, 0x04}}, + "BinaryOK/Insufficient Bytes", Value.BinaryOK, Value{Type: TypeBinary, Data: []byte{0x01, 0x02, 0x03, 0x04}}, nil, []interface{}{byte(0x00), []byte(nil), false}, }, { - "BinaryOK/Success", Value.BinaryOK, Value{Type: bsontype.Binary, Data: AppendBinary(nil, 0xFF, []byte{0x01, 0x02, 0x03})}, + "BinaryOK/Success", Value.BinaryOK, Value{Type: TypeBinary, Data: AppendBinary(nil, 0xFF, []byte{0x01, 0x02, 0x03})}, nil, []interface{}{byte(0xFF), []byte{0x01, 0x02, 0x03}, true}, }, { - "ObjectID/Not ObjectID", Value.ObjectID, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.ObjectID", bsontype.String}, + "ObjectID/Not ObjectID", Value.ObjectID, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.ObjectID", TypeString}, nil, }, { - "ObjectID/Insufficient Bytes", Value.ObjectID, Value{Type: bsontype.ObjectID, Data: []byte{0x01, 0x02, 0x03, 0x04}}, + "ObjectID/Insufficient Bytes", Value.ObjectID, Value{Type: TypeObjectID, Data: []byte{0x01, 0x02, 0x03, 0x04}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03, 0x04}, []byte{0x01, 0x02, 0x03, 0x04}), nil, }, { - "ObjectID/Success", Value.ObjectID, Value{Type: bsontype.ObjectID, Data: AppendObjectID(nil, primitive.ObjectID{0x01, 0x02})}, + "ObjectID/Success", Value.ObjectID, Value{Type: TypeObjectID, Data: AppendObjectID(nil, [12]byte{0x01, 0x02})}, nil, - []interface{}{primitive.ObjectID{0x01, 0x02}}, + []interface{}{[12]byte{0x01, 0x02}}, }, { - "ObjectIDOK/Not ObjectID", Value.ObjectIDOK, Value{Type: bsontype.String}, + "ObjectIDOK/Not ObjectID", Value.ObjectIDOK, Value{Type: TypeString}, nil, - []interface{}{primitive.ObjectID{}, false}, + []interface{}{[12]byte{}, false}, }, { - "ObjectIDOK/Insufficient Bytes", Value.ObjectIDOK, Value{Type: bsontype.ObjectID, Data: []byte{0x01, 0x02, 0x03, 0x04}}, + "ObjectIDOK/Insufficient Bytes", Value.ObjectIDOK, Value{Type: TypeObjectID, Data: []byte{0x01, 0x02, 0x03, 0x04}}, nil, - []interface{}{primitive.ObjectID{}, false}, + []interface{}{[12]byte{}, false}, }, { - "ObjectIDOK/Success", Value.ObjectIDOK, Value{Type: bsontype.ObjectID, Data: AppendObjectID(nil, primitive.ObjectID{0x01, 0x02})}, + "ObjectIDOK/Success", Value.ObjectIDOK, Value{Type: TypeObjectID, Data: AppendObjectID(nil, [12]byte{0x01, 0x02})}, nil, - []interface{}{primitive.ObjectID{0x01, 0x02}, true}, + []interface{}{[12]byte{0x01, 0x02}, true}, }, { - "Boolean/Not Boolean", Value.Boolean, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.Boolean", bsontype.String}, + "Boolean/Not Boolean", Value.Boolean, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.Boolean", TypeString}, nil, }, { - "Boolean/Insufficient Bytes", Value.Boolean, Value{Type: bsontype.Boolean, Data: []byte{}}, + "Boolean/Insufficient Bytes", Value.Boolean, Value{Type: TypeBoolean, Data: []byte{}}, NewInsufficientBytesError([]byte{}, []byte{}), nil, }, { - "Boolean/Success", Value.Boolean, Value{Type: bsontype.Boolean, Data: AppendBoolean(nil, true)}, + "Boolean/Success", Value.Boolean, Value{Type: TypeBoolean, Data: AppendBoolean(nil, true)}, nil, []interface{}{true}, }, { - "BooleanOK/Not Boolean", Value.BooleanOK, Value{Type: bsontype.String}, + "BooleanOK/Not Boolean", Value.BooleanOK, Value{Type: TypeString}, nil, []interface{}{false, false}, }, { - "BooleanOK/Insufficient Bytes", Value.BooleanOK, Value{Type: bsontype.Boolean, Data: []byte{}}, + "BooleanOK/Insufficient Bytes", Value.BooleanOK, Value{Type: TypeBoolean, Data: []byte{}}, nil, []interface{}{false, false}, }, { - "BooleanOK/Success", Value.BooleanOK, Value{Type: bsontype.Boolean, Data: AppendBoolean(nil, true)}, + "BooleanOK/Success", Value.BooleanOK, Value{Type: TypeBoolean, Data: AppendBoolean(nil, true)}, nil, []interface{}{true, true}, }, { - "DateTime/Not DateTime", Value.DateTime, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.DateTime", bsontype.String}, + "DateTime/Not DateTime", Value.DateTime, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.DateTime", TypeString}, nil, }, { - "DateTime/Insufficient Bytes", Value.DateTime, Value{Type: bsontype.DateTime, Data: []byte{0x01, 0x02, 0x03}}, + "DateTime/Insufficient Bytes", Value.DateTime, Value{Type: TypeDateTime, Data: []byte{0x01, 0x02, 0x03}}, NewInsufficientBytesError([]byte{}, []byte{}), nil, }, { - "DateTime/Success", Value.DateTime, Value{Type: bsontype.DateTime, Data: AppendDateTime(nil, 12345)}, + "DateTime/Success", Value.DateTime, Value{Type: TypeDateTime, Data: AppendDateTime(nil, 12345)}, nil, []interface{}{int64(12345)}, }, { - "DateTimeOK/Not DateTime", Value.DateTimeOK, Value{Type: bsontype.String}, + "DateTimeOK/Not DateTime", Value.DateTimeOK, Value{Type: TypeString}, nil, []interface{}{int64(0), false}, }, { - "DateTimeOK/Insufficient Bytes", Value.DateTimeOK, Value{Type: bsontype.DateTime, Data: []byte{0x01, 0x02, 0x03}}, + "DateTimeOK/Insufficient Bytes", Value.DateTimeOK, Value{Type: TypeDateTime, Data: []byte{0x01, 0x02, 0x03}}, nil, []interface{}{int64(0), false}, }, { - "DateTimeOK/Success", Value.DateTimeOK, Value{Type: bsontype.DateTime, Data: AppendDateTime(nil, 12345)}, + "DateTimeOK/Success", Value.DateTimeOK, Value{Type: TypeDateTime, Data: AppendDateTime(nil, 12345)}, nil, []interface{}{int64(12345), true}, }, { - "Time/Not DateTime", Value.Time, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.Time", bsontype.String}, + "Time/Not DateTime", Value.Time, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.Time", TypeString}, nil, }, { - "Time/Insufficient Bytes", Value.Time, Value{Type: bsontype.DateTime, Data: []byte{0x01, 0x02, 0x03}}, + "Time/Insufficient Bytes", Value.Time, Value{Type: TypeDateTime, Data: []byte{0x01, 0x02, 0x03}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03}, []byte{0x01, 0x02, 0x03}), nil, }, { - "Time/Success", Value.Time, Value{Type: bsontype.DateTime, Data: AppendTime(nil, now)}, + "Time/Success", Value.Time, Value{Type: TypeDateTime, Data: AppendTime(nil, now)}, nil, []interface{}{now}, }, { - "TimeOK/Not DateTime", Value.TimeOK, Value{Type: bsontype.String}, + "TimeOK/Not DateTime", Value.TimeOK, Value{Type: TypeString}, nil, []interface{}{time.Time{}, false}, }, { - "TimeOK/Insufficient Bytes", Value.TimeOK, Value{Type: bsontype.DateTime, Data: []byte{0x01, 0x02, 0x03}}, + "TimeOK/Insufficient Bytes", Value.TimeOK, Value{Type: TypeDateTime, Data: []byte{0x01, 0x02, 0x03}}, nil, []interface{}{time.Time{}, false}, }, { - "TimeOK/Success", Value.TimeOK, Value{Type: bsontype.DateTime, Data: AppendTime(nil, now)}, + "TimeOK/Success", Value.TimeOK, Value{Type: TypeDateTime, Data: AppendTime(nil, now)}, nil, []interface{}{now, true}, }, { - "Regex/Not Regex", Value.Regex, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.Regex", bsontype.String}, + "Regex/Not Regex", Value.Regex, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.Regex", TypeString}, nil, }, { - "Regex/Insufficient Bytes", Value.Regex, Value{Type: bsontype.Regex, Data: []byte{0x01, 0x02, 0x03}}, + "Regex/Insufficient Bytes", Value.Regex, Value{Type: TypeRegex, Data: []byte{0x01, 0x02, 0x03}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03}, []byte{0x01, 0x02, 0x03}), nil, }, { - "Regex/Success", Value.Regex, Value{Type: bsontype.Regex, Data: AppendRegex(nil, "/abcdefg/", "hijkl")}, + "Regex/Success", Value.Regex, Value{Type: TypeRegex, Data: AppendRegex(nil, "/abcdefg/", "hijkl")}, nil, []interface{}{"/abcdefg/", "hijkl"}, }, { - "RegexOK/Not Regex", Value.RegexOK, Value{Type: bsontype.String}, + "RegexOK/Not Regex", Value.RegexOK, Value{Type: TypeString}, nil, []interface{}{"", "", false}, }, { - "RegexOK/Insufficient Bytes", Value.RegexOK, Value{Type: bsontype.Regex, Data: []byte{0x01, 0x02, 0x03}}, + "RegexOK/Insufficient Bytes", Value.RegexOK, Value{Type: TypeRegex, Data: []byte{0x01, 0x02, 0x03}}, nil, []interface{}{"", "", false}, }, { - "RegexOK/Success", Value.RegexOK, Value{Type: bsontype.Regex, Data: AppendRegex(nil, "/abcdefg/", "hijkl")}, + "RegexOK/Success", Value.RegexOK, Value{Type: TypeRegex, Data: AppendRegex(nil, "/abcdefg/", "hijkl")}, nil, []interface{}{"/abcdefg/", "hijkl", true}, }, { - "DBPointer/Not DBPointer", Value.DBPointer, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.DBPointer", bsontype.String}, + "DBPointer/Not DBPointer", Value.DBPointer, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.DBPointer", TypeString}, nil, }, { - "DBPointer/Insufficient Bytes", Value.DBPointer, Value{Type: bsontype.DBPointer, Data: []byte{0x01, 0x02, 0x03}}, + "DBPointer/Insufficient Bytes", Value.DBPointer, Value{Type: TypeDBPointer, Data: []byte{0x01, 0x02, 0x03}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03}, []byte{0x01, 0x02, 0x03}), nil, }, { - "DBPointer/Success", Value.DBPointer, Value{Type: bsontype.DBPointer, Data: AppendDBPointer(nil, "foobar", oid)}, + "DBPointer/Success", Value.DBPointer, Value{Type: TypeDBPointer, Data: AppendDBPointer(nil, "foobar", oid)}, nil, []interface{}{"foobar", oid}, }, { - "DBPointerOK/Not DBPointer", Value.DBPointerOK, Value{Type: bsontype.String}, + "DBPointerOK/Not DBPointer", Value.DBPointerOK, Value{Type: TypeString}, nil, - []interface{}{"", primitive.ObjectID{}, false}, + []interface{}{"", [12]byte{}, false}, }, { - "DBPointerOK/Insufficient Bytes", Value.DBPointerOK, Value{Type: bsontype.DBPointer, Data: []byte{0x01, 0x02, 0x03}}, + "DBPointerOK/Insufficient Bytes", Value.DBPointerOK, Value{Type: TypeDBPointer, Data: []byte{0x01, 0x02, 0x03}}, nil, - []interface{}{"", primitive.ObjectID{}, false}, + []interface{}{"", [12]byte{}, false}, }, { - "DBPointerOK/Success", Value.DBPointerOK, Value{Type: bsontype.DBPointer, Data: AppendDBPointer(nil, "foobar", oid)}, + "DBPointerOK/Success", Value.DBPointerOK, Value{Type: TypeDBPointer, Data: AppendDBPointer(nil, "foobar", oid)}, nil, []interface{}{"foobar", oid, true}, }, { - "JavaScript/Not JavaScript", Value.JavaScript, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.JavaScript", bsontype.String}, + "JavaScript/Not JavaScript", Value.JavaScript, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.JavaScript", TypeString}, nil, }, { - "JavaScript/Insufficient Bytes", Value.JavaScript, Value{Type: bsontype.JavaScript, Data: []byte{0x01, 0x02, 0x03}}, + "JavaScript/Insufficient Bytes", Value.JavaScript, Value{Type: TypeJavaScript, Data: []byte{0x01, 0x02, 0x03}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03}, []byte{0x01, 0x02, 0x03}), nil, }, { - "JavaScript/Success", Value.JavaScript, Value{Type: bsontype.JavaScript, Data: AppendJavaScript(nil, "var hello = 'world';")}, + "JavaScript/Success", Value.JavaScript, Value{Type: TypeJavaScript, Data: AppendJavaScript(nil, "var hello = 'world';")}, nil, []interface{}{"var hello = 'world';"}, }, { - "JavaScriptOK/Not JavaScript", Value.JavaScriptOK, Value{Type: bsontype.String}, + "JavaScriptOK/Not JavaScript", Value.JavaScriptOK, Value{Type: TypeString}, nil, []interface{}{"", false}, }, { - "JavaScriptOK/Insufficient Bytes", Value.JavaScriptOK, Value{Type: bsontype.JavaScript, Data: []byte{0x01, 0x02, 0x03}}, + "JavaScriptOK/Insufficient Bytes", Value.JavaScriptOK, Value{Type: TypeJavaScript, Data: []byte{0x01, 0x02, 0x03}}, nil, []interface{}{"", false}, }, { - "JavaScriptOK/Success", Value.JavaScriptOK, Value{Type: bsontype.JavaScript, Data: AppendJavaScript(nil, "var hello = 'world';")}, + "JavaScriptOK/Success", Value.JavaScriptOK, Value{Type: TypeJavaScript, Data: AppendJavaScript(nil, "var hello = 'world';")}, nil, []interface{}{"var hello = 'world';", true}, }, { - "Symbol/Not Symbol", Value.Symbol, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.Symbol", bsontype.String}, + "Symbol/Not Symbol", Value.Symbol, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.Symbol", TypeString}, nil, }, { - "Symbol/Insufficient Bytes", Value.Symbol, Value{Type: bsontype.Symbol, Data: []byte{0x01, 0x02, 0x03}}, + "Symbol/Insufficient Bytes", Value.Symbol, Value{Type: TypeSymbol, Data: []byte{0x01, 0x02, 0x03}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03}, []byte{0x01, 0x02, 0x03}), nil, }, { - "Symbol/Success", Value.Symbol, Value{Type: bsontype.Symbol, Data: AppendSymbol(nil, "symbol123456")}, + "Symbol/Success", Value.Symbol, Value{Type: TypeSymbol, Data: AppendSymbol(nil, "symbol123456")}, nil, []interface{}{"symbol123456"}, }, { - "SymbolOK/Not Symbol", Value.SymbolOK, Value{Type: bsontype.String}, + "SymbolOK/Not Symbol", Value.SymbolOK, Value{Type: TypeString}, nil, []interface{}{"", false}, }, { - "SymbolOK/Insufficient Bytes", Value.SymbolOK, Value{Type: bsontype.Symbol, Data: []byte{0x01, 0x02, 0x03}}, + "SymbolOK/Insufficient Bytes", Value.SymbolOK, Value{Type: TypeSymbol, Data: []byte{0x01, 0x02, 0x03}}, nil, []interface{}{"", false}, }, { - "SymbolOK/Success", Value.SymbolOK, Value{Type: bsontype.Symbol, Data: AppendSymbol(nil, "symbol123456")}, + "SymbolOK/Success", Value.SymbolOK, Value{Type: TypeSymbol, Data: AppendSymbol(nil, "symbol123456")}, nil, []interface{}{"symbol123456", true}, }, { - "CodeWithScope/Not CodeWithScope", Value.CodeWithScope, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.CodeWithScope", bsontype.String}, + "CodeWithScope/Not CodeWithScope", Value.CodeWithScope, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.CodeWithScope", TypeString}, nil, }, { - "CodeWithScope/Insufficient Bytes", Value.CodeWithScope, Value{Type: bsontype.CodeWithScope, Data: []byte{0x01, 0x02, 0x03}}, + "CodeWithScope/Insufficient Bytes", Value.CodeWithScope, Value{Type: TypeCodeWithScope, Data: []byte{0x01, 0x02, 0x03}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03}, []byte{0x01, 0x02, 0x03}), nil, }, { - "CodeWithScope/Success", Value.CodeWithScope, Value{Type: bsontype.CodeWithScope, Data: AppendCodeWithScope(nil, "var hello = 'world';", Document{0x05, 0x00, 0x00, 0x00, 0x00})}, + "CodeWithScope/Success", Value.CodeWithScope, Value{Type: TypeCodeWithScope, Data: AppendCodeWithScope(nil, "var hello = 'world';", Document{0x05, 0x00, 0x00, 0x00, 0x00})}, nil, []interface{}{"var hello = 'world';", Document{0x05, 0x00, 0x00, 0x00, 0x00}}, }, { - "CodeWithScopeOK/Not CodeWithScope", Value.CodeWithScopeOK, Value{Type: bsontype.String}, + "CodeWithScopeOK/Not CodeWithScope", Value.CodeWithScopeOK, Value{Type: TypeString}, nil, []interface{}{"", Document(nil), false}, }, { - "CodeWithScopeOK/Insufficient Bytes", Value.CodeWithScopeOK, Value{Type: bsontype.CodeWithScope, Data: []byte{0x01, 0x02, 0x03}}, + "CodeWithScopeOK/Insufficient Bytes", Value.CodeWithScopeOK, Value{Type: TypeCodeWithScope, Data: []byte{0x01, 0x02, 0x03}}, nil, []interface{}{"", Document(nil), false}, }, { - "CodeWithScopeOK/Success", Value.CodeWithScopeOK, Value{Type: bsontype.CodeWithScope, Data: AppendCodeWithScope(nil, "var hello = 'world';", Document{0x05, 0x00, 0x00, 0x00, 0x00})}, + "CodeWithScopeOK/Success", Value.CodeWithScopeOK, Value{Type: TypeCodeWithScope, Data: AppendCodeWithScope(nil, "var hello = 'world';", Document{0x05, 0x00, 0x00, 0x00, 0x00})}, nil, []interface{}{"var hello = 'world';", Document{0x05, 0x00, 0x00, 0x00, 0x00}, true}, }, { - "Int32/Not Int32", Value.Int32, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.Int32", bsontype.String}, + "Int32/Not Int32", Value.Int32, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.Int32", TypeString}, nil, }, { - "Int32/Insufficient Bytes", Value.Int32, Value{Type: bsontype.Int32, Data: []byte{0x01, 0x02, 0x03}}, + "Int32/Insufficient Bytes", Value.Int32, Value{Type: TypeInt32, Data: []byte{0x01, 0x02, 0x03}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03}, []byte{0x01, 0x02, 0x03}), nil, }, { - "Int32/Success", Value.Int32, Value{Type: bsontype.Int32, Data: AppendInt32(nil, 1234)}, + "Int32/Success", Value.Int32, Value{Type: TypeInt32, Data: AppendInt32(nil, 1234)}, nil, []interface{}{int32(1234)}, }, { - "Int32OK/Not Int32", Value.Int32OK, Value{Type: bsontype.String}, + "Int32OK/Not Int32", Value.Int32OK, Value{Type: TypeString}, nil, []interface{}{int32(0), false}, }, { - "Int32OK/Insufficient Bytes", Value.Int32OK, Value{Type: bsontype.Int32, Data: []byte{0x01, 0x02, 0x03}}, + "Int32OK/Insufficient Bytes", Value.Int32OK, Value{Type: TypeInt32, Data: []byte{0x01, 0x02, 0x03}}, nil, []interface{}{int32(0), false}, }, { - "Int32OK/Success", Value.Int32OK, Value{Type: bsontype.Int32, Data: AppendInt32(nil, 1234)}, + "Int32OK/Success", Value.Int32OK, Value{Type: TypeInt32, Data: AppendInt32(nil, 1234)}, nil, []interface{}{int32(1234), true}, }, { - "Timestamp/Not Timestamp", Value.Timestamp, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.Timestamp", bsontype.String}, + "Timestamp/Not Timestamp", Value.Timestamp, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.Timestamp", TypeString}, nil, }, { - "Timestamp/Insufficient Bytes", Value.Timestamp, Value{Type: bsontype.Timestamp, Data: []byte{0x01, 0x02, 0x03}}, + "Timestamp/Insufficient Bytes", Value.Timestamp, Value{Type: TypeTimestamp, Data: []byte{0x01, 0x02, 0x03}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03}, []byte{0x01, 0x02, 0x03}), nil, }, { - "Timestamp/Success", Value.Timestamp, Value{Type: bsontype.Timestamp, Data: AppendTimestamp(nil, 12345, 67890)}, + "Timestamp/Success", Value.Timestamp, Value{Type: TypeTimestamp, Data: AppendTimestamp(nil, 12345, 67890)}, nil, []interface{}{uint32(12345), uint32(67890)}, }, { - "TimestampOK/Not Timestamp", Value.TimestampOK, Value{Type: bsontype.String}, + "TimestampOK/Not Timestamp", Value.TimestampOK, Value{Type: TypeString}, nil, []interface{}{uint32(0), uint32(0), false}, }, { - "TimestampOK/Insufficient Bytes", Value.TimestampOK, Value{Type: bsontype.Timestamp, Data: []byte{0x01, 0x02, 0x03}}, + "TimestampOK/Insufficient Bytes", Value.TimestampOK, Value{Type: TypeTimestamp, Data: []byte{0x01, 0x02, 0x03}}, nil, []interface{}{uint32(0), uint32(0), false}, }, { - "TimestampOK/Success", Value.TimestampOK, Value{Type: bsontype.Timestamp, Data: AppendTimestamp(nil, 12345, 67890)}, + "TimestampOK/Success", Value.TimestampOK, Value{Type: TypeTimestamp, Data: AppendTimestamp(nil, 12345, 67890)}, nil, []interface{}{uint32(12345), uint32(67890), true}, }, { - "Int64/Not Int64", Value.Int64, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.Int64", bsontype.String}, + "Int64/Not Int64", Value.Int64, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.Int64", TypeString}, nil, }, { - "Int64/Insufficient Bytes", Value.Int64, Value{Type: bsontype.Int64, Data: []byte{0x01, 0x02, 0x03}}, + "Int64/Insufficient Bytes", Value.Int64, Value{Type: TypeInt64, Data: []byte{0x01, 0x02, 0x03}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03}, []byte{0x01, 0x02, 0x03}), nil, }, { - "Int64/Success", Value.Int64, Value{Type: bsontype.Int64, Data: AppendInt64(nil, 1234567890)}, + "Int64/Success", Value.Int64, Value{Type: TypeInt64, Data: AppendInt64(nil, 1234567890)}, nil, []interface{}{int64(1234567890)}, }, { - "Int64OK/Not Int64", Value.Int64OK, Value{Type: bsontype.String}, + "Int64OK/Not Int64", Value.Int64OK, Value{Type: TypeString}, nil, []interface{}{int64(0), false}, }, { - "Int64OK/Insufficient Bytes", Value.Int64OK, Value{Type: bsontype.Int64, Data: []byte{0x01, 0x02, 0x03}}, + "Int64OK/Insufficient Bytes", Value.Int64OK, Value{Type: TypeInt64, Data: []byte{0x01, 0x02, 0x03}}, nil, []interface{}{int64(0), false}, }, { - "Int64OK/Success", Value.Int64OK, Value{Type: bsontype.Int64, Data: AppendInt64(nil, 1234567890)}, + "Int64OK/Success", Value.Int64OK, Value{Type: TypeInt64, Data: AppendInt64(nil, 1234567890)}, nil, []interface{}{int64(1234567890), true}, }, { - "Decimal128/Not Decimal128", Value.Decimal128, Value{Type: bsontype.String}, - ElementTypeError{"bsoncore.Value.Decimal128", bsontype.String}, + "Decimal128/Not Decimal128", Value.Decimal128, Value{Type: TypeString}, + ElementTypeError{"bsoncore.Value.Decimal128", TypeString}, nil, }, { - "Decimal128/Insufficient Bytes", Value.Decimal128, Value{Type: bsontype.Decimal128, Data: []byte{0x01, 0x02, 0x03}}, + "Decimal128/Insufficient Bytes", Value.Decimal128, Value{Type: TypeDecimal128, Data: []byte{0x01, 0x02, 0x03}}, NewInsufficientBytesError([]byte{0x01, 0x02, 0x03}, []byte{0x01, 0x02, 0x03}), nil, }, { - "Decimal128/Success", Value.Decimal128, Value{Type: bsontype.Decimal128, Data: AppendDecimal128(nil, primitive.NewDecimal128(12345, 67890))}, + "Decimal128/Success", Value.Decimal128, Value{Type: TypeDecimal128, Data: AppendDecimal128(nil, 12345, 67890)}, nil, - []interface{}{primitive.NewDecimal128(12345, 67890)}, + []interface{}{uint64(12345), uint64(67890)}, }, { - "Decimal128OK/Not Decimal128", Value.Decimal128OK, Value{Type: bsontype.String}, + "Decimal128OK/Not Decimal128", Value.Decimal128OK, Value{Type: TypeString}, nil, - []interface{}{primitive.Decimal128{}, false}, + []interface{}{uint64(0), uint64(0), false}, }, { - "Decimal128OK/Insufficient Bytes", Value.Decimal128OK, Value{Type: bsontype.Decimal128, Data: []byte{0x01, 0x02, 0x03}}, + "Decimal128OK/Insufficient Bytes", Value.Decimal128OK, Value{Type: TypeDecimal128, Data: []byte{0x01, 0x02, 0x03}}, nil, - []interface{}{primitive.Decimal128{}, false}, + []interface{}{uint64(0), uint64(0), false}, }, { - "Decimal128OK/Success", Value.Decimal128OK, Value{Type: bsontype.Decimal128, Data: AppendDecimal128(nil, primitive.NewDecimal128(12345, 67890))}, + "Decimal128OK/Success", Value.Decimal128OK, Value{Type: TypeDecimal128, Data: AppendDecimal128(nil, 12345, 67890)}, nil, - []interface{}{primitive.NewDecimal128(12345, 67890), true}, + []interface{}{uint64(12345), uint64(67890), true}, }, { - "Timestamp.String/Success", Value.String, Value{Type: bsontype.Timestamp, Data: AppendTimestamp(nil, 12345, 67890)}, + "Timestamp.String/Success", Value.String, Value{Type: TypeTimestamp, Data: AppendTimestamp(nil, 12345, 67890)}, nil, []interface{}{"{\"$timestamp\":{\"t\":12345,\"i\":67890}}"}, }, @@ -669,7 +667,7 @@ func TestValue(t *testing.T) { for idx := range got { gotv, wantv := got[idx].Interface(), want[idx].Interface() - if !cmp.Equal(gotv, wantv, cmp.Comparer(compareDecimal128)) { + if !cmp.Equal(gotv, wantv) { t.Errorf("return values at index %d are not equal. got %v; want %v", idx, gotv, wantv) } } diff --git a/x/mongo/driver/auth/aws_conv.go b/x/mongo/driver/auth/aws_conv.go index 616182d9cf..51fc310a91 100644 --- a/x/mongo/driver/auth/aws_conv.go +++ b/x/mongo/driver/auth/aws_conv.go @@ -18,7 +18,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/aws/credentials" v4signer "go.mongodb.org/mongo-driver/internal/aws/signer/v4" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" @@ -41,8 +40,8 @@ type awsConversation struct { } type serverMessage struct { - Nonce primitive.Binary `bson:"s"` - Host string `bson:"h"` + Nonce bson.Binary `bson:"s"` + Host string `bson:"h"` } const ( diff --git a/x/mongo/driver/batch_cursor.go b/x/mongo/driver/batch_cursor.go index 99db007c31..773b0f2024 100644 --- a/x/mongo/driver/batch_cursor.go +++ b/x/mongo/driver/batch_cursor.go @@ -15,7 +15,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/codecutil" "go.mongodb.org/mongo-driver/internal/csot" @@ -310,7 +309,7 @@ func (bc *BatchCursor) KillCursor(ctx context.Context) error { return Operation{ CommandFn: func(dst []byte, desc description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendStringElement(dst, "killCursors", bc.collection) - dst = bsoncore.BuildArrayElement(dst, "cursors", bsoncore.Value{Type: bsontype.Int64, Data: bsoncore.AppendInt64(nil, bc.id)}) + dst = bsoncore.BuildArrayElement(dst, "cursors", bsoncore.Value{Type: bsoncore.TypeInt64, Data: bsoncore.AppendInt64(nil, bc.id)}) return dst, nil }, Database: bc.database, @@ -379,7 +378,7 @@ func (bc *BatchCursor) getMore(ctx context.Context) { } // The getMore command does not support commenting pre-4.4. - if comment.Type != bsontype.Type(0) && bc.serverDescription.WireVersion.Max >= 9 { + if comment.Type != bsoncore.Type(0) && bc.serverDescription.WireVersion.Max >= 9 { dst = bsoncore.AppendValueElement(dst, "comment", comment) } diff --git a/x/mongo/driver/crypt.go b/x/mongo/driver/crypt.go index 576c007d67..77e24762b0 100644 --- a/x/mongo/driver/crypt.go +++ b/x/mongo/driver/crypt.go @@ -15,7 +15,6 @@ import ( "strings" "time" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" "go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt" "go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt/options" @@ -174,11 +173,11 @@ func (c *crypt) RewrapDataKey(ctx context.Context, filter []byte, rewrappedDocuments := []bsoncore.Document{} for _, rewrappedDocumentValue := range rewrappedDocumentValues { - if rewrappedDocumentValue.Type != bsontype.EmbeddedDocument { + if rewrappedDocumentValue.Type != bsoncore.TypeEmbeddedDocument { // If a value in the document's array returned by mongocrypt is anything other than an embedded document, // then something is wrong and we should terminate the routine. return nil, fmt.Errorf("expected value of type %q, got: %q", - bsontype.EmbeddedDocument.String(), + bsoncore.TypeEmbeddedDocument.String(), rewrappedDocumentValue.Type.String()) } rewrappedDocuments = append(rewrappedDocuments, rewrappedDocumentValue.Document()) diff --git a/x/mongo/driver/errors.go b/x/mongo/driver/errors.go index 93b3444185..411479130a 100644 --- a/x/mongo/driver/errors.go +++ b/x/mongo/driver/errors.go @@ -389,19 +389,19 @@ func ExtractErrorFromServerResponse(doc bsoncore.Document) error { switch elem.Key() { case "ok": switch elem.Value().Type { - case bson.TypeInt32: + case bsoncore.TypeInt32: if elem.Value().Int32() == 1 { ok = true } - case bson.TypeInt64: + case bsoncore.TypeInt64: if elem.Value().Int64() == 1 { ok = true } - case bson.TypeDouble: + case bsoncore.TypeDouble: if elem.Value().Double() == 1 { ok = true } - case bson.TypeBoolean: + case bsoncore.TypeBoolean: if elem.Value().Boolean() { ok = true } diff --git a/x/mongo/driver/integration/compressor_test.go b/x/mongo/driver/integration/compressor_test.go index 5fca9baf80..50153c50cc 100644 --- a/x/mongo/driver/integration/compressor_test.go +++ b/x/mongo/driver/integration/compressor_test.go @@ -11,7 +11,6 @@ import ( "os" "testing" - "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/internal/integtest" "go.mongodb.org/mongo-driver/internal/require" "go.mongodb.org/mongo-driver/mongo/writeconcern" @@ -52,7 +51,7 @@ func TestCompression(t *testing.T) { networkVal, err := result.LookupErr("network") noerr(t, err) - require.Equal(t, networkVal.Type, bson.TypeEmbeddedDocument) + require.Equal(t, bsoncore.TypeEmbeddedDocument, networkVal.Type) compressionVal, err := networkVal.Document().LookupErr("compression") noerr(t, err) diff --git a/x/mongo/driver/integration/scram_test.go b/x/mongo/driver/integration/scram_test.go index 7d998421ee..fcf40e837b 100644 --- a/x/mongo/driver/integration/scram_test.go +++ b/x/mongo/driver/integration/scram_test.go @@ -12,7 +12,6 @@ import ( "os" "testing" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/internal/integtest" "go.mongodb.org/mongo-driver/mongo/description" "go.mongodb.org/mongo-driver/mongo/options" @@ -156,13 +155,13 @@ func createScramUsers(t *testing.T, s driver.Server, cases []scramTestCase) erro for _, c := range cases { var values []bsoncore.Value for _, v := range c.mechanisms { - values = append(values, bsoncore.Value{Type: bsontype.String, Data: bsoncore.AppendString(nil, v)}) + values = append(values, bsoncore.Value{Type: bsoncore.TypeString, Data: bsoncore.AppendString(nil, v)}) } newUserCmd := bsoncore.BuildDocumentFromElements(nil, bsoncore.AppendStringElement(nil, "createUser", c.username), bsoncore.AppendStringElement(nil, "pwd", c.password), bsoncore.AppendArrayElement(nil, "roles", bsoncore.BuildArray(nil, - bsoncore.Value{Type: bsontype.EmbeddedDocument, Data: bsoncore.BuildDocumentFromElements(nil, + bsoncore.Value{Type: bsoncore.TypeEmbeddedDocument, Data: bsoncore.BuildDocumentFromElements(nil, bsoncore.AppendStringElement(nil, "role", "readWrite"), bsoncore.AppendStringElement(nil, "db", db), )}, diff --git a/x/mongo/driver/mongocrypt/mongocrypt_test.go b/x/mongo/driver/mongocrypt/mongocrypt_test.go index ea9639fcca..67c4577f98 100644 --- a/x/mongo/driver/mongocrypt/mongocrypt_test.go +++ b/x/mongo/driver/mongocrypt/mongocrypt_test.go @@ -19,7 +19,6 @@ import ( "testing" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" "go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt/options" ) @@ -318,7 +317,7 @@ func TestMongoCrypt(t *testing.T) { defer crypt.Close() // create explicit encryption context and check initial state - keyID := primitive.Binary{ + keyID := bson.Binary{ Subtype: 0x04, // 0x04 is UUID subtype Data: []byte("aaaaaaaaaaaaaaaa"), } diff --git a/x/mongo/driver/mongocrypt/options/mongocrypt_context_options.go b/x/mongo/driver/mongocrypt/options/mongocrypt_context_options.go index 2874416a19..75d56f0585 100644 --- a/x/mongo/driver/mongocrypt/options/mongocrypt_context_options.go +++ b/x/mongo/driver/mongocrypt/options/mongocrypt_context_options.go @@ -7,7 +7,7 @@ package options import ( - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -51,7 +51,7 @@ const ( // ExplicitEncryptionOptions specifies options for configuring an explicit encryption context. type ExplicitEncryptionOptions struct { - KeyID *primitive.Binary + KeyID *bson.Binary KeyAltName *string Algorithm string QueryType string @@ -73,7 +73,7 @@ func ExplicitEncryption() *ExplicitEncryptionOptions { } // SetKeyID sets the key identifier. -func (eeo *ExplicitEncryptionOptions) SetKeyID(keyID primitive.Binary) *ExplicitEncryptionOptions { +func (eeo *ExplicitEncryptionOptions) SetKeyID(keyID bson.Binary) *ExplicitEncryptionOptions { eeo.KeyID = &keyID return eeo } diff --git a/x/mongo/driver/operation.go b/x/mongo/driver/operation.go index 4f97dd7a86..0ce697c28a 100644 --- a/x/mongo/driver/operation.go +++ b/x/mongo/driver/operation.go @@ -18,8 +18,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/csot" "go.mongodb.org/mongo-driver/internal/driverutil" @@ -100,7 +98,7 @@ type startedInformation struct { driverConnectionID int64 serverConnID *int64 redacted bool - serviceID *primitive.ObjectID + serviceID *bson.ObjectID serverAddress address.Address } @@ -114,7 +112,7 @@ type finishedInformation struct { driverConnectionID int64 serverConnID *int64 redacted bool - serviceID *primitive.ObjectID + serviceID *bson.ObjectID serverAddress address.Address duration time.Duration } @@ -1196,7 +1194,7 @@ func (op Operation) createLegacyHandshakeWireMessage( } if len(rp) > 0 { wrapper, dst = bsoncore.AppendDocumentStart(dst) - dst = bsoncore.AppendHeader(dst, bsontype.EmbeddedDocument, "$query") + dst = bsoncore.AppendHeader(dst, bsoncore.TypeEmbeddedDocument, "$query") } idx, dst := bsoncore.AppendDocumentStart(dst) dst, err = op.CommandFn(dst, desc) @@ -1477,7 +1475,7 @@ func (op Operation) addWriteConcern(dst []byte, desc description.SelectedServer) return dst, err } - return append(bsoncore.AppendHeader(dst, t, "writeConcern"), data...), nil + return append(bsoncore.AppendHeader(dst, bsoncore.Type(t), "writeConcern"), data...), nil } func (op Operation) addSession(dst []byte, desc description.SelectedServer) ([]byte, error) { @@ -1531,7 +1529,7 @@ func (op Operation) addClusterTime(dst []byte, desc description.SelectedServer) if err != nil { return dst } - return append(bsoncore.AppendHeader(dst, val.Type, "$clusterTime"), val.Value...) + return append(bsoncore.AppendHeader(dst, bsoncore.Type(val.Type), "$clusterTime"), val.Value...) // return bsoncore.AppendDocumentElement(dst, "$clusterTime", clusterTime) } @@ -1610,7 +1608,7 @@ func (op Operation) updateOperationTime(response bsoncore.Document) { } t, i := opTimeElem.Timestamp() - _ = sess.AdvanceOperationTime(&primitive.Timestamp{ + _ = sess.AdvanceOperationTime(&bson.Timestamp{ T: t, I: i, }) diff --git a/x/mongo/driver/operation/aggregate.go b/x/mongo/driver/operation/aggregate.go index d7f29be676..286bfe25a6 100644 --- a/x/mongo/driver/operation/aggregate.go +++ b/x/mongo/driver/operation/aggregate.go @@ -11,7 +11,6 @@ import ( "errors" "time" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/driverutil" "go.mongodb.org/mongo-driver/mongo/description" @@ -118,9 +117,9 @@ func (a *Aggregate) Execute(ctx context.Context) error { } func (a *Aggregate) command(dst []byte, desc description.SelectedServer) ([]byte, error) { - header := bsoncore.Value{Type: bsontype.String, Data: bsoncore.AppendString(nil, a.collection)} + header := bsoncore.Value{Type: bsoncore.TypeString, Data: bsoncore.AppendString(nil, a.collection)} if a.collection == "" { - header = bsoncore.Value{Type: bsontype.Int32, Data: []byte{0x01, 0x00, 0x00, 0x00}} + header = bsoncore.Value{Type: bsoncore.TypeInt32, Data: []byte{0x01, 0x00, 0x00, 0x00}} } dst = bsoncore.AppendValueElement(dst, "aggregate", header) @@ -143,10 +142,10 @@ func (a *Aggregate) command(dst []byte, desc description.SelectedServer) ([]byte } dst = bsoncore.AppendDocumentElement(dst, "collation", a.collation) } - if a.comment.Type != bsontype.Type(0) { + if a.comment.Type != bsoncore.Type(0) { dst = bsoncore.AppendValueElement(dst, "comment", a.comment) } - if a.hint.Type != bsontype.Type(0) { + if a.hint.Type != bsoncore.Type(0) { dst = bsoncore.AppendValueElement(dst, "hint", a.hint) } diff --git a/x/mongo/driver/operation/count.go b/x/mongo/driver/operation/count.go index 8de1e9f8d9..bd1204cd5e 100644 --- a/x/mongo/driver/operation/count.go +++ b/x/mongo/driver/operation/count.go @@ -12,7 +12,6 @@ import ( "fmt" "time" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/driverutil" "go.mongodb.org/mongo-driver/mongo/description" @@ -145,7 +144,7 @@ func (c *Count) command(dst []byte, _ description.SelectedServer) ([]byte, error if c.query != nil { dst = bsoncore.AppendDocumentElement(dst, "query", c.query) } - if c.comment.Type != bsontype.Type(0) { + if c.comment.Type != bsoncore.Type(0) { dst = bsoncore.AppendValueElement(dst, "comment", c.comment) } return dst, nil diff --git a/x/mongo/driver/operation/create_indexes.go b/x/mongo/driver/operation/create_indexes.go index 77daf676a4..a8e55313ed 100644 --- a/x/mongo/driver/operation/create_indexes.go +++ b/x/mongo/driver/operation/create_indexes.go @@ -12,7 +12,6 @@ import ( "fmt" "time" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/driverutil" "go.mongodb.org/mongo-driver/mongo/description" @@ -125,7 +124,7 @@ func (ci *CreateIndexes) Execute(ctx context.Context) error { func (ci *CreateIndexes) command(dst []byte, desc description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendStringElement(dst, "createIndexes", ci.collection) - if ci.commitQuorum.Type != bsontype.Type(0) { + if ci.commitQuorum.Type != bsoncore.Type(0) { if desc.WireVersion == nil || !desc.WireVersion.Includes(9) { return nil, errors.New("the 'commitQuorum' command parameter requires a minimum server wire version of 9") } diff --git a/x/mongo/driver/operation/delete.go b/x/mongo/driver/operation/delete.go index bf95cf496d..e3546c7ad5 100644 --- a/x/mongo/driver/operation/delete.go +++ b/x/mongo/driver/operation/delete.go @@ -12,7 +12,6 @@ import ( "fmt" "time" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/driverutil" "go.mongodb.org/mongo-driver/internal/logger" @@ -122,7 +121,7 @@ func (d *Delete) Execute(ctx context.Context) error { func (d *Delete) command(dst []byte, desc description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendStringElement(dst, "delete", d.collection) - if d.comment.Type != bsontype.Type(0) { + if d.comment.Type != bsoncore.Type(0) { dst = bsoncore.AppendValueElement(dst, "comment", d.comment) } if d.ordered != nil { diff --git a/x/mongo/driver/operation/distinct.go b/x/mongo/driver/operation/distinct.go index b7e675ce42..af65eb7d31 100644 --- a/x/mongo/driver/operation/distinct.go +++ b/x/mongo/driver/operation/distinct.go @@ -11,7 +11,6 @@ import ( "errors" "time" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/driverutil" "go.mongodb.org/mongo-driver/mongo/description" @@ -119,7 +118,7 @@ func (d *Distinct) command(dst []byte, desc description.SelectedServer) ([]byte, } dst = bsoncore.AppendDocumentElement(dst, "collation", d.collation) } - if d.comment.Type != bsontype.Type(0) { + if d.comment.Type != bsoncore.Type(0) { dst = bsoncore.AppendValueElement(dst, "comment", d.comment) } if d.key != nil { diff --git a/x/mongo/driver/operation/find.go b/x/mongo/driver/operation/find.go index a62b9522c0..d6cd90aaaa 100644 --- a/x/mongo/driver/operation/find.go +++ b/x/mongo/driver/operation/find.go @@ -11,7 +11,6 @@ import ( "errors" "time" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/driverutil" "go.mongodb.org/mongo-driver/internal/logger" @@ -136,13 +135,13 @@ func (f *Find) command(dst []byte, desc description.SelectedServer) ([]byte, err } dst = bsoncore.AppendDocumentElement(dst, "collation", f.collation) } - if f.comment.Type != bsontype.Type(0) { + if f.comment.Type != bsoncore.Type(0) { dst = bsoncore.AppendValueElement(dst, "comment", f.comment) } if f.filter != nil { dst = bsoncore.AppendDocumentElement(dst, "filter", f.filter) } - if f.hint.Type != bsontype.Type(0) { + if f.hint.Type != bsoncore.Type(0) { dst = bsoncore.AppendValueElement(dst, "hint", f.hint) } if f.let != nil { diff --git a/x/mongo/driver/operation/find_and_modify.go b/x/mongo/driver/operation/find_and_modify.go index 7faf561135..5af8a0c105 100644 --- a/x/mongo/driver/operation/find_and_modify.go +++ b/x/mongo/driver/operation/find_and_modify.go @@ -13,7 +13,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/driverutil" "go.mongodb.org/mongo-driver/mongo/description" @@ -84,7 +83,7 @@ func buildFindAndModifyResult(response bsoncore.Document) (FindAndModifyResult, famr.Value, ok = element.Value().DocumentOK() // The 'value' field returned by a FindAndModify can be null in the case that no document was found. - if element.Value().Type != bsontype.Null && !ok { + if element.Value().Type != bsoncore.TypeNull && !ok { return famr, fmt.Errorf("response field 'value' is type document or null, but received BSON type %s", element.Value().Type) } case "lastErrorObject": @@ -169,7 +168,7 @@ func (fam *FindAndModify) command(dst []byte, desc description.SelectedServer) ( } dst = bsoncore.AppendDocumentElement(dst, "collation", fam.collation) } - if fam.comment.Type != bsontype.Type(0) { + if fam.comment.Type != bsoncore.Type(0) { dst = bsoncore.AppendValueElement(dst, "comment", fam.comment) } if fam.fields != nil { @@ -199,7 +198,7 @@ func (fam *FindAndModify) command(dst []byte, desc description.SelectedServer) ( dst = bsoncore.AppendBooleanElement(dst, "upsert", *fam.upsert) } - if fam.hint.Type != bsontype.Type(0) { + if fam.hint.Type != bsoncore.Type(0) { if desc.WireVersion == nil || !desc.WireVersion.Includes(8) { return nil, errors.New("the 'hint' command parameter requires a minimum server wire version of 8") diff --git a/x/mongo/driver/operation/insert.go b/x/mongo/driver/operation/insert.go index 7da4b8b0fb..7da70653ee 100644 --- a/x/mongo/driver/operation/insert.go +++ b/x/mongo/driver/operation/insert.go @@ -12,7 +12,6 @@ import ( "fmt" "time" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/driverutil" "go.mongodb.org/mongo-driver/internal/logger" @@ -124,7 +123,7 @@ func (i *Insert) command(dst []byte, desc description.SelectedServer) ([]byte, e if i.bypassDocumentValidation != nil && (desc.WireVersion != nil && desc.WireVersion.Includes(4)) { dst = bsoncore.AppendBooleanElement(dst, "bypassDocumentValidation", *i.bypassDocumentValidation) } - if i.comment.Type != bsontype.Type(0) { + if i.comment.Type != bsoncore.Type(0) { dst = bsoncore.AppendValueElement(dst, "comment", i.comment) } if i.ordered != nil { diff --git a/x/mongo/driver/operation/update.go b/x/mongo/driver/operation/update.go index 881b1bcf7b..65c33bc5f6 100644 --- a/x/mongo/driver/operation/update.go +++ b/x/mongo/driver/operation/update.go @@ -13,7 +13,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/driverutil" "go.mongodb.org/mongo-driver/internal/logger" @@ -178,7 +177,7 @@ func (u *Update) command(dst []byte, desc description.SelectedServer) ([]byte, e dst = bsoncore.AppendBooleanElement(dst, "bypassDocumentValidation", *u.bypassDocumentValidation) } - if u.comment.Type != bsontype.Type(0) { + if u.comment.Type != bsoncore.Type(0) { dst = bsoncore.AppendValueElement(dst, "comment", u.comment) } if u.ordered != nil { diff --git a/x/mongo/driver/operation_test.go b/x/mongo/driver/operation_test.go index befe51f2db..964a23f6c3 100644 --- a/x/mongo/driver/operation_test.go +++ b/x/mongo/driver/operation_test.go @@ -14,8 +14,7 @@ import ( "time" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/csot" "go.mongodb.org/mongo-driver/internal/handshake" @@ -386,7 +385,7 @@ func TestOperation(t *testing.T) { Operation{}.updateClusterTimes(bsoncore.BuildDocumentFromElements(nil)) // should do nothing }) t.Run("updateOperationTime", func(t *testing.T) { - want := primitive.Timestamp{T: 1234, I: 4567} + want := bson.Timestamp{T: 1234, I: 4567} sessPool := session.NewPool(nil) id, err := uuid.New() @@ -417,7 +416,7 @@ func TestOperation(t *testing.T) { rpWithTags := bsoncore.BuildDocumentFromElements(nil, bsoncore.AppendStringElement(nil, "mode", "secondaryPreferred"), bsoncore.BuildArrayElement(nil, "tags", - bsoncore.Value{Type: bsontype.EmbeddedDocument, + bsoncore.Value{Type: bsoncore.TypeEmbeddedDocument, Data: bsoncore.BuildDocumentFromElements(nil, bsoncore.AppendStringElement(nil, "disk", "ssd"), bsoncore.AppendStringElement(nil, "use", "reporting"), @@ -439,7 +438,7 @@ func TestOperation(t *testing.T) { rpWithAllOptions := bsoncore.BuildDocumentFromElements(nil, bsoncore.AppendStringElement(nil, "mode", "secondaryPreferred"), bsoncore.BuildArrayElement(nil, "tags", - bsoncore.Value{Type: bsontype.EmbeddedDocument, + bsoncore.Value{Type: bsoncore.TypeEmbeddedDocument, Data: bsoncore.BuildDocumentFromElements(nil, bsoncore.AppendStringElement(nil, "disk", "ssd"), bsoncore.AppendStringElement(nil, "use", "reporting"), diff --git a/x/mongo/driver/session/client_session.go b/x/mongo/driver/session/client_session.go index d99ad101ae..abc7a64efd 100644 --- a/x/mongo/driver/session/client_session.go +++ b/x/mongo/driver/session/client_session.go @@ -11,7 +11,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/uuid" "go.mongodb.org/mongo-driver/mongo/description" "go.mongodb.org/mongo-driver/mongo/readconcern" @@ -92,7 +91,7 @@ type Client struct { ClientID uuid.UUID ClusterTime bson.Raw Consistent bool // causal consistency - OperationTime *primitive.Timestamp + OperationTime *bson.Timestamp IsImplicit bool Terminated bool RetryingCommit bool @@ -120,7 +119,7 @@ type Client struct { PinnedServer *description.Server RecoveryToken bson.Raw PinnedConnection LoadBalancedTransactionConnection - SnapshotTime *primitive.Timestamp + SnapshotTime *bson.Timestamp } func getClusterTime(clusterTime bson.Raw) (uint32, uint32) { @@ -232,7 +231,7 @@ func (c *Client) AdvanceClusterTime(clusterTime bson.Raw) error { } // AdvanceOperationTime updates the session's operation time. -func (c *Client) AdvanceOperationTime(opTime *primitive.Timestamp) error { +func (c *Client) AdvanceOperationTime(opTime *bson.Timestamp) error { if c.Terminated { return ErrSessionEnded } @@ -294,7 +293,7 @@ func (c *Client) UpdateSnapshotTime(response bsoncore.Document) { } t, i := ssTimeElem.Timestamp() - c.SnapshotTime = &primitive.Timestamp{ + c.SnapshotTime = &bson.Timestamp{ T: t, I: i, } diff --git a/x/mongo/driver/session/client_session_test.go b/x/mongo/driver/session/client_session_test.go index 1ba1198802..e361d2f2fc 100644 --- a/x/mongo/driver/session/client_session_test.go +++ b/x/mongo/driver/session/client_session_test.go @@ -11,7 +11,7 @@ import ( "errors" "testing" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/require" "go.mongodb.org/mongo-driver/internal/uuid" @@ -24,7 +24,7 @@ var sessionOpts = &ClientOptions{ CausalConsistency: &consistent, } -func compareOperationTimes(t *testing.T, expected *primitive.Timestamp, actual *primitive.Timestamp) { +func compareOperationTimes(t *testing.T, expected *bson.Timestamp, actual *bson.Timestamp) { if expected.T != actual.T { t.Fatalf("T value mismatch; expected %d got %d", expected.T, actual.T) } @@ -87,7 +87,7 @@ func TestClientSession(t *testing.T) { sess, err := NewClientSession(&Pool{}, id, sessionOpts) require.Nil(t, err, "Unexpected error") - optime1 := &primitive.Timestamp{ + optime1 := &bson.Timestamp{ T: 1, I: 0, } @@ -95,7 +95,7 @@ func TestClientSession(t *testing.T) { assert.Nil(t, err, "error updating first operation time: %s", err) compareOperationTimes(t, optime1, sess.OperationTime) - optime2 := &primitive.Timestamp{ + optime2 := &bson.Timestamp{ T: 2, I: 0, } @@ -103,7 +103,7 @@ func TestClientSession(t *testing.T) { assert.Nil(t, err, "error updating second operation time: %s", err) compareOperationTimes(t, optime2, sess.OperationTime) - optime3 := &primitive.Timestamp{ + optime3 := &bson.Timestamp{ T: 2, I: 1, } @@ -111,7 +111,7 @@ func TestClientSession(t *testing.T) { assert.Nil(t, err, "error updating third operation time: %s", err) compareOperationTimes(t, optime3, sess.OperationTime) - err = sess.AdvanceOperationTime(&primitive.Timestamp{ + err = sess.AdvanceOperationTime(&bson.Timestamp{ T: 1, I: 10, }) diff --git a/x/mongo/driver/topology/CMAP_spec_test.go b/x/mongo/driver/topology/CMAP_spec_test.go index 764d25db9d..62283d2156 100644 --- a/x/mongo/driver/topology/CMAP_spec_test.go +++ b/x/mongo/driver/topology/CMAP_spec_test.go @@ -19,7 +19,7 @@ import ( "testing" "time" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/require" "go.mongodb.org/mongo-driver/internal/spectest" @@ -208,7 +208,7 @@ func runCMAPTest(t *testing.T, testFileName string) { } })) - s := NewServer("mongodb://fake", primitive.NewObjectID(), sOpts...) + s := NewServer("mongodb://fake", bson.NewObjectID(), sOpts...) s.state = serverConnected require.NoError(t, err, "error connecting connection pool") defer s.pool.close(context.Background()) diff --git a/x/mongo/driver/topology/connection_options.go b/x/mongo/driver/topology/connection_options.go index 43e6f3f507..41533a149a 100644 --- a/x/mongo/driver/topology/connection_options.go +++ b/x/mongo/driver/topology/connection_options.go @@ -13,7 +13,7 @@ import ( "net/http" "time" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/httputil" "go.mongodb.org/mongo-driver/x/mongo/driver" @@ -45,7 +45,7 @@ var DefaultDialer Dialer = &net.Dialer{} type Handshaker = driver.Handshaker // generationNumberFn is a callback type used by a connection to fetch its generation number given its service ID. -type generationNumberFn func(serviceID *primitive.ObjectID) uint64 +type generationNumberFn func(serviceID *bson.ObjectID) uint64 type connectionConfig struct { connectTimeout time.Duration diff --git a/x/mongo/driver/topology/fsm.go b/x/mongo/driver/topology/fsm.go index e9904a9a06..30ebfe1886 100644 --- a/x/mongo/driver/topology/fsm.go +++ b/x/mongo/driver/topology/fsm.go @@ -11,7 +11,7 @@ import ( "fmt" "sync/atomic" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/internal/ptrutil" "go.mongodb.org/mongo-driver/mongo/address" "go.mongodb.org/mongo-driver/mongo/description" @@ -27,7 +27,7 @@ var ( type fsm struct { description.Topology - maxElectionID primitive.ObjectID + maxElectionID bson.ObjectID maxSetVersion uint32 compatible atomic.Value compatibilityErr error diff --git a/x/mongo/driver/topology/pool.go b/x/mongo/driver/topology/pool.go index 147452d68c..d4dc3c76b9 100644 --- a/x/mongo/driver/topology/pool.go +++ b/x/mongo/driver/topology/pool.go @@ -14,7 +14,7 @@ import ( "sync/atomic" "time" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/logger" "go.mongodb.org/mongo-driver/mongo/address" @@ -77,7 +77,7 @@ type poolConfig struct { LoadBalanced bool PoolMonitor *event.PoolMonitor Logger *logger.Logger - handshakeErrFn func(error, uint64, *primitive.ObjectID) + handshakeErrFn func(error, uint64, *bson.ObjectID) } type pool struct { @@ -100,7 +100,7 @@ type pool struct { // handshakeErrFn is used to handle any errors that happen during connection establishment and // handshaking. - handshakeErrFn func(error, uint64, *primitive.ObjectID) + handshakeErrFn func(error, uint64, *bson.ObjectID) connOpts []ConnectionOption generation *poolGenerationMap @@ -681,7 +681,7 @@ func (p *pool) closeConnection(conn *connection) error { return nil } -func (p *pool) getGenerationForNewConnection(serviceID *primitive.ObjectID) uint64 { +func (p *pool) getGenerationForNewConnection(serviceID *bson.ObjectID) uint64 { return p.generation.addConnection(serviceID) } @@ -829,12 +829,12 @@ func (p *pool) checkInNoEvent(conn *connection) error { } // clear calls clearImpl internally with a false interruptAllConnections value. -func (p *pool) clear(err error, serviceID *primitive.ObjectID) { +func (p *pool) clear(err error, serviceID *bson.ObjectID) { p.clearImpl(err, serviceID, false) } // clearAll does same as the "clear" method but interrupts all connections. -func (p *pool) clearAll(err error, serviceID *primitive.ObjectID) { +func (p *pool) clearAll(err error, serviceID *bson.ObjectID) { p.clearImpl(err, serviceID, true) } @@ -858,7 +858,7 @@ func (p *pool) interruptConnections(conns []*connection) { // mode). // If interruptAllConnections is true, this function calls interruptConnections to interrupt all // non-idle connections. -func (p *pool) clearImpl(err error, serviceID *primitive.ObjectID, interruptAllConnections bool) { +func (p *pool) clearImpl(err error, serviceID *bson.ObjectID, interruptAllConnections bool) { if p.getState() == poolClosed { return } diff --git a/x/mongo/driver/topology/pool_generation_counter.go b/x/mongo/driver/topology/pool_generation_counter.go index dd10c0ce7a..a0d804af40 100644 --- a/x/mongo/driver/topology/pool_generation_counter.go +++ b/x/mongo/driver/topology/pool_generation_counter.go @@ -10,7 +10,7 @@ import ( "sync" "sync/atomic" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" ) // Pool generation state constants. @@ -27,23 +27,23 @@ type generationStats struct { } // poolGenerationMap tracks the version for each service ID present in a pool. For deployments that are not behind a -// load balancer, there is only one service ID: primitive.NilObjectID. For load-balanced deployments, each server behind +// load balancer, there is only one service ID: bson.NilObjectID. For load-balanced deployments, each server behind // the load balancer will have a unique service ID. type poolGenerationMap struct { // state must be accessed using the atomic package and should be at the beginning of the struct. // - atomic bug: https://pkg.go.dev/sync/atomic#pkg-note-BUG // - suggested layout: https://go101.org/article/memory-layout.html state int64 - generationMap map[primitive.ObjectID]*generationStats + generationMap map[bson.ObjectID]*generationStats sync.Mutex } func newPoolGenerationMap() *poolGenerationMap { pgm := &poolGenerationMap{ - generationMap: make(map[primitive.ObjectID]*generationStats), + generationMap: make(map[bson.ObjectID]*generationStats), } - pgm.generationMap[primitive.NilObjectID] = &generationStats{} + pgm.generationMap[bson.NilObjectID] = &generationStats{} return pgm } @@ -57,7 +57,7 @@ func (p *poolGenerationMap) disconnect() { // addConnection increments the connection count for the generation associated with the given service ID and returns the // generation number for the connection. -func (p *poolGenerationMap) addConnection(serviceIDPtr *primitive.ObjectID) uint64 { +func (p *poolGenerationMap) addConnection(serviceIDPtr *bson.ObjectID) uint64 { serviceID := getServiceID(serviceIDPtr) p.Lock() defer p.Unlock() @@ -77,7 +77,7 @@ func (p *poolGenerationMap) addConnection(serviceIDPtr *primitive.ObjectID) uint return 0 } -func (p *poolGenerationMap) removeConnection(serviceIDPtr *primitive.ObjectID) { +func (p *poolGenerationMap) removeConnection(serviceIDPtr *bson.ObjectID) { serviceID := getServiceID(serviceIDPtr) p.Lock() defer p.Unlock() @@ -96,7 +96,7 @@ func (p *poolGenerationMap) removeConnection(serviceIDPtr *primitive.ObjectID) { } } -func (p *poolGenerationMap) clear(serviceIDPtr *primitive.ObjectID) { +func (p *poolGenerationMap) clear(serviceIDPtr *bson.ObjectID) { serviceID := getServiceID(serviceIDPtr) p.Lock() defer p.Unlock() @@ -106,7 +106,7 @@ func (p *poolGenerationMap) clear(serviceIDPtr *primitive.ObjectID) { } } -func (p *poolGenerationMap) stale(serviceIDPtr *primitive.ObjectID, knownGeneration uint64) bool { +func (p *poolGenerationMap) stale(serviceIDPtr *bson.ObjectID, knownGeneration uint64) bool { // If the map has been disconnected, all connections should be considered stale to ensure that they're closed. if atomic.LoadInt64(&p.state) == generationDisconnected { return true @@ -118,7 +118,7 @@ func (p *poolGenerationMap) stale(serviceIDPtr *primitive.ObjectID, knownGenerat return false } -func (p *poolGenerationMap) getGeneration(serviceIDPtr *primitive.ObjectID) (uint64, bool) { +func (p *poolGenerationMap) getGeneration(serviceIDPtr *bson.ObjectID) (uint64, bool) { serviceID := getServiceID(serviceIDPtr) p.Lock() defer p.Unlock() @@ -129,7 +129,7 @@ func (p *poolGenerationMap) getGeneration(serviceIDPtr *primitive.ObjectID) (uin return 0, false } -func (p *poolGenerationMap) getNumConns(serviceIDPtr *primitive.ObjectID) uint64 { +func (p *poolGenerationMap) getNumConns(serviceIDPtr *bson.ObjectID) uint64 { serviceID := getServiceID(serviceIDPtr) p.Lock() defer p.Unlock() @@ -140,9 +140,9 @@ func (p *poolGenerationMap) getNumConns(serviceIDPtr *primitive.ObjectID) uint64 return 0 } -func getServiceID(oid *primitive.ObjectID) primitive.ObjectID { +func getServiceID(oid *bson.ObjectID) bson.ObjectID { if oid == nil { - return primitive.NilObjectID + return bson.NilObjectID } return *oid } diff --git a/x/mongo/driver/topology/sdam_spec_test.go b/x/mongo/driver/topology/sdam_spec_test.go index 9968f15056..2dac5e7b92 100644 --- a/x/mongo/driver/topology/sdam_spec_test.go +++ b/x/mongo/driver/topology/sdam_spec_test.go @@ -17,7 +17,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/spectest" @@ -34,35 +33,35 @@ type response struct { } type Hello struct { - Arbiters []string `bson:"arbiters,omitempty"` - ArbiterOnly bool `bson:"arbiterOnly,omitempty"` - ClusterTime bson.Raw `bson:"$clusterTime,omitempty"` - Compression []string `bson:"compression,omitempty"` - ElectionID primitive.ObjectID `bson:"electionId,omitempty"` - Hidden bool `bson:"hidden,omitempty"` - Hosts []string `bson:"hosts,omitempty"` - HelloOK bool `bson:"helloOk,omitempty"` - IsWritablePrimary bool `bson:"isWritablePrimary,omitempty"` - IsReplicaSet bool `bson:"isreplicaset,omitempty"` - LastWrite *lastWriteDate `bson:"lastWrite,omitempty"` - LogicalSessionTimeoutMinutes uint32 `bson:"logicalSessionTimeoutMinutes,omitempty"` - MaxBSONObjectSize uint32 `bson:"maxBsonObjectSize,omitempty"` - MaxMessageSizeBytes uint32 `bson:"maxMessageSizeBytes,omitempty"` - MaxWriteBatchSize uint32 `bson:"maxWriteBatchSize,omitempty"` - Me string `bson:"me,omitempty"` - MaxWireVersion int32 `bson:"maxWireVersion,omitempty"` - MinWireVersion int32 `bson:"minWireVersion,omitempty"` - Msg string `bson:"msg,omitempty"` - OK int32 `bson:"ok"` - Passives []string `bson:"passives,omitempty"` - Primary string `bson:"primary,omitempty"` - ReadOnly bool `bson:"readOnly,omitempty"` - SaslSupportedMechs []string `bson:"saslSupportedMechs,omitempty"` - Secondary bool `bson:"secondary,omitempty"` - SetName string `bson:"setName,omitempty"` - SetVersion uint32 `bson:"setVersion,omitempty"` - Tags map[string]string `bson:"tags,omitempty"` - TopologyVersion *topologyVersion `bson:"topologyVersion,omitempty"` + Arbiters []string `bson:"arbiters,omitempty"` + ArbiterOnly bool `bson:"arbiterOnly,omitempty"` + ClusterTime bson.Raw `bson:"$clusterTime,omitempty"` + Compression []string `bson:"compression,omitempty"` + ElectionID bson.ObjectID `bson:"electionId,omitempty"` + Hidden bool `bson:"hidden,omitempty"` + Hosts []string `bson:"hosts,omitempty"` + HelloOK bool `bson:"helloOk,omitempty"` + IsWritablePrimary bool `bson:"isWritablePrimary,omitempty"` + IsReplicaSet bool `bson:"isreplicaset,omitempty"` + LastWrite *lastWriteDate `bson:"lastWrite,omitempty"` + LogicalSessionTimeoutMinutes uint32 `bson:"logicalSessionTimeoutMinutes,omitempty"` + MaxBSONObjectSize uint32 `bson:"maxBsonObjectSize,omitempty"` + MaxMessageSizeBytes uint32 `bson:"maxMessageSizeBytes,omitempty"` + MaxWriteBatchSize uint32 `bson:"maxWriteBatchSize,omitempty"` + Me string `bson:"me,omitempty"` + MaxWireVersion int32 `bson:"maxWireVersion,omitempty"` + MinWireVersion int32 `bson:"minWireVersion,omitempty"` + Msg string `bson:"msg,omitempty"` + OK int32 `bson:"ok"` + Passives []string `bson:"passives,omitempty"` + Primary string `bson:"primary,omitempty"` + ReadOnly bool `bson:"readOnly,omitempty"` + SaslSupportedMechs []string `bson:"saslSupportedMechs,omitempty"` + Secondary bool `bson:"secondary,omitempty"` + SetName string `bson:"setName,omitempty"` + SetVersion uint32 `bson:"setVersion,omitempty"` + Tags map[string]string `bson:"tags,omitempty"` + TopologyVersion *topologyVersion `bson:"topologyVersion,omitempty"` } type lastWriteDate struct { @@ -73,7 +72,7 @@ type server struct { Type string SetName string SetVersion uint32 - ElectionID *primitive.ObjectID `bson:"electionId"` + ElectionID *bson.ObjectID `bson:"electionId"` MinWireVersion *int32 MaxWireVersion *int32 TopologyVersion *topologyVersion @@ -81,7 +80,7 @@ type server struct { } type topologyVersion struct { - ProcessID primitive.ObjectID `bson:"processId"` + ProcessID bson.ObjectID `bson:"processId"` Counter int64 } @@ -155,7 +154,7 @@ type outcome struct { SetName string LogicalSessionTimeoutMinutes *int64 MaxSetVersion uint32 - MaxElectionID primitive.ObjectID `bson:"maxElectionId"` + MaxElectionID bson.ObjectID `bson:"maxElectionId"` Compatible *bool Events []monitoringEvent } @@ -574,7 +573,7 @@ func TestHasStalePrimary(t *testing.T) { srv := description.Server{ WireVersion: &description.VersionRange{Min: 17, Max: 17}, - ElectionID: primitive.NewObjectIDFromTimestamp(time.Now()), + ElectionID: bson.NewObjectIDFromTimestamp(time.Now()), SetVersion: 1, } @@ -592,7 +591,7 @@ func TestHasStalePrimary(t *testing.T) { srv := description.Server{ WireVersion: &description.VersionRange{Min: 17, Max: 17}, - ElectionID: primitive.NewObjectIDFromTimestamp(time.Now()), + ElectionID: bson.NewObjectIDFromTimestamp(time.Now()), SetVersion: 2, } @@ -610,7 +609,7 @@ func TestHasStalePrimary(t *testing.T) { srv := description.Server{ WireVersion: &description.VersionRange{Min: 17, Max: 17}, - ElectionID: primitive.NewObjectIDFromTimestamp(time.Now()), + ElectionID: bson.NewObjectIDFromTimestamp(time.Now()), SetVersion: 1, } @@ -627,13 +626,13 @@ func TestHasStalePrimary(t *testing.T) { t.Parallel() fsm := fsm{ - maxElectionID: primitive.NewObjectIDFromTimestamp(time.Now()), + maxElectionID: bson.NewObjectIDFromTimestamp(time.Now()), maxSetVersion: 2, } srv := description.Server{ WireVersion: &description.VersionRange{Min: 17, Max: 17}, - ElectionID: primitive.NewObjectIDFromTimestamp(time.Now().Add(time.Second)), + ElectionID: bson.NewObjectIDFromTimestamp(time.Now().Add(time.Second)), SetVersion: 1, } @@ -645,13 +644,13 @@ func TestHasStalePrimary(t *testing.T) { t.Parallel() fsm := fsm{ - maxElectionID: primitive.NewObjectIDFromTimestamp(time.Now()), + maxElectionID: bson.NewObjectIDFromTimestamp(time.Now()), maxSetVersion: 1, } srv := description.Server{ WireVersion: &description.VersionRange{Min: 17, Max: 17}, - ElectionID: primitive.NewObjectIDFromTimestamp(time.Now().Add(time.Second)), + ElectionID: bson.NewObjectIDFromTimestamp(time.Now().Add(time.Second)), SetVersion: 2, } @@ -663,13 +662,13 @@ func TestHasStalePrimary(t *testing.T) { t.Parallel() fsm := fsm{ - maxElectionID: primitive.NewObjectIDFromTimestamp(time.Now()), + maxElectionID: bson.NewObjectIDFromTimestamp(time.Now()), maxSetVersion: 1, } srv := description.Server{ WireVersion: &description.VersionRange{Min: 17, Max: 17}, - ElectionID: primitive.NewObjectIDFromTimestamp(time.Now().Add(time.Second)), + ElectionID: bson.NewObjectIDFromTimestamp(time.Now().Add(time.Second)), SetVersion: 1, } @@ -682,12 +681,12 @@ func TestHasStalePrimary(t *testing.T) { srv := description.Server{ WireVersion: &description.VersionRange{Min: 17, Max: 17}, - ElectionID: primitive.NewObjectIDFromTimestamp(time.Now().Add(-time.Second)), + ElectionID: bson.NewObjectIDFromTimestamp(time.Now().Add(-time.Second)), SetVersion: 1, } fsm := fsm{ - maxElectionID: primitive.NewObjectIDFromTimestamp(time.Now()), + maxElectionID: bson.NewObjectIDFromTimestamp(time.Now()), maxSetVersion: 2, } @@ -700,12 +699,12 @@ func TestHasStalePrimary(t *testing.T) { srv := description.Server{ WireVersion: &description.VersionRange{Min: 17, Max: 17}, - ElectionID: primitive.NewObjectIDFromTimestamp(time.Now().Add(-time.Second)), + ElectionID: bson.NewObjectIDFromTimestamp(time.Now().Add(-time.Second)), SetVersion: 2, } fsm := fsm{ - maxElectionID: primitive.NewObjectIDFromTimestamp(time.Now()), + maxElectionID: bson.NewObjectIDFromTimestamp(time.Now()), maxSetVersion: 1, } @@ -718,12 +717,12 @@ func TestHasStalePrimary(t *testing.T) { srv := description.Server{ WireVersion: &description.VersionRange{Min: 17, Max: 17}, - ElectionID: primitive.NewObjectIDFromTimestamp(time.Now().Add(-time.Second)), + ElectionID: bson.NewObjectIDFromTimestamp(time.Now().Add(-time.Second)), SetVersion: 1, } fsm := fsm{ - maxElectionID: primitive.NewObjectIDFromTimestamp(time.Now()), + maxElectionID: bson.NewObjectIDFromTimestamp(time.Now()), maxSetVersion: 1, } diff --git a/x/mongo/driver/topology/server.go b/x/mongo/driver/topology/server.go index 373f3a861c..653dee2d9b 100644 --- a/x/mongo/driver/topology/server.go +++ b/x/mongo/driver/topology/server.go @@ -16,7 +16,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/driverutil" "go.mongodb.org/mongo-driver/internal/logger" @@ -105,7 +104,7 @@ type Server struct { // description related fields desc atomic.Value // holds a description.Server updateTopologyCallback atomic.Value - topologyID primitive.ObjectID + topologyID bson.ObjectID // subscriber related fields subLock sync.Mutex @@ -138,7 +137,7 @@ type updateTopologyCallback func(description.Server) description.Server func ConnectServer( addr address.Address, updateCallback updateTopologyCallback, - topologyID primitive.ObjectID, + topologyID bson.ObjectID, opts ...ServerOption, ) (*Server, error) { srvr := NewServer(addr, topologyID, opts...) @@ -151,7 +150,7 @@ func ConnectServer( // NewServer creates a new server. The mongodb server at the address will be monitored // on an internal monitoring goroutine. -func NewServer(addr address.Address, topologyID primitive.ObjectID, opts ...ServerOption) *Server { +func NewServer(addr address.Address, topologyID bson.ObjectID, opts ...ServerOption) *Server { cfg := newServerConfig(opts...) globalCtx, globalCtxCancel := context.WithCancel(context.Background()) s := &Server{ @@ -329,7 +328,7 @@ func (s *Server) Connection(ctx context.Context) (*mnet.Connection, error) { // ProcessHandshakeError implements SDAM error handling for errors that occur before a connection // finishes handshaking. -func (s *Server) ProcessHandshakeError(err error, startingGenerationNumber uint64, serviceID *primitive.ObjectID) { +func (s *Server) ProcessHandshakeError(err error, startingGenerationNumber uint64, serviceID *bson.ObjectID) { // Ignore the error if the server is behind a load balancer but the service ID is unknown. This indicates that the // error happened when dialing the connection or during the MongoDB handshake, so we don't know the service ID to // use for clearing the pool. diff --git a/x/mongo/driver/topology/server_options.go b/x/mongo/driver/topology/server_options.go index 84229c4401..c02600e232 100644 --- a/x/mongo/driver/topology/server_options.go +++ b/x/mongo/driver/topology/server_options.go @@ -10,7 +10,6 @@ import ( "time" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsoncodec" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/logger" "go.mongodb.org/mongo-driver/x/mongo/driver" @@ -29,7 +28,7 @@ type serverConfig struct { heartbeatTimeout time.Duration serverMonitoringMode string serverMonitor *event.ServerMonitor - registry *bsoncodec.Registry + registry *bson.Registry monitoringDisabled bool serverAPI *driver.ServerAPIOptions loadBalanced bool @@ -178,7 +177,7 @@ func WithClock(fn func(clock *session.ClusterClock) *session.ClusterClock) Serve // WithRegistry configures the registry for the server to use when creating // cursors. -func WithRegistry(fn func(*bsoncodec.Registry) *bsoncodec.Registry) ServerOption { +func WithRegistry(fn func(*bson.Registry) *bson.Registry) ServerOption { return func(cfg *serverConfig) { cfg.registry = fn(cfg.registry) } diff --git a/x/mongo/driver/topology/server_test.go b/x/mongo/driver/topology/server_test.go index 1bf7aa8f1a..366fc83917 100644 --- a/x/mongo/driver/topology/server_test.go +++ b/x/mongo/driver/topology/server_test.go @@ -24,7 +24,7 @@ import ( "time" "github.com/google/go-cmp/cmp" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/eventtest" @@ -165,7 +165,7 @@ func TestServerHeartbeatTimeout(t *testing.T) { tpm := eventtest.NewTestPoolMonitor() server := NewServer( address.Address("localhost:27017"), - primitive.NewObjectID(), + bson.NewObjectID(), WithConnectionPoolMonitor(func(*event.PoolMonitor) *event.PoolMonitor { return tpm.PoolMonitor }), @@ -299,7 +299,7 @@ func TestServerConnectionTimeout(t *testing.T) { tpm := eventtest.NewTestPoolMonitor() server := NewServer( address.Address(l.Addr().String()), - primitive.NewObjectID(), + bson.NewObjectID(), WithConnectionPoolMonitor(func(*event.PoolMonitor) *event.PoolMonitor { return tpm.PoolMonitor }), @@ -380,7 +380,7 @@ func TestServer(t *testing.T) { var returnConnectionError bool s := NewServer( address.Address("localhost"), - primitive.NewObjectID(), + bson.NewObjectID(), WithConnectionOptions(func(connOpts ...ConnectionOption) []ConnectionOption { return append(connOpts, WithHandshaker(func(Handshaker) Handshaker { @@ -450,10 +450,10 @@ func TestServer(t *testing.T) { } t.Run("multiple connection initialization errors are processed correctly", func(t *testing.T) { - assertGenerationStats := func(t *testing.T, server *Server, serviceID primitive.ObjectID, wantGeneration, wantNumConns uint64) { + assertGenerationStats := func(t *testing.T, server *Server, serviceID bson.ObjectID, wantGeneration, wantNumConns uint64) { t.Helper() - getGeneration := func(serviceIDPtr *primitive.ObjectID) uint64 { + getGeneration := func(serviceIDPtr *bson.ObjectID) uint64 { generation, _ := server.pool.generation.getGeneration(serviceIDPtr) return generation } @@ -505,9 +505,9 @@ func TestServer(t *testing.T) { t.Run(tc.name, func(t *testing.T) { var returnConnectionError bool - var serviceID primitive.ObjectID + var serviceID bson.ObjectID if tc.loadBalanced { - serviceID = primitive.NewObjectID() + serviceID = bson.NewObjectID() } handshaker := &testHandshaker{ @@ -567,7 +567,7 @@ func TestServer(t *testing.T) { WithMaxConnecting(func(uint64) uint64 { return 1 }), } - server, err := ConnectServer(address.Address("localhost:27017"), nil, primitive.NewObjectID(), serverOpts...) + server, err := ConnectServer(address.Address("localhost:27017"), nil, bson.NewObjectID(), serverOpts...) assert.Nil(t, err, "ConnectServer error: %v", err) defer func() { _ = server.Disconnect(context.Background()) @@ -600,7 +600,7 @@ func TestServer(t *testing.T) { }) d := newdialer(&net.Dialer{}) s := NewServer(address.Address(addr.String()), - primitive.NewObjectID(), + bson.NewObjectID(), WithConnectionOptions(func(option ...ConnectionOption) []ConnectionOption { return []ConnectionOption{WithDialer(func(_ Dialer) Dialer { return d })} }), @@ -648,7 +648,7 @@ func TestServer(t *testing.T) { updated.Store(true) return desc } - s, err := ConnectServer(address.Address("localhost"), updateCallback, primitive.NewObjectID()) + s, err := ConnectServer(address.Address("localhost"), updateCallback, bson.NewObjectID()) require.NoError(t, err) s.updateDescription(description.Server{Addr: s.address}) require.True(t, updated.Load().(bool)) @@ -663,7 +663,7 @@ func TestServer(t *testing.T) { return append(connOpts, dialerOpt) }) - s := NewServer(address.Address("localhost:27017"), primitive.NewObjectID(), serverOpt) + s := NewServer(address.Address("localhost:27017"), bson.NewObjectID(), serverOpt) // do a heartbeat with a nil connection so a new one will be dialed _, err := s.check() @@ -727,7 +727,7 @@ func TestServer(t *testing.T) { WithServerMonitor(func(*event.ServerMonitor) *event.ServerMonitor { return sdam }), } - s := NewServer(address.Address("localhost:27017"), primitive.NewObjectID(), serverOpts...) + s := NewServer(address.Address("localhost:27017"), bson.NewObjectID(), serverOpts...) // set up heartbeat connection, which doesn't send events _, err := s.check() @@ -786,7 +786,7 @@ func TestServer(t *testing.T) { name := "test" s := NewServer(address.Address("localhost"), - primitive.NewObjectID(), + bson.NewObjectID(), WithServerAppName(func(string) string { return name })) require.Equal(t, name, s.cfg.appname, "expected appname to be: %v, got: %v", name, s.cfg.appname) }) @@ -795,7 +795,7 @@ func TestServer(t *testing.T) { s := NewServer( address.Address("localhost"), - primitive.NewObjectID(), + bson.NewObjectID(), WithConnectionOptions(func(connOpts ...ConnectionOption) []ConnectionOption { return append( connOpts, @@ -816,7 +816,7 @@ func TestServer(t *testing.T) { server, err := ConnectServer( address.Address("invalid"), nil, - primitive.NewObjectID(), + bson.NewObjectID(), withMonitoringDisabled(func(bool) bool { return true }), @@ -851,8 +851,8 @@ func TestServer(t *testing.T) { func TestServer_ProcessError(t *testing.T) { t.Parallel() - processID := primitive.NewObjectID() - newProcessID := primitive.NewObjectID() + processID := bson.NewObjectID() + newProcessID := bson.NewObjectID() testCases := []struct { name string @@ -1188,7 +1188,7 @@ func TestServer_ProcessError(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() - server := NewServer(address.Address(""), primitive.NewObjectID()) + server := NewServer(address.Address(""), bson.NewObjectID()) server.state = serverConnected err := server.pool.ready() require.Nil(t, err, "pool.ready() error: %v", err) @@ -1290,7 +1290,7 @@ func (p *processErrorTestConn) Description() description.Server { // kind, topology version process ID and counter, and last error. func newServerDescription( kind description.ServerKind, - processID primitive.ObjectID, + processID bson.ObjectID, counter int64, lastError error, ) description.Server { diff --git a/x/mongo/driver/topology/topology.go b/x/mongo/driver/topology/topology.go index 6525f365f1..a80c9653db 100644 --- a/x/mongo/driver/topology/topology.go +++ b/x/mongo/driver/topology/topology.go @@ -21,7 +21,7 @@ import ( "sync/atomic" "time" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/internal/logger" "go.mongodb.org/mongo-driver/internal/randutil" @@ -108,7 +108,7 @@ type Topology struct { serversClosed bool servers map[address.Address]*Server - id primitive.ObjectID + id bson.ObjectID } var ( @@ -147,7 +147,7 @@ func New(cfg *Config) (*Topology, error) { subscribers: make(map[uint64]chan description.Topology), servers: make(map[address.Address]*Server), dnsResolver: dns.DefaultResolver, - id: primitive.NewObjectID(), + id: bson.NewObjectID(), } t.desc.Store(description.Topology{}) t.updateCallback = func(desc description.Server) description.Server { diff --git a/x/mongo/driver/topology/topology_test.go b/x/mongo/driver/topology/topology_test.go index a9c54be034..aae357bc3b 100644 --- a/x/mongo/driver/topology/topology_test.go +++ b/x/mongo/driver/topology/topology_test.go @@ -17,7 +17,7 @@ import ( "testing" "time" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/internal/require" "go.mongodb.org/mongo-driver/internal/spectest" @@ -981,7 +981,7 @@ func runInWindowTest(t *testing.T, directory string, filename string) { for _, testDesc := range test.TopologyDescription.Servers { server := NewServer( address.Address(testDesc.Address), - primitive.NilObjectID, + bson.NilObjectID, withMonitoringDisabled(func(bool) bool { return true })) servers[testDesc.Address] = server