From 8df69c40420208abde45c4782f8cab2875b489f3 Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Fri, 28 Aug 2020 10:27:41 +0300 Subject: [PATCH] sdk: Define container identifier type Signed-off-by: Leonard Lyubich --- pkg/container/id.go | 51 ++++++++++++++++++++++++++++++++++++++++ pkg/container/id_test.go | 27 +++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 pkg/container/id.go create mode 100644 pkg/container/id_test.go diff --git a/pkg/container/id.go b/pkg/container/id.go new file mode 100644 index 0000000..5bccc07 --- /dev/null +++ b/pkg/container/id.go @@ -0,0 +1,51 @@ +package container + +import ( + "crypto/sha256" + + "github.com/nspcc-dev/neofs-api-go/v2/refs" + "github.com/pkg/errors" +) + +// ID represents container identifier +// that supports different type of values. +type ID struct { + val []byte +} + +// SetSHA256 sets container identifier value to SHA256 checksum. +func (id *ID) SetSHA256(v [sha256.Size]byte) { + if id != nil { + id.val = v[:] + } +} + +// ToV2 returns the v2 container ID message. +func (id *ID) ToV2() *refs.ContainerID { + if id != nil { + idV2 := new(refs.ContainerID) + idV2.SetValue(id.val) + + return idV2 + } + + return nil +} + +func IDFromV2(idV2 *refs.ContainerID) (*ID, error) { + if idV2 == nil { + return nil, nil + } + + val := idV2.GetValue() + if ln := len(val); ln != sha256.Size { + return nil, errors.Errorf( + "could not convert %T to %T: expected length %d, received %d", + idV2, (*ID)(nil), sha256.Size, ln, + ) + } + + return &ID{ + val: val, + }, nil +} diff --git a/pkg/container/id_test.go b/pkg/container/id_test.go new file mode 100644 index 0000000..245f433 --- /dev/null +++ b/pkg/container/id_test.go @@ -0,0 +1,27 @@ +package container + +import ( + "crypto/rand" + "crypto/sha256" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestIDV2_0(t *testing.T) { + cid := new(ID) + + checksum := [sha256.Size]byte{} + + _, err := rand.Read(checksum[:]) + require.NoError(t, err) + + cid.SetSHA256(checksum) + + cidV2 := cid.ToV2() + + cid2, err := IDFromV2(cidV2) + require.NoError(t, err) + + require.Equal(t, cid, cid2) +}