momento_functions_host/
encoding.rs

1//! Encoding and decoding of byte array payloads
2
3use crate::FunctionResult;
4
5/// A payload which can be converted to a vector of bytes
6pub trait Encode {
7    /// Convert the payload to a vector of bytes
8    fn try_serialize(self) -> FunctionResult<impl Into<Vec<u8>>>;
9}
10
11impl Encode for Vec<u8> {
12    fn try_serialize(self) -> FunctionResult<impl Into<Vec<u8>>> {
13        Ok(self)
14    }
15}
16impl Encode for &[u8] {
17    fn try_serialize(self) -> FunctionResult<impl Into<Vec<u8>>> {
18        Ok(self)
19    }
20}
21impl Encode for String {
22    fn try_serialize(self) -> FunctionResult<impl Into<Vec<u8>>> {
23        Ok(self.into_bytes())
24    }
25}
26impl Encode for &str {
27    fn try_serialize(self) -> FunctionResult<impl Into<Vec<u8>>> {
28        Ok(self.as_bytes())
29    }
30}
31impl Encode for Option<Vec<u8>> {
32    fn try_serialize(self) -> FunctionResult<impl Into<Vec<u8>>> {
33        match self {
34            Some(v) => Ok(v),
35            None => Ok(Vec::new()),
36        }
37    }
38}
39impl Encode for () {
40    fn try_serialize(self) -> FunctionResult<impl Into<Vec<u8>>> {
41        Ok([])
42    }
43}
44
45/// Payload extractor for encodings
46pub trait Extract: Sized {
47    /// Convert from a payload to a value
48    fn extract(payload: Vec<u8>) -> FunctionResult<Self>;
49}
50
51impl Extract for Vec<u8> {
52    fn extract(payload: Vec<u8>) -> FunctionResult<Self> {
53        Ok(payload)
54    }
55}
56
57/// JSON encoding and decoding
58pub struct Json<T>(pub T);
59impl<T: serde::de::DeserializeOwned> Extract for Json<T> {
60    fn extract(payload: Vec<u8>) -> FunctionResult<Self> {
61        Ok(Json(serde_json::from_slice(&payload).map_err(|e| {
62            crate::Error::MessageError(format!("failed to deserialize json: {e}"))
63        })?))
64    }
65}
66impl<T: serde::Serialize> Encode for Json<T> {
67    fn try_serialize(self) -> FunctionResult<impl Into<Vec<u8>>> {
68        serde_json::to_vec(&self.0)
69            .map_err(|e| crate::Error::MessageError(format!("failed to serialize json: {e}")))
70    }
71}