use core::cmp;
use zerocopy::{FromBytes, Immutable, KnownLayout, Unaligned};
use crate::error::Result;
use crate::io;
use crate::io::Read;
macro_rules! iter_try {
($e:expr_2021) => {
match $e {
Ok(x) => x,
Err(e) => return Some(Err(e.into())),
}
};
}
pub(crate) struct ReadOnlyCursor<'a>(&'a [u8]);
impl<'a> ReadOnlyCursor<'a> {
pub(crate) fn new(data: &'a [u8]) -> Self {
Self(data)
}
}
impl<'a> Read for ReadOnlyCursor<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let bytes_to_read = cmp::min(self.0.len(), buf.len());
buf[..bytes_to_read].copy_from_slice(&self.0[..bytes_to_read]);
self.0 = &self.0[bytes_to_read..];
Ok(bytes_to_read)
}
}
#[inline(always)]
#[track_caller]
pub(crate) fn read_pod<T, Pod, const LEN: usize>(r: &mut T) -> Result<Pod>
where
T: Read,
Pod: FromBytes + Immutable + KnownLayout + Unaligned,
{
let mut bytes = [0u8; LEN];
r.read_exact(&mut bytes)?;
Ok(Pod::read_from_bytes(&bytes).unwrap())
}
pub(crate) fn pod_from_prefix<Pod, const LEN: usize>(bytes: &[u8]) -> Option<Pod>
where
Pod: FromBytes + Immutable + KnownLayout + Unaligned,
{
let prefix = bytes.get(..LEN)?;
Pod::read_from_bytes(prefix).ok()
}