use std::num::NonZero;
use crate::{base::Either, buffer, buffer::segments::scatter};
pub unsafe trait Scatter<'data> {
fn remaining(&self) -> usize;
fn seek(mut self, offset: usize) -> Option<Self>
where
Self: Sized,
{
if offset > self.remaining() {
return None;
}
scatter::Take::new(&mut self, offset).finish();
Some(self)
}
fn take_bytes(&mut self, limit: usize) -> scatter::Take<'_, 'data, Self>
where
Self: Sized,
{
scatter::Take::new(self, limit)
}
unsafe fn advance<const MAX: usize>(
&mut self,
cap: NonZero<usize>,
) -> buffer::raw::Chunk<'data, MAX>;
}
unsafe impl<'data, C: Scatter<'data> + ?Sized> Scatter<'data> for &mut C {
fn remaining(&self) -> usize {
C::remaining(self)
}
unsafe fn advance<const MAX: usize>(
&mut self,
cap: NonZero<usize>,
) -> buffer::raw::Chunk<'data, MAX> {
unsafe { C::advance(self, cap) }
}
}
unsafe impl<'data> Scatter<'data> for &'data [u8] {
fn remaining(&self) -> usize {
self.len()
}
unsafe fn advance<const MAX: usize>(
&mut self,
cap: NonZero<usize>,
) -> buffer::raw::Chunk<'data, MAX> {
let (bytes, suffix) = unsafe { self.split_at_unchecked(cap.get()) };
*self = suffix;
unsafe { buffer::raw::Chunk::new(bytes) }
}
}
unsafe impl<'a, L, R> Scatter<'a> for Either<L, R>
where
L: Scatter<'a>,
R: Scatter<'a>,
{
fn remaining(&self) -> usize {
match self {
Self::Left(cursor) => cursor.remaining(),
Self::Right(cursor) => cursor.remaining(),
}
}
unsafe fn advance<const MAX: usize>(
&mut self,
cap: NonZero<usize>,
) -> buffer::raw::Chunk<'a, MAX> {
match self {
Self::Left(cursor) => unsafe { cursor.advance(cap) },
Self::Right(cursor) => unsafe { cursor.advance(cap) },
}
}
}
const _: [(); 3 * std::mem::size_of::<usize>()] =
[(); std::mem::size_of::<Either<&'static [u8], &'static [u8]>>()];
mod queues;