libmagic-rs 0.6.0

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
// Copyright (c) 2025-2026 the libmagic-rs contributors
// SPDX-License-Identifier: Apache-2.0

//! Strength calculation for magic rules
//!
//! This module implements the strength calculation algorithm based on libmagic's
//! `apprentice_magic_strength` function. Strength is used to order rules during
//! evaluation, giving priority to more specific rules.
//!
//! # Algorithm Overview
//!
//! The default strength of a rule is calculated based on several factors:
//! - **Type specificity**: String types have higher strength than numeric types
//! - **Operator specificity**: Equality operators are more specific than bitwise
//! - **Offset type**: Absolute offsets are more reliable than indirect/relative
//! - **Value length**: Longer strings are more specific matches
//!
//! The calculated strength can be modified using `!:strength` directives in magic
//! files, which apply arithmetic operations to the default strength.

use crate::parser::ast::{MagicRule, OffsetSpec, Operator, StrengthModifier, TypeKind, Value};

/// Maximum strength value (clamped to prevent overflow)
pub const MAX_STRENGTH: i32 = 255;

/// Minimum strength value (clamped to prevent negative strength)
pub const MIN_STRENGTH: i32 = 0;

/// Calculate the default strength of a magic rule based on its specificity.
///
/// This function implements an algorithm inspired by libmagic's `apprentice_magic_strength`
/// function. The strength is calculated based on:
///
/// - **Type contribution**: How specific the type matching is
/// - **Operator contribution**: How specific the comparison is
/// - **Offset contribution**: How reliable the offset is
/// - **Value length contribution**: For strings, longer matches are more specific
///
/// # Arguments
///
/// * `rule` - The magic rule to calculate strength for
///
/// # Returns
///
/// The calculated default strength as an `i32`, clamped to `[MIN_STRENGTH, MAX_STRENGTH]`
///
/// # Examples
///
/// ```
/// use libmagic_rs::parser::ast::{MagicRule, OffsetSpec, TypeKind, Operator, Value};
/// use libmagic_rs::evaluator::strength::calculate_default_strength;
///
/// let rule = MagicRule {
///     offset: OffsetSpec::Absolute(0),
///     typ: TypeKind::String { max_length: None },
///     op: Operator::Equal,
///     value: Value::String("ELF".to_string()),
///     message: "ELF file".to_string(),
///     children: vec![],
///     level: 0,
///     strength_modifier: None,
/// value_transform: None,
/// };
///
/// let strength = calculate_default_strength(&rule);
/// assert!(strength > 0);
/// ```
#[must_use]
pub fn calculate_default_strength(rule: &MagicRule) -> i32 {
    let mut strength: i32 = 0;

    // Type contribution: more specific types get higher strength
    strength += match &rule.typ {
        // Strings are most specific (they match exact byte sequences)
        TypeKind::String { max_length } | TypeKind::PString { max_length, .. } => {
            // Base string strength
            let base = 20;
            // Add bonus for limited-length strings (more constrained match)
            if max_length.is_some() { base + 5 } else { base }
        }
        // UCS-2 strings (`lestring16`/`bestring16`) match byte sequences too,
        // but each character is two bytes wide. Treat them like an unbounded
        // `string` -- no `max_length` knob exists at the magic-file level, so
        // the "constrained" bonus does not apply.
        TypeKind::String16 { .. } => 20,
        // Regex matches a pattern -- treat similarly to an unbounded string.
        // A rule with an EXPLICIT count (byte count, or line count with a
        // specific N) is more constrained than a plain `regex` default, so
        // it gets the same bonus as a length-limited string. Note that
        // `RegexCount::Lines(None)` (the `regex/l` shorthand) has the same
        // effective scan window as `RegexCount::Default` -- both walk the
        // full 8192-byte capped window -- so they get the same strength
        // score. Giving `Lines(None)` the "constrained" bonus would reward
        // users for typing `/l` instead of nothing even though the scan
        // window is identical.
        TypeKind::Regex { count, .. } => {
            use crate::parser::ast::RegexCount;
            match count {
                RegexCount::Default | RegexCount::Lines(None) => 20,
                RegexCount::Bytes(_) | RegexCount::Lines(Some(_)) => 25,
            }
        }
        // Search is always a bounded scan (the range is mandatory), so it
        // gets the "constrained match" bonus unconditionally. This matches
        // the max_length bonus used for String and PString.
        TypeKind::Search { .. } => 25,
        // 64-bit types are most specific among numerics
        TypeKind::Quad { .. } | TypeKind::Double { .. } | TypeKind::QDate { .. } => 16,
        // 32-bit types are fairly specific
        TypeKind::Long { .. } | TypeKind::Float { .. } | TypeKind::Date { .. } => 15,
        // 16-bit integers are moderately specific
        TypeKind::Short { .. } => 10,
        // Single bytes are least specific
        TypeKind::Byte { .. } => 5,
        // Meta-type directives do not read or compare bytes, so most of
        // them contribute no ordering specificity. `Use` and `Indirect`
        // get a moderate score because the rules they dispatch into can
        // carry real specificity that is opaque from the call site.
        //
        // `clippy::match_same_arms` is silenced here so the per-variant
        // rationale is preserved verbatim instead of being collapsed into
        // a single OR-arm: the variants are semantically distinct (each
        // dispatches into a different evaluator path) and the explicit
        // table is the documentation we want to keep next to the values.
        #[allow(clippy::match_same_arms)]
        TypeKind::Meta(meta) => match meta {
            // `default` must sort below every real rule so it only fires
            // when no sibling matched at the current level.
            crate::parser::ast::MetaType::Default => 0,
            // `clear` is a control-flow toggle with no byte-matching
            // specificity of its own.
            crate::parser::ast::MetaType::Clear => 0,
            // `name` rules are extracted at load time and never sorted at
            // eval time; the value is provided for completeness.
            crate::parser::ast::MetaType::Name(_) => 0,
            // `use` dispatches into a subroutine whose specificity is
            // opaque from the call site -- give it a moderate weight so
            // it sorts above pure no-ops but below real type-bearing rules.
            crate::parser::ast::MetaType::Use(_) => 5,
            // `indirect` re-evaluates the root rule set at the resolved
            // offset; same rationale as `use` for the moderate weight.
            crate::parser::ast::MetaType::Indirect => 5,
            // `offset` reports the current file offset rather than reading
            // a typed value -- no byte-matching specificity.
            crate::parser::ast::MetaType::Offset => 0,
        },
    };

    // Operator contribution: equality is most specific
    strength += match &rule.op {
        // Exact equality is most specific
        Operator::Equal => 10,
        // Inequality is somewhat specific
        Operator::NotEqual => 5,
        // Comparison operators are moderately specific
        Operator::LessThan
        | Operator::GreaterThan
        | Operator::LessEqual
        | Operator::GreaterEqual => 6,
        // Bitwise AND with mask is moderately specific
        Operator::BitwiseAndMask(_) => 7,
        // Plain bitwise AND is least specific
        Operator::BitwiseAnd => 3,
        // Bitwise XOR and NOT are moderately specific
        Operator::BitwiseXor | Operator::BitwiseNot => 4,
        // Any value always matches, least specific
        Operator::AnyValue => 1,
    };

    // Offset contribution: absolute offsets are most reliable
    strength += match &rule.offset {
        // Absolute offsets are most reliable
        OffsetSpec::Absolute(_) => 10,
        // From-end offsets are also reliable (just from the other end)
        OffsetSpec::FromEnd(_) => 8,
        // Indirect offsets depend on reading a pointer first
        OffsetSpec::Indirect { .. } => 5,
        // Relative offsets depend on previous match position
        OffsetSpec::Relative(_) => 3,
    };

    // Value length contribution: longer values are more specific
    // Only applicable to string and bytes values
    let value_length_bonus = match &rule.value {
        Value::String(s) => {
            // Each character adds to specificity, capped at 20
            i32::try_from(s.len()).unwrap_or(20).min(20)
        }
        Value::Bytes(b) => {
            // Each byte adds to specificity, capped at 20
            i32::try_from(b.len()).unwrap_or(20).min(20)
        }
        // Numeric values don't get length bonus
        Value::Uint(_) | Value::Int(_) | Value::Float(_) => 0,
    };
    strength += value_length_bonus;

    // Clamp to valid range
    strength.clamp(MIN_STRENGTH, MAX_STRENGTH)
}

/// Apply a strength modifier to a base strength value.
///
/// This function applies the arithmetic operation specified by the `StrengthModifier`
/// to the given base strength. The result is clamped to `[MIN_STRENGTH, MAX_STRENGTH]`.
///
/// # Arguments
///
/// * `base_strength` - The default calculated strength
/// * `modifier` - The modifier to apply
///
/// # Returns
///
/// The modified strength, clamped to valid range
///
/// # Examples
///
/// ```
/// use libmagic_rs::parser::ast::StrengthModifier;
/// use libmagic_rs::evaluator::strength::apply_strength_modifier;
///
/// // Add 10 to strength
/// assert_eq!(apply_strength_modifier(50, &StrengthModifier::Add(10)), 60);
///
/// // Subtract 5 from strength
/// assert_eq!(apply_strength_modifier(50, &StrengthModifier::Subtract(5)), 45);
///
/// // Multiply by 2
/// assert_eq!(apply_strength_modifier(50, &StrengthModifier::Multiply(2)), 100);
///
/// // Divide by 2
/// assert_eq!(apply_strength_modifier(50, &StrengthModifier::Divide(2)), 25);
///
/// // Set to absolute value
/// assert_eq!(apply_strength_modifier(50, &StrengthModifier::Set(75)), 75);
/// ```
#[must_use]
pub fn apply_strength_modifier(base_strength: i32, modifier: &StrengthModifier) -> i32 {
    let result = match modifier {
        StrengthModifier::Add(n) => base_strength.saturating_add(*n),
        StrengthModifier::Subtract(n) => base_strength.saturating_sub(*n),
        StrengthModifier::Multiply(n) => base_strength.saturating_mul(*n),
        StrengthModifier::Divide(n) => {
            if *n == 0 {
                // Division by zero: return base strength unchanged
                // (magic file contains !:strength /0 which is invalid)
                base_strength
            } else {
                base_strength / n
            }
        }
        StrengthModifier::Set(n) => *n,
    };

    // Clamp to valid range
    result.clamp(MIN_STRENGTH, MAX_STRENGTH)
}

/// Calculate the final strength of a magic rule, including any modifiers.
///
/// This function first calculates the default strength based on the rule's
/// specificity, then applies any strength modifier if present.
///
/// # Arguments
///
/// * `rule` - The magic rule to calculate strength for
///
/// # Returns
///
/// The final calculated strength, clamped to `[MIN_STRENGTH, MAX_STRENGTH]`
///
/// # Examples
///
/// ```
/// use libmagic_rs::parser::ast::{MagicRule, OffsetSpec, TypeKind, Operator, Value, StrengthModifier};
/// use libmagic_rs::evaluator::strength::calculate_rule_strength;
///
/// let rule = MagicRule {
///     offset: OffsetSpec::Absolute(0),
///     typ: TypeKind::Byte { signed: true },
///     op: Operator::Equal,
///     value: Value::Uint(0x7f),
///     message: "ELF magic".to_string(),
///     children: vec![],
///     level: 0,
///     strength_modifier: Some(StrengthModifier::Add(20)),
/// value_transform: None,
/// };
///
/// let strength = calculate_rule_strength(&rule);
/// // Base: 5 (byte) + 10 (equal) + 10 (absolute) + 0 (numeric) = 25
/// // With modifier: 25 + 20 = 45
/// assert_eq!(strength, 45);
/// ```
#[must_use]
pub fn calculate_rule_strength(rule: &MagicRule) -> i32 {
    let base_strength = calculate_default_strength(rule);

    if let Some(ref modifier) = rule.strength_modifier {
        apply_strength_modifier(base_strength, modifier)
    } else {
        base_strength
    }
}

/// Sort magic rules by their calculated strength in descending order.
///
/// Higher strength rules are evaluated first, as they represent more specific
/// matches. This function sorts the rules in-place.
///
/// # Arguments
///
/// * `rules` - The slice of magic rules to sort
///
/// # Examples
///
/// ```
/// use libmagic_rs::parser::ast::{MagicRule, OffsetSpec, TypeKind, Operator, Value};
/// use libmagic_rs::evaluator::strength::sort_rules_by_strength;
///
/// let mut rules = vec![
///     MagicRule {
///         offset: OffsetSpec::Absolute(0),
///         typ: TypeKind::Byte { signed: true },
///         op: Operator::Equal,
///         value: Value::Uint(0x7f),
///         message: "byte rule".to_string(),
///         children: vec![],
///         level: 0,
///         strength_modifier: None,
///     value_transform: None,
///     },
///     MagicRule {
///         offset: OffsetSpec::Absolute(0),
///         typ: TypeKind::String { max_length: None },
///         op: Operator::Equal,
///         value: Value::String("MAGIC".to_string()),
///         message: "string rule".to_string(),
///         children: vec![],
///         level: 0,
///         strength_modifier: None,
///     value_transform: None,
///     },
/// ];
///
/// 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");
/// ```
pub fn sort_rules_by_strength(rules: &mut [MagicRule]) {
    // Use a stable sort keyed on the negated strength so that higher-strength
    // rules come first while preserving source order for ties. This avoids
    // breaking tests that rely on deterministic ordering of equal-strength
    // rules.
    rules.sort_by_cached_key(|rule| calculate_rule_strength(rule).saturating_neg());
}

/// Sort magic rules by strength in descending order, recursively sorting child
/// rules as well.
///
/// This is intended for use at magic database load time so that first-match
/// evaluation encounters more-specific rules earlier. Child rules (nested
/// under a parent match) are also sorted so that the same ordering benefit
/// applies within each hierarchical level.
///
/// The sort is stable: rules with equal strength preserve their source
/// order, so test assertions and libmagic-file semantics that depend on
/// the original ordering of equal-strength siblings continue to hold.
///
/// # Arguments
///
/// * `rules` - The slice of magic rules to sort (in-place, recursive)
///
/// # Examples
///
/// ```
/// use libmagic_rs::parser::ast::{MagicRule, OffsetSpec, TypeKind, Operator, Value};
/// use libmagic_rs::evaluator::strength::sort_rules_by_strength_recursive;
///
/// let mut rules: Vec<MagicRule> = vec![];
/// sort_rules_by_strength_recursive(&mut rules);
/// assert!(rules.is_empty());
/// ```
pub fn sort_rules_by_strength_recursive(rules: &mut [MagicRule]) {
    sort_rules_by_strength(rules);
    for rule in rules.iter_mut() {
        sort_rules_by_strength_recursive(&mut rule.children);
    }
}

/// Sort magic rules by strength and return the sorted vec (consuming the input).
///
/// This is a convenience function that takes ownership of the rules vector,
/// sorts it by strength, and returns the sorted vector.
///
/// # Arguments
///
/// * `rules` - The vector of magic rules to sort
///
/// # Returns
///
/// The sorted vector with higher strength rules first
///
/// # Examples
///
/// ```
/// use libmagic_rs::parser::ast::{MagicRule, OffsetSpec, TypeKind, Operator, Value};
/// use libmagic_rs::evaluator::strength::into_sorted_by_strength;
///
/// let rules = vec![
///     MagicRule {
///         offset: OffsetSpec::Absolute(0),
///         typ: TypeKind::Byte { signed: true },
///         op: Operator::Equal,
///         value: Value::Uint(0),
///         message: "byte rule".to_string(),
///         children: vec![],
///         level: 0,
///         strength_modifier: None,
///     value_transform: None,
///     },
///     MagicRule {
///         offset: OffsetSpec::Absolute(0),
///         typ: TypeKind::String { max_length: None },
///         op: Operator::Equal,
///         value: Value::String("MAGIC".to_string()),
///         message: "string rule".to_string(),
///         children: vec![],
///         level: 0,
///         strength_modifier: None,
///     value_transform: None,
///     },
/// ];
///
/// let sorted = into_sorted_by_strength(rules);
/// assert_eq!(sorted[0].message, "string rule");
/// ```
#[must_use]
pub fn into_sorted_by_strength(mut rules: Vec<MagicRule>) -> Vec<MagicRule> {
    sort_rules_by_strength(&mut rules);
    rules
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::ast::{Endianness, IndirectAdjustmentOp};

    // 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 },
                        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),
                        },
                        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 },
                        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)",
            ),
        ];

        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 },
                    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_with_modifier() {
        let mut rules = vec![
            {
                let mut r = make_rule(
                    TypeKind::String { max_length: None },
                    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 },
            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("sub".to_string()), "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)"
        );
    }
}