From 7cd7f340e2cac31e7ea312dbadc83f6d71c15d04 Mon Sep 17 00:00:00 2001 From: Cristian Angelini Date: Tue, 14 Nov 2017 13:33:52 +0100 Subject: [PATCH] Fixes slices equality, when slices are extracted from the same array --- deep.go | 7 +++--- deep_test.go | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 3 deletions(-) diff --git a/deep.go b/deep.go index 2fd634d..c7eceb0 100644 --- a/deep.go +++ b/deep.go @@ -257,12 +257,13 @@ func (c *cmp) equals(a, b reflect.Value, level int) { return } - if a.Pointer() == b.Pointer() { + aLen := a.Len() + bLen := b.Len() + + if a.Pointer() == b.Pointer() && aLen == bLen { return } - aLen := a.Len() - bLen := b.Len() n := aLen if bLen > aLen { n = bLen diff --git a/deep_test.go b/deep_test.go index 9bd54e8..78ed6cf 100644 --- a/deep_test.go +++ b/deep_test.go @@ -539,6 +539,77 @@ func TestSlice(t *testing.T) { } } +func TestSiblingSlices(t *testing.T) { + father := []int{1, 2, 3, 4} + a := father[0:3] + b := father[0:3] + + diff := deep.Equal(a, b) + if len(diff) > 0 { + t.Error("should be equal:", diff) + } + diff = deep.Equal(b, a) + if len(diff) > 0 { + t.Error("should be equal:", diff) + } + + a = father[0:3] + b = father[0:2] + diff = deep.Equal(a, b) + if diff == nil { + t.Fatal("no diff") + } + if len(diff) != 1 { + t.Error("too many diff:", diff) + } + if diff[0] != "slice[2]: 3 != " { + t.Error("wrong diff:", diff[0]) + } + + a = father[0:2] + b = father[0:3] + + diff = deep.Equal(a, b) + if diff == nil { + t.Fatal("no diff") + } + if len(diff) != 1 { + t.Error("too many diff:", diff) + } + if diff[0] != "slice[2]: != 3" { + t.Error("wrong diff:", diff[0]) + } + + a = father[0:2] + b = father[2:4] + + diff = deep.Equal(a, b) + if diff == nil { + t.Fatal("no diff") + } + if len(diff) != 2 { + t.Error("too many diff:", diff) + } + if diff[0] != "slice[0]: 1 != 3" { + t.Error("wrong diff:", diff[0]) + } + if diff[1] != "slice[1]: 2 != 4" { + t.Error("wrong diff:", diff[1]) + } + + a = father[0:0] + b = father[1:1] + + diff = deep.Equal(a, b) + if len(diff) > 0 { + t.Error("should be equal:", diff) + } + diff = deep.Equal(b, a) + if len(diff) > 0 { + t.Error("should be equal:", diff) + } +} + func TestPointer(t *testing.T) { type T struct { i int