1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#[cfg(feature = "flex")]
mod flex {
    use flexbuffers::{DeserializationError, SerializationError};

    #[derive(Debug, thiserror::Error)]
    #[error("{0}")]
    pub struct DecodeError(DeserializationError);

    #[derive(Debug, thiserror::Error)]
    #[error("{0}")]
    pub struct EncodeError(SerializationError);

    #[inline]
    pub fn to_vec<T: serde::Serialize>(value: &T) -> Result<Vec<u8>, EncodeError> {
        flexbuffers::to_vec(value).map_err(EncodeError)
    }

    #[inline]
    pub fn from_slice<T: serde::de::DeserializeOwned>(slice: &[u8]) -> Result<T, DecodeError> {
        flexbuffers::from_slice(&slice).map_err(DecodeError)
    }
}

#[allow(dead_code)]
#[cfg(feature = "json")]
mod json {
    use serde_json::Error;

    #[derive(Debug, thiserror::Error)]
    #[error("{0}")]
    pub struct DecodeError(#[from] Error);

    #[derive(Debug, thiserror::Error)]
    #[error("{0}")]
    pub struct EncodeError(Error);

    #[inline]
    pub fn to_vec<T: serde::Serialize>(value: &T) -> Result<Vec<u8>, EncodeError> {
        serde_json::to_vec(value).map_err(EncodeError)
    }

    #[inline]
    pub fn from_slice<T: serde::de::DeserializeOwned>(slice: &[u8]) -> Result<T, DecodeError> {
        serde_json::from_slice(slice).map_err(DecodeError)
    }
}

#[cfg(feature = "flex")]
pub use flex::*;

#[cfg(feature = "json")]
pub use json::*;