libp2p_swarm/connection/
supported_protocols.rs1use std::collections::HashSet;
2
3use crate::{handler::ProtocolsChange, StreamProtocol};
4
5#[derive(Default, Clone, Debug)]
6pub struct SupportedProtocols {
7 protocols: HashSet<StreamProtocol>,
8}
9
10impl SupportedProtocols {
11 pub fn on_protocols_change(&mut self, change: ProtocolsChange) -> bool {
12 match change {
13 ProtocolsChange::Added(added) => {
14 let mut changed = false;
15
16 for p in added {
17 changed |= self.protocols.insert(p.clone());
18 }
19
20 changed
21 }
22 ProtocolsChange::Removed(removed) => {
23 let mut changed = false;
24
25 for p in removed {
26 changed |= self.protocols.remove(p);
27 }
28
29 changed
30 }
31 }
32 }
33
34 pub fn iter(&self) -> impl Iterator<Item = &StreamProtocol> {
35 self.protocols.iter()
36 }
37}
38
39#[cfg(test)]
40mod tests {
41 use super::*;
42 use crate::handler::{ProtocolsAdded, ProtocolsRemoved};
43
44 #[test]
45 fn protocols_change_added_returns_correct_changed_value() {
46 let mut protocols = SupportedProtocols::default();
47
48 let changed = protocols.on_protocols_change(add_foo());
49 assert!(changed);
50
51 let changed = protocols.on_protocols_change(add_foo());
52 assert!(!changed);
53
54 let changed = protocols.on_protocols_change(add_foo_bar());
55 assert!(changed);
56 }
57
58 #[test]
59 fn protocols_change_removed_returns_correct_changed_value() {
60 let mut protocols = SupportedProtocols::default();
61
62 let changed = protocols.on_protocols_change(remove_foo());
63 assert!(!changed);
64
65 protocols.on_protocols_change(add_foo());
66
67 let changed = protocols.on_protocols_change(remove_foo());
68 assert!(changed);
69 }
70
71 fn add_foo() -> ProtocolsChange<'static> {
72 ProtocolsChange::Added(ProtocolsAdded {
73 protocols: FOO_PROTOCOLS.iter(),
74 })
75 }
76
77 fn add_foo_bar() -> ProtocolsChange<'static> {
78 ProtocolsChange::Added(ProtocolsAdded {
79 protocols: FOO_BAR_PROTOCOLS.iter(),
80 })
81 }
82
83 fn remove_foo() -> ProtocolsChange<'static> {
84 ProtocolsChange::Removed(ProtocolsRemoved {
85 protocols: FOO_PROTOCOLS.iter(),
86 })
87 }
88
89 static FOO_PROTOCOLS: &[StreamProtocol] = &[StreamProtocol::new("/foo")];
90 static FOO_BAR_PROTOCOLS: &[StreamProtocol] =
91 &[StreamProtocol::new("/foo"), StreamProtocol::new("/bar")];
92}