From 8c33d363760b747e2017642ae28fb3db39441ded Mon Sep 17 00:00:00 2001 From: seiya <20365512+seiyab@users.noreply.github.com> Date: Tue, 30 Apr 2024 09:42:30 +0900 Subject: [PATCH] support map --- deepequal.go | 22 +++++++++++++++++++++- teq_default_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/deepequal.go b/deepequal.go index 9e1bec5..bbe3c68 100644 --- a/deepequal.go +++ b/deepequal.go @@ -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, @@ -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() } diff --git a/teq_default_test.go b/teq_default_test.go index 26d8ab7..01dd018 100644 --- a/teq_default_test.go +++ b/teq_default_test.go @@ -26,6 +26,7 @@ func TestEqual(t *testing.T) { {"primitives", primitives()}, {"structs", structs()}, {"slices", slices()}, + {"maps", maps()}, {"recursions", recursions()}, } @@ -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