sled_extensions/
encoding.rs

1#[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
9/// The Encoding trait
10///
11/// By implementing this trait, a custom data format can be used to store information in Sled
12pub trait Encoding<T> {
13    /// Encoding data to bytes
14    fn encode(t: &T) -> Result<Vec<u8>>;
15
16    /// Decoding data from bytes
17    fn decode(slice: &[u8]) -> Result<T>;
18}
19
20#[derive(Clone, Debug, Default)]
21/// A 'Plain' Encoding that only works on values that are already bytes
22pub struct PlainEncoding;
23
24#[cfg(feature = "bincode")]
25#[derive(Clone, Debug, Default)]
26/// An Encoding backed by bincode to store serde-compatible types
27///
28/// Note that Bincode cannot store certain kinds of types, such as untagged enums
29pub struct BincodeEncoding;
30
31#[cfg(feature = "cbor")]
32#[derive(Clone, Debug, Default)]
33/// An Encoding backed by bincode to store serde-compatible types
34pub struct CborEncoding;
35
36#[cfg(feature = "json")]
37#[derive(Clone, Debug, Default)]
38/// An Encoding backed by json to store serde-compatible types
39pub 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}