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 #[allow(dead_code)]
46 pub fn new(a: A, b: B) -> Self {
47 SelectSecurityUpgrade(a, b)
48 }
49}
50
51impl<A, B> UpgradeInfo for SelectSecurityUpgrade<A, B>
52where
53 A: UpgradeInfo,
54 B: UpgradeInfo,
55{
56 type Info = Either<A::Info, B::Info>;
57 type InfoIter = Chain<
58 Map<<A::InfoIter as IntoIterator>::IntoIter, fn(A::Info) -> Self::Info>,
59 Map<<B::InfoIter as IntoIterator>::IntoIter, fn(B::Info) -> Self::Info>,
60 >;
61
62 fn protocol_info(&self) -> Self::InfoIter {
63 let a = self
64 .0
65 .protocol_info()
66 .into_iter()
67 .map(Either::Left as fn(A::Info) -> _);
68 let b = self
69 .1
70 .protocol_info()
71 .into_iter()
72 .map(Either::Right as fn(B::Info) -> _);
73
74 a.chain(b)
75 }
76}
77
78impl<C, A, B, TA, TB, EA, EB> InboundConnectionUpgrade<C> for SelectSecurityUpgrade<A, B>
79where
80 A: InboundConnectionUpgrade<C, Output = (PeerId, TA), Error = EA>,
81 B: InboundConnectionUpgrade<C, Output = (PeerId, TB), Error = EB>,
82{
83 type Output = (PeerId, future::Either<TA, TB>);
84 type Error = Either<EA, EB>;
85 type Future = MapOk<
86 EitherFuture<A::Future, B::Future>,
87 fn(future::Either<(PeerId, TA), (PeerId, TB)>) -> (PeerId, future::Either<TA, TB>),
88 >;
89
90 fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
91 match info {
92 Either::Left(info) => EitherFuture::First(self.0.upgrade_inbound(sock, info)),
93 Either::Right(info) => EitherFuture::Second(self.1.upgrade_inbound(sock, info)),
94 }
95 .map_ok(future::Either::factor_first)
96 }
97}
98
99impl<C, A, B, TA, TB, EA, EB> OutboundConnectionUpgrade<C> for SelectSecurityUpgrade<A, B>
100where
101 A: OutboundConnectionUpgrade<C, Output = (PeerId, TA), Error = EA>,
102 B: OutboundConnectionUpgrade<C, Output = (PeerId, TB), Error = EB>,
103{
104 type Output = (PeerId, future::Either<TA, TB>);
105 type Error = Either<EA, EB>;
106 type Future = MapOk<
107 EitherFuture<A::Future, B::Future>,
108 fn(future::Either<(PeerId, TA), (PeerId, TB)>) -> (PeerId, future::Either<TA, TB>),
109 >;
110
111 fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
112 match info {
113 Either::Left(info) => EitherFuture::First(self.0.upgrade_outbound(sock, info)),
114 Either::Right(info) => EitherFuture::Second(self.1.upgrade_outbound(sock, info)),
115 }
116 .map_ok(future::Either::factor_first)
117 }
118}