Skip to content

Commit

Permalink
valueIsScalar improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
yazgazan committed May 9, 2019
1 parent fb1c87b commit e0c0b8d
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 9 deletions.
25 changes: 16 additions & 9 deletions diff/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ func Diff(lhs, rhs interface{}, opts ...ConfigOpt) (Differ, error) {
}

func diff(c config, lhs, rhs interface{}, visited *visited) (Differ, error) {
lhsVal := reflect.ValueOf(lhs)
rhsVal := reflect.ValueOf(rhs)
lhsVal, lhs := indirectValueOf(lhs)
rhsVal, rhs := indirectValueOf(rhs)

if d, ok := nilCheck(lhs, rhs); ok {
return d, nil
Expand All @@ -56,7 +56,7 @@ func diff(c config, lhs, rhs interface{}, visited *visited) (Differ, error) {
return types{lhs, rhs}, ErrCyclic
}

if valuesAreScalar(lhsVal, rhsVal) {
if valueIsScalar(lhsVal) && valueIsScalar(rhsVal) {
return scalar{lhs, rhs}, nil
}
if lhsVal.Kind() != rhsVal.Kind() {
Expand All @@ -75,15 +75,22 @@ func diff(c config, lhs, rhs interface{}, visited *visited) (Differ, error) {
return types{lhs, rhs}, &ErrUnsupported{lhsVal.Type(), rhsVal.Type()}
}

func valuesAreScalar(lhs, rhs reflect.Value) bool {
if lhs.Kind() == reflect.Struct || rhs.Kind() == reflect.Struct {
return false
func indirectValueOf(i interface{}) (reflect.Value, interface{}) {
v := reflect.Indirect(reflect.ValueOf(i))
if !v.IsValid() || !v.CanInterface() {
return reflect.ValueOf(i), i
}
if lhs.Kind() == reflect.Array || rhs.Kind() == reflect.Array {

return v, v.Interface()
}

func valueIsScalar(v reflect.Value) bool {
switch v.Kind() {
default:
return v.Type().Comparable()
case reflect.Struct, reflect.Array, reflect.Ptr, reflect.Chan:
return false
}

return lhs.Type().Comparable() && rhs.Type().Comparable()
}

func nilCheck(lhs, rhs interface{}) (Differ, bool) {
Expand Down
30 changes: 30 additions & 0 deletions diff/diff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package diff

import (
"fmt"
"reflect"
"strings"
"testing"
)
Expand Down Expand Up @@ -1128,3 +1129,32 @@ func TestIsSlice(t *testing.T) {
t.Error("IsSlice(Diff(map{...}, map{...})) = false, expected true")
}
}

func TestValueIsScalar(t *testing.T) {
for _, test := range []struct {
In interface{}
Expected bool
}{
{int(42), true},
{int8(23), true},
{"foo", true},
{true, true},
{float32(1.2), true},
{complex(5, -3), true},

{[]byte("foo"), false},
{struct{}{}, false},
{&struct{}{}, false},
{[]int{1, 2, 3}, false},
{[3]int{1, 2, 3}, false},
{map[string]int{"foo": 22}, false},
{func() {}, false},
{make(chan struct{}), false},
} {
v := reflect.ValueOf(test.In)
got := valueIsScalar(v)
if got != test.Expected {
t.Errorf("valueIsScalar(%T) = %v, expected %v", test.In, got, test.Expected)
}
}
}

0 comments on commit e0c0b8d

Please # to comment.