use alloc::vec::Vec;
use std::cell::RefCell;
use crate::runtime::{SharedCell, Value};
struct Mirror {
block: Vec<u8>,
owner: Value,
}
thread_local! {
static MIRRORS: RefCell<Vec<Mirror>> = const { RefCell::new(Vec::new()) };
}
fn the_same_object(first: &Value, second: &Value) -> bool {
match (first, second) {
(Value::Object(first), Value::Object(second)) => SharedCell::ptr_eq(first, second),
_ => false,
}
}
pub fn the_address_of_a_buffer(owner: &Value, bytes: &[u8]) -> i64 {
MIRRORS.with(|mirrors| {
let mut mirrors = mirrors.borrow_mut();
if let Some(mirror) = mirrors.iter_mut().find(|m| the_same_object(&m.owner, owner)) {
mirror.block.resize(bytes.len(), 0);
mirror.block.copy_from_slice(bytes);
return mirror.block.as_ptr() as i64;
}
let block = bytes.to_vec();
let address = block.as_ptr() as i64;
mirrors.push(Mirror {
block,
owner: owner.clone(),
});
address
})
}
pub fn the_mirror_is_updated(owner: &Value, bytes: &[u8]) {
MIRRORS.with(|mirrors| {
let mut mirrors = mirrors.borrow_mut();
if let Some(mirror) = mirrors.iter_mut().find(|m| the_same_object(&m.owner, owner)) {
mirror.block.resize(bytes.len(), 0);
mirror.block.copy_from_slice(bytes);
}
});
}
pub fn the_mirrors_are_read() -> Vec<(Value, Vec<u8>)> {
MIRRORS.with(|mirrors| {
mirrors
.borrow()
.iter()
.map(|mirror| (mirror.owner.clone(), mirror.block.clone()))
.collect()
})
}
pub fn forget_all() {
MIRRORS.with(|mirrors| mirrors.borrow_mut().clear());
}