libmagic-rs 0.12.5

A pure-Rust implementation of libmagic for file type identification
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
// Copyright (c) 2025-2026 the libmagic-rs contributors
// SPDX-License-Identifier: Apache-2.0

//! Unit tests for [`super`]'s strength calculation.
//!
//! Split out of `strength.rs` to keep the production module inside the
//! project's file-size convention; the calculation itself is ~477 lines
//! while these tests are roughly twice that.

use super::*;
use crate::parser::ast::{
    Endianness, IndirectAdjustmentOp, MetaType, PStringLengthWidth, RegexCount, RegexFlags,
    StringFlags,
};

/// Search strength falls as the scan widens, and a wide scan does not
/// outrank a real numeric detector.
///
/// sgml's `0 search/4096/cwt \<!--` is a 4-byte pattern over a 4096-byte
/// window; `cafebabe`'s Mach-O slice detector is `0 lelong&0xfffffffe
/// 0xfeedface`. With a flat search bonus the former sorted first and
/// mislabeled ~15% of `/usr/bin` Mach-O binaries as SGML (#379).
#[test]
fn search_strength_falls_as_the_scan_range_widens() {
    use crate::parser::ast::{Endianness, OffsetSpec, Operator, TypeKind, Value};
    use std::num::NonZeroUsize;

    fn search_rule(range: usize) -> MagicRule {
        MagicRule::new(
            OffsetSpec::Absolute(0),
            TypeKind::Search {
                range: NonZeroUsize::new(range),
                flags: crate::parser::ast::SearchFlags::default(),
            },
            Operator::Equal,
            Value::String("<!--".to_string()),
            "exported SGML document text".to_string(),
        )
    }

    let long_detector = MagicRule::new(
        OffsetSpec::Absolute(0),
        TypeKind::Long {
            endian: Endianness::Little,
            signed: true,
        },
        Operator::BitwiseAndMask(0xffff_fffe),
        Value::Uint(0xfeed_face),
        "Mach-O".to_string(),
    );
    let long_score = calculate_default_strength(&long_detector);

    // Widening the scan weakens the evidence, so the score must not rise.
    // It saturates rather than falling forever: libmagic's multiplier is
    // `MAX(MULT / range, 1)` with MULT = 10, so any range at or above 10
    // floors to 1 and further widening changes nothing.
    let cases: &[(usize, i32, &str)] = &[
        (4, 32, "tight scan -- multiplier 2"),
        (16, 28, "at the saturation floor -- multiplier 1"),
        (4096, 28, "wide scan, the sgml shape -- still multiplier 1"),
    ];

    let mut previous: Option<i32> = None;
    for &(range, expected, label) in cases {
        let score = calculate_default_strength(&search_rule(range));
        assert_eq!(
            score, expected,
            "{label} (range {range}) scored {score}, expected {expected}"
        );
        if let Some(prev) = previous {
            assert!(
                score <= prev,
                "{label} (range {range}) must not outrank a narrower scan, \
                 got {score} after {prev}"
            );
        }
        previous = Some(score);
    }

    // The actual #379 regression: the sgml shape must lose to the Mach-O
    // detector. A tight scan legitimately ties it, which is why the bar
    // here is the wide case specifically, not every case.
    let wide_score = calculate_default_strength(&search_rule(4096));
    assert!(
        wide_score < long_score,
        "a 4-byte pattern over a 4096-byte window must rank below the long \
         detector, got search={wide_score} long={long_score}"
    );
}

// Helper to create a basic test rule
fn make_rule(typ: TypeKind, op: Operator, offset: OffsetSpec, value: Value) -> MagicRule {
    MagicRule {
        offset,
        typ,
        op,
        value,
        message: "test".to_string(),
        children: vec![],
        level: 0,
        strength_modifier: None,
        value_transform: None,
    }
}

// ============================================================
// Tests for calculate_default_strength
// ============================================================

#[test]
#[allow(clippy::too_many_lines)]
fn test_calculate_default_strength_table() {
    // Table of (rule_factory, expected_strength, description). Each case
    // exercises one strength contribution dimension (type, operator,
    // offset, or value length); the formula is documented in each row.
    type Case = (fn() -> MagicRule, i32, &'static str);
    let cases: &[Case] = &[
        // --- Type contribution (Equal/Absolute/numeric baseline) ---
        (
            || {
                make_rule(
                    TypeKind::Byte { signed: true },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::Uint(0),
                )
            },
            25, // Byte 5 + Equal 10 + Absolute 10 + Numeric 0
            "type=byte",
        ),
        (
            || {
                make_rule(
                    TypeKind::Short {
                        endian: Endianness::Little,
                        signed: false,
                    },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::Uint(0),
                )
            },
            30, // Short 10 + Equal 10 + Absolute 10
            "type=short",
        ),
        (
            || {
                make_rule(
                    TypeKind::Long {
                        endian: Endianness::Big,
                        signed: false,
                    },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::Uint(0),
                )
            },
            35, // Long 15 + Equal 10 + Absolute 10
            "type=long",
        ),
        (
            || {
                make_rule(
                    TypeKind::Quad {
                        endian: Endianness::Little,
                        signed: false,
                    },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::Uint(0),
                )
            },
            36, // Quad 16 + Equal 10 + Absolute 10
            "type=quad",
        ),
        (
            || {
                make_rule(
                    TypeKind::Date {
                        endian: Endianness::Big,
                        utc: true,
                    },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::Uint(0),
                )
            },
            35, // Date 15 + Equal 10 + Absolute 10
            "type=date",
        ),
        (
            || {
                make_rule(
                    TypeKind::QDate {
                        endian: Endianness::Little,
                        utc: false,
                    },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::Uint(0),
                )
            },
            36, // QDate 16 + Equal 10 + Absolute 10
            "type=qdate",
        ),
        (
            || {
                make_rule(
                    TypeKind::String {
                        max_length: None,
                        flags: StringFlags::default(),
                    },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::String("ELF".to_string()),
                )
            },
            43, // String 20 + Equal 10 + Absolute 10 + len(3)
            "type=string len=3",
        ),
        (
            || {
                make_rule(
                    TypeKind::String {
                        max_length: Some(10),
                        flags: StringFlags::default(),
                    },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::String("TEST".to_string()),
                )
            },
            49, // String w/max 25 + Equal 10 + Absolute 10 + len(4)
            "type=string max_length=10",
        ),
        // --- Operator contribution (Byte/Absolute baseline) ---
        (
            || {
                make_rule(
                    TypeKind::Byte { signed: true },
                    Operator::NotEqual,
                    OffsetSpec::Absolute(0),
                    Value::Uint(0),
                )
            },
            20, // Byte 5 + NotEqual 5 + Absolute 10
            "op=not_equal",
        ),
        (
            || {
                make_rule(
                    TypeKind::Byte { signed: true },
                    Operator::BitwiseAnd,
                    OffsetSpec::Absolute(0),
                    Value::Uint(0),
                )
            },
            18, // Byte 5 + BitwiseAnd 3 + Absolute 10
            "op=bitwise_and",
        ),
        (
            || {
                make_rule(
                    TypeKind::Byte { signed: true },
                    Operator::BitwiseAndMask(0xFF),
                    OffsetSpec::Absolute(0),
                    Value::Uint(0),
                )
            },
            22, // Byte 5 + BitwiseAndMask 7 + Absolute 10
            "op=bitwise_and_mask",
        ),
        // Comparison operators (all should give the same strength).
        (
            || {
                make_rule(
                    TypeKind::Byte { signed: true },
                    Operator::LessThan,
                    OffsetSpec::Absolute(0),
                    Value::Uint(0),
                )
            },
            21, // Byte 5 + Comparison 6 + Absolute 10
            "op=less_than",
        ),
        (
            || {
                make_rule(
                    TypeKind::Byte { signed: true },
                    Operator::GreaterThan,
                    OffsetSpec::Absolute(0),
                    Value::Uint(0),
                )
            },
            21,
            "op=greater_than",
        ),
        (
            || {
                make_rule(
                    TypeKind::Byte { signed: true },
                    Operator::LessEqual,
                    OffsetSpec::Absolute(0),
                    Value::Uint(0),
                )
            },
            21,
            "op=less_equal",
        ),
        (
            || {
                make_rule(
                    TypeKind::Byte { signed: true },
                    Operator::GreaterEqual,
                    OffsetSpec::Absolute(0),
                    Value::Uint(0),
                )
            },
            21,
            "op=greater_equal",
        ),
        // --- Offset contribution (Byte/Equal baseline) ---
        (
            || {
                make_rule(
                    TypeKind::Byte { signed: true },
                    Operator::Equal,
                    OffsetSpec::Indirect {
                        base_offset: 0,
                        base_relative: false,
                        pointer_type: TypeKind::Long {
                            endian: Endianness::Little,
                            signed: false,
                        },
                        adjustment: 0,
                        adjustment_op: IndirectAdjustmentOp::Add,
                        result_relative: false,
                        endian: Endianness::Little,
                    },
                    Value::Uint(0),
                )
            },
            20, // Byte 5 + Equal 10 + Indirect 5
            "offset=indirect",
        ),
        (
            || {
                make_rule(
                    TypeKind::Byte { signed: true },
                    Operator::Equal,
                    OffsetSpec::Relative(4),
                    Value::Uint(0),
                )
            },
            18, // Byte 5 + Equal 10 + Relative 3
            "offset=relative",
        ),
        (
            || {
                make_rule(
                    TypeKind::Byte { signed: true },
                    Operator::Equal,
                    OffsetSpec::FromEnd(-4),
                    Value::Uint(0),
                )
            },
            23, // Byte 5 + Equal 10 + FromEnd 8
            "offset=from_end",
        ),
        // --- Value-length contribution ---
        (
            || {
                make_rule(
                    TypeKind::Byte { signed: true },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::Bytes(vec![0x7f, 0x45, 0x4c, 0x46]),
                )
            },
            29, // Byte 5 + Equal 10 + Absolute 10 + bytes len(4)
            "value=bytes len=4",
        ),
        (
            || {
                make_rule(
                    TypeKind::String {
                        max_length: None,
                        flags: StringFlags::default(),
                    },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::String("This is a very long string that exceeds the cap".to_string()),
                )
            },
            60, // String 20 + Equal 10 + Absolute 10 + capped len(20)
            "value=long_string (cap)",
        ),
        // --- Type arms the table previously omitted ---
        // `RegexCount::Default` and `Lines(None)` are behaviorally identical
        // (both scan the full 8192-byte capped window), so they must score
        // the same -- GOTCHAS S2.10. Nothing pinned that before.
        (
            || {
                make_rule(
                    TypeKind::Regex {
                        flags: RegexFlags::default(),
                        count: RegexCount::Default,
                    },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::String("x".to_string()),
                )
            },
            41, // Regex 20 + Equal 10 + Absolute 10 + len("x") 1
            "type=regex count=default",
        ),
        (
            || {
                make_rule(
                    TypeKind::Regex {
                        flags: RegexFlags::default(),
                        count: RegexCount::Lines(None),
                    },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::String("x".to_string()),
                )
            },
            41, // identical to Default by S2.10
            "type=regex count=lines(none)",
        ),
        (
            || {
                make_rule(
                    TypeKind::Regex {
                        flags: RegexFlags::default(),
                        count: RegexCount::Lines(std::num::NonZeroU32::new(3)),
                    },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::String("x".to_string()),
                )
            },
            46, // Regex 25 (explicit count) + Equal 10 + Absolute 10 + len 1
            "type=regex count=lines(3)",
        ),
        (
            || {
                make_rule(
                    TypeKind::Regex {
                        flags: RegexFlags::default(),
                        count: RegexCount::Bytes(
                            std::num::NonZeroU32::new(100).expect("100 is non-zero"),
                        ),
                    },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::String("x".to_string()),
                )
            },
            46, // Regex 25 (explicit count) + Equal 10 + Absolute 10 + len 1
            "type=regex count=bytes(100)",
        ),
        (
            || {
                make_rule(
                    TypeKind::String16 {
                        endian: Endianness::Little,
                    },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::String("x".to_string()),
                )
            },
            41, // String16 20 + Equal 10 + Absolute 10 + len 1
            "type=string16",
        ),
        (
            || {
                make_rule(
                    TypeKind::PString {
                        max_length: None,
                        length_width: PStringLengthWidth::OneByte,
                        length_includes_itself: false,
                    },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::String("x".to_string()),
                )
            },
            41, // PString 20 + Equal 10 + Absolute 10 + len 1
            "type=pstring max_length=none",
        ),
        (
            || {
                make_rule(
                    TypeKind::PString {
                        max_length: Some(8),
                        length_width: PStringLengthWidth::OneByte,
                        length_includes_itself: false,
                    },
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::String("x".to_string()),
                )
            },
            46, // PString 20 + constrained 5 + Equal 10 + Absolute 10 + len 1
            "type=pstring max_length=8",
        ),
        (
            || {
                make_rule(
                    TypeKind::Meta(MetaType::Offset),
                    Operator::Equal,
                    OffsetSpec::Absolute(0),
                    Value::Uint(0),
                )
            },
            20, // Meta 0 + Equal 10 + Absolute 10
            "type=meta(offset)",
        ),
    ];

    for (factory, expected, desc) in cases {
        let rule = factory();
        let strength = calculate_default_strength(&rule);
        assert_eq!(
            strength, *expected,
            "calculate_default_strength mismatch for case '{desc}'"
        );
    }
}

// ============================================================
// Tests for apply_strength_modifier
// ============================================================

#[test]
fn test_apply_modifier_add() {
    assert_eq!(apply_strength_modifier(50, &StrengthModifier::Add(10)), 60);
}

#[test]
fn test_apply_modifier_subtract() {
    assert_eq!(
        apply_strength_modifier(50, &StrengthModifier::Subtract(10)),
        40
    );
}

#[test]
fn test_apply_modifier_multiply() {
    assert_eq!(
        apply_strength_modifier(50, &StrengthModifier::Multiply(2)),
        100
    );
}

#[test]
fn test_apply_modifier_divide() {
    assert_eq!(
        apply_strength_modifier(50, &StrengthModifier::Divide(2)),
        25
    );
}

#[test]
fn test_apply_modifier_set() {
    assert_eq!(apply_strength_modifier(50, &StrengthModifier::Set(75)), 75);
}

#[test]
fn test_apply_modifier_add_overflow() {
    // Should clamp to MAX_STRENGTH
    assert_eq!(
        apply_strength_modifier(250, &StrengthModifier::Add(100)),
        MAX_STRENGTH
    );
}

#[test]
fn test_apply_modifier_subtract_underflow() {
    // Should clamp to MIN_STRENGTH
    assert_eq!(
        apply_strength_modifier(10, &StrengthModifier::Subtract(100)),
        MIN_STRENGTH
    );
}

#[test]
fn test_apply_modifier_multiply_overflow() {
    // Should clamp to MAX_STRENGTH
    assert_eq!(
        apply_strength_modifier(200, &StrengthModifier::Multiply(10)),
        MAX_STRENGTH
    );
}

#[test]
fn test_apply_modifier_divide_by_zero() {
    // Should return base strength unchanged
    assert_eq!(
        apply_strength_modifier(50, &StrengthModifier::Divide(0)),
        50
    );
}

#[test]
fn test_apply_modifier_set_negative() {
    // Should clamp to MIN_STRENGTH
    assert_eq!(
        apply_strength_modifier(50, &StrengthModifier::Set(-10)),
        MIN_STRENGTH
    );
}

#[test]
fn test_apply_modifier_set_over_max() {
    // Should clamp to MAX_STRENGTH
    assert_eq!(
        apply_strength_modifier(50, &StrengthModifier::Set(1000)),
        MAX_STRENGTH
    );
}

// ============================================================
// Tests for calculate_rule_strength
// ============================================================

#[test]
fn test_rule_strength_without_modifier() {
    let rule = make_rule(
        TypeKind::Byte { signed: true },
        Operator::Equal,
        OffsetSpec::Absolute(0),
        Value::Uint(0),
    );
    // Byte: 5, Equal: 10, Absolute: 10, Numeric: 0 = 25
    assert_eq!(calculate_rule_strength(&rule), 25);
}

#[test]
fn test_rule_strength_with_add_modifier() {
    let mut rule = make_rule(
        TypeKind::Byte { signed: true },
        Operator::Equal,
        OffsetSpec::Absolute(0),
        Value::Uint(0),
    );
    rule.strength_modifier = Some(StrengthModifier::Add(20));
    // Base: 25, Add 20 = 45
    assert_eq!(calculate_rule_strength(&rule), 45);
}

#[test]
fn test_rule_strength_with_multiply_modifier() {
    let mut rule = make_rule(
        TypeKind::Byte { signed: true },
        Operator::Equal,
        OffsetSpec::Absolute(0),
        Value::Uint(0),
    );
    rule.strength_modifier = Some(StrengthModifier::Multiply(2));
    // Base: 25, Multiply by 2 = 50
    assert_eq!(calculate_rule_strength(&rule), 50);
}

#[test]
fn test_rule_strength_with_set_modifier() {
    let mut rule = make_rule(
        TypeKind::Byte { signed: true },
        Operator::Equal,
        OffsetSpec::Absolute(0),
        Value::Uint(0),
    );
    rule.strength_modifier = Some(StrengthModifier::Set(100));
    // Set overrides base strength
    assert_eq!(calculate_rule_strength(&rule), 100);
}

// ============================================================
// Tests for sort_rules_by_strength
// ============================================================

#[test]
fn test_sort_rules_by_strength_basic() {
    let mut rules = vec![
        {
            let mut r = make_rule(
                TypeKind::Byte { signed: true },
                Operator::Equal,
                OffsetSpec::Absolute(0),
                Value::Uint(0),
            );
            r.message = "byte rule".to_string();
            r
        },
        {
            let mut r = make_rule(
                TypeKind::String {
                    max_length: None,
                    flags: StringFlags::default(),
                },
                Operator::Equal,
                OffsetSpec::Absolute(0),
                Value::String("MAGIC".to_string()),
            );
            r.message = "string rule".to_string();
            r
        },
    ];

    sort_rules_by_strength(&mut rules);

    // String rule should come first (higher strength)
    assert_eq!(rules[0].message, "string rule");
    assert_eq!(rules[1].message, "byte rule");
}

#[test]
fn test_sort_rules_by_strength_preserves_child_file_order() {
    // libmagic's `apprentice_sort` orders whole top-level magic entries by
    // their first line's strength but NEVER reorders continuation
    // (child) lines. `sort_rules_by_strength` is non-recursive to match:
    // it sorts only the top-level slice, leaving each rule's `children`
    // in source order. This is load-bearing for `default`/`clear` firing
    // and for multi-fragment descriptions (e.g. gzip's detail siblings).
    //
    // Build one top-level rule whose children are, in file order, a
    // low-strength `default` FIRST and a high-strength byte comparison
    // SECOND. A recursive sort would swap them (byte outranks default),
    // wrongly letting the comparison sibling suppress the `default`.
    let low_first = {
        let mut r = make_rule(
            TypeKind::Meta(crate::parser::ast::MetaType::Default),
            Operator::AnyValue,
            OffsetSpec::Absolute(0),
            Value::Uint(0),
        );
        r.message = "default-child".to_string();
        r.level = 1;
        r
    };
    let high_second = {
        let mut r = make_rule(
            TypeKind::Long {
                endian: crate::parser::ast::Endianness::Big,
                signed: false,
            },
            Operator::Equal,
            OffsetSpec::Absolute(0),
            Value::Uint(0xDEAD_BEEF),
        );
        r.message = "strong-child".to_string();
        r.level = 1;
        r
    };
    let mut parent = make_rule(
        TypeKind::Byte { signed: true },
        Operator::Equal,
        OffsetSpec::Absolute(0),
        Value::Uint(0),
    );
    parent.message = "parent".to_string();
    parent.children = vec![low_first, high_second];

    let mut rules = vec![parent];
    sort_rules_by_strength(&mut rules);

    let child_order: Vec<&str> = rules[0]
        .children
        .iter()
        .map(|c| c.message.as_str())
        .collect();
    assert_eq!(
        child_order,
        vec!["default-child", "strong-child"],
        "child rules must stay in file order; the non-recursive sort must \
         not reorder continuation rules by strength"
    );
}

#[test]
fn test_sort_rules_by_strength_with_modifier() {
    let mut rules = vec![
        {
            let mut r = make_rule(
                TypeKind::String {
                    max_length: None,
                    flags: StringFlags::default(),
                },
                Operator::Equal,
                OffsetSpec::Absolute(0),
                Value::String("TEST".to_string()),
            );
            r.message = "string rule".to_string();
            // Lower the strength with a modifier
            r.strength_modifier = Some(StrengthModifier::Set(10));
            r
        },
        {
            let mut r = make_rule(
                TypeKind::Byte { signed: true },
                Operator::Equal,
                OffsetSpec::Absolute(0),
                Value::Uint(0),
            );
            r.message = "byte rule".to_string();
            // Boost the strength with a modifier
            r.strength_modifier = Some(StrengthModifier::Set(100));
            r
        },
    ];

    sort_rules_by_strength(&mut rules);

    // Byte rule should now come first due to strength modifier
    assert_eq!(rules[0].message, "byte rule");
    assert_eq!(rules[1].message, "string rule");
}

#[test]
fn test_sort_rules_empty() {
    let mut rules: Vec<MagicRule> = vec![];
    sort_rules_by_strength(&mut rules);
    assert!(rules.is_empty());
}

#[test]
fn test_sort_rules_single() {
    let mut rules = vec![make_rule(
        TypeKind::Byte { signed: true },
        Operator::Equal,
        OffsetSpec::Absolute(0),
        Value::Uint(0),
    )];
    sort_rules_by_strength(&mut rules);
    assert_eq!(rules.len(), 1);
}

#[test]
fn test_into_sorted_by_strength() {
    let rules = vec![
        {
            let mut r = make_rule(
                TypeKind::Byte { signed: true },
                Operator::Equal,
                OffsetSpec::Absolute(0),
                Value::Uint(0),
            );
            r.message = "byte rule".to_string();
            r
        },
        {
            let mut r = make_rule(
                TypeKind::Long {
                    endian: Endianness::Big,
                    signed: false,
                },
                Operator::Equal,
                OffsetSpec::Absolute(0),
                Value::Uint(0),
            );
            r.message = "long rule".to_string();
            r
        },
    ];

    let sorted = into_sorted_by_strength(rules);

    // Long rule should come first (higher strength)
    assert_eq!(sorted[0].message, "long rule");
    assert_eq!(sorted[1].message, "byte rule");
}

// ============================================================
// Edge case and integration tests
// ============================================================

#[test]
fn test_strength_comparison_string_vs_byte() {
    let string_rule = make_rule(
        TypeKind::String {
            max_length: None,
            flags: StringFlags::default(),
        },
        Operator::Equal,
        OffsetSpec::Absolute(0),
        Value::String("AB".to_string()),
    );
    let byte_rule = make_rule(
        TypeKind::Byte { signed: true },
        Operator::Equal,
        OffsetSpec::Absolute(0),
        Value::Uint(0x7f),
    );

    let string_strength = calculate_rule_strength(&string_rule);
    let byte_strength = calculate_rule_strength(&byte_rule);

    // String should have higher strength even with short value
    assert!(
        string_strength > byte_strength,
        "String strength {string_strength} should be > byte strength {byte_strength}"
    );
}

#[test]
fn test_strength_comparison_absolute_vs_relative_offset() {
    let absolute_rule = make_rule(
        TypeKind::Byte { signed: true },
        Operator::Equal,
        OffsetSpec::Absolute(0),
        Value::Uint(0x7f),
    );
    let relative_rule = make_rule(
        TypeKind::Byte { signed: true },
        Operator::Equal,
        OffsetSpec::Relative(4),
        Value::Uint(0x7f),
    );

    let absolute_strength = calculate_rule_strength(&absolute_rule);
    let relative_strength = calculate_rule_strength(&relative_rule);

    // Absolute should have higher strength
    assert!(
        absolute_strength > relative_strength,
        "Absolute strength {absolute_strength} should be > relative strength {relative_strength}"
    );
}

// ============================================================
// MetaType strength tests
// ============================================================

fn meta_rule(meta: crate::parser::ast::MetaType, msg: &str) -> MagicRule {
    let mut rule = make_rule(
        TypeKind::Meta(meta),
        Operator::Equal,
        OffsetSpec::Absolute(0),
        Value::Uint(0),
    );
    rule.message = msg.to_string();
    rule
}

#[test]
fn test_meta_default_and_clear_sort_to_bottom() {
    use crate::parser::ast::MetaType;
    let mut rules = vec![
        meta_rule(MetaType::Default, "default"),
        meta_rule(MetaType::Clear, "clear"),
        {
            let mut r = make_rule(
                TypeKind::Byte { signed: true },
                Operator::Equal,
                OffsetSpec::Absolute(0),
                Value::Uint(0),
            );
            r.message = "byte".to_string();
            r
        },
    ];

    sort_rules_by_strength(&mut rules);

    // Byte rule has nonzero strength; default/clear are 0 + Equal 10 +
    // Absolute 10 + numeric 0 = 20. Byte is 5 + Equal 10 + Absolute 10
    // = 25 -- so byte sorts first.
    assert_eq!(rules[0].message, "byte");
}

#[test]
fn test_meta_use_and_indirect_sort_above_default() {
    use crate::parser::ast::MetaType;
    let use_rule = meta_rule(
        MetaType::Use {
            name: "sub".to_string(),
            flip_endian: false,
        },
        "use",
    );
    let indirect_rule = meta_rule(MetaType::Indirect, "indirect");
    let default_rule = meta_rule(MetaType::Default, "default");
    let clear_rule = meta_rule(MetaType::Clear, "clear");

    // use/indirect strength: 5 + Equal 10 + Absolute 10 = 25
    // default/clear strength: 0 + Equal 10 + Absolute 10 = 20
    assert!(
        calculate_default_strength(&use_rule) > calculate_default_strength(&default_rule),
        "use should sort above default"
    );
    assert!(
        calculate_default_strength(&indirect_rule) > calculate_default_strength(&default_rule),
        "indirect should sort above default"
    );
    assert!(
        calculate_default_strength(&use_rule) > calculate_default_strength(&clear_rule),
        "use should sort above clear"
    );
    assert!(
        calculate_default_strength(&indirect_rule) > calculate_default_strength(&clear_rule),
        "indirect should sort above clear"
    );
}

#[test]
fn test_meta_name_strength_is_zero() {
    use crate::parser::ast::MetaType;
    let name_rule = meta_rule(MetaType::Name("foo".to_string()), "name");
    let default_rule = meta_rule(MetaType::Default, "default");
    // Both Name and Default should produce identical strength scores
    // (both contribute 0 from the type axis).
    assert_eq!(
        calculate_default_strength(&name_rule),
        calculate_default_strength(&default_rule),
        "Name strength should equal Default strength (both type-axis 0)"
    );
}

/// Pin the canonical penalty per flag bit (pinned by request from
/// the `CodeRabbit` PR #288 review). Each row asserts which flags
/// reduce rule specificity (penalized) versus which do not
/// (non-penalized).
///
/// **Penalized**: `/c`, `/C`, `/w`, `/W` -- they broaden the match.
/// **Non-penalized**: `/T` (pattern-side trim, not fuzziness), `/b`
/// and `/t` (MIME-output hints, no comparison effect), `/f`
/// (TIGHTENS the match by requiring a word boundary).
///
/// Penalties also stack additively across multiple penalized flags
/// (e.g., `/cw` = 2 points).
#[test]
fn string_flag_specificity_penalty_per_flag_table() {
    let cases: &[(&str, StringFlags, i32)] = &[
        ("no flags", StringFlags::default(), 0),
        (
            "/c only",
            StringFlags::default().with_ignore_lowercase(true),
            1,
        ),
        (
            "/C only",
            StringFlags::default().with_ignore_uppercase(true),
            1,
        ),
        (
            "/w only",
            StringFlags::default().with_compact_optional_whitespace(true),
            1,
        ),
        (
            "/W only",
            StringFlags::default().with_compact_whitespace(true),
            1,
        ),
        (
            "/T only (non-penalized)",
            StringFlags::default().with_trim(true),
            0,
        ),
        (
            "/t only (non-penalized)",
            StringFlags::default().with_text_test(true),
            0,
        ),
        (
            "/b only (non-penalized)",
            StringFlags::default().with_bin_test(true),
            0,
        ),
        (
            "/f only (non-penalized)",
            StringFlags::default().with_full_word(true),
            0,
        ),
        (
            "/cw stacks (case + whitespace)",
            StringFlags::default()
                .with_ignore_lowercase(true)
                .with_compact_optional_whitespace(true),
            2,
        ),
        (
            "/cC stacks (both case folds)",
            StringFlags::default()
                .with_ignore_lowercase(true)
                .with_ignore_uppercase(true),
            2,
        ),
        (
            "all four penalized flags",
            StringFlags::default()
                .with_ignore_lowercase(true)
                .with_ignore_uppercase(true)
                .with_compact_whitespace(true)
                .with_compact_optional_whitespace(true),
            4,
        ),
        (
            "mixed: 2 penalized + 4 non-penalized",
            StringFlags::default()
                .with_ignore_lowercase(true)
                .with_compact_whitespace(true)
                .with_trim(true)
                .with_text_test(true)
                .with_bin_test(true)
                .with_full_word(true),
            2,
        ),
    ];

    for (label, flags, expected) in cases {
        let actual = string_flag_specificity_penalty(*flags);
        assert_eq!(
            actual, *expected,
            "case {label}: expected penalty {expected}, got {actual}"
        );
    }
}

// ============================================================
// Property tests for the clamp and saturation paths
// ============================================================

proptest::proptest! {
    /// `calculate_default_strength` stays inside its documented range and
    /// never panics, for any pattern length and scan range.
    ///
    /// The table above pins exact scores for chosen inputs; this covers the
    /// paths those fixed cases cannot reach -- `saturating_mul` in the
    /// `Search` arm, the `i32::MAX` fallback in `search_pattern_len`, and the
    /// final `clamp`.
    #[test]
    fn prop_search_strength_stays_within_clamp(
        pattern_len in 0usize..2048,
        range in proptest::option::of(1usize..100_000),
    ) {
        let rule = MagicRule::new(
            OffsetSpec::Absolute(0),
            TypeKind::Search {
                range: range.and_then(std::num::NonZeroUsize::new),
                flags: crate::parser::ast::SearchFlags::default(),
            },
            Operator::Equal,
            Value::String("x".repeat(pattern_len)),
            "prop".to_string(),
        );
        let score = calculate_default_strength(&rule);
        proptest::prop_assert!(
            (MIN_STRENGTH..=MAX_STRENGTH).contains(&score),
            "score {score} outside [{MIN_STRENGTH}, {MAX_STRENGTH}] for len={pattern_len} range={range:?}"
        );
    }

    /// Widening the scan range never raises the score, for any pattern.
    ///
    /// This is the invariant the #379 fix rests on: a wider scan is weaker
    /// evidence. It is monotonic non-increasing rather than strictly
    /// decreasing, because libmagic's `MAX(MULT / range, 1)` floors at 1.
    #[test]
    fn prop_widening_the_scan_never_raises_strength(
        pattern_len in 1usize..64,
        a in 1usize..5000,
        b in 1usize..5000,
    ) {
        let score_for = |range: usize| {
            calculate_default_strength(&MagicRule::new(
                OffsetSpec::Absolute(0),
                TypeKind::Search {
                    range: std::num::NonZeroUsize::new(range),
                    flags: crate::parser::ast::SearchFlags::default(),
                },
                Operator::Equal,
                Value::String("x".repeat(pattern_len)),
                "prop".to_string(),
            ))
        };
        let (narrow, wide) = if a <= b { (a, b) } else { (b, a) };
        proptest::prop_assert!(
            score_for(wide) <= score_for(narrow),
            "widening {narrow} -> {wide} raised the score for len={pattern_len}"
        );
    }
}