"Fossies" - the Fresh Open Source Software Archive

Member "fd-8.1.1/src/regex_helper.rs" (25 May 2020, 1825 Bytes) of package /linux/privat/fd-8.1.1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Rust source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 use regex_syntax::hir::Hir;
    2 use regex_syntax::ParserBuilder;
    3 
    4 /// Determine if a regex pattern contains a literal uppercase character.
    5 pub fn pattern_has_uppercase_char(pattern: &str) -> bool {
    6     let mut parser = ParserBuilder::new().allow_invalid_utf8(true).build();
    7 
    8     parser
    9         .parse(pattern)
   10         .map(|hir| hir_has_uppercase_char(&hir))
   11         .unwrap_or(false)
   12 }
   13 
   14 /// Determine if a regex expression contains a literal uppercase character.
   15 fn hir_has_uppercase_char(hir: &Hir) -> bool {
   16     use regex_syntax::hir::*;
   17 
   18     match *hir.kind() {
   19         HirKind::Literal(Literal::Unicode(c)) => c.is_uppercase(),
   20         HirKind::Literal(Literal::Byte(b)) => char::from(b).is_uppercase(),
   21         HirKind::Class(Class::Unicode(ref ranges)) => ranges
   22             .iter()
   23             .any(|r| r.start().is_uppercase() || r.end().is_uppercase()),
   24         HirKind::Class(Class::Bytes(ref ranges)) => ranges
   25             .iter()
   26             .any(|r| char::from(r.start()).is_uppercase() || char::from(r.end()).is_uppercase()),
   27         HirKind::Group(Group { ref hir, .. }) | HirKind::Repetition(Repetition { ref hir, .. }) => {
   28             hir_has_uppercase_char(hir)
   29         }
   30         HirKind::Concat(ref hirs) | HirKind::Alternation(ref hirs) => {
   31             hirs.iter().any(hir_has_uppercase_char)
   32         }
   33         _ => false,
   34     }
   35 }
   36 
   37 #[test]
   38 fn pattern_has_uppercase_char_simple() {
   39     assert!(pattern_has_uppercase_char("A"));
   40     assert!(pattern_has_uppercase_char("foo.EXE"));
   41 
   42     assert!(!pattern_has_uppercase_char("a"));
   43     assert!(!pattern_has_uppercase_char("foo.exe123"));
   44 }
   45 
   46 #[test]
   47 fn pattern_has_uppercase_char_advanced() {
   48     assert!(pattern_has_uppercase_char("foo.[a-zA-Z]"));
   49 
   50     assert!(!pattern_has_uppercase_char(r"\Acargo"));
   51     assert!(!pattern_has_uppercase_char(r"carg\x6F"));
   52 }