use crate::Multiaddr;
use std::{task::Context, task::Poll};
use super::{Connected, SubstreamEndpoint};
pub trait ConnectionHandler {
type InEvent;
type OutEvent;
type Error;
type Substream;
type OutboundOpenInfo;
fn inject_substream(&mut self, substream: Self::Substream, endpoint: SubstreamEndpoint<Self::OutboundOpenInfo>);
fn inject_event(&mut self, event: Self::InEvent);
fn inject_address_change(&mut self, new_address: &Multiaddr);
fn poll(&mut self, cx: &mut Context<'_>)
-> Poll<Result<ConnectionHandlerEvent<Self::OutboundOpenInfo, Self::OutEvent>, Self::Error>>;
}
pub trait IntoConnectionHandler {
type Handler: ConnectionHandler;
fn into_handler(self, connected: &Connected) -> Self::Handler;
}
impl<T> IntoConnectionHandler for T
where
T: ConnectionHandler
{
type Handler = Self;
fn into_handler(self, _: &Connected) -> Self {
self
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ConnectionHandlerEvent<TOutboundOpenInfo, TCustom> {
OutboundSubstreamRequest(TOutboundOpenInfo),
Custom(TCustom),
}
impl<TOutboundOpenInfo, TCustom> ConnectionHandlerEvent<TOutboundOpenInfo, TCustom> {
pub fn map_outbound_open_info<F, I>(self, map: F) -> ConnectionHandlerEvent<I, TCustom>
where F: FnOnce(TOutboundOpenInfo) -> I
{
match self {
ConnectionHandlerEvent::OutboundSubstreamRequest(val) => {
ConnectionHandlerEvent::OutboundSubstreamRequest(map(val))
},
ConnectionHandlerEvent::Custom(val) => ConnectionHandlerEvent::Custom(val),
}
}
pub fn map_custom<F, I>(self, map: F) -> ConnectionHandlerEvent<TOutboundOpenInfo, I>
where F: FnOnce(TCustom) -> I
{
match self {
ConnectionHandlerEvent::OutboundSubstreamRequest(val) => {
ConnectionHandlerEvent::OutboundSubstreamRequest(val)
},
ConnectionHandlerEvent::Custom(val) => ConnectionHandlerEvent::Custom(map(val)),
}
}
}