Skip to content

Commit d5e11aa

Browse files
glossdBenjamin Rewis
authored andcommitted
GODRIVER-1919 Support decoding ObjectIDs from hex strings in BSON (#610)
1 parent e0ed6d6 commit d5e11aa

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

bson/bsoncodec/default_value_decoders.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -718,6 +718,7 @@ func (dvd DefaultValueDecoders) UndefinedDecodeValue(dc DecodeContext, vr bsonrw
718718
return nil
719719
}
720720

721+
// Accept both 12-byte string and pretty-printed 24-byte hex string formats.
721722
func (dvd DefaultValueDecoders) objectIDDecodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) {
722723
if t != tOID {
723724
return emptyValue, ValueDecoderError{
@@ -740,6 +741,9 @@ func (dvd DefaultValueDecoders) objectIDDecodeType(dc DecodeContext, vr bsonrw.V
740741
if err != nil {
741742
return emptyValue, err
742743
}
744+
if oid, err = primitive.ObjectIDFromHex(str); err == nil {
745+
break
746+
}
743747
if len(str) != 12 {
744748
return emptyValue, fmt.Errorf("an ObjectID string must be exactly 12 bytes long (got %v)", len(str))
745749
}

bson/bsoncodec/default_value_decoders_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1118,6 +1118,17 @@ func TestDefaultValueDecoders(t *testing.T) {
11181118
bsonrwtest.ReadString,
11191119
nil,
11201120
},
1121+
{
1122+
"success/string-hex",
1123+
primitive.ObjectID{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62},
1124+
nil,
1125+
&bsonrwtest.ValueReaderWriter{
1126+
BSONType: bsontype.String,
1127+
Return: "303132333435363738396162",
1128+
},
1129+
bsonrwtest.ReadString,
1130+
nil,
1131+
},
11211132
{
11221133
"decode null",
11231134
primitive.ObjectID{},

0 commit comments

Comments
 (0)