libp2p_core/upgrade/
either.rs1use crate::{
22 either::{EitherOutput, EitherError, EitherFuture2, EitherName},
23 upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}
24};
25
26#[derive(Debug, Clone)]
28pub enum EitherUpgrade<A, B> { A(A), B(B) }
29
30impl<A, B> UpgradeInfo for EitherUpgrade<A, B>
31where
32 A: UpgradeInfo,
33 B: UpgradeInfo
34{
35 type Info = EitherName<A::Info, B::Info>;
36 type InfoIter = EitherIter<
37 <A::InfoIter as IntoIterator>::IntoIter,
38 <B::InfoIter as IntoIterator>::IntoIter
39 >;
40
41 fn protocol_info(&self) -> Self::InfoIter {
42 match self {
43 EitherUpgrade::A(a) => EitherIter::A(a.protocol_info().into_iter()),
44 EitherUpgrade::B(b) => EitherIter::B(b.protocol_info().into_iter())
45 }
46 }
47}
48
49impl<C, A, B, TA, TB, EA, EB> InboundUpgrade<C> for EitherUpgrade<A, B>
50where
51 A: InboundUpgrade<C, Output = TA, Error = EA>,
52 B: InboundUpgrade<C, Output = TB, Error = EB>,
53{
54 type Output = EitherOutput<TA, TB>;
55 type Error = EitherError<EA, EB>;
56 type Future = EitherFuture2<A::Future, B::Future>;
57
58 fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
59 match (self, info) {
60 (EitherUpgrade::A(a), EitherName::A(info)) => EitherFuture2::A(a.upgrade_inbound(sock, info)),
61 (EitherUpgrade::B(b), EitherName::B(info)) => EitherFuture2::B(b.upgrade_inbound(sock, info)),
62 _ => panic!("Invalid invocation of EitherUpgrade::upgrade_inbound")
63 }
64 }
65}
66
67impl<C, A, B, TA, TB, EA, EB> OutboundUpgrade<C> for EitherUpgrade<A, B>
68where
69 A: OutboundUpgrade<C, Output = TA, Error = EA>,
70 B: OutboundUpgrade<C, Output = TB, Error = EB>,
71{
72 type Output = EitherOutput<TA, TB>;
73 type Error = EitherError<EA, EB>;
74 type Future = EitherFuture2<A::Future, B::Future>;
75
76 fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
77 match (self, info) {
78 (EitherUpgrade::A(a), EitherName::A(info)) => EitherFuture2::A(a.upgrade_outbound(sock, info)),
79 (EitherUpgrade::B(b), EitherName::B(info)) => EitherFuture2::B(b.upgrade_outbound(sock, info)),
80 _ => panic!("Invalid invocation of EitherUpgrade::upgrade_outbound")
81 }
82 }
83}
84
85#[derive(Debug, Clone)]
87pub enum EitherIter<A, B> { A(A), B(B) }
88
89impl<A, B> Iterator for EitherIter<A, B>
90where
91 A: Iterator,
92 B: Iterator
93{
94 type Item = EitherName<A::Item, B::Item>;
95
96 fn next(&mut self) -> Option<Self::Item> {
97 match self {
98 EitherIter::A(a) => a.next().map(EitherName::A),
99 EitherIter::B(b) => b.next().map(EitherName::B)
100 }
101 }
102
103 fn size_hint(&self) -> (usize, Option<usize>) {
104 match self {
105 EitherIter::A(a) => a.size_hint(),
106 EitherIter::B(b) => b.size_hint()
107 }
108 }
109}
110