1use core::{
2    fmt::Debug,
3    panic::{RefUnwindSafe, UnwindSafe},
4};
5
6use alloc::sync::Arc;
7
8use regex_syntax::hir::{literal, Hir};
9
10use crate::{
11    meta::{
12        error::{BuildError, RetryError, RetryFailError, RetryQuadraticError},
13        regex::{Cache, RegexInfo},
14        reverse_inner, wrappers,
15    },
16    nfa::thompson::{self, WhichCaptures, NFA},
17    util::{
18        captures::{Captures, GroupInfo},
19        look::LookMatcher,
20        prefilter::{self, Prefilter, PrefilterI},
21        primitives::{NonMaxUsize, PatternID},
22        search::{Anchored, HalfMatch, Input, Match, MatchKind, PatternSet},
23    },
24};
25
26pub(super) trait Strategy:
41    Debug + Send + Sync + RefUnwindSafe + UnwindSafe + 'static
42{
43    fn group_info(&self) -> &GroupInfo;
44
45    fn create_cache(&self) -> Cache;
46
47    fn reset_cache(&self, cache: &mut Cache);
48
49    fn is_accelerated(&self) -> bool;
50
51    fn memory_usage(&self) -> usize;
52
53    fn search(&self, cache: &mut Cache, input: &Input<'_>) -> Option<Match>;
54
55    fn search_half(
56        &self,
57        cache: &mut Cache,
58        input: &Input<'_>,
59    ) -> Option<HalfMatch>;
60
61    fn is_match(&self, cache: &mut Cache, input: &Input<'_>) -> bool;
62
63    fn search_slots(
64        &self,
65        cache: &mut Cache,
66        input: &Input<'_>,
67        slots: &mut [Option<NonMaxUsize>],
68    ) -> Option<PatternID>;
69
70    fn which_overlapping_matches(
71        &self,
72        cache: &mut Cache,
73        input: &Input<'_>,
74        patset: &mut PatternSet,
75    );
76}
77
78pub(super) fn new(
79    info: &RegexInfo,
80    hirs: &[&Hir],
81) -> Result<Arc<dyn Strategy>, BuildError> {
82    let pre = if info.is_always_anchored_start() {
86        debug!("skipping literal extraction since regex is anchored");
104        None
105    } else if let Some(pre) = info.config().get_prefilter() {
106        debug!(
107            "skipping literal extraction since the caller provided a prefilter"
108        );
109        Some(pre.clone())
110    } else if info.config().get_auto_prefilter() {
111        let kind = info.config().get_match_kind();
112        let prefixes = crate::util::prefilter::prefixes(kind, hirs);
113        if let Some(pre) = Pre::from_prefixes(info, &prefixes) {
116            debug!(
117                "found that the regex can be broken down to a literal \
118                 search, avoiding the regex engine entirely",
119            );
120            return Ok(pre);
121        }
122        if let Some(pre) = Pre::from_alternation_literals(info, hirs) {
135            debug!(
136                "found plain alternation of literals, \
137                 avoiding regex engine entirely and using Aho-Corasick"
138            );
139            return Ok(pre);
140        }
141        prefixes.literals().and_then(|strings| {
142            debug!(
143                "creating prefilter from {} literals: {:?}",
144                strings.len(),
145                strings,
146            );
147            Prefilter::new(kind, strings)
148        })
149    } else {
150        debug!("skipping literal extraction since prefilters were disabled");
151        None
152    };
153    let mut core = Core::new(info.clone(), pre.clone(), hirs)?;
154    core = match ReverseAnchored::new(core) {
164        Err(core) => core,
165        Ok(ra) => {
166            debug!("using reverse anchored strategy");
167            return Ok(Arc::new(ra));
168        }
169    };
170    core = match ReverseSuffix::new(core, hirs) {
171        Err(core) => core,
172        Ok(rs) => {
173            debug!("using reverse suffix strategy");
174            return Ok(Arc::new(rs));
175        }
176    };
177    core = match ReverseInner::new(core, hirs) {
178        Err(core) => core,
179        Ok(ri) => {
180            debug!("using reverse inner strategy");
181            return Ok(Arc::new(ri));
182        }
183    };
184    debug!("using core strategy");
185    Ok(Arc::new(core))
186}
187
188#[derive(Clone, Debug)]
189struct Pre<P> {
190    pre: P,
191    group_info: GroupInfo,
192}
193
194impl<P: PrefilterI> Pre<P> {
195    fn new(pre: P) -> Arc<dyn Strategy> {
196        let group_info = GroupInfo::new([[None::<&str>]]).unwrap();
201        Arc::new(Pre { pre, group_info })
202    }
203}
204
205impl Pre<()> {
209    fn from_prefixes(
225        info: &RegexInfo,
226        prefixes: &literal::Seq,
227    ) -> Option<Arc<dyn Strategy>> {
228        let kind = info.config().get_match_kind();
229        if !prefixes.is_exact() {
233            return None;
234        }
235        if info.pattern_len() != 1 {
242            return None;
243        }
244        if info.props()[0].explicit_captures_len() != 0 {
249            return None;
250        }
251        if !info.props()[0].look_set().is_empty() {
259            return None;
260        }
261        if kind != MatchKind::LeftmostFirst {
265            return None;
266        }
267        let prefixes = prefixes.literals().unwrap();
280        debug!(
281            "trying to bypass regex engine by creating \
282             prefilter from {} literals: {:?}",
283            prefixes.len(),
284            prefixes,
285        );
286        let choice = match prefilter::Choice::new(kind, prefixes) {
287            Some(choice) => choice,
288            None => {
289                debug!(
290                    "regex bypass failed because no prefilter could be built"
291                );
292                return None;
293            }
294        };
295        let strat: Arc<dyn Strategy> = match choice {
296            prefilter::Choice::Memchr(pre) => Pre::new(pre),
297            prefilter::Choice::Memchr2(pre) => Pre::new(pre),
298            prefilter::Choice::Memchr3(pre) => Pre::new(pre),
299            prefilter::Choice::Memmem(pre) => Pre::new(pre),
300            prefilter::Choice::Teddy(pre) => Pre::new(pre),
301            prefilter::Choice::ByteSet(pre) => Pre::new(pre),
302            prefilter::Choice::AhoCorasick(pre) => Pre::new(pre),
303        };
304        Some(strat)
305    }
306
307    fn from_alternation_literals(
315        info: &RegexInfo,
316        hirs: &[&Hir],
317    ) -> Option<Arc<dyn Strategy>> {
318        use crate::util::prefilter::AhoCorasick;
319
320        let lits = crate::meta::literal::alternation_literals(info, hirs)?;
321        let ac = AhoCorasick::new(MatchKind::LeftmostFirst, &lits)?;
322        Some(Pre::new(ac))
323    }
324}
325
326impl<P: PrefilterI> Strategy for Pre<P> {
356    #[cfg_attr(feature = "perf-inline", inline(always))]
357    fn group_info(&self) -> &GroupInfo {
358        &self.group_info
359    }
360
361    fn create_cache(&self) -> Cache {
362        Cache {
363            capmatches: Captures::all(self.group_info().clone()),
364            pikevm: wrappers::PikeVMCache::none(),
365            backtrack: wrappers::BoundedBacktrackerCache::none(),
366            onepass: wrappers::OnePassCache::none(),
367            hybrid: wrappers::HybridCache::none(),
368            revhybrid: wrappers::ReverseHybridCache::none(),
369        }
370    }
371
372    fn reset_cache(&self, _cache: &mut Cache) {}
373
374    fn is_accelerated(&self) -> bool {
375        self.pre.is_fast()
376    }
377
378    fn memory_usage(&self) -> usize {
379        self.pre.memory_usage()
380    }
381
382    #[cfg_attr(feature = "perf-inline", inline(always))]
383    fn search(&self, _cache: &mut Cache, input: &Input<'_>) -> Option<Match> {
384        if input.is_done() {
385            return None;
386        }
387        if input.get_anchored().is_anchored() {
388            return self
389                .pre
390                .prefix(input.haystack(), input.get_span())
391                .map(|sp| Match::new(PatternID::ZERO, sp));
392        }
393        self.pre
394            .find(input.haystack(), input.get_span())
395            .map(|sp| Match::new(PatternID::ZERO, sp))
396    }
397
398    #[cfg_attr(feature = "perf-inline", inline(always))]
399    fn search_half(
400        &self,
401        cache: &mut Cache,
402        input: &Input<'_>,
403    ) -> Option<HalfMatch> {
404        self.search(cache, input).map(|m| HalfMatch::new(m.pattern(), m.end()))
405    }
406
407    #[cfg_attr(feature = "perf-inline", inline(always))]
408    fn is_match(&self, cache: &mut Cache, input: &Input<'_>) -> bool {
409        self.search(cache, input).is_some()
410    }
411
412    #[cfg_attr(feature = "perf-inline", inline(always))]
413    fn search_slots(
414        &self,
415        cache: &mut Cache,
416        input: &Input<'_>,
417        slots: &mut [Option<NonMaxUsize>],
418    ) -> Option<PatternID> {
419        let m = self.search(cache, input)?;
420        if let Some(slot) = slots.get_mut(0) {
421            *slot = NonMaxUsize::new(m.start());
422        }
423        if let Some(slot) = slots.get_mut(1) {
424            *slot = NonMaxUsize::new(m.end());
425        }
426        Some(m.pattern())
427    }
428
429    #[cfg_attr(feature = "perf-inline", inline(always))]
430    fn which_overlapping_matches(
431        &self,
432        cache: &mut Cache,
433        input: &Input<'_>,
434        patset: &mut PatternSet,
435    ) {
436        if self.search(cache, input).is_some() {
437            patset.insert(PatternID::ZERO);
438        }
439    }
440}
441
442#[derive(Debug)]
443struct Core {
444    info: RegexInfo,
445    pre: Option<Prefilter>,
446    nfa: NFA,
447    nfarev: Option<NFA>,
448    pikevm: wrappers::PikeVM,
449    backtrack: wrappers::BoundedBacktracker,
450    onepass: wrappers::OnePass,
451    hybrid: wrappers::Hybrid,
452    dfa: wrappers::DFA,
453}
454
455impl Core {
456    fn new(
457        info: RegexInfo,
458        pre: Option<Prefilter>,
459        hirs: &[&Hir],
460    ) -> Result<Core, BuildError> {
461        let mut lookm = LookMatcher::new();
462        lookm.set_line_terminator(info.config().get_line_terminator());
463        let thompson_config = thompson::Config::new()
464            .utf8(info.config().get_utf8_empty())
465            .nfa_size_limit(info.config().get_nfa_size_limit())
466            .shrink(false)
467            .which_captures(info.config().get_which_captures())
468            .look_matcher(lookm);
469        let nfa = thompson::Compiler::new()
470            .configure(thompson_config.clone())
471            .build_many_from_hir(hirs)
472            .map_err(BuildError::nfa)?;
473        let pikevm = wrappers::PikeVM::new(&info, pre.clone(), &nfa)?;
480        let backtrack =
481            wrappers::BoundedBacktracker::new(&info, pre.clone(), &nfa)?;
482        let onepass = wrappers::OnePass::new(&info, &nfa);
487        let (nfarev, hybrid, dfa) =
494            if !info.config().get_hybrid() && !info.config().get_dfa() {
495                (None, wrappers::Hybrid::none(), wrappers::DFA::none())
496            } else {
497                let nfarev = thompson::Compiler::new()
508                    .configure(
514                        thompson_config
515                            .clone()
516                            .which_captures(WhichCaptures::None)
517                            .reverse(true),
518                    )
519                    .build_many_from_hir(hirs)
520                    .map_err(BuildError::nfa)?;
521                let dfa = if !info.config().get_dfa() {
522                    wrappers::DFA::none()
523                } else {
524                    wrappers::DFA::new(&info, pre.clone(), &nfa, &nfarev)
525                };
526                let hybrid = if !info.config().get_hybrid() {
527                    wrappers::Hybrid::none()
528                } else if dfa.is_some() {
529                    debug!("skipping lazy DFA because we have a full DFA");
530                    wrappers::Hybrid::none()
531                } else {
532                    wrappers::Hybrid::new(&info, pre.clone(), &nfa, &nfarev)
533                };
534                (Some(nfarev), hybrid, dfa)
535            };
536        Ok(Core {
537            info,
538            pre,
539            nfa,
540            nfarev,
541            pikevm,
542            backtrack,
543            onepass,
544            hybrid,
545            dfa,
546        })
547    }
548
549    #[cfg_attr(feature = "perf-inline", inline(always))]
550    fn try_search_mayfail(
551        &self,
552        cache: &mut Cache,
553        input: &Input<'_>,
554    ) -> Option<Result<Option<Match>, RetryFailError>> {
555        if let Some(e) = self.dfa.get(input) {
556            trace!("using full DFA for search at {:?}", input.get_span());
557            Some(e.try_search(input))
558        } else if let Some(e) = self.hybrid.get(input) {
559            trace!("using lazy DFA for search at {:?}", input.get_span());
560            Some(e.try_search(&mut cache.hybrid, input))
561        } else {
562            None
563        }
564    }
565
566    fn search_nofail(
567        &self,
568        cache: &mut Cache,
569        input: &Input<'_>,
570    ) -> Option<Match> {
571        let caps = &mut cache.capmatches;
572        caps.set_pattern(None);
573        let pid = if let Some(ref e) = self.onepass.get(input) {
580            trace!("using OnePass for search at {:?}", input.get_span());
581            e.search_slots(&mut cache.onepass, input, caps.slots_mut())
582        } else if let Some(ref e) = self.backtrack.get(input) {
583            trace!(
584                "using BoundedBacktracker for search at {:?}",
585                input.get_span()
586            );
587            e.search_slots(&mut cache.backtrack, input, caps.slots_mut())
588        } else {
589            trace!("using PikeVM for search at {:?}", input.get_span());
590            let e = self.pikevm.get();
591            e.search_slots(&mut cache.pikevm, input, caps.slots_mut())
592        };
593        caps.set_pattern(pid);
594        caps.get_match()
595    }
596
597    fn search_half_nofail(
598        &self,
599        cache: &mut Cache,
600        input: &Input<'_>,
601    ) -> Option<HalfMatch> {
602        let m = self.search_nofail(cache, input)?;
607        Some(HalfMatch::new(m.pattern(), m.end()))
608    }
609
610    fn search_slots_nofail(
611        &self,
612        cache: &mut Cache,
613        input: &Input<'_>,
614        slots: &mut [Option<NonMaxUsize>],
615    ) -> Option<PatternID> {
616        if let Some(ref e) = self.onepass.get(input) {
617            trace!(
618                "using OnePass for capture search at {:?}",
619                input.get_span()
620            );
621            e.search_slots(&mut cache.onepass, input, slots)
622        } else if let Some(ref e) = self.backtrack.get(input) {
623            trace!(
624                "using BoundedBacktracker for capture search at {:?}",
625                input.get_span()
626            );
627            e.search_slots(&mut cache.backtrack, input, slots)
628        } else {
629            trace!(
630                "using PikeVM for capture search at {:?}",
631                input.get_span()
632            );
633            let e = self.pikevm.get();
634            e.search_slots(&mut cache.pikevm, input, slots)
635        }
636    }
637
638    fn is_match_nofail(&self, cache: &mut Cache, input: &Input<'_>) -> bool {
639        if let Some(ref e) = self.onepass.get(input) {
640            trace!(
641                "using OnePass for is-match search at {:?}",
642                input.get_span()
643            );
644            e.search_slots(&mut cache.onepass, input, &mut []).is_some()
645        } else if let Some(ref e) = self.backtrack.get(input) {
646            trace!(
647                "using BoundedBacktracker for is-match search at {:?}",
648                input.get_span()
649            );
650            e.is_match(&mut cache.backtrack, input)
651        } else {
652            trace!(
653                "using PikeVM for is-match search at {:?}",
654                input.get_span()
655            );
656            let e = self.pikevm.get();
657            e.is_match(&mut cache.pikevm, input)
658        }
659    }
660
661    fn is_capture_search_needed(&self, slots_len: usize) -> bool {
662        slots_len > self.nfa.group_info().implicit_slot_len()
663    }
664}
665
666impl Strategy for Core {
667    #[cfg_attr(feature = "perf-inline", inline(always))]
668    fn group_info(&self) -> &GroupInfo {
669        self.nfa.group_info()
670    }
671
672    #[cfg_attr(feature = "perf-inline", inline(always))]
673    fn create_cache(&self) -> Cache {
674        Cache {
675            capmatches: Captures::all(self.group_info().clone()),
676            pikevm: self.pikevm.create_cache(),
677            backtrack: self.backtrack.create_cache(),
678            onepass: self.onepass.create_cache(),
679            hybrid: self.hybrid.create_cache(),
680            revhybrid: wrappers::ReverseHybridCache::none(),
681        }
682    }
683
684    #[cfg_attr(feature = "perf-inline", inline(always))]
685    fn reset_cache(&self, cache: &mut Cache) {
686        cache.pikevm.reset(&self.pikevm);
687        cache.backtrack.reset(&self.backtrack);
688        cache.onepass.reset(&self.onepass);
689        cache.hybrid.reset(&self.hybrid);
690    }
691
692    fn is_accelerated(&self) -> bool {
693        self.pre.as_ref().map_or(false, |pre| pre.is_fast())
694    }
695
696    fn memory_usage(&self) -> usize {
697        self.info.memory_usage()
698            + self.pre.as_ref().map_or(0, |pre| pre.memory_usage())
699            + self.nfa.memory_usage()
700            + self.nfarev.as_ref().map_or(0, |nfa| nfa.memory_usage())
701            + self.onepass.memory_usage()
702            + self.dfa.memory_usage()
703    }
704
705    #[cfg_attr(feature = "perf-inline", inline(always))]
706    fn search(&self, cache: &mut Cache, input: &Input<'_>) -> Option<Match> {
707        return if let Some(e) = self.dfa.get(input) {
710            trace!("using full DFA for full search at {:?}", input.get_span());
711            match e.try_search(input) {
712                Ok(x) => x,
713                Err(_err) => {
714                    trace!("full DFA search failed: {}", _err);
715                    self.search_nofail(cache, input)
716                }
717            }
718        } else if let Some(e) = self.hybrid.get(input) {
719            trace!("using lazy DFA for full search at {:?}", input.get_span());
720            match e.try_search(&mut cache.hybrid, input) {
721                Ok(x) => x,
722                Err(_err) => {
723                    trace!("lazy DFA search failed: {}", _err);
724                    self.search_nofail(cache, input)
725                }
726            }
727        } else {
728            self.search_nofail(cache, input)
729        };
730    }
731
732    #[cfg_attr(feature = "perf-inline", inline(always))]
733    fn search_half(
734        &self,
735        cache: &mut Cache,
736        input: &Input<'_>,
737    ) -> Option<HalfMatch> {
738        if let Some(e) = self.dfa.get(input) {
742            trace!("using full DFA for half search at {:?}", input.get_span());
743            match e.try_search_half_fwd(input) {
744                Ok(x) => x,
745                Err(_err) => {
746                    trace!("full DFA half search failed: {}", _err);
747                    self.search_half_nofail(cache, input)
748                }
749            }
750        } else if let Some(e) = self.hybrid.get(input) {
751            trace!("using lazy DFA for half search at {:?}", input.get_span());
752            match e.try_search_half_fwd(&mut cache.hybrid, input) {
753                Ok(x) => x,
754                Err(_err) => {
755                    trace!("lazy DFA half search failed: {}", _err);
756                    self.search_half_nofail(cache, input)
757                }
758            }
759        } else {
760            self.search_half_nofail(cache, input)
761        }
762    }
763
764    #[cfg_attr(feature = "perf-inline", inline(always))]
765    fn is_match(&self, cache: &mut Cache, input: &Input<'_>) -> bool {
766        if let Some(e) = self.dfa.get(input) {
767            trace!(
768                "using full DFA for is-match search at {:?}",
769                input.get_span()
770            );
771            match e.try_search_half_fwd(input) {
772                Ok(x) => x.is_some(),
773                Err(_err) => {
774                    trace!("full DFA half search failed: {}", _err);
775                    self.is_match_nofail(cache, input)
776                }
777            }
778        } else if let Some(e) = self.hybrid.get(input) {
779            trace!(
780                "using lazy DFA for is-match search at {:?}",
781                input.get_span()
782            );
783            match e.try_search_half_fwd(&mut cache.hybrid, input) {
784                Ok(x) => x.is_some(),
785                Err(_err) => {
786                    trace!("lazy DFA half search failed: {}", _err);
787                    self.is_match_nofail(cache, input)
788                }
789            }
790        } else {
791            self.is_match_nofail(cache, input)
792        }
793    }
794
795    #[cfg_attr(feature = "perf-inline", inline(always))]
796    fn search_slots(
797        &self,
798        cache: &mut Cache,
799        input: &Input<'_>,
800        slots: &mut [Option<NonMaxUsize>],
801    ) -> Option<PatternID> {
802        if !self.is_capture_search_needed(slots.len()) {
808            trace!("asked for slots unnecessarily, trying fast path");
809            let m = self.search(cache, input)?;
810            copy_match_to_slots(m, slots);
811            return Some(m.pattern());
812        }
813        if self.onepass.get(&input).is_some() {
827            return self.search_slots_nofail(cache, &input, slots);
828        }
829        let m = match self.try_search_mayfail(cache, input) {
830            Some(Ok(Some(m))) => m,
831            Some(Ok(None)) => return None,
832            Some(Err(_err)) => {
833                trace!("fast capture search failed: {}", _err);
834                return self.search_slots_nofail(cache, input, slots);
835            }
836            None => {
837                return self.search_slots_nofail(cache, input, slots);
838            }
839        };
840        trace!(
845            "match found at {}..{} in capture search, \
846		  	 using another engine to find captures",
847            m.start(),
848            m.end(),
849        );
850        let input = input
851            .clone()
852            .span(m.start()..m.end())
853            .anchored(Anchored::Pattern(m.pattern()));
854        Some(
855            self.search_slots_nofail(cache, &input, slots)
856                .expect("should find a match"),
857        )
858    }
859
860    #[cfg_attr(feature = "perf-inline", inline(always))]
861    fn which_overlapping_matches(
862        &self,
863        cache: &mut Cache,
864        input: &Input<'_>,
865        patset: &mut PatternSet,
866    ) {
867        if let Some(e) = self.dfa.get(input) {
868            trace!(
869                "using full DFA for overlapping search at {:?}",
870                input.get_span()
871            );
872            let _err = match e.try_which_overlapping_matches(input, patset) {
873                Ok(()) => return,
874                Err(err) => err,
875            };
876            trace!("fast overlapping search failed: {}", _err);
877        } else if let Some(e) = self.hybrid.get(input) {
878            trace!(
879                "using lazy DFA for overlapping search at {:?}",
880                input.get_span()
881            );
882            let _err = match e.try_which_overlapping_matches(
883                &mut cache.hybrid,
884                input,
885                patset,
886            ) {
887                Ok(()) => {
888                    return;
889                }
890                Err(err) => err,
891            };
892            trace!("fast overlapping search failed: {}", _err);
893        }
894        trace!(
895            "using PikeVM for overlapping search at {:?}",
896            input.get_span()
897        );
898        let e = self.pikevm.get();
899        e.which_overlapping_matches(&mut cache.pikevm, input, patset)
900    }
901}
902
903#[derive(Debug)]
904struct ReverseAnchored {
905    core: Core,
906}
907
908impl ReverseAnchored {
909    fn new(core: Core) -> Result<ReverseAnchored, Core> {
910        if !core.info.is_always_anchored_end() {
911            debug!(
912                "skipping reverse anchored optimization because \
913				 the regex is not always anchored at the end"
914            );
915            return Err(core);
916        }
917        if core.info.is_always_anchored_start() {
926            debug!(
927                "skipping reverse anchored optimization because \
928				 the regex is also anchored at the start"
929            );
930            return Err(core);
931        }
932        if !core.hybrid.is_some() && !core.dfa.is_some() {
936            debug!(
937                "skipping reverse anchored optimization because \
938				 we don't have a lazy DFA or a full DFA"
939            );
940            return Err(core);
941        }
942        Ok(ReverseAnchored { core })
943    }
944
945    #[cfg_attr(feature = "perf-inline", inline(always))]
946    fn try_search_half_anchored_rev(
947        &self,
948        cache: &mut Cache,
949        input: &Input<'_>,
950    ) -> Result<Option<HalfMatch>, RetryFailError> {
951        let input = input.clone().anchored(Anchored::Yes);
956        if let Some(e) = self.core.dfa.get(&input) {
957            trace!(
958                "using full DFA for reverse anchored search at {:?}",
959                input.get_span()
960            );
961            e.try_search_half_rev(&input)
962        } else if let Some(e) = self.core.hybrid.get(&input) {
963            trace!(
964                "using lazy DFA for reverse anchored search at {:?}",
965                input.get_span()
966            );
967            e.try_search_half_rev(&mut cache.hybrid, &input)
968        } else {
969            unreachable!("ReverseAnchored always has a DFA")
970        }
971    }
972}
973
974impl Strategy for ReverseAnchored {
982    #[cfg_attr(feature = "perf-inline", inline(always))]
983    fn group_info(&self) -> &GroupInfo {
984        self.core.group_info()
985    }
986
987    #[cfg_attr(feature = "perf-inline", inline(always))]
988    fn create_cache(&self) -> Cache {
989        self.core.create_cache()
990    }
991
992    #[cfg_attr(feature = "perf-inline", inline(always))]
993    fn reset_cache(&self, cache: &mut Cache) {
994        self.core.reset_cache(cache);
995    }
996
997    fn is_accelerated(&self) -> bool {
998        true
1002    }
1003
1004    fn memory_usage(&self) -> usize {
1005        self.core.memory_usage()
1006    }
1007
1008    #[cfg_attr(feature = "perf-inline", inline(always))]
1009    fn search(&self, cache: &mut Cache, input: &Input<'_>) -> Option<Match> {
1010        if input.get_anchored().is_anchored() {
1011            return self.core.search(cache, input);
1012        }
1013        match self.try_search_half_anchored_rev(cache, input) {
1014            Err(_err) => {
1015                trace!("fast reverse anchored search failed: {}", _err);
1016                self.core.search_nofail(cache, input)
1017            }
1018            Ok(None) => None,
1019            Ok(Some(hm)) => {
1020                Some(Match::new(hm.pattern(), hm.offset()..input.end()))
1021            }
1022        }
1023    }
1024
1025    #[cfg_attr(feature = "perf-inline", inline(always))]
1026    fn search_half(
1027        &self,
1028        cache: &mut Cache,
1029        input: &Input<'_>,
1030    ) -> Option<HalfMatch> {
1031        if input.get_anchored().is_anchored() {
1032            return self.core.search_half(cache, input);
1033        }
1034        match self.try_search_half_anchored_rev(cache, input) {
1035            Err(_err) => {
1036                trace!("fast reverse anchored search failed: {}", _err);
1037                self.core.search_half_nofail(cache, input)
1038            }
1039            Ok(None) => None,
1040            Ok(Some(hm)) => {
1041                Some(HalfMatch::new(hm.pattern(), input.end()))
1048            }
1049        }
1050    }
1051
1052    #[cfg_attr(feature = "perf-inline", inline(always))]
1053    fn is_match(&self, cache: &mut Cache, input: &Input<'_>) -> bool {
1054        if input.get_anchored().is_anchored() {
1055            return self.core.is_match(cache, input);
1056        }
1057        match self.try_search_half_anchored_rev(cache, input) {
1058            Err(_err) => {
1059                trace!("fast reverse anchored search failed: {}", _err);
1060                self.core.is_match_nofail(cache, input)
1061            }
1062            Ok(None) => false,
1063            Ok(Some(_)) => true,
1064        }
1065    }
1066
1067    #[cfg_attr(feature = "perf-inline", inline(always))]
1068    fn search_slots(
1069        &self,
1070        cache: &mut Cache,
1071        input: &Input<'_>,
1072        slots: &mut [Option<NonMaxUsize>],
1073    ) -> Option<PatternID> {
1074        if input.get_anchored().is_anchored() {
1075            return self.core.search_slots(cache, input, slots);
1076        }
1077        match self.try_search_half_anchored_rev(cache, input) {
1078            Err(_err) => {
1079                trace!("fast reverse anchored search failed: {}", _err);
1080                self.core.search_slots_nofail(cache, input, slots)
1081            }
1082            Ok(None) => None,
1083            Ok(Some(hm)) => {
1084                if !self.core.is_capture_search_needed(slots.len()) {
1085                    trace!("asked for slots unnecessarily, skipping captures");
1086                    let m = Match::new(hm.pattern(), hm.offset()..input.end());
1087                    copy_match_to_slots(m, slots);
1088                    return Some(m.pattern());
1089                }
1090                let start = hm.offset();
1091                let input = input
1092                    .clone()
1093                    .span(start..input.end())
1094                    .anchored(Anchored::Pattern(hm.pattern()));
1095                self.core.search_slots_nofail(cache, &input, slots)
1096            }
1097        }
1098    }
1099
1100    #[cfg_attr(feature = "perf-inline", inline(always))]
1101    fn which_overlapping_matches(
1102        &self,
1103        cache: &mut Cache,
1104        input: &Input<'_>,
1105        patset: &mut PatternSet,
1106    ) {
1107        self.core.which_overlapping_matches(cache, input, patset)
1112    }
1113}
1114
1115#[derive(Debug)]
1116struct ReverseSuffix {
1117    core: Core,
1118    pre: Prefilter,
1119}
1120
1121impl ReverseSuffix {
1122    fn new(core: Core, hirs: &[&Hir]) -> Result<ReverseSuffix, Core> {
1123        if !core.info.config().get_auto_prefilter() {
1124            debug!(
1125                "skipping reverse suffix optimization because \
1126                 automatic prefilters are disabled"
1127            );
1128            return Err(core);
1129        }
1130        if core.info.is_always_anchored_start() {
1146            debug!(
1147                "skipping reverse suffix optimization because \
1148				 the regex is always anchored at the start",
1149            );
1150            return Err(core);
1151        }
1152        if !core.hybrid.is_some() && !core.dfa.is_some() {
1156            debug!(
1157                "skipping reverse suffix optimization because \
1158				 we don't have a lazy DFA or a full DFA"
1159            );
1160            return Err(core);
1161        }
1162        if core.pre.as_ref().map_or(false, |p| p.is_fast()) {
1163            debug!(
1164                "skipping reverse suffix optimization because \
1165				 we already have a prefilter that we think is fast"
1166            );
1167            return Err(core);
1168        }
1169        let kind = core.info.config().get_match_kind();
1170        let suffixes = crate::util::prefilter::suffixes(kind, hirs);
1171        let lcs = match suffixes.longest_common_suffix() {
1172            None => {
1173                debug!(
1174                    "skipping reverse suffix optimization because \
1175                     a longest common suffix could not be found",
1176                );
1177                return Err(core);
1178            }
1179            Some(lcs) if lcs.is_empty() => {
1180                debug!(
1181                    "skipping reverse suffix optimization because \
1182                     the longest common suffix is the empty string",
1183                );
1184                return Err(core);
1185            }
1186            Some(lcs) => lcs,
1187        };
1188        let pre = match Prefilter::new(kind, &[lcs]) {
1189            Some(pre) => pre,
1190            None => {
1191                debug!(
1192                    "skipping reverse suffix optimization because \
1193                     a prefilter could not be constructed from the \
1194                     longest common suffix",
1195                );
1196                return Err(core);
1197            }
1198        };
1199        if !pre.is_fast() {
1200            debug!(
1201                "skipping reverse suffix optimization because \
1202				 while we have a suffix prefilter, it is not \
1203				 believed to be 'fast'"
1204            );
1205            return Err(core);
1206        }
1207        Ok(ReverseSuffix { core, pre })
1208    }
1209
1210    #[cfg_attr(feature = "perf-inline", inline(always))]
1211    fn try_search_half_start(
1212        &self,
1213        cache: &mut Cache,
1214        input: &Input<'_>,
1215    ) -> Result<Option<HalfMatch>, RetryError> {
1216        let mut span = input.get_span();
1217        let mut min_start = 0;
1218        loop {
1219            let litmatch = match self.pre.find(input.haystack(), span) {
1220                None => return Ok(None),
1221                Some(span) => span,
1222            };
1223            trace!("reverse suffix scan found suffix match at {:?}", litmatch);
1224            let revinput = input
1225                .clone()
1226                .anchored(Anchored::Yes)
1227                .span(input.start()..litmatch.end);
1228            match self
1229                .try_search_half_rev_limited(cache, &revinput, min_start)?
1230            {
1231                None => {
1232                    if span.start >= span.end {
1233                        break;
1234                    }
1235                    span.start = litmatch.start.checked_add(1).unwrap();
1236                }
1237                Some(hm) => return Ok(Some(hm)),
1238            }
1239            min_start = litmatch.end;
1240        }
1241        Ok(None)
1242    }
1243
1244    #[cfg_attr(feature = "perf-inline", inline(always))]
1245    fn try_search_half_fwd(
1246        &self,
1247        cache: &mut Cache,
1248        input: &Input<'_>,
1249    ) -> Result<Option<HalfMatch>, RetryFailError> {
1250        if let Some(e) = self.core.dfa.get(&input) {
1251            trace!(
1252                "using full DFA for forward reverse suffix search at {:?}",
1253                input.get_span()
1254            );
1255            e.try_search_half_fwd(&input)
1256        } else if let Some(e) = self.core.hybrid.get(&input) {
1257            trace!(
1258                "using lazy DFA for forward reverse suffix search at {:?}",
1259                input.get_span()
1260            );
1261            e.try_search_half_fwd(&mut cache.hybrid, &input)
1262        } else {
1263            unreachable!("ReverseSuffix always has a DFA")
1264        }
1265    }
1266
1267    #[cfg_attr(feature = "perf-inline", inline(always))]
1268    fn try_search_half_rev_limited(
1269        &self,
1270        cache: &mut Cache,
1271        input: &Input<'_>,
1272        min_start: usize,
1273    ) -> Result<Option<HalfMatch>, RetryError> {
1274        if let Some(e) = self.core.dfa.get(&input) {
1275            trace!(
1276                "using full DFA for reverse suffix search at {:?}, \
1277                 but will be stopped at {} to avoid quadratic behavior",
1278                input.get_span(),
1279                min_start,
1280            );
1281            e.try_search_half_rev_limited(&input, min_start)
1282        } else if let Some(e) = self.core.hybrid.get(&input) {
1283            trace!(
1284                "using lazy DFA for reverse suffix search at {:?}, \
1285                 but will be stopped at {} to avoid quadratic behavior",
1286                input.get_span(),
1287                min_start,
1288            );
1289            e.try_search_half_rev_limited(&mut cache.hybrid, &input, min_start)
1290        } else {
1291            unreachable!("ReverseSuffix always has a DFA")
1292        }
1293    }
1294}
1295
1296impl Strategy for ReverseSuffix {
1297    #[cfg_attr(feature = "perf-inline", inline(always))]
1298    fn group_info(&self) -> &GroupInfo {
1299        self.core.group_info()
1300    }
1301
1302    #[cfg_attr(feature = "perf-inline", inline(always))]
1303    fn create_cache(&self) -> Cache {
1304        self.core.create_cache()
1305    }
1306
1307    #[cfg_attr(feature = "perf-inline", inline(always))]
1308    fn reset_cache(&self, cache: &mut Cache) {
1309        self.core.reset_cache(cache);
1310    }
1311
1312    fn is_accelerated(&self) -> bool {
1313        self.pre.is_fast()
1314    }
1315
1316    fn memory_usage(&self) -> usize {
1317        self.core.memory_usage() + self.pre.memory_usage()
1318    }
1319
1320    #[cfg_attr(feature = "perf-inline", inline(always))]
1321    fn search(&self, cache: &mut Cache, input: &Input<'_>) -> Option<Match> {
1322        if input.get_anchored().is_anchored() {
1323            return self.core.search(cache, input);
1324        }
1325        match self.try_search_half_start(cache, input) {
1326            Err(RetryError::Quadratic(_err)) => {
1327                trace!("reverse suffix optimization failed: {}", _err);
1328                self.core.search(cache, input)
1329            }
1330            Err(RetryError::Fail(_err)) => {
1331                trace!("reverse suffix reverse fast search failed: {}", _err);
1332                self.core.search_nofail(cache, input)
1333            }
1334            Ok(None) => None,
1335            Ok(Some(hm_start)) => {
1336                let fwdinput = input
1337                    .clone()
1338                    .anchored(Anchored::Pattern(hm_start.pattern()))
1339                    .span(hm_start.offset()..input.end());
1340                match self.try_search_half_fwd(cache, &fwdinput) {
1341                    Err(_err) => {
1342                        trace!(
1343                            "reverse suffix forward fast search failed: {}",
1344                            _err
1345                        );
1346                        self.core.search_nofail(cache, input)
1347                    }
1348                    Ok(None) => {
1349                        unreachable!(
1350                            "suffix match plus reverse match implies \
1351						     there must be a match",
1352                        )
1353                    }
1354                    Ok(Some(hm_end)) => Some(Match::new(
1355                        hm_start.pattern(),
1356                        hm_start.offset()..hm_end.offset(),
1357                    )),
1358                }
1359            }
1360        }
1361    }
1362
1363    #[cfg_attr(feature = "perf-inline", inline(always))]
1364    fn search_half(
1365        &self,
1366        cache: &mut Cache,
1367        input: &Input<'_>,
1368    ) -> Option<HalfMatch> {
1369        if input.get_anchored().is_anchored() {
1370            return self.core.search_half(cache, input);
1371        }
1372        match self.try_search_half_start(cache, input) {
1373            Err(RetryError::Quadratic(_err)) => {
1374                trace!("reverse suffix half optimization failed: {}", _err);
1375                self.core.search_half(cache, input)
1376            }
1377            Err(RetryError::Fail(_err)) => {
1378                trace!(
1379                    "reverse suffix reverse fast half search failed: {}",
1380                    _err
1381                );
1382                self.core.search_half_nofail(cache, input)
1383            }
1384            Ok(None) => None,
1385            Ok(Some(hm_start)) => {
1386                let fwdinput = input
1396                    .clone()
1397                    .anchored(Anchored::Pattern(hm_start.pattern()))
1398                    .span(hm_start.offset()..input.end());
1399                match self.try_search_half_fwd(cache, &fwdinput) {
1400                    Err(_err) => {
1401                        trace!(
1402                            "reverse suffix forward fast search failed: {}",
1403                            _err
1404                        );
1405                        self.core.search_half_nofail(cache, input)
1406                    }
1407                    Ok(None) => {
1408                        unreachable!(
1409                            "suffix match plus reverse match implies \
1410						     there must be a match",
1411                        )
1412                    }
1413                    Ok(Some(hm_end)) => Some(hm_end),
1414                }
1415            }
1416        }
1417    }
1418
1419    #[cfg_attr(feature = "perf-inline", inline(always))]
1420    fn is_match(&self, cache: &mut Cache, input: &Input<'_>) -> bool {
1421        if input.get_anchored().is_anchored() {
1422            return self.core.is_match(cache, input);
1423        }
1424        match self.try_search_half_start(cache, input) {
1425            Err(RetryError::Quadratic(_err)) => {
1426                trace!("reverse suffix half optimization failed: {}", _err);
1427                self.core.is_match_nofail(cache, input)
1428            }
1429            Err(RetryError::Fail(_err)) => {
1430                trace!(
1431                    "reverse suffix reverse fast half search failed: {}",
1432                    _err
1433                );
1434                self.core.is_match_nofail(cache, input)
1435            }
1436            Ok(None) => false,
1437            Ok(Some(_)) => true,
1438        }
1439    }
1440
1441    #[cfg_attr(feature = "perf-inline", inline(always))]
1442    fn search_slots(
1443        &self,
1444        cache: &mut Cache,
1445        input: &Input<'_>,
1446        slots: &mut [Option<NonMaxUsize>],
1447    ) -> Option<PatternID> {
1448        if input.get_anchored().is_anchored() {
1449            return self.core.search_slots(cache, input, slots);
1450        }
1451        if !self.core.is_capture_search_needed(slots.len()) {
1452            trace!("asked for slots unnecessarily, trying fast path");
1453            let m = self.search(cache, input)?;
1454            copy_match_to_slots(m, slots);
1455            return Some(m.pattern());
1456        }
1457        let hm_start = match self.try_search_half_start(cache, input) {
1458            Err(RetryError::Quadratic(_err)) => {
1459                trace!(
1460                    "reverse suffix captures optimization failed: {}",
1461                    _err
1462                );
1463                return self.core.search_slots(cache, input, slots);
1464            }
1465            Err(RetryError::Fail(_err)) => {
1466                trace!(
1467                    "reverse suffix reverse fast captures search failed: {}",
1468                    _err
1469                );
1470                return self.core.search_slots_nofail(cache, input, slots);
1471            }
1472            Ok(None) => return None,
1473            Ok(Some(hm_start)) => hm_start,
1474        };
1475        trace!(
1476            "match found at {}..{} in capture search, \
1477		  	 using another engine to find captures",
1478            hm_start.offset(),
1479            input.end(),
1480        );
1481        let start = hm_start.offset();
1482        let input = input
1483            .clone()
1484            .span(start..input.end())
1485            .anchored(Anchored::Pattern(hm_start.pattern()));
1486        self.core.search_slots_nofail(cache, &input, slots)
1487    }
1488
1489    #[cfg_attr(feature = "perf-inline", inline(always))]
1490    fn which_overlapping_matches(
1491        &self,
1492        cache: &mut Cache,
1493        input: &Input<'_>,
1494        patset: &mut PatternSet,
1495    ) {
1496        self.core.which_overlapping_matches(cache, input, patset)
1497    }
1498}
1499
1500#[derive(Debug)]
1501struct ReverseInner {
1502    core: Core,
1503    preinner: Prefilter,
1504    nfarev: NFA,
1505    hybrid: wrappers::ReverseHybrid,
1506    dfa: wrappers::ReverseDFA,
1507}
1508
1509impl ReverseInner {
1510    fn new(core: Core, hirs: &[&Hir]) -> Result<ReverseInner, Core> {
1511        if !core.info.config().get_auto_prefilter() {
1512            debug!(
1513                "skipping reverse inner optimization because \
1514                 automatic prefilters are disabled"
1515            );
1516            return Err(core);
1517        }
1518        if core.info.config().get_match_kind() != MatchKind::LeftmostFirst {
1523            debug!(
1524                "skipping reverse inner optimization because \
1525				 match kind is {:?} but this only supports leftmost-first",
1526                core.info.config().get_match_kind(),
1527            );
1528            return Err(core);
1529        }
1530        if core.info.is_always_anchored_start() {
1546            debug!(
1547                "skipping reverse inner optimization because \
1548				 the regex is always anchored at the start",
1549            );
1550            return Err(core);
1551        }
1552        if !core.hybrid.is_some() && !core.dfa.is_some() {
1556            debug!(
1557                "skipping reverse inner optimization because \
1558				 we don't have a lazy DFA or a full DFA"
1559            );
1560            return Err(core);
1561        }
1562        if core.pre.as_ref().map_or(false, |p| p.is_fast()) {
1563            debug!(
1564                "skipping reverse inner optimization because \
1565				 we already have a prefilter that we think is fast"
1566            );
1567            return Err(core);
1568        } else if core.pre.is_some() {
1569            debug!(
1570                "core engine has a prefix prefilter, but it is \
1571                 probably not fast, so continuing with attempt to \
1572                 use reverse inner prefilter"
1573            );
1574        }
1575        let (concat_prefix, preinner) = match reverse_inner::extract(hirs) {
1576            Some(x) => x,
1577            None => return Err(core),
1580        };
1581        debug!("building reverse NFA for prefix before inner literal");
1582        let mut lookm = LookMatcher::new();
1583        lookm.set_line_terminator(core.info.config().get_line_terminator());
1584        let thompson_config = thompson::Config::new()
1585            .reverse(true)
1586            .utf8(core.info.config().get_utf8_empty())
1587            .nfa_size_limit(core.info.config().get_nfa_size_limit())
1588            .shrink(false)
1589            .which_captures(WhichCaptures::None)
1590            .look_matcher(lookm);
1591        let result = thompson::Compiler::new()
1592            .configure(thompson_config)
1593            .build_from_hir(&concat_prefix);
1594        let nfarev = match result {
1595            Ok(nfarev) => nfarev,
1596            Err(_err) => {
1597                debug!(
1598                    "skipping reverse inner optimization because the \
1599					 reverse NFA failed to build: {}",
1600                    _err,
1601                );
1602                return Err(core);
1603            }
1604        };
1605        debug!("building reverse DFA for prefix before inner literal");
1606        let dfa = if !core.info.config().get_dfa() {
1607            wrappers::ReverseDFA::none()
1608        } else {
1609            wrappers::ReverseDFA::new(&core.info, &nfarev)
1610        };
1611        let hybrid = if !core.info.config().get_hybrid() {
1612            wrappers::ReverseHybrid::none()
1613        } else if dfa.is_some() {
1614            debug!(
1615                "skipping lazy DFA for reverse inner optimization \
1616				 because we have a full DFA"
1617            );
1618            wrappers::ReverseHybrid::none()
1619        } else {
1620            wrappers::ReverseHybrid::new(&core.info, &nfarev)
1621        };
1622        Ok(ReverseInner { core, preinner, nfarev, hybrid, dfa })
1623    }
1624
1625    #[cfg_attr(feature = "perf-inline", inline(always))]
1626    fn try_search_full(
1627        &self,
1628        cache: &mut Cache,
1629        input: &Input<'_>,
1630    ) -> Result<Option<Match>, RetryError> {
1631        let mut span = input.get_span();
1632        let mut min_match_start = 0;
1633        let mut min_pre_start = 0;
1634        loop {
1635            let litmatch = match self.preinner.find(input.haystack(), span) {
1636                None => return Ok(None),
1637                Some(span) => span,
1638            };
1639            if litmatch.start < min_pre_start {
1640                trace!(
1641                    "found inner prefilter match at {:?}, which starts \
1642					 before the end of the last forward scan at {}, \
1643					 quitting to avoid quadratic behavior",
1644                    litmatch,
1645                    min_pre_start,
1646                );
1647                return Err(RetryError::Quadratic(RetryQuadraticError::new()));
1648            }
1649            trace!("reverse inner scan found inner match at {:?}", litmatch);
1650            let revinput = input
1651                .clone()
1652                .anchored(Anchored::Yes)
1653                .span(input.start()..litmatch.start);
1654            match self.try_search_half_rev_limited(
1661                cache,
1662                &revinput,
1663                min_match_start,
1664            )? {
1665                None => {
1666                    if span.start >= span.end {
1667                        break;
1668                    }
1669                    span.start = litmatch.start.checked_add(1).unwrap();
1670                }
1671                Some(hm_start) => {
1672                    let fwdinput = input
1673                        .clone()
1674                        .anchored(Anchored::Pattern(hm_start.pattern()))
1675                        .span(hm_start.offset()..input.end());
1676                    match self.try_search_half_fwd_stopat(cache, &fwdinput)? {
1677                        Err(stopat) => {
1678                            min_pre_start = stopat;
1679                            span.start =
1680                                litmatch.start.checked_add(1).unwrap();
1681                        }
1682                        Ok(hm_end) => {
1683                            return Ok(Some(Match::new(
1684                                hm_start.pattern(),
1685                                hm_start.offset()..hm_end.offset(),
1686                            )))
1687                        }
1688                    }
1689                }
1690            }
1691            min_match_start = litmatch.end;
1692        }
1693        Ok(None)
1694    }
1695
1696    #[cfg_attr(feature = "perf-inline", inline(always))]
1697    fn try_search_half_fwd_stopat(
1698        &self,
1699        cache: &mut Cache,
1700        input: &Input<'_>,
1701    ) -> Result<Result<HalfMatch, usize>, RetryFailError> {
1702        if let Some(e) = self.core.dfa.get(&input) {
1703            trace!(
1704                "using full DFA for forward reverse inner search at {:?}",
1705                input.get_span()
1706            );
1707            e.try_search_half_fwd_stopat(&input)
1708        } else if let Some(e) = self.core.hybrid.get(&input) {
1709            trace!(
1710                "using lazy DFA for forward reverse inner search at {:?}",
1711                input.get_span()
1712            );
1713            e.try_search_half_fwd_stopat(&mut cache.hybrid, &input)
1714        } else {
1715            unreachable!("ReverseInner always has a DFA")
1716        }
1717    }
1718
1719    #[cfg_attr(feature = "perf-inline", inline(always))]
1720    fn try_search_half_rev_limited(
1721        &self,
1722        cache: &mut Cache,
1723        input: &Input<'_>,
1724        min_start: usize,
1725    ) -> Result<Option<HalfMatch>, RetryError> {
1726        if let Some(e) = self.dfa.get(&input) {
1727            trace!(
1728                "using full DFA for reverse inner search at {:?}, \
1729                 but will be stopped at {} to avoid quadratic behavior",
1730                input.get_span(),
1731                min_start,
1732            );
1733            e.try_search_half_rev_limited(&input, min_start)
1734        } else if let Some(e) = self.hybrid.get(&input) {
1735            trace!(
1736                "using lazy DFA for reverse inner search at {:?}, \
1737                 but will be stopped at {} to avoid quadratic behavior",
1738                input.get_span(),
1739                min_start,
1740            );
1741            e.try_search_half_rev_limited(
1742                &mut cache.revhybrid,
1743                &input,
1744                min_start,
1745            )
1746        } else {
1747            unreachable!("ReverseInner always has a DFA")
1748        }
1749    }
1750}
1751
1752impl Strategy for ReverseInner {
1753    #[cfg_attr(feature = "perf-inline", inline(always))]
1754    fn group_info(&self) -> &GroupInfo {
1755        self.core.group_info()
1756    }
1757
1758    #[cfg_attr(feature = "perf-inline", inline(always))]
1759    fn create_cache(&self) -> Cache {
1760        let mut cache = self.core.create_cache();
1761        cache.revhybrid = self.hybrid.create_cache();
1762        cache
1763    }
1764
1765    #[cfg_attr(feature = "perf-inline", inline(always))]
1766    fn reset_cache(&self, cache: &mut Cache) {
1767        self.core.reset_cache(cache);
1768        cache.revhybrid.reset(&self.hybrid);
1769    }
1770
1771    fn is_accelerated(&self) -> bool {
1772        self.preinner.is_fast()
1773    }
1774
1775    fn memory_usage(&self) -> usize {
1776        self.core.memory_usage()
1777            + self.preinner.memory_usage()
1778            + self.nfarev.memory_usage()
1779            + self.dfa.memory_usage()
1780    }
1781
1782    #[cfg_attr(feature = "perf-inline", inline(always))]
1783    fn search(&self, cache: &mut Cache, input: &Input<'_>) -> Option<Match> {
1784        if input.get_anchored().is_anchored() {
1785            return self.core.search(cache, input);
1786        }
1787        match self.try_search_full(cache, input) {
1788            Err(RetryError::Quadratic(_err)) => {
1789                trace!("reverse inner optimization failed: {}", _err);
1790                self.core.search(cache, input)
1791            }
1792            Err(RetryError::Fail(_err)) => {
1793                trace!("reverse inner fast search failed: {}", _err);
1794                self.core.search_nofail(cache, input)
1795            }
1796            Ok(matornot) => matornot,
1797        }
1798    }
1799
1800    #[cfg_attr(feature = "perf-inline", inline(always))]
1801    fn search_half(
1802        &self,
1803        cache: &mut Cache,
1804        input: &Input<'_>,
1805    ) -> Option<HalfMatch> {
1806        if input.get_anchored().is_anchored() {
1807            return self.core.search_half(cache, input);
1808        }
1809        match self.try_search_full(cache, input) {
1810            Err(RetryError::Quadratic(_err)) => {
1811                trace!("reverse inner half optimization failed: {}", _err);
1812                self.core.search_half(cache, input)
1813            }
1814            Err(RetryError::Fail(_err)) => {
1815                trace!("reverse inner fast half search failed: {}", _err);
1816                self.core.search_half_nofail(cache, input)
1817            }
1818            Ok(None) => None,
1819            Ok(Some(m)) => Some(HalfMatch::new(m.pattern(), m.end())),
1820        }
1821    }
1822
1823    #[cfg_attr(feature = "perf-inline", inline(always))]
1824    fn is_match(&self, cache: &mut Cache, input: &Input<'_>) -> bool {
1825        if input.get_anchored().is_anchored() {
1826            return self.core.is_match(cache, input);
1827        }
1828        match self.try_search_full(cache, input) {
1829            Err(RetryError::Quadratic(_err)) => {
1830                trace!("reverse inner half optimization failed: {}", _err);
1831                self.core.is_match_nofail(cache, input)
1832            }
1833            Err(RetryError::Fail(_err)) => {
1834                trace!("reverse inner fast half search failed: {}", _err);
1835                self.core.is_match_nofail(cache, input)
1836            }
1837            Ok(None) => false,
1838            Ok(Some(_)) => true,
1839        }
1840    }
1841
1842    #[cfg_attr(feature = "perf-inline", inline(always))]
1843    fn search_slots(
1844        &self,
1845        cache: &mut Cache,
1846        input: &Input<'_>,
1847        slots: &mut [Option<NonMaxUsize>],
1848    ) -> Option<PatternID> {
1849        if input.get_anchored().is_anchored() {
1850            return self.core.search_slots(cache, input, slots);
1851        }
1852        if !self.core.is_capture_search_needed(slots.len()) {
1853            trace!("asked for slots unnecessarily, trying fast path");
1854            let m = self.search(cache, input)?;
1855            copy_match_to_slots(m, slots);
1856            return Some(m.pattern());
1857        }
1858        let m = match self.try_search_full(cache, input) {
1859            Err(RetryError::Quadratic(_err)) => {
1860                trace!("reverse inner captures optimization failed: {}", _err);
1861                return self.core.search_slots(cache, input, slots);
1862            }
1863            Err(RetryError::Fail(_err)) => {
1864                trace!("reverse inner fast captures search failed: {}", _err);
1865                return self.core.search_slots_nofail(cache, input, slots);
1866            }
1867            Ok(None) => return None,
1868            Ok(Some(m)) => m,
1869        };
1870        trace!(
1871            "match found at {}..{} in capture search, \
1872		  	 using another engine to find captures",
1873            m.start(),
1874            m.end(),
1875        );
1876        let input = input
1877            .clone()
1878            .span(m.start()..m.end())
1879            .anchored(Anchored::Pattern(m.pattern()));
1880        self.core.search_slots_nofail(cache, &input, slots)
1881    }
1882
1883    #[cfg_attr(feature = "perf-inline", inline(always))]
1884    fn which_overlapping_matches(
1885        &self,
1886        cache: &mut Cache,
1887        input: &Input<'_>,
1888        patset: &mut PatternSet,
1889    ) {
1890        self.core.which_overlapping_matches(cache, input, patset)
1891    }
1892}
1893
1894#[cfg_attr(feature = "perf-inline", inline(always))]
1905fn copy_match_to_slots(m: Match, slots: &mut [Option<NonMaxUsize>]) {
1906    let slot_start = m.pattern().as_usize() * 2;
1907    let slot_end = slot_start + 1;
1908    if let Some(slot) = slots.get_mut(slot_start) {
1909        *slot = NonMaxUsize::new(m.start());
1910    }
1911    if let Some(slot) = slots.get_mut(slot_end) {
1912        *slot = NonMaxUsize::new(m.end());
1913    }
1914}