neoneo-go/pkg/vm/slot.go

84 lines
1.6 KiB
Go
Raw Normal View History

2020-05-07 08:45:24 +00:00
package vm
import (
2021-09-08 14:27:11 +00:00
"encoding/json"
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
)
2020-05-07 08:45:24 +00:00
// Slot is a fixed-size slice of stack items.
type Slot struct {
storage []stackitem.Item
2020-05-08 12:34:32 +00:00
refs *refCounter
2020-05-07 08:45:24 +00:00
}
// newSlot returns new slot with the provided reference counter.
func newSlot(refs *refCounter) *Slot {
2020-05-07 08:45:24 +00:00
return &Slot{
refs: refs,
2020-05-07 08:45:24 +00:00
}
}
// init sets static slot size to n. It is intended to be used only by INITSSLOT.
func (s *Slot) init(n int) {
if s.storage != nil {
panic("already initialized")
}
s.storage = make([]stackitem.Item, n)
}
2020-05-08 12:34:32 +00:00
func (v *VM) newSlot(n int) *Slot {
s := newSlot(&v.refs)
s.init(n)
return s
2020-05-08 12:34:32 +00:00
}
2020-05-07 08:45:24 +00:00
// Set sets i-th storage slot.
func (s *Slot) Set(i int, item stackitem.Item) {
2020-05-08 12:34:32 +00:00
if s.storage[i] == item {
return
}
old := s.storage[i]
2020-05-07 08:45:24 +00:00
s.storage[i] = item
2020-05-08 12:34:32 +00:00
if old != nil {
s.refs.Remove(old)
}
s.refs.Add(item)
2020-05-07 08:45:24 +00:00
}
// Get returns item contained in i-th slot.
func (s *Slot) Get(i int) stackitem.Item {
2020-05-07 08:45:24 +00:00
if item := s.storage[i]; item != nil {
return item
}
return stackitem.Null{}
2020-05-07 08:45:24 +00:00
}
// Clear removes all slot variables from reference counter.
func (s *Slot) Clear() {
for _, item := range s.storage {
s.refs.Remove(item)
}
}
// Size returns slot size.
func (s *Slot) Size() int {
if s.storage == nil {
panic("not initialized")
}
return len(s.storage)
}
2021-09-08 14:27:11 +00:00
// MarshalJSON implements JSON marshalling interface.
func (s *Slot) MarshalJSON() ([]byte, error) {
items := s.storage
arr := make([]json.RawMessage, len(items))
for i := range items {
data, err := stackitem.ToJSONWithTypes(items[i])
if err == nil {
arr[i] = data
}
}
return json.Marshal(arr)
}