Skip to content

Commit

Permalink
check for nil pointers before calling IsZero. (#67)
Browse files Browse the repository at this point in the history
* check for nil pointers before calling IsZero.
This avoids panics when a nil pointer to a type that implements zeroable interface is passed to IsZero

Signed-off-by: Michał Szczygieł <1153719+mszczygiel@users.noreply.github.com>

* move tests for nil zeroable to TestIsZero

Signed-off-by: Michał Szczygieł <1153719+mszczygiel@users.noreply.github.com>

* slightly cleanup nil handling

Signed-off-by: Michał Szczygieł <1153719+mszczygiel@users.noreply.github.com>

---------

Signed-off-by: Michał Szczygieł <1153719+mszczygiel@users.noreply.github.com>
  • Loading branch information
mszczygiel committed Mar 28, 2023
1 parent 0579829 commit f28dd7a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
16 changes: 12 additions & 4 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -341,12 +341,21 @@ type zeroable interface {
// IsZero returns true when the value passed into the function is a zero value.
// This allows for safer checking of interface values.
func IsZero(data interface{}) bool {
v := reflect.ValueOf(data)
// check for nil data
switch v.Kind() {
case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
if v.IsNil() {
return true
}
}

// check for things that have an IsZero method instead
if vv, ok := data.(zeroable); ok {
return vv.IsZero()
}

// continue with slightly more complex reflection
v := reflect.ValueOf(data)
switch v.Kind() {
case reflect.String:
return v.Len() == 0
Expand All @@ -358,14 +367,13 @@ func IsZero(data interface{}) bool {
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
return v.IsNil()
case reflect.Struct, reflect.Array:
return reflect.DeepEqual(data, reflect.Zero(v.Type()).Interface())
case reflect.Invalid:
return true
default:
return false
}
return false
}

// AddInitialisms add additional initialisms
Expand Down
11 changes: 11 additions & 0 deletions util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,14 @@ type ZeroesWithTime struct {
Time time.Time
}

type dummyZeroable struct {
zero bool
}

func (d dummyZeroable) IsZero() bool {
return d.zero
}

func TestIsZero(t *testing.T) {
var strs [5]string
var strss []string
Expand Down Expand Up @@ -384,6 +392,9 @@ func TestIsZero(t *testing.T) {
{[...]string{"hello"}, false},
{[]string(nil), true},
{[]string{"a"}, false},
{&dummyZeroable{true}, true},
{&dummyZeroable{false}, false},
{(*dummyZeroable)(nil), true},
}

for _, it := range data {
Expand Down

0 comments on commit f28dd7a

Please sign in to comment.