mwc_libp2p_core/upgrade/
from_fn.rs

1// Copyright 2020 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::{Endpoint, upgrade::{InboundUpgrade, OutboundUpgrade, ProtocolName, UpgradeInfo}};
22
23use futures::prelude::*;
24use std::iter;
25
26/// Initializes a new [`FromFnUpgrade`].
27///
28/// # Example
29///
30/// ```
31/// # use mwc_libp2p_core::transport::{Transport, MemoryTransport};
32/// # use mwc_libp2p_core::upgrade;
33/// # use std::io;
34/// let _transport = MemoryTransport::default()
35///     .and_then(move |out, cp| {
36///         upgrade::apply(out, upgrade::from_fn("/foo/1", move |mut sock, endpoint| async move {
37///             if endpoint.is_dialer() {
38///                 upgrade::write_one(&mut sock, "some handshake data").await?;
39///             } else {
40///                 let handshake_data = upgrade::read_one(&mut sock, 1024).await?;
41///                 if handshake_data != b"some handshake data" {
42///                     return Err(upgrade::ReadOneError::from(io::Error::from(io::ErrorKind::Other)));
43///                 }
44///             }
45///             Ok(sock)
46///         }), cp, upgrade::Version::V1)
47///     });
48/// ```
49///
50pub fn from_fn<P, F, C, Fut, Out, Err>(protocol_name: P, fun: F) -> FromFnUpgrade<P, F>
51where
52    // Note: these bounds are there in order to help the compiler infer types
53    P: ProtocolName + Clone,
54    F: FnOnce(C, Endpoint) -> Fut,
55    Fut: Future<Output = Result<Out, Err>>,
56{
57    FromFnUpgrade { protocol_name, fun }
58}
59
60/// Implements the `UpgradeInfo`, `InboundUpgrade` and `OutboundUpgrade` traits.
61///
62/// The upgrade consists in calling the function passed when creating this struct.
63#[derive(Debug, Clone)]
64pub struct FromFnUpgrade<P, F> {
65    protocol_name: P,
66    fun: F,
67}
68
69impl<P, F> UpgradeInfo for FromFnUpgrade<P, F>
70where
71    P: ProtocolName + Clone,
72{
73    type Info = P;
74    type InfoIter = iter::Once<P>;
75
76    fn protocol_info(&self) -> Self::InfoIter {
77        iter::once(self.protocol_name.clone())
78    }
79}
80
81impl<C, P, F, Fut, Err, Out> InboundUpgrade<C> for FromFnUpgrade<P, F>
82where
83    P: ProtocolName + Clone,
84    F: FnOnce(C, Endpoint) -> Fut,
85    Fut: Future<Output = Result<Out, Err>>,
86{
87    type Output = Out;
88    type Error = Err;
89    type Future = Fut;
90
91    fn upgrade_inbound(self, sock: C, _: Self::Info) -> Self::Future {
92        (self.fun)(sock, Endpoint::Listener)
93    }
94}
95
96impl<C, P, F, Fut, Err, Out> OutboundUpgrade<C> for FromFnUpgrade<P, F>
97where
98    P: ProtocolName + Clone,
99    F: FnOnce(C, Endpoint) -> Fut,
100    Fut: Future<Output = Result<Out, Err>>,
101{
102    type Output = Out;
103    type Error = Err;
104    type Future = Fut;
105
106    fn upgrade_outbound(self, sock: C, _: Self::Info) -> Self::Future {
107        (self.fun)(sock, Endpoint::Dialer)
108    }
109}