memory.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package vm
  17. import "fmt"
  18. type Memory struct {
  19. store []byte
  20. }
  21. func NewMemory() *Memory {
  22. return &Memory{nil}
  23. }
  24. func (m *Memory) Set(offset, size uint64, value []byte) {
  25. // length of store may never be less than offset + size.
  26. // The store should be resized PRIOR to setting the memory
  27. if size > uint64(len(m.store)) {
  28. panic("INVALID memory: store empty")
  29. }
  30. // It's possible the offset is greater than 0 and size equals 0. This is because
  31. // the calcMemSize (common.go) could potentially return 0 when size is zero (NO-OP)
  32. if size > 0 {
  33. copy(m.store[offset:offset+size], value)
  34. }
  35. }
  36. func (m *Memory) Resize(size uint64) {
  37. if uint64(m.Len()) < size {
  38. m.store = append(m.store, make([]byte, size-uint64(m.Len()))...)
  39. }
  40. }
  41. func (self *Memory) Get(offset, size int64) (cpy []byte) {
  42. if size == 0 {
  43. return nil
  44. }
  45. if len(self.store) > int(offset) {
  46. cpy = make([]byte, size)
  47. copy(cpy, self.store[offset:offset+size])
  48. return
  49. }
  50. return
  51. }
  52. func (self *Memory) GetPtr(offset, size int64) []byte {
  53. if size == 0 {
  54. return nil
  55. }
  56. if len(self.store) > int(offset) {
  57. return self.store[offset : offset+size]
  58. }
  59. return nil
  60. }
  61. func (m *Memory) Len() int {
  62. return len(m.store)
  63. }
  64. func (m *Memory) Data() []byte {
  65. return m.store
  66. }
  67. func (m *Memory) Print() {
  68. fmt.Printf("### mem %d bytes ###\n", len(m.store))
  69. if len(m.store) > 0 {
  70. addr := 0
  71. for i := 0; i+32 <= len(m.store); i += 32 {
  72. fmt.Printf("%03d: % x\n", addr, m.store[i:i+32])
  73. addr++
  74. }
  75. } else {
  76. fmt.Println("-- empty --")
  77. }
  78. fmt.Println("####################")
  79. }