1 use std::fmt; 2 use std::iter::repeat; 3 4 /// An error that occurred during parsing or compiling a regular expression. 5 #[derive(Clone, PartialEq)] 6 pub 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 21 impl ::std::error::Error for Error { 22 // TODO: Remove this method entirely on the next breaking semver release. 23 #[allow(deprecated)] description(&self) -> &str24 fn description(&self) -> &str { 25 match *self { 26 Error::Syntax(ref err) => err, 27 Error::CompiledTooBig(_) => "compiled program too big", 28 Error::__Nonexhaustive => unreachable!(), 29 } 30 } 31 } 32 33 impl fmt::Display for Error { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result34 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 35 match *self { 36 Error::Syntax(ref err) => err.fmt(f), 37 Error::CompiledTooBig(limit) => write!( 38 f, 39 "Compiled regex exceeds size limit of {} bytes.", 40 limit 41 ), 42 Error::__Nonexhaustive => unreachable!(), 43 } 44 } 45 } 46 47 // We implement our own Debug implementation so that we show nicer syntax 48 // errors when people use `Regex::new(...).unwrap()`. It's a little weird, 49 // but the `Syntax` variant is already storing a `String` anyway, so we might 50 // as well format it nicely. 51 impl fmt::Debug for Error { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result52 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 53 match *self { 54 Error::Syntax(ref err) => { 55 let hr: String = repeat('~').take(79).collect(); 56 writeln!(f, "Syntax(")?; 57 writeln!(f, "{}", hr)?; 58 writeln!(f, "{}", err)?; 59 writeln!(f, "{}", hr)?; 60 write!(f, ")")?; 61 Ok(()) 62 } 63 Error::CompiledTooBig(limit) => { 64 f.debug_tuple("CompiledTooBig").field(&limit).finish() 65 } 66 Error::__Nonexhaustive => { 67 f.debug_tuple("__Nonexhaustive").finish() 68 } 69 } 70 } 71 } 72