sdk: Define container identifier type

Signed-off-by: Leonard Lyubich <leonard@nspcc.ru>
This commit is contained in:
Leonard Lyubich 2020-08-28 10:27:41 +03:00 committed by Stanislav Bogatyrev
parent 7f4544ede0
commit 8df69c4042
2 changed files with 78 additions and 0 deletions

51
pkg/container/id.go Normal file
View file

@ -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
}

27
pkg/container/id_test.go Normal file
View file

@ -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)
}