rust_ipfs/p2p/
protocol.rs1use std::{
2 collections::VecDeque,
3 task::{Context, Poll},
4};
5
6use libp2p::core::transport::PortUse;
7use libp2p::{
8 core::Endpoint,
9 swarm::{
10 self, ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler,
11 THandlerInEvent, ToSwarm,
12 },
13 Multiaddr, PeerId, StreamProtocol,
14};
15
16mod handler;
17
18#[derive(Default, Debug)]
19pub struct Behaviour {
20 events: VecDeque<ToSwarm<<Self as NetworkBehaviour>::ToSwarm, THandlerInEvent<Self>>>,
21 protocol: Vec<StreamProtocol>,
22}
23
24impl Behaviour {
25 pub fn iter(&self) -> impl Iterator<Item = String> + '_ {
26 self.protocol.iter().map(|s| s.to_string())
27 }
28}
29
30impl NetworkBehaviour for Behaviour {
31 type ConnectionHandler = handler::Handler;
32 type ToSwarm = void::Void;
33
34 fn handle_pending_inbound_connection(
35 &mut self,
36 _: ConnectionId,
37 _: &Multiaddr,
38 _: &Multiaddr,
39 ) -> Result<(), ConnectionDenied> {
40 Ok(())
41 }
42
43 fn handle_pending_outbound_connection(
44 &mut self,
45 _: ConnectionId,
46 _: Option<PeerId>,
47 _: &[Multiaddr],
48 _: Endpoint,
49 ) -> Result<Vec<Multiaddr>, ConnectionDenied> {
50 Ok(vec![])
51 }
52
53 fn handle_established_inbound_connection(
54 &mut self,
55 _: ConnectionId,
56 _: PeerId,
57 _: &Multiaddr,
58 _: &Multiaddr,
59 ) -> Result<THandler<Self>, ConnectionDenied> {
60 Ok(handler::Handler::default())
61 }
62
63 fn handle_established_outbound_connection(
64 &mut self,
65 _: ConnectionId,
66 _: PeerId,
67 _: &Multiaddr,
68 _: Endpoint,
69 _: PortUse,
70 ) -> Result<THandler<Self>, ConnectionDenied> {
71 Ok(handler::Handler::default())
72 }
73
74 fn on_connection_handler_event(
75 &mut self,
76 _: PeerId,
77 _: ConnectionId,
78 event: swarm::THandlerOutEvent<Self>,
79 ) {
80 match event {
81 handler::Out::Protocol(protocol) => {
82 if self.protocol.ne(&protocol) {
83 self.protocol = protocol;
84 }
85 }
86 }
87 }
88
89 fn on_swarm_event(&mut self, _: FromSwarm) {}
90
91 fn poll(&mut self, _: &mut Context) -> Poll<ToSwarm<Self::ToSwarm, THandlerInEvent<Self>>> {
92 if let Some(event) = self.events.pop_front() {
93 return Poll::Ready(event);
94 }
95 Poll::Pending
96 }
97}