Skip to main content

momento_functions_bytes/
encoding.rs

1//! Encoding and decoding of byte array payloads
2
3use std::convert::Infallible;
4
5use crate::Data;
6
7/// Required to be implemented by encode error types.
8pub trait EncodeError: std::error::Error + 'static {}
9
10impl EncodeError for Infallible {}
11
12impl EncodeError for serde_json::Error {}
13
14/// A payload which can be converted to a vector of bytes
15pub trait Encode {
16    /// The error type returned when encoding fails.
17    type Error: EncodeError;
18    /// Convert the payload to a vector of bytes
19    fn try_serialize(self) -> Result<Data, Self::Error>;
20}
21
22// A pass-through for IO convenience
23impl Encode for Data {
24    type Error = Infallible;
25    fn try_serialize(self) -> Result<Data, Self::Error> {
26        Ok(self)
27    }
28}
29impl Encode for Vec<u8> {
30    type Error = Infallible;
31    fn try_serialize(self) -> Result<Data, Self::Error> {
32        Ok(self.into())
33    }
34}
35impl Encode for &[u8] {
36    type Error = Infallible;
37    fn try_serialize(self) -> Result<Data, Self::Error> {
38        Ok(self.to_vec().into())
39    }
40}
41impl Encode for String {
42    type Error = Infallible;
43    fn try_serialize(self) -> Result<Data, Self::Error> {
44        Ok(self.into_bytes().into())
45    }
46}
47impl Encode for &str {
48    type Error = Infallible;
49    fn try_serialize(self) -> Result<Data, Self::Error> {
50        Ok(self.as_bytes().to_vec().into())
51    }
52}
53impl Encode for Option<Vec<u8>> {
54    type Error = Infallible;
55    fn try_serialize(self) -> Result<Data, Self::Error> {
56        match self {
57            Some(v) => Ok(v.into()),
58            None => Ok(Vec::new().into()),
59        }
60    }
61}
62impl Encode for () {
63    type Error = Infallible;
64    fn try_serialize(self) -> Result<Data, Self::Error> {
65        Ok(Vec::new().into())
66    }
67}
68impl Encode for serde_json::Value {
69    type Error = serde_json::Error;
70    fn try_serialize(self) -> Result<Data, Self::Error> {
71        serde_json::to_vec(&self).map(Into::into)
72    }
73}
74
75/// Required to be implemented by extract error types.
76pub trait ExtractError: std::error::Error + 'static {}
77
78impl ExtractError for Infallible {}
79
80impl ExtractError for serde_json::Error {}
81
82/// Payload extractor for encodings
83pub trait Extract: Sized {
84    /// The error type returned when extraction fails.
85    type Error: ExtractError;
86    /// Convert from a payload to a value
87    fn extract(payload: Data) -> Result<Self, Self::Error>;
88}
89
90impl Extract for Vec<u8> {
91    type Error = Infallible;
92    fn extract(payload: Data) -> Result<Self, Self::Error> {
93        Ok(payload.into_bytes())
94    }
95}
96
97impl Extract for Data {
98    type Error = Infallible;
99
100    fn extract(payload: Data) -> Result<Self, Self::Error> {
101        Ok(payload)
102    }
103}
104
105/// JSON encoding and decoding
106pub struct Json<T>(pub T);
107impl<T: serde::de::DeserializeOwned> Extract for Json<T> {
108    type Error = serde_json::Error;
109    fn extract(payload: Data) -> Result<Self, Self::Error> {
110        Ok(Json(serde_json::from_slice(&payload.into_bytes())?))
111    }
112}
113
114impl<T: serde::Serialize> Encode for Json<T> {
115    type Error = serde_json::Error;
116    fn try_serialize(self) -> Result<Data, Self::Error> {
117        serde_json::to_vec(&self.0).map(Into::into)
118    }
119}