grippo 0.3.1

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
// Project:   grippo
// File:      src/strmatch/signature.rs
// Purpose:   Declarative signatures, matched alone or as one overlapping set
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A [`Signature`] is the cheapest test that says "definitely not this". A
//! [`SignatureSet`] runs many of them in one overlapping aho-corasick pass and
//! calls each signature's verify function only at its own literal hits.

use std::collections::HashMap;

use aho_corasick::{AhoCorasick, AhoCorasickKind, MatchKind};
use memchr::memmem::Finder;
use thiserror::Error;

/// Checks the bytes around a literal hit: the span and the start of the hit.
/// It should cost no more than one read of the span.
pub type Verify = fn(&[u8], usize) -> bool;

/// Most [`Verify`] calls one signature makes on one span, unless
/// [`SignatureBuilder::verify_cap`] says otherwise.
///
/// A signature with more `any_of` hits than this fires without asking again,
/// so a span full of its literal costs a bounded number of calls and at worst
/// one parser attempt.
pub const MAX_VERIFY: u8 = 8;

/// Most `all_of` literals one signature can hold.
pub const MAX_ALL_OF: usize = 64;

/// Which of two firing signatures wins.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum Specificity {
    /// A catch-all, such as plain syslog. Loses to any `Specific` match.
    Generic,
    /// Names one source, such as one firewall product.
    #[default]
    Specific,
}

/// Why a signature or set did not build.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum SignatureError {
    /// A literal is empty, so it would match everywhere.
    #[error("signature: an empty literal matches every position")]
    EmptyLiteral,
    /// More `all_of` literals than [`MAX_ALL_OF`].
    #[error("signature: {got} all_of literals, at most {max}")]
    TooManyAllOf {
        /// Literals given.
        got: usize,
        /// The limit.
        max: usize,
    },
    /// More signatures than a set can index.
    #[error("signature: a set holds at most {max} signatures")]
    TooMany {
        /// The limit.
        max: usize,
    },
    /// The automaton refused the literal set.
    #[error("signature: the literal automaton does not build: {source}")]
    Automaton {
        /// The automaton's error.
        #[source]
        source: Box<aho_corasick::BuildError>,
    },
}

fn automaton_error(e: aho_corasick::BuildError) -> SignatureError {
    SignatureError::Automaton {
        source: Box::new(e),
    }
}

/// One searched literal. memmem can't fold case, so a folded literal with a
/// letter in it, held in lower case, is found by its first byte in either
/// case and a folded compare there.
#[derive(Debug, Clone)]
enum Needle {
    Exact(Box<Finder<'static>>),
    Folded(Box<[u8]>),
}

impl Needle {
    fn new(literal: &[u8], folded: bool) -> Self {
        if folded && literal.iter().any(u8::is_ascii_alphabetic) {
            Self::Folded(literal.into())
        } else {
            Self::Exact(Box::new(Finder::new(literal).into_owned()))
        }
    }

    fn find(&self, hay: &[u8]) -> Option<usize> {
        match self {
            Self::Exact(f) => f.find(hay),
            Self::Folded(literal) => {
                let first = *literal.first()?;
                let starts = hay.get(..=hay.len().checked_sub(literal.len())?)?;
                memchr::memchr2_iter(first, first.to_ascii_uppercase(), starts).find(|&at| {
                    hay.get(at..at + literal.len())
                        .is_some_and(|here| here.eq_ignore_ascii_case(literal))
                })
            }
        }
    }

    fn bytes(&self) -> &[u8] {
        match self {
            Self::Exact(f) => f.needle(),
            Self::Folded(literal) => literal,
        }
    }
}

/// `span` starts with `literal`, with ASCII case folded when `folded`.
fn starts_with(span: &[u8], literal: &[u8], folded: bool) -> bool {
    if folded {
        span.get(..literal.len())
            .is_some_and(|head| head.eq_ignore_ascii_case(literal))
    } else {
        span.starts_with(literal)
    }
}

/// One declarative signature. It fires on a span when every rule holds:
///
/// - the span starts with one of the `anchored` literals, when there are any
/// - every `all_of` literal appears somewhere
/// - one `any_of` literal appears where `verify` accepts it, or more than
///   its verify cap, [`MAX_VERIFY`] by default, of them appear, when there
///   are `any_of` literals, else `verify` accepts position 0, when it is set
/// - with `within` set, "appears" means inside that many leading bytes
///
/// With `ascii_case_insensitive` set, every literal matches with ASCII case
/// folded. A signature with no literal at all can't rule a span out. It
/// always fires alone and never fires in a [`SignatureSet`].
#[derive(Debug, Clone)]
pub struct Signature {
    anchored: Vec<Box<[u8]>>,
    all_of: Vec<Needle>,
    any_of: Vec<Needle>,
    verify: Option<Verify>,
    within: Option<usize>,
    folded: bool,
    verify_cap: Option<u8>,
    every_hit: bool,
    specificity: Specificity,
    priority: u8,
}

/// Builds a [`Signature`].
#[derive(Debug, Clone)]
pub struct SignatureBuilder {
    anchored: Vec<Box<[u8]>>,
    all_of: Vec<Box<[u8]>>,
    any_of: Vec<Box<[u8]>>,
    verify: Option<Verify>,
    within: Option<usize>,
    folded: bool,
    verify_cap: Option<u8>,
    every_hit: bool,
    specificity: Specificity,
    priority: u8,
}

impl Default for SignatureBuilder {
    fn default() -> Self {
        Self {
            anchored: Vec::new(),
            all_of: Vec::new(),
            any_of: Vec::new(),
            verify: None,
            within: None,
            folded: false,
            verify_cap: Some(MAX_VERIFY),
            every_hit: false,
            specificity: Specificity::default(),
            priority: 0,
        }
    }
}

impl SignatureBuilder {
    /// Literals one of which must start the span: `CEF:`, `LEEF:`.
    #[must_use]
    pub fn anchored<I, L>(mut self, literals: I) -> Self
    where
        I: IntoIterator<Item = L>,
        L: AsRef<[u8]>,
    {
        self.anchored
            .extend(literals.into_iter().map(|l| l.as_ref().into()));
        self
    }

    /// Literals that must all appear somewhere in the span.
    #[must_use]
    pub fn all_of<I, L>(mut self, literals: I) -> Self
    where
        I: IntoIterator<Item = L>,
        L: AsRef<[u8]>,
    {
        self.all_of
            .extend(literals.into_iter().map(|l| l.as_ref().into()));
        self
    }

    /// Literals at least one of which must appear, at a position `verify` accepts.
    #[must_use]
    pub fn any_of<I, L>(mut self, literals: I) -> Self
    where
        I: IntoIterator<Item = L>,
        L: AsRef<[u8]>,
    {
        self.any_of
            .extend(literals.into_iter().map(|l| l.as_ref().into()));
        self
    }

    /// Checked at each `any_of` hit, or at position 0 when there are none.
    #[must_use]
    pub const fn verify(mut self, verify: Verify) -> Self {
        self.verify = Some(verify);
        self
    }

    /// The `all_of` and `any_of` literals must lie in the first `bytes` of the
    /// span, for a marker that only ever sits in a header. A set then reads no
    /// further into a span no other signature needs.
    #[must_use]
    pub const fn within(mut self, bytes: usize) -> Self {
        self.within = Some(bytes);
        self
    }

    /// Every literal, anchored ones included, matches with ASCII case folded,
    /// so `build` finds `Build` and `BUILD`. Other bytes match as given, as
    /// `StrMatcherBuilder::ascii_case_insensitive` reads them.
    #[must_use]
    pub const fn ascii_case_insensitive(mut self, enabled: bool) -> Self {
        self.folded = enabled;
        self
    }

    /// Most `verify` calls the signature makes on a span before an `any_of`
    /// hit fires it unasked, or `None` to ask at every hit, so it fires only
    /// where `verify` accepts. Default `Some(MAX_VERIFY)`.
    #[must_use]
    pub const fn verify_cap(mut self, cap: Option<u8>) -> Self {
        self.verify_cap = cap;
        self
    }

    /// In a [`SignatureSet`], report every `any_of` hit that fires the
    /// signature, each with its span and offset, rather than the first, for a
    /// caller that reads on from each hit, such as a header after every
    /// `CEF:`. The hits come in span and offset order, one a position. Off by
    /// default. It changes nothing for a signature with no `any_of` literal,
    /// or for [`Signature::may_match`].
    #[must_use]
    pub const fn every_hit(mut self, enabled: bool) -> Self {
        self.every_hit = enabled;
        self
    }

    /// Specific (the default) or Generic.
    #[must_use]
    pub const fn specificity(mut self, specificity: Specificity) -> Self {
        self.specificity = specificity;
        self
    }

    /// Higher wins among signatures of the same specificity. Default 0.
    #[must_use]
    pub const fn priority(mut self, priority: u8) -> Self {
        self.priority = priority;
        self
    }

    /// Build the signature.
    ///
    /// # Errors
    ///
    /// [`SignatureError::EmptyLiteral`] for an empty literal, and
    /// [`SignatureError::TooManyAllOf`] past [`MAX_ALL_OF`].
    pub fn build(self) -> Result<Signature, SignatureError> {
        let all = [&self.anchored, &self.all_of, &self.any_of];
        if all.iter().any(|lits| lits.iter().any(|l| l.is_empty())) {
            return Err(SignatureError::EmptyLiteral);
        }
        if self.all_of.len() > MAX_ALL_OF {
            return Err(SignatureError::TooManyAllOf {
                got: self.all_of.len(),
                max: MAX_ALL_OF,
            });
        }
        let folded = self.folded;
        // One case for every folded literal, so a set finds each spelling once.
        let lower = |lits: Vec<Box<[u8]>>| -> Vec<Box<[u8]>> {
            if folded {
                lits.iter().map(|l| l.to_ascii_lowercase().into()).collect()
            } else {
                lits
            }
        };
        let needles = |lits: Vec<Box<[u8]>>| -> Vec<Needle> {
            lower(lits).iter().map(|l| Needle::new(l, folded)).collect()
        };
        Ok(Signature {
            anchored: lower(self.anchored),
            all_of: needles(self.all_of),
            any_of: needles(self.any_of),
            verify: self.verify,
            within: self.within,
            folded,
            verify_cap: self.verify_cap,
            every_hit: self.every_hit,
            specificity: self.specificity,
            priority: self.priority,
        })
    }
}

impl Signature {
    /// Start a builder.
    #[must_use]
    pub fn builder() -> SignatureBuilder {
        SignatureBuilder::default()
    }

    /// `true` when no literal can rule a span out, so the signature has no
    /// fast exit and is never identified in a set.
    #[must_use]
    pub const fn is_literal_free(&self) -> bool {
        self.anchored.is_empty() && self.all_of.is_empty() && self.any_of.is_empty()
    }

    /// Specific or Generic.
    #[must_use]
    pub const fn specificity(&self) -> Specificity {
        self.specificity
    }

    /// Tie-break priority within a specificity.
    #[must_use]
    pub const fn priority(&self) -> u8 {
        self.priority
    }

    /// What [`Self::may_match`] costs, from the table's `literal` and `memmem`
    /// rows: a compare for the anchored literals and a search for each other
    /// literal, every one counted, as on a line that holds them all. `None`
    /// when the table lacks a row.
    #[must_use]
    pub fn cost(&self) -> Option<crate::cost::Cost> {
        use crate::cost::{Cost, Line, of};
        let (literal, memmem) = (of("literal")?, of("memmem")?);
        #[allow(
            clippy::cast_precision_loss,
            reason = "a signature holds far fewer than 2^24 literals"
        )]
        let searches = (self.all_of.len() + self.any_of.len()) as f32;
        let compares: f32 = if self.anchored.is_empty() { 0.0 } else { 1.0 };
        let line = |l: Line, s: Line| Line {
            fixed_ns: compares.mul_add(l.fixed_ns, searches * s.fixed_ns),
            ns_per_byte: searches * s.ns_per_byte,
        };
        Some(Cost {
            hit: line(literal.hit, memmem.hit),
            miss: line(literal.miss, memmem.miss),
        })
    }

    /// `true` when `span` starts with one of the anchored literals, the
    /// marker a format such as CEF opens with, whatever follows it.
    #[must_use]
    pub fn marks(&self, span: &[u8]) -> bool {
        self.anchored
            .iter()
            .any(|a| starts_with(span, a, self.folded))
    }

    /// `false` only when `span` can't be this signature's.
    #[must_use]
    pub fn may_match(&self, span: &[u8]) -> bool {
        (self.anchored.is_empty()
            || self
                .anchored
                .iter()
                .any(|a| starts_with(span, a, self.folded)))
            && self.searched(span).is_some()
    }

    /// Every rule but the anchor: the start of the `any_of` hit that fires
    /// the signature, 0 when it has none, or `None` when a rule fails.
    fn searched(&self, span: &[u8]) -> Option<usize> {
        let head = self.within.map_or(span, |n| &span[..span.len().min(n)]);
        if !self.all_of.iter().all(|f| f.find(head).is_some()) {
            return None;
        }
        if self.any_of.is_empty() {
            return self.verify.is_none_or(|v| v(span, 0)).then_some(0);
        }
        let Some(verify) = self.verify else {
            return self.any_of.iter().find_map(|f| f.find(head));
        };
        let mut calls = 0_u8;
        for f in &self.any_of {
            let mut from = 0;
            // Every occurrence, overlapping ones included, as a set finds them.
            while let Some(at) = f.find(&head[from..]).map(|i| from + i) {
                if Some(calls) == self.verify_cap || verify(span, at) {
                    return Some(at);
                }
                calls = calls.saturating_add(1);
                from = at + 1;
            }
        }
        None
    }

    /// Literals a search for this signature looks for.
    const fn searched_len(&self) -> usize {
        self.all_of.len() + self.any_of.len()
    }
}

/// The most literals, and the largest table, a set's automaton takes as a
/// DFA: it reads a byte in one step where the default takes several.
const DFA_LITERALS: usize = 1_024;
const DFA_BYTES: usize = 1 << 20;

/// With this many searched literals or fewer still possible on a span, a set
/// searches for each one itself: a few SIMD searches cost less than one pass
/// of the automaton over the span.
const DIRECT_LITERALS: usize = 8;

/// How one literal counts toward one signature, with what the scan needs of
/// the signature packed beside it so a hit reads one array.
#[derive(Debug, Clone, Copy)]
struct Use {
    sig: u32,
    /// The signature's `all_of` literals, plus one for an `any_of` hit when
    /// it has `any_of` literals.
    need: u8,
    /// [`ANY_OF`], or which of the signature's `all_of` literals this is.
    slot: u8,
    /// The signature has `within`.
    bounded: bool,
    /// The signature has anchored literals.
    anchored: bool,
}

/// [`Use::slot`] for an `any_of` literal: past every `all_of` index.
const ANY_OF: u8 = u8::MAX;

/// The uses of one literal: those in `start..every` count at its first hit
/// on a span, and those in `every..end`, `any_of` uses with a `verify`, at
/// each hit.
#[derive(Debug, Clone, Copy)]
struct Uses {
    start: usize,
    every: usize,
    end: usize,
}

#[derive(Debug, Clone)]
struct Meta {
    verify: Option<Verify>,
    specificity: Specificity,
    priority: u8,
    has_any_of: bool,
    folded: bool,
    verify_cap: Option<u8>,
    /// Report each `any_of` hit, from [`SignatureScratch::hits`].
    every_hit: bool,
    /// [`Use::need`].
    need: u8,
    /// Where this signature's searched literals must end by.
    within: usize,
    /// How far a scan must read for this signature once it is live: 0 with
    /// no searched literal.
    reach: usize,
}

/// One signature's progress through the span a scan is on. Any other
/// `epoch` means it is untouched there, and for a signature with an anchor,
/// that the span doesn't start with one.
#[derive(Debug, Clone, Copy, Default)]
struct Live {
    epoch: u32,
    /// Conditions met, toward [`Use::need`].
    met: u8,
    /// Verify calls that said no.
    refused: u8,
    triggered: bool,
}

/// One signature's marks on the span a several-span scan is on, each holding
/// the span epoch it was set on.
#[derive(Debug, Clone, Copy, Default)]
struct SpanMarks {
    /// The span starts with one of the signature's anchors.
    anchored: u32,
    /// `refused` counts this span's verify calls.
    verified: u32,
    refused: u8,
}

/// Scratch for [`SignatureSet`] scans, reused across spans so a scan allocates
/// nothing. Build one with [`SignatureSet::scratch`].
#[derive(Debug, Clone)]
pub struct SignatureScratch {
    /// Per signature, for the whole call.
    live: Vec<Live>,
    /// Where each fired signature's triggering hit starts.
    trigger: Vec<usize>,
    /// Which span that hit lies in, for a several-span scan.
    trigger_span: Vec<usize>,
    /// The `all_of` literals counted so far, for a several-span scan.
    all: Vec<u64>,
    /// Per signature, for the span a several-span scan is on.
    marks: Vec<SpanMarks>,
    /// The epoch of the last span each literal was seen on.
    seen: Vec<u32>,
    /// Signatures every searched rule holds for, in the order they got there.
    ready: Vec<u32>,
    /// Signatures the span starts with an anchor of.
    anchored: Vec<u32>,
    /// Each firing `any_of` hit of a signature that reports every hit: the
    /// signature, the span and the offset.
    hits: Vec<(u32, usize, usize)>,
    /// Marks a call: `live`.
    epoch: u32,
    /// Marks a span: `seen` and `marks`.
    span_epoch: u32,
}

impl SignatureScratch {
    /// A mark no earlier call left on `live`.
    fn next_epoch(&mut self) -> u32 {
        self.epoch = self.epoch.wrapping_add(1);
        if self.epoch == 0 {
            self.live.fill(Live::default());
            self.epoch = 1;
        }
        self.epoch
    }

    /// A mark no earlier span left on `seen` or `marks`.
    fn next_span_epoch(&mut self) -> u32 {
        self.span_epoch = self.span_epoch.wrapping_add(1);
        if self.span_epoch == 0 {
            self.seen.fill(0);
            self.marks.fill(SpanMarks::default());
            self.span_epoch = 1;
        }
        self.span_epoch
    }
}

/// A signature that fired: its index in the set's input order, and where its
/// triggering `any_of` literal starts (0 when it has none).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct SignatureMatch {
    /// Position in the set's input order.
    pub index: usize,
    /// Start of an `any_of` hit that fired it: one `verify` accepted, or the
    /// one past [`MAX_VERIFY`] refusals. 0 with no `any_of` literal.
    pub at: usize,
    /// The span `at` is in, from [`SignatureSet::for_each_match_spans`]. With
    /// no `any_of` literal, the first span the signature reads where `verify`,
    /// when set, accepts position 0. Always 0 from a one-span call.
    pub span: usize,
}

/// Many signatures matched in one overlapping pass.
///
/// A span's start is tested against the anchored literals first. Every other
/// distinct literal goes into one `MatchKind::Standard` automaton, so a
/// literal shared by many signatures is found once and nested literals are
/// all reported. Each literal's signatures are visited at its first hit on a
/// span, and again only for an `any_of` literal with a `verify`. Folded
/// signatures' literals go into a second automaton that folds ASCII case. An
/// automaton runs only for the signatures still possible, and no further than
/// they need. When those hold only a few literals between them, each is
/// searched for on its own instead.
#[derive(Debug, Clone)]
pub struct SignatureSet {
    /// The searched literals of exact signatures, then of folded ones.
    /// Anchored ones are tested by `anchors`.
    automata: [Option<AhoCorasick>; 2],
    /// The folded automaton's literal 0 is this one in `spans`.
    folded_base: usize,
    uses: Vec<Use>,
    /// Each literal's run of `uses`.
    spans: Vec<Uses>,
    metas: Vec<Meta>,
    /// Anchored literals, their signature and whether it folds, by the
    /// literal's first byte in either case.
    anchors: Vec<Vec<(Box<[u8]>, u32, bool)>>,
    /// How far each automaton must read for the signatures that need no anchor.
    free_reach: [usize; 2],
    /// The signatures, for searching one on its own.
    sigs: Vec<Signature>,
    /// Signatures with searched literals and no anchor: possible on any span.
    free: Vec<u32>,
    /// Searched literals across `free`.
    free_literals: usize,
    /// The shortest span a signature in `free` can fire on.
    free_min: usize,
    /// Signatures with an anchor.
    anchored: usize,
    /// A signature reports every hit, which only the automaton walk gives.
    every_hit: bool,
}

/// Each literal's uses as the build collects them, per automaton.
#[derive(Default)]
struct Literals<'a> {
    ids: HashMap<&'a [u8], usize>,
    bytes: Vec<&'a [u8]>,
    once: Vec<Vec<Use>>,
    every: Vec<Vec<Use>>,
}

impl<'a> Literals<'a> {
    fn add(&mut self, literal: &'a [u8], each_hit: bool, u: Use) {
        let id = *self.ids.entry(literal).or_insert_with(|| {
            self.bytes.push(literal);
            self.once.push(Vec::new());
            self.every.push(Vec::new());
            self.bytes.len() - 1
        });
        if each_hit {
            self.every[id].push(u);
        } else {
            self.once[id].push(u);
        }
    }

    fn automaton(&self, folded: bool) -> Result<Option<AhoCorasick>, SignatureError> {
        if self.bytes.is_empty() {
            return Ok(None);
        }
        let build = |kind| {
            AhoCorasick::builder()
                .match_kind(MatchKind::Standard)
                .ascii_case_insensitive(folded)
                .kind(kind)
                .build(&self.bytes)
                .map_err(automaton_error)
        };
        // aho-corasick picks its DFA for 100 literals or fewer. A larger
        // set takes it too while the table stays small.
        let dfa = (self.bytes.len() <= DFA_LITERALS)
            .then(|| build(Some(AhoCorasickKind::DFA)))
            .transpose()?
            .filter(|ac| ac.memory_usage() <= DFA_BYTES);
        Ok(Some(match dfa {
            Some(ac) => ac,
            None => build(None)?,
        }))
    }
}

impl SignatureSet {
    /// Build a set. Indices in [`SignatureMatch`] follow `signatures`' order.
    ///
    /// # Errors
    ///
    /// [`SignatureError::Automaton`] when the automaton refuses the literals.
    pub fn new<'a, I>(signatures: I) -> Result<Self, SignatureError>
    where
        I: IntoIterator<Item = &'a Signature>,
    {
        let mut literals: [Literals<'a>; 2] = [Literals::default(), Literals::default()];
        let mut metas = Vec::new();
        let mut anchors: Vec<Vec<(Box<[u8]>, u32, bool)>> = vec![Vec::new(); 256];
        let mut free_reach = [0_usize; 2];
        let mut sigs = Vec::new();
        let mut free = Vec::new();
        let mut free_literals = 0_usize;
        let mut free_min = usize::MAX;
        let mut anchored = 0_usize;
        let mut every_hit = false;
        for (i, sig) in signatures.into_iter().enumerate() {
            let index = u32::try_from(i).map_err(|_| SignatureError::TooMany {
                max: u32::MAX as usize,
            })?;
            for a in &sig.anchored {
                let Some(&first) = a.first() else { continue };
                // A folded literal is held in lower case and filed under both.
                let upper = first.to_ascii_uppercase();
                let other = (sig.folded && upper != first).then_some(upper);
                for b in std::iter::once(first).chain(other) {
                    anchors[usize::from(b)].push((a.clone(), index, sig.folded));
                }
            }
            let has_any_of = !sig.any_of.is_empty();
            let need = u8::try_from(sig.all_of.len() + usize::from(has_any_of)).map_err(|_| {
                SignatureError::TooManyAllOf {
                    got: sig.all_of.len(),
                    max: MAX_ALL_OF,
                }
            })?;
            let use_ = |slot| Use {
                sig: index,
                need,
                slot,
                bounded: sig.within.is_some(),
                anchored: !sig.anchored.is_empty(),
            };
            let lits = &mut literals[usize::from(sig.folded)];
            // `build` holds all_of to MAX_ALL_OF, so each index fits a u64 bit.
            for (slot, f) in (0_u8..).zip(&sig.all_of) {
                lits.add(f.bytes(), false, use_(slot));
            }
            let every = sig.every_hit && !sig.any_of.is_empty();
            every_hit |= every;
            for f in &sig.any_of {
                lits.add(f.bytes(), sig.verify.is_some() || every, use_(ANY_OF));
            }
            let within = sig.within.unwrap_or(usize::MAX);
            let searched = sig.searched_len() > 0;
            let reach = if searched { within } else { 0 };
            if sig.anchored.is_empty() {
                let k = usize::from(sig.folded);
                free_reach[k] = free_reach[k].max(reach);
                if searched {
                    free.push(index);
                    free_literals += sig.searched_len();
                    let longest_needed = sig.all_of.iter().map(|f| f.bytes().len()).max();
                    let shortest_any = sig.any_of.iter().map(|f| f.bytes().len()).min();
                    let least = longest_needed.unwrap_or(0).max(shortest_any.unwrap_or(0));
                    free_min = free_min.min(least);
                }
            } else {
                anchored += 1;
            }
            sigs.push(sig.clone());
            metas.push(Meta {
                verify: sig.verify,
                specificity: sig.specificity,
                priority: sig.priority,
                has_any_of,
                folded: sig.folded,
                verify_cap: sig.verify_cap,
                every_hit: every,
                need,
                within,
                reach,
            });
        }
        let automata = [literals[0].automaton(false)?, literals[1].automaton(true)?];
        let folded_base = literals[0].bytes.len();
        let mut uses = Vec::new();
        let mut spans = Vec::new();
        for lits in literals {
            for (once, every) in lits.once.into_iter().zip(lits.every) {
                let start = uses.len();
                uses.extend(once);
                let split = uses.len();
                uses.extend(every);
                spans.push(Uses {
                    start,
                    every: split,
                    end: uses.len(),
                });
            }
        }
        Ok(Self {
            automata,
            folded_base,
            uses,
            spans,
            metas,
            anchors,
            free_reach,
            sigs,
            free,
            free_literals,
            free_min,
            anchored,
            every_hit,
        })
    }

    /// `false` only when no signature in the set can fire on `span`: it
    /// starts with no anchored literal, and it is shorter than every
    /// unanchored signature's literals. A table lookup and the few literals
    /// under its first byte, for ruling a short value out before a scan.
    #[must_use]
    pub fn could_fire(&self, span: &[u8]) -> bool {
        span.len() >= self.free_min
            || span.first().is_some_and(|&first| {
                self.anchors[usize::from(first)]
                    .iter()
                    .any(|(literal, _, folded)| starts_with(span, literal, *folded))
            })
    }

    /// Number of signatures in the set.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.metas.len()
    }

    /// `true` when the set holds no signature.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.metas.is_empty()
    }

    /// Scratch sized for this set.
    #[must_use]
    pub fn scratch(&self) -> SignatureScratch {
        let n = self.metas.len();
        SignatureScratch {
            live: vec![Live::default(); n],
            trigger: vec![0; n],
            trigger_span: vec![0; n],
            all: vec![0; n],
            marks: vec![SpanMarks::default(); n],
            seen: vec![0; self.spans.len()],
            ready: Vec::with_capacity(n),
            anchored: Vec::with_capacity(self.anchored),
            hits: Vec::new(),
            epoch: 0,
            span_epoch: 0,
        }
    }

    /// `scratch` was sized for a set with this many signatures and literals.
    const fn fits(&self, scratch: &SignatureScratch) -> bool {
        scratch.live.len() == self.metas.len()
            && scratch.marks.len() == self.metas.len()
            && scratch.seen.len() == self.spans.len()
    }

    /// Call `f` for every signature that fires on `span`, in input order.
    ///
    /// Each signature fires here exactly when [`Signature::may_match`] says so,
    /// except a literal-free one, which never fires in a set.
    pub fn for_each_match(
        &self,
        span: &[u8],
        scratch: &mut SignatureScratch,
        mut f: impl FnMut(SignatureMatch),
    ) {
        if !self.fits(scratch) {
            *scratch = self.scratch();
        }
        // Emptied here as well as at the end, for a scan `f` panicked out of.
        scratch.ready.clear();
        scratch.anchored.clear();
        scratch.hits.clear();
        let epoch = scratch.next_epoch();
        let span_epoch = scratch.next_span_epoch();
        let mut reach = self.free_reach;
        let mut literals = self.free_literals;
        if let Some(&first) = span.first() {
            for (literal, sig, folded) in &self.anchors[usize::from(first)] {
                let i = *sig as usize;
                let live = &mut scratch.live[i];
                // A second anchor of one signature adds nothing.
                if live.epoch == epoch || !starts_with(span, literal, *folded) {
                    continue;
                }
                *live = Live {
                    epoch,
                    ..Live::default()
                };
                scratch.anchored.push(*sig);
                literals += self.sigs[i].searched_len();
                let m = &self.metas[i];
                let k = usize::from(m.folded);
                reach[k] = reach[k].max(m.reach);
            }
        }
        let direct = literals <= DIRECT_LITERALS && !self.every_hit;
        if direct {
            // The anchored ones touched above, then the ones that need none.
            for &sig in scratch.anchored.iter().chain(&self.free) {
                let i = sig as usize;
                if let Some(at) = self.sigs[i].searched(span) {
                    scratch.trigger[i] = at;
                    scratch.ready.push(sig);
                }
            }
        } else {
            for &sig in &scratch.anchored {
                if self.metas[sig as usize].need == 0 {
                    scratch.ready.push(sig);
                }
            }
            let bases = [0, self.folded_base];
            for (k, ac) in self.automata.iter().enumerate() {
                let Some(ac) = ac else { continue };
                if reach[k] == 0 {
                    continue;
                }
                let head = &span[..span.len().min(reach[k])];
                for hit in ac.find_overlapping_iter(head) {
                    let id = bases[k] + hit.pattern().as_usize();
                    let hit = (id, hit.start(), hit.end());
                    self.visit::<false>(span, 0, hit, (epoch, span_epoch), scratch);
                }
            }
        }
        scratch.ready.sort_unstable();
        prepare_hits(&mut scratch.hits);
        let mut hits = 0;
        for &sig in &scratch.ready {
            let i = sig as usize;
            let m = &self.metas[i];
            if m.every_hit {
                report_hits(&scratch.hits, &mut hits, sig, &mut f);
                continue;
            }
            let at = if direct || m.has_any_of {
                Some(scratch.trigger[i])
            } else {
                m.verify.is_none_or(|v| v(span, 0)).then_some(0)
            };
            if let Some(at) = at {
                f(SignatureMatch {
                    index: i,
                    at,
                    span: 0,
                });
            }
        }
        scratch.ready.clear();
        scratch.anchored.clear();
        scratch.hits.clear();
    }

    /// Call `f` for every signature that fires over `spans` taken together, in
    /// input order: the parts of one record, such as a message body and its
    /// header fields.
    ///
    /// A signature reads every span, or with anchors, the spans that start
    /// with one. Across the spans it reads, each `all_of` literal may lie in a
    /// different span, an `any_of` hit is verified in its own span, and
    /// `within` and [`MAX_VERIFY`] hold per span. With no `any_of` literal,
    /// `verify` is called at position 0 of each span it reads until one
    /// accepts. A signature that reports every hit gives each in span order.
    /// One span gives exactly [`Self::for_each_match`]. Two or more are each
    /// read by the automaton, without the direct search a set of few literals
    /// makes on one span.
    pub fn for_each_match_spans(
        &self,
        spans: &[&[u8]],
        scratch: &mut SignatureScratch,
        mut f: impl FnMut(SignatureMatch),
    ) {
        if let [span] = spans {
            return self.for_each_match(span, scratch, f);
        }
        if !self.fits(scratch) {
            *scratch = self.scratch();
        }
        scratch.ready.clear();
        scratch.hits.clear();
        let epoch = scratch.next_epoch();
        let bases = [0, self.folded_base];
        for (s, span) in spans.iter().enumerate() {
            let span_epoch = scratch.next_span_epoch();
            let mut reach = self.free_reach;
            if let Some(&first) = span.first() {
                for (literal, sig, folded) in &self.anchors[usize::from(first)] {
                    let i = *sig as usize;
                    let marks = &mut scratch.marks[i];
                    if marks.anchored == span_epoch || !starts_with(span, literal, *folded) {
                        continue;
                    }
                    marks.anchored = span_epoch;
                    let m = &self.metas[i];
                    let k = usize::from(m.folded);
                    reach[k] = reach[k].max(m.reach);
                    let live = &mut scratch.live[i];
                    if live.epoch != epoch {
                        *live = Live {
                            epoch,
                            ..Live::default()
                        };
                        scratch.all[i] = 0;
                        if m.need == 0 {
                            scratch.ready.push(*sig);
                        }
                    }
                }
            }
            for (k, ac) in self.automata.iter().enumerate() {
                let Some(ac) = ac else { continue };
                if reach[k] == 0 {
                    continue;
                }
                let head = &span[..span.len().min(reach[k])];
                for hit in ac.find_overlapping_iter(head) {
                    let id = bases[k] + hit.pattern().as_usize();
                    let hit = (id, hit.start(), hit.end());
                    self.visit::<true>(span, s, hit, (epoch, span_epoch), scratch);
                }
            }
        }
        scratch.ready.sort_unstable();
        prepare_hits(&mut scratch.hits);
        let mut hits = 0;
        for &sig in &scratch.ready {
            let i = sig as usize;
            let m = &self.metas[i];
            if m.every_hit {
                report_hits(&scratch.hits, &mut hits, sig, &mut f);
                continue;
            }
            let fired = if m.has_any_of {
                Some((scratch.trigger_span[i], scratch.trigger[i]))
            } else {
                let sig = &self.sigs[i];
                spans
                    .iter()
                    .position(|span| {
                        (sig.anchored.is_empty()
                            || sig.anchored.iter().any(|a| starts_with(span, a, m.folded)))
                            && m.verify.is_none_or(|v| v(span, 0))
                    })
                    .map(|s| (s, 0))
            };
            if let Some((span, at)) = fired {
                f(SignatureMatch { index: i, at, span });
            }
        }
        scratch.ready.clear();
        scratch.hits.clear();
    }

    /// Count one hit of literal `id`, from `start` to `end`, toward each
    /// signature that uses it: all of them on its first hit in the span, then
    /// only the verified `any_of` ones. Overlapping search reports hits in
    /// order of their end, so a later hit of a counted literal ends further in
    /// and changes nothing else, `within` included.
    ///
    /// `POOLED` is a scan of span `s` of several: a signature's `live` lasts
    /// the call, so its `all_of` bitmask stops a literal counting twice and
    /// its anchor and verify cap are read from this span's marks.
    fn visit<const POOLED: bool>(
        &self,
        span: &[u8],
        s: usize,
        (id, start, end): (usize, usize, usize),
        (epoch, span_epoch): (u32, u32),
        scratch: &mut SignatureScratch,
    ) {
        let run = self.spans[id];
        let from = if scratch.seen[id] == span_epoch {
            run.every
        } else {
            scratch.seen[id] = span_epoch;
            run.start
        };
        for (k, u) in self.uses[from..run.end].iter().enumerate() {
            let i = u.sig as usize;
            if u.bounded && end > self.metas[i].within {
                continue;
            }
            if POOLED && u.anchored && scratch.marks[i].anchored != span_epoch {
                continue;
            }
            let live = &mut scratch.live[i];
            if live.epoch != epoch {
                if u.anchored {
                    continue;
                }
                *live = Live {
                    epoch,
                    ..Live::default()
                };
                if POOLED {
                    scratch.all[i] = 0;
                }
            }
            if u.slot == ANY_OF {
                let m = &self.metas[i];
                if live.triggered && !m.every_hit {
                    continue;
                }
                if from + k >= run.every {
                    let refused = if POOLED {
                        let marks = &mut scratch.marks[i];
                        if marks.verified != span_epoch {
                            marks.verified = span_epoch;
                            marks.refused = 0;
                        }
                        &mut marks.refused
                    } else {
                        &mut live.refused
                    };
                    let asks = m.verify_cap.is_none_or(|cap| *refused < cap);
                    if asks && !m.verify.is_none_or(|v| v(span, start)) {
                        *refused = refused.saturating_add(1);
                        continue;
                    }
                }
                if m.every_hit {
                    scratch.hits.push((u.sig, s, start));
                    if live.triggered {
                        continue;
                    }
                }
                live.triggered = true;
                scratch.trigger[i] = start;
                if POOLED {
                    scratch.trigger_span[i] = s;
                }
            } else if POOLED {
                let bit = 1_u64 << u.slot;
                if scratch.all[i] & bit != 0 {
                    continue;
                }
                scratch.all[i] |= bit;
            }
            live.met += 1;
            if live.met == u.need {
                scratch.ready.push(u.sig);
            }
        }
    }

    /// Keep `m` in `best` when it beats it: Specific over Generic, then the
    /// higher priority. A later index never wins a tie.
    fn keep_best(&self, best: &mut Option<SignatureMatch>, m: SignatureMatch) {
        let key = |m: SignatureMatch| {
            (
                self.metas[m.index].specificity,
                self.metas[m.index].priority,
            )
        };
        if best.is_none_or(|b| key(m) > key(b)) {
            *best = Some(m);
        }
    }

    /// The winning signature on `span`: Specific beats Generic, then the higher
    /// priority, then the earlier index.
    #[must_use]
    pub fn best(&self, span: &[u8], scratch: &mut SignatureScratch) -> Option<SignatureMatch> {
        let mut best: Option<SignatureMatch> = None;
        self.for_each_match(span, scratch, |m| self.keep_best(&mut best, m));
        best
    }

    /// The winning signature over `spans` taken together, as
    /// [`Self::for_each_match_spans`] fires them and [`Self::best`] ranks them.
    #[must_use]
    pub fn best_spans(
        &self,
        spans: &[&[u8]],
        scratch: &mut SignatureScratch,
    ) -> Option<SignatureMatch> {
        let mut best: Option<SignatureMatch> = None;
        self.for_each_match_spans(spans, scratch, |m| self.keep_best(&mut best, m));
        best
    }
}

/// Sort recorded hits by signature, span and offset, one a position.
fn prepare_hits(hits: &mut Vec<(u32, usize, usize)>) {
    hits.sort_unstable();
    hits.dedup();
}

/// Call `f` on each of `sig`'s hits, reading `hits` from `next`, where the
/// hits of the signatures before it in input order end.
fn report_hits(
    hits: &[(u32, usize, usize)],
    next: &mut usize,
    sig: u32,
    f: &mut impl FnMut(SignatureMatch),
) {
    *next += hits[*next..].partition_point(|h| h.0 < sig);
    for &(_, span, at) in hits[*next..].iter().take_while(|h| h.0 == sig) {
        *next += 1;
        f(SignatureMatch {
            index: sig as usize,
            at,
            span,
        });
    }
}

#[cfg(test)]
mod tests;