From 1100f629df05d81da9d0a378763a394c4c52e265 Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Thu, 21 May 2020 13:00:11 +0300 Subject: [PATCH] opcode: implement FromString() --- pkg/vm/opcode/from_string.go | 20 ++++++++++++++++++++ pkg/vm/opcode/opcode_test.go | 10 ++++++++++ 2 files changed, 30 insertions(+) create mode 100644 pkg/vm/opcode/from_string.go diff --git a/pkg/vm/opcode/from_string.go b/pkg/vm/opcode/from_string.go new file mode 100644 index 000000000..b79d69ae9 --- /dev/null +++ b/pkg/vm/opcode/from_string.go @@ -0,0 +1,20 @@ +package opcode + +import "errors" + +var stringToOpcode = make(map[string]Opcode) + +func init() { + for i := 0; i < 255; i++ { + op := Opcode(i) + stringToOpcode[op.String()] = op + } +} + +// FromString converts string representation to and opcode itself. +func FromString(s string) (Opcode, error) { + if op, ok := stringToOpcode[s]; ok { + return op, nil + } + return 0, errors.New("invalid opcode") +} diff --git a/pkg/vm/opcode/opcode_test.go b/pkg/vm/opcode/opcode_test.go index 862093652..f0f5a0451 100644 --- a/pkg/vm/opcode/opcode_test.go +++ b/pkg/vm/opcode/opcode_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // Nothing more to test here, really. @@ -18,3 +19,12 @@ func TestStringer(t *testing.T) { assert.Equal(t, s, o.String()) } } + +func TestFromString(t *testing.T) { + _, err := FromString("abcdef") + require.Error(t, err) + + op, err := FromString(MUL.String()) + require.NoError(t, err) + require.Equal(t, MUL, op) +}