use std::{marker, num, ops};
use crate::buffer::{bytes::scope, raw, storage, write::consume};
#[derive(Debug)]
pub struct Range<'id> {
pub(in crate::buffer::bytes::scope) bounds: ops::Range<usize>,
pub(in crate::buffer::bytes::scope) brand: marker::PhantomData<*mut &'id ()>,
}
impl<'id> Range<'id> {
pub(in crate::buffer::bytes::scope) fn new(
source: scope::View<'_, 'id>,
bounds: ops::Range<usize>,
) -> Self {
Self {
bounds,
brand: source.brand,
}
}
pub(in crate::buffer) fn try_consume<S: raw::Store>(
source: &'id mut S,
amount: usize,
) -> Result<(), consume::Error> {
let end = source.as_ref().len();
consume::Error::check(amount, end)?;
unsafe { scope::raw::project(source, amount..end) };
Ok(())
}
pub(in crate::buffer) fn select_max<const SUFFIX: bool, S: raw::Store>(
source: &'id mut S,
max: usize,
) -> usize {
let end = source.as_ref().len();
let amount = max.min(end);
let bounds = if SUFFIX { amount..end } else { 0..amount };
unsafe { scope::raw::project(source, bounds) };
amount
}
}
impl<S: raw::Store> raw::Selection<'_, S> {
pub(in crate::buffer) fn consume(self) {
let (source, amount) = self.into_parts();
let end = source.as_ref().len();
unsafe { scope::raw::project(source, amount..end) };
}
}
impl<O: storage::regions::End> storage::Shared<O> {
pub fn try_split<const N: usize>(mut self) -> Result<([u8; N], Self), consume::Error> {
let bytes = self.as_slice();
let end = bytes.len();
let head = bytes.first_chunk::<N>().ok_or_else(|| {
consume::Error::new(
num::NonZero::<usize>::MIN.saturating_add(N.saturating_sub(1)),
end,
)
})?;
let head = *head;
unsafe { scope::raw::project(&mut self, N..end) };
Ok((head, self))
}
}
impl Range<'_> {
pub(in crate::buffer) fn into_inner(self) -> ops::Range<usize> {
self.bounds
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
self.bounds.end - self.bounds.start
}
}
const _: () = assert!(size_of::<Range<'static>>() == 2 * size_of::<usize>());