Skip to main content

quorum_set/tree/
tree_error.rs

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