github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/core/vm/memory.go (about) 1 package vm 2 3 import "fmt" 4 5 // Memory implements a simple memory model for the quickchain virtual machine. 6 type Memory struct { 7 store []byte 8 lastGasCost uint64 9 } 10 11 func NewMemory() *Memory { 12 return &Memory{} 13 } 14 15 // Set sets offset + size to value 16 func (m *Memory) Set(offset, size uint64, value []byte) { 17 // length of store may never be less than offset + size. 18 // The store should be resized PRIOR to setting the memory 19 if size > uint64(len(m.store)) { 20 panic("INVALID memory: store empty") 21 } 22 23 // It's possible the offset is greater than 0 and size equals 0. This is because 24 // the calcMemSize (common.go) could potentially return 0 when size is zero (NO-OP) 25 if size > 0 { 26 copy(m.store[offset:offset+size], value) 27 } 28 } 29 30 // Resize resizes the memory to size 31 func (m *Memory) Resize(size uint64) { 32 if uint64(m.Len()) < size { 33 m.store = append(m.store, make([]byte, size-uint64(m.Len()))...) 34 } 35 } 36 37 // Get returns offset + size as a new slice 38 func (m *Memory) Get(offset, size int64) (cpy []byte) { 39 if size == 0 { 40 return nil 41 } 42 43 if len(m.store) > int(offset) { 44 cpy = make([]byte, size) 45 copy(cpy, m.store[offset:offset+size]) 46 47 return 48 } 49 50 return 51 } 52 53 // GetPtr returns the offset + size 54 func (m *Memory) GetPtr(offset, size int64) []byte { 55 if size == 0 { 56 return nil 57 } 58 59 if len(m.store) > int(offset) { 60 return m.store[offset : offset+size] 61 } 62 63 return nil 64 } 65 66 // Len returns the length of the backing slice 67 func (m *Memory) Len() int { 68 return len(m.store) 69 } 70 71 // Data returns the backing slice 72 func (m *Memory) Data() []byte { 73 return m.store 74 } 75 76 func (m *Memory) Print() { 77 fmt.Printf("### mem %d bytes ###\n", len(m.store)) 78 if len(m.store) > 0 { 79 addr := 0 80 for i := 0; i+32 <= len(m.store); i += 32 { 81 fmt.Printf("%03d: % x\n", addr, m.store[i:i+32]) 82 addr++ 83 } 84 } else { 85 fmt.Println("-- empty --") 86 } 87 fmt.Println("####################") 88 }