use serde::{Serialize, de::DeserializeOwned};
use crate::error::StoreError;
pub trait Codec {
fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, StoreError>;
fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, StoreError>;
}
#[cfg(feature = "json")]
pub struct JsonCodec;
#[cfg(feature = "json")]
impl Codec for JsonCodec {
fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, StoreError> {
serde_json::to_vec(value).map_err(|e| StoreError::Codec(e.to_string()))
}
fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, StoreError> {
serde_json::from_slice(bytes).map_err(|e| StoreError::Codec(e.to_string()))
}
}
#[cfg(feature = "postcard")]
pub struct PostcardCodec;
#[cfg(feature = "postcard")]
impl Codec for PostcardCodec {
fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, StoreError> {
postcard::to_allocvec(value).map_err(|e| StoreError::Codec(e.to_string()))
}
fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, StoreError> {
postcard::from_bytes(bytes).map_err(|e| StoreError::Codec(e.to_string()))
}
}