Skip to main content

graphity_core/
error.rs

1//! The error type of the operations that validate whole inputs, and the panics of the others.
2//!
3//! The Java implementation distinguishes `IndexOutOfBoundsException` (an index or ID outside its
4//! range) from `IllegalArgumentException` (any other violated contract) and, for a builder at its
5//! limit, `IllegalStateException`. Rust keeps the same distinction in two forms:
6//!
7//! - Operations that validate whole inputs return a [`Result`] whose [`GraphError`] names the
8//!   category in its [`ErrorKind`]. Whole inputs are arrays that must form a graph, a mapping or a
9//!   partition, and graphs that must be acyclic or a forest.
10//! - Single arguments out of their range panic, like an out-of-bounds slice index. So does a
11//!   mapping that breaks its contract where it is used, in `NodeMapping::inverted`, `compose` and
12//!   `graphs::remapped`: one that maps two indices to the same index, or that maps outside the
13//!   space the call names. [`NodeMapping::of`](crate::NodeMapping::of) leaves the first of these to
14//!   the caller, as Java does. The panic message starts with the category: `index out of bounds: `,
15//!   `invalid argument: ` or `illegal state: `.
16
17use std::fmt;
18
19/// The category of a [`GraphError`]: the counterpart of the Java exception class.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum ErrorKind {
22    /// An index or ID lies outside its range; Java throws `IndexOutOfBoundsException`.
23    IndexOutOfBounds,
24    /// The input breaks the contract otherwise; Java throws `IllegalArgumentException`.
25    InvalidArgument,
26}
27
28/// An input that does not meet the contract of the operation it was passed to: the error of the
29/// operations that check a whole input, such as [`Graph::of`](crate::Graph::of) or
30/// [`top_order::of`](crate::top_order::of).
31///
32/// [`kind`](Self::kind) tells Java's two exceptions apart, and [`message`](Self::message) is Java's
33/// message with Rust's names. The `Display` form is the message.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct GraphError {
36    kind: ErrorKind,
37    message: String,
38}
39
40impl GraphError {
41    pub(crate) fn index_out_of_bounds(message: impl Into<String>) -> Self {
42        Self {
43            kind: ErrorKind::IndexOutOfBounds,
44            message: message.into(),
45        }
46    }
47
48    pub(crate) fn invalid_argument(message: impl Into<String>) -> Self {
49        Self {
50            kind: ErrorKind::InvalidArgument,
51            message: message.into(),
52        }
53    }
54
55    /// Returns whether an index was out of its range or the input broke the contract otherwise.
56    ///
57    /// **Time:** O(1).
58    pub fn kind(&self) -> ErrorKind {
59        self.kind
60    }
61
62    /// Returns the description of what was wrong, without the category.
63    ///
64    /// **Time:** O(1).
65    pub fn message(&self) -> &str {
66        &self.message
67    }
68}
69
70impl fmt::Display for GraphError {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        f.write_str(&self.message)
73    }
74}
75
76impl std::error::Error for GraphError {}
77
78/// Panics with an `index out of bounds: ` message; the counterpart of Java's
79/// `IndexOutOfBoundsException`.
80#[cold]
81#[track_caller]
82pub(crate) fn panic_index_out_of_bounds(message: fmt::Arguments<'_>) -> ! {
83    panic!("index out of bounds: {message}")
84}
85
86/// Panics with an `invalid argument: ` message; the counterpart of Java's
87/// `IllegalArgumentException`.
88#[cold]
89#[track_caller]
90pub(crate) fn panic_invalid_argument(message: fmt::Arguments<'_>) -> ! {
91    panic!("invalid argument: {message}")
92}
93
94/// Panics with an `illegal state: ` message; the counterpart of Java's
95/// `IllegalStateException`.
96#[cold]
97#[track_caller]
98pub(crate) fn panic_illegal_state(message: fmt::Arguments<'_>) -> ! {
99    panic!("illegal state: {message}")
100}
101
102/// Panics like `Objects.checkIndex` if `index` is not in `0..length`.
103#[inline]
104#[track_caller]
105pub(crate) fn check_index(index: u32, length: u32) {
106    if index >= length {
107        index_out_of_range(index, length);
108    }
109}
110
111/// Checks every node of a list of start nodes, sources or entries before any work begins: the
112/// check of each slice form of a traversal or search, shared as Java's package-private `Checks`.
113///
114/// # Panics
115/// With an `index out of bounds` message if a node is not in `0..node_count`.
116#[track_caller]
117pub(crate) fn check_nodes(nodes: &[u32], node_count: u32) {
118    for &node in nodes {
119        check_index(node, node_count);
120    }
121}
122
123#[cold]
124#[track_caller]
125fn index_out_of_range(index: u32, length: u32) -> ! {
126    panic_index_out_of_bounds(format_args!("the len is {length} but the index is {index}"))
127}
128
129/// `panic_index_out_of_bounds` with `format!` syntax.
130macro_rules! index_out_of_bounds {
131    ($($arg:tt)*) => {
132        $crate::error::panic_index_out_of_bounds(format_args!($($arg)*))
133    };
134}
135
136/// `panic_invalid_argument` with `format!` syntax.
137macro_rules! invalid_argument {
138    ($($arg:tt)*) => {
139        $crate::error::panic_invalid_argument(format_args!($($arg)*))
140    };
141}
142
143/// `panic_illegal_state` with `format!` syntax.
144macro_rules! illegal_state {
145    ($($arg:tt)*) => {
146        $crate::error::panic_illegal_state(format_args!($($arg)*))
147    };
148}
149
150pub(crate) use {illegal_state, index_out_of_bounds, invalid_argument};
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn kind_and_message_are_kept_apart() {
158        let error = GraphError::invalid_argument("graph contains a cycle");
159        assert_eq!(error.kind(), ErrorKind::InvalidArgument);
160        assert_eq!(error.message(), "graph contains a cycle");
161        assert_eq!(error.to_string(), "graph contains a cycle");
162        let error = GraphError::index_out_of_bounds("out-node 2 of node 0");
163        assert_eq!(error.kind(), ErrorKind::IndexOutOfBounds);
164    }
165
166    #[test]
167    #[should_panic(expected = "index out of bounds: the len is 4 but the index is 4")]
168    fn check_index_names_length_and_index() {
169        check_index(4, 4);
170    }
171
172    #[test]
173    fn check_index_accepts_the_range() {
174        check_index(0, 1);
175        check_index(3, 4);
176    }
177
178    #[test]
179    #[should_panic(expected = "invalid argument: odd")]
180    fn invalid_argument_names_the_category() {
181        invalid_argument!("odd");
182    }
183
184    #[test]
185    #[should_panic(expected = "illegal state: full")]
186    fn illegal_state_names_the_category() {
187        illegal_state!("full");
188    }
189}