libp2p/builder/
select_muxer.rs1#![allow(unreachable_pub)]
22
23use either::Either;
24use futures::future;
25use libp2p_core::either::EitherFuture;
26use libp2p_core::upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade};
27use libp2p_core::UpgradeInfo;
28use std::iter::{Chain, Map};
29
30#[derive(Debug, Clone)]
31pub struct SelectMuxerUpgrade<A, B>(A, B);
32
33impl<A, B> SelectMuxerUpgrade<A, B> {
34 pub fn new(a: A, b: B) -> Self {
35 SelectMuxerUpgrade(a, b)
36 }
37}
38
39impl<A, B> UpgradeInfo for SelectMuxerUpgrade<A, B>
40where
41 A: UpgradeInfo,
42 B: UpgradeInfo,
43{
44 type Info = Either<A::Info, B::Info>;
45 type InfoIter = Chain<
46 Map<<A::InfoIter as IntoIterator>::IntoIter, fn(A::Info) -> Self::Info>,
47 Map<<B::InfoIter as IntoIterator>::IntoIter, fn(B::Info) -> Self::Info>,
48 >;
49
50 fn protocol_info(&self) -> Self::InfoIter {
51 let a = self
52 .0
53 .protocol_info()
54 .into_iter()
55 .map(Either::Left as fn(A::Info) -> _);
56 let b = self
57 .1
58 .protocol_info()
59 .into_iter()
60 .map(Either::Right as fn(B::Info) -> _);
61
62 a.chain(b)
63 }
64}
65
66impl<C, A, B, TA, TB, EA, EB> InboundConnectionUpgrade<C> for SelectMuxerUpgrade<A, B>
67where
68 A: InboundConnectionUpgrade<C, Output = TA, Error = EA>,
69 B: InboundConnectionUpgrade<C, Output = TB, Error = EB>,
70{
71 type Output = future::Either<TA, TB>;
72 type Error = Either<EA, EB>;
73 type Future = EitherFuture<A::Future, B::Future>;
74
75 fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
76 match info {
77 Either::Left(info) => EitherFuture::First(self.0.upgrade_inbound(sock, info)),
78 Either::Right(info) => EitherFuture::Second(self.1.upgrade_inbound(sock, info)),
79 }
80 }
81}
82
83impl<C, A, B, TA, TB, EA, EB> OutboundConnectionUpgrade<C> for SelectMuxerUpgrade<A, B>
84where
85 A: OutboundConnectionUpgrade<C, Output = TA, Error = EA>,
86 B: OutboundConnectionUpgrade<C, Output = TB, Error = EB>,
87{
88 type Output = future::Either<TA, TB>;
89 type Error = Either<EA, EB>;
90 type Future = EitherFuture<A::Future, B::Future>;
91
92 fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
93 match info {
94 Either::Left(info) => EitherFuture::First(self.0.upgrade_outbound(sock, info)),
95 Either::Right(info) => EitherFuture::Second(self.1.upgrade_outbound(sock, info)),
96 }
97 }
98}