From a65db086085949eed2f6d6d5337220e221f733a9 Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Tue, 1 Sep 2020 16:11:38 +0300 Subject: [PATCH] [#130] sdk: Define object identifier type Signed-off-by: Leonard Lyubich --- pkg/object/id.go | 54 +++++++++++++++++++++++++++++++++++++++++++ pkg/object/id_test.go | 27 ++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 pkg/object/id.go create mode 100644 pkg/object/id_test.go diff --git a/pkg/object/id.go b/pkg/object/id.go new file mode 100644 index 0000000..437f2d4 --- /dev/null +++ b/pkg/object/id.go @@ -0,0 +1,54 @@ +package object + +import ( + "crypto/sha256" + + "github.com/nspcc-dev/neofs-api-go/v2/refs" + "github.com/pkg/errors" +) + +// ID represents object identifier that +// supports different type of values. +type ID struct { + val []byte +} + +// SetSHA256 sets object identifier value to SHA256 checksum. +func (id *ID) SetSHA256(v [sha256.Size]byte) { + if id != nil { + id.val = v[:] + } +} + +// ToV2 converts ID to v2 ObjectID message. +func (id *ID) ToV2() *refs.ObjectID { + if id != nil { + idV2 := new(refs.ObjectID) + idV2.SetValue(id.val) + + return idV2 + } + + return nil +} + +// IDFromV2 converts v2 ObjectID message to ID. +// +// Returns an error if the format of the identifier +// in the message is broken. +func IDFromV2(idV2 *refs.ObjectID) (*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: invalid length %d", + idV2, (*ID)(nil), ln, + ) + } + + return &ID{ + val: val, + }, nil +} diff --git a/pkg/object/id_test.go b/pkg/object/id_test.go new file mode 100644 index 0000000..bbf29cf --- /dev/null +++ b/pkg/object/id_test.go @@ -0,0 +1,27 @@ +package object + +import ( + "crypto/rand" + "crypto/sha256" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestIDV2(t *testing.T) { + id := new(ID) + + checksum := [sha256.Size]byte{} + + _, err := rand.Read(checksum[:]) + require.NoError(t, err) + + id.SetSHA256(checksum) + + idV2 := id.ToV2() + + id2, err := IDFromV2(idV2) + require.NoError(t, err) + + require.Equal(t, id, id2) +}