Debian Codegraph @

third_party/rust/regex/src/builders.rs

raw
1 #![allow(warnings)]
2
3 // This module defines an internal builder that encapsulates all interaction
4 // with meta::Regex construction, and then 4 public API builders that wrap
5 // around it. The docs are essentially repeated on each of the 4 public
6 // builders, with tweaks to the examples as needed.
7 //
8 // The reason why there are so many builders is partially because of a misstep
9 // in the initial API design: the builder constructor takes in the pattern
10 // strings instead of using the `build` method to accept the pattern strings.
11 // This means `new` has a different signature for each builder. It probably
12 // would have been nicer to to use one builder with `fn new()`, and then add
13 // `build(pat)` and `build_many(pats)` constructors.
14 //
15 // The other reason is because I think the `bytes` module should probably
16 // have its own builder type. That way, it is completely isolated from the
17 // top-level API.
18 //
19 // If I could do it again, I'd probably have a `regex::Builder` and a
20 // `regex::bytes::Builder`. Each would have `build` and `build_set` (or
21 // `build_many`) methods for constructing a single pattern `Regex` and a
22 // multi-pattern `RegexSet`, respectively.
23
24 use alloc::{
25 string::{String, ToString},
26 sync::Arc,
27 vec,
28 vec::Vec,
29 };
30
31 use regex_automata::{
32 meta, nfa::thompson::WhichCaptures, util::syntax, MatchKind,
33 };
34
35 use crate::error::Error;
36
37 /// A builder for constructing a `Regex`, `bytes::Regex`, `RegexSet` or a
38 /// `bytes::RegexSet`.
39 ///
40 /// This is essentially the implementation of the four different builder types
41 /// in the public API: `RegexBuilder`, `bytes::RegexBuilder`, `RegexSetBuilder`
42 /// and `bytes::RegexSetBuilder`.
43 #[derive(Clone, Debug)]
44 struct Builder {
45 pats: Vec<String>,
46 metac: meta::Config,
47 syntaxc: syntax::Config,
48 }
49
50 impl Default for Builder {
51 fn default() -> Builder {
52 let metac = meta::Config::new()
53 .nfa_size_limit(Some(10 * (1 << 20)))
54 .hybrid_cache_capacity(2 * (1 << 20));
55 Builder { pats: vec![], metac, syntaxc: syntax::Config::default() }
56 }
57 }
58
59 impl Builder {
60 fn new<I, S>(patterns: I) -> Builder
61 where
62 S: AsRef<str>,
63 I: IntoIterator<Item = S>,
64 {
65 let mut b = Builder::default();
66 b.pats.extend(patterns.into_iter().map(|p| p.as_ref().to_string()));
67 b
68 }
69
70 fn build_one_string(&self) -> Result<crate::Regex, Error> {
71 assert_eq!(1, self.pats.len());
72 let metac = self
73 .metac
74 .clone()
75 .match_kind(MatchKind::LeftmostFirst)
76 .utf8_empty(true);
77 let syntaxc = self.syntaxc.clone().utf8(true);
78 let pattern = Arc::from(self.pats[0].as_str());
79 meta::Builder::new()
80 .configure(metac)
81 .syntax(syntaxc)
82 .build(&pattern)
83 .map(|meta| crate::Regex { meta, pattern })
84 .map_err(Error::from_meta_build_error)
85 }
86
87 fn build_one_bytes(&self) -> Result<crate::bytes::Regex, Error> {
88 assert_eq!(1, self.pats.len());
89 let metac = self
90 .metac
91 .clone()
92 .match_kind(MatchKind::LeftmostFirst)
93 .utf8_empty(false);
94 let syntaxc = self.syntaxc.clone().utf8(false);
95 let pattern = Arc::from(self.pats[0].as_str());
96 meta::Builder::new()
97 .configure(metac)
98 .syntax(syntaxc)
99 .build(&pattern)
100 .map(|meta| crate::bytes::Regex { meta, pattern })
101 .map_err(Error::from_meta_build_error)
102 }
103
104 fn build_many_string(&self) -> Result<crate::RegexSet, Error> {
105 let metac = self
106 .metac
107 .clone()
108 .match_kind(MatchKind::All)
109 .utf8_empty(true)
110 .which_captures(WhichCaptures::None);
111 let syntaxc = self.syntaxc.clone().utf8(true);
112 let patterns = Arc::from(self.pats.as_slice());
113 meta::Builder::new()
114 .configure(metac)
115 .syntax(syntaxc)
116 .build_many(&patterns)
117 .map(|meta| crate::RegexSet { meta, patterns })
118 .map_err(Error::from_meta_build_error)
119 }
120
121 fn build_many_bytes(&self) -> Result<crate::bytes::RegexSet, Error> {
122 let metac = self
123 .metac
124 .clone()
125 .match_kind(MatchKind::All)
126 .utf8_empty(false)
127 .which_captures(WhichCaptures::None);
128 let syntaxc = self.syntaxc.clone().utf8(false);
129 let patterns = Arc::from(self.pats.as_slice());
130 meta::Builder::new()
131 .configure(metac)
132 .syntax(syntaxc)
133 .build_many(&patterns)
134 .map(|meta| crate::bytes::RegexSet { meta, patterns })
135 .map_err(Error::from_meta_build_error)
136 }
137
138 fn case_insensitive(&mut self, yes: bool) -> &mut Builder {
139 self.syntaxc = self.syntaxc.case_insensitive(yes);
140 self
141 }
142
143 fn multi_line(&mut self, yes: bool) -> &mut Builder {
144 self.syntaxc = self.syntaxc.multi_line(yes);
145 self
146 }
147
148 fn dot_matches_new_line(&mut self, yes: bool) -> &mut Builder {
149 self.syntaxc = self.syntaxc.dot_matches_new_line(yes);
150 self
151 }
152
153 fn crlf(&mut self, yes: bool) -> &mut Builder {
154 self.syntaxc = self.syntaxc.crlf(yes);
155 self
156 }
157
158 fn line_terminator(&mut self, byte: u8) -> &mut Builder {
159 self.metac = self.metac.clone().line_terminator(byte);
160 self.syntaxc = self.syntaxc.line_terminator(byte);
161 self
162 }
163
164 fn swap_greed(&mut self, yes: bool) -> &mut Builder {
165 self.syntaxc = self.syntaxc.swap_greed(yes);
166 self
167 }
168
169 fn ignore_whitespace(&mut self, yes: bool) -> &mut Builder {
170 self.syntaxc = self.syntaxc.ignore_whitespace(yes);
171 self
172 }
173
174 fn unicode(&mut self, yes: bool) -> &mut Builder {
175 self.syntaxc = self.syntaxc.unicode(yes);
176 self
177 }
178
179 fn octal(&mut self, yes: bool) -> &mut Builder {
180 self.syntaxc = self.syntaxc.octal(yes);
181 self
182 }
183
184 fn size_limit(&mut self, limit: usize) -> &mut Builder {
185 self.metac = self.metac.clone().nfa_size_limit(Some(limit));
186 self
187 }
188
189 fn dfa_size_limit(&mut self, limit: usize) -> &mut Builder {
190 self.metac = self.metac.clone().hybrid_cache_capacity(limit);
191 self
192 }
193
194 fn nest_limit(&mut self, limit: u32) -> &mut Builder {
195 self.syntaxc = self.syntaxc.nest_limit(limit);
196 self
197 }
198 }
199
200 pub(crate) mod string {
201 use crate::{error::Error, Regex, RegexSet};
202
203 use super::Builder;
204
205 /// A configurable builder for a [`Regex`].
206 ///
207 /// This builder can be used to programmatically set flags such as `i`
208 /// (case insensitive) and `x` (for verbose mode). This builder can also be
209 /// used to configure things like the line terminator and a size limit on
210 /// the compiled regular expression.
211 #[derive(Clone, Debug)]
212 pub struct RegexBuilder {
213 builder: Builder,
214 }
215
216 impl RegexBuilder {
217 /// Create a new builder with a default configuration for the given
218 /// pattern.
219 ///
220 /// If the pattern is invalid or exceeds the configured size limits,
221 /// then an error will be returned when [`RegexBuilder::build`] is
222 /// called.
223 pub fn new(pattern: &str) -> RegexBuilder {
224 RegexBuilder { builder: Builder::new([pattern]) }
225 }
226
227 /// Compiles the pattern given to `RegexBuilder::new` with the
228 /// configuration set on this builder.
229 ///
230 /// If the pattern isn't a valid regex or if a configured size limit
231 /// was exceeded, then an error is returned.
232 pub fn build(&self) -> Result<Regex, Error> {
233 self.builder.build_one_string()
234 }
235
236 /// This configures Unicode mode for the entire pattern.
237 ///
238 /// Enabling Unicode mode does a number of things:
239 ///
240 /// * Most fundamentally, it causes the fundamental atom of matching
241 /// to be a single codepoint. When Unicode mode is disabled, it's a
242 /// single byte. For example, when Unicode mode is enabled, `.` will
243 /// match `💩` once, where as it will match 4 times when Unicode mode
244 /// is disabled. (Since the UTF-8 encoding of `💩` is 4 bytes long.)
245 /// * Case insensitive matching uses Unicode simple case folding rules.
246 /// * Unicode character classes like `\p{Letter}` and `\p{Greek}` are
247 /// available.
248 /// * Perl character classes are Unicode aware. That is, `\w`, `\s` and
249 /// `\d`.
250 /// * The word boundary assertions, `\b` and `\B`, use the Unicode
251 /// definition of a word character.
252 ///
253 /// Note that if Unicode mode is disabled, then the regex will fail to
254 /// compile if it could match invalid UTF-8. For example, when Unicode
255 /// mode is disabled, then since `.` matches any byte (except for
256 /// `\n`), then it can match invalid UTF-8 and thus building a regex
257 /// from it will fail. Another example is `\w` and `\W`. Since `\w` can
258 /// only match ASCII bytes when Unicode mode is disabled, it's allowed.
259 /// But `\W` can match more than ASCII bytes, including invalid UTF-8,
260 /// and so it is not allowed. This restriction can be lifted only by
261 /// using a [`bytes::Regex`](crate::bytes::Regex).
262 ///
263 /// For more details on the Unicode support in this crate, see the
264 /// [Unicode section](crate#unicode) in this crate's top-level
265 /// documentation.
266 ///
267 /// The default for this is `true`.
268 ///
269 /// # Example
270 ///
271 /// ```
272 /// use regex::RegexBuilder;
273 ///
274 /// let re = RegexBuilder::new(r"\w")
275 /// .unicode(false)
276 /// .build()
277 /// .unwrap();
278 /// // Normally greek letters would be included in \w, but since
279 /// // Unicode mode is disabled, it only matches ASCII letters.
280 /// assert!(!re.is_match("δ"));
281 ///
282 /// let re = RegexBuilder::new(r"s")
283 /// .case_insensitive(true)
284 /// .unicode(false)
285 /// .build()
286 /// .unwrap();
287 /// // Normally 'ſ' is included when searching for 's' case
288 /// // insensitively due to Unicode's simple case folding rules. But
289 /// // when Unicode mode is disabled, only ASCII case insensitive rules
290 /// // are used.
291 /// assert!(!re.is_match("ſ"));
292 /// ```
293 pub fn unicode(&mut self, yes: bool) -> &mut RegexBuilder {
294 self.builder.unicode(yes);
295 self
296 }
297
298 /// This configures whether to enable case insensitive matching for the
299 /// entire pattern.
300 ///
301 /// This setting can also be configured using the inline flag `i`
302 /// in the pattern. For example, `(?i:foo)` matches `foo` case
303 /// insensitively while `(?-i:foo)` matches `foo` case sensitively.
304 ///
305 /// The default for this is `false`.
306 ///
307 /// # Example
308 ///
309 /// ```
310 /// use regex::RegexBuilder;
311 ///
312 /// let re = RegexBuilder::new(r"foo(?-i:bar)quux")
313 /// .case_insensitive(true)
314 /// .build()
315 /// .unwrap();
316 /// assert!(re.is_match("FoObarQuUx"));
317 /// // Even though case insensitive matching is enabled in the builder,
318 /// // it can be locally disabled within the pattern. In this case,
319 /// // `bar` is matched case sensitively.
320 /// assert!(!re.is_match("fooBARquux"));
321 /// ```
322 pub fn case_insensitive(&mut self, yes: bool) -> &mut RegexBuilder {
323 self.builder.case_insensitive(yes);
324 self
325 }
326
327 /// This configures multi-line mode for the entire pattern.
328 ///
329 /// Enabling multi-line mode changes the behavior of the `^` and `$`
330 /// anchor assertions. Instead of only matching at the beginning and
331 /// end of a haystack, respectively, multi-line mode causes them to
332 /// match at the beginning and end of a line *in addition* to the
333 /// beginning and end of a haystack. More precisely, `^` will match at
334 /// the position immediately following a `\n` and `$` will match at the
335 /// position immediately preceding a `\n`.
336 ///
337 /// The behavior of this option can be impacted by other settings too:
338 ///
339 /// * The [`RegexBuilder::line_terminator`] option changes `\n` above
340 /// to any ASCII byte.
341 /// * The [`RegexBuilder::crlf`] option changes the line terminator to
342 /// be either `\r` or `\n`, but never at the position between a `\r`
343 /// and `\n`.
344 ///
345 /// This setting can also be configured using the inline flag `m` in
346 /// the pattern.
347 ///
348 /// The default for this is `false`.
349 ///
350 /// # Example
351 ///
352 /// ```
353 /// use regex::RegexBuilder;
354 ///
355 /// let re = RegexBuilder::new(r"^foo$")
356 /// .multi_line(true)
357 /// .build()
358 /// .unwrap();
359 /// assert_eq!(Some(1..4), re.find("\nfoo\n").map(|m| m.range()));
360 /// ```
361 pub fn multi_line(&mut self, yes: bool) -> &mut RegexBuilder {
362 self.builder.multi_line(yes);
363 self
364 }
365
366 /// This configures dot-matches-new-line mode for the entire pattern.
367 ///
368 /// Perhaps surprisingly, the default behavior for `.` is not to match
369 /// any character, but rather, to match any character except for the
370 /// line terminator (which is `\n` by default). When this mode is
371 /// enabled, the behavior changes such that `.` truly matches any
372 /// character.
373 ///
374 /// This setting can also be configured using the inline flag `s` in
375 /// the pattern. For example, `(?s:.)` and `\p{any}` are equivalent
376 /// regexes.
377 ///
378 /// The default for this is `false`.
379 ///
380 /// # Example
381 ///
382 /// ```
383 /// use regex::RegexBuilder;
384 ///
385 /// let re = RegexBuilder::new(r"foo.bar")
386 /// .dot_matches_new_line(true)
387 /// .build()
388 /// .unwrap();
389 /// let hay = "foo\nbar";
390 /// assert_eq!(Some("foo\nbar"), re.find(hay).map(|m| m.as_str()));
391 /// ```
392 pub fn dot_matches_new_line(
393 &mut self,
394 yes: bool,
395 ) -> &mut RegexBuilder {
396 self.builder.dot_matches_new_line(yes);
397 self
398 }
399
400 /// This configures CRLF mode for the entire pattern.
401 ///
402 /// When CRLF mode is enabled, both `\r` ("carriage return" or CR for
403 /// short) and `\n` ("line feed" or LF for short) are treated as line
404 /// terminators. This results in the following:
405 ///
406 /// * Unless dot-matches-new-line mode is enabled, `.` will now match
407 /// any character except for `\n` and `\r`.
408 /// * When multi-line mode is enabled, `^` will match immediately
409 /// following a `\n` or a `\r`. Similarly, `$` will match immediately
410 /// preceding a `\n` or a `\r`. Neither `^` nor `$` will ever match
411 /// between `\r` and `\n`.
412 ///
413 /// This setting can also be configured using the inline flag `R` in
414 /// the pattern.
415 ///
416 /// The default for this is `false`.
417 ///
418 /// # Example
419 ///
420 /// ```
421 /// use regex::RegexBuilder;
422 ///
423 /// let re = RegexBuilder::new(r"^foo$")
424 /// .multi_line(true)
425 /// .crlf(true)
426 /// .build()
427 /// .unwrap();
428 /// let hay = "\r\nfoo\r\n";
429 /// // If CRLF mode weren't enabled here, then '$' wouldn't match
430 /// // immediately after 'foo', and thus no match would be found.
431 /// assert_eq!(Some("foo"), re.find(hay).map(|m| m.as_str()));
432 /// ```
433 ///
434 /// This example demonstrates that `^` will never match at a position
435 /// between `\r` and `\n`. (`$` will similarly not match between a `\r`
436 /// and a `\n`.)
437 ///
438 /// ```
439 /// use regex::RegexBuilder;
440 ///
441 /// let re = RegexBuilder::new(r"^")
442 /// .multi_line(true)
443 /// .crlf(true)
444 /// .build()
445 /// .unwrap();
446 /// let hay = "\r\n\r\n";
447 /// let ranges: Vec<_> = re.find_iter(hay).map(|m| m.range()).collect();
448 /// assert_eq!(ranges, vec![0..0, 2..2, 4..4]);
449 /// ```
450 pub fn crlf(&mut self, yes: bool) -> &mut RegexBuilder {
451 self.builder.crlf(yes);
452 self
453 }
454
455 /// Configures the line terminator to be used by the regex.
456 ///
457 /// The line terminator is relevant in two ways for a particular regex:
458 ///
459 /// * When dot-matches-new-line mode is *not* enabled (the default),
460 /// then `.` will match any character except for the configured line
461 /// terminator.
462 /// * When multi-line mode is enabled (not the default), then `^` and
463 /// `$` will match immediately after and before, respectively, a line
464 /// terminator.
465 ///
466 /// In both cases, if CRLF mode is enabled in a particular context,
467 /// then it takes precedence over any configured line terminator.
468 ///
469 /// This option cannot be configured from within the pattern.
470 ///
471 /// The default line terminator is `\n`.
472 ///
473 /// # Example
474 ///
475 /// This shows how to treat the NUL byte as a line terminator. This can
476 /// be a useful heuristic when searching binary data.
477 ///
478 /// ```
479 /// use regex::RegexBuilder;
480 ///
481 /// let re = RegexBuilder::new(r"^foo$")
482 /// .multi_line(true)
483 /// .line_terminator(b'\x00')
484 /// .build()
485 /// .unwrap();
486 /// let hay = "\x00foo\x00";
487 /// assert_eq!(Some(1..4), re.find(hay).map(|m| m.range()));
488 /// ```
489 ///
490 /// This example shows that the behavior of `.` is impacted by this
491 /// setting as well:
492 ///
493 /// ```
494 /// use regex::RegexBuilder;
495 ///
496 /// let re = RegexBuilder::new(r".")
497 /// .line_terminator(b'\x00')
498 /// .build()
499 /// .unwrap();
500 /// assert!(re.is_match("\n"));
501 /// assert!(!re.is_match("\x00"));
502 /// ```
503 ///
504 /// This shows that building a regex will fail if the byte given
505 /// is not ASCII and the pattern could result in matching invalid
506 /// UTF-8. This is because any singular non-ASCII byte is not valid
507 /// UTF-8, and it is not permitted for a [`Regex`] to match invalid
508 /// UTF-8. (It is permissible to use a non-ASCII byte when building a
509 /// [`bytes::Regex`](crate::bytes::Regex).)
510 ///
511 /// ```
512 /// use regex::RegexBuilder;
513 ///
514 /// assert!(RegexBuilder::new(r".").line_terminator(0x80).build().is_err());
515 /// // Note that using a non-ASCII byte isn't enough on its own to
516 /// // cause regex compilation to fail. You actually have to make use
517 /// // of it in the regex in a way that leads to matching invalid
518 /// // UTF-8. If you don't, then regex compilation will succeed!
519 /// assert!(RegexBuilder::new(r"a").line_terminator(0x80).build().is_ok());
520 /// ```
521 pub fn line_terminator(&mut self, byte: u8) -> &mut RegexBuilder {
522 self.builder.line_terminator(byte);
523 self
524 }
525
526 /// This configures swap-greed mode for the entire pattern.
527 ///
528 /// When swap-greed mode is enabled, patterns like `a+` will become
529 /// non-greedy and patterns like `a+?` will become greedy. In other
530 /// words, the meanings of `a+` and `a+?` are switched.
531 ///
532 /// This setting can also be configured using the inline flag `U` in
533 /// the pattern.
534 ///
535 /// The default for this is `false`.
536 ///
537 /// # Example
538 ///
539 /// ```
540 /// use regex::RegexBuilder;
541 ///
542 /// let re = RegexBuilder::new(r"a+")
543 /// .swap_greed(true)
544 /// .build()
545 /// .unwrap();
546 /// assert_eq!(Some("a"), re.find("aaa").map(|m| m.as_str()));
547 /// ```
548 pub fn swap_greed(&mut self, yes: bool) -> &mut RegexBuilder {
549 self.builder.swap_greed(yes);
550 self
551 }
552
553 /// This configures verbose mode for the entire pattern.
554 ///
555 /// When enabled, whitespace will treated as insignifcant in the
556 /// pattern and `#` can be used to start a comment until the next new
557 /// line.
558 ///
559 /// Normally, in most places in a pattern, whitespace is treated
560 /// literally. For example ` +` will match one or more ASCII whitespace
561 /// characters.
562 ///
563 /// When verbose mode is enabled, `\#` can be used to match a literal
564 /// `#` and `\ ` can be used to match a literal ASCII whitespace
565 /// character.
566 ///
567 /// Verbose mode is useful for permitting regexes to be formatted and
568 /// broken up more nicely. This may make them more easily readable.
569 ///
570 /// This setting can also be configured using the inline flag `x` in
571 /// the pattern.
572 ///
573 /// The default for this is `false`.
574 ///
575 /// # Example
576 ///
577 /// ```
578 /// use regex::RegexBuilder;
579 ///
580 /// let pat = r"
581 /// \b
582 /// (?<first>\p{Uppercase}\w*) # always start with uppercase letter
583 /// [\s--\n]+ # whitespace should separate names
584 /// (?: # middle name can be an initial!
585 /// (?:(?<initial>\p{Uppercase})\.|(?<middle>\p{Uppercase}\w*))
586 /// [\s--\n]+
587 /// )?
588 /// (?<last>\p{Uppercase}\w*)
589 /// \b
590 /// ";
591 /// let re = RegexBuilder::new(pat)
592 /// .ignore_whitespace(true)
593 /// .build()
594 /// .unwrap();
595 ///
596 /// let caps = re.captures("Harry Potter").unwrap();
597 /// assert_eq!("Harry", &caps["first"]);
598 /// assert_eq!("Potter", &caps["last"]);
599 ///
600 /// let caps = re.captures("Harry J. Potter").unwrap();
601 /// assert_eq!("Harry", &caps["first"]);
602 /// // Since a middle name/initial isn't required for an overall match,
603 /// // we can't assume that 'initial' or 'middle' will be populated!
604 /// assert_eq!(Some("J"), caps.name("initial").map(|m| m.as_str()));
605 /// assert_eq!(None, caps.name("middle").map(|m| m.as_str()));
606 /// assert_eq!("Potter", &caps["last"]);
607 ///
608 /// let caps = re.captures("Harry James Potter").unwrap();
609 /// assert_eq!("Harry", &caps["first"]);
610 /// // Since a middle name/initial isn't required for an overall match,
611 /// // we can't assume that 'initial' or 'middle' will be populated!
612 /// assert_eq!(None, caps.name("initial").map(|m| m.as_str()));
613 /// assert_eq!(Some("James"), caps.name("middle").map(|m| m.as_str()));
614 /// assert_eq!("Potter", &caps["last"]);
615 /// ```
616 pub fn ignore_whitespace(&mut self, yes: bool) -> &mut RegexBuilder {
617 self.builder.ignore_whitespace(yes);
618 self
619 }
620
621 /// This configures octal mode for the entire pattern.
622 ///
623 /// Octal syntax is a little-known way of uttering Unicode codepoints
624 /// in a pattern. For example, `a`, `\x61`, `\u0061` and `\141` are all
625 /// equivalent patterns, where the last example shows octal syntax.
626 ///
627 /// While supporting octal syntax isn't in and of itself a problem,
628 /// it does make good error messages harder. That is, in PCRE based
629 /// regex engines, syntax like `\1` invokes a backreference, which is
630 /// explicitly unsupported this library. However, many users expect
631 /// backreferences to be supported. Therefore, when octal support
632 /// is disabled, the error message will explicitly mention that
633 /// backreferences aren't supported.
634 ///
635 /// The default for this is `false`.
636 ///
637 /// # Example
638 ///
639 /// ```
640 /// use regex::RegexBuilder;
641 ///
642 /// // Normally this pattern would not compile, with an error message
643 /// // about backreferences not being supported. But with octal mode
644 /// // enabled, octal escape sequences work.
645 /// let re = RegexBuilder::new(r"\141")
646 /// .octal(true)
647 /// .build()
648 /// .unwrap();
649 /// assert!(re.is_match("a"));
650 /// ```
651 pub fn octal(&mut self, yes: bool) -> &mut RegexBuilder {
652 self.builder.octal(yes);
653 self
654 }
655
656 /// Sets the approximate size limit, in bytes, of the compiled regex.
657 ///
658 /// This roughly corresponds to the number of heap memory, in
659 /// bytes, occupied by a single regex. If the regex would otherwise
660 /// approximately exceed this limit, then compiling that regex will
661 /// fail.
662 ///
663 /// The main utility of a method like this is to avoid compiling
664 /// regexes that use an unexpected amount of resources, such as
665 /// time and memory. Even if the memory usage of a large regex is
666 /// acceptable, its search time may not be. Namely, worst case time
667 /// complexity for search is `O(m * n)`, where `m ~ len(pattern)` and
668 /// `n ~ len(haystack)`. That is, search time depends, in part, on the
669 /// size of the compiled regex. This means that putting a limit on the
670 /// size of the regex limits how much a regex can impact search time.
671 ///
672 /// For more information about regex size limits, see the section on
673 /// [untrusted inputs](crate#untrusted-input) in the top-level crate
674 /// documentation.
675 ///
676 /// The default for this is some reasonable number that permits most
677 /// patterns to compile successfully.
678 ///
679 /// # Example
680 ///
681 /// ```
682 /// use regex::RegexBuilder;
683 ///
684 /// // It may surprise you how big some seemingly small patterns can
685 /// // be! Since \w is Unicode aware, this generates a regex that can
686 /// // match approximately 140,000 distinct codepoints.
687 /// assert!(RegexBuilder::new(r"\w").size_limit(45_000).build().is_err());
688 /// ```
689 pub fn size_limit(&mut self, bytes: usize) -> &mut RegexBuilder {
690 self.builder.size_limit(bytes);
691 self
692 }
693
694 /// Set the approximate capacity, in bytes, of the cache of transitions
695 /// used by the lazy DFA.
696 ///
697 /// While the lazy DFA isn't always used, in tends to be the most
698 /// commonly use regex engine in default configurations. It tends to
699 /// adopt the performance profile of a fully build DFA, but without the
700 /// downside of taking worst case exponential time to build.
701 ///
702 /// The downside is that it needs to keep a cache of transitions and
703 /// states that are built while running a search, and this cache
704 /// can fill up. When it fills up, the cache will reset itself. Any
705 /// previously generated states and transitions will then need to be
706 /// re-generated. If this happens too many times, then this library
707 /// will bail out of using the lazy DFA and switch to a different regex
708 /// engine.
709 ///
710 /// If your regex provokes this particular downside of the lazy DFA,
711 /// then it may be beneficial to increase its cache capacity. This will
712 /// potentially reduce the frequency of cache resetting (ideally to
713 /// `0`). While it won't fix all potential performance problems with
714 /// the lazy DFA, increasing the cache capacity does fix some.
715 ///
716 /// There is no easy way to determine, a priori, whether increasing
717 /// this cache capacity will help. In general, the larger your regex,
718 /// the more cache it's likely to use. But that isn't an ironclad rule.
719 /// For example, a regex like `[01]*1[01]{N}` would normally produce a
720 /// fully build DFA that is exponential in size with respect to `N`.
721 /// The lazy DFA will prevent exponential space blow-up, but it cache
722 /// is likely to fill up, even when it's large and even for smallish
723 /// values of `N`.
724 ///
725 /// If you aren't sure whether this helps or not, it is sensible to
726 /// set this to some arbitrarily large number in testing, such as
727 /// `usize::MAX`. Namely, this represents the amount of capacity that
728 /// *may* be used. It's probably not a good idea to use `usize::MAX` in
729 /// production though, since it implies there are no controls on heap
730 /// memory used by this library during a search. In effect, set it to
731 /// whatever you're willing to allocate for a single regex search.
732 pub fn dfa_size_limit(&mut self, bytes: usize) -> &mut RegexBuilder {
733 self.builder.dfa_size_limit(bytes);
734 self
735 }
736
737 /// Set the nesting limit for this parser.
738 ///
739 /// The nesting limit controls how deep the abstract syntax tree is
740 /// allowed to be. If the AST exceeds the given limit (e.g., with too
741 /// many nested groups), then an error is returned by the parser.
742 ///
743 /// The purpose of this limit is to act as a heuristic to prevent stack
744 /// overflow for consumers that do structural induction on an AST using
745 /// explicit recursion. While this crate never does this (instead using
746 /// constant stack space and moving the call stack to the heap), other
747 /// crates may.
748 ///
749 /// This limit is not checked until the entire AST is parsed.
750 /// Therefore, if callers want to put a limit on the amount of heap
751 /// space used, then they should impose a limit on the length, in
752 /// bytes, of the concrete pattern string. In particular, this is
753 /// viable since this parser implementation will limit itself to heap
754 /// space proportional to the length of the pattern string. See also
755 /// the [untrusted inputs](crate#untrusted-input) section in the
756 /// top-level crate documentation for more information about this.
757 ///
758 /// Note that a nest limit of `0` will return a nest limit error for
759 /// most patterns but not all. For example, a nest limit of `0` permits
760 /// `a` but not `ab`, since `ab` requires an explicit concatenation,
761 /// which results in a nest depth of `1`. In general, a nest limit is
762 /// not something that manifests in an obvious way in the concrete
763 /// syntax, therefore, it should not be used in a granular way.
764 ///
765 /// # Example
766 ///
767 /// ```
768 /// use regex::RegexBuilder;
769 ///
770 /// assert!(RegexBuilder::new(r"a").nest_limit(0).build().is_ok());
771 /// assert!(RegexBuilder::new(r"ab").nest_limit(0).build().is_err());
772 /// ```
773 pub fn nest_limit(&mut self, limit: u32) -> &mut RegexBuilder {
774 self.builder.nest_limit(limit);
775 self
776 }
777 }
778
779 /// A configurable builder for a [`RegexSet`].
780 ///
781 /// This builder can be used to programmatically set flags such as
782 /// `i` (case insensitive) and `x` (for verbose mode). This builder
783 /// can also be used to configure things like the line terminator
784 /// and a size limit on the compiled regular expression.
785 #[derive(Clone, Debug)]
786 pub struct RegexSetBuilder {
787 builder: Builder,
788 }
789
790 impl RegexSetBuilder {
791 /// Create a new builder with a default configuration for the given
792 /// patterns.
793 ///
794 /// If the patterns are invalid or exceed the configured size limits,
795 /// then an error will be returned when [`RegexSetBuilder::build`] is
796 /// called.
797 pub fn new<I, S>(patterns: I) -> RegexSetBuilder
798 where
799 I: IntoIterator<Item = S>,
800 S: AsRef<str>,
801 {
802 RegexSetBuilder { builder: Builder::new(patterns) }
803 }
804
805 /// Compiles the patterns given to `RegexSetBuilder::new` with the
806 /// configuration set on this builder.
807 ///
808 /// If the patterns aren't valid regexes or if a configured size limit
809 /// was exceeded, then an error is returned.
810 pub fn build(&self) -> Result<RegexSet, Error> {
811 self.builder.build_many_string()
812 }
813
814 /// This configures Unicode mode for the all of the patterns.
815 ///
816 /// Enabling Unicode mode does a number of things:
817 ///
818 /// * Most fundamentally, it causes the fundamental atom of matching
819 /// to be a single codepoint. When Unicode mode is disabled, it's a
820 /// single byte. For example, when Unicode mode is enabled, `.` will
821 /// match `💩` once, where as it will match 4 times when Unicode mode
822 /// is disabled. (Since the UTF-8 encoding of `💩` is 4 bytes long.)
823 /// * Case insensitive matching uses Unicode simple case folding rules.
824 /// * Unicode character classes like `\p{Letter}` and `\p{Greek}` are
825 /// available.
826 /// * Perl character classes are Unicode aware. That is, `\w`, `\s` and
827 /// `\d`.
828 /// * The word boundary assertions, `\b` and `\B`, use the Unicode
829 /// definition of a word character.
830 ///
831 /// Note that if Unicode mode is disabled, then the regex will fail to
832 /// compile if it could match invalid UTF-8. For example, when Unicode
833 /// mode is disabled, then since `.` matches any byte (except for
834 /// `\n`), then it can match invalid UTF-8 and thus building a regex
835 /// from it will fail. Another example is `\w` and `\W`. Since `\w` can
836 /// only match ASCII bytes when Unicode mode is disabled, it's allowed.
837 /// But `\W` can match more than ASCII bytes, including invalid UTF-8,
838 /// and so it is not allowed. This restriction can be lifted only by
839 /// using a [`bytes::RegexSet`](crate::bytes::RegexSet).
840 ///
841 /// For more details on the Unicode support in this crate, see the
842 /// [Unicode section](crate#unicode) in this crate's top-level
843 /// documentation.
844 ///
845 /// The default for this is `true`.
846 ///
847 /// # Example
848 ///
849 /// ```
850 /// use regex::RegexSetBuilder;
851 ///
852 /// let re = RegexSetBuilder::new([r"\w"])
853 /// .unicode(false)
854 /// .build()
855 /// .unwrap();
856 /// // Normally greek letters would be included in \w, but since
857 /// // Unicode mode is disabled, it only matches ASCII letters.
858 /// assert!(!re.is_match("δ"));
859 ///
860 /// let re = RegexSetBuilder::new([r"s"])
861 /// .case_insensitive(true)
862 /// .unicode(false)
863 /// .build()
864 /// .unwrap();
865 /// // Normally 'ſ' is included when searching for 's' case
866 /// // insensitively due to Unicode's simple case folding rules. But
867 /// // when Unicode mode is disabled, only ASCII case insensitive rules
868 /// // are used.
869 /// assert!(!re.is_match("ſ"));
870 /// ```
871 pub fn unicode(&mut self, yes: bool) -> &mut RegexSetBuilder {
872 self.builder.unicode(yes);
873 self
874 }
875
876 /// This configures whether to enable case insensitive matching for all
877 /// of the patterns.
878 ///
879 /// This setting can also be configured using the inline flag `i`
880 /// in the pattern. For example, `(?i:foo)` matches `foo` case
881 /// insensitively while `(?-i:foo)` matches `foo` case sensitively.
882 ///
883 /// The default for this is `false`.
884 ///
885 /// # Example
886 ///
887 /// ```
888 /// use regex::RegexSetBuilder;
889 ///
890 /// let re = RegexSetBuilder::new([r"foo(?-i:bar)quux"])
891 /// .case_insensitive(true)
892 /// .build()
893 /// .unwrap();
894 /// assert!(re.is_match("FoObarQuUx"));
895 /// // Even though case insensitive matching is enabled in the builder,
896 /// // it can be locally disabled within the pattern. In this case,
897 /// // `bar` is matched case sensitively.
898 /// assert!(!re.is_match("fooBARquux"));
899 /// ```
900 pub fn case_insensitive(&mut self, yes: bool) -> &mut RegexSetBuilder {
901 self.builder.case_insensitive(yes);
902 self
903 }
904
905 /// This configures multi-line mode for all of the patterns.
906 ///
907 /// Enabling multi-line mode changes the behavior of the `^` and `$`
908 /// anchor assertions. Instead of only matching at the beginning and
909 /// end of a haystack, respectively, multi-line mode causes them to
910 /// match at the beginning and end of a line *in addition* to the
911 /// beginning and end of a haystack. More precisely, `^` will match at
912 /// the position immediately following a `\n` and `$` will match at the
913 /// position immediately preceding a `\n`.
914 ///
915 /// The behavior of this option can be impacted by other settings too:
916 ///
917 /// * The [`RegexSetBuilder::line_terminator`] option changes `\n`
918 /// above to any ASCII byte.
919 /// * The [`RegexSetBuilder::crlf`] option changes the line terminator
920 /// to be either `\r` or `\n`, but never at the position between a `\r`
921 /// and `\n`.
922 ///
923 /// This setting can also be configured using the inline flag `m` in
924 /// the pattern.
925 ///
926 /// The default for this is `false`.
927 ///
928 /// # Example
929 ///
930 /// ```
931 /// use regex::RegexSetBuilder;
932 ///
933 /// let re = RegexSetBuilder::new([r"^foo$"])
934 /// .multi_line(true)
935 /// .build()
936 /// .unwrap();
937 /// assert!(re.is_match("\nfoo\n"));
938 /// ```
939 pub fn multi_line(&mut self, yes: bool) -> &mut RegexSetBuilder {
940 self.builder.multi_line(yes);
941 self
942 }
943
944 /// This configures dot-matches-new-line mode for the entire pattern.
945 ///
946 /// Perhaps surprisingly, the default behavior for `.` is not to match
947 /// any character, but rather, to match any character except for the
948 /// line terminator (which is `\n` by default). When this mode is
949 /// enabled, the behavior changes such that `.` truly matches any
950 /// character.
951 ///
952 /// This setting can also be configured using the inline flag `s` in
953 /// the pattern. For example, `(?s:.)` and `\p{any}` are equivalent
954 /// regexes.
955 ///
956 /// The default for this is `false`.
957 ///
958 /// # Example
959 ///
960 /// ```
961 /// use regex::RegexSetBuilder;
962 ///
963 /// let re = RegexSetBuilder::new([r"foo.bar"])
964 /// .dot_matches_new_line(true)
965 /// .build()
966 /// .unwrap();
967 /// let hay = "foo\nbar";
968 /// assert!(re.is_match(hay));
969 /// ```
970 pub fn dot_matches_new_line(
971 &mut self,
972 yes: bool,
973 ) -> &mut RegexSetBuilder {
974 self.builder.dot_matches_new_line(yes);
975 self
976 }
977
978 /// This configures CRLF mode for all of the patterns.
979 ///
980 /// When CRLF mode is enabled, both `\r` ("carriage return" or CR for
981 /// short) and `\n` ("line feed" or LF for short) are treated as line
982 /// terminators. This results in the following:
983 ///
984 /// * Unless dot-matches-new-line mode is enabled, `.` will now match
985 /// any character except for `\n` and `\r`.
986 /// * When multi-line mode is enabled, `^` will match immediately
987 /// following a `\n` or a `\r`. Similarly, `$` will match immediately
988 /// preceding a `\n` or a `\r`. Neither `^` nor `$` will ever match
989 /// between `\r` and `\n`.
990 ///
991 /// This setting can also be configured using the inline flag `R` in
992 /// the pattern.
993 ///
994 /// The default for this is `false`.
995 ///
996 /// # Example
997 ///
998 /// ```
999 /// use regex::RegexSetBuilder;
1000 ///
1001 /// let re = RegexSetBuilder::new([r"^foo$"])
1002 /// .multi_line(true)
1003 /// .crlf(true)
1004 /// .build()
1005 /// .unwrap();
1006 /// let hay = "\r\nfoo\r\n";
1007 /// // If CRLF mode weren't enabled here, then '$' wouldn't match
1008 /// // immediately after 'foo', and thus no match would be found.
1009 /// assert!(re.is_match(hay));
1010 /// ```
1011 ///
1012 /// This example demonstrates that `^` will never match at a position
1013 /// between `\r` and `\n`. (`$` will similarly not match between a `\r`
1014 /// and a `\n`.)
1015 ///
1016 /// ```
1017 /// use regex::RegexSetBuilder;
1018 ///
1019 /// let re = RegexSetBuilder::new([r"^\n"])
1020 /// .multi_line(true)
1021 /// .crlf(true)
1022 /// .build()
1023 /// .unwrap();
1024 /// assert!(!re.is_match("\r\n"));
1025 /// ```
1026 pub fn crlf(&mut self, yes: bool) -> &mut RegexSetBuilder {
1027 self.builder.crlf(yes);
1028 self
1029 }
1030
1031 /// Configures the line terminator to be used by the regex.
1032 ///
1033 /// The line terminator is relevant in two ways for a particular regex:
1034 ///
1035 /// * When dot-matches-new-line mode is *not* enabled (the default),
1036 /// then `.` will match any character except for the configured line
1037 /// terminator.
1038 /// * When multi-line mode is enabled (not the default), then `^` and
1039 /// `$` will match immediately after and before, respectively, a line
1040 /// terminator.
1041 ///
1042 /// In both cases, if CRLF mode is enabled in a particular context,
1043 /// then it takes precedence over any configured line terminator.
1044 ///
1045 /// This option cannot be configured from within the pattern.
1046 ///
1047 /// The default line terminator is `\n`.
1048 ///
1049 /// # Example
1050 ///
1051 /// This shows how to treat the NUL byte as a line terminator. This can
1052 /// be a useful heuristic when searching binary data.
1053 ///
1054 /// ```
1055 /// use regex::RegexSetBuilder;
1056 ///
1057 /// let re = RegexSetBuilder::new([r"^foo$"])
1058 /// .multi_line(true)
1059 /// .line_terminator(b'\x00')
1060 /// .build()
1061 /// .unwrap();
1062 /// let hay = "\x00foo\x00";
1063 /// assert!(re.is_match(hay));
1064 /// ```
1065 ///
1066 /// This example shows that the behavior of `.` is impacted by this
1067 /// setting as well:
1068 ///
1069 /// ```
1070 /// use regex::RegexSetBuilder;
1071 ///
1072 /// let re = RegexSetBuilder::new([r"."])
1073 /// .line_terminator(b'\x00')
1074 /// .build()
1075 /// .unwrap();
1076 /// assert!(re.is_match("\n"));
1077 /// assert!(!re.is_match("\x00"));
1078 /// ```
1079 ///
1080 /// This shows that building a regex will fail if the byte given
1081 /// is not ASCII and the pattern could result in matching invalid
1082 /// UTF-8. This is because any singular non-ASCII byte is not valid
1083 /// UTF-8, and it is not permitted for a [`RegexSet`] to match invalid
1084 /// UTF-8. (It is permissible to use a non-ASCII byte when building a
1085 /// [`bytes::RegexSet`](crate::bytes::RegexSet).)
1086 ///
1087 /// ```
1088 /// use regex::RegexSetBuilder;
1089 ///
1090 /// assert!(
1091 /// RegexSetBuilder::new([r"."])
1092 /// .line_terminator(0x80)
1093 /// .build()
1094 /// .is_err()
1095 /// );
1096 /// // Note that using a non-ASCII byte isn't enough on its own to
1097 /// // cause regex compilation to fail. You actually have to make use
1098 /// // of it in the regex in a way that leads to matching invalid
1099 /// // UTF-8. If you don't, then regex compilation will succeed!
1100 /// assert!(
1101 /// RegexSetBuilder::new([r"a"])
1102 /// .line_terminator(0x80)
1103 /// .build()
1104 /// .is_ok()
1105 /// );
1106 /// ```
1107 pub fn line_terminator(&mut self, byte: u8) -> &mut RegexSetBuilder {
1108 self.builder.line_terminator(byte);
1109 self
1110 }
1111
1112 /// This configures swap-greed mode for all of the patterns.
1113 ///
1114 /// When swap-greed mode is enabled, patterns like `a+` will become
1115 /// non-greedy and patterns like `a+?` will become greedy. In other
1116 /// words, the meanings of `a+` and `a+?` are switched.
1117 ///
1118 /// This setting can also be configured using the inline flag `U` in
1119 /// the pattern.
1120 ///
1121 /// Note that this is generally not useful for a `RegexSet` since a
1122 /// `RegexSet` can only report whether a pattern matches or not. Since
1123 /// greediness never impacts whether a match is found or not (only the
1124 /// offsets of the match), it follows that whether parts of a pattern
1125 /// are greedy or not doesn't matter for a `RegexSet`.
1126 ///
1127 /// The default for this is `false`.
1128 pub fn swap_greed(&mut self, yes: bool) -> &mut RegexSetBuilder {
1129 self.builder.swap_greed(yes);
1130 self
1131 }
1132
1133 /// This configures verbose mode for all of the patterns.
1134 ///
1135 /// When enabled, whitespace will treated as insignifcant in the
1136 /// pattern and `#` can be used to start a comment until the next new
1137 /// line.
1138 ///
1139 /// Normally, in most places in a pattern, whitespace is treated
1140 /// literally. For example ` +` will match one or more ASCII whitespace
1141 /// characters.
1142 ///
1143 /// When verbose mode is enabled, `\#` can be used to match a literal
1144 /// `#` and `\ ` can be used to match a literal ASCII whitespace
1145 /// character.
1146 ///
1147 /// Verbose mode is useful for permitting regexes to be formatted and
1148 /// broken up more nicely. This may make them more easily readable.
1149 ///
1150 /// This setting can also be configured using the inline flag `x` in
1151 /// the pattern.
1152 ///
1153 /// The default for this is `false`.
1154 ///
1155 /// # Example
1156 ///
1157 /// ```
1158 /// use regex::RegexSetBuilder;
1159 ///
1160 /// let pat = r"
1161 /// \b
1162 /// (?<first>\p{Uppercase}\w*) # always start with uppercase letter
1163 /// [\s--\n]+ # whitespace should separate names
1164 /// (?: # middle name can be an initial!
1165 /// (?:(?<initial>\p{Uppercase})\.|(?<middle>\p{Uppercase}\w*))
1166 /// [\s--\n]+
1167 /// )?
1168 /// (?<last>\p{Uppercase}\w*)
1169 /// \b
1170 /// ";
1171 /// let re = RegexSetBuilder::new([pat])
1172 /// .ignore_whitespace(true)
1173 /// .build()
1174 /// .unwrap();
1175 /// assert!(re.is_match("Harry Potter"));
1176 /// assert!(re.is_match("Harry J. Potter"));
1177 /// assert!(re.is_match("Harry James Potter"));
1178 /// assert!(!re.is_match("harry J. Potter"));
1179 /// ```
1180 pub fn ignore_whitespace(
1181 &mut self,
1182 yes: bool,
1183 ) -> &mut RegexSetBuilder {
1184 self.builder.ignore_whitespace(yes);
1185 self
1186 }
1187
1188 /// This configures octal mode for all of the patterns.
1189 ///
1190 /// Octal syntax is a little-known way of uttering Unicode codepoints
1191 /// in a pattern. For example, `a`, `\x61`, `\u0061` and `\141` are all
1192 /// equivalent patterns, where the last example shows octal syntax.
1193 ///
1194 /// While supporting octal syntax isn't in and of itself a problem,
1195 /// it does make good error messages harder. That is, in PCRE based
1196 /// regex engines, syntax like `\1` invokes a backreference, which is
1197 /// explicitly unsupported this library. However, many users expect
1198 /// backreferences to be supported. Therefore, when octal support
1199 /// is disabled, the error message will explicitly mention that
1200 /// backreferences aren't supported.
1201 ///
1202 /// The default for this is `false`.
1203 ///
1204 /// # Example
1205 ///
1206 /// ```
1207 /// use regex::RegexSetBuilder;
1208 ///
1209 /// // Normally this pattern would not compile, with an error message
1210 /// // about backreferences not being supported. But with octal mode
1211 /// // enabled, octal escape sequences work.
1212 /// let re = RegexSetBuilder::new([r"\141"])
1213 /// .octal(true)
1214 /// .build()
1215 /// .unwrap();
1216 /// assert!(re.is_match("a"));
1217 /// ```
1218 pub fn octal(&mut self, yes: bool) -> &mut RegexSetBuilder {
1219 self.builder.octal(yes);
1220 self
1221 }
1222
1223 /// Sets the approximate size limit, in bytes, of the compiled regex.
1224 ///
1225 /// This roughly corresponds to the number of heap memory, in
1226 /// bytes, occupied by a single regex. If the regex would otherwise
1227 /// approximately exceed this limit, then compiling that regex will
1228 /// fail.
1229 ///
1230 /// The main utility of a method like this is to avoid compiling
1231 /// regexes that use an unexpected amount of resources, such as
1232 /// time and memory. Even if the memory usage of a large regex is
1233 /// acceptable, its search time may not be. Namely, worst case time
1234 /// complexity for search is `O(m * n)`, where `m ~ len(pattern)` and
1235 /// `n ~ len(haystack)`. That is, search time depends, in part, on the
1236 /// size of the compiled regex. This means that putting a limit on the
1237 /// size of the regex limits how much a regex can impact search time.
1238 ///
1239 /// For more information about regex size limits, see the section on
1240 /// [untrusted inputs](crate#untrusted-input) in the top-level crate
1241 /// documentation.
1242 ///
1243 /// The default for this is some reasonable number that permits most
1244 /// patterns to compile successfully.
1245 ///
1246 /// # Example
1247 ///
1248 /// ```
1249 /// use regex::RegexSetBuilder;
1250 ///
1251 /// // It may surprise you how big some seemingly small patterns can
1252 /// // be! Since \w is Unicode aware, this generates a regex that can
1253 /// // match approximately 140,000 distinct codepoints.
1254 /// assert!(
1255 /// RegexSetBuilder::new([r"\w"])
1256 /// .size_limit(45_000)
1257 /// .build()
1258 /// .is_err()
1259 /// );
1260 /// ```
1261 pub fn size_limit(&mut self, bytes: usize) -> &mut RegexSetBuilder {
1262 self.builder.size_limit(bytes);
1263 self
1264 }
1265
1266 /// Set the approximate capacity, in bytes, of the cache of transitions
1267 /// used by the lazy DFA.
1268 ///
1269 /// While the lazy DFA isn't always used, in tends to be the most
1270 /// commonly use regex engine in default configurations. It tends to
1271 /// adopt the performance profile of a fully build DFA, but without the
1272 /// downside of taking worst case exponential time to build.
1273 ///
1274 /// The downside is that it needs to keep a cache of transitions and
1275 /// states that are built while running a search, and this cache
1276 /// can fill up. When it fills up, the cache will reset itself. Any
1277 /// previously generated states and transitions will then need to be
1278 /// re-generated. If this happens too many times, then this library
1279 /// will bail out of using the lazy DFA and switch to a different regex
1280 /// engine.
1281 ///
1282 /// If your regex provokes this particular downside of the lazy DFA,
1283 /// then it may be beneficial to increase its cache capacity. This will
1284 /// potentially reduce the frequency of cache resetting (ideally to
1285 /// `0`). While it won't fix all potential performance problems with
1286 /// the lazy DFA, increasing the cache capacity does fix some.
1287 ///
1288 /// There is no easy way to determine, a priori, whether increasing
1289 /// this cache capacity will help. In general, the larger your regex,
1290 /// the more cache it's likely to use. But that isn't an ironclad rule.
1291 /// For example, a regex like `[01]*1[01]{N}` would normally produce a
1292 /// fully build DFA that is exponential in size with respect to `N`.
1293 /// The lazy DFA will prevent exponential space blow-up, but it cache
1294 /// is likely to fill up, even when it's large and even for smallish
1295 /// values of `N`.
1296 ///
1297 /// If you aren't sure whether this helps or not, it is sensible to
1298 /// set this to some arbitrarily large number in testing, such as
1299 /// `usize::MAX`. Namely, this represents the amount of capacity that
1300 /// *may* be used. It's probably not a good idea to use `usize::MAX` in
1301 /// production though, since it implies there are no controls on heap
1302 /// memory used by this library during a search. In effect, set it to
1303 /// whatever you're willing to allocate for a single regex search.
1304 pub fn dfa_size_limit(
1305 &mut self,
1306 bytes: usize,
1307 ) -> &mut RegexSetBuilder {
1308 self.builder.dfa_size_limit(bytes);
1309 self
1310 }
1311
1312 /// Set the nesting limit for this parser.
1313 ///
1314 /// The nesting limit controls how deep the abstract syntax tree is
1315 /// allowed to be. If the AST exceeds the given limit (e.g., with too
1316 /// many nested groups), then an error is returned by the parser.
1317 ///
1318 /// The purpose of this limit is to act as a heuristic to prevent stack
1319 /// overflow for consumers that do structural induction on an AST using
1320 /// explicit recursion. While this crate never does this (instead using
1321 /// constant stack space and moving the call stack to the heap), other
1322 /// crates may.
1323 ///
1324 /// This limit is not checked until the entire AST is parsed.
1325 /// Therefore, if callers want to put a limit on the amount of heap
1326 /// space used, then they should impose a limit on the length, in
1327 /// bytes, of the concrete pattern string. In particular, this is
1328 /// viable since this parser implementation will limit itself to heap
1329 /// space proportional to the length of the pattern string. See also
1330 /// the [untrusted inputs](crate#untrusted-input) section in the
1331 /// top-level crate documentation for more information about this.
1332 ///
1333 /// Note that a nest limit of `0` will return a nest limit error for
1334 /// most patterns but not all. For example, a nest limit of `0` permits
1335 /// `a` but not `ab`, since `ab` requires an explicit concatenation,
1336 /// which results in a nest depth of `1`. In general, a nest limit is
1337 /// not something that manifests in an obvious way in the concrete
1338 /// syntax, therefore, it should not be used in a granular way.
1339 ///
1340 /// # Example
1341 ///
1342 /// ```
1343 /// use regex::RegexSetBuilder;
1344 ///
1345 /// assert!(RegexSetBuilder::new([r"a"]).nest_limit(0).build().is_ok());
1346 /// assert!(RegexSetBuilder::new([r"ab"]).nest_limit(0).build().is_err());
1347 /// ```
1348 pub fn nest_limit(&mut self, limit: u32) -> &mut RegexSetBuilder {
1349 self.builder.nest_limit(limit);
1350 self
1351 }
1352 }
1353 }
1354
1355 pub(crate) mod bytes {
1356 use crate::{
1357 bytes::{Regex, RegexSet},
1358 error::Error,
1359 };
1360
1361 use super::Builder;
1362
1363 /// A configurable builder for a [`Regex`].
1364 ///
1365 /// This builder can be used to programmatically set flags such as `i`
1366 /// (case insensitive) and `x` (for verbose mode). This builder can also be
1367 /// used to configure things like the line terminator and a size limit on
1368 /// the compiled regular expression.
1369 #[derive(Clone, Debug)]
1370 pub struct RegexBuilder {
1371 builder: Builder,
1372 }
1373
1374 impl RegexBuilder {
1375 /// Create a new builder with a default configuration for the given
1376 /// pattern.
1377 ///
1378 /// If the pattern is invalid or exceeds the configured size limits,
1379 /// then an error will be returned when [`RegexBuilder::build`] is
1380 /// called.
1381 pub fn new(pattern: &str) -> RegexBuilder {
1382 RegexBuilder { builder: Builder::new([pattern]) }
1383 }
1384
1385 /// Compiles the pattern given to `RegexBuilder::new` with the
1386 /// configuration set on this builder.
1387 ///
1388 /// If the pattern isn't a valid regex or if a configured size limit
1389 /// was exceeded, then an error is returned.
1390 pub fn build(&self) -> Result<Regex, Error> {
1391 self.builder.build_one_bytes()
1392 }
1393
1394 /// This configures Unicode mode for the entire pattern.
1395 ///
1396 /// Enabling Unicode mode does a number of things:
1397 ///
1398 /// * Most fundamentally, it causes the fundamental atom of matching
1399 /// to be a single codepoint. When Unicode mode is disabled, it's a
1400 /// single byte. For example, when Unicode mode is enabled, `.` will
1401 /// match `💩` once, where as it will match 4 times when Unicode mode
1402 /// is disabled. (Since the UTF-8 encoding of `💩` is 4 bytes long.)
1403 /// * Case insensitive matching uses Unicode simple case folding rules.
1404 /// * Unicode character classes like `\p{Letter}` and `\p{Greek}` are
1405 /// available.
1406 /// * Perl character classes are Unicode aware. That is, `\w`, `\s` and
1407 /// `\d`.
1408 /// * The word boundary assertions, `\b` and `\B`, use the Unicode
1409 /// definition of a word character.
1410 ///
1411 /// Note that unlike the top-level `Regex` for searching `&str`, it
1412 /// is permitted to disable Unicode mode even if the resulting pattern
1413 /// could match invalid UTF-8. For example, `(?-u:.)` is not a valid
1414 /// pattern for a top-level `Regex`, but is valid for a `bytes::Regex`.
1415 ///
1416 /// For more details on the Unicode support in this crate, see the
1417 /// [Unicode section](crate#unicode) in this crate's top-level
1418 /// documentation.
1419 ///
1420 /// The default for this is `true`.
1421 ///
1422 /// # Example
1423 ///
1424 /// ```
1425 /// use regex::bytes::RegexBuilder;
1426 ///
1427 /// let re = RegexBuilder::new(r"\w")
1428 /// .unicode(false)
1429 /// .build()
1430 /// .unwrap();
1431 /// // Normally greek letters would be included in \w, but since
1432 /// // Unicode mode is disabled, it only matches ASCII letters.
1433 /// assert!(!re.is_match("δ".as_bytes()));
1434 ///
1435 /// let re = RegexBuilder::new(r"s")
1436 /// .case_insensitive(true)
1437 /// .unicode(false)
1438 /// .build()
1439 /// .unwrap();
1440 /// // Normally 'ſ' is included when searching for 's' case
1441 /// // insensitively due to Unicode's simple case folding rules. But
1442 /// // when Unicode mode is disabled, only ASCII case insensitive rules
1443 /// // are used.
1444 /// assert!(!re.is_match("ſ".as_bytes()));
1445 /// ```
1446 ///
1447 /// Since this builder is for constructing a [`bytes::Regex`](Regex),
1448 /// one can disable Unicode mode even if it would match invalid UTF-8:
1449 ///
1450 /// ```
1451 /// use regex::bytes::RegexBuilder;
1452 ///
1453 /// let re = RegexBuilder::new(r".")
1454 /// .unicode(false)
1455 /// .build()
1456 /// .unwrap();
1457 /// // Normally greek letters would be included in \w, but since
1458 /// // Unicode mode is disabled, it only matches ASCII letters.
1459 /// assert!(re.is_match(b"\xFF"));
1460 /// ```
1461 pub fn unicode(&mut self, yes: bool) -> &mut RegexBuilder {
1462 self.builder.unicode(yes);
1463 self
1464 }
1465
1466 /// This configures whether to enable case insensitive matching for the
1467 /// entire pattern.
1468 ///
1469 /// This setting can also be configured using the inline flag `i`
1470 /// in the pattern. For example, `(?i:foo)` matches `foo` case
1471 /// insensitively while `(?-i:foo)` matches `foo` case sensitively.
1472 ///
1473 /// The default for this is `false`.
1474 ///
1475 /// # Example
1476 ///
1477 /// ```
1478 /// use regex::bytes::RegexBuilder;
1479 ///
1480 /// let re = RegexBuilder::new(r"foo(?-i:bar)quux")
1481 /// .case_insensitive(true)
1482 /// .build()
1483 /// .unwrap();
1484 /// assert!(re.is_match(b"FoObarQuUx"));
1485 /// // Even though case insensitive matching is enabled in the builder,
1486 /// // it can be locally disabled within the pattern. In this case,
1487 /// // `bar` is matched case sensitively.
1488 /// assert!(!re.is_match(b"fooBARquux"));
1489 /// ```
1490 pub fn case_insensitive(&mut self, yes: bool) -> &mut RegexBuilder {
1491 self.builder.case_insensitive(yes);
1492 self
1493 }
1494
1495 /// This configures multi-line mode for the entire pattern.
1496 ///
1497 /// Enabling multi-line mode changes the behavior of the `^` and `$`
1498 /// anchor assertions. Instead of only matching at the beginning and
1499 /// end of a haystack, respectively, multi-line mode causes them to
1500 /// match at the beginning and end of a line *in addition* to the
1501 /// beginning and end of a haystack. More precisely, `^` will match at
1502 /// the position immediately following a `\n` and `$` will match at the
1503 /// position immediately preceding a `\n`.
1504 ///
1505 /// The behavior of this option can be impacted by other settings too:
1506 ///
1507 /// * The [`RegexBuilder::line_terminator`] option changes `\n` above
1508 /// to any ASCII byte.
1509 /// * The [`RegexBuilder::crlf`] option changes the line terminator to
1510 /// be either `\r` or `\n`, but never at the position between a `\r`
1511 /// and `\n`.
1512 ///
1513 /// This setting can also be configured using the inline flag `m` in
1514 /// the pattern.
1515 ///
1516 /// The default for this is `false`.
1517 ///
1518 /// # Example
1519 ///
1520 /// ```
1521 /// use regex::bytes::RegexBuilder;
1522 ///
1523 /// let re = RegexBuilder::new(r"^foo$")
1524 /// .multi_line(true)
1525 /// .build()
1526 /// .unwrap();
1527 /// assert_eq!(Some(1..4), re.find(b"\nfoo\n").map(|m| m.range()));
1528 /// ```
1529 pub fn multi_line(&mut self, yes: bool) -> &mut RegexBuilder {
1530 self.builder.multi_line(yes);
1531 self
1532 }
1533
1534 /// This configures dot-matches-new-line mode for the entire pattern.
1535 ///
1536 /// Perhaps surprisingly, the default behavior for `.` is not to match
1537 /// any character, but rather, to match any character except for the
1538 /// line terminator (which is `\n` by default). When this mode is
1539 /// enabled, the behavior changes such that `.` truly matches any
1540 /// character.
1541 ///
1542 /// This setting can also be configured using the inline flag `s` in
1543 /// the pattern. For example, `(?s:.)` and `\p{any}` are equivalent
1544 /// regexes.
1545 ///
1546 /// The default for this is `false`.
1547 ///
1548 /// # Example
1549 ///
1550 /// ```
1551 /// use regex::bytes::RegexBuilder;
1552 ///
1553 /// let re = RegexBuilder::new(r"foo.bar")
1554 /// .dot_matches_new_line(true)
1555 /// .build()
1556 /// .unwrap();
1557 /// let hay = b"foo\nbar";
1558 /// assert_eq!(Some(&b"foo\nbar"[..]), re.find(hay).map(|m| m.as_bytes()));
1559 /// ```
1560 pub fn dot_matches_new_line(
1561 &mut self,
1562 yes: bool,
1563 ) -> &mut RegexBuilder {
1564 self.builder.dot_matches_new_line(yes);
1565 self
1566 }
1567
1568 /// This configures CRLF mode for the entire pattern.
1569 ///
1570 /// When CRLF mode is enabled, both `\r` ("carriage return" or CR for
1571 /// short) and `\n` ("line feed" or LF for short) are treated as line
1572 /// terminators. This results in the following:
1573 ///
1574 /// * Unless dot-matches-new-line mode is enabled, `.` will now match
1575 /// any character except for `\n` and `\r`.
1576 /// * When multi-line mode is enabled, `^` will match immediately
1577 /// following a `\n` or a `\r`. Similarly, `$` will match immediately
1578 /// preceding a `\n` or a `\r`. Neither `^` nor `$` will ever match
1579 /// between `\r` and `\n`.
1580 ///
1581 /// This setting can also be configured using the inline flag `R` in
1582 /// the pattern.
1583 ///
1584 /// The default for this is `false`.
1585 ///
1586 /// # Example
1587 ///
1588 /// ```
1589 /// use regex::bytes::RegexBuilder;
1590 ///
1591 /// let re = RegexBuilder::new(r"^foo$")
1592 /// .multi_line(true)
1593 /// .crlf(true)
1594 /// .build()
1595 /// .unwrap();
1596 /// let hay = b"\r\nfoo\r\n";
1597 /// // If CRLF mode weren't enabled here, then '$' wouldn't match
1598 /// // immediately after 'foo', and thus no match would be found.
1599 /// assert_eq!(Some(&b"foo"[..]), re.find(hay).map(|m| m.as_bytes()));
1600 /// ```
1601 ///
1602 /// This example demonstrates that `^` will never match at a position
1603 /// between `\r` and `\n`. (`$` will similarly not match between a `\r`
1604 /// and a `\n`.)
1605 ///
1606 /// ```
1607 /// use regex::bytes::RegexBuilder;
1608 ///
1609 /// let re = RegexBuilder::new(r"^")
1610 /// .multi_line(true)
1611 /// .crlf(true)
1612 /// .build()
1613 /// .unwrap();
1614 /// let hay = b"\r\n\r\n";
1615 /// let ranges: Vec<_> = re.find_iter(hay).map(|m| m.range()).collect();
1616 /// assert_eq!(ranges, vec![0..0, 2..2, 4..4]);
1617 /// ```
1618 pub fn crlf(&mut self, yes: bool) -> &mut RegexBuilder {
1619 self.builder.crlf(yes);
1620 self
1621 }
1622
1623 /// Configures the line terminator to be used by the regex.
1624 ///
1625 /// The line terminator is relevant in two ways for a particular regex:
1626 ///
1627 /// * When dot-matches-new-line mode is *not* enabled (the default),
1628 /// then `.` will match any character except for the configured line
1629 /// terminator.
1630 /// * When multi-line mode is enabled (not the default), then `^` and
1631 /// `$` will match immediately after and before, respectively, a line
1632 /// terminator.
1633 ///
1634 /// In both cases, if CRLF mode is enabled in a particular context,
1635 /// then it takes precedence over any configured line terminator.
1636 ///
1637 /// This option cannot be configured from within the pattern.
1638 ///
1639 /// The default line terminator is `\n`.
1640 ///
1641 /// # Example
1642 ///
1643 /// This shows how to treat the NUL byte as a line terminator. This can
1644 /// be a useful heuristic when searching binary data.
1645 ///
1646 /// ```
1647 /// use regex::bytes::RegexBuilder;
1648 ///
1649 /// let re = RegexBuilder::new(r"^foo$")
1650 /// .multi_line(true)
1651 /// .line_terminator(b'\x00')
1652 /// .build()
1653 /// .unwrap();
1654 /// let hay = b"\x00foo\x00";
1655 /// assert_eq!(Some(1..4), re.find(hay).map(|m| m.range()));
1656 /// ```
1657 ///
1658 /// This example shows that the behavior of `.` is impacted by this
1659 /// setting as well:
1660 ///
1661 /// ```
1662 /// use regex::bytes::RegexBuilder;
1663 ///
1664 /// let re = RegexBuilder::new(r".")
1665 /// .line_terminator(b'\x00')
1666 /// .build()
1667 /// .unwrap();
1668 /// assert!(re.is_match(b"\n"));
1669 /// assert!(!re.is_match(b"\x00"));
1670 /// ```
1671 ///
1672 /// This shows that building a regex will work even when the byte
1673 /// given is not ASCII. This is unlike the top-level `Regex` API where
1674 /// matching invalid UTF-8 is not allowed.
1675 ///
1676 /// Note though that you must disable Unicode mode. This is required
1677 /// because Unicode mode requires matching one codepoint at a time,
1678 /// and there is no way to match a non-ASCII byte as if it were a
1679 /// codepoint.
1680 ///
1681 /// ```
1682 /// use regex::bytes::RegexBuilder;
1683 ///
1684 /// assert!(
1685 /// RegexBuilder::new(r".")
1686 /// .unicode(false)
1687 /// .line_terminator(0x80)
1688 /// .build()
1689 /// .is_ok(),
1690 /// );
1691 /// ```
1692 pub fn line_terminator(&mut self, byte: u8) -> &mut RegexBuilder {
1693 self.builder.line_terminator(byte);
1694 self
1695 }
1696
1697 /// This configures swap-greed mode for the entire pattern.
1698 ///
1699 /// When swap-greed mode is enabled, patterns like `a+` will become
1700 /// non-greedy and patterns like `a+?` will become greedy. In other
1701 /// words, the meanings of `a+` and `a+?` are switched.
1702 ///
1703 /// This setting can also be configured using the inline flag `U` in
1704 /// the pattern.
1705 ///
1706 /// The default for this is `false`.
1707 ///
1708 /// # Example
1709 ///
1710 /// ```
1711 /// use regex::bytes::RegexBuilder;
1712 ///
1713 /// let re = RegexBuilder::new(r"a+")
1714 /// .swap_greed(true)
1715 /// .build()
1716 /// .unwrap();
1717 /// assert_eq!(Some(&b"a"[..]), re.find(b"aaa").map(|m| m.as_bytes()));
1718 /// ```
1719 pub fn swap_greed(&mut self, yes: bool) -> &mut RegexBuilder {
1720 self.builder.swap_greed(yes);
1721 self
1722 }
1723
1724 /// This configures verbose mode for the entire pattern.
1725 ///
1726 /// When enabled, whitespace will treated as insignifcant in the
1727 /// pattern and `#` can be used to start a comment until the next new
1728 /// line.
1729 ///
1730 /// Normally, in most places in a pattern, whitespace is treated
1731 /// literally. For example ` +` will match one or more ASCII whitespace
1732 /// characters.
1733 ///
1734 /// When verbose mode is enabled, `\#` can be used to match a literal
1735 /// `#` and `\ ` can be used to match a literal ASCII whitespace
1736 /// character.
1737 ///
1738 /// Verbose mode is useful for permitting regexes to be formatted and
1739 /// broken up more nicely. This may make them more easily readable.
1740 ///
1741 /// This setting can also be configured using the inline flag `x` in
1742 /// the pattern.
1743 ///
1744 /// The default for this is `false`.
1745 ///
1746 /// # Example
1747 ///
1748 /// ```
1749 /// use regex::bytes::RegexBuilder;
1750 ///
1751 /// let pat = r"
1752 /// \b
1753 /// (?<first>\p{Uppercase}\w*) # always start with uppercase letter
1754 /// [\s--\n]+ # whitespace should separate names
1755 /// (?: # middle name can be an initial!
1756 /// (?:(?<initial>\p{Uppercase})\.|(?<middle>\p{Uppercase}\w*))
1757 /// [\s--\n]+
1758 /// )?
1759 /// (?<last>\p{Uppercase}\w*)
1760 /// \b
1761 /// ";
1762 /// let re = RegexBuilder::new(pat)
1763 /// .ignore_whitespace(true)
1764 /// .build()
1765 /// .unwrap();
1766 ///
1767 /// let caps = re.captures(b"Harry Potter").unwrap();
1768 /// assert_eq!(&b"Harry"[..], &caps["first"]);
1769 /// assert_eq!(&b"Potter"[..], &caps["last"]);
1770 ///
1771 /// let caps = re.captures(b"Harry J. Potter").unwrap();
1772 /// assert_eq!(&b"Harry"[..], &caps["first"]);
1773 /// // Since a middle name/initial isn't required for an overall match,
1774 /// // we can't assume that 'initial' or 'middle' will be populated!
1775 /// assert_eq!(
1776 /// Some(&b"J"[..]),
1777 /// caps.name("initial").map(|m| m.as_bytes()),
1778 /// );
1779 /// assert_eq!(None, caps.name("middle").map(|m| m.as_bytes()));
1780 /// assert_eq!(&b"Potter"[..], &caps["last"]);
1781 ///
1782 /// let caps = re.captures(b"Harry James Potter").unwrap();
1783 /// assert_eq!(&b"Harry"[..], &caps["first"]);
1784 /// // Since a middle name/initial isn't required for an overall match,
1785 /// // we can't assume that 'initial' or 'middle' will be populated!
1786 /// assert_eq!(None, caps.name("initial").map(|m| m.as_bytes()));
1787 /// assert_eq!(
1788 /// Some(&b"James"[..]),
1789 /// caps.name("middle").map(|m| m.as_bytes()),
1790 /// );
1791 /// assert_eq!(&b"Potter"[..], &caps["last"]);
1792 /// ```
1793 pub fn ignore_whitespace(&mut self, yes: bool) -> &mut RegexBuilder {
1794 self.builder.ignore_whitespace(yes);
1795 self
1796 }
1797
1798 /// This configures octal mode for the entire pattern.
1799 ///
1800 /// Octal syntax is a little-known way of uttering Unicode codepoints
1801 /// in a pattern. For example, `a`, `\x61`, `\u0061` and `\141` are all
1802 /// equivalent patterns, where the last example shows octal syntax.
1803 ///
1804 /// While supporting octal syntax isn't in and of itself a problem,
1805 /// it does make good error messages harder. That is, in PCRE based
1806 /// regex engines, syntax like `\1` invokes a backreference, which is
1807 /// explicitly unsupported this library. However, many users expect
1808 /// backreferences to be supported. Therefore, when octal support
1809 /// is disabled, the error message will explicitly mention that
1810 /// backreferences aren't supported.
1811 ///
1812 /// The default for this is `false`.
1813 ///
1814 /// # Example
1815 ///
1816 /// ```
1817 /// use regex::bytes::RegexBuilder;
1818 ///
1819 /// // Normally this pattern would not compile, with an error message
1820 /// // about backreferences not being supported. But with octal mode
1821 /// // enabled, octal escape sequences work.
1822 /// let re = RegexBuilder::new(r"\141")
1823 /// .octal(true)
1824 /// .build()
1825 /// .unwrap();
1826 /// assert!(re.is_match(b"a"));
1827 /// ```
1828 pub fn octal(&mut self, yes: bool) -> &mut RegexBuilder {
1829 self.builder.octal(yes);
1830 self
1831 }
1832
1833 /// Sets the approximate size limit, in bytes, of the compiled regex.
1834 ///
1835 /// This roughly corresponds to the number of heap memory, in
1836 /// bytes, occupied by a single regex. If the regex would otherwise
1837 /// approximately exceed this limit, then compiling that regex will
1838 /// fail.
1839 ///
1840 /// The main utility of a method like this is to avoid compiling
1841 /// regexes that use an unexpected amount of resources, such as
1842 /// time and memory. Even if the memory usage of a large regex is
1843 /// acceptable, its search time may not be. Namely, worst case time
1844 /// complexity for search is `O(m * n)`, where `m ~ len(pattern)` and
1845 /// `n ~ len(haystack)`. That is, search time depends, in part, on the
1846 /// size of the compiled regex. This means that putting a limit on the
1847 /// size of the regex limits how much a regex can impact search time.
1848 ///
1849 /// For more information about regex size limits, see the section on
1850 /// [untrusted inputs](crate#untrusted-input) in the top-level crate
1851 /// documentation.
1852 ///
1853 /// The default for this is some reasonable number that permits most
1854 /// patterns to compile successfully.
1855 ///
1856 /// # Example
1857 ///
1858 /// ```
1859 /// use regex::bytes::RegexBuilder;
1860 ///
1861 /// // It may surprise you how big some seemingly small patterns can
1862 /// // be! Since \w is Unicode aware, this generates a regex that can
1863 /// // match approximately 140,000 distinct codepoints.
1864 /// assert!(RegexBuilder::new(r"\w").size_limit(45_000).build().is_err());
1865 /// ```
1866 pub fn size_limit(&mut self, bytes: usize) -> &mut RegexBuilder {
1867 self.builder.size_limit(bytes);
1868 self
1869 }
1870
1871 /// Set the approximate capacity, in bytes, of the cache of transitions
1872 /// used by the lazy DFA.
1873 ///
1874 /// While the lazy DFA isn't always used, in tends to be the most
1875 /// commonly use regex engine in default configurations. It tends to
1876 /// adopt the performance profile of a fully build DFA, but without the
1877 /// downside of taking worst case exponential time to build.
1878 ///
1879 /// The downside is that it needs to keep a cache of transitions and
1880 /// states that are built while running a search, and this cache
1881 /// can fill up. When it fills up, the cache will reset itself. Any
1882 /// previously generated states and transitions will then need to be
1883 /// re-generated. If this happens too many times, then this library
1884 /// will bail out of using the lazy DFA and switch to a different regex
1885 /// engine.
1886 ///
1887 /// If your regex provokes this particular downside of the lazy DFA,
1888 /// then it may be beneficial to increase its cache capacity. This will
1889 /// potentially reduce the frequency of cache resetting (ideally to
1890 /// `0`). While it won't fix all potential performance problems with
1891 /// the lazy DFA, increasing the cache capacity does fix some.
1892 ///
1893 /// There is no easy way to determine, a priori, whether increasing
1894 /// this cache capacity will help. In general, the larger your regex,
1895 /// the more cache it's likely to use. But that isn't an ironclad rule.
1896 /// For example, a regex like `[01]*1[01]{N}` would normally produce a
1897 /// fully build DFA that is exponential in size with respect to `N`.
1898 /// The lazy DFA will prevent exponential space blow-up, but it cache
1899 /// is likely to fill up, even when it's large and even for smallish
1900 /// values of `N`.
1901 ///
1902 /// If you aren't sure whether this helps or not, it is sensible to
1903 /// set this to some arbitrarily large number in testing, such as
1904 /// `usize::MAX`. Namely, this represents the amount of capacity that
1905 /// *may* be used. It's probably not a good idea to use `usize::MAX` in
1906 /// production though, since it implies there are no controls on heap
1907 /// memory used by this library during a search. In effect, set it to
1908 /// whatever you're willing to allocate for a single regex search.
1909 pub fn dfa_size_limit(&mut self, bytes: usize) -> &mut RegexBuilder {
1910 self.builder.dfa_size_limit(bytes);
1911 self
1912 }
1913
1914 /// Set the nesting limit for this parser.
1915 ///
1916 /// The nesting limit controls how deep the abstract syntax tree is
1917 /// allowed to be. If the AST exceeds the given limit (e.g., with too
1918 /// many nested groups), then an error is returned by the parser.
1919 ///
1920 /// The purpose of this limit is to act as a heuristic to prevent stack
1921 /// overflow for consumers that do structural induction on an AST using
1922 /// explicit recursion. While this crate never does this (instead using
1923 /// constant stack space and moving the call stack to the heap), other
1924 /// crates may.
1925 ///
1926 /// This limit is not checked until the entire AST is parsed.
1927 /// Therefore, if callers want to put a limit on the amount of heap
1928 /// space used, then they should impose a limit on the length, in
1929 /// bytes, of the concrete pattern string. In particular, this is
1930 /// viable since this parser implementation will limit itself to heap
1931 /// space proportional to the length of the pattern string. See also
1932 /// the [untrusted inputs](crate#untrusted-input) section in the
1933 /// top-level crate documentation for more information about this.
1934 ///
1935 /// Note that a nest limit of `0` will return a nest limit error for
1936 /// most patterns but not all. For example, a nest limit of `0` permits
1937 /// `a` but not `ab`, since `ab` requires an explicit concatenation,
1938 /// which results in a nest depth of `1`. In general, a nest limit is
1939 /// not something that manifests in an obvious way in the concrete
1940 /// syntax, therefore, it should not be used in a granular way.
1941 ///
1942 /// # Example
1943 ///
1944 /// ```
1945 /// use regex::bytes::RegexBuilder;
1946 ///
1947 /// assert!(RegexBuilder::new(r"a").nest_limit(0).build().is_ok());
1948 /// assert!(RegexBuilder::new(r"ab").nest_limit(0).build().is_err());
1949 /// ```
1950 pub fn nest_limit(&mut self, limit: u32) -> &mut RegexBuilder {
1951 self.builder.nest_limit(limit);
1952 self
1953 }
1954 }
1955
1956 /// A configurable builder for a [`RegexSet`].
1957 ///
1958 /// This builder can be used to programmatically set flags such as `i`
1959 /// (case insensitive) and `x` (for verbose mode). This builder can also be
1960 /// used to configure things like the line terminator and a size limit on
1961 /// the compiled regular expression.
1962 #[derive(Clone, Debug)]
1963 pub struct RegexSetBuilder {
1964 builder: Builder,
1965 }
1966
1967 impl RegexSetBuilder {
1968 /// Create a new builder with a default configuration for the given
1969 /// patterns.
1970 ///
1971 /// If the patterns are invalid or exceed the configured size limits,
1972 /// then an error will be returned when [`RegexSetBuilder::build`] is
1973 /// called.
1974 pub fn new<I, S>(patterns: I) -> RegexSetBuilder
1975 where
1976 I: IntoIterator<Item = S>,
1977 S: AsRef<str>,
1978 {
1979 RegexSetBuilder { builder: Builder::new(patterns) }
1980 }
1981
1982 /// Compiles the patterns given to `RegexSetBuilder::new` with the
1983 /// configuration set on this builder.
1984 ///
1985 /// If the patterns aren't valid regexes or if a configured size limit
1986 /// was exceeded, then an error is returned.
1987 pub fn build(&self) -> Result<RegexSet, Error> {
1988 self.builder.build_many_bytes()
1989 }
1990
1991 /// This configures Unicode mode for the all of the patterns.
1992 ///
1993 /// Enabling Unicode mode does a number of things:
1994 ///
1995 /// * Most fundamentally, it causes the fundamental atom of matching
1996 /// to be a single codepoint. When Unicode mode is disabled, it's a
1997 /// single byte. For example, when Unicode mode is enabled, `.` will
1998 /// match `💩` once, where as it will match 4 times when Unicode mode
1999 /// is disabled. (Since the UTF-8 encoding of `💩` is 4 bytes long.)
2000 /// * Case insensitive matching uses Unicode simple case folding rules.
2001 /// * Unicode character classes like `\p{Letter}` and `\p{Greek}` are
2002 /// available.
2003 /// * Perl character classes are Unicode aware. That is, `\w`, `\s` and
2004 /// `\d`.
2005 /// * The word boundary assertions, `\b` and `\B`, use the Unicode
2006 /// definition of a word character.
2007 ///
2008 /// Note that unlike the top-level `RegexSet` for searching `&str`,
2009 /// it is permitted to disable Unicode mode even if the resulting
2010 /// pattern could match invalid UTF-8. For example, `(?-u:.)` is not
2011 /// a valid pattern for a top-level `RegexSet`, but is valid for a
2012 /// `bytes::RegexSet`.
2013 ///
2014 /// For more details on the Unicode support in this crate, see the
2015 /// [Unicode section](crate#unicode) in this crate's top-level
2016 /// documentation.
2017 ///
2018 /// The default for this is `true`.
2019 ///
2020 /// # Example
2021 ///
2022 /// ```
2023 /// use regex::bytes::RegexSetBuilder;
2024 ///
2025 /// let re = RegexSetBuilder::new([r"\w"])
2026 /// .unicode(false)
2027 /// .build()
2028 /// .unwrap();
2029 /// // Normally greek letters would be included in \w, but since
2030 /// // Unicode mode is disabled, it only matches ASCII letters.
2031 /// assert!(!re.is_match("δ".as_bytes()));
2032 ///
2033 /// let re = RegexSetBuilder::new([r"s"])
2034 /// .case_insensitive(true)
2035 /// .unicode(false)
2036 /// .build()
2037 /// .unwrap();
2038 /// // Normally 'ſ' is included when searching for 's' case
2039 /// // insensitively due to Unicode's simple case folding rules. But
2040 /// // when Unicode mode is disabled, only ASCII case insensitive rules
2041 /// // are used.
2042 /// assert!(!re.is_match("ſ".as_bytes()));
2043 /// ```
2044 ///
2045 /// Since this builder is for constructing a
2046 /// [`bytes::RegexSet`](RegexSet), one can disable Unicode mode even if
2047 /// it would match invalid UTF-8:
2048 ///
2049 /// ```
2050 /// use regex::bytes::RegexSetBuilder;
2051 ///
2052 /// let re = RegexSetBuilder::new([r"."])
2053 /// .unicode(false)
2054 /// .build()
2055 /// .unwrap();
2056 /// // Normally greek letters would be included in \w, but since
2057 /// // Unicode mode is disabled, it only matches ASCII letters.
2058 /// assert!(re.is_match(b"\xFF"));
2059 /// ```
2060 pub fn unicode(&mut self, yes: bool) -> &mut RegexSetBuilder {
2061 self.builder.unicode(yes);
2062 self
2063 }
2064
2065 /// This configures whether to enable case insensitive matching for all
2066 /// of the patterns.
2067 ///
2068 /// This setting can also be configured using the inline flag `i`
2069 /// in the pattern. For example, `(?i:foo)` matches `foo` case
2070 /// insensitively while `(?-i:foo)` matches `foo` case sensitively.
2071 ///
2072 /// The default for this is `false`.
2073 ///
2074 /// # Example
2075 ///
2076 /// ```
2077 /// use regex::bytes::RegexSetBuilder;
2078 ///
2079 /// let re = RegexSetBuilder::new([r"foo(?-i:bar)quux"])
2080 /// .case_insensitive(true)
2081 /// .build()
2082 /// .unwrap();
2083 /// assert!(re.is_match(b"FoObarQuUx"));
2084 /// // Even though case insensitive matching is enabled in the builder,
2085 /// // it can be locally disabled within the pattern. In this case,
2086 /// // `bar` is matched case sensitively.
2087 /// assert!(!re.is_match(b"fooBARquux"));
2088 /// ```
2089 pub fn case_insensitive(&mut self, yes: bool) -> &mut RegexSetBuilder {
2090 self.builder.case_insensitive(yes);
2091 self
2092 }
2093
2094 /// This configures multi-line mode for all of the patterns.
2095 ///
2096 /// Enabling multi-line mode changes the behavior of the `^` and `$`
2097 /// anchor assertions. Instead of only matching at the beginning and
2098 /// end of a haystack, respectively, multi-line mode causes them to
2099 /// match at the beginning and end of a line *in addition* to the
2100 /// beginning and end of a haystack. More precisely, `^` will match at
2101 /// the position immediately following a `\n` and `$` will match at the
2102 /// position immediately preceding a `\n`.
2103 ///
2104 /// The behavior of this option can be impacted by other settings too:
2105 ///
2106 /// * The [`RegexSetBuilder::line_terminator`] option changes `\n`
2107 /// above to any ASCII byte.
2108 /// * The [`RegexSetBuilder::crlf`] option changes the line terminator
2109 /// to be either `\r` or `\n`, but never at the position between a `\r`
2110 /// and `\n`.
2111 ///
2112 /// This setting can also be configured using the inline flag `m` in
2113 /// the pattern.
2114 ///
2115 /// The default for this is `false`.
2116 ///
2117 /// # Example
2118 ///
2119 /// ```
2120 /// use regex::bytes::RegexSetBuilder;
2121 ///
2122 /// let re = RegexSetBuilder::new([r"^foo$"])
2123 /// .multi_line(true)
2124 /// .build()
2125 /// .unwrap();
2126 /// assert!(re.is_match(b"\nfoo\n"));
2127 /// ```
2128 pub fn multi_line(&mut self, yes: bool) -> &mut RegexSetBuilder {
2129 self.builder.multi_line(yes);
2130 self
2131 }
2132
2133 /// This configures dot-matches-new-line mode for the entire pattern.
2134 ///
2135 /// Perhaps surprisingly, the default behavior for `.` is not to match
2136 /// any character, but rather, to match any character except for the
2137 /// line terminator (which is `\n` by default). When this mode is
2138 /// enabled, the behavior changes such that `.` truly matches any
2139 /// character.
2140 ///
2141 /// This setting can also be configured using the inline flag `s` in
2142 /// the pattern. For example, `(?s:.)` and `\p{any}` are equivalent
2143 /// regexes.
2144 ///
2145 /// The default for this is `false`.
2146 ///
2147 /// # Example
2148 ///
2149 /// ```
2150 /// use regex::bytes::RegexSetBuilder;
2151 ///
2152 /// let re = RegexSetBuilder::new([r"foo.bar"])
2153 /// .dot_matches_new_line(true)
2154 /// .build()
2155 /// .unwrap();
2156 /// let hay = b"foo\nbar";
2157 /// assert!(re.is_match(hay));
2158 /// ```
2159 pub fn dot_matches_new_line(
2160 &mut self,
2161 yes: bool,
2162 ) -> &mut RegexSetBuilder {
2163 self.builder.dot_matches_new_line(yes);
2164 self
2165 }
2166
2167 /// This configures CRLF mode for all of the patterns.
2168 ///
2169 /// When CRLF mode is enabled, both `\r` ("carriage return" or CR for
2170 /// short) and `\n` ("line feed" or LF for short) are treated as line
2171 /// terminators. This results in the following:
2172 ///
2173 /// * Unless dot-matches-new-line mode is enabled, `.` will now match
2174 /// any character except for `\n` and `\r`.
2175 /// * When multi-line mode is enabled, `^` will match immediately
2176 /// following a `\n` or a `\r`. Similarly, `$` will match immediately
2177 /// preceding a `\n` or a `\r`. Neither `^` nor `$` will ever match
2178 /// between `\r` and `\n`.
2179 ///
2180 /// This setting can also be configured using the inline flag `R` in
2181 /// the pattern.
2182 ///
2183 /// The default for this is `false`.
2184 ///
2185 /// # Example
2186 ///
2187 /// ```
2188 /// use regex::bytes::RegexSetBuilder;
2189 ///
2190 /// let re = RegexSetBuilder::new([r"^foo$"])
2191 /// .multi_line(true)
2192 /// .crlf(true)
2193 /// .build()
2194 /// .unwrap();
2195 /// let hay = b"\r\nfoo\r\n";
2196 /// // If CRLF mode weren't enabled here, then '$' wouldn't match
2197 /// // immediately after 'foo', and thus no match would be found.
2198 /// assert!(re.is_match(hay));
2199 /// ```
2200 ///
2201 /// This example demonstrates that `^` will never match at a position
2202 /// between `\r` and `\n`. (`$` will similarly not match between a `\r`
2203 /// and a `\n`.)
2204 ///
2205 /// ```
2206 /// use regex::bytes::RegexSetBuilder;
2207 ///
2208 /// let re = RegexSetBuilder::new([r"^\n"])
2209 /// .multi_line(true)
2210 /// .crlf(true)
2211 /// .build()
2212 /// .unwrap();
2213 /// assert!(!re.is_match(b"\r\n"));
2214 /// ```
2215 pub fn crlf(&mut self, yes: bool) -> &mut RegexSetBuilder {
2216 self.builder.crlf(yes);
2217 self
2218 }
2219
2220 /// Configures the line terminator to be used by the regex.
2221 ///
2222 /// The line terminator is relevant in two ways for a particular regex:
2223 ///
2224 /// * When dot-matches-new-line mode is *not* enabled (the default),
2225 /// then `.` will match any character except for the configured line
2226 /// terminator.
2227 /// * When multi-line mode is enabled (not the default), then `^` and
2228 /// `$` will match immediately after and before, respectively, a line
2229 /// terminator.
2230 ///
2231 /// In both cases, if CRLF mode is enabled in a particular context,
2232 /// then it takes precedence over any configured line terminator.
2233 ///
2234 /// This option cannot be configured from within the pattern.
2235 ///
2236 /// The default line terminator is `\n`.
2237 ///
2238 /// # Example
2239 ///
2240 /// This shows how to treat the NUL byte as a line terminator. This can
2241 /// be a useful heuristic when searching binary data.
2242 ///
2243 /// ```
2244 /// use regex::bytes::RegexSetBuilder;
2245 ///
2246 /// let re = RegexSetBuilder::new([r"^foo$"])
2247 /// .multi_line(true)
2248 /// .line_terminator(b'\x00')
2249 /// .build()
2250 /// .unwrap();
2251 /// let hay = b"\x00foo\x00";
2252 /// assert!(re.is_match(hay));
2253 /// ```
2254 ///
2255 /// This example shows that the behavior of `.` is impacted by this
2256 /// setting as well:
2257 ///
2258 /// ```
2259 /// use regex::bytes::RegexSetBuilder;
2260 ///
2261 /// let re = RegexSetBuilder::new([r"."])
2262 /// .line_terminator(b'\x00')
2263 /// .build()
2264 /// .unwrap();
2265 /// assert!(re.is_match(b"\n"));
2266 /// assert!(!re.is_match(b"\x00"));
2267 /// ```
2268 ///
2269 /// This shows that building a regex will work even when the byte given
2270 /// is not ASCII. This is unlike the top-level `RegexSet` API where
2271 /// matching invalid UTF-8 is not allowed.
2272 ///
2273 /// Note though that you must disable Unicode mode. This is required
2274 /// because Unicode mode requires matching one codepoint at a time,
2275 /// and there is no way to match a non-ASCII byte as if it were a
2276 /// codepoint.
2277 ///
2278 /// ```
2279 /// use regex::bytes::RegexSetBuilder;
2280 ///
2281 /// assert!(
2282 /// RegexSetBuilder::new([r"."])
2283 /// .unicode(false)
2284 /// .line_terminator(0x80)
2285 /// .build()
2286 /// .is_ok(),
2287 /// );
2288 /// ```
2289 pub fn line_terminator(&mut self, byte: u8) -> &mut RegexSetBuilder {
2290 self.builder.line_terminator(byte);
2291 self
2292 }
2293
2294 /// This configures swap-greed mode for all of the patterns.
2295 ///
2296 /// When swap-greed mode is enabled, patterns like `a+` will become
2297 /// non-greedy and patterns like `a+?` will become greedy. In other
2298 /// words, the meanings of `a+` and `a+?` are switched.
2299 ///
2300 /// This setting can also be configured using the inline flag `U` in
2301 /// the pattern.
2302 ///
2303 /// Note that this is generally not useful for a `RegexSet` since a
2304 /// `RegexSet` can only report whether a pattern matches or not. Since
2305 /// greediness never impacts whether a match is found or not (only the
2306 /// offsets of the match), it follows that whether parts of a pattern
2307 /// are greedy or not doesn't matter for a `RegexSet`.
2308 ///
2309 /// The default for this is `false`.
2310 pub fn swap_greed(&mut self, yes: bool) -> &mut RegexSetBuilder {
2311 self.builder.swap_greed(yes);
2312 self
2313 }
2314
2315 /// This configures verbose mode for all of the patterns.
2316 ///
2317 /// When enabled, whitespace will treated as insignifcant in the
2318 /// pattern and `#` can be used to start a comment until the next new
2319 /// line.
2320 ///
2321 /// Normally, in most places in a pattern, whitespace is treated
2322 /// literally. For example ` +` will match one or more ASCII whitespace
2323 /// characters.
2324 ///
2325 /// When verbose mode is enabled, `\#` can be used to match a literal
2326 /// `#` and `\ ` can be used to match a literal ASCII whitespace
2327 /// character.
2328 ///
2329 /// Verbose mode is useful for permitting regexes to be formatted and
2330 /// broken up more nicely. This may make them more easily readable.
2331 ///
2332 /// This setting can also be configured using the inline flag `x` in
2333 /// the pattern.
2334 ///
2335 /// The default for this is `false`.
2336 ///
2337 /// # Example
2338 ///
2339 /// ```
2340 /// use regex::bytes::RegexSetBuilder;
2341 ///
2342 /// let pat = r"
2343 /// \b
2344 /// (?<first>\p{Uppercase}\w*) # always start with uppercase letter
2345 /// [\s--\n]+ # whitespace should separate names
2346 /// (?: # middle name can be an initial!
2347 /// (?:(?<initial>\p{Uppercase})\.|(?<middle>\p{Uppercase}\w*))
2348 /// [\s--\n]+
2349 /// )?
2350 /// (?<last>\p{Uppercase}\w*)
2351 /// \b
2352 /// ";
2353 /// let re = RegexSetBuilder::new([pat])
2354 /// .ignore_whitespace(true)
2355 /// .build()
2356 /// .unwrap();
2357 /// assert!(re.is_match(b"Harry Potter"));
2358 /// assert!(re.is_match(b"Harry J. Potter"));
2359 /// assert!(re.is_match(b"Harry James Potter"));
2360 /// assert!(!re.is_match(b"harry J. Potter"));
2361 /// ```
2362 pub fn ignore_whitespace(
2363 &mut self,
2364 yes: bool,
2365 ) -> &mut RegexSetBuilder {
2366 self.builder.ignore_whitespace(yes);
2367 self
2368 }
2369
2370 /// This configures octal mode for all of the patterns.
2371 ///
2372 /// Octal syntax is a little-known way of uttering Unicode codepoints
2373 /// in a pattern. For example, `a`, `\x61`, `\u0061` and `\141` are all
2374 /// equivalent patterns, where the last example shows octal syntax.
2375 ///
2376 /// While supporting octal syntax isn't in and of itself a problem,
2377 /// it does make good error messages harder. That is, in PCRE based
2378 /// regex engines, syntax like `\1` invokes a backreference, which is
2379 /// explicitly unsupported this library. However, many users expect
2380 /// backreferences to be supported. Therefore, when octal support
2381 /// is disabled, the error message will explicitly mention that
2382 /// backreferences aren't supported.
2383 ///
2384 /// The default for this is `false`.
2385 ///
2386 /// # Example
2387 ///
2388 /// ```
2389 /// use regex::bytes::RegexSetBuilder;
2390 ///
2391 /// // Normally this pattern would not compile, with an error message
2392 /// // about backreferences not being supported. But with octal mode
2393 /// // enabled, octal escape sequences work.
2394 /// let re = RegexSetBuilder::new([r"\141"])
2395 /// .octal(true)
2396 /// .build()
2397 /// .unwrap();
2398 /// assert!(re.is_match(b"a"));
2399 /// ```
2400 pub fn octal(&mut self, yes: bool) -> &mut RegexSetBuilder {
2401 self.builder.octal(yes);
2402 self
2403 }
2404
2405 /// Sets the approximate size limit, in bytes, of the compiled regex.
2406 ///
2407 /// This roughly corresponds to the number of heap memory, in
2408 /// bytes, occupied by a single regex. If the regex would otherwise
2409 /// approximately exceed this limit, then compiling that regex will
2410 /// fail.
2411 ///
2412 /// The main utility of a method like this is to avoid compiling
2413 /// regexes that use an unexpected amount of resources, such as
2414 /// time and memory. Even if the memory usage of a large regex is
2415 /// acceptable, its search time may not be. Namely, worst case time
2416 /// complexity for search is `O(m * n)`, where `m ~ len(pattern)` and
2417 /// `n ~ len(haystack)`. That is, search time depends, in part, on the
2418 /// size of the compiled regex. This means that putting a limit on the
2419 /// size of the regex limits how much a regex can impact search time.
2420 ///
2421 /// For more information about regex size limits, see the section on
2422 /// [untrusted inputs](crate#untrusted-input) in the top-level crate
2423 /// documentation.
2424 ///
2425 /// The default for this is some reasonable number that permits most
2426 /// patterns to compile successfully.
2427 ///
2428 /// # Example
2429 ///
2430 /// ```
2431 /// use regex::bytes::RegexSetBuilder;
2432 ///
2433 /// // It may surprise you how big some seemingly small patterns can
2434 /// // be! Since \w is Unicode aware, this generates a regex that can
2435 /// // match approximately 140,000 distinct codepoints.
2436 /// assert!(
2437 /// RegexSetBuilder::new([r"\w"])
2438 /// .size_limit(45_000)
2439 /// .build()
2440 /// .is_err()
2441 /// );
2442 /// ```
2443 pub fn size_limit(&mut self, bytes: usize) -> &mut RegexSetBuilder {
2444 self.builder.size_limit(bytes);
2445 self
2446 }
2447
2448 /// Set the approximate capacity, in bytes, of the cache of transitions
2449 /// used by the lazy DFA.
2450 ///
2451 /// While the lazy DFA isn't always used, in tends to be the most
2452 /// commonly use regex engine in default configurations. It tends to
2453 /// adopt the performance profile of a fully build DFA, but without the
2454 /// downside of taking worst case exponential time to build.
2455 ///
2456 /// The downside is that it needs to keep a cache of transitions and
2457 /// states that are built while running a search, and this cache
2458 /// can fill up. When it fills up, the cache will reset itself. Any
2459 /// previously generated states and transitions will then need to be
2460 /// re-generated. If this happens too many times, then this library
2461 /// will bail out of using the lazy DFA and switch to a different regex
2462 /// engine.
2463 ///
2464 /// If your regex provokes this particular downside of the lazy DFA,
2465 /// then it may be beneficial to increase its cache capacity. This will
2466 /// potentially reduce the frequency of cache resetting (ideally to
2467 /// `0`). While it won't fix all potential performance problems with
2468 /// the lazy DFA, increasing the cache capacity does fix some.
2469 ///
2470 /// There is no easy way to determine, a priori, whether increasing
2471 /// this cache capacity will help. In general, the larger your regex,
2472 /// the more cache it's likely to use. But that isn't an ironclad rule.
2473 /// For example, a regex like `[01]*1[01]{N}` would normally produce a
2474 /// fully build DFA that is exponential in size with respect to `N`.
2475 /// The lazy DFA will prevent exponential space blow-up, but it cache
2476 /// is likely to fill up, even when it's large and even for smallish
2477 /// values of `N`.
2478 ///
2479 /// If you aren't sure whether this helps or not, it is sensible to
2480 /// set this to some arbitrarily large number in testing, such as
2481 /// `usize::MAX`. Namely, this represents the amount of capacity that
2482 /// *may* be used. It's probably not a good idea to use `usize::MAX` in
2483 /// production though, since it implies there are no controls on heap
2484 /// memory used by this library during a search. In effect, set it to
2485 /// whatever you're willing to allocate for a single regex search.
2486 pub fn dfa_size_limit(
2487 &mut self,
2488 bytes: usize,
2489 ) -> &mut RegexSetBuilder {
2490 self.builder.dfa_size_limit(bytes);
2491 self
2492 }
2493
2494 /// Set the nesting limit for this parser.
2495 ///
2496 /// The nesting limit controls how deep the abstract syntax tree is
2497 /// allowed to be. If the AST exceeds the given limit (e.g., with too
2498 /// many nested groups), then an error is returned by the parser.
2499 ///
2500 /// The purpose of this limit is to act as a heuristic to prevent stack
2501 /// overflow for consumers that do structural induction on an AST using
2502 /// explicit recursion. While this crate never does this (instead using
2503 /// constant stack space and moving the call stack to the heap), other
2504 /// crates may.
2505 ///
2506 /// This limit is not checked until the entire AST is parsed.
2507 /// Therefore, if callers want to put a limit on the amount of heap
2508 /// space used, then they should impose a limit on the length, in
2509 /// bytes, of the concrete pattern string. In particular, this is
2510 /// viable since this parser implementation will limit itself to heap
2511 /// space proportional to the length of the pattern string. See also
2512 /// the [untrusted inputs](crate#untrusted-input) section in the
2513 /// top-level crate documentation for more information about this.
2514 ///
2515 /// Note that a nest limit of `0` will return a nest limit error for
2516 /// most patterns but not all. For example, a nest limit of `0` permits
2517 /// `a` but not `ab`, since `ab` requires an explicit concatenation,
2518 /// which results in a nest depth of `1`. In general, a nest limit is
2519 /// not something that manifests in an obvious way in the concrete
2520 /// syntax, therefore, it should not be used in a granular way.
2521 ///
2522 /// # Example
2523 ///
2524 /// ```
2525 /// use regex::bytes::RegexSetBuilder;
2526 ///
2527 /// assert!(RegexSetBuilder::new([r"a"]).nest_limit(0).build().is_ok());
2528 /// assert!(RegexSetBuilder::new([r"ab"]).nest_limit(0).build().is_err());
2529 /// ```
2530 pub fn nest_limit(&mut self, limit: u32) -> &mut RegexSetBuilder {
2531 self.builder.nest_limit(limit);
2532 self
2533 }
2534 }
2535 }