libp2p_swarm/handler/
map_out.rs1use crate::handler::{
22 ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, SubstreamProtocol,
23};
24use futures::ready;
25use std::fmt::Debug;
26use std::task::{Context, Poll};
27
28#[derive(Debug)]
30pub struct MapOutEvent<TConnectionHandler, TMap> {
31 inner: TConnectionHandler,
32 map: TMap,
33}
34
35impl<TConnectionHandler, TMap> MapOutEvent<TConnectionHandler, TMap> {
36 pub(crate) fn new(inner: TConnectionHandler, map: TMap) -> Self {
38 MapOutEvent { inner, map }
39 }
40}
41
42impl<TConnectionHandler, TMap, TNewOut> ConnectionHandler for MapOutEvent<TConnectionHandler, TMap>
43where
44 TConnectionHandler: ConnectionHandler,
45 TMap: FnMut(TConnectionHandler::ToBehaviour) -> TNewOut,
46 TNewOut: Debug + Send + 'static,
47 TMap: Send + 'static,
48{
49 type FromBehaviour = TConnectionHandler::FromBehaviour;
50 type ToBehaviour = TNewOut;
51 type InboundProtocol = TConnectionHandler::InboundProtocol;
52 type OutboundProtocol = TConnectionHandler::OutboundProtocol;
53 type InboundOpenInfo = TConnectionHandler::InboundOpenInfo;
54 type OutboundOpenInfo = TConnectionHandler::OutboundOpenInfo;
55
56 fn listen_protocol(&self) -> SubstreamProtocol<Self::InboundProtocol, Self::InboundOpenInfo> {
57 self.inner.listen_protocol()
58 }
59
60 fn on_behaviour_event(&mut self, event: Self::FromBehaviour) {
61 self.inner.on_behaviour_event(event)
62 }
63
64 fn connection_keep_alive(&self) -> bool {
65 self.inner.connection_keep_alive()
66 }
67
68 fn poll(
69 &mut self,
70 cx: &mut Context<'_>,
71 ) -> Poll<
72 ConnectionHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::ToBehaviour>,
73 > {
74 self.inner.poll(cx).map(|ev| match ev {
75 ConnectionHandlerEvent::NotifyBehaviour(ev) => {
76 ConnectionHandlerEvent::NotifyBehaviour((self.map)(ev))
77 }
78 ConnectionHandlerEvent::OutboundSubstreamRequest { protocol } => {
79 ConnectionHandlerEvent::OutboundSubstreamRequest { protocol }
80 }
81 ConnectionHandlerEvent::ReportRemoteProtocols(support) => {
82 ConnectionHandlerEvent::ReportRemoteProtocols(support)
83 }
84 })
85 }
86
87 fn poll_close(&mut self, cx: &mut Context<'_>) -> Poll<Option<Self::ToBehaviour>> {
88 let Some(e) = ready!(self.inner.poll_close(cx)) else {
89 return Poll::Ready(None);
90 };
91
92 Poll::Ready(Some((self.map)(e)))
93 }
94
95 fn on_connection_event(
96 &mut self,
97 event: ConnectionEvent<
98 Self::InboundProtocol,
99 Self::OutboundProtocol,
100 Self::InboundOpenInfo,
101 Self::OutboundOpenInfo,
102 >,
103 ) {
104 self.inner.on_connection_event(event);
105 }
106}