regex/
error.rs

1use std::fmt;
2use std::iter::repeat;
3
4/// An error that occurred during parsing or compiling a regular expression.
5#[derive(Clone, PartialEq)]
6pub enum Error {
7    /// A syntax error.
8    Syntax(String),
9    /// The compiled program exceeded the set size limit.
10    /// The argument is the size limit imposed.
11    CompiledTooBig(usize),
12    /// Hints that destructuring should not be exhaustive.
13    ///
14    /// This enum may grow additional variants, so this makes sure clients
15    /// don't count on exhaustive matching. (Otherwise, adding a new variant
16    /// could break existing code.)
17    #[doc(hidden)]
18    __Nonexhaustive,
19}
20
21impl ::std::error::Error for Error {
22    fn description(&self) -> &str {
23        match *self {
24            Error::Syntax(ref err) => err,
25            Error::CompiledTooBig(_) => "compiled program too big",
26            Error::__Nonexhaustive => unreachable!(),
27        }
28    }
29}
30
31impl fmt::Display for Error {
32    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
33        match *self {
34            Error::Syntax(ref err) => err.fmt(f),
35            Error::CompiledTooBig(limit) => write!(
36                f,
37                "Compiled regex exceeds size limit of {} bytes.",
38                limit
39            ),
40            Error::__Nonexhaustive => unreachable!(),
41        }
42    }
43}
44
45// We implement our own Debug implementation so that we show nicer syntax
46// errors when people use `Regex::new(...).unwrap()`. It's a little weird,
47// but the `Syntax` variant is already storing a `String` anyway, so we might
48// as well format it nicely.
49impl fmt::Debug for Error {
50    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
51        match *self {
52            Error::Syntax(ref err) => {
53                let hr: String = repeat('~').take(79).collect();
54                writeln!(f, "Syntax(")?;
55                writeln!(f, "{}", hr)?;
56                writeln!(f, "{}", err)?;
57                writeln!(f, "{}", hr)?;
58                write!(f, ")")?;
59                Ok(())
60            }
61            Error::CompiledTooBig(limit) => {
62                f.debug_tuple("CompiledTooBig").field(&limit).finish()
63            }
64            Error::__Nonexhaustive => {
65                f.debug_tuple("__Nonexhaustive").finish()
66            }
67        }
68    }
69}