libp2p_core/upgrade/
either.rs1use crate::{
22 either::EitherFuture,
23 upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo},
24};
25use either::Either;
26use futures::future;
27use std::iter::Map;
28
29impl<A, B> UpgradeInfo for Either<A, B>
30where
31 A: UpgradeInfo,
32 B: UpgradeInfo,
33{
34 type Info = Either<A::Info, B::Info>;
35 type InfoIter = Either<
36 Map<<A::InfoIter as IntoIterator>::IntoIter, fn(A::Info) -> Self::Info>,
37 Map<<B::InfoIter as IntoIterator>::IntoIter, fn(B::Info) -> Self::Info>,
38 >;
39
40 fn protocol_info(&self) -> Self::InfoIter {
41 match self {
42 Either::Left(a) => Either::Left(a.protocol_info().into_iter().map(Either::Left)),
43 Either::Right(b) => Either::Right(b.protocol_info().into_iter().map(Either::Right)),
44 }
45 }
46}
47
48impl<C, A, B, TA, TB, EA, EB> InboundUpgrade<C> for Either<A, B>
49where
50 A: InboundUpgrade<C, Output = TA, Error = EA>,
51 B: InboundUpgrade<C, Output = TB, Error = EB>,
52{
53 type Output = future::Either<TA, TB>;
54 type Error = Either<EA, EB>;
55 type Future = EitherFuture<A::Future, B::Future>;
56
57 fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
58 match (self, info) {
59 (Either::Left(a), Either::Left(info)) => {
60 EitherFuture::First(a.upgrade_inbound(sock, info))
61 }
62 (Either::Right(b), Either::Right(info)) => {
63 EitherFuture::Second(b.upgrade_inbound(sock, info))
64 }
65 _ => panic!("Invalid invocation of EitherUpgrade::upgrade_inbound"),
66 }
67 }
68}
69
70impl<C, A, B, TA, TB, EA, EB> OutboundUpgrade<C> for Either<A, B>
71where
72 A: OutboundUpgrade<C, Output = TA, Error = EA>,
73 B: OutboundUpgrade<C, Output = TB, Error = EB>,
74{
75 type Output = future::Either<TA, TB>;
76 type Error = Either<EA, EB>;
77 type Future = EitherFuture<A::Future, B::Future>;
78
79 fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
80 match (self, info) {
81 (Either::Left(a), Either::Left(info)) => {
82 EitherFuture::First(a.upgrade_outbound(sock, info))
83 }
84 (Either::Right(b), Either::Right(info)) => {
85 EitherFuture::Second(b.upgrade_outbound(sock, info))
86 }
87 _ => panic!("Invalid invocation of EitherUpgrade::upgrade_outbound"),
88 }
89 }
90}