io_error/lib.rs
1//! Convenient macro for creating I/O errors.
2//!
3//! This adds a macro, `err!()` which is used to create `std::io::Error` values. Refer to the
4//! documentation of the macro for usage.
5
6use std::{error, fmt};
7
8/// Not used in public.
9#[doc(hidden)]
10#[derive(Debug)]
11pub struct Err {
12 /// Description of the error.
13 pub desc: &'static str,
14 /// The formatted string of the error.
15 pub fmt: String,
16}
17
18impl fmt::Display for Err {
19 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
20 write!(f, "{}", self.fmt)
21 }
22}
23
24impl error::Error for Err {
25 fn description(&self) -> &str {
26 self.desc
27 }
28}
29
30/// Create an I/O error.
31///
32/// This constructs a value of type `std::io::Error` defined by the given parameter.
33///
34/// The first argument defines the kind (`std::io::ErrorKind`) of the error. There is no need for
35/// importing the type, as it is already prefixed with the enum.
36///
37/// The second argument is the description of the error, given in the form of a string literal.
38///
39/// The rest arguments are the usual formatting syntax (like `println!()`) representing the
40/// `Display` implementation of the error. If none, it will simply use the second argument (the
41/// description).
42///
43/// # Example
44///
45/// ```rust
46/// #[macro_use]
47/// extern crate io_error;
48///
49/// let x = 42 + 3;
50/// let error = err!(NotFound, "my error description", "this is an error, x is {}", x);
51/// let error2 = err!(InvalidData, "my second error description");
52/// ```
53#[macro_export]
54macro_rules! err {
55 ($kind:ident, $desc:expr, $($rest:tt)*) => {
56 // Construct the I/O error.
57 ::std::io::Error::new(::std::io::ErrorKind::$kind, $crate::Err {
58 desc: $desc,
59 fmt: format!($($rest)*),
60 })
61 };
62 // If the formatter is excluded, we default to the description.
63 ($kind:ident, $desc:expr) => {
64 err!($kind, $desc, "{}", $desc)
65 };
66}
67
68#[cfg(test)]
69mod tests {
70 #[test]
71 fn test() {
72 let _ = err!(NotFound, "test");
73 let _ = err!(NotFound, "test", "x {} y", 2 + 2);
74 }
75}