From aa20a9518118d8aed2dcab8f1c6dae711c4eb569 Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Tue, 3 Dec 2019 16:17:04 +0300 Subject: [PATCH] util: add Uint256DecodeStringBE() --- pkg/util/uint256.go | 15 +++++++++++++++ pkg/util/uint256_test.go | 10 ++++++++++ 2 files changed, 25 insertions(+) diff --git a/pkg/util/uint256.go b/pkg/util/uint256.go index 8a859b42b..10dcfe0a5 100644 --- a/pkg/util/uint256.go +++ b/pkg/util/uint256.go @@ -28,6 +28,21 @@ func Uint256DecodeStringLE(s string) (u Uint256, err error) { return Uint256DecodeBytesLE(b) } +// Uint256DecodeStringBE attempts to decode the given string (in BE representation) +// into an Uint256. +func Uint256DecodeStringBE(s string) (u Uint256, err error) { + if len(s) != Uint256Size*2 { + return u, fmt.Errorf("expected string size of %d got %d", Uint256Size*2, len(s)) + } + + b, err := hex.DecodeString(s) + if err != nil { + return u, err + } + + return Uint256DecodeBytesBE(b) +} + // Uint256DecodeBytesBE attempts to decode the given string (in BE representation) into an Uint256. func Uint256DecodeBytesBE(b []byte) (u Uint256, err error) { if len(b) != Uint256Size { diff --git a/pkg/util/uint256_test.go b/pkg/util/uint256_test.go index 4d5ba4178..9fc8bf1c0 100644 --- a/pkg/util/uint256_test.go +++ b/pkg/util/uint256_test.go @@ -37,6 +37,10 @@ func TestUint256DecodeString(t *testing.T) { require.NoError(t, err) assert.Equal(t, hexStr, val.StringLE()) + valBE, err := Uint256DecodeStringBE(hexStr) + require.NoError(t, err) + assert.Equal(t, val, valBE.Reverse()) + bs, err := hex.DecodeString(hexStr) require.NoError(t, err) @@ -48,9 +52,15 @@ func TestUint256DecodeString(t *testing.T) { _, err = Uint256DecodeStringLE(hexStr[1:]) assert.Error(t, err) + _, err = Uint256DecodeStringBE(hexStr[1:]) + assert.Error(t, err) + hexStr = "zzz7308fa0ab18155bccfc08485468c112409ea5064595699e98c545f245f32d" _, err = Uint256DecodeStringLE(hexStr) assert.Error(t, err) + + _, err = Uint256DecodeStringBE(hexStr) + assert.Error(t, err) } func TestUint256DecodeBytes(t *testing.T) {