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/// All three cases are caller bugs: a correct quorum rule never contains the
10/// same child twice, never requires zero children, and never requires more
11/// children than it has. Construction reports them instead of repairing the
12/// input, so the mistake surfaces where 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    /// `quorum_size` is `0`, so every input, even an empty one, would
31    /// satisfy the tree.
32    ZeroQuorumSize,
33}
34
35impl fmt::Display for QuorumTreeError {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match self {
38            Self::DuplicateChild { canonical_id } => {
39                write!(f, "duplicate child node: {canonical_id}")
40            }
41            Self::UnsatisfiableQuorum {
42                quorum_size,
43                num_children,
44            } => {
45                write!(
46                    f,
47                    "quorum size {quorum_size} exceeds the number of child nodes {num_children}"
48                )
49            }
50            Self::ZeroQuorumSize => {
51                write!(f, "quorum size 0 accepts every input, even an empty one")
52            }
53        }
54    }
55}
56
57impl Error for QuorumTreeError {}
58
59#[cfg(test)]
60mod tests {
61    use super::QuorumTreeError;
62
63    #[test]
64    fn test_display() {
65        let err = QuorumTreeError::DuplicateChild {
66            canonical_id: "Id=1".to_string(),
67        };
68        assert_eq!("duplicate child node: Id=1", err.to_string());
69
70        let err = QuorumTreeError::UnsatisfiableQuorum {
71            quorum_size: 3,
72            num_children: 2,
73        };
74        assert_eq!(
75            "quorum size 3 exceeds the number of child nodes 2",
76            err.to_string()
77        );
78
79        let err = QuorumTreeError::ZeroQuorumSize;
80        let message = err.to_string();
81        assert_eq!(
82            "quorum size 0 accepts every input, even an empty one",
83            message
84        );
85    }
86}