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
use holochain_core_types::error::RibosomeErrorCode;
use holochain_wasm_utils::memory_allocation::{SinglePageAllocation, SinglePageStack, U16_MAX};
use wasmi::{MemoryRef, ModuleRef};
#[derive(Clone, Debug)]
pub struct SinglePageManager {
stack: SinglePageStack,
wasm_memory: MemoryRef,
}
#[allow(unknown_lints)]
#[allow(cast_lossless)]
impl SinglePageManager {
pub fn new(wasm_instance: &ModuleRef) -> Self {
let wasm_memory = wasm_instance
.export_by_name("memory")
.expect("all modules compiled with rustc should have an export named 'memory'; qed")
.as_memory()
.expect("in module generated by rustc export named 'memory' should be a memory; qed")
.clone();
return SinglePageManager {
stack: SinglePageStack::default(),
wasm_memory: wasm_memory.clone(),
};
}
pub fn allocate(&mut self, length: u16) -> Result<SinglePageAllocation, RibosomeErrorCode> {
if self.stack.top() as u32 + length as u32 > U16_MAX {
return Err(RibosomeErrorCode::OutOfMemory);
}
let offset = self.stack.allocate(length);
SinglePageAllocation::new(offset, length)
}
pub fn write(&mut self, data: &[u8]) -> Result<SinglePageAllocation, RibosomeErrorCode> {
let data_len = data.len();
if data_len > <u16>::max_value() as usize {
return Err(RibosomeErrorCode::OutOfMemory);
}
if data_len == 0 {
return Err(RibosomeErrorCode::ZeroSizedAllocation);
}
let mem_buf: SinglePageAllocation;
{
let res = self.allocate(data_len as u16);
if let Err(err_code) = res {
return Err(err_code);
}
mem_buf = res.unwrap();
}
self.wasm_memory
.set(mem_buf.offset() as u32, &data)
.expect("memory should be writable");
Ok(mem_buf)
}
pub fn read(&self, allocation: SinglePageAllocation) -> Vec<u8> {
return self
.wasm_memory
.get(allocation.offset() as u32, allocation.length() as usize)
.expect("Successfully retrieve the result");
}
}