From 7b4acd5a7fbc5e387c6f4e81f04441b6718b4787 Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Wed, 29 Jul 2020 12:59:19 +0300 Subject: [PATCH] vm: allow to convert stack to a slice Signed-off-by: Evgenii Stratonikov --- pkg/vm/stack.go | 9 +++++++++ pkg/vm/stack_test.go | 16 ++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/pkg/vm/stack.go b/pkg/vm/stack.go index 44e9d6d94..f5f93287d 100644 --- a/pkg/vm/stack.go +++ b/pkg/vm/stack.go @@ -396,6 +396,15 @@ func (s *Stack) PopSigElements() ([][]byte, error) { return elems, nil } +// ToArray converts stack to an array of stackitems with top item being the last. +func (s *Stack) ToArray() []stackitem.Item { + items := make([]stackitem.Item, 0, s.len) + s.IterBack(func(e *Element) { + items = append(items, e.Item()) + }) + return items +} + // ToContractParameters converts Stack to slice of smartcontract.Parameter. func (s *Stack) ToContractParameters() []smartcontract.Parameter { items := make([]smartcontract.Parameter, 0, s.Len()) diff --git a/pkg/vm/stack_test.go b/pkg/vm/stack_test.go index 82c15e962..885ccbf08 100644 --- a/pkg/vm/stack_test.go +++ b/pkg/vm/stack_test.go @@ -237,6 +237,22 @@ func TestPushVal(t *testing.T) { assert.IsType(t, elem.value, &stackitem.Array{}) } +func TestStack_ToArray(t *testing.T) { + t.Run("Empty", func(t *testing.T) { + s := NewStack("test") + items := s.ToArray() + require.Equal(t, 0, len(items)) + }) + t.Run("NonEmpty", func(t *testing.T) { + s := NewStack("test") + expected := []stackitem.Item{stackitem.Make(1), stackitem.Make(true)} + for i := range expected { + s.PushVal(expected[i]) + } + require.Equal(t, expected, s.ToArray()) + }) +} + func TestSwapElemValues(t *testing.T) { s := NewStack("test")