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
use super::{ConnectionId, Destination};
use derive_more::IntoIterator;
use serde::{Deserialize, Serialize};
use std::{
    collections::HashMap,
    ops::{Deref, DerefMut, Index, IndexMut},
};

/// Represents a list of information about active connections
#[derive(Clone, Debug, PartialEq, Eq, IntoIterator, Serialize, Deserialize)]
pub struct ConnectionList(pub(crate) HashMap<ConnectionId, Destination>);

impl ConnectionList {
    pub fn new() -> Self {
        Self(HashMap::new())
    }

    /// Returns a reference to the destination associated with an active connection
    pub fn connection_destination(&self, id: ConnectionId) -> Option<&Destination> {
        self.0.get(&id)
    }
}

impl Default for ConnectionList {
    fn default() -> Self {
        Self::new()
    }
}

impl Deref for ConnectionList {
    type Target = HashMap<ConnectionId, Destination>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for ConnectionList {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl Index<u64> for ConnectionList {
    type Output = Destination;

    fn index(&self, connection_id: u64) -> &Self::Output {
        &self.0[&connection_id]
    }
}

impl IndexMut<u64> for ConnectionList {
    fn index_mut(&mut self, connection_id: u64) -> &mut Self::Output {
        self.0
            .get_mut(&connection_id)
            .expect("No connection with id")
    }
}