[#230] pkg: Implement string encode/decode methods on Checksum

Signed-off-by: Leonard Lyubich <leonard@nspcc.ru>
This commit is contained in:
Leonard Lyubich 2020-12-17 18:25:17 +03:00
parent 6861de042b
commit 0f04087543
2 changed files with 42 additions and 0 deletions

View file

@ -3,8 +3,10 @@ package pkg
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
"github.com/pkg/errors"
)
// Checksum represents v2-compatible checksum.
@ -109,3 +111,35 @@ func (c *Checksum) UnmarshalJSON(data []byte) error {
return (*refs.Checksum)(c).
UnmarshalJSON(data)
}
func (c *Checksum) String() string {
return hex.EncodeToString(
(*refs.Checksum)(c).
GetSum(),
)
}
// Parse parses Checksum from its string representation.
func (c *Checksum) Parse(s string) error {
data, err := hex.DecodeString(s)
if err != nil {
return err
}
var typ refs.ChecksumType
switch ln := len(data); ln {
default:
return errors.Errorf("unsupported checksum length %d", ln)
case sha256.Size:
typ = refs.SHA256
case 64:
typ = refs.TillichZemor
}
cV2 := (*refs.Checksum)(c)
cV2.SetType(typ)
cV2.SetSum(data)
return nil
}

View file

@ -90,4 +90,12 @@ func TestChecksumEncoding(t *testing.T) {
require.Equal(t, cs, cs2)
})
t.Run("string", func(t *testing.T) {
cs2 := NewChecksum()
require.NoError(t, cs2.Parse(cs.String()))
require.Equal(t, cs, cs2)
})
}