magic_regexp/core/traits.rs
1use regex::Regex;
2use thiserror::Error;
3
4#[derive(Error, Debug)]
5/// An error, which can occur while using this crate.
6/// Mostly used to wrap errors from the Regex crate.
7pub enum Error {
8 #[error("An regex error occurred")]
9 RegexError(#[from] regex::Error),
10}
11
12/// A type, which is used to return results from this crate.
13/// Mostly used to wrap results from the Regex crate.
14pub type Result<T> = std::result::Result<T, Error>;
15
16/// A trait, which allows to convert something to a regex.
17/// Mostly needed to work with this lib and Regex crate.
18pub trait AsRegex: ToString {
19 /// Returns the regex, which represents the wanted statement.
20 fn as_regex(&self) -> Result<Regex> {
21 let regex = Regex::new(&self.to_string())?;
22 Ok(regex)
23 }
24}
25
26/// A trait, which allows to chain regex statements with conditions.
27/// Import this, if you want to use the `and`, `or` and `optionally` methods and chain statements.
28pub trait Condition: AsRegex + Sized {
29 /// Returns the regex, which chains the two given statements with an `and` condition.
30 fn and(self, other: impl AsRegex) -> Regex {
31 Regex::new(&format!("{}{}", self.to_string(), other.to_string()))
32 .expect("Invalid regex (and)")
33 }
34 /// Returns the regex, which chains the two given statements with an `or` condition.
35 fn or(self, other: impl AsRegex) -> Regex {
36 Regex::new(&format!("{}|{}", self.to_string(), other.to_string()))
37 .expect("Invalid regex (or)")
38 }
39 /// Returns the regex, which sets the given statement to optional.
40 fn optionally(self) -> Regex {
41 Regex::new(&format!("(?:{})?", self.to_string())).expect("Invalid regex (optionally)")
42 }
43}