use crate::content_type::ContentType;
use crate::error::StreamError;
use bytes::BytesMut;
pub trait StreamFormat {
fn format_name(&self) -> &'static str;
fn default_content_type(&self) -> &'static str;
fn accepts_content_type(&self, ct: &ContentType<'_>) -> bool {
ct.matches(self.default_content_type())
}
}
pub trait StreamFormatEncode<T>: StreamFormat {
type Encoder: ItemEncoder<T>;
fn encoder(&self) -> Self::Encoder;
}
pub trait ItemEncoder<T> {
fn prologue(&mut self, buf: &mut BytesMut) -> Result<(), StreamError> {
let _ = buf;
Ok(())
}
fn encode(&mut self, item: &T, index: u64, buf: &mut BytesMut) -> Result<(), StreamError>;
fn epilogue(&mut self, buf: &mut BytesMut) -> Result<(), StreamError> {
let _ = buf;
Ok(())
}
}
pub trait FrameParser<F, T> {
fn parse(&self, frame: F) -> Result<T, StreamError>;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct IdentityParser;
impl<T> FrameParser<Result<T, StreamError>, T> for IdentityParser {
fn parse(&self, frame: Result<T, StreamError>) -> Result<T, StreamError> {
frame
}
}
pub trait StreamFormatDecode<T>: StreamFormat {
type Frame;
type Framer: tokio_util::codec::Decoder<Item = Self::Frame, Error = StreamError> + Send;
type Parser: FrameParser<Self::Frame, T> + Send;
fn framer(&self, options: &DecodeOptions) -> Self::Framer;
fn parser(&self) -> Self::Parser;
}
pub trait DefaultFormat: Sized {
fn default_format() -> Self;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct DecodeOptions {
pub max_obj_len: usize,
pub buf_capacity: usize,
}
pub const DEFAULT_BUF_CAPACITY: usize = 8 * 1024;
impl DecodeOptions {
pub fn new() -> Self {
Self {
max_obj_len: usize::MAX,
buf_capacity: DEFAULT_BUF_CAPACITY,
}
}
pub fn max_obj_len(mut self, value: usize) -> Self {
self.max_obj_len = value;
self
}
pub fn buf_capacity(mut self, value: usize) -> Self {
self.buf_capacity = value;
self
}
}
impl Default for DecodeOptions {
fn default() -> Self {
Self::new()
}
}