use bytes::{Buf, Bytes};
#[derive(Debug)]
pub enum Message<T, Data: Buf = Bytes> {
Header(T),
Payload(PayloadItem<Data>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PayloadItem<Data: Buf = Bytes> {
Chunk(Data),
Eof,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum PayloadSize {
Length(u64),
Chunked,
Empty,
}
impl PayloadSize {
#[inline(always)]
pub fn new_chunked() -> Self {
PayloadSize::Chunked
}
#[inline(always)]
pub fn new_empty() -> Self {
PayloadSize::Empty
}
#[inline(always)]
pub fn new_length(length: u64) -> Self {
PayloadSize::Length(length)
}
#[inline]
pub fn is_chunked(&self) -> bool {
matches!(self, PayloadSize::Chunked)
}
#[inline]
pub fn is_empty(&self) -> bool {
matches!(self, PayloadSize::Empty)
}
#[inline]
pub fn is_not_empty(&self) -> bool {
!self.is_empty()
}
}
impl<T> Message<T> {
#[inline]
pub fn is_payload(&self) -> bool {
matches!(self, Message::Payload(_))
}
#[inline]
pub fn is_header(&self) -> bool {
matches!(self, Message::Header(_))
}
pub fn into_payload_item(self) -> Option<PayloadItem> {
match self {
Message::Header(_) => None,
Message::Payload(payload_item) => Some(payload_item),
}
}
}
impl<T> From<Bytes> for Message<T> {
fn from(bytes: Bytes) -> Self {
Self::Payload(PayloadItem::Chunk(bytes))
}
}
impl<D: Buf> PayloadItem<D> {
#[inline]
pub fn is_eof(&self) -> bool {
matches!(self, PayloadItem::Eof)
}
#[inline]
pub fn is_chunk(&self) -> bool {
matches!(self, PayloadItem::Chunk(_))
}
}
impl PayloadItem {
pub fn as_bytes(&self) -> Option<&Bytes> {
match self {
PayloadItem::Chunk(bytes) => Some(bytes),
PayloadItem::Eof => None,
}
}
pub fn as_mut_bytes(&mut self) -> Option<&mut Bytes> {
match self {
PayloadItem::Chunk(bytes) => Some(bytes),
PayloadItem::Eof => None,
}
}
pub fn into_bytes(self) -> Option<Bytes> {
match self {
PayloadItem::Chunk(bytes) => Some(bytes),
PayloadItem::Eof => None,
}
}
}