libmagic-rs 0.5.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
// 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,
/// };
///
/// 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 } => {
            // Base string strength
            let base = 20;
            // Add bonus for limited-length strings (more constrained match)
            if max_length.is_some() { base + 5 } else { base }
        }
        // 64-bit types are most specific among numerics
        TypeKind::Quad { .. } | TypeKind::Double { .. } => 16,
        // 32-bit types are fairly specific
        TypeKind::Long { .. } | TypeKind::Float { .. } => 15,
        // 16-bit integers are moderately specific
        TypeKind::Short { .. } => 10,
        // Single bytes are least specific
        TypeKind::Byte { .. } => 5,
    };

    // 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)),
/// };
///
/// 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,
///     },
///     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,
///     },
/// ];
///
/// 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]) {
    rules.sort_by(|a, b| {
        let strength_a = calculate_rule_strength(a);
        let strength_b = calculate_rule_strength(b);
        // Sort in descending order (higher strength first)
        strength_b.cmp(&strength_a)
    });
}

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

    // 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,
        }
    }

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

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

    #[test]
    fn test_strength_type_short() {
        let rule = make_rule(
            TypeKind::Short {
                endian: Endianness::Little,
                signed: false,
            },
            Operator::Equal,
            OffsetSpec::Absolute(0),
            Value::Uint(0),
        );
        let strength = calculate_default_strength(&rule);
        // Short: 10, Equal: 10, Absolute: 10, Numeric: 0 = 30
        assert_eq!(strength, 30);
    }

    #[test]
    fn test_strength_type_long() {
        let rule = make_rule(
            TypeKind::Long {
                endian: Endianness::Big,
                signed: false,
            },
            Operator::Equal,
            OffsetSpec::Absolute(0),
            Value::Uint(0),
        );
        let strength = calculate_default_strength(&rule);
        // Long: 15, Equal: 10, Absolute: 10, Numeric: 0 = 35
        assert_eq!(strength, 35);
    }

    #[test]
    fn test_strength_type_quad() {
        let rule = make_rule(
            TypeKind::Quad {
                endian: Endianness::Little,
                signed: false,
            },
            Operator::Equal,
            OffsetSpec::Absolute(0),
            Value::Uint(0),
        );
        let strength = calculate_default_strength(&rule);
        // Quad: 16, Equal: 10, Absolute: 10, Numeric: 0 = 36
        assert_eq!(strength, 36);
    }

    #[test]
    fn test_strength_type_string() {
        let rule = make_rule(
            TypeKind::String { max_length: None },
            Operator::Equal,
            OffsetSpec::Absolute(0),
            Value::String("ELF".to_string()),
        );
        let strength = calculate_default_strength(&rule);
        // String: 20, Equal: 10, Absolute: 10, String length 3: 3 = 43
        assert_eq!(strength, 43);
    }

    #[test]
    fn test_strength_type_string_with_max_length() {
        let rule = make_rule(
            TypeKind::String {
                max_length: Some(10),
            },
            Operator::Equal,
            OffsetSpec::Absolute(0),
            Value::String("TEST".to_string()),
        );
        let strength = calculate_default_strength(&rule);
        // String with max_length: 25, Equal: 10, Absolute: 10, String length 4: 4 = 49
        assert_eq!(strength, 49);
    }

    #[test]
    fn test_strength_operator_not_equal() {
        let rule = make_rule(
            TypeKind::Byte { signed: true },
            Operator::NotEqual,
            OffsetSpec::Absolute(0),
            Value::Uint(0),
        );
        let strength = calculate_default_strength(&rule);
        // Byte: 5, NotEqual: 5, Absolute: 10, Numeric: 0 = 20
        assert_eq!(strength, 20);
    }

    #[test]
    fn test_strength_operator_bitwise_and() {
        let rule = make_rule(
            TypeKind::Byte { signed: true },
            Operator::BitwiseAnd,
            OffsetSpec::Absolute(0),
            Value::Uint(0),
        );
        let strength = calculate_default_strength(&rule);
        // Byte: 5, BitwiseAnd: 3, Absolute: 10, Numeric: 0 = 18
        assert_eq!(strength, 18);
    }

    #[test]
    fn test_strength_operator_bitwise_and_mask() {
        let rule = make_rule(
            TypeKind::Byte { signed: true },
            Operator::BitwiseAndMask(0xFF),
            OffsetSpec::Absolute(0),
            Value::Uint(0),
        );
        let strength = calculate_default_strength(&rule);
        // Byte: 5, BitwiseAndMask: 7, Absolute: 10, Numeric: 0 = 22
        assert_eq!(strength, 22);
    }

    #[test]
    fn test_strength_comparison_operators() {
        let operators = [
            Operator::LessThan,
            Operator::GreaterThan,
            Operator::LessEqual,
            Operator::GreaterEqual,
        ];
        for op in operators {
            let rule = make_rule(
                TypeKind::Byte { signed: true },
                op.clone(),
                OffsetSpec::Absolute(0),
                Value::Uint(0),
            );
            let strength = calculate_default_strength(&rule);
            // Byte: 5, Comparison: 6, Absolute: 10, Numeric: 0 = 21
            assert_eq!(strength, 21, "Failed for operator: {op:?}");
        }
    }

    #[test]
    fn test_strength_offset_indirect() {
        let rule = make_rule(
            TypeKind::Byte { signed: true },
            Operator::Equal,
            OffsetSpec::Indirect {
                base_offset: 0,
                pointer_type: TypeKind::Long {
                    endian: Endianness::Little,
                    signed: false,
                },
                adjustment: 0,
                endian: Endianness::Little,
            },
            Value::Uint(0),
        );
        let strength = calculate_default_strength(&rule);
        // Byte: 5, Equal: 10, Indirect: 5, Numeric: 0 = 20
        assert_eq!(strength, 20);
    }

    #[test]
    fn test_strength_offset_relative() {
        let rule = make_rule(
            TypeKind::Byte { signed: true },
            Operator::Equal,
            OffsetSpec::Relative(4),
            Value::Uint(0),
        );
        let strength = calculate_default_strength(&rule);
        // Byte: 5, Equal: 10, Relative: 3, Numeric: 0 = 18
        assert_eq!(strength, 18);
    }

    #[test]
    fn test_strength_offset_from_end() {
        let rule = make_rule(
            TypeKind::Byte { signed: true },
            Operator::Equal,
            OffsetSpec::FromEnd(-4),
            Value::Uint(0),
        );
        let strength = calculate_default_strength(&rule);
        // Byte: 5, Equal: 10, FromEnd: 8, Numeric: 0 = 23
        assert_eq!(strength, 23);
    }

    #[test]
    fn test_strength_value_bytes() {
        let rule = make_rule(
            TypeKind::Byte { signed: true },
            Operator::Equal,
            OffsetSpec::Absolute(0),
            Value::Bytes(vec![0x7f, 0x45, 0x4c, 0x46]),
        );
        let strength = calculate_default_strength(&rule);
        // Byte: 5, Equal: 10, Absolute: 10, Bytes length 4: 4 = 29
        assert_eq!(strength, 29);
    }

    #[test]
    fn test_strength_value_long_string() {
        let rule = 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()),
        );
        let strength = calculate_default_strength(&rule);
        // String: 20, Equal: 10, Absolute: 10, String length capped at 20: 20 = 60
        assert_eq!(strength, 60);
    }

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