Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swap opcode #35

Merged
merged 1 commit into from
May 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions vm/op_codes.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const (
Push
Dup
Roll
Swap
Pop
Add
Sub
Expand Down Expand Up @@ -91,6 +92,7 @@ var OpCodes = []OpCode{
{Push, "push", 1, []int{BYTES}, 1, 1},
{Dup, "dup", 0, nil, 1, 2},
{Roll, "roll", 1, []int{BYTE}, 1, 2},
{Swap, "swap", 0, nil, 1, 2},
{Pop, "pop", 0, nil, 1, 1},
{Add, "add", 0, nil, 1, 2},
{Sub, "sub", 0, nil, 1, 2},
Expand Down
12 changes: 12 additions & 0 deletions vm/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,18 @@ func (vm *VM) Exec(trace bool) bool {
return false
}
}
case Swap:
last, err1 := vm.evaluationStack.Pop()
secondLast, err2 := vm.evaluationStack.Pop()
if !vm.checkErrors(opCode.Name, err1, err2) {
return false
}

err1 = vm.evaluationStack.Push(last)
err2 = vm.evaluationStack.Push(secondLast)
if !vm.checkErrors(opCode.Name, err1, err2) {
return false
}
case Pop:
_, rerr := vm.PopBytes(opCode)
if !vm.checkErrors(opCode.Name, rerr) {
Expand Down
36 changes: 36 additions & 0 deletions vm/vm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1454,6 +1454,42 @@ func TestVM_Exec_Roll(t *testing.T) {
}
}

func TestVM_Exec_Swap(t *testing.T) {
code := []byte{
Push, 1, 1,
Push, 1, 2,
Push, 1, 3,
Swap,
Halt,
}

vm, isSuccess := execCode(code)
assert.Assert(t, isSuccess)

last, err := vm.evaluationStack.Pop()
assert.NilError(t, err)
secondLast, err := vm.evaluationStack.Pop()
assert.NilError(t, err)

assertBytes(t, last, 2)
assertBytes(t, secondLast, 3)
}

func TestVM_Exec_SwapError(t *testing.T) {
code := []byte{
Push, 1, 1,
Swap,
Halt,
}

vm, isSuccess := execCode(code)
assert.Assert(t, !isSuccess)

errMsg, err := vm.evaluationStack.Pop()
assert.NilError(t, err)
assert.Equal(t, string(errMsg), "swap: pop() on empty stack")
}

func TestVM_Exec_NewMap(t *testing.T) {
code := []byte{
NewMap,
Expand Down