radixtarget_rust/node/
base.rs

1// base.rs: Shared base node trait for radix trees
2use std::collections::{HashMap, HashSet};
3
4/// Trait for nodes that can be pruned (base node for radix trees).
5pub trait BaseNode {
6    /// Returns true if the node is dead (no data, no children)
7    fn is_dead(&self) -> bool;
8    /// Returns mutable reference to children as a trait object
9    fn children_mut(&mut self) -> &mut HashMap<u64, Box<Self>>
10    where
11        Self: Sized;
12    /// Returns immutable reference to children
13    fn children(&self) -> &HashMap<u64, Box<Self>>
14    where
15        Self: Sized;
16    /// Returns the host as a string if present
17    fn host_string(&self) -> Option<String>;
18    /// Prune dead child nodes recursively, returns number pruned
19    fn prune(&mut self) -> usize
20    where
21        Self: Sized,
22    {
23        let mut pruned = 0;
24        let keys: Vec<u64> = self.children_mut().keys().copied().collect();
25        for key in keys {
26            if let Some(child) = self.children_mut().get_mut(&key) {
27                pruned += child.prune();
28                if child.is_dead() {
29                    self.children_mut().remove(&key);
30                    pruned += 1;
31                }
32            }
33        }
34        pruned
35    }
36    /// Clear all children recursively and return deleted hosts
37    fn clear(&mut self) -> Vec<String>
38    where
39        Self: Sized,
40    {
41        let mut hosts = Vec::new();
42        for (_, child) in self.children_mut().iter_mut() {
43            hosts.extend(child.clear());
44            if let Some(host) = child.host_string() {
45                hosts.push(host);
46            }
47        }
48        self.children_mut().clear();
49        hosts
50    }
51
52    /// Get all hosts in this subtree
53    fn all_hosts(&self) -> HashSet<String>
54    where
55        Self: Sized,
56    {
57        let mut hosts = HashSet::new();
58        if let Some(host) = self.host_string() {
59            hosts.insert(host);
60        }
61        for child in self.children().values() {
62            hosts.extend(child.all_hosts());
63        }
64        hosts
65    }
66}