1#![allow(unreachable_pub)]
23
24use std::iter::{Chain, Map};
25
26use either::Either;
27use futures::{future, future::MapOk, TryFutureExt};
28use libp2p_core::{
29 either::EitherFuture,
30 upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade, UpgradeInfo},
31};
32use libp2p_identity::PeerId;
33
34#[derive(Debug, Clone)]
39pub struct SelectSecurityUpgrade<A, B>(A, B);
40
41impl<A, B> SelectSecurityUpgrade<A, B> {
42 pub fn new(a: A, b: B) -> Self {
46 SelectSecurityUpgrade(a, b)
47 }
48}
49
50impl<A, B> UpgradeInfo for SelectSecurityUpgrade<A, B>
51where
52 A: UpgradeInfo,
53 B: UpgradeInfo,
54{
55 type Info = Either<A::Info, B::Info>;
56 type InfoIter = Chain<
57 Map<<A::InfoIter as IntoIterator>::IntoIter, fn(A::Info) -> Self::Info>,
58 Map<<B::InfoIter as IntoIterator>::IntoIter, fn(B::Info) -> Self::Info>,
59 >;
60
61 fn protocol_info(&self) -> Self::InfoIter {
62 let a = self
63 .0
64 .protocol_info()
65 .into_iter()
66 .map(Either::Left as fn(A::Info) -> _);
67 let b = self
68 .1
69 .protocol_info()
70 .into_iter()
71 .map(Either::Right as fn(B::Info) -> _);
72
73 a.chain(b)
74 }
75}
76
77impl<C, A, B, TA, TB, EA, EB> InboundConnectionUpgrade<C> for SelectSecurityUpgrade<A, B>
78where
79 A: InboundConnectionUpgrade<C, Output = (PeerId, TA), Error = EA>,
80 B: InboundConnectionUpgrade<C, Output = (PeerId, TB), Error = EB>,
81{
82 type Output = (PeerId, future::Either<TA, TB>);
83 type Error = Either<EA, EB>;
84 type Future = MapOk<
85 EitherFuture<A::Future, B::Future>,
86 fn(future::Either<(PeerId, TA), (PeerId, TB)>) -> (PeerId, future::Either<TA, TB>),
87 >;
88
89 fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
90 match info {
91 Either::Left(info) => EitherFuture::First(self.0.upgrade_inbound(sock, info)),
92 Either::Right(info) => EitherFuture::Second(self.1.upgrade_inbound(sock, info)),
93 }
94 .map_ok(future::Either::factor_first)
95 }
96}
97
98impl<C, A, B, TA, TB, EA, EB> OutboundConnectionUpgrade<C> for SelectSecurityUpgrade<A, B>
99where
100 A: OutboundConnectionUpgrade<C, Output = (PeerId, TA), Error = EA>,
101 B: OutboundConnectionUpgrade<C, Output = (PeerId, TB), Error = EB>,
102{
103 type Output = (PeerId, future::Either<TA, TB>);
104 type Error = Either<EA, EB>;
105 type Future = MapOk<
106 EitherFuture<A::Future, B::Future>,
107 fn(future::Either<(PeerId, TA), (PeerId, TB)>) -> (PeerId, future::Either<TA, TB>),
108 >;
109
110 fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
111 match info {
112 Either::Left(info) => EitherFuture::First(self.0.upgrade_outbound(sock, info)),
113 Either::Right(info) => EitherFuture::Second(self.1.upgrade_outbound(sock, info)),
114 }
115 .map_ok(future::Either::factor_first)
116 }
117}