diff --git a/pkg/container/id.go b/pkg/container/id.go new file mode 100644 index 00000000..5bccc073 --- /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 00000000..245f433b --- /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) +}