Skip to main content

quorum_set/tree/
quorum_node.rs

1use std::fmt;
2
3use sha2::Digest;
4use sha2::Sha256;
5
6use super::canonical_id::CanonicalId;
7use super::canonical_id::MAX_CANONICAL_ID_LEN;
8use super::canonical_id::fmt_escaped;
9use crate::QuorumTree;
10
11/// A child of a [`QuorumTree`](crate::QuorumTree).
12///
13/// A node can be either a leaf node ID or a nested quorum tree. Nested trees
14/// allow hierarchical quorum rules such as "two data centers, each selected by
15/// a local majority".
16#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub enum Node<ID>
18where ID: Ord
19{
20    /// A leaf node ID.
21    Id(ID),
22
23    /// A nested quorum tree.
24    Subtree(QuorumTree<ID>),
25}
26
27impl<ID> Node<ID>
28where ID: Ord
29{
30    /// Returns whether `ids` select this child node.
31    ///
32    /// A leaf node is selected when its ID is present in `ids`. A nested tree is
33    /// selected when `ids` satisfy that tree.
34    pub(crate) fn is_selected_by<'a, I>(&self, ids: I) -> bool
35    where
36        ID: 'a,
37        I: IntoIterator<Item = &'a ID> + Clone,
38    {
39        match self {
40            Node::Id(id) => ids.into_iter().any(|candidate| candidate == id),
41            Node::Subtree(m) => m.spec.is_quorum(ids),
42        }
43    }
44}
45
46impl<ID> CanonicalId for Node<ID>
47where
48    ID: CanonicalId,
49    ID: Ord,
50{
51    fn fmt_canonical_id<W>(&self, f: &mut W) -> fmt::Result
52    where W: fmt::Write + ?Sized {
53        match self {
54            Node::Id(id) => {
55                write!(f, "Id=")?;
56
57                let id = id.canonical_id();
58                if id.len() > MAX_CANONICAL_ID_LEN {
59                    write!(f, "Hash#1:{:x}", Sha256::digest(id.as_bytes()))?;
60                } else {
61                    fmt_escaped(&id, f)?;
62                }
63            }
64            Node::Subtree(m) => {
65                write!(f, "Subtree=")?;
66                m.fmt_canonical_id(f)?;
67            }
68        }
69        Ok(())
70    }
71}