use super::utils::{check_data_size, compress_data, decompress_data};
use super::Serializer;
use crate::error::{CacheError, Result};
use serde::{de::DeserializeOwned, Serialize};
#[derive(Clone, Debug)]
pub struct JsonSerializer {
compress: bool,
}
const MAX_JSON_SIZE: usize = 5 * 1024 * 1024;
impl JsonSerializer {
pub fn new() -> Self {
Self { compress: false }
}
pub fn with_compression() -> Self {
Self { compress: true }
}
}
impl Default for JsonSerializer {
fn default() -> Self {
Self::new()
}
}
impl Serializer for JsonSerializer {
fn serialize<T: Serialize>(&self, value: &T) -> Result<Vec<u8>> {
let json_bytes =
serde_json::to_vec(value).map_err(|e| CacheError::Serialization(e.to_string()))?;
if self.compress {
compress_data(&json_bytes)
} else {
Ok(json_bytes)
}
}
fn deserialize<T: DeserializeOwned>(&self, data: &[u8]) -> Result<T> {
check_data_size(data, MAX_JSON_SIZE, "JSON")?;
let json_bytes = if self.compress {
decompress_data(data)?
} else {
data.to_vec()
};
serde_json::from_slice(&json_bytes).map_err(|e| CacheError::Serialization(e.to_string()))
}
}