#![allow(missing_docs)]
use anyhow::Result;
use serde::{Deserialize, Serialize};
#[allow(clippy::missing_errors_doc)]
pub trait Codec: Send + Sync + Copy {
fn decode_slice<'a, T>(&self, v: &'a [u8]) -> Result<T>
where
T: Deserialize<'a>;
fn encode_to_vec<T>(&self, value: &T) -> Result<Vec<u8>>
where
T: ?Sized + Serialize;
}
#[derive(Clone, Copy)]
pub struct NaiveCodec {}
impl Codec for NaiveCodec {
fn decode_slice<'a, T>(&self, v: &'a [u8]) -> Result<T>
where
T: Deserialize<'a>,
{
Ok(serde_json::from_slice(v)?)
}
fn encode_to_vec<T>(&self, value: &T) -> Result<Vec<u8>>
where
T: ?Sized + Serialize,
{
Ok(serde_json::to_vec(value)?)
}
}
#[derive(Clone, Copy)]
pub struct BinaryCodec {}
impl Codec for BinaryCodec {
fn decode_slice<'a, T>(&self, v: &'a [u8]) -> Result<T>
where
T: Deserialize<'a>,
{
Ok(rmp_serde::from_slice(v)?)
}
fn encode_to_vec<T>(&self, value: &T) -> Result<Vec<u8>>
where
T: ?Sized + Serialize,
{
let val: serde_json::Value = serde_json::from_slice(&serde_json::to_vec(value)?)?;
Ok(rmp_serde::to_vec(&val)?)
}
}
#[derive(Clone, Copy)]
pub enum DynCodec {
Binary(BinaryCodec),
Naive(NaiveCodec),
}
impl Codec for DynCodec {
fn decode_slice<'a, T>(&self, v: &'a [u8]) -> Result<T>
where
T: Deserialize<'a>,
{
match self {
DynCodec::Binary(binary_codec) => binary_codec.decode_slice(v),
DynCodec::Naive(naive_codec) => naive_codec.decode_slice(v),
}
}
fn encode_to_vec<T>(&self, value: &T) -> Result<Vec<u8>>
where
T: ?Sized + Serialize,
{
match self {
DynCodec::Binary(binary_codec) => binary_codec.encode_to_vec(value),
DynCodec::Naive(naive_codec) => naive_codec.encode_to_vec(value),
}
}
}