use core::marker::PhantomData;
use core::mem::size_of;
use std::io;
use crate::BStackRaiiAllocator;
use bstack::{BStack, BStackRange};
use bytemuck::{Pod, Zeroable};
use crate::io_core::{TryCloneIn, dealloc_range};
use crate::primitives::EightCC;
use crate::types::compiled::{BStackOwned, BlockHeader, HEADER_SIZE};
use crate::types::traits::{BStackBlock, BStackCast, BStackMove, BStackRef};
#[repr(C, packed)]
#[derive(Clone, Copy)]
pub struct BoxOnDisk<T: Pod> {
pub header: BlockHeader,
pub value: T,
}
unsafe impl<T: Pod> Zeroable for BoxOnDisk<T> {}
unsafe impl<T: Pod> Pod for BoxOnDisk<T> {}
pub struct BStackBox<T: Pod> {
range: BStackRange,
_marker: PhantomData<fn() -> T>,
}
impl<T: Pod> BStackBox<T> {
const SIZE: u64 = size_of::<BoxOnDisk<T>>() as u64;
pub fn new<A: BStackRaiiAllocator>(allocator: &A, value: T) -> io::Result<BStackOwned<Self>> {
let od = BoxOnDisk {
header: BlockHeader {
size: Self::SIZE,
tag: Self::eightcc(),
},
value,
};
let mut slice = allocator.alloc(Self::SIZE)?;
if let Err(e) = slice.write_range(0, bytemuck::bytes_of(&od)) {
let _ = allocator.dealloc(slice);
return Err(e);
}
Ok(unsafe { BStackOwned::from_raw(Self::from_range(slice.as_range())) })
}
pub fn get(&self, stack: &BStack) -> io::Result<T> {
let mut buf = std::vec![0u8; size_of::<BoxOnDisk<T>>()];
let r = unsafe { BStackRef::<Self>::from_range(self.range) };
r.read_on_disk(stack, &mut buf)?;
let off = HEADER_SIZE as usize;
Ok(bytemuck::pod_read_unaligned::<T>(
&buf[off..off + size_of::<T>()],
))
}
pub fn set<A: BStackRaiiAllocator>(&self, allocator: &A, value: T) -> io::Result<()> {
allocator
.stack()
.set(self.range.start() + HEADER_SIZE, bytemuck::bytes_of(&value))
}
}
impl<T: Pod> BStackCast for BStackBox<T> {
fn eightcc() -> EightCC {
const BASE: EightCC = EightCC::new([b'B', b'o', b'x', 0x80, 0x81, 0x82, 0x83, 0x84]);
BASE.mix(EightCC::new((size_of::<T>() as u64).to_le_bytes()))
}
}
impl<T: Pod> crate::types::traits::BStackEmbeddable for BStackBox<T> {}
impl<T: Pod> BStackBlock for BStackBox<T> {
type OnDisk = BoxOnDisk<T>;
unsafe fn from_range(range: BStackRange) -> Self {
BStackBox {
range,
_marker: PhantomData,
}
}
fn range(&self) -> BStackRange {
self.range
}
}
impl<T: Pod> TryCloneIn for BStackBox<T> {}
impl<T: Pod> BStackMove for BStackBox<T> {
type Fields<'a, A: BStackRaiiAllocator> = T;
fn bstack_move<A: BStackRaiiAllocator>(
owned: BStackOwned<Self>,
allocator: &A,
) -> io::Result<T> {
let me = owned.into_inner();
let value = match me.get(allocator.stack()) {
Ok(v) => v,
Err(e) => {
let _ = unsafe { dealloc_range(allocator, me.range) };
return Err(e);
}
};
unsafe { dealloc_range(allocator, me.range)? };
Ok(value)
}
}