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
use std::{fmt, result};

/// The result type for argument parsers.
pub type Result<T> = result::Result<T, Error>;

/// The error type for argument parser.
#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct Error {
    option:     String,
    message:    String,
}

impl Error {
    /// Creates an argument error from any type that can be stringified.
    pub fn from_string<S: ToString + ?Sized>(e: &S) -> Self {
        Error {
            option:    String::new(),
            message:   e.to_string(),
        }
    }

    /// Sets the particular option that triggered the error.
    pub fn with_option<S: Into<String>>(mut self, option: S) -> Self {
        self.option = option.into();
        self
    }
}

impl ::std::error::Error for Error {
    fn description(&self) -> &str {
        "Argument parsing error"
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if !self.option.is_empty() {
            write!(f, "option {}: ", self.option)?;
        }

        write!(f, "{}", self.message)
    }
}