libp2p_core/upgrade/
optional.rs1use crate::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo};
22
23#[derive(Debug, Clone)]
28pub struct OptionalUpgrade<T>(Option<T>);
29
30impl<T> OptionalUpgrade<T> {
31 pub fn some(inner: T) -> Self {
33 OptionalUpgrade(Some(inner))
34 }
35
36 pub fn none() -> Self {
38 OptionalUpgrade(None)
39 }
40}
41
42impl<T> UpgradeInfo for OptionalUpgrade<T>
43where
44 T: UpgradeInfo,
45{
46 type Info = T::Info;
47 type InfoIter = Iter<<T::InfoIter as IntoIterator>::IntoIter>;
48
49 fn protocol_info(&self) -> Self::InfoIter {
50 Iter(self.0.as_ref().map(|p| p.protocol_info().into_iter()))
51 }
52}
53
54impl<C, T> InboundUpgrade<C> for OptionalUpgrade<T>
55where
56 T: InboundUpgrade<C>,
57{
58 type Output = T::Output;
59 type Error = T::Error;
60 type Future = T::Future;
61
62 fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
63 if let Some(inner) = self.0 {
64 inner.upgrade_inbound(sock, info)
65 } else {
66 panic!("Bad API usage; a protocol has been negotiated while this struct contains None")
67 }
68 }
69}
70
71impl<C, T> OutboundUpgrade<C> for OptionalUpgrade<T>
72where
73 T: OutboundUpgrade<C>,
74{
75 type Output = T::Output;
76 type Error = T::Error;
77 type Future = T::Future;
78
79 fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
80 if let Some(inner) = self.0 {
81 inner.upgrade_outbound(sock, info)
82 } else {
83 panic!("Bad API usage; a protocol has been negotiated while this struct contains None")
84 }
85 }
86}
87
88#[derive(Debug, Clone)]
90pub struct Iter<T>(Option<T>);
91
92impl<T> Iterator for Iter<T>
93where
94 T: Iterator,
95{
96 type Item = T::Item;
97
98 fn next(&mut self) -> Option<Self::Item> {
99 if let Some(iter) = self.0.as_mut() {
100 iter.next()
101 } else {
102 None
103 }
104 }
105
106 fn size_hint(&self) -> (usize, Option<usize>) {
107 if let Some(iter) = self.0.as_ref() {
108 iter.size_hint()
109 } else {
110 (0, Some(0))
111 }
112 }
113}
114
115impl<T> ExactSizeIterator for Iter<T>
116where
117 T: ExactSizeIterator
118{
119}