termimage/
error.rs

1use std::io::Write;
2
3
4/// Enum representing all possible values the application can fail.
5#[derive(Debug, Clone, Hash, PartialEq, Eq)]
6pub enum Error {
7    /// Failed to guess the image format.
8    GuessingFormatFailed(String),
9    /// Failed to open image file.
10    OpeningImageFailed(String),
11}
12
13impl Error {
14    /// Get the executable exit value from an `Error` instance.
15    ///
16    /// # Examples
17    ///
18    /// ```
19    /// # use termimage::Error;
20    /// # use std::iter::FromIterator;
21    /// let mut out = Vec::new();
22    /// Error::GuessingFormatFailed("not_image.rs".to_string()).print_error(&mut out);
23    /// assert_eq!(String::from_iter(out.iter().map(|&i| i as char)),
24    ///            "Failed to guess format of \"not_image.rs\".\n".to_string());
25    /// ```
26    pub fn print_error<W: Write>(&self, err_out: &mut W) {
27        match *self {
28            Error::GuessingFormatFailed(ref fname) => writeln!(err_out, "Failed to guess format of \"{}\".", fname).unwrap(),
29            Error::OpeningImageFailed(ref fname) => writeln!(err_out, "Failed to open image file \"{}\".", fname).unwrap(),
30        }
31    }
32
33    /// Get the executable exit value from an `Error` instance.
34    ///
35    /// # Examples
36    ///
37    /// ```
38    /// # use std::process::exit;
39    /// # use termimage::Error;
40    /// assert_eq!(Error::GuessingFormatFailed("".to_string()).exit_value(), 1);
41    /// assert_eq!(Error::OpeningImageFailed("".to_string()).exit_value(), 2);
42    /// ```
43    pub fn exit_value(&self) -> i32 {
44        match *self {
45            Error::GuessingFormatFailed(_) => 1,
46            Error::OpeningImageFailed(_) => 2,
47        }
48    }
49}