use crate::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo};
use multistream_select::Negotiated;
#[derive(Debug, Clone)]
pub struct OptionalUpgrade<T>(Option<T>);
impl<T> OptionalUpgrade<T> {
pub fn some(inner: T) -> Self {
OptionalUpgrade(Some(inner))
}
pub fn none() -> Self {
OptionalUpgrade(None)
}
}
impl<T> UpgradeInfo for OptionalUpgrade<T>
where
T: UpgradeInfo,
{
type Info = T::Info;
type InfoIter = Iter<<T::InfoIter as IntoIterator>::IntoIter>;
fn protocol_info(&self) -> Self::InfoIter {
Iter(self.0.as_ref().map(|p| p.protocol_info().into_iter()))
}
}
impl<C, T> InboundUpgrade<C> for OptionalUpgrade<T>
where
T: InboundUpgrade<C>,
{
type Output = T::Output;
type Error = T::Error;
type Future = T::Future;
fn upgrade_inbound(self, sock: Negotiated<C>, info: Self::Info) -> Self::Future {
if let Some(inner) = self.0 {
inner.upgrade_inbound(sock, info)
} else {
panic!("Bad API usage; a protocol has been negotiated while this struct contains None")
}
}
}
impl<C, T> OutboundUpgrade<C> for OptionalUpgrade<T>
where
T: OutboundUpgrade<C>,
{
type Output = T::Output;
type Error = T::Error;
type Future = T::Future;
fn upgrade_outbound(self, sock: Negotiated<C>, info: Self::Info) -> Self::Future {
if let Some(inner) = self.0 {
inner.upgrade_outbound(sock, info)
} else {
panic!("Bad API usage; a protocol has been negotiated while this struct contains None")
}
}
}
#[derive(Debug, Clone)]
pub struct Iter<T>(Option<T>);
impl<T> Iterator for Iter<T>
where
T: Iterator,
{
type Item = T::Item;
fn next(&mut self) -> Option<Self::Item> {
if let Some(iter) = self.0.as_mut() {
iter.next()
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
if let Some(iter) = self.0.as_ref() {
iter.size_hint()
} else {
(0, Some(0))
}
}
}
impl<T> ExactSizeIterator for Iter<T>
where
T: ExactSizeIterator
{
}