Skip to content

Commit 6c22d67

Browse files
GODRIVER-3436 Avoid initializing null data given custom decoder (#1902)
1 parent c3448e6 commit 6c22d67

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

bson/bsoncodec/default_value_decoders.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1521,6 +1521,12 @@ func (dvd DefaultValueDecoders) ValueUnmarshalerDecodeValue(_ DecodeContext, vr
15211521
return ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val}
15221522
}
15231523

1524+
if vr.Type() == bsontype.Null {
1525+
val.Set(reflect.Zero(val.Type()))
1526+
1527+
return vr.ReadNull()
1528+
}
1529+
15241530
if val.Kind() == reflect.Ptr && val.IsNil() {
15251531
if !val.CanSet() {
15261532
return ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val}

bson/unmarshaling_cases_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,25 @@ type unmarshalerNonPtrStruct struct {
199199

200200
type myInt64 int64
201201

202+
var _ ValueUnmarshaler = (*myInt64)(nil)
203+
204+
func (mi *myInt64) UnmarshalBSONValue(t bsontype.Type, bytes []byte) error {
205+
if len(bytes) == 0 {
206+
return nil
207+
}
208+
209+
if t == bsontype.Int64 {
210+
i, err := bsonrw.NewBSONValueReader(bsontype.Int64, bytes).ReadInt64()
211+
if err != nil {
212+
return err
213+
}
214+
215+
*mi = myInt64(i)
216+
}
217+
218+
return nil
219+
}
220+
202221
func (mi *myInt64) UnmarshalBSON(bytes []byte) error {
203222
if len(bytes) == 0 {
204223
return nil

0 commit comments

Comments
 (0)