party_types/
channel.rs

1use std::{any::Any, fmt::Debug, marker::PhantomData};
2
3use crate::{Rx, Tx};
4use anyhow::{bail, Result};
5
6pub type Msg = Box<dyn Any + Send + 'static>;
7
8pub trait Transport: Clone {
9    type Rx;
10    type Tx;
11
12    /// Create a pair of channels, the first A->B, the second B->A
13    fn make_channel(&self) -> (Self::Tx, Self::Rx);
14    fn recv(&self, rx: &mut Self::Rx) -> Result<Msg>;
15    fn send(&self, tx: &mut Self::Tx, value: Msg) -> Result<()>;
16    fn choice(&self, rx1: &mut Self::Rx, rx2: &mut Self::Rx) -> Result<Either>;
17}
18
19pub enum Either {
20    Left(Msg),
21    Right(Msg),
22    Both(Msg),
23}
24
25pub struct Channel<To, Tr: Transport> {
26    pub(crate) tx: Tr::Tx,
27    pub(crate) rx: Tr::Rx,
28    pub(crate) tr: Tr,
29    _ph: PhantomData<To>,
30}
31
32impl<To, Tr> Clone for Channel<To, Tr>
33where
34    Tr: Transport,
35    Tr::Rx: Clone,
36    Tr::Tx: Clone,
37{
38    fn clone(&self) -> Self {
39        Self {
40            tx: self.tx.clone(),
41            rx: self.rx.clone(),
42            tr: self.tr.clone(),
43            _ph: PhantomData,
44        }
45    }
46}
47
48impl<To, Tr: Transport> Channel<To, Tr> {
49    pub(crate) fn new(tr: Tr, tx: Tr::Tx, rx: Tr::Rx) -> Self {
50        Self {
51            tx,
52            rx,
53            tr,
54            _ph: PhantomData,
55        }
56    }
57
58    pub fn recv<T: Debug + 'static, Cont>(
59        &mut self,
60        protocol: Rx<To, T, Cont>,
61    ) -> Result<(T, Cont)> {
62        let value = self.tr.recv(&mut self.rx)?;
63        let value = match value.downcast::<T>() {
64            Ok(v) => v,
65            Err(v) => bail!("got unexpected message {:?}", v),
66        };
67        Ok((*value, protocol.cont))
68    }
69
70    pub fn send<T: Send + 'static, Cont>(
71        &mut self,
72        protocol: Tx<To, T, Cont>,
73        value: T,
74    ) -> Result<Cont> {
75        self.tr.send(&mut self.tx, Box::new(value))?;
76        Ok(protocol.cont)
77    }
78}