libp2p_core/transport/
boxed.rs

1// Copyright 2018 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21use crate::transport::{ListenerId, Transport, TransportError, TransportEvent};
22use futures::{prelude::*, stream::FusedStream};
23use multiaddr::Multiaddr;
24use std::{
25    error::Error,
26    fmt, io,
27    pin::Pin,
28    task::{Context, Poll},
29};
30
31/// Creates a new [`Boxed`] transport from the given transport.
32pub(crate) fn boxed<T>(transport: T) -> Boxed<T::Output>
33where
34    T: Transport + Send + Unpin + 'static,
35    T::Error: Send + Sync,
36    T::Dial: Send + 'static,
37    T::ListenerUpgrade: Send + 'static,
38{
39    Boxed {
40        inner: Box::new(transport) as Box<_>,
41    }
42}
43
44/// A `Boxed` transport is a `Transport` whose `Dial`, `Listener`
45/// and `ListenerUpgrade` futures are `Box`ed and only the `Output`
46/// type is captured in a type variable.
47pub struct Boxed<O> {
48    inner: Box<dyn Abstract<O> + Send + Unpin>,
49}
50
51type Dial<O> = Pin<Box<dyn Future<Output = io::Result<O>> + Send>>;
52type ListenerUpgrade<O> = Pin<Box<dyn Future<Output = io::Result<O>> + Send>>;
53
54trait Abstract<O> {
55    fn listen_on(
56        &mut self,
57        id: ListenerId,
58        addr: Multiaddr,
59    ) -> Result<(), TransportError<io::Error>>;
60    fn remove_listener(&mut self, id: ListenerId) -> bool;
61    fn dial(&mut self, addr: Multiaddr) -> Result<Dial<O>, TransportError<io::Error>>;
62    fn dial_as_listener(&mut self, addr: Multiaddr) -> Result<Dial<O>, TransportError<io::Error>>;
63    fn address_translation(&self, server: &Multiaddr, observed: &Multiaddr) -> Option<Multiaddr>;
64    fn poll(
65        self: Pin<&mut Self>,
66        cx: &mut Context<'_>,
67    ) -> Poll<TransportEvent<ListenerUpgrade<O>, io::Error>>;
68}
69
70impl<T, O> Abstract<O> for T
71where
72    T: Transport<Output = O> + 'static,
73    T::Error: Send + Sync,
74    T::Dial: Send + 'static,
75    T::ListenerUpgrade: Send + 'static,
76{
77    fn listen_on(
78        &mut self,
79        id: ListenerId,
80        addr: Multiaddr,
81    ) -> Result<(), TransportError<io::Error>> {
82        Transport::listen_on(self, id, addr).map_err(|e| e.map(box_err))
83    }
84
85    fn remove_listener(&mut self, id: ListenerId) -> bool {
86        Transport::remove_listener(self, id)
87    }
88
89    fn dial(&mut self, addr: Multiaddr) -> Result<Dial<O>, TransportError<io::Error>> {
90        let fut = Transport::dial(self, addr)
91            .map(|r| r.map_err(box_err))
92            .map_err(|e| e.map(box_err))?;
93        Ok(Box::pin(fut) as Dial<_>)
94    }
95
96    fn dial_as_listener(&mut self, addr: Multiaddr) -> Result<Dial<O>, TransportError<io::Error>> {
97        let fut = Transport::dial_as_listener(self, addr)
98            .map(|r| r.map_err(box_err))
99            .map_err(|e| e.map(box_err))?;
100        Ok(Box::pin(fut) as Dial<_>)
101    }
102
103    fn address_translation(&self, server: &Multiaddr, observed: &Multiaddr) -> Option<Multiaddr> {
104        Transport::address_translation(self, server, observed)
105    }
106
107    fn poll(
108        self: Pin<&mut Self>,
109        cx: &mut Context<'_>,
110    ) -> Poll<TransportEvent<ListenerUpgrade<O>, io::Error>> {
111        self.poll(cx).map(|event| {
112            event
113                .map_upgrade(|upgrade| {
114                    let up = upgrade.map_err(box_err);
115                    Box::pin(up) as ListenerUpgrade<O>
116                })
117                .map_err(box_err)
118        })
119    }
120}
121
122impl<O> fmt::Debug for Boxed<O> {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        write!(f, "BoxedTransport")
125    }
126}
127
128impl<O> Transport for Boxed<O> {
129    type Output = O;
130    type Error = io::Error;
131    type ListenerUpgrade = ListenerUpgrade<O>;
132    type Dial = Dial<O>;
133
134    fn listen_on(
135        &mut self,
136        id: ListenerId,
137        addr: Multiaddr,
138    ) -> Result<(), TransportError<Self::Error>> {
139        self.inner.listen_on(id, addr)
140    }
141
142    fn remove_listener(&mut self, id: ListenerId) -> bool {
143        self.inner.remove_listener(id)
144    }
145
146    fn dial(&mut self, addr: Multiaddr) -> Result<Self::Dial, TransportError<Self::Error>> {
147        self.inner.dial(addr)
148    }
149
150    fn dial_as_listener(
151        &mut self,
152        addr: Multiaddr,
153    ) -> Result<Self::Dial, TransportError<Self::Error>> {
154        self.inner.dial_as_listener(addr)
155    }
156
157    fn address_translation(&self, server: &Multiaddr, observed: &Multiaddr) -> Option<Multiaddr> {
158        self.inner.address_translation(server, observed)
159    }
160
161    fn poll(
162        mut self: Pin<&mut Self>,
163        cx: &mut Context<'_>,
164    ) -> Poll<TransportEvent<Self::ListenerUpgrade, Self::Error>> {
165        Pin::new(self.inner.as_mut()).poll(cx)
166    }
167}
168
169impl<O> Stream for Boxed<O> {
170    type Item = TransportEvent<ListenerUpgrade<O>, io::Error>;
171
172    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
173        Transport::poll(self, cx).map(Some)
174    }
175}
176
177impl<O> FusedStream for Boxed<O> {
178    fn is_terminated(&self) -> bool {
179        false
180    }
181}
182
183fn box_err<E: Error + Send + Sync + 'static>(e: E) -> io::Error {
184    io::Error::new(io::ErrorKind::Other, e)
185}