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> {
pub fn from_plain(owner: &'a storage::Shared) -> Option<Self> {
Self::new(owner.owner().as_ref()?.untag(), owner.as_ref())
}
pub fn from_scoped(owner: &'a storage::Shared<resident::State<'_>>) -> Option<Self> {
Self::new(owner.owner().registration()?, owner.as_ref())
}
fn new(identity: ptr::NonNull<()>, bytes: &'a [u8]) -> Option<Self> {
Some(Self {
registration: identity,
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())
}
}
const _: () = {
assert!(size_of::<View<'static>>() == 3 * size_of::<usize>());
assert!(size_of::<Option<View<'static>>>() == size_of::<View<'static>>());
};