use std::{marker, ops};
use crate::buffer::{self, 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,
}
}
unsafe fn project<S: raw::Store>(source: &'id mut S, bounds: ops::Range<usize>) {
let range = Self {
bounds,
brand: marker::PhantomData,
};
S::project(unsafe { raw::Slice::from_parts(source, range) });
}
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 { Self::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 { Self::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 { Range::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, _) = buffer::Read::try_split(bytes)?;
let head = *head;
unsafe { Range::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>());