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
// 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;
/// 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;
/// libmagic's `MULT` from `apprentice_magic_strength`, used to scale a
/// `search` rule's strength inversely by its scan range.
const SEARCH_RANGE_MULT: usize = 10;
/// Upper bound on a `search` rule's type contribution, matching the
/// constrained-string score so a tight scan cannot outrank an exact match.
const SEARCH_STRENGTH_CAP: i32 = 25;
/// Byte length of a `search` rule's pattern, which is what libmagic's
/// `vallen` measures. A non-pattern operand contributes no length.
/// 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, StringFlags, TypeKind, Operator, Value};
/// use libmagic_rs::evaluator::strength::calculate_default_strength;
///
/// let rule = MagicRule::new(OffsetSpec::Absolute(0), TypeKind::String { max_length: None, flags: StringFlags::default() }, Operator::Equal, Value::String("ELF".to_string()), "ELF file".to_string());
///
/// let strength = calculate_default_strength(&rule);
/// assert!(strength > 0);
/// ```
/// Count how many `string`-flag bits make a rule's pattern fuzzier.
///
/// libmagic `apprentice.c::apprentice_magic_strength` subtracts 1 from the
/// computed strength for each `STRING_IGNORE_*` bit set. We extend the
/// same reasoning to the whitespace flags (`/w` and `/W`) because they
/// broaden what the rule matches.
///
/// Penalized flags (each costs 1 point):
/// - `/c` (`ignore_lowercase`) -- ASCII case-fold when pattern is lowercase
/// - `/C` (`ignore_uppercase`) -- ASCII case-fold when pattern is uppercase
/// - `/w` (`compact_optional_whitespace`) -- file whitespace optional
/// - `/W` (`compact_whitespace`) -- file whitespace required but elastic
///
/// Non-penalized flags (no specificity change):
/// - `/t` (`text_test`) and `/b` (`bin_test`) -- MIME-output hints only
/// - `/T` (`trim`) -- pattern-side normalization, not a fuzziness knob
/// - `/f` (`full_word`) -- TIGHTENS the match by requiring a post-match
/// word boundary; opposite direction from fuzziness, so it should not
/// be penalized.
/// 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);
/// ```
/// 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::new(
/// OffsetSpec::Absolute(0),
/// TypeKind::Byte { signed: true },
/// Operator::Equal,
/// Value::Uint(0x7f),
/// "ELF magic".to_string(),
/// )
/// .with_strength_modifier(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);
/// ```
/// 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, StringFlags, TypeKind, Operator, Value};
/// use libmagic_rs::evaluator::strength::sort_rules_by_strength;
///
/// let mut rules = vec![
/// MagicRule::new(OffsetSpec::Absolute(0), TypeKind::Byte { signed: true }, Operator::Equal, Value::Uint(0x7f), "byte rule".to_string()),
/// MagicRule::new(OffsetSpec::Absolute(0), TypeKind::String { max_length: None, flags: StringFlags::default() }, Operator::Equal, Value::String("MAGIC".to_string()), "string rule".to_string()),
/// ];
///
/// 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");
/// ```
/// Sort magic rules by strength in descending order, recursively sorting child
/// rules as well.
///
/// **Do not use this at magic database load time.** Child rules must stay in
/// source order: `default` and `clear` fire based on whether an *earlier*
/// sibling matched, and multi-fragment descriptions render in file order, so
/// reordering children can suppress a `default` or scramble a description.
/// libmagic's `apprentice_sort` orders whole entries by their first line and
/// never reorders the lines inside one. Load paths use the non-recursive
/// [`sort_rules_by_strength`] for exactly this reason -- see GOTCHAS S13.4 and
/// S13.5.
///
/// This recursive variant exists for callers that genuinely want a fully
/// ordered tree independent of evaluation semantics, such as tooling that
/// inspects or reports on rule specificity. It has no production callers.
///
/// 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, StringFlags, 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());
/// ```
/// 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, StringFlags, TypeKind, Operator, Value};
/// use libmagic_rs::evaluator::strength::into_sorted_by_strength;
///
/// let rules = vec![
/// MagicRule::new(OffsetSpec::Absolute(0), TypeKind::Byte { signed: true }, Operator::Equal, Value::Uint(0), "byte rule".to_string()),
/// MagicRule::new(OffsetSpec::Absolute(0), TypeKind::String { max_length: None, flags: StringFlags::default() }, Operator::Equal, Value::String("MAGIC".to_string()), "string rule".to_string()),
/// ];
///
/// let sorted = into_sorted_by_strength(rules);
/// assert_eq!(sorted[0].message, "string rule");
/// ```