polybox_core/payload.rs
1use crate::*;
2use std::any::Any;
3
4/// Holds a [`MessageSpecifier::Payload`]
5#[derive(Debug)]
6pub struct BoxedPayload(Box<dyn Any + Send>);
7
8impl BoxedPayload {
9 pub fn new<T>(payload: Payload<T>) -> Self
10 where
11 T: Message,
12 Payload<T>: Send + 'static,
13 {
14 Self(Box::new(payload))
15 }
16
17 pub fn downcast<T>(self) -> Result<Payload<T>, Self>
18 where
19 T: Message,
20 Payload<T>: 'static,
21 {
22 match self.0.downcast() {
23 Ok(cast) => Ok(*cast),
24 Err(boxed) => Err(Self(boxed)),
25 }
26 }
27
28 pub fn try_into_interface<T>(self) -> Result<T, Self>
29 where
30 T: Interface,
31 {
32 T::try_from_boxed_payload(self)
33 }
34}
35
36// #[cfg(test)]
37// mod test {
38// use super::*;
39
40// #[test]
41// fn boxed_msg() {
42// struct Msg1;
43// struct Msg2;
44
45// impl Message for Msg1 {
46// type Payload = Self;
47// type Returned = ();
48// fn into_payload(self) -> (Self::Payload, Self::Returned) {
49// (self, ())
50// }
51// fn from_payload(sent: Self::Payload, _returned: Self::Returned) -> Self {
52// sent
53// }
54// }
55
56// impl Message for Msg2 {
57// type Payload = Self;
58// type Returned = ();
59// fn into_payload(self) -> (Self::Payload, Self::Returned) {
60// (self, ())
61// }
62// fn from_payload(sent: Self::Payload, _returned: Self::Returned) -> Self {
63// sent
64// }
65// }
66
67// let boxed = AnyPayload::new::<Msg1>(Msg1);
68// assert!(boxed.downcast::<Msg1>().is_ok());
69
70// let boxed = AnyPayload::new::<Msg1>(Msg1);
71// assert!(boxed.downcast::<Msg2>().is_err());
72// }
73// }