use crate::StreamReadError;
use bytes::{Buf, Bytes};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Chunk(pub(crate) Bytes);
impl AsRef<[u8]> for Chunk {
fn as_ref(&self) -> &[u8] {
self.0.chunk()
}
}
impl From<Bytes> for Chunk {
fn from(bytes: Bytes) -> Self {
Self(bytes)
}
}
impl From<&'static [u8]> for Chunk {
fn from(bytes: &'static [u8]) -> Self {
Self(Bytes::from_static(bytes))
}
}
impl<const N: usize> From<&'static [u8; N]> for Chunk {
fn from(bytes: &'static [u8; N]) -> Self {
Self(Bytes::from_static(bytes))
}
}
impl PartialEq<[u8]> for Chunk {
fn eq(&self, other: &[u8]) -> bool {
self.as_ref() == other
}
}
impl PartialEq<&[u8]> for Chunk {
fn eq(&self, other: &&[u8]) -> bool {
self.as_ref() == *other
}
}
impl<const N: usize> PartialEq<&[u8; N]> for Chunk {
fn eq(&self, other: &&[u8; N]) -> bool {
self.as_ref() == other.as_slice()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StreamEvent {
Chunk(Chunk),
Gap,
Eof,
ReadError(StreamReadError),
}
impl StreamEvent {
pub fn chunk(chunk: impl Into<Chunk>) -> Self {
Self::Chunk(chunk.into())
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use assertr::AssertThat;
use assertr::actual::Actual;
use assertr::mode::Panic;
use tokio::sync::mpsc;
pub(crate) async fn event_receiver(events: Vec<StreamEvent>) -> mpsc::Receiver<StreamEvent> {
let (tx, rx) = mpsc::channel(events.len().max(1));
for event in events {
tx.send(event).await.unwrap();
}
drop(tx);
rx
}
pub(crate) trait StreamEventAssertions<'t> {
#[allow(clippy::wrong_self_convention)]
fn is_chunk(self) -> AssertThat<'t, Chunk, Panic>;
}
impl<'t> StreamEventAssertions<'t> for AssertThat<'t, StreamEvent, Panic> {
#[track_caller]
fn is_chunk(self) -> AssertThat<'t, Chunk, Panic> {
if !matches!(self.actual(), StreamEvent::Chunk(_)) {
let actual = self.actual();
self.fail(format_args!(
"Actual: {actual:#?}\n\nis not of expected variant: StreamEvent::Chunk"
));
}
self.map(|actual| match actual {
Actual::Owned(StreamEvent::Chunk(chunk)) => Actual::Owned(chunk),
Actual::Borrowed(StreamEvent::Chunk(chunk)) => Actual::Borrowed(chunk),
_ => unreachable!("variant verified above"),
})
}
}
}