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
use crate::error::Error;
use crate::storage::Storage;
use crate::{
blockchain::Blockchain, context::OwnedContext, params::ParamType, storage::StorageAPI,
};
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::cell::RefCell;
pub fn mock_context(storage_size: usize) -> OwnedContext<MockBlockchain> {
OwnedContext {
blockchain: MockBlockchain::new(),
storage: mock_storage(storage_size),
}
}
pub fn mock_storage(storage_size: usize) -> Storage {
let storage = MockStorageAPI::new(storage_size);
Storage {
api: Box::new(storage),
}
}
pub struct MockStorageAPI {
storage: RefCell<Vec<u8>>,
}
impl MockStorageAPI {
pub fn new(size: usize) -> Self {
let storage = RefCell::new(alloc::vec![0; size].to_vec());
Self { storage }
}
}
pub struct MockBlockchain {}
impl MockBlockchain {
pub fn new() -> Self {
Self {}
}
}
impl Default for MockBlockchain {
fn default() -> Self {
Self::new()
}
}
impl Blockchain for MockBlockchain {
fn get_param(&self, _param_id: i32) -> Option<ParamType> {
unimplemented!()
}
}
impl StorageAPI for MockStorageAPI {
fn write(&self, offset: u32, data: &[u8]) -> Result<(), Error> {
if offset as usize + data.len() > self.storage.borrow().len() {
return Err(Error::GenericError("overflowed"));
}
for (i, d) in data.iter().enumerate() {
self.storage.borrow_mut()[i + offset as usize] = *d;
}
Ok(())
}
fn read(&self, offset: u32, length: u32) -> Result<Vec<u8>, Error> {
if (offset + length) as usize > self.storage.borrow().len() {
return Err(Error::GenericError("overflowed"));
}
let c = &self.storage.borrow()[offset as usize..(offset + length) as usize];
Ok(c.into())
}
}