momento_functions_host/
encoding.rs1use std::convert::Infallible;
4
5pub trait EncodeError: std::error::Error + 'static {}
7
8impl EncodeError for Infallible {}
9
10impl EncodeError for serde_json::Error {}
11
12pub trait Encode {
14 type Error: EncodeError;
16 fn try_serialize(self) -> Result<impl Into<Vec<u8>>, Self::Error>;
18}
19
20impl Encode for Vec<u8> {
21 type Error = Infallible;
22 fn try_serialize(self) -> Result<impl Into<Vec<u8>>, Self::Error> {
23 Ok(self)
24 }
25}
26impl Encode for &[u8] {
27 type Error = Infallible;
28 fn try_serialize(self) -> Result<impl Into<Vec<u8>>, Self::Error> {
29 Ok(self)
30 }
31}
32impl Encode for String {
33 type Error = Infallible;
34 fn try_serialize(self) -> Result<impl Into<Vec<u8>>, Self::Error> {
35 Ok(self.into_bytes())
36 }
37}
38impl Encode for &str {
39 type Error = Infallible;
40 fn try_serialize(self) -> Result<impl Into<Vec<u8>>, Self::Error> {
41 Ok(self.as_bytes())
42 }
43}
44impl Encode for Option<Vec<u8>> {
45 type Error = Infallible;
46 fn try_serialize(self) -> Result<impl Into<Vec<u8>>, Self::Error> {
47 match self {
48 Some(v) => Ok(v),
49 None => Ok(Vec::new()),
50 }
51 }
52}
53impl Encode for () {
54 type Error = Infallible;
55 fn try_serialize(self) -> Result<impl Into<Vec<u8>>, Self::Error> {
56 Ok([])
57 }
58}
59impl Encode for serde_json::Value {
60 type Error = serde_json::Error;
61 fn try_serialize(self) -> Result<impl Into<Vec<u8>>, Self::Error> {
62 serde_json::to_vec(&self)
63 }
64}
65
66pub trait ExtractError: std::error::Error + 'static {}
68
69impl ExtractError for Infallible {}
70
71impl ExtractError for serde_json::Error {}
72
73pub trait Extract: Sized {
75 type Error: ExtractError;
77 fn extract(payload: Vec<u8>) -> Result<Self, Self::Error>;
79}
80
81impl Extract for Vec<u8> {
82 type Error = Infallible;
83 fn extract(payload: Vec<u8>) -> Result<Self, Self::Error> {
84 Ok(payload)
85 }
86}
87
88pub struct Json<T>(pub T);
90impl<T: serde::de::DeserializeOwned> Extract for Json<T> {
91 type Error = serde_json::Error;
92 fn extract(payload: Vec<u8>) -> Result<Self, Self::Error> {
93 Ok(Json(serde_json::from_slice(&payload)?))
94 }
95}
96
97impl<T: serde::Serialize> Encode for Json<T> {
98 type Error = serde_json::Error;
99 fn try_serialize(self) -> Result<impl Into<Vec<u8>>, Self::Error> {
100 serde_json::to_vec(&self.0)
101 }
102}