Skip to main content

silens_scan/
scan_query.rs

1//! Borrowed query view over findings contained in [`ScanResults`](crate::ScanResults).
2
3use std::cmp::Ordering;
4
5use crate::{Confidence, Finding, ScanEntry, ScanSort, Severity};
6
7#[derive(Debug, Copy, Clone)]
8enum QueryConstraint<T> {
9    Exact(T),
10    AtLeast(T),
11}
12
13/// Borrowed query over findings produced by a batch scan.
14///
15/// Queries are lazy and allocation-free until sorting or collection is
16/// explicitly requested.
17#[derive(Debug, Copy, Clone)]
18#[must_use = "queries do nothing until they are iterated, inspected, collected, or sorted"]
19pub struct ScanQuery<'a, K> {
20    entries: &'a [ScanEntry<K>],
21    severity: Option<QueryConstraint<Severity>>,
22    confidence: Option<QueryConstraint<Confidence>>,
23    rule_id: Option<&'a str>,
24}
25
26impl<'a, K> ScanQuery<'a, K> {
27    pub(crate) const fn new(entries: &'a [ScanEntry<K>]) -> Self {
28        Self {
29            entries,
30            severity: None,
31            confidence: None,
32            rule_id: None,
33        }
34    }
35
36    /// Restricts the query to findings with exactly `severity`.
37    ///
38    /// This replaces any previously configured severity constraint.
39    pub const fn severity(mut self, severity: Severity) -> Self {
40        self.severity = Some(QueryConstraint::Exact(severity));
41        self
42    }
43
44    /// Restricts the query to findings whose severity is at least `severity`.
45    ///
46    /// Severity follows its documented natural ordering:
47    /// `Info < Low < Medium < High < Critical`.
48    ///
49    /// This replaces any previously configured severity constraint.
50    pub const fn minimum_severity(mut self, severity: Severity) -> Self {
51        self.severity = Some(QueryConstraint::AtLeast(severity));
52        self
53    }
54
55    /// Restricts the query to findings with exactly `confidence`.
56    ///
57    /// This replaces any previously configured confidence constraint.
58    pub const fn confidence(mut self, confidence: Confidence) -> Self {
59        self.confidence = Some(QueryConstraint::Exact(confidence));
60        self
61    }
62
63    /// Restricts the query to findings whose confidence is at least
64    /// `confidence`.
65    ///
66    /// Confidence follows its documented natural ordering:
67    /// `Low < Medium < High`.
68    ///
69    /// This replaces any previously configured confidence constraint.
70    pub const fn minimum_confidence(mut self, confidence: Confidence) -> Self {
71        self.confidence = Some(QueryConstraint::AtLeast(confidence));
72        self
73    }
74
75    /// Restricts the query to findings produced by the exact rule identifier.
76    ///
77    /// The identifier is borrowed by the query and is compared without
78    /// allocation.
79    pub const fn rule_id(mut self, rule_id: &'a str) -> Self {
80        self.rule_id = Some(rule_id);
81        self
82    }
83
84    /// Restricts the query to critical findings.
85    pub const fn critical(self) -> Self {
86        self.severity(Severity::Critical)
87    }
88
89    /// Restricts the query to high- or critical-severity findings.
90    pub const fn high_priority(self) -> Self {
91        self.minimum_severity(Severity::High)
92    }
93
94    /// Restricts the query to high-confidence findings.
95    pub const fn high_confidence(self) -> Self {
96        self.confidence(Confidence::High)
97    }
98
99    /// Iterates over every finding while retaining its source key.
100    ///
101    /// The iterator is borrowed and allocation-free. Findings are yielded in
102    /// source input order and in each report's deterministic finding order.
103    pub fn iter(&self) -> impl Iterator<Item = (&'a K, &'a Finding)> + '_ {
104        self.entries
105            .iter()
106            .flat_map(|entry| {
107                entry
108                    .report()
109                    .iter()
110                    .map(move |finding| (entry.key(), finding))
111            })
112            .filter(|(_, finding)| self.matches(finding))
113    }
114
115    /// Returns `true` when `finding` satisfies every configured filter.
116    #[must_use]
117    fn matches(&self, finding: &Finding) -> bool {
118        if !matches_constraint(finding.severity(), self.severity) {
119            return false;
120        }
121
122        if !matches_constraint(finding.confidence(), self.confidence) {
123            return false;
124        }
125
126        if let Some(rule_id) = self.rule_id
127            && finding.rule_id().as_str() != rule_id
128        {
129            return false;
130        }
131
132        true
133    }
134
135    /// Materializes and sorts the findings selected by this query.
136    ///
137    /// Filtering remains lazy until this method is called. Sorting allocates a
138    /// vector containing borrowed `(source, finding)` pairs, but it never
139    /// clones source keys or findings and never mutates the underlying
140    /// [`ScanResults`](crate::ScanResults).
141    ///
142    /// Source sorting requires `K: Ord`. The same bound is applied to the
143    /// complete sorting API so one `sort(ScanSort::...)` method can cover every
144    /// supported ordering consistently.
145    pub fn sort(&self, sort: ScanSort) -> SortedScanQuery<'a, K>
146    where
147        K: Ord,
148    {
149        let mut findings = self.collect();
150
151        findings.sort_by(|left, right| compare_findings(*left, *right, sort));
152
153        SortedScanQuery::new(findings)
154    }
155
156    /// Returns the number of findings selected by this query.
157    #[must_use]
158    pub fn count(&self) -> usize {
159        self.iter().count()
160    }
161
162    /// Returns the first finding selected by this query, if any.
163    #[must_use]
164    pub fn first(&self) -> Option<(&'a K, &'a Finding)> {
165        self.iter().next()
166    }
167
168    /// Returns the last finding selected by this query, if any.
169    ///
170    /// The query remains allocation-free. This walks the selected findings to
171    /// completion because the underlying filtered iterator is not required to
172    /// be double-ended.
173    #[must_use]
174    pub fn last(&self) -> Option<(&'a K, &'a Finding)> {
175        self.iter().last()
176    }
177
178    /// Returns `true` when this query selects at least one finding.
179    ///
180    /// Evaluation short-circuits at the first match.
181    #[must_use]
182    pub fn has_matches(&self) -> bool {
183        self.iter().next().is_some()
184    }
185
186    /// Returns `true` when this query selects no findings.
187    ///
188    /// Evaluation short-circuits at the first match.
189    #[must_use]
190    pub fn is_empty(&self) -> bool {
191        !self.has_matches()
192    }
193
194    /// Materializes the selected findings as borrowed `(source, finding)`
195    /// pairs.
196    ///
197    /// Neither source keys nor findings are cloned.
198    #[must_use]
199    pub fn collect(&self) -> Vec<(&'a K, &'a Finding)> {
200        self.iter().collect()
201    }
202}
203
204fn matches_constraint<T>(value: T, constraint: Option<QueryConstraint<T>>) -> bool
205where
206    T: Copy + Ord,
207{
208    match constraint {
209        None => true,
210        Some(QueryConstraint::Exact(expected)) => value == expected,
211        Some(QueryConstraint::AtLeast(minimum)) => value >= minimum,
212    }
213}
214
215/// Materialized, sorted view of findings selected by a [`ScanQuery`].
216///
217/// This type owns only the vector of borrowed `(source, finding)` pairs.
218/// Source keys and findings remain owned by the originating
219/// [`ScanResults`](crate::ScanResults).
220#[derive(Debug, Clone)]
221#[must_use = "sorted queries should be inspected, iterated, or consumed"]
222pub struct SortedScanQuery<'a, K> {
223    findings: Vec<(&'a K, &'a Finding)>,
224}
225
226impl<'a, K> SortedScanQuery<'a, K> {
227    pub(crate) const fn new(findings: Vec<(&'a K, &'a Finding)>) -> Self {
228        Self { findings }
229    }
230
231    /// Returns the number of sorted findings.
232    #[must_use]
233    pub const fn len(&self) -> usize {
234        self.findings.len()
235    }
236
237    /// Returns the number of sorted findings.
238    #[must_use]
239    pub const fn count(&self) -> usize {
240        self.findings.len()
241    }
242
243    /// Returns `true` when the sorted query contains at least one finding.
244    #[must_use]
245    pub const fn has_matches(&self) -> bool {
246        !self.findings.is_empty()
247    }
248
249    /// Returns `true` when the sorted query contains no findings.
250    #[must_use]
251    pub const fn is_empty(&self) -> bool {
252        self.findings.is_empty()
253    }
254
255    /// Iterates over sorted `(source, finding)` pairs.
256    pub fn iter(
257        &self,
258    ) -> impl DoubleEndedIterator<Item = (&'a K, &'a Finding)> + ExactSizeIterator + '_ {
259        self.findings.iter().copied()
260    }
261
262    /// Returns the first sorted finding, if any.
263    #[must_use]
264    pub fn first(&self) -> Option<(&'a K, &'a Finding)> {
265        self.findings.first().copied()
266    }
267
268    /// Returns the last sorted finding, if any.
269    #[must_use]
270    pub fn last(&self) -> Option<(&'a K, &'a Finding)> {
271        self.findings.last().copied()
272    }
273
274    /// Returns the sorted findings as a borrowed slice.
275    #[must_use]
276    pub fn as_slice(&self) -> &[(&'a K, &'a Finding)] {
277        &self.findings
278    }
279
280    /// Returns the sorted borrowed pairs as a new vector.
281    ///
282    /// Only references are copied; source keys and findings are not cloned.
283    #[must_use]
284    pub fn to_vec(&self) -> Vec<(&'a K, &'a Finding)> {
285        self.findings.clone()
286    }
287
288    /// Consumes the sorted query and returns its borrowed pairs without copying
289    /// the vector.
290    #[must_use]
291    pub fn into_vec(self) -> Vec<(&'a K, &'a Finding)> {
292        self.findings
293    }
294}
295
296impl<'a, K> IntoIterator for SortedScanQuery<'a, K> {
297    type Item = (&'a K, &'a Finding);
298    type IntoIter = std::vec::IntoIter<Self::Item>;
299
300    fn into_iter(self) -> Self::IntoIter {
301        self.findings.into_iter()
302    }
303}
304
305impl<'query, 'a, K> IntoIterator for &'query SortedScanQuery<'a, K> {
306    type Item = (&'a K, &'a Finding);
307    type IntoIter = std::iter::Copied<std::slice::Iter<'query, (&'a K, &'a Finding)>>;
308
309    fn into_iter(self) -> Self::IntoIter {
310        self.findings.iter().copied()
311    }
312}
313
314fn compare_findings<K: Ord>(
315    left: (&K, &Finding),
316    right: (&K, &Finding),
317    sort: ScanSort,
318) -> Ordering {
319    let primary = match sort {
320        ScanSort::RuleId => left.1.rule_id().as_str().cmp(right.1.rule_id().as_str()),
321        ScanSort::RuleIdDescending => right.1.rule_id().as_str().cmp(left.1.rule_id().as_str()),
322        ScanSort::Source => left.0.cmp(right.0),
323        ScanSort::SourceDescending => right.0.cmp(left.0),
324        ScanSort::Severity => left.1.severity().cmp(&right.1.severity()),
325        ScanSort::SeverityDescending => right.1.severity().cmp(&left.1.severity()),
326        ScanSort::Confidence => left.1.confidence().cmp(&right.1.confidence()),
327        ScanSort::ConfidenceDescending => right.1.confidence().cmp(&left.1.confidence()),
328        ScanSort::Location => left.1.location().cmp(right.1.location()),
329        ScanSort::LocationDescending => right.1.location().cmp(left.1.location()),
330    };
331
332    if primary != Ordering::Equal {
333        return primary;
334    }
335
336    // Preserve a deterministic total ordering when multiple findings share the
337    // selected sort key. The tie-break chain is intentionally independent from
338    // the chosen direction so repeated queries produce a stable result.
339    left.0
340        .cmp(right.0)
341        .then_with(|| left.1.location().cmp(right.1.location()))
342        .then_with(|| left.1.rule_id().as_str().cmp(right.1.rule_id().as_str()))
343        .then_with(|| left.1.severity().cmp(&right.1.severity()))
344        .then_with(|| left.1.confidence().cmp(&right.1.confidence()))
345}
346
347#[cfg(test)]
348mod tests {
349    use crate::{Confidence, Location, RuleId, ScanEntry, ScanReport, Severity};
350
351    use super::*;
352
353    fn finding(rule: &str, severity: Severity, confidence: Confidence) -> Finding {
354        Finding::new(
355            RuleId::from(rule),
356            Location::from_span(0, 1),
357            severity,
358            confidence,
359            None,
360        )
361    }
362
363    fn report(rule: &str, severity: Severity) -> ScanReport {
364        ScanReport::new(vec![finding(rule, severity, Confidence::High)])
365    }
366
367    #[test]
368    fn iterates_all_findings_without_cloning() {
369        let entries = [
370            ScanEntry::new("a", 1, report("one", Severity::High)),
371            ScanEntry::new("b", 1, report("two", Severity::Medium)),
372        ];
373        let query = ScanQuery::new(&entries);
374
375        let findings = query.collect();
376
377        assert_eq!(findings.len(), 2);
378        assert_eq!(*findings[0].0, "a");
379        assert_eq!(findings[0].1.rule_id().as_str(), "one");
380        assert_eq!(*findings[1].0, "b");
381        assert_eq!(findings[1].1.rule_id().as_str(), "two");
382    }
383
384    #[test]
385    fn exposes_count_and_first_helpers() {
386        let entries = [ScanEntry::new(
387            "source",
388            1,
389            report("rule", Severity::Critical),
390        )];
391        let query = ScanQuery::new(&entries);
392
393        assert_eq!(query.count(), 1);
394
395        let (key, finding) = query.first().expect("one finding should exist");
396        assert_eq!(*key, "source");
397        assert_eq!(finding.rule_id().as_str(), "rule");
398    }
399
400    #[test]
401    fn empty_query_has_no_findings() {
402        let entries: [ScanEntry<&str>; 0] = [];
403        let query = ScanQuery::new(&entries);
404
405        assert_eq!(query.count(), 0);
406        assert!(query.first().is_none());
407        assert!(query.collect().is_empty());
408    }
409    #[test]
410    fn filters_exact_severity() {
411        let entries = [ScanEntry::new(
412            "source",
413            3,
414            ScanReport::new(vec![
415                finding("low", Severity::Low, Confidence::High),
416                finding("high", Severity::High, Confidence::High),
417                finding("critical", Severity::Critical, Confidence::High),
418            ]),
419        )];
420
421        let findings = ScanQuery::new(&entries).severity(Severity::High).collect();
422
423        assert_eq!(findings.len(), 1);
424        assert_eq!(findings[0].1.rule_id().as_str(), "high");
425    }
426
427    #[test]
428    fn filters_minimum_severity() {
429        let entries = [ScanEntry::new(
430            "source",
431            3,
432            ScanReport::new(vec![
433                finding("medium", Severity::Medium, Confidence::High),
434                finding("high", Severity::High, Confidence::High),
435                finding("critical", Severity::Critical, Confidence::High),
436            ]),
437        )];
438
439        let findings = ScanQuery::new(&entries)
440            .minimum_severity(Severity::High)
441            .collect();
442
443        assert_eq!(findings.len(), 2);
444        assert_eq!(findings[0].1.rule_id().as_str(), "high");
445        assert_eq!(findings[1].1.rule_id().as_str(), "critical");
446    }
447
448    #[test]
449    fn filters_confidence_and_minimum_confidence() {
450        let entries = [ScanEntry::new(
451            "source",
452            3,
453            ScanReport::new(vec![
454                finding("low", Severity::High, Confidence::Low),
455                finding("medium", Severity::High, Confidence::Medium),
456                finding("high", Severity::High, Confidence::High),
457            ]),
458        )];
459
460        let exact = ScanQuery::new(&entries)
461            .confidence(Confidence::Medium)
462            .collect();
463        assert_eq!(exact.len(), 1);
464        assert_eq!(exact[0].1.rule_id().as_str(), "medium");
465
466        let minimum = ScanQuery::new(&entries)
467            .minimum_confidence(Confidence::Medium)
468            .collect();
469        assert_eq!(minimum.len(), 2);
470    }
471
472    #[test]
473    fn filters_exact_rule_identifier() {
474        let entries = [ScanEntry::new(
475            "source",
476            2,
477            ScanReport::new(vec![
478                finding("github.token", Severity::Critical, Confidence::High),
479                finding("stripe.secret", Severity::Critical, Confidence::High),
480            ]),
481        )];
482
483        let findings = ScanQuery::new(&entries).rule_id("stripe.secret").collect();
484
485        assert_eq!(findings.len(), 1);
486        assert_eq!(findings[0].1.rule_id().as_str(), "stripe.secret");
487    }
488
489    #[test]
490    fn composes_independent_filters() {
491        let entries = [ScanEntry::new(
492            "source",
493            4,
494            ScanReport::new(vec![
495                finding("target", Severity::High, Confidence::High),
496                finding("target", Severity::High, Confidence::Medium),
497                finding("target", Severity::Medium, Confidence::High),
498                finding("other", Severity::Critical, Confidence::High),
499            ]),
500        )];
501
502        let findings = ScanQuery::new(&entries)
503            .minimum_severity(Severity::High)
504            .minimum_confidence(Confidence::High)
505            .rule_id("target")
506            .collect();
507
508        assert_eq!(findings.len(), 1);
509        assert_eq!(findings[0].1.rule_id().as_str(), "target");
510    }
511
512    #[test]
513    fn exact_and_minimum_filters_replace_each_other() {
514        let entries = [ScanEntry::new(
515            "source",
516            2,
517            ScanReport::new(vec![
518                finding("high", Severity::High, Confidence::High),
519                finding("critical", Severity::Critical, Confidence::High),
520            ]),
521        )];
522
523        let findings = ScanQuery::new(&entries)
524            .severity(Severity::Critical)
525            .minimum_severity(Severity::High)
526            .collect();
527
528        assert_eq!(findings.len(), 2);
529    }
530
531    #[test]
532    fn convenience_filters_match_domain_semantics() {
533        let entries = [ScanEntry::new(
534            "source",
535            3,
536            ScanReport::new(vec![
537                finding("medium", Severity::Medium, Confidence::High),
538                finding("high", Severity::High, Confidence::Medium),
539                finding("critical", Severity::Critical, Confidence::High),
540            ]),
541        )];
542
543        assert_eq!(ScanQuery::new(&entries).critical().count(), 1);
544        assert_eq!(ScanQuery::new(&entries).high_priority().count(), 2);
545        assert_eq!(ScanQuery::new(&entries).high_confidence().count(), 2);
546    }
547
548    #[test]
549    fn sorts_by_rule_identifier_in_both_directions() {
550        let entries = [ScanEntry::new(
551            "source",
552            3,
553            ScanReport::new(vec![
554                finding("zeta", Severity::High, Confidence::High),
555                finding("alpha", Severity::High, Confidence::High),
556                finding("middle", Severity::High, Confidence::High),
557            ]),
558        )];
559
560        let ascending = ScanQuery::new(&entries).sort(ScanSort::RuleId);
561        let descending = ScanQuery::new(&entries).sort(ScanSort::RuleIdDescending);
562
563        assert_eq!(
564            ascending
565                .iter()
566                .map(|(_, finding)| finding.rule_id().as_str())
567                .collect::<Vec<_>>(),
568            ["alpha", "middle", "zeta"],
569        );
570        assert_eq!(
571            descending
572                .iter()
573                .map(|(_, finding)| finding.rule_id().as_str())
574                .collect::<Vec<_>>(),
575            ["zeta", "middle", "alpha"],
576        );
577    }
578
579    #[test]
580    fn sorts_by_source_key() {
581        let entries = [
582            ScanEntry::new("z.env", 1, report("z", Severity::High)),
583            ScanEntry::new("a.env", 1, report("a", Severity::High)),
584            ScanEntry::new("m.env", 1, report("m", Severity::High)),
585        ];
586
587        let sorted = ScanQuery::new(&entries).sort(ScanSort::Source);
588
589        assert_eq!(
590            sorted.iter().map(|(key, _)| *key).collect::<Vec<_>>(),
591            ["a.env", "m.env", "z.env"],
592        );
593    }
594
595    #[test]
596    fn sorts_by_severity_and_confidence() {
597        let entries = [ScanEntry::new(
598            "source",
599            3,
600            ScanReport::new(vec![
601                finding("medium", Severity::Medium, Confidence::Low),
602                finding("critical", Severity::Critical, Confidence::Medium),
603                finding("high", Severity::High, Confidence::High),
604            ]),
605        )];
606
607        let severity = ScanQuery::new(&entries).sort(ScanSort::SeverityDescending);
608        assert_eq!(
609            severity
610                .iter()
611                .map(|(_, finding)| finding.severity())
612                .collect::<Vec<_>>(),
613            [Severity::Critical, Severity::High, Severity::Medium],
614        );
615
616        let confidence = ScanQuery::new(&entries).sort(ScanSort::ConfidenceDescending);
617        assert_eq!(
618            confidence
619                .iter()
620                .map(|(_, finding)| finding.confidence())
621                .collect::<Vec<_>>(),
622            [Confidence::High, Confidence::Medium, Confidence::Low],
623        );
624    }
625
626    #[test]
627    fn sorts_by_location() {
628        let entries = [ScanEntry::new(
629            "source",
630            12,
631            ScanReport::new(vec![
632                Finding::new(
633                    RuleId::from("later"),
634                    Location::from_span(8, 9),
635                    Severity::High,
636                    Confidence::High,
637                    None,
638                ),
639                Finding::new(
640                    RuleId::from("first"),
641                    Location::from_span(1, 2),
642                    Severity::High,
643                    Confidence::High,
644                    None,
645                ),
646            ]),
647        )];
648
649        let sorted = ScanQuery::new(&entries).sort(ScanSort::Location);
650
651        assert_eq!(sorted.first().unwrap().1.location().start(), 1);
652        assert_eq!(sorted.last().unwrap().1.location().start(), 8);
653    }
654
655    #[test]
656    fn sorting_happens_after_lazy_filtering() {
657        let entries = [ScanEntry::new(
658            "source",
659            3,
660            ScanReport::new(vec![
661                finding("zeta", Severity::High, Confidence::High),
662                finding("ignored", Severity::Low, Confidence::High),
663                finding("alpha", Severity::Critical, Confidence::High),
664            ]),
665        )];
666
667        let sorted = ScanQuery::new(&entries)
668            .minimum_severity(Severity::High)
669            .sort(ScanSort::RuleId);
670
671        assert_eq!(sorted.len(), 2);
672        assert_eq!(sorted.first().unwrap().1.rule_id().as_str(), "alpha");
673        assert_eq!(sorted.last().unwrap().1.rule_id().as_str(), "zeta");
674    }
675
676    #[test]
677    fn sorted_query_exposes_owned_vector_of_borrowed_pairs() {
678        let entries = [ScanEntry::new("source", 1, report("rule", Severity::High))];
679
680        let sorted = ScanQuery::new(&entries).sort(ScanSort::RuleId);
681
682        assert!(!sorted.is_empty());
683        assert_eq!(sorted.as_slice().len(), 1);
684
685        let pairs = sorted.into_vec();
686        assert_eq!(pairs.len(), 1);
687        assert_eq!(pairs[0].1.rule_id().as_str(), "rule");
688    }
689
690    #[test]
691    fn lazy_query_helpers_short_circuit_semantically() {
692        let entries = [ScanEntry::new(
693            "source",
694            2,
695            ScanReport::new(vec![
696                finding("first", Severity::High, Confidence::High),
697                finding("last", Severity::Critical, Confidence::High),
698            ]),
699        )];
700
701        let query = ScanQuery::new(&entries).minimum_severity(Severity::High);
702
703        assert!(query.has_matches());
704        assert!(!query.is_empty());
705        assert_eq!(query.first().unwrap().1.rule_id().as_str(), "first");
706        assert_eq!(query.last().unwrap().1.rule_id().as_str(), "last");
707        assert_eq!(query.collect().len(), 2);
708    }
709
710    #[test]
711    fn lazy_query_helpers_handle_no_matches() {
712        let entries = [ScanEntry::new(
713            "source",
714            1,
715            report("medium", Severity::Medium),
716        )];
717
718        let query = ScanQuery::new(&entries).critical();
719
720        assert!(!query.has_matches());
721        assert!(query.is_empty());
722        assert!(query.first().is_none());
723        assert!(query.last().is_none());
724        assert!(query.collect().is_empty());
725    }
726
727    #[test]
728    fn sorted_query_helpers_match_materialized_state() {
729        let entries = [ScanEntry::new(
730            "source",
731            2,
732            ScanReport::new(vec![
733                finding("zeta", Severity::High, Confidence::High),
734                finding("alpha", Severity::Critical, Confidence::High),
735            ]),
736        )];
737
738        let sorted = ScanQuery::new(&entries).sort(ScanSort::RuleId);
739
740        assert_eq!(sorted.len(), 2);
741        assert_eq!(sorted.count(), 2);
742        assert!(sorted.has_matches());
743        assert!(!sorted.is_empty());
744        assert_eq!(sorted.to_vec().len(), 2);
745        assert_eq!(sorted.first().unwrap().1.rule_id().as_str(), "alpha");
746        assert_eq!(sorted.last().unwrap().1.rule_id().as_str(), "zeta");
747    }
748}