1use serde::{de::DeserializeOwned, Serialize};
27
28#[cfg(feature = "simd-json")]
33pub fn from_slice<T: DeserializeOwned>(slice: &[u8]) -> Result<T, JsonError> {
34 let mut slice_copy = slice.to_vec();
36 simd_json::from_slice(&mut slice_copy).map_err(JsonError::SimdJson)
37}
38
39#[cfg(not(feature = "simd-json"))]
43pub fn from_slice<T: DeserializeOwned>(slice: &[u8]) -> Result<T, JsonError> {
44 serde_json::from_slice(slice).map_err(JsonError::SerdeJson)
45}
46
47#[cfg(feature = "simd-json")]
52pub fn from_slice_mut<T: DeserializeOwned>(slice: &mut [u8]) -> Result<T, JsonError> {
53 simd_json::from_slice(slice).map_err(JsonError::SimdJson)
54}
55
56#[cfg(not(feature = "simd-json"))]
60pub fn from_slice_mut<T: DeserializeOwned>(slice: &mut [u8]) -> Result<T, JsonError> {
61 serde_json::from_slice(slice).map_err(JsonError::SerdeJson)
62}
63
64#[cfg(feature = "simd-json")]
68pub fn to_vec<T: Serialize>(value: &T) -> Result<Vec<u8>, JsonError> {
69 simd_json::to_vec(value).map_err(JsonError::SimdJson)
70}
71
72#[cfg(not(feature = "simd-json"))]
76pub fn to_vec<T: Serialize>(value: &T) -> Result<Vec<u8>, JsonError> {
77 serde_json::to_vec(value).map_err(JsonError::SerdeJson)
78}
79
80#[cfg(feature = "simd-json")]
85pub fn to_vec_with_capacity<T: Serialize>(
86 value: &T,
87 capacity: usize,
88) -> Result<Vec<u8>, JsonError> {
89 let mut buf = Vec::with_capacity(capacity);
90 simd_json::to_writer(&mut buf, value).map_err(JsonError::SimdJson)?;
91 Ok(buf)
92}
93
94#[cfg(not(feature = "simd-json"))]
99pub fn to_vec_with_capacity<T: Serialize>(
100 value: &T,
101 capacity: usize,
102) -> Result<Vec<u8>, JsonError> {
103 let mut buf = Vec::with_capacity(capacity);
104 serde_json::to_writer(&mut buf, value).map_err(JsonError::SerdeJson)?;
105 Ok(buf)
106}
107
108pub fn to_vec_pretty<T: Serialize>(value: &T) -> Result<Vec<u8>, JsonError> {
110 serde_json::to_vec_pretty(value).map_err(JsonError::SerdeJson)
111}
112
113#[derive(Debug)]
115pub enum JsonError {
116 SerdeJson(serde_json::Error),
117 #[cfg(feature = "simd-json")]
118 SimdJson(simd_json::Error),
119}
120
121impl std::fmt::Display for JsonError {
122 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123 match self {
124 JsonError::SerdeJson(e) => write!(f, "{}", e),
125 #[cfg(feature = "simd-json")]
126 JsonError::SimdJson(e) => write!(f, "{}", e),
127 }
128 }
129}
130
131impl std::error::Error for JsonError {
132 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
133 match self {
134 JsonError::SerdeJson(e) => Some(e),
135 #[cfg(feature = "simd-json")]
136 JsonError::SimdJson(e) => Some(e),
137 }
138 }
139}
140
141impl From<serde_json::Error> for JsonError {
142 fn from(e: serde_json::Error) -> Self {
143 JsonError::SerdeJson(e)
144 }
145}
146
147#[cfg(feature = "simd-json")]
148impl From<simd_json::Error> for JsonError {
149 fn from(e: simd_json::Error) -> Self {
150 JsonError::SimdJson(e)
151 }
152}