use std::{marker, num, ptr};
use crate::buffer::{resident, storage};
#[derive(Clone, Copy)]
pub struct View<'a> {
registration: ptr::NonNull<()>,
start: ptr::NonNull<u8>,
len: num::NonZero<usize>,
scope: marker::PhantomData<&'a [u8]>,
}
impl<'a> View<'a> {
fn new(registration: ptr::NonNull<()>, bytes: &'a [u8]) -> Option<Self> {
Some(Self {
registration,
start: ptr::NonNull::from(bytes).cast(),
len: num::NonZero::new(bytes.len())?,
scope: marker::PhantomData,
})
}
pub const fn is_empty(&self) -> bool {
false
}
pub const fn len(&self) -> usize {
self.len.get()
}
pub fn contains(&self, other: &View<'_>) -> bool {
self.registration == other.registration
&& self.start <= other.start
&& other.end() <= self.end()
}
fn end(&self) -> *const u8 {
self.start.as_ptr().wrapping_add(self.len())
}
}
impl storage::Shared {
#[doc(hidden)]
pub fn backing(&self) -> Option<View<'_>> {
View::new(self.owner().as_ref()?.untag(), self.as_slice())
}
}
impl resident::Shared<'_> {
#[doc(hidden)]
pub fn backing(&self) -> Option<View<'_>> {
View::new(self.owner().registration()?, self.as_slice())
}
}
const _: () = {
assert!(size_of::<View<'static>>() == 3 * size_of::<usize>());
assert!(size_of::<Option<View<'static>>>() == size_of::<View<'static>>());
};