use std::{convert::Infallible, error::Error};
pub trait Encoder {
type Input: ?Sized;
type Output<'a>: AsRef<[u8]>;
type Error: Into<Box<dyn Error + Send + Sync>>;
fn encode<'a>(&mut self, input: &'a Self::Input) -> Result<Self::Output<'a>, Self::Error>;
}
pub trait Decoder {
type Output;
type Error: Into<Box<dyn Error + Send + Sync>>;
fn decode(&mut self, bytes: Vec<u8>) -> Result<Self::Output, Self::Error>;
}
pub struct BytesCodec;
impl Encoder for BytesCodec {
type Input = [u8];
type Output<'a> = &'a [u8];
type Error = Infallible;
fn encode<'a>(&mut self, input: &'a [u8]) -> Result<Self::Output<'a>, Self::Error> {
Ok(input)
}
}
impl Decoder for BytesCodec {
type Output = Vec<u8>;
type Error = Infallible;
fn decode(&mut self, bytes: Vec<u8>) -> Result<Vec<u8>, Self::Error> {
Ok(bytes)
}
}
pub trait Codec {
type Encoder: Encoder;
type Decoder: Decoder;
fn into_components(self) -> (Self::Encoder, Self::Decoder);
}
impl Codec for BytesCodec {
type Encoder = Self;
type Decoder = Self;
fn into_components(self) -> (Self::Encoder, Self::Decoder) {
(Self, Self)
}
}
impl<E: Encoder, D: Decoder> Codec for (E, D) {
type Encoder = E;
type Decoder = D;
fn into_components(self) -> (Self::Encoder, Self::Decoder) {
self
}
}