1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
use crate::{GraphEntry, Query};
use std::{
    error::Error,
    fmt::{Debug, Display, Formatter},
    ops::DerefMut,
    path::Path,
};

/// The result type alias of a graph operation, see [`GraphError`] & [`GraphErrorKind`] for more.
///
/// # Examples
///
/// ```
/// use graph_theory::GraphResult;
/// ```
pub type GraphResult<T = ()> = Result<T, GraphError>;

/// The error type of a graph operation, see [`GraphErrorKind`] for more.
///
/// # Size
///
/// The size of this struct is always 8 bytes.
///
/// ```
/// use graph_theory::GraphError;
/// assert_eq!(std::mem::size_of::<GraphError>(), 8);
/// ```
///
/// # Examples
///
/// ```
/// use graph_theory::GraphError;
/// GraphError::node_not_found(0); // node id 0 not found
/// GraphError::edge_out_of_range(0, 5); // edge id 0 out of range (max 5)
/// GraphError::custom("user angry"); // user is angry now
/// ```
#[derive(Debug)]
pub struct GraphError {
    kind: Box<GraphErrorKind>,
}

/// The real error type of a graph operation, it will not be exposed to the user, see [`GraphError`] for more.
///
/// # Examples
///
/// ```
/// use graph_theory::GraphEngine;
/// ```
#[derive(Debug)]
pub enum GraphErrorKind {
    /// Some index is not found in storage.
    ///
    /// # Examples
    ///
    /// - edge id 0 out of range
    ///
    /// ```
    /// use graph_theory::{GraphError, Query};
    /// GraphError::not_found(Query::edge(0));
    /// GraphError::edge_not_found(0);
    /// ```
    NotFound { query: Query },

    /// Some index is not found in storage.
    ///
    /// # Examples
    ///
    /// - edge id 0 out of range
    ///
    /// ```
    /// use graph_theory::{GraphError, Query};
    /// GraphError::not_found(Query::edge(0));
    /// GraphError::edge_not_found(0);
    /// ```
    NotSupported { query: Query },
    /// Some index is out of range of storage.
    ///
    /// Max index is 5, but you query index 6.
    ///
    /// # Examples
    ///
    /// ```
    /// use graph_theory::{GraphError, Query};
    /// GraphError::not_found(Query::edge(0));
    /// GraphError::node_out_of_range(6, 5);
    /// ```
    OutOfRange {
        /// The entry type of the error.
        entry: GraphEntry,
        /// The entry index you want to access.
        index: usize,
        /// All elements count of the storage.
        max: usize,
    },
    /// An IO error occurred.
    ///
    /// # Examples
    ///
    /// ```
    /// use graph_theory::{GraphError, Query};
    /// ```
    IO {
        /// The position of the error occurred.
        entry: String,
        /// The wrapped IO error.
        error: std::io::Error,
    },
    /// # Arguments
    ///
    /// * `index`:
    ///
    /// returns: Option<Cow<Self::Node>>
    ///
    /// # Examples
    ///
    /// ```
    /// use graph_theory::GraphEngine;
    /// ```
    Custom {
        /// # Arguments
        message: String,
    },
}

impl Error for GraphError {}

impl Display for GraphError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.kind, f)
    }
}

impl Display for GraphErrorKind {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            GraphErrorKind::NotFound { query } => {
                write!(f, "{query:?} not found")
            }
            GraphErrorKind::NotSupported { query } => {
                write!(f, "{query:?} not found")
            }
            GraphErrorKind::OutOfRange { entry, index, max } => {
                write!(f, "{entry:?} index {index} is out of range, max index is {max}")
            }
            GraphErrorKind::Custom { message } => f.write_str(message),
            GraphErrorKind::IO { entry, error } if entry.is_empty() => {
                write!(f, "IO error: {error}", error = error)
            }
            GraphErrorKind::IO { entry, error } => {
                write!(f, "IO error at {entry:?}: {error}", entry = entry, error = error)
            }
        }
    }
}

impl GraphError {
    /// Some index is not found in storage.
    ///
    /// # Examples
    ///
    /// - edge id 0 out of range
    ///
    /// ```
    /// use graph_theory::{GraphError, Query};
    /// GraphError::not_found(Query::edge(0));
    /// GraphError::edge_not_found(0);
    /// ```
    pub fn custom<S>(message: S) -> Self
    where
        S: ToString,
    {
        Self { kind: Box::new(GraphErrorKind::Custom { message: message.to_string() }) }
    }
    /// Some index is not found in storage.
    ///
    /// # Examples
    ///
    /// - edge id 0 out of range
    ///
    /// ```
    /// use graph_theory::{GraphError, Query};
    /// GraphError::not_found(Query::edge(0));
    /// GraphError::edge_not_found(0);
    /// ```
    pub fn not_found<Q: Into<Query>>(query: Q) -> Self {
        Self { kind: Box::new(GraphErrorKind::NotFound { query: query.into() }) }
    }
    /// Some index is not found in storage.
    ///
    /// # Examples
    ///
    /// - edge id 0 out of range
    ///
    /// ```
    /// use graph_theory::{GraphError, Query};
    /// GraphError::not_found(Query::edge(0));
    /// GraphError::edge_not_found(0);
    /// ```
    pub fn not_support<Q: Into<Query>>(query: Q) -> Self {
        Self { kind: Box::new(GraphErrorKind::NotSupported { query: query.into() }) }
    }
    /// Fill where the io error occurred.
    ///
    /// # Examples
    ///
    /// - edge id 0 out of range
    ///
    /// ```
    /// use graph_theory::{GraphError, Query};
    /// GraphError::not_found(Query::edge(0));
    /// GraphError::edge_not_found(0);
    /// ```
    pub fn with_io_path<P>(mut self, path: P) -> Self
    where
        P: AsRef<Path>,
    {
        match self.kind.deref_mut() {
            GraphErrorKind::IO { entry, error: _ } => {
                *entry = path.as_ref().to_string_lossy().to_string();
                self
            }
            _ => self,
        }
    }
    /// Some index is not found in storage.
    ///
    /// # Examples
    ///
    /// - edge id 0 out of range
    ///
    /// ```
    /// use graph_theory::{GraphError, Query};
    /// GraphError::not_found(Query::edge(0));
    /// GraphError::edge_not_found(0);
    /// ```
    pub fn node_out_of_range(index: usize, max: usize) -> Self {
        Self { kind: Box::new(GraphErrorKind::OutOfRange { entry: GraphEntry::Node, index, max }) }
    }
    /// Some index is not found in storage.
    ///
    /// # Examples
    ///
    /// - edge id 0 out of range
    ///
    /// ```
    /// use graph_theory::{GraphError, Query};
    /// GraphError::not_found(Query::edge(0));
    /// ```
    pub fn edge_out_of_range(index: usize, max: usize) -> Self {
        Self { kind: Box::new(GraphErrorKind::OutOfRange { entry: GraphEntry::Edge, index, max }) }
    }
}