use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use super::{BytesResult, FsError, ListResult, UnitResult};
const OP_READ: u32 = 0;
const OP_WRITE: u32 = 1;
const OP_REMOVE: u32 = 2;
const OP_LIST: u32 = 3;
const SEP: char = '\u{1f}';
#[link(wasm_import_module = "env")]
unsafe extern "C" {
fn day_dom_fs_start(
id: u32,
op: u32,
path: *const u8,
path_len: usize,
data: *const u8,
data_len: usize,
);
}
type Callback = Box<dyn FnOnce(BytesResult)>;
thread_local! {
static PENDING: RefCell<HashMap<u32, Callback>> = RefCell::new(HashMap::new());
static NEXT_ID: Cell<u32> = const { Cell::new(1) };
}
fn start(op: u32, path: &str, data: &[u8], on_done: Callback) {
let id = NEXT_ID.with(|n| {
let id = n.get();
n.set(id.wrapping_add(1).max(1));
id
});
PENDING.with(|p| p.borrow_mut().insert(id, on_done));
unsafe {
day_dom_fs_start(id, op, path.as_ptr(), path.len(), data.as_ptr(), data.len());
}
}
pub fn read(_path: &str) -> BytesResult {
Err(FsError::Unsupported)
}
pub fn write(_path: &str, _bytes: &[u8]) -> UnitResult {
Err(FsError::Unsupported)
}
pub fn remove(_path: &str) -> UnitResult {
Err(FsError::Unsupported)
}
pub fn list(_dir: &str) -> ListResult {
Err(FsError::Unsupported)
}
pub fn read_async(path: String, on_done: Box<dyn FnOnce(BytesResult) + Send>) {
start(OP_READ, &path, &[], Box::new(on_done));
}
pub fn write_async(path: String, bytes: Vec<u8>, on_done: Box<dyn FnOnce(UnitResult) + Send>) {
start(
OP_WRITE,
&path,
&bytes,
Box::new(move |r| on_done(r.map(|_| ()))),
);
}
pub fn remove_async(path: String, on_done: Box<dyn FnOnce(UnitResult) + Send>) {
start(
OP_REMOVE,
&path,
&[],
Box::new(move |r| on_done(r.map(|_| ()))),
);
}
pub fn list_async(dir: String, on_done: Box<dyn FnOnce(ListResult) + Send>) {
start(
OP_LIST,
&dir,
&[],
Box::new(move |r| {
on_done(r.map(|bytes| {
let joined = String::from_utf8_lossy(&bytes);
if joined.is_empty() {
Vec::new()
} else {
joined.split(SEP).map(str::to_owned).collect()
}
}))
}),
);
}
fn complete(id: u32, result: BytesResult) {
if let Some(cb) = PENDING.with(|p| p.borrow_mut().remove(&id)) {
cb(result);
}
}
#[unsafe(no_mangle)]
pub extern "C" fn day_fs_alloc(len: usize) -> *mut u8 {
let mut v = Vec::<u8>::with_capacity(len);
let ptr = v.as_mut_ptr();
std::mem::forget(v);
ptr
}
fn take_buf(ptr: *mut u8, len: usize) -> Vec<u8> {
if ptr.is_null() || len == 0 {
return Vec::new();
}
unsafe { Vec::from_raw_parts(ptr, len, len) }
}
#[unsafe(no_mangle)]
pub extern "C" fn day_fs_done(id: u32, ptr: *mut u8, len: usize) {
complete(id, Ok(take_buf(ptr, len)));
}
#[unsafe(no_mangle)]
pub extern "C" fn day_fs_failed(id: u32, kind: u32, msg_ptr: *mut u8, msg_len: usize) {
let msg = String::from_utf8_lossy(&take_buf(msg_ptr, msg_len)).into_owned();
let err = match kind {
1 => FsError::NotFound,
2 => FsError::Unsupported,
_ => FsError::Io(msg),
};
complete(id, Err(err));
}