libp2p_swarm/connection/
supported_protocols.rs

1use crate::handler::ProtocolsChange;
2use crate::StreamProtocol;
3use std::collections::HashSet;
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    use once_cell::sync::Lazy;
44
45    #[test]
46    fn protocols_change_added_returns_correct_changed_value() {
47        let mut protocols = SupportedProtocols::default();
48
49        let changed = protocols.on_protocols_change(add_foo());
50        assert!(changed);
51
52        let changed = protocols.on_protocols_change(add_foo());
53        assert!(!changed);
54
55        let changed = protocols.on_protocols_change(add_foo_bar());
56        assert!(changed);
57    }
58
59    #[test]
60    fn protocols_change_removed_returns_correct_changed_value() {
61        let mut protocols = SupportedProtocols::default();
62
63        let changed = protocols.on_protocols_change(remove_foo());
64        assert!(!changed);
65
66        protocols.on_protocols_change(add_foo());
67
68        let changed = protocols.on_protocols_change(remove_foo());
69        assert!(changed);
70    }
71
72    fn add_foo() -> ProtocolsChange<'static> {
73        ProtocolsChange::Added(ProtocolsAdded::from_set(&FOO_PROTOCOLS))
74    }
75
76    fn add_foo_bar() -> ProtocolsChange<'static> {
77        ProtocolsChange::Added(ProtocolsAdded::from_set(&FOO_BAR_PROTOCOLS))
78    }
79
80    fn remove_foo() -> ProtocolsChange<'static> {
81        ProtocolsChange::Removed(ProtocolsRemoved::from_set(&FOO_PROTOCOLS))
82    }
83
84    static FOO_PROTOCOLS: Lazy<HashSet<StreamProtocol>> =
85        Lazy::new(|| HashSet::from([StreamProtocol::new("/foo")]));
86    static FOO_BAR_PROTOCOLS: Lazy<HashSet<StreamProtocol>> =
87        Lazy::new(|| HashSet::from([StreamProtocol::new("/foo"), StreamProtocol::new("/bar")]));
88}