use std::convert::Infallible;
use futures::future::{ready, Ready};
use libp2p_core::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo};
use libp2p_swarm::Stream;
use smallvec::SmallVec;
#[derive(Debug, Clone)]
pub enum ProtocolSupport {
Inbound,
Outbound,
Full,
}
impl ProtocolSupport {
pub fn inbound(&self) -> bool {
match self {
ProtocolSupport::Inbound | ProtocolSupport::Full => true,
ProtocolSupport::Outbound => false,
}
}
pub fn outbound(&self) -> bool {
match self {
ProtocolSupport::Outbound | ProtocolSupport::Full => true,
ProtocolSupport::Inbound => false,
}
}
}
#[derive(Debug)]
pub struct Protocol<P> {
pub(crate) protocols: SmallVec<[P; 2]>,
}
impl<P> UpgradeInfo for Protocol<P>
where
P: AsRef<str> + Clone,
{
type Info = P;
type InfoIter = smallvec::IntoIter<[Self::Info; 2]>;
fn protocol_info(&self) -> Self::InfoIter {
self.protocols.clone().into_iter()
}
}
impl<P> InboundUpgrade<Stream> for Protocol<P>
where
P: AsRef<str> + Clone,
{
type Output = (Stream, P);
type Error = Infallible;
type Future = Ready<Result<Self::Output, Self::Error>>;
fn upgrade_inbound(self, io: Stream, protocol: Self::Info) -> Self::Future {
ready(Ok((io, protocol)))
}
}
impl<P> OutboundUpgrade<Stream> for Protocol<P>
where
P: AsRef<str> + Clone,
{
type Output = (Stream, P);
type Error = Infallible;
type Future = Ready<Result<Self::Output, Self::Error>>;
fn upgrade_outbound(self, io: Stream, protocol: Self::Info) -> Self::Future {
ready(Ok((io, protocol)))
}
}