From 2cec088f08e9d985976382cd72891e6a0d01a1a8 Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Fri, 8 May 2020 15:34:32 +0300 Subject: [PATCH] vm: add reference counter to slots --- pkg/vm/slot.go | 16 +++++++++++++++- pkg/vm/slot_test.go | 2 +- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/pkg/vm/slot.go b/pkg/vm/slot.go index e5a3d928d..279cb3f39 100644 --- a/pkg/vm/slot.go +++ b/pkg/vm/slot.go @@ -3,18 +3,32 @@ package vm // Slot is a fixed-size slice of stack items. type Slot struct { storage []StackItem + refs *refCounter } // newSlot returns new slot of n items. -func newSlot(n int) *Slot { +func newSlot(n int, refs *refCounter) *Slot { return &Slot{ storage: make([]StackItem, n), + refs: refs, } } +func (v *VM) newSlot(n int) *Slot { + return newSlot(n, v.refs) +} + // Set sets i-th storage slot. func (s *Slot) Set(i int, item StackItem) { + if s.storage[i] == item { + return + } + old := s.storage[i] s.storage[i] = item + if old != nil { + s.refs.Remove(old) + } + s.refs.Add(item) } // Get returns item contained in i-th slot. diff --git a/pkg/vm/slot_test.go b/pkg/vm/slot_test.go index 49684e73a..65781b7af 100644 --- a/pkg/vm/slot_test.go +++ b/pkg/vm/slot_test.go @@ -8,7 +8,7 @@ import ( ) func TestSlot_Get(t *testing.T) { - s := newSlot(3) + s := newSlot(3, newRefCounter()) require.NotNil(t, s) require.Equal(t, 3, s.Size())