use std::alloc::{Layout, alloc, alloc_zeroed, dealloc, realloc as raw_realloc};
use engine::Value;
use crate::jsvalue::{ENGINE_BOX_TAG, ENGINE_STRING_TAG, JsValue};
pub const HEADER_SIZE: usize = 8;
pub const REF_COUNT_OFFSET: usize = 4;
pub const PAYLOAD_OFFSET: usize = HEADER_SIZE;
pub const ALIGN: usize = 8;
pub const MAX_PAYLOAD: usize = (u32::MAX >> 2) as usize - HEADER_SIZE;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Kind {
Bytes,
Value,
}
impl Kind {
fn slot(self, size: usize) -> u32 {
match self {
Kind::Bytes => {
debug_assert!(size <= MAX_PAYLOAD);
((size as u32) << 2) | 0b10
}
Kind::Value => 0b01,
}
}
fn decode(slot: u32) -> Option<(Kind, usize)> {
match slot & 0b11 {
0b01 if slot == Kind::Value.slot(0) => Some((Kind::Value, size_of::<Value>())),
0b10 => Some((Kind::Bytes, (slot >> 2) as usize)),
_ => None,
}
}
}
#[repr(C)]
struct Header {
slot: u32,
ref_count: i32,
}
const _: () = assert!(core::mem::offset_of!(Header, ref_count) == REF_COUNT_OFFSET);
const _: () = assert!(core::mem::align_of::<Value>() <= ALIGN);
fn layout_for(size: usize) -> Option<Layout> {
if size > MAX_PAYLOAD {
return None;
}
let padded = size.max(size_of::<Value>());
Layout::from_size_align(padded.checked_add(HEADER_SIZE)?, ALIGN).ok()
}
unsafe fn header_of(block: *mut u8) -> Option<(Kind, usize)> {
let slot = unsafe { (block as *const u32).read() };
Kind::decode(slot)
}
unsafe fn write_header(block: *mut u8, kind: Kind, size: usize) {
unsafe {
(block as *mut u32).write(kind.slot(size));
(block.add(REF_COUNT_OFFSET) as *mut i32).write(1);
}
}
pub unsafe fn alloc_raw(size: usize) -> *mut u8 {
let Some(layout) = layout_for(size) else {
return std::ptr::null_mut();
};
let block = unsafe { alloc(layout) };
if block.is_null() {
return std::ptr::null_mut();
}
unsafe {
write_header(block, Kind::Bytes, size);
block.add(PAYLOAD_OFFSET)
}
}
pub unsafe fn alloc_raw_zeroed(size: usize) -> *mut u8 {
let Some(layout) = layout_for(size) else {
return std::ptr::null_mut();
};
let block = unsafe { alloc_zeroed(layout) };
if block.is_null() {
return std::ptr::null_mut();
}
unsafe {
write_header(block, Kind::Bytes, size);
block.add(PAYLOAD_OFFSET)
}
}
pub unsafe fn realloc_raw(payload: *mut u8, old_size: usize, new_size: usize) -> *mut u8 {
if payload.is_null() {
return unsafe { alloc_raw(new_size) };
}
if new_size == 0 {
unsafe { free_raw(payload) };
return std::ptr::null_mut();
}
let (Some(old_layout), Some(new_layout)) = (layout_for(old_size), layout_for(new_size)) else {
return std::ptr::null_mut();
};
let block = unsafe { payload.sub(PAYLOAD_OFFSET) };
let moved = unsafe { raw_realloc(block, old_layout, new_layout.size()) };
if moved.is_null() {
return std::ptr::null_mut();
}
unsafe {
write_header(moved, Kind::Bytes, new_size);
moved.add(PAYLOAD_OFFSET)
}
}
pub unsafe fn free_raw(payload: *mut u8) {
if payload.is_null() {
return;
}
let block = unsafe { payload.sub(PAYLOAD_OFFSET) };
let Some((kind, size)) = (unsafe { header_of(block) }) else {
debug_assert!(false, "js_free on a block this allocator did not produce");
return;
};
debug_assert_eq!(kind, Kind::Bytes, "js_free on a value box");
if let Some(layout) = layout_for(size) {
unsafe { dealloc(block, layout) };
}
}
pub unsafe fn payload_size(payload: *mut u8) -> usize {
if payload.is_null() {
return 0;
}
let block = unsafe { payload.sub(PAYLOAD_OFFSET) };
unsafe { header_of(block) }.map_or(0, |(_, size)| size)
}
#[repr(C)]
pub struct ValueBox {
header: Header,
value: Value,
}
const _: () = assert!(core::mem::offset_of!(ValueBox, value) == PAYLOAD_OFFSET);
const _: () = assert!(core::mem::offset_of!(ValueBox, header) == 0);
impl ValueBox {
pub unsafe fn ref_count(payload: *mut ()) -> i32 {
unsafe { (payload.cast::<u8>().sub(4) as *const i32).read() }
}
pub unsafe fn set_ref_count(payload: *mut (), count: i32) {
unsafe {
(payload.cast::<u8>().sub(4) as *mut i32).write(count);
}
}
}
pub fn box_value(value: Value) -> JsValue {
let tag = match &value {
Value::String(_) => ENGINE_STRING_TAG,
_ => ENGINE_BOX_TAG,
};
let block = Box::new(ValueBox {
header: Header {
slot: Kind::Value.slot(0),
ref_count: 1,
},
value,
});
let payload = (&raw const block.value) as *mut ();
std::mem::forget(block);
JsValue::mkptr(tag, payload)
}
pub unsafe fn value_of(payload: *mut ()) -> Value {
unsafe { (&*(payload as *const Value)).clone() }
}
pub unsafe fn free_value(payload: *mut ()) {
if payload.is_null() {
return;
}
let block = unsafe { payload.cast::<u8>().sub(PAYLOAD_OFFSET) as *mut ValueBox };
debug_assert_eq!(
unsafe { (*block).header.slot },
Kind::Value.slot(0),
"__JS_FreeValue on something that is not a value box"
);
drop(unsafe { Box::from_raw(block) });
}