use assembly_core::buffer::{Buffer, CastError, MinimallyAligned, Repr};
use assembly_fdb_core::file::ArrayHeader;
use latin1str::Latin1Str;
use std::{convert::TryFrom, mem::size_of, ops::Deref, result::Result};
#[derive(Clone, Debug)]
pub struct BaseHandle<P: Deref, T>
where
<P as Deref>::Target: AsRef<[u8]>,
{
pub(super) mem: P,
pub(super) raw: T,
}
impl<P, T> Copy for BaseHandle<P, T>
where
P: Deref + Copy,
T: Copy,
<P as Deref>::Target: AsRef<[u8]>,
{
}
impl<P: Deref> BaseHandle<P, ()>
where
<P as Deref>::Target: AsRef<[u8]>,
{
pub fn new(mem: P) -> Self {
Self { mem, raw: () }
}
}
impl<T, P: Deref> BaseHandle<P, Option<T>>
where
<P as Deref>::Target: AsRef<[u8]>,
{
pub fn transpose(self) -> Option<BaseHandle<P, T>> {
if let Some(raw) = self.raw {
Some(BaseHandle { mem: self.mem, raw })
} else {
None
}
}
}
impl<P: Deref, T> BaseHandle<P, T>
where
<P as Deref>::Target: AsRef<[u8]>,
{
pub fn raw(&self) -> &T {
&self.raw
}
pub fn raw_mut(&mut self) -> &mut T {
&mut self.raw
}
pub fn as_bytes(&self) -> &[u8] {
self.mem.deref().as_ref()
}
pub fn replace<O>(self, raw: O) -> BaseHandle<P, O> {
BaseHandle { mem: self.mem, raw }
}
}
pub type Handle<'a, T> = BaseHandle<&'a [u8], T>;
impl<'a, T> Handle<'a, T> {
pub fn buf(self) -> &'a [u8] {
self.mem
}
pub fn into_raw(self) -> T {
self.raw
}
pub(crate) fn wrap<R>(&self, raw: R) -> Handle<'a, R> {
Handle { mem: self.mem, raw }
}
pub(crate) fn try_map_cast<R: MinimallyAligned>(
&self,
offset: u32,
) -> Result<RefHandle<'a, R>, CastError> {
let raw: &'a R = self.mem.try_cast(offset)?;
Ok(self.wrap(raw))
}
pub(crate) fn try_map_cast_slice<R: MinimallyAligned>(
&self,
offset: u32,
count: u32,
) -> Result<RefHandle<'a, [R]>, CastError> {
let raw: &'a [R] = self.mem.try_cast_slice(offset, count)?;
Ok(self.wrap(raw))
}
pub(crate) fn try_map_cast_array<R: MinimallyAligned>(
&self,
array: ArrayHeader,
) -> Result<RefHandle<'a, [R]>, CastError> {
let raw: &'a [R] = self.mem.try_cast_slice(array.base_offset, array.count)?;
Ok(self.wrap(raw))
}
pub fn map<X>(self, mapper: impl Fn(&'a [u8], T) -> X) -> Handle<'a, X> {
let raw = mapper(self.mem, self.raw);
Handle { mem: self.mem, raw }
}
pub fn map_val<X>(self, mapper: impl Fn(T) -> X) -> Handle<'a, X> {
let raw = mapper(self.raw);
Handle { mem: self.mem, raw }
}
pub fn try_map<X, E>(
self,
mapper: impl Fn(&'a [u8], T) -> Result<X, E>,
) -> Result<Handle<'a, X>, E> {
let raw = mapper(self.mem, self.raw)?;
Ok(Handle { mem: self.mem, raw })
}
}
impl<'a, T> Iterator for Handle<'a, T>
where
T: Iterator,
{
type Item = Handle<'a, T::Item>;
fn next(&mut self) -> Option<Self::Item> {
self.raw.next().map(|raw| Handle { mem: self.mem, raw })
}
}
#[allow(dead_code)]
pub trait TryFromHandle<'a, T>: Sized {
type Error;
fn try_from(h: Handle<'a, T>) -> Result<Self, Self::Error>;
}
pub type RefHandle<'a, T> = Handle<'a, &'a T>;
impl<'a, T> RefHandle<'a, [T]> {
pub fn get(self, index: usize) -> Option<RefHandle<'a, T>> {
self.raw.get(index).map(|raw| self.wrap(raw))
}
}
impl<'a, T: Repr> RefHandle<'a, T> {
pub fn map_extract(self) -> Handle<'a, T::Value> {
self.wrap(self.raw.extract())
}
}
pub type SliceIterHandle<'a, T> = Handle<'a, std::slice::Iter<'a, T>>;
pub fn get_string(buf: &[u8], offset: u32) -> Result<&Latin1Str, CastError> {
let start = offset as usize;
let buf = buf.get(start..).ok_or(CastError::OutOfBounds { offset })?;
Ok(Latin1Str::from_bytes_until_nul(buf))
}
pub fn get_i64(buf: &[u8], addr: u32) -> Result<i64, CastError> {
let start = addr as usize;
let end = start + size_of::<u64>();
if end > buf.len() {
Err(CastError::OutOfBounds { offset: addr })
} else {
let (_, base) = buf.split_at(start);
let (bytes, _) = base.split_at(size_of::<u64>());
let val = i64::from_le_bytes(<[u8; 8]>::try_from(bytes).unwrap());
Ok(val)
}
}