php_std/pcre/compiled.rs
1//! A PHP regex compiled once and matched many times: `preg_match()` without
2//! the per-call cache lookup, for libraries that run fixed patterns on a hot
3//! path (`utopia-user-agent` runs its tables on every request).
4//!
5//! | PHP | Rust |
6//! |---|---|
7//! | `preg_match($re, $s, $m) === 1`, then `$m[$n]` | [`Regex::compiled`], [`Regex::captures`], [`Captures::get`] |
8//! | `preg_match($re, $s) === 1` | [`Regex::is_match`] |
9//!
10//! Both run exactly the calls `preg_match()` makes, so a match that fails
11//! (`pcre.backtrack_limit`, the JIT stack) is no match, as `preg_match()`
12//! returning `false` is not `1`. They do not set `preg_last_error()`.
13
14use std::sync::Arc;
15
16use super::ffi::UNSET;
17use super::{Call, CompileFailure, Regex, cached};
18
19/// The groups of one match of [`Regex::captures`], as `preg_match()` puts
20/// them in `$matches`.
21#[derive(Debug, Clone)]
22pub struct Captures<'s> {
23 subject: &'s [u8],
24 ovector: Offsets,
25}
26
27/// The offset pairs of the groups a match set: inline for up to
28/// [`INLINE`] groups, which is most patterns.
29#[derive(Debug, Clone)]
30enum Offsets {
31 Inline { len: usize, pairs: [usize; 2 * INLINE] },
32 Heap(Vec<usize>),
33}
34
35const INLINE: usize = 6;
36
37impl Offsets {
38 fn new(ov: &[usize]) -> Self {
39 if ov.len() <= 2 * INLINE {
40 let mut pairs = [0; 2 * INLINE];
41 pairs[..ov.len()].copy_from_slice(ov);
42 Offsets::Inline { len: ov.len(), pairs }
43 } else {
44 Offsets::Heap(ov.to_vec())
45 }
46 }
47
48 fn as_slice(&self) -> &[usize] {
49 match self {
50 Offsets::Inline { len, pairs } => &pairs[..*len],
51 Offsets::Heap(v) => v,
52 }
53 }
54}
55
56impl<'s> Captures<'s> {
57 /// `$matches[$group]`: `None` when `$matches` has no such key (groups
58 /// after the last one that took part in the match); an unset group
59 /// before it is `""`.
60 pub fn get(&self, group: usize) -> Option<&'s [u8]> {
61 let ov = self.ovector.as_slice();
62 let (start, end) = (*ov.get(2 * group)?, ov[2 * group + 1]);
63 Some(if start == UNSET { &[] } else { &self.subject[start..end] })
64 }
65
66 /// `count($matches)` (without named groups): the whole match and every
67 /// group up to the last one set.
68 pub fn len(&self) -> usize {
69 self.ovector.as_slice().len() / 2
70 }
71
72 /// Always `false`: a match has at least the whole match.
73 pub fn is_empty(&self) -> bool {
74 self.ovector.as_slice().is_empty()
75 }
76}
77
78impl Regex {
79 /// `pcre_get_compiled_regex_cache()` as `preg_match()` calls it: the
80 /// pattern from the per-process cache, compiled (JIT included, as the
81 /// process has it) on a miss. A pattern that does not compile is the
82 /// warning `preg_match()` emits for it.
83 pub fn compiled(regex: &[u8]) -> Result<Arc<Regex>, CompileFailure> {
84 cached("preg_match", regex).map(|(re, _)| re).map_err(|message| CompileFailure { message })
85 }
86
87 /// `preg_match($regex, $subject, $matches) === 1`: the groups of the
88 /// first match, or `None` when there is none or the match fails.
89 pub fn captures<'s>(&self, subject: &'s [u8]) -> Option<Captures<'s>> {
90 let mut session = self.session();
91 match self.call(&mut session, subject, 0, self.first_call(subject.is_empty())) {
92 Ok(Some(count)) => {
93 let ov = session.ovector(count);
94 (ov[1] >= ov[0]).then(|| Captures { subject, ovector: Offsets::new(ov) })
95 }
96 _ => None,
97 }
98 }
99
100 /// `preg_match($regex, $subject) === 1`. Without `$matches`, PHP
101 /// retries an empty match at the same position (anchored, not empty at
102 /// start), and a failure there makes the result `false`.
103 pub fn is_match(&self, subject: &[u8]) -> bool {
104 let mut session = self.session();
105 match self.call(&mut session, subject, 0, self.first_call(subject.is_empty())) {
106 Ok(Some(count)) => {
107 let ov = session.ovector(count);
108 let (start, end) = (ov[0], ov[1]);
109 end != start || self.call(&mut session, subject, end, Call::Retry).is_ok()
110 }
111 _ => false,
112 }
113 }
114}