-
Notifications
You must be signed in to change notification settings - Fork 106
/
db.rs
48 lines (41 loc) · 1.24 KB
/
db.rs
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
use cosmwasm::traits::{ReadonlyStorage, Storage};
use crate::memory::Buffer;
// this represents something passed in from the caller side of FFI
#[repr(C)]
pub struct db_t {}
#[repr(C)]
pub struct DB_vtable {
pub read_db: extern "C" fn(*mut db_t, Buffer, Buffer) -> i64,
pub write_db: extern "C" fn(*mut db_t, Buffer, Buffer),
}
#[repr(C)]
pub struct DB {
pub state: *mut db_t,
pub vtable: DB_vtable,
}
impl ReadonlyStorage for DB {
fn get(&self, key: &[u8]) -> Option<Vec<u8>> {
let buf = Buffer::from_vec(key.to_vec());
// TODO: dynamic size
let mut buf2 = Buffer::from_vec(vec![0u8; 2000]);
let res = (self.vtable.read_db)(self.state, buf, buf2);
// read in the number of bytes returned
if res < 0 {
// TODO
panic!("val was not big enough for data");
}
if res == 0 {
return None;
}
buf2.len = res as usize;
unsafe { Some(buf2.consume()) }
}
}
impl Storage for DB {
fn set(&mut self, key: &[u8], value: &[u8]) {
let buf = Buffer::from_vec(key.to_vec());
let buf2 = Buffer::from_vec(value.to_vec());
// caller will free input
(self.vtable.write_db)(self.state, buf, buf2);
}
}