Skip to main content

waratah_router/
table.rs

1//! Static in-memory routing table (`NodeId` → address).
2
3use std::collections::HashMap;
4use std::net::SocketAddr;
5
6use crate::{NodeId, RouterError};
7
8/// Maps physical partition node ids to listen addresses.
9#[derive(Debug, Clone, Default)]
10pub struct RoutingTable {
11    addresses: HashMap<NodeId, SocketAddr>,
12}
13
14impl RoutingTable {
15    /// Empty table.
16    pub fn new() -> Self {
17        Self::default()
18    }
19
20    /// Insert or replace the address for `node`.
21    pub fn insert(&mut self, node: NodeId, address: SocketAddr) {
22        self.addresses.insert(node, address);
23    }
24
25    /// Look up the address for `node`.
26    pub fn lookup(&self, node: &NodeId) -> Result<SocketAddr, RouterError> {
27        self.addresses
28            .get(node)
29            .copied()
30            .ok_or_else(|| RouterError::UnknownNode(node.clone()))
31    }
32
33    /// Every `(node, address)` pair (order is hash-map iteration).
34    pub fn iter(&self) -> impl Iterator<Item = (&NodeId, SocketAddr)> + '_ {
35        self.addresses.iter().map(|(id, addr)| (id, *addr))
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42    use std::net::{Ipv4Addr, SocketAddrV4};
43
44    fn localhost(port: u16) -> SocketAddr {
45        SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port))
46    }
47
48    #[test]
49    fn lookup_hit_and_miss() {
50        let mut table = RoutingTable::new();
51        let node = NodeId::new("s-0");
52        table.insert(node.clone(), localhost(7001));
53        assert_eq!(table.lookup(&node).unwrap(), localhost(7001));
54        assert_eq!(
55            table.lookup(&NodeId::new("missing")),
56            Err(RouterError::UnknownNode(NodeId::new("missing")))
57        );
58        let dumped: Vec<_> = table.iter().map(|(id, addr)| (id.clone(), addr)).collect();
59        assert_eq!(dumped, vec![(node, localhost(7001))]);
60    }
61}