Skip to main content

quorum_set/tree/
tree_error.rs

1use std::error::Error;
2use std::fmt;
3
4#[cfg(doc)]
5use crate::QuorumTree;
6
7/// An error returned when building an invalid [`QuorumTree`].
8///
9/// Both cases are caller bugs: a correct quorum rule never contains the same
10/// child twice and never requires more children than it has. Construction
11/// reports them instead of repairing the input, so the mistake surfaces where
12/// it is made.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum QuorumTreeError {
15    /// The same child node was given more than once.
16    DuplicateChild {
17        /// Canonical ID of the duplicated child node.
18        canonical_id: String,
19    },
20
21    /// `quorum_size` exceeds the number of child nodes, so no input could
22    /// satisfy the tree.
23    UnsatisfiableQuorum {
24        /// The required number of selected children.
25        quorum_size: u64,
26        /// The number of child nodes.
27        num_children: usize,
28    },
29}
30
31impl fmt::Display for QuorumTreeError {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        match self {
34            Self::DuplicateChild { canonical_id } => {
35                write!(f, "duplicate child node: {canonical_id}")
36            }
37            Self::UnsatisfiableQuorum {
38                quorum_size,
39                num_children,
40            } => {
41                write!(
42                    f,
43                    "quorum size {quorum_size} exceeds the number of child nodes {num_children}"
44                )
45            }
46        }
47    }
48}
49
50impl Error for QuorumTreeError {}
51
52#[cfg(test)]
53mod tests {
54    use super::QuorumTreeError;
55
56    #[test]
57    fn test_display() {
58        let err = QuorumTreeError::DuplicateChild {
59            canonical_id: "Id=1".to_string(),
60        };
61        assert_eq!("duplicate child node: Id=1", err.to_string());
62
63        let err = QuorumTreeError::UnsatisfiableQuorum {
64            quorum_size: 3,
65            num_children: 2,
66        };
67        assert_eq!(
68            "quorum size 3 exceeds the number of child nodes 2",
69            err.to_string()
70        );
71    }
72}