heed_types/
serde_json.rs

1use std::borrow::Cow;
2
3use heed_traits::{BoxedError, BytesDecode, BytesEncode};
4use serde::{Deserialize, Serialize};
5
6/// Describes a type that is [`Serialize`]/[`Deserialize`] and uses `serde_json` to do so.
7///
8/// It can borrow bytes from the original slice.
9pub struct SerdeJson<T>(std::marker::PhantomData<T>);
10
11impl<'a, T: 'a> BytesEncode<'a> for SerdeJson<T>
12where
13    T: Serialize,
14{
15    type EItem = T;
16
17    fn bytes_encode(item: &Self::EItem) -> Result<Cow<[u8]>, BoxedError> {
18        serde_json::to_vec(item).map(Cow::Owned).map_err(Into::into)
19    }
20}
21
22impl<'a, T: 'a> BytesDecode<'a> for SerdeJson<T>
23where
24    T: Deserialize<'a>,
25{
26    type DItem = T;
27
28    fn bytes_decode(bytes: &'a [u8]) -> Result<Self::DItem, BoxedError> {
29        serde_json::from_slice(bytes).map_err(Into::into)
30    }
31}
32
33unsafe impl<T> Send for SerdeJson<T> {}
34
35unsafe impl<T> Sync for SerdeJson<T> {}