use std::marker::PhantomData;
use crate::{
dec::{DecodeError, Decoder},
enc::{EncodeError, Encoder},
};
use bytes::Bytes;
use serde::de::DeserializeOwned;
use serde::Serialize;
use thiserror::Error;
pub mod ws;
#[derive(Debug, Error, PartialEq, Eq)]
pub enum CodecLoadError {
#[error("Unsupported protocol {0}")]
UnsupportedProtocol(String),
#[error("Requested encoding method enabled")]
DisabledEncoding(&'static str),
}
pub trait TypedEncoder<T> {
type Error;
fn encode(&self, value: &T) -> Result<Bytes, Self::Error>;
fn encode_mut(&mut self, value: &T) -> Result<Bytes, Self::Error>;
}
pub trait TypedDecoder {
type Item;
type Error;
fn decode(&self, data: Bytes) -> Result<Self::Item, Self::Error>;
fn decode_mut(&mut self, data: Bytes) -> Result<Self::Item, Self::Error>;
}
pub trait Codec {
type SendItem;
type SendError;
type RecvItem;
type RecvError;
fn encoder(
&self,
) -> Box<dyn TypedEncoder<Self::SendItem, Error = Self::SendError> + Send + Sync>;
fn decoder(
&self,
) -> Box<dyn TypedDecoder<Item = Self::RecvItem, Error = Self::RecvError> + Send + Sync>;
}
pub struct WrappedEncoder<T, E> {
encoder: E,
_tag: PhantomData<T>,
}
impl<T, E> WrappedEncoder<T, E>
where
T: Serialize,
E: Encoder,
{
pub fn new(encoder: E) -> Self {
Self {
encoder,
_tag: PhantomData,
}
}
}
impl<T, E> TypedEncoder<T> for WrappedEncoder<T, E>
where
T: Serialize,
E: Encoder,
{
type Error = EncodeError;
#[inline]
fn encode(&self, value: &T) -> Result<Bytes, Self::Error> {
self.encoder.encode(value)
}
#[inline]
fn encode_mut(&mut self, value: &T) -> Result<Bytes, Self::Error> {
self.encoder.encode_mut(value)
}
}
pub struct WrappedDecoder<T, D> {
decoder: D,
_tag: PhantomData<T>,
}
impl<T, E> WrappedDecoder<T, E>
where
T: Serialize,
E: Decoder,
{
pub fn new(decoder: E) -> Self {
Self {
decoder,
_tag: PhantomData,
}
}
}
impl<T, D> TypedDecoder for WrappedDecoder<T, D>
where
T: DeserializeOwned,
D: Decoder,
{
type Item = T;
type Error = DecodeError;
#[inline]
fn decode(&self, data: Bytes) -> Result<Self::Item, Self::Error> {
self.decoder.decode(data)
}
#[inline]
fn decode_mut(&mut self, data: Bytes) -> Result<Self::Item, Self::Error> {
self.decoder.decode_mut(data)
}
}