|
| 1 | +use crate::Error; |
| 2 | +use pcre2::bytes::{Captures, Regex, RegexBuilder}; |
| 3 | +use std::collections::{btree_map, BTreeMap, HashMap}; |
| 4 | + |
| 5 | +/// The `Pattern` represents a compiled regex, ready to be matched against arbitrary text. |
| 6 | +#[derive(Debug)] |
| 7 | +pub struct Pcre2Pattern { |
| 8 | + regex: Regex, |
| 9 | + names: BTreeMap<String, usize>, |
| 10 | +} |
| 11 | + |
| 12 | +impl Pcre2Pattern { |
| 13 | + /// Creates a new pattern from a raw regex string and an alias map to identify the |
| 14 | + /// fields properly. |
| 15 | + pub(crate) fn new(regex: &str, alias: &HashMap<String, String>) -> Result<Self, Error> { |
| 16 | + let mut builder = RegexBuilder::new(); |
| 17 | + builder.jit_if_available(true); |
| 18 | + builder.utf(true); |
| 19 | + match builder.build(regex) { |
| 20 | + Ok(r) => Ok({ |
| 21 | + let mut names = BTreeMap::new(); |
| 22 | + for (i, name) in r.capture_names().iter().enumerate() { |
| 23 | + if let Some(name) = name { |
| 24 | + let name = match alias.iter().find(|&(_k, v)| v == name) { |
| 25 | + Some(item) => item.0.clone(), |
| 26 | + None => String::from(name), |
| 27 | + }; |
| 28 | + names.insert(name, i); |
| 29 | + } |
| 30 | + } |
| 31 | + Self { regex: r, names } |
| 32 | + }), |
| 33 | + Err(e) => Err(Error::RegexCompilationFailed(format!( |
| 34 | + "Regex compilation failed: {e:?}:\n{regex}" |
| 35 | + ))), |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + /// Matches this compiled `Pattern` against the text and returns the matches. |
| 40 | + pub fn match_against<'a>(&'a self, text: &'a str) -> Option<Pcre2Matches<'a>> { |
| 41 | + self.regex |
| 42 | + .captures(text.as_bytes()) |
| 43 | + .ok() |
| 44 | + .flatten() |
| 45 | + .map(|caps| Pcre2Matches { |
| 46 | + captures: caps, |
| 47 | + pattern: self, |
| 48 | + }) |
| 49 | + } |
| 50 | + |
| 51 | + /// Returns all names this `Pattern` captures. |
| 52 | + pub fn capture_names(&self) -> impl Iterator<Item = &str> { |
| 53 | + self.names.keys().map(|s| s.as_str()) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +/// The `Matches` represent matched results from a `Pattern` against a provided text. |
| 58 | +#[derive(Debug)] |
| 59 | +pub struct Pcre2Matches<'a> { |
| 60 | + captures: Captures<'a>, |
| 61 | + pattern: &'a Pcre2Pattern, |
| 62 | +} |
| 63 | + |
| 64 | +impl<'a> Pcre2Matches<'a> { |
| 65 | + /// Gets the value for the name (or) alias if found, `None` otherwise. |
| 66 | + pub fn get(&self, name_or_alias: &str) -> Option<&str> { |
| 67 | + self.pattern |
| 68 | + .names |
| 69 | + .get(name_or_alias) |
| 70 | + .and_then(|&idx| self.captures.get(idx)) |
| 71 | + .map(|m| std::str::from_utf8(m.as_bytes()).unwrap()) |
| 72 | + } |
| 73 | + |
| 74 | + /// Returns the number of matches. |
| 75 | + pub fn len(&self) -> usize { |
| 76 | + self.pattern.names.len() |
| 77 | + } |
| 78 | + |
| 79 | + /// Returns true if there are no matches, false otherwise. |
| 80 | + pub fn is_empty(&self) -> bool { |
| 81 | + self.len() == 0 |
| 82 | + } |
| 83 | + |
| 84 | + /// Returns a tuple of key/value with all the matches found. |
| 85 | + /// |
| 86 | + /// Note that if no match is found, the value is empty. |
| 87 | + pub fn iter(&'a self) -> Pcre2MatchesIter<'a> { |
| 88 | + Pcre2MatchesIter { |
| 89 | + captures: &self.captures, |
| 90 | + names: self.pattern.names.iter(), |
| 91 | + } |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +impl<'a> IntoIterator for &'a Pcre2Matches<'a> { |
| 96 | + type Item = (&'a str, &'a str); |
| 97 | + type IntoIter = Pcre2MatchesIter<'a>; |
| 98 | + |
| 99 | + fn into_iter(self) -> Self::IntoIter { |
| 100 | + self.iter() |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +/// An `Iterator` over all matches, accessible via `Matches`. |
| 105 | +pub struct Pcre2MatchesIter<'a> { |
| 106 | + captures: &'a Captures<'a>, |
| 107 | + names: btree_map::Iter<'a, String, usize>, |
| 108 | +} |
| 109 | + |
| 110 | +impl<'a> Iterator for Pcre2MatchesIter<'a> { |
| 111 | + type Item = (&'a str, &'a str); |
| 112 | + |
| 113 | + fn next(&mut self) -> Option<Self::Item> { |
| 114 | + for (k, &v) in self.names.by_ref() { |
| 115 | + if let Some(m) = self.captures.get(v) { |
| 116 | + return Some((k.as_str(), std::str::from_utf8(m.as_bytes()).unwrap())); |
| 117 | + } |
| 118 | + } |
| 119 | + None |
| 120 | + } |
| 121 | +} |
0 commit comments