pub trait Stateful {
type State: Copy;
fn capture_state(&self) -> Self::State;
fn restore_state(&mut self, state: Self::State);
}
#[derive(Clone, Copy)]
pub struct StateBlob {
pub bytes: [u8; 256],
pub len: usize,
}
impl StateBlob {
pub const EMPTY: Self = Self {
bytes: [0u8; 256],
len: 0,
};
pub fn from_value<T: Copy>(val: &T) -> Self {
let size = std::mem::size_of::<T>();
assert!(size <= 256, "StateBlob overflow: type too large");
let mut blob = Self::EMPTY;
blob.len = size;
unsafe {
std::ptr::copy_nonoverlapping(
val as *const T as *const u8,
blob.bytes.as_mut_ptr(),
size,
);
}
blob
}
pub fn to_value<T: Copy>(&self) -> T {
assert_eq!(self.len, std::mem::size_of::<T>());
unsafe { std::ptr::read(self.bytes.as_ptr() as *const T) }
}
}
impl Default for StateBlob {
fn default() -> Self {
Self::EMPTY
}
}