From 1ebeff7f6f3dea118e7027a1e10d5b13ba222b06 Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Thu, 5 Oct 2023 13:53:12 +0300 Subject: [PATCH] [#42] common: Add routines for fixed-width uint64 marshaling Signed-off-by: Evgenii Stratonikov --- common/storage.go | 16 ++++++++++ tests/common_test.go | 61 +++++++++++++++++++++++++++++++++++++++ tests/testdata/config.yml | 2 ++ tests/testdata/encode.go | 17 +++++++++++ 4 files changed, 96 insertions(+) create mode 100644 tests/common_test.go create mode 100644 tests/testdata/config.yml create mode 100644 tests/testdata/encode.go diff --git a/common/storage.go b/common/storage.go index 3b9e494..afa4e7b 100644 --- a/common/storage.go +++ b/common/storage.go @@ -1,6 +1,7 @@ package common import ( + "github.com/nspcc-dev/neo-go/pkg/interop/convert" "github.com/nspcc-dev/neo-go/pkg/interop/native/std" "github.com/nspcc-dev/neo-go/pkg/interop/storage" ) @@ -10,3 +11,18 @@ func SetSerialized(ctx storage.Context, key interface{}, value interface{}) { data := std.Serialize(value) storage.Put(ctx, key, data) } + +// ToFixedWidth64 converts x to bytes such that numbers <= math.MaxUint64 +// have constant with of 9. +func ToFixedWidth64(x int) []byte { + data := convert.ToBytes(x) + if x < 0 || len(data) >= 9 { + return data + } + return append(data, make([]byte, 9-len(data))...) +} + +// FromFixedWidth64 is a reverse function for ToFixedWidth64. +func FromFixedWidth64(x []byte) int { + return convert.ToInteger(x) +} diff --git a/tests/common_test.go b/tests/common_test.go new file mode 100644 index 0000000..0085d2c --- /dev/null +++ b/tests/common_test.go @@ -0,0 +1,61 @@ +package tests + +import ( + "math" + "math/big" + "path" + "testing" + + "github.com/nspcc-dev/neo-go/pkg/neotest" + "github.com/stretchr/testify/require" +) + +const testdataPath = "./testdata" + +func newTestdataInvoker(t *testing.T) *neotest.ContractInvoker { + e := newExecutor(t) + ctr := neotest.CompileFile(t, e.CommitteeHash, testdataPath, path.Join(testdataPath, "config.yml")) + e.DeployContract(t, ctr, nil) + return e.CommitteeInvoker(ctr.Hash) +} + +func TestEncodeU64(t *testing.T) { + // Let's check boundary values for all bit sizes: + var nums []uint64 + for i := 0; i < 64; i++ { + if i != 0 { + nums = append(nums, (1<