Skip to content

Commit

Permalink
GODRIVER-1919 Support decoding ObjectIDs from hex strings in BSON (#610)
Browse files Browse the repository at this point in the history
  • Loading branch information
glossd authored Mar 17, 2021
1 parent b7f9264 commit 4ccd545
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
4 changes: 4 additions & 0 deletions bson/bsoncodec/default_value_decoders.go
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,7 @@ func (dvd DefaultValueDecoders) UndefinedDecodeValue(dc DecodeContext, vr bsonrw
return nil
}

// Accept both 12-byte string and pretty-printed 24-byte hex string formats.
func (dvd DefaultValueDecoders) objectIDDecodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) {
if t != tOID {
return emptyValue, ValueDecoderError{
Expand All @@ -740,6 +741,9 @@ func (dvd DefaultValueDecoders) objectIDDecodeType(dc DecodeContext, vr bsonrw.V
if err != nil {
return emptyValue, err
}
if oid, err = primitive.ObjectIDFromHex(str); err == nil {
break
}
if len(str) != 12 {
return emptyValue, fmt.Errorf("an ObjectID string must be exactly 12 bytes long (got %v)", len(str))
}
Expand Down
11 changes: 11 additions & 0 deletions bson/bsoncodec/default_value_decoders_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1118,6 +1118,17 @@ func TestDefaultValueDecoders(t *testing.T) {
bsonrwtest.ReadString,
nil,
},
{
"success/string-hex",
primitive.ObjectID{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62},
nil,
&bsonrwtest.ValueReaderWriter{
BSONType: bsontype.String,
Return: "303132333435363738396162",
},
bsonrwtest.ReadString,
nil,
},
{
"decode null",
primitive.ObjectID{},
Expand Down

0 comments on commit 4ccd545

Please sign in to comment.