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