use serde::{de::DeserializeOwned, Serialize};
#[cfg(feature = "simd-json")]
pub fn from_slice<T: DeserializeOwned>(slice: &[u8]) -> Result<T, JsonError> {
let mut slice_copy = slice.to_vec();
simd_json::from_slice(&mut slice_copy).map_err(JsonError::SimdJson)
}
#[cfg(not(feature = "simd-json"))]
pub fn from_slice<T: DeserializeOwned>(slice: &[u8]) -> Result<T, JsonError> {
serde_json::from_slice(slice).map_err(JsonError::SerdeJson)
}
#[cfg(feature = "simd-json")]
#[allow(dead_code)]
pub fn from_slice_mut<T: DeserializeOwned>(slice: &mut [u8]) -> Result<T, JsonError> {
simd_json::from_slice(slice).map_err(JsonError::SimdJson)
}
#[cfg(not(feature = "simd-json"))]
#[allow(dead_code)]
pub fn from_slice_mut<T: DeserializeOwned>(slice: &mut [u8]) -> Result<T, JsonError> {
serde_json::from_slice(slice).map_err(JsonError::SerdeJson)
}
#[cfg(feature = "simd-json")]
#[allow(dead_code)]
pub fn to_vec<T: Serialize>(value: &T) -> Result<Vec<u8>, JsonError> {
simd_json::to_vec(value).map_err(JsonError::SimdJson)
}
#[cfg(not(feature = "simd-json"))]
#[allow(dead_code)]
pub fn to_vec<T: Serialize>(value: &T) -> Result<Vec<u8>, JsonError> {
serde_json::to_vec(value).map_err(JsonError::SerdeJson)
}
#[cfg(feature = "simd-json")]
pub fn to_vec_with_capacity<T: Serialize>(
value: &T,
capacity: usize,
) -> Result<Vec<u8>, JsonError> {
let mut buf = Vec::with_capacity(capacity);
simd_json::to_writer(&mut buf, value).map_err(JsonError::SimdJson)?;
Ok(buf)
}
#[cfg(not(feature = "simd-json"))]
pub fn to_vec_with_capacity<T: Serialize>(
value: &T,
capacity: usize,
) -> Result<Vec<u8>, JsonError> {
let mut buf = Vec::with_capacity(capacity);
serde_json::to_writer(&mut buf, value).map_err(JsonError::SerdeJson)?;
Ok(buf)
}
#[allow(dead_code)]
pub fn to_vec_pretty<T: Serialize>(value: &T) -> Result<Vec<u8>, JsonError> {
serde_json::to_vec_pretty(value).map_err(JsonError::SerdeJson)
}
#[derive(Debug)]
pub enum JsonError {
SerdeJson(serde_json::Error),
#[cfg(feature = "simd-json")]
SimdJson(simd_json::Error),
}
impl std::fmt::Display for JsonError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
JsonError::SerdeJson(e) => write!(f, "{}", e),
#[cfg(feature = "simd-json")]
JsonError::SimdJson(e) => write!(f, "{}", e),
}
}
}
impl std::error::Error for JsonError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
JsonError::SerdeJson(e) => Some(e),
#[cfg(feature = "simd-json")]
JsonError::SimdJson(e) => Some(e),
}
}
}
impl From<serde_json::Error> for JsonError {
fn from(e: serde_json::Error) -> Self {
JsonError::SerdeJson(e)
}
}
#[cfg(feature = "simd-json")]
impl From<simd_json::Error> for JsonError {
fn from(e: simd_json::Error) -> Self {
JsonError::SimdJson(e)
}
}