[#140] sdk: Refactor reference types

Refactor v2-compatible reference types to be wrappers over corresponding
types from v2.

Signed-off-by: Leonard Lyubich <leonard@nspcc.ru>
This commit is contained in:
Leonard Lyubich 2020-09-10 12:57:29 +03:00 committed by Stanislav Bogatyrev
parent 2026473733
commit 524280a5e8
10 changed files with 73 additions and 215 deletions

View file

@ -4,44 +4,29 @@ 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
// ID represents v2-compatible container identifier.
type ID refs.ContainerID
// NewIDFromV2 wraps v2 ContainerID message to ID.
func NewIDFromV2(idV2 *refs.ContainerID) *ID {
return (*ID)(idV2)
}
// NewID creates and initializes blank ID.
//
// Works similar to NewIDFromV2(new(ContainerID)).
func NewID() *ID {
return NewIDFromV2(new(refs.ContainerID))
}
// SetSHA256 sets container identifier value to SHA256 checksum.
func (id *ID) SetSHA256(v [sha256.Size]byte) {
if id != nil {
id.val = v[:]
}
(*refs.ContainerID)(id).SetValue(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) {
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
return (*refs.ContainerID)(id)
}

View file

@ -9,7 +9,7 @@ import (
)
func TestIDV2_0(t *testing.T) {
cid := new(ID)
cid := NewID()
checksum := [sha256.Size]byte{}
@ -20,8 +20,5 @@ func TestIDV2_0(t *testing.T) {
cidV2 := cid.ToV2()
cid2, err := IDFromV2(cidV2)
require.NoError(t, err)
require.Equal(t, cid, cid2)
require.Equal(t, checksum[:], cidV2.GetValue())
}