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