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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use bigint::{M256, U256};
use super::errors::NotSupportedError;
pub trait Memory: Sized {
fn new(memory_limit: usize) -> Self;
fn check_write(&self, index: U256) -> Result<(), NotSupportedError>;
fn check_write_range(&self, start: U256, len: U256) -> Result<(), NotSupportedError>;
fn write(&mut self, index: U256, value: M256) -> Result<(), NotSupportedError>;
fn write_raw(&mut self, index: U256, value: u8) -> Result<(), NotSupportedError>;
fn read(&self, index: U256) -> M256;
fn read_raw(&self, index: U256) -> u8;
}
pub struct SeqMemory {
memory: Vec<u8>,
memory_limit: usize,
}
impl SeqMemory {
#[inline]
pub fn len(&self) -> usize {
self.memory.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl Memory for SeqMemory {
fn new(memory_limit: usize) -> Self {
SeqMemory {
memory: Vec::new(),
memory_limit,
}
}
fn check_write(&self, index: U256) -> Result<(), NotSupportedError> {
let end = index + 32.into();
if end > U256::from(self.memory_limit) {
Err(NotSupportedError::MemoryIndexNotSupported)
} else {
Ok(())
}
}
fn check_write_range(&self, start: U256, len: U256) -> Result<(), NotSupportedError> {
if len == U256::zero() {
return Ok(());
}
if start.saturating_add(len) > U256::from(self.memory_limit) {
Err(NotSupportedError::MemoryIndexNotSupported)
} else {
self.check_write(start + len - U256::from(1u64))
}
}
fn write(&mut self, index: U256, value: M256) -> Result<(), NotSupportedError> {
let end = M256::from(index) + 32.into();
if end > M256::from(self.memory_limit) {
return Err(NotSupportedError::MemoryIndexNotSupported);
}
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<(), NotSupportedError> {
if index > U256::from(self.memory_limit) {
return Err(NotSupportedError::MemoryIndexNotSupported);
}
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, item) in a[0..32].iter_mut().enumerate() {
*item = 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]
}
}