From 5fe5af5bf9700f6b9d17a5ea2044a9e5345f23cc Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Fri, 28 May 2021 10:25:30 +0300 Subject: [PATCH] [#283] pkg/owner: Implement Equal method of ID type Implement `owner.ID.Equal` method which defines a comparison relationship between two identifiers. Signed-off-by: Leonard Lyubich --- pkg/owner/id.go | 11 +++++++++++ pkg/owner/id_test.go | 22 +++++++++++++++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/pkg/owner/id.go b/pkg/owner/id.go index ea8f5fc..2743b73 100644 --- a/pkg/owner/id.go +++ b/pkg/owner/id.go @@ -1,6 +1,7 @@ package owner import ( + "bytes" "errors" "fmt" @@ -40,6 +41,16 @@ func (id *ID) String() string { return base58.Encode((*refs.OwnerID)(id).GetValue()) } +// Equal defines a comparison relation on ID's. +// +// ID's are equal if they have the same binary representation. +func (id *ID) Equal(id2 *ID) bool { + return bytes.Equal( + (*refs.ObjectID)(id).GetValue(), + (*refs.ObjectID)(id2).GetValue(), + ) +} + func ScriptHashBE(id fmt.Stringer) ([]byte, error) { addr, err := address.StringToUint160(id.String()) if err != nil { diff --git a/pkg/owner/id_test.go b/pkg/owner/id_test.go index 49816bf..c6d7bc2 100644 --- a/pkg/owner/id_test.go +++ b/pkg/owner/id_test.go @@ -1,4 +1,4 @@ -package owner +package owner_test import ( "crypto/rand" @@ -6,6 +6,8 @@ import ( "testing" "github.com/mr-tron/base58" + . "github.com/nspcc-dev/neofs-api-go/pkg/owner" + ownertest "github.com/nspcc-dev/neofs-api-go/pkg/owner/test" "github.com/nspcc-dev/neofs-crypto/test" "github.com/stretchr/testify/require" ) @@ -93,3 +95,21 @@ func TestIDEncoding(t *testing.T) { require.Equal(t, id, a2) }) } + +func TestID_Equal(t *testing.T) { + var ( + data1 = []byte{1, 2, 3} + data2 = data1 + data3 = append(data1, 255) + ) + + id1 := ownertest.GenerateFromBytes(data1) + + require.True(t, id1.Equal( + ownertest.GenerateFromBytes(data2), + )) + + require.False(t, id1.Equal( + ownertest.GenerateFromBytes(data3), + )) +}