Skip to content

Commit

Permalink
vm: make REMOVE consume array from stack
Browse files Browse the repository at this point in the history
  • Loading branch information
fyrchik committed Sep 12, 2019
1 parent 5a588ec commit 2ef8145
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 15 deletions.
23 changes: 19 additions & 4 deletions pkg/vm/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -728,10 +728,25 @@ func (v *VM) execute(ctx *Context, op Instruction) {
}
case REMOVE:
key := int(v.estack.Pop().BigInt().Int64())
elem := v.estack.Peek(0)
a := elem.Array()
a = append(a[:key], a[key+1:]...)
elem.value = makeStackItem(a)
elem := v.estack.Pop()
switch t := elem.value.(type) {
case *ArrayItem:
a := t.value
if key < 0 || key >= len(a) {
panic("REMOVE: invalid index")
}
a = append(a[:key], a[key+1:]...)
t.value = a
case *StructItem:
a := t.value
if key < 0 || key >= len(a) {
panic("REMOVE: invalid index")
}
a = append(a[:key], a[key+1:]...)
t.value = a
default:
panic("REMOVE: invalid type")
}

case ARRAYSIZE:
elem := v.estack.Pop()
Expand Down
14 changes: 3 additions & 11 deletions pkg/vm/vm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1314,23 +1314,15 @@ func TestREMOVEBadIndex(t *testing.T) {
}

func TestREMOVEGood(t *testing.T) {
prog := makeProgram(REMOVE)
prog := makeProgram(DUP, PUSH2, REMOVE)
elements := []int{22, 34, 42, 55, 81}
reselements := []int{22, 34, 55, 81}
vm := load(prog)
vm.estack.PushVal(1)
vm.estack.PushVal(elements)
vm.estack.PushVal(2)
vm.Run()
assert.Equal(t, false, vm.state.HasFlag(faultState))
assert.Equal(t, 2, vm.estack.Len())
a := vm.estack.Peek(0).Array()
assert.Equal(t, len(reselements), len(a))
for k, v := range reselements {
e := a[k].Value().(*big.Int)
assert.Equal(t, int64(v), e.Int64())
}
assert.Equal(t, int64(1), vm.estack.Peek(1).BigInt().Int64())
assert.Equal(t, 1, vm.estack.Len())
assert.Equal(t, makeStackItem(reselements), vm.estack.Pop().value)
}

func makeProgram(opcodes ...Instruction) []byte {
Expand Down

0 comments on commit 2ef8145

Please sign in to comment.