1use crate::{
2 compat::{
3 string::{String, ToString},
4 vec::Vec,
5 },
6 errcode::{Kind, Origin},
7 Address, Error, LocalMessage, Result, Route,
8};
9use core::fmt::{self, Debug, Display, Formatter};
10use core::marker::PhantomData;
11use serde::{de::DeserializeOwned, Deserialize, Serialize};
12use serde_bare::ser::{Serializer, VecWrite};
13
14pub type Encoded = Vec<u8>;
16
17#[derive(Serialize, Deserialize, Clone, Debug, Hash, Ord, PartialOrd, Eq, PartialEq)]
26pub struct ProtocolId(String);
27
28impl ProtocolId {
29 pub fn none() -> Self {
31 Self(String::new())
32 }
33
34 #[allow(clippy::should_implement_trait)]
36 pub fn from_str(s: &str) -> Self {
37 Self(s.to_string())
38 }
39
40 pub fn as_str(&self) -> &str {
42 self.0.as_str()
43 }
44}
45
46impl From<&'static str> for ProtocolId {
47 fn from(s: &'static str) -> Self {
48 Self::from_str(s)
49 }
50}
51
52impl Display for ProtocolId {
53 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
54 write!(f, "{}", self.0)
55 }
56}
57
58pub trait Encodable {
60 fn encode(self) -> Result<Encoded>;
62}
63
64pub trait Decodable: Sized {
66 #[allow(clippy::ptr_arg)]
68 fn decode(e: &[u8]) -> Result<Self>;
69}
70
71pub trait Message: Encodable + Decodable + Send + 'static {}
73
74impl Message for () {}
75
76impl Message for String {}
77
78impl Message for Vec<u8> {}
79
80impl Encodable for Vec<u8> {
81 fn encode(self) -> Result<Encoded> {
82 Ok(self)
83 }
84}
85
86impl Decodable for Vec<u8> {
87 fn decode(e: &[u8]) -> Result<Self> {
88 Ok(e.to_vec())
89 }
90}
91
92impl Encodable for () {
93 fn encode(self) -> Result<Encoded> {
94 Ok(vec![])
95 }
96}
97
98impl Decodable for () {
99 fn decode(_e: &[u8]) -> Result<Self> {
100 Ok(())
101 }
102}
103
104impl Encodable for String {
105 fn encode(self) -> Result<Encoded> {
106 serialize(self)
107 }
108}
109
110impl Decodable for String {
111 fn decode(e: &[u8]) -> Result<Self> {
112 deserialize(e)
113 }
114}
115
116pub fn serialize<T: Serialize>(t: T) -> Result<Encoded> {
118 let mut vec = Vec::new();
119 let mut serializer = Serializer::new(VecWrite::new(&mut vec));
120 t.serialize(&mut serializer)?;
121 Ok(vec)
122}
123
124pub fn deserialize<T: DeserializeOwned>(encoded: &[u8]) -> Result<T> {
126 Ok(serde_bare::from_slice(encoded)?)
127}
128
129#[derive(Debug, Clone)]
131pub struct NeutralMessage(Vec<u8>);
132
133impl NeutralMessage {
134 pub fn into_vec(self) -> Vec<u8> {
136 self.0
137 }
138}
139
140impl From<Vec<u8>> for NeutralMessage {
141 fn from(v: Vec<u8>) -> Self {
142 Self(v)
143 }
144}
145
146impl From<NeutralMessage> for Vec<u8> {
147 fn from(m: NeutralMessage) -> Self {
148 m.0
149 }
150}
151
152impl Encodable for NeutralMessage {
153 fn encode(self) -> Result<Encoded> {
154 Ok(self.0)
155 }
156}
157
158impl Decodable for NeutralMessage {
159 fn decode(v: &[u8]) -> Result<Self> {
160 Ok(Self(v.to_vec()))
161 }
162}
163
164impl Message for NeutralMessage {}
165
166impl From<serde_bare::error::Error> for Error {
167 #[track_caller]
168 fn from(e: serde_bare::error::Error) -> Self {
169 Error::new(Origin::Core, Kind::Io, e)
170 }
171}
172
173impl From<minicbor::decode::Error> for Error {
174 #[track_caller]
175 fn from(e: minicbor::decode::Error) -> Self {
176 Error::new(Origin::Unknown, Kind::Invalid, e)
177 }
178}
179
180#[cfg(feature = "std")]
181impl<E> From<minicbor::encode::Error<E>> for Error
182where
183 E: std::error::Error + Send + Sync + 'static,
184{
185 #[track_caller]
186 fn from(e: minicbor::encode::Error<E>) -> Self {
187 Error::new(Origin::Unknown, Kind::Invalid, e)
188 }
189}
190
191#[cfg(not(feature = "std"))]
192impl<E: Display> From<minicbor::encode::Error<E>> for Error {
193 #[track_caller]
194 fn from(e: minicbor::encode::Error<E>) -> Self {
195 Error::new(Origin::Unknown, Kind::Invalid, e)
196 }
197}
198
199pub struct Routed<M: Message> {
215 phantom: PhantomData<M>,
217 msg_addr: Address,
219 src_addr: Address,
222 local_msg: LocalMessage,
224}
225
226impl<M: Message> Routed<M> {
227 pub fn new(msg_addr: Address, src_addr: Address, local_msg: LocalMessage) -> Self {
231 Self {
232 phantom: PhantomData,
233 msg_addr,
234 src_addr,
235 local_msg,
236 }
237 }
238
239 #[inline]
241 pub fn msg_addr(&self) -> &Address {
242 &self.msg_addr
243 }
244
245 #[inline]
247 pub fn src_addr(&self) -> &Address {
248 &self.src_addr
249 }
250
251 #[inline]
253 pub fn onward_route(&self) -> &Route {
254 self.local_msg.onward_route()
255 }
256
257 #[inline]
259 pub fn return_route(&self) -> &Route {
260 self.local_msg.return_route()
261 }
262 #[inline]
264 pub fn sender(&self) -> Result<&Address> {
265 self.local_msg.return_route().recipient()
266 }
267
268 #[inline]
270 pub fn into_body(self) -> Result<M> {
271 M::decode(&self.into_payload())
272 }
273
274 #[inline]
276 pub fn into_local_message(self) -> LocalMessage {
277 self.local_msg
278 }
279
280 #[inline]
282 pub fn local_message(&self) -> &LocalMessage {
283 &self.local_msg
284 }
285
286 #[inline]
288 pub fn payload(&self) -> &[u8] {
289 self.local_msg.payload()
290 }
291
292 #[inline]
294 pub fn into_payload(self) -> Vec<u8> {
295 self.local_msg.into_payload()
296 }
297}
298
299impl<M: Message + Debug> Debug for Routed<M> {
300 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
301 f.debug_struct("Routed")
302 .field("msg_addr", &self.msg_addr)
303 .field("src_addr", &self.src_addr)
304 .field("type", &core::any::type_name::<M>())
305 .field("local_msg", &self.local_msg)
306 .finish()
307 }
308}
309
310#[derive(Clone, Debug, PartialEq, Eq, crate::Message)]
349pub struct Any;
350
351impl Display for Any {
352 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
353 write!(f, "Any Message")
354 }
355}
356
357impl Encodable for Any {
358 fn encode(self) -> Result<Encoded> {
359 Ok(vec![])
360 }
361}
362
363impl Decodable for Any {
364 fn decode(_: &[u8]) -> Result<Self> {
365 Ok(Self)
366 }
367}