use std::cell::Cell;
use crate::hash::HashMap;
thread_local! {
#[expect(clippy::disallowed_types, reason = "thread-local !Send JS Uint8Array table on single-threaded wasm32")]
static ARRAYS: std::cell::RefCell<HashMap<u64, js_sys::Uint8Array>> = std::cell::RefCell::default();
static NEXT_KEY: Cell<u64> = const { Cell::new(0) };
}
pub struct HostBytes {
key: u64,
len: usize,
}
impl HostBytes {
#[must_use]
pub fn new(array: js_sys::Uint8Array) -> Self {
let key = NEXT_KEY.with(|next| next.replace(next.get() + 1));
let len = array.length() as usize;
ARRAYS.with(|arrays| arrays.borrow_mut().insert(key, array));
HostBytes { key, len }
}
#[must_use]
pub fn len(&self) -> usize {
self.len
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[must_use]
pub fn array(&self) -> Option<js_sys::Uint8Array> {
let array = ARRAYS.with(|arrays| arrays.borrow().get(&self.key).cloned());
debug_assert!(array.is_some(), "host bytes used on another thread");
array
}
#[must_use]
pub(crate) fn to_vec(&self) -> Vec<u8> {
self.to_pod_vec()
}
#[must_use]
pub fn to_pod_vec<T: bytemuck::Pod>(&self) -> Vec<T> {
debug_assert!(self.len.is_multiple_of(size_of::<T>()));
let mut values = vec![T::zeroed(); self.len / size_of::<T>()];
if let Some(array) = self.array() {
array.copy_to(bytemuck::cast_slice_mut(&mut values));
}
values
}
}
impl Clone for HostBytes {
fn clone(&self) -> Self {
self.array().map_or(HostBytes { key: u64::MAX, len: self.len }, HostBytes::new)
}
}
impl Drop for HostBytes {
fn drop(&mut self) {
let _ = ARRAYS.try_with(|arrays| arrays.borrow_mut().remove(&self.key));
}
}
impl PartialEq for HostBytes {
fn eq(&self, other: &Self) -> bool {
self.len == other.len && self.to_vec() == other.to_vec()
}
}
impl Eq for HostBytes {}
impl std::fmt::Debug for HostBytes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HostBytes").field("len", &self.len).finish_non_exhaustive()
}
}