sled_extensions/
encoding.rs1#[cfg(any(feature = "bincode", feature = "cbor", feature = "json"))]
2use serde::{de::DeserializeOwned, ser::Serialize};
3
4#[cfg(any(feature = "bincode", feature = "cbor", feature = "json"))]
5use crate::error::Error;
6
7use crate::error::Result;
8
9pub trait Encoding<T> {
13 fn encode(t: &T) -> Result<Vec<u8>>;
15
16 fn decode(slice: &[u8]) -> Result<T>;
18}
19
20#[derive(Clone, Debug, Default)]
21pub struct PlainEncoding;
23
24#[cfg(feature = "bincode")]
25#[derive(Clone, Debug, Default)]
26pub struct BincodeEncoding;
30
31#[cfg(feature = "cbor")]
32#[derive(Clone, Debug, Default)]
33pub struct CborEncoding;
35
36#[cfg(feature = "json")]
37#[derive(Clone, Debug, Default)]
38pub struct JsonEncoding;
40
41impl<T> Encoding<T> for PlainEncoding
42where
43 T: AsRef<[u8]>,
44 for<'a> T: From<&'a [u8]>,
45{
46 fn encode(t: &T) -> Result<Vec<u8>> {
47 Ok(t.as_ref().to_vec())
48 }
49
50 fn decode(slice: &[u8]) -> Result<T> {
51 Ok(slice.into())
52 }
53}
54
55#[cfg(feature = "bincode")]
56impl<T> Encoding<T> for BincodeEncoding
57where
58 T: DeserializeOwned + Serialize + 'static,
59{
60 fn encode(t: &T) -> Result<Vec<u8>> {
61 bincode::serialize(t).map_err(Error::BincodeSerialize)
62 }
63
64 fn decode(slice: &[u8]) -> Result<T> {
65 bincode::deserialize(slice).map_err(Error::BincodeDeserialize)
66 }
67}
68
69#[cfg(feature = "cbor")]
70impl<T> Encoding<T> for CborEncoding
71where
72 T: DeserializeOwned + Serialize + 'static,
73{
74 fn encode(t: &T) -> Result<Vec<u8>> {
75 serde_cbor::to_vec(t).map_err(Error::CborSerialize)
76 }
77
78 fn decode(slice: &[u8]) -> Result<T> {
79 serde_cbor::from_slice(slice).map_err(Error::CborDeserialize)
80 }
81}
82
83#[cfg(feature = "json")]
84impl<T> Encoding<T> for JsonEncoding
85where
86 T: DeserializeOwned + Serialize + 'static,
87{
88 fn encode(t: &T) -> Result<Vec<u8>> {
89 serde_json::to_vec(t).map_err(Error::JsonSerialize)
90 }
91
92 fn decode(slice: &[u8]) -> Result<T> {
93 serde_json::from_slice(slice).map_err(Error::JsonDeserialize)
94 }
95}