Skip to main content

hopr_transport/
socket.rs

1use futures::{Sink, Stream};
2use hopr_api::types::internal::routing::DestinationRouting;
3use hopr_protocol_app::prelude::{ApplicationDataIn, ApplicationDataOut};
4
5/// Represents the socket behavior of the hopr-lib spawned `Hopr` object.
6///
7/// HOPR socket aims to mimic a simple socket like write and read behavior for unstructured
8/// communication without the advanced session properties.
9///
10/// Typical use cases might be low level UDP based protocols that can wrap the HOPR socket
11/// without needing the advanced session functionality.
12pub struct HoprSocket<T, U> {
13    rx: T,
14    tx: U,
15}
16
17impl<T, U> From<(T, U)> for HoprSocket<T, U>
18where
19    T: Stream<Item = ApplicationDataIn> + Send + 'static,
20    U: Sink<(DestinationRouting, ApplicationDataOut)> + Send + Clone + 'static,
21{
22    fn from(value: (T, U)) -> Self {
23        Self {
24            rx: value.0,
25            tx: value.1,
26        }
27    }
28}
29
30impl<T, U> HoprSocket<T, U>
31where
32    T: Stream<Item = ApplicationDataIn> + Send + 'static,
33    U: Sink<(DestinationRouting, ApplicationDataOut)> + Send + Clone + 'static,
34{
35    pub fn reader(self) -> T {
36        self.rx
37    }
38
39    pub fn writer(&self) -> U {
40        self.tx.clone()
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use futures::channel::mpsc;
47    use hopr_api::types::internal::routing::DestinationRouting;
48    use hopr_protocol_app::prelude::{ApplicationDataIn, ApplicationDataOut};
49
50    use super::*;
51
52    #[tokio::test]
53    async fn socket_from_tuple_and_reader_writer_work() -> anyhow::Result<()> {
54        let (tx, _rx) = mpsc::unbounded::<(DestinationRouting, ApplicationDataOut)>();
55        let (_in_tx, in_rx) = mpsc::unbounded::<ApplicationDataIn>();
56
57        let socket = HoprSocket::from((in_rx, tx));
58        // writer() should return a clone of the sender
59        let _writer = socket.writer();
60        // reader() consumes the socket and returns the stream
61        let _reader = socket.reader();
62
63        Ok(())
64    }
65}