From 0f040875433d51b28bb78ede9e9690a4f869f0fb Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Thu, 17 Dec 2020 18:25:17 +0300 Subject: [PATCH] [#230] pkg: Implement string encode/decode methods on Checksum Signed-off-by: Leonard Lyubich --- pkg/checksum.go | 34 ++++++++++++++++++++++++++++++++++ pkg/checksum_test.go | 8 ++++++++ 2 files changed, 42 insertions(+) diff --git a/pkg/checksum.go b/pkg/checksum.go index 72087a7..c03071f 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 41cc9d3..e636f40 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) + }) }