surrealpatch/src/sql/regex.rs

83 lines
1.7 KiB
Rust
Raw Normal View History

use nom::bytes::complete::escaped;
2020-06-29 15:36:01 +00:00
use nom::bytes::complete::is_not;
use nom::bytes::complete::tag;
use nom::character::complete::one_of;
2020-06-29 15:36:01 +00:00
use nom::IResult;
use serde::{Deserialize, Serialize};
2021-03-29 15:43:37 +00:00
use std::cmp::Ordering;
2020-06-29 15:36:01 +00:00
use std::fmt;
use std::str;
2021-03-29 15:43:37 +00:00
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2020-06-29 15:36:01 +00:00
pub struct Regex {
2021-03-29 15:43:37 +00:00
pub input: String,
#[serde(skip)]
pub value: Option<regex::Regex>,
2020-06-29 15:36:01 +00:00
}
impl<'a> From<&'a str> for Regex {
fn from(r: &str) -> Regex {
let r = r.replace("\\/", "/");
let r = r.as_str();
2020-06-29 15:36:01 +00:00
Regex {
2021-03-29 15:43:37 +00:00
input: String::from(r),
value: match regex::Regex::new(r) {
Ok(v) => Some(v),
Err(_) => None,
},
2020-06-29 15:36:01 +00:00
}
}
}
2021-03-29 15:43:37 +00:00
impl PartialEq for Regex {
fn eq(&self, other: &Self) -> bool {
self.input == other.input
}
}
impl PartialOrd for Regex {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.input.cmp(&other.input))
}
}
2020-06-29 15:36:01 +00:00
impl fmt::Display for Regex {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2021-03-29 15:43:37 +00:00
write!(f, "/{}/", &self.input)
2020-06-29 15:36:01 +00:00
}
}
pub fn regex(i: &str) -> IResult<&str, Regex> {
let (i, _) = tag("/")(i)?;
let (i, v) = escaped(is_not("\\/"), '\\', one_of("/"))(i)?;
let (i, _) = tag("/")(i)?;
2020-06-29 15:36:01 +00:00
Ok((i, Regex::from(v)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn regex_simple() {
let sql = "/test/";
let res = regex(sql);
assert!(res.is_ok());
let out = res.unwrap().1;
assert_eq!("/test/", format!("{}", out));
assert_eq!(out, Regex::from("test"));
}
#[test]
fn regex_complex() {
let sql = r"/test\/[a-z]+\/.*/";
2020-06-29 15:36:01 +00:00
let res = regex(sql);
assert!(res.is_ok());
let out = res.unwrap().1;
assert_eq!(r"/test/[a-z]+/.*/", format!("{}", out));
assert_eq!(out, Regex::from("test/[a-z]+/.*"));
2020-06-29 15:36:01 +00:00
}
}