diff --git a/pkg/checksum.go b/pkg/checksum.go index 72087a71..c03071f6 100644 --- a/pkg/checksum.go +++ b/pkg/checksum.go @@ -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 +} diff --git a/pkg/checksum_test.go b/pkg/checksum_test.go index 41cc9d34..e636f403 100644 --- a/pkg/checksum_test.go +++ b/pkg/checksum_test.go @@ -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) + }) }