use std::cell::RefCell;
use crate::{Answer, Event};
thread_local! {
static ROOM: RefCell<Vec<Vec<u8>>> = const { RefCell::new(Vec::new()) };
static ANSWER: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
}
pub fn alloc(len: i32) -> i32 {
let mut buf = vec![0u8; len.max(0) as usize];
let ptr = buf.as_mut_ptr() as usize as i32;
ROOM.with(|r| r.borrow_mut().push(buf));
ptr
}
pub fn take(ptr: i32, len: i32) -> Vec<u8> {
ROOM.with(|r| {
let mut room = r.borrow_mut();
match room.iter().position(|b| b.as_ptr() as usize as i32 == ptr) {
Some(i) => {
let mut b = room.swap_remove(i);
b.truncate(len.max(0) as usize);
b
}
None => Vec::new(),
}
})
}
pub fn pack(ptr: *const u8, len: usize) -> i64 {
(((ptr as usize as u64) << 32) | (len as u64 & 0xffff_ffff)) as i64
}
pub fn handle(ptr: i32, len: i32, handle: impl FnOnce(Event) -> Answer) -> i64 {
let input = take(ptr, len);
let answer = match serde_json::from_slice(&input) {
Ok(v) => handle(Event::from_value(v)),
Err(e) => {
let mut a = Answer::default();
a.log_error(format!("the host sent an event that is not JSON: {e}"));
a
}
};
let bytes = serde_json::to_vec(&answer).unwrap_or_else(|_| b"{}".to_vec());
ANSWER.with(|a| {
*a.borrow_mut() = bytes;
let a = a.borrow();
pack(a.as_ptr(), a.len())
})
}