pub fn evaluate_single_rule(
rule: &MagicRule,
buffer: &[u8],
) -> Result<Option<(usize, Value)>, LibmagicError>Expand description
Evaluate a single magic rule against a file buffer
This function performs the core rule evaluation by:
- Resolving the rule’s offset specification to an absolute position
- Reading and interpreting bytes at that position according to the rule’s type
- Applying the rule’s operator to compare the read value with the expected value
§Arguments
rule- The magic rule to evaluatebuffer- The file buffer to evaluate against
§Returns
Returns Ok(Some((offset, value))) if the rule matches (with the resolved offset and
read value), Ok(None) if it doesn’t match, or Err(LibmagicError) if evaluation
fails due to buffer access issues or other errors.
§Examples
use libmagic_rs::evaluator::evaluate_single_rule;
use libmagic_rs::parser::ast::{MagicRule, OffsetSpec, TypeKind, Operator, Value};
// Create a rule to check for ELF magic bytes at offset 0
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: None,
};
let elf_buffer = &[0x7f, 0x45, 0x4c, 0x46]; // ELF magic bytes
let result = evaluate_single_rule(&rule, elf_buffer).unwrap();
assert!(result.is_some()); // Should match
let non_elf_buffer = &[0x50, 0x4b, 0x03, 0x04]; // ZIP magic bytes
let result = evaluate_single_rule(&rule, non_elf_buffer).unwrap();
assert!(result.is_none()); // Should not match§Errors
LibmagicError::EvaluationError- If offset resolution fails, buffer access is out of bounds, or type interpretation fails