memory.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package vm
  2. import (
  3. "fmt"
  4. "github.com/ethereum/go-ethereum/common"
  5. )
  6. type Memory struct {
  7. store []byte
  8. }
  9. func NewMemory() *Memory {
  10. return &Memory{nil}
  11. }
  12. func (m *Memory) Set(offset, size uint64, value []byte) {
  13. value = common.RightPadBytes(value, int(size))
  14. totSize := offset + size
  15. lenSize := uint64(len(m.store) - 1)
  16. if totSize > lenSize {
  17. // Calculate the diff between the sizes
  18. diff := totSize - lenSize
  19. if diff > 0 {
  20. // Create a new empty slice and append it
  21. newSlice := make([]byte, diff-1)
  22. // Resize slice
  23. m.store = append(m.store, newSlice...)
  24. }
  25. }
  26. copy(m.store[offset:offset+size], value)
  27. }
  28. func (m *Memory) Resize(size uint64) {
  29. if uint64(m.Len()) < size {
  30. m.store = append(m.store, make([]byte, size-uint64(m.Len()))...)
  31. }
  32. }
  33. func (self *Memory) Get(offset, size int64) (cpy []byte) {
  34. if size == 0 {
  35. return nil
  36. }
  37. if len(self.store) > int(offset) {
  38. cpy = make([]byte, size)
  39. copy(cpy, self.store[offset:offset+size])
  40. return
  41. }
  42. return
  43. }
  44. func (m *Memory) Len() int {
  45. return len(m.store)
  46. }
  47. func (m *Memory) Data() []byte {
  48. return m.store
  49. }
  50. func (m *Memory) Print() {
  51. fmt.Printf("### mem %d bytes ###\n", len(m.store))
  52. if len(m.store) > 0 {
  53. addr := 0
  54. for i := 0; i+32 <= len(m.store); i += 32 {
  55. fmt.Printf("%03d: % x\n", addr, m.store[i:i+32])
  56. addr++
  57. }
  58. } else {
  59. fmt.Println("-- empty --")
  60. }
  61. fmt.Println("####################")
  62. }