memory.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package vm
  2. import "fmt"
  3. type Memory struct {
  4. store []byte
  5. }
  6. func NewMemory() *Memory {
  7. return &Memory{nil}
  8. }
  9. func (m *Memory) Set(offset, size uint64, value []byte) {
  10. // length of store may never be less than offset + size.
  11. // The store should be resized PRIOR to setting the memory
  12. if size > uint64(len(m.store)) {
  13. panic("INVALID memory: store empty")
  14. }
  15. // It's possible the offset is greater than 0 and size equals 0. This is because
  16. // the calcMemSize (common.go) could potentially return 0 when size is zero (NO-OP)
  17. if size > 0 {
  18. copy(m.store[offset:offset+size], value)
  19. }
  20. }
  21. func (m *Memory) Resize(size uint64) {
  22. if uint64(m.Len()) < size {
  23. m.store = append(m.store, make([]byte, size-uint64(m.Len()))...)
  24. }
  25. }
  26. func (self *Memory) Get(offset, size int64) (cpy []byte) {
  27. if size == 0 {
  28. return nil
  29. }
  30. if len(self.store) > int(offset) {
  31. cpy = make([]byte, size)
  32. copy(cpy, self.store[offset:offset+size])
  33. return
  34. }
  35. return
  36. }
  37. func (self *Memory) GetPtr(offset, size int64) []byte {
  38. if size == 0 {
  39. return nil
  40. }
  41. if len(self.store) > int(offset) {
  42. return self.store[offset : offset+size]
  43. }
  44. return nil
  45. }
  46. func (m *Memory) Len() int {
  47. return len(m.store)
  48. }
  49. func (m *Memory) Data() []byte {
  50. return m.store
  51. }
  52. func (m *Memory) Print() {
  53. fmt.Printf("### mem %d bytes ###\n", len(m.store))
  54. if len(m.store) > 0 {
  55. addr := 0
  56. for i := 0; i+32 <= len(m.store); i += 32 {
  57. fmt.Printf("%03d: % x\n", addr, m.store[i:i+32])
  58. addr++
  59. }
  60. } else {
  61. fmt.Println("-- empty --")
  62. }
  63. fmt.Println("####################")
  64. }