Skip to content

Commit

Permalink
Merge pull request #307 from wenerme/unwrap
Browse files Browse the repository at this point in the history
unwrap type to detect nil ptr prevent panic fix #306
  • Loading branch information
vmihailenco authored May 28, 2021
2 parents 4e8027a + 52b4cd1 commit da62e6f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
16 changes: 16 additions & 0 deletions msgpack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -459,3 +459,19 @@ func ExampleMarshal_ignore_simple_zero_structs_when_tagged_with_omitempty() {
// Output: msgpack_test.T{I:msgpack_test.NullInt{Valid:false, Int:0}, J:msgpack_test.NullInt{Valid:true, Int:0}, S:msgpack_test.Secretive{Visible:false, hidden:false}}
// msgpack_test.T{I:msgpack_test.NullInt{Valid:true, Int:42}, J:msgpack_test.NullInt{Valid:true, Int:0}, S:msgpack_test.Secretive{Visible:false, hidden:false}}
}

type Value interface{}
type Wrapper struct {
Value Value `msgpack:"v,omitempty"`
}

func TestEncodeWrappedValue(t *testing.T) {
var v Value
v = (*time.Time)(nil)
c := &Wrapper{
Value: v,
}
var buf bytes.Buffer
require.Nil(t, msgpack.NewEncoder(&buf).Encode(v))
require.Nil(t, msgpack.NewEncoder(&buf).Encode(c))
}
9 changes: 7 additions & 2 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,13 @@ type isZeroer interface {
}

func isEmptyValue(v reflect.Value) bool {
// unwrap to detect nil ptr
for v.Kind() == reflect.Interface || v.Kind() == reflect.Ptr {
if v.IsNil() {
return true
}
v = v.Elem()
}
if z, ok := v.Interface().(isZeroer); ok {
return nilable(v.Kind()) && v.IsNil() || z.IsZero()
}
Expand All @@ -332,8 +339,6 @@ func isEmptyValue(v reflect.Value) bool {
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
}
return false
}
Expand Down

0 comments on commit da62e6f

Please sign in to comment.