usher/
node.rs

1//! Nodes to represent the internal structure of a router.
2use super::matcher::Matcher;
3
4/// Node structure to represent the internal structure of a router.
5///
6/// A router is simply a `Node` which doesn't have any parent nodes,
7/// which allows for the recursive structure of the tree. Each
8/// `Node` can have a value of the generic type, which is the value
9/// returned when routing occurs.
10///
11/// Every `Node` also has an associated `Matcher` which is used
12/// to test for compatibility when routing (because not every node
13/// is applicable on a given segment order). This `Matcher` is
14/// automatically provided to the `Node` at creation time and is
15/// calculated by the routing system.
16///
17/// Lastly, a `Node` can have child instances to represent the
18/// recursive structure of a router. These children are stored in
19/// a `Vec` as there's currently no logical way to index them into
20/// a more suitable structure. If a `Node` has no children, the
21/// containing vector does not require any memory allocation. Any
22/// memory will be allocated lazily, and should remain minimal in
23/// most standard cases (as it depends on the allocator in use).
24pub struct Node<T> {
25    value: Option<T>,
26    matcher: Box<dyn Matcher>,
27    children: Vec<Node<T>>,
28}
29
30impl<T> Node<T> {
31    /// Constructs a new `Node` from a literal.
32    pub(crate) fn new(matcher: Box<dyn Matcher>) -> Self {
33        Self {
34            matcher,
35            value: None,
36            children: Vec::new(),
37        }
38    }
39
40    /// Registers a child node inside this node.
41    pub(crate) fn add_child(&mut self, child: Node<T>) {
42        self.children.reserve_exact(1);
43        self.children.push(child);
44    }
45
46    /// Retrieves a reference to the children of this node.
47    pub(crate) fn children(&self) -> &[Node<T>] {
48        &self.children
49    }
50
51    /// Retrieves a mutable reference to the children of this node.
52    pub(crate) fn children_mut(&mut self) -> &mut [Node<T>] {
53        &mut self.children
54    }
55
56    /// Retrieves the matching struct for this node.
57    pub(crate) fn matcher(&self) -> &dyn Matcher {
58        &*self.matcher
59    }
60
61    /// Updates the inner value of this routing
62    pub(crate) fn update<F>(&mut self, f: F)
63    where
64        F: FnOnce(Option<T>) -> T,
65    {
66        let t = f(self.value.take());
67        self.value.replace(t);
68    }
69
70    /// Retrieves a potential handler associated with the provided method.
71    pub(crate) fn value(&self) -> Option<&T> {
72        self.value.as_ref()
73    }
74}