momento_functions_host/
encoding.rs1use crate::FunctionResult;
4
5pub trait Encode {
7 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
45pub trait Extract: Sized {
47 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
57pub 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}