Use sqlite-specific ffi

This commit is contained in:
folex 2019-08-14 20:19:39 +03:00
parent 9391252717
commit 04f1fcfbe1

View File

@ -6,25 +6,23 @@ fn init() {
}
#[invocation_handler(init_fn = init)]
fn azaza(_arg: String) -> String {
println!("Hello, world!");
info!("hello");
fn run(arg: String) -> String {
query(arg)
}
fn query(query: String) -> String {
info!("executing query: '{}'", query);
let query = "CREATE VIRTUAL TABLE users USING FTS5(body)";
unsafe {
let bytes = query.as_bytes();
let query_ptr = ffi::allocate(bytes.len());
info!("allocated");
for (i, byte) in bytes.iter().enumerate() {
info!("will store {} {}", i, *byte);
let ptr = query_ptr + i as i32;
ffi::store(ptr, *byte);
}
info!("stored");
let result_ptr = ffi::invoke(query_ptr, bytes.len());
info!("invoked");
let mut result_size = 0;
for i in 0u8..4u8 {
@ -32,23 +30,19 @@ fn azaza(_arg: String) -> String {
let b = ffi::load(ptr);
result_size = result_size | (b >> 8*i)
}
info!("loaded");
let mut result_bytes = vec![0; result_size as usize];
for i in 0u8..result_size {
for i in 4u8..result_size {
let ptr = result_ptr + i as i32;
let b = ffi::load(ptr);
result_bytes[i as usize] = b;
result_bytes[i as usize - 4] = b;
}
info!("parsed to bytes");
let result_str = std::str::from_utf8(result_bytes.as_slice());
if result_str.is_err() {
info!("unable to decode result from result_bytes: {:?}", result_bytes);
}
info!("result is {:?}", result_str);
result_str.expect("unable to decode result").to_string()
}
}
@ -56,10 +50,15 @@ fn azaza(_arg: String) -> String {
pub mod ffi {
#[link(wasm_import_module = "sqlite")]
extern "C" {
#[link_name="sqlite_allocate"]
pub fn allocate(size: usize) -> i32;
#[link_name="sqlite_deallocate"]
pub fn deallocate(ptr: i32, size: usize);
#[link_name="sqlite_invoke"]
pub fn invoke(ptr: i32, size: usize) -> i32;
#[link_name="sqlite_store"]
pub fn store(ptr: i32, byte: u8);
#[link_name="sqlite_load"]
pub fn load(ptr: i32) -> u8;
}
}