1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use bigint::{U256, M256};
use super::errors::MemoryError;
pub trait Memory {
fn check_write(&self, index: U256) -> Result<(), MemoryError>;
fn check_write_range(&self, start: U256, len: U256) -> Result<(), MemoryError>;
fn write(&mut self, index: U256, value: M256) -> Result<(), MemoryError>;
fn write_raw(&mut self, index: U256, value: u8) -> Result<(), MemoryError>;
fn read(&self, index: U256) -> M256;
fn read_raw(&self, index: U256) -> u8;
}
pub struct SeqMemory {
memory: Vec<u8>,
}
impl Default for SeqMemory {
fn default() -> SeqMemory {
SeqMemory {
memory: Vec::new(),
}
}
}
impl Memory for SeqMemory {
fn check_write(&self, index: U256) -> Result<(), MemoryError> {
let end = index + 32.into();
if end > U256::from(usize::max_value()) {
Err(MemoryError::IndexNotSupported)
} else {
Ok(())
}
}
fn check_write_range(&self, start: U256, len: U256) -> Result<(), MemoryError> {
if len == U256::zero() {
return Ok(());
}
if M256::from(start) + M256::from(len) < M256::from(start) {
Err(MemoryError::IndexNotSupported)
} else {
self.check_write(start + len - U256::from(1u64))
}
}
fn write(&mut self, index: U256, value: M256) -> Result<(), MemoryError> {
let end = M256::from(index) + 32.into();
if end > M256::from(usize::max_value()) {
return Err(MemoryError::IndexNotSupported);
}
for i in 0..32 {
self.write_raw(index + i.into(), value.index(i)).unwrap();
}
Ok(())
}
fn write_raw(&mut self, index: U256, value: u8) -> Result<(), MemoryError> {
if index > U256::from(usize::max_value()) {
return Err(MemoryError::IndexNotSupported);
}
let index: usize = index.as_usize();
if self.memory.len() <= index {
self.memory.resize(index + 1, 0u8);
}
self.memory[index] = value;
Ok(())
}
fn read(&self, index: U256) -> M256 {
let mut a: [u8; 32] = [0u8; 32];
for i in 0..32 {
a[i] = self.read_raw(index + i.into());
}
a.as_ref().into()
}
fn read_raw(&self, index: U256) -> u8 {
if index > U256::from(usize::max_value()) {
return 0u8;
}
let index: usize = index.as_usize();
if self.memory.len() <= index {
return 0u8;
}
self.memory[index]
}
}