1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use crate::handler::ProtocolsChange;
use crate::StreamProtocol;
use std::collections::HashSet;

#[derive(Default, Clone, Debug)]
pub struct SupportedProtocols {
    protocols: HashSet<StreamProtocol>,
}

impl SupportedProtocols {
    pub fn on_protocols_change(&mut self, change: ProtocolsChange) -> bool {
        match change {
            ProtocolsChange::Added(added) => {
                let mut changed = false;

                for p in added {
                    changed |= self.protocols.insert(p.clone());
                }

                changed
            }
            ProtocolsChange::Removed(removed) => {
                let mut changed = false;

                for p in removed {
                    changed |= self.protocols.remove(p);
                }

                changed
            }
        }
    }

    pub fn iter(&self) -> impl Iterator<Item = &StreamProtocol> {
        self.protocols.iter()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::handler::{ProtocolsAdded, ProtocolsRemoved};

    #[test]
    fn protocols_change_added_returns_correct_changed_value() {
        let mut protocols = SupportedProtocols::default();

        let changed = protocols.on_protocols_change(add_foo());
        assert!(changed);

        let changed = protocols.on_protocols_change(add_foo());
        assert!(!changed);

        let changed = protocols.on_protocols_change(add_foo_bar());
        assert!(changed);
    }

    #[test]
    fn protocols_change_removed_returns_correct_changed_value() {
        let mut protocols = SupportedProtocols::default();

        let changed = protocols.on_protocols_change(remove_foo());
        assert!(!changed);

        protocols.on_protocols_change(add_foo());

        let changed = protocols.on_protocols_change(remove_foo());
        assert!(changed);
    }

    fn add_foo() -> ProtocolsChange<'static> {
        ProtocolsChange::Added(ProtocolsAdded {
            protocols: FOO_PROTOCOLS.iter(),
        })
    }

    fn add_foo_bar() -> ProtocolsChange<'static> {
        ProtocolsChange::Added(ProtocolsAdded {
            protocols: FOO_BAR_PROTOCOLS.iter(),
        })
    }

    fn remove_foo() -> ProtocolsChange<'static> {
        ProtocolsChange::Removed(ProtocolsRemoved {
            protocols: FOO_PROTOCOLS.iter(),
        })
    }

    static FOO_PROTOCOLS: &[StreamProtocol] = &[StreamProtocol::new("/foo")];
    static FOO_BAR_PROTOCOLS: &[StreamProtocol] =
        &[StreamProtocol::new("/foo"), StreamProtocol::new("/bar")];
}