Skip to content

Commit

Permalink
GODRIVER-3436 Avoid initializing null data given custom decoder (#1902)
Browse files Browse the repository at this point in the history
  • Loading branch information
prestonvasquez authored Dec 6, 2024
1 parent c3448e6 commit 6c22d67
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
6 changes: 6 additions & 0 deletions bson/bsoncodec/default_value_decoders.go
Original file line number Diff line number Diff line change
Expand Up @@ -1521,6 +1521,12 @@ func (dvd DefaultValueDecoders) ValueUnmarshalerDecodeValue(_ DecodeContext, vr
return ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val}
}

if vr.Type() == bsontype.Null {
val.Set(reflect.Zero(val.Type()))

return vr.ReadNull()
}

if val.Kind() == reflect.Ptr && val.IsNil() {
if !val.CanSet() {
return ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val}
Expand Down
19 changes: 19 additions & 0 deletions bson/unmarshaling_cases_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,25 @@ type unmarshalerNonPtrStruct struct {

type myInt64 int64

var _ ValueUnmarshaler = (*myInt64)(nil)

func (mi *myInt64) UnmarshalBSONValue(t bsontype.Type, bytes []byte) error {
if len(bytes) == 0 {
return nil
}

if t == bsontype.Int64 {
i, err := bsonrw.NewBSONValueReader(bsontype.Int64, bytes).ReadInt64()
if err != nil {
return err
}

*mi = myInt64(i)
}

return nil
}

func (mi *myInt64) UnmarshalBSON(bytes []byte) error {
if len(bytes) == 0 {
return nil
Expand Down

0 comments on commit 6c22d67

Please sign in to comment.