Skip to content

Commit

Permalink
support map (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
seiyab authored May 1, 2024
1 parent 0f6e443 commit 688ec97
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
22 changes: 21 additions & 1 deletion deepequal.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ var eqs = map[reflect.Kind]func(v1, v2 reflect.Value, nx next) bool{
reflect.Interface: interfaceEq,
reflect.Pointer: pointerEq,
reflect.Struct: structEq,
reflect.Map: todo,
reflect.Map: mapEq,
reflect.Func: todo,
reflect.Int: intEq,
reflect.Int8: intEq,
Expand Down Expand Up @@ -175,6 +175,26 @@ func structEq(v1, v2 reflect.Value, nx next) bool {
return true
}

func mapEq(v1, v2 reflect.Value, nx next) bool {
if v1.IsNil() != v2.IsNil() {
return false
}
if v1.Len() != v2.Len() {
return false
}
if v1.UnsafePointer() == v2.UnsafePointer() {
return true
}
for _, k := range v1.MapKeys() {
val1 := v1.MapIndex(k)
val2 := v2.MapIndex(k)
if !val1.IsValid() || !val2.IsValid() || !nx(val1, val2) {
return false
}
}
return true
}

func intEq(v1, v2 reflect.Value, _ next) bool { return v1.Int() == v2.Int() }
func uintEq(v1, v2 reflect.Value, _ next) bool { return v1.Uint() == v2.Uint() }
func stringEq(v1, v2 reflect.Value, _ next) bool { return v1.String() == v2.String() }
Expand Down
31 changes: 31 additions & 0 deletions teq_default_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ func TestEqual(t *testing.T) {
{"primitives", primitives()},
{"structs", structs()},
{"slices", slices()},
{"maps", maps()},
{"recursions", recursions()},
}

Expand Down Expand Up @@ -111,6 +112,36 @@ func slices() []test {
}
}

func maps() []test {
return []test{
{map[string]int{"a": 1}, map[string]int{"a": 1}, nil, false},
{map[string]int{"a": 1}, map[string]int{"a": 2}, []string{"expected map[a:1], got map[a:2]"}, false},
{map[string]int{"a": 1}, map[string]int{"b": 1}, []string{"expected map[a:1], got map[b:1]"}, false},
{map[string]int{"a": 0}, map[string]int{}, []string{"expected map[a:0], got map[]"}, false},

{
map[int]map[string]int{
1: {"abc": 1},
},
map[int]map[string]int{
1: {"abc": 1},
},
nil,
false,
},
{
map[int]map[string]int{
1: {"abc": 1},
},
map[int]map[string]int{
1: {"abc": 2},
},
[]string{"expected map[1:map[abc:1]], got map[1:map[abc:2]]"},
false,
},
}
}

func recursions() []test {
type privateRecursiveStruct struct {
i int
Expand Down

0 comments on commit 688ec97

Please sign in to comment.