Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

API Reference

Complete API documentation for libmagic-rs library components.

Core Types

MagicDatabase

The main interface for loading magic rules and evaluating files.

#![allow(unused)]
fn main() {
use libmagic_rs::MagicDatabase;
}

Constructor Methods

MethodDescription
with_builtin_rules()Create database with built-in rules
with_builtin_rules_and_config(config)Create with built-in rules and custom config
load_from_file(path)Load rules from a file or directory
load_from_file_with_config(path, config)Load from file with custom config

Evaluation Methods

MethodDescription
evaluate_file(path)Evaluate a file and return results
evaluate_buffer(buffer)Evaluate an in-memory buffer

Accessor Methods

MethodReturn TypeDescription
config()&EvaluationConfigGet evaluation configuration
source_path()Option<&Path>Get path rules were loaded from

Example

#![allow(unused)]
fn main() {
use libmagic_rs::{MagicDatabase, EvaluationConfig};

// Using built-in rules
let db = MagicDatabase::with_builtin_rules()?;
let result = db.evaluate_file("sample.bin")?;
println!("Type: {}", result.description);

// With custom configuration
let config = EvaluationConfig {
    timeout_ms: Some(5000),
    enable_mime_types: true,
    ..Default::default()
};
let db = MagicDatabase::with_builtin_rules_and_config(config)?;

// From file
let db = MagicDatabase::load_from_file("/usr/share/misc/magic")?;
}

EvaluationResult

Result of magic rule evaluation.

#![allow(unused)]
fn main() {
use libmagic_rs::EvaluationResult;
}

Fields

FieldTypeDescription
descriptionStringHuman-readable file type description
mime_typeOption<String>MIME type (if enabled)
confidencef64Confidence score (0.0-1.0)
matchesVec<MatchResult>Individual match results
metadataEvaluationMetadataEvaluation diagnostics

Example

#![allow(unused)]
fn main() {
let result = db.evaluate_file("document.pdf")?;

println!("Description: {}", result.description);
println!("Confidence: {:.0}%", result.confidence * 100.0);

if let Some(mime) = &result.mime_type {
    println!("MIME Type: {}", mime);
}

println!("Evaluation time: {:.2}ms", result.metadata.evaluation_time_ms);
}

EvaluationConfig

Configuration for rule evaluation behavior.

#![allow(unused)]
fn main() {
use libmagic_rs::EvaluationConfig;
}

Fields

FieldTypeDefaultDescription
max_recursion_depthu3220Maximum nesting depth for rules (1-1000)
max_string_lengthusize8192Maximum string bytes to read (1-1MB)
stop_at_first_matchbooltrueStop after first match
enable_mime_typesboolfalseMap results to MIME types
timeout_msOption<u64>NoneEvaluation timeout (1-300000ms)

Preset Configurations

#![allow(unused)]
fn main() {
// Default balanced settings
let config = EvaluationConfig::default();

// Optimized for speed
let config = EvaluationConfig::performance();
// - max_recursion_depth: 10
// - max_string_length: 1024
// - stop_at_first_match: true
// - timeout_ms: Some(1000)

// Optimized for completeness
let config = EvaluationConfig::comprehensive();
// - max_recursion_depth: 50
// - max_string_length: 32768
// - stop_at_first_match: false
// - enable_mime_types: true
// - timeout_ms: Some(30000)
}

Validation

#![allow(unused)]
fn main() {
let config = EvaluationConfig {
    max_recursion_depth: 25,
    max_string_length: 16384,
    ..Default::default()
};

// Validate configuration
config.validate()?;
}

EvaluationMetadata

Diagnostic information about the evaluation process.

#![allow(unused)]
fn main() {
use libmagic_rs::EvaluationMetadata;
}

Fields

FieldTypeDescription
file_sizeu64Size of analyzed file in bytes
evaluation_time_msf64Time taken in milliseconds
rules_evaluatedusizeNumber of rules tested
magic_fileOption<PathBuf>Source magic file path
timed_outboolWhether evaluation timed out

AST Types

MagicRule

Represents a parsed magic rule.

#![allow(unused)]
fn main() {
use libmagic_rs::MagicRule;
}
FieldTypeDescription
offsetOffsetSpecWhere to read data
typTypeKindType of data to read
opOperatorComparison operator
valueValueExpected value
messageStringDescription message
childrenVec<MagicRule>Nested rules
levelu32Indentation level
strength_modifierOption<StrengthModifier>Optional strength modifier from !:strength directive

StrengthModifier

Optional modifier for rule strength calculation.

#![allow(unused)]
fn main() {
use libmagic_rs::StrengthModifier;
}
VariantDescription
Add(i32)Add to base strength
Subtract(i32)Subtract from base strength
Multiply(i32)Multiply base strength
Divide(i32)Divide base strength
Set(i32)Set strength to fixed value

OffsetSpec

Offset specification for locating data.

#![allow(unused)]
fn main() {
use libmagic_rs::OffsetSpec;
}
VariantDescription
Absolute(i64)Absolute offset from file start
Indirect { base_offset, pointer_type, adjustment, endian }Indirect through pointer
Relative(i64)Relative to previous match
FromEnd(i64)Offset from end of file

TypeKind

Data type specifications.

#![allow(unused)]
fn main() {
use libmagic_rs::TypeKind;
}
VariantDescription
Byte { signed }Single byte with explicit signedness (struct variant since v0.2.0; previously unit variant)
Short { endian, signed }16-bit integer
Long { endian, signed }32-bit integer
Float { endian }32-bit IEEE 754 floating-point (added in v0.5.0)
Double { endian }64-bit IEEE 754 double-precision floating-point (added in v0.5.0)
String { max_length }String data (discriminant changed from 4 to 6 in v0.5.0)
PString { max_length }Pascal string - length-prefixed byte followed by string data (returns Value::String)

Operator

Comparison and bitwise operators for magic rule matching.

#![allow(unused)]
fn main() {
use libmagic_rs::Operator;
}
VariantDescription
EqualEquality comparison (=)
NotEqualInequality comparison (!=)
LessThanLess than comparison (<) (added in v0.2.0)
GreaterThanGreater than comparison (>) (added in v0.2.0)
LessEqualLess than or equal comparison (<=) (added in v0.2.0)
GreaterEqualGreater than or equal comparison (>=) (added in v0.2.0)
BitwiseAndBitwise AND (&) - matches if any bits overlap
BitwiseAndMask(u64)Bitwise AND with mask - masked comparison of file data
BitwiseXorBitwise XOR (^) - matches if XOR result is non-zero
BitwiseNotBitwise NOT (~) - compares complement of file value with expected value
AnyValueMatch any value (x) - unconditional match

Examples

#![allow(unused)]
fn main() {
use libmagic_rs::{MagicDatabase, Operator};
use libmagic_rs::parser::grammar::parse_magic_rule;

// Equal operator (default)
let (_, rule) = parse_magic_rule("0 byte =0x7f").unwrap();
assert_eq!(rule.op, Operator::Equal);

// Bitwise AND - check if bit is set
let (_, rule) = parse_magic_rule("0 byte &0x80").unwrap();
assert_eq!(rule.op, Operator::BitwiseAnd);

// Bitwise XOR - check for difference
let (_, rule) = parse_magic_rule("0 byte ^0xFF").unwrap();
assert_eq!(rule.op, Operator::BitwiseXor);

// Bitwise NOT - check complement
let (_, rule) = parse_magic_rule("0 byte ~0xFF").unwrap();
assert_eq!(rule.op, Operator::BitwiseNot);

// Any value - always matches
let (_, rule) = parse_magic_rule("0 byte x").unwrap();
assert_eq!(rule.op, Operator::AnyValue);
}

Value

Value types for matching.

#![allow(unused)]
fn main() {
use libmagic_rs::Value;
}
VariantDescription
Uint(u64)Unsigned integer
Int(i64)Signed integer
Float(f64)Floating-point value (added in v0.5.0)
Bytes(Vec<u8>)Byte sequence
String(String)String value

The Value enum derives PartialEq but no longer derives Eq (removed in v0.5.0 to support floating-point values).

Endianness

Byte order specification.

#![allow(unused)]
fn main() {
use libmagic_rs::Endianness;
}
VariantDescription
LittleLittle-endian
BigBig-endian
NativeSystem native

Error Types

LibmagicError

Main error type for all library operations.

#![allow(unused)]
fn main() {
use libmagic_rs::LibmagicError;
}

Variants

VariantDescription
ParseError(ParseError)Magic file parsing error
EvaluationError(EvaluationError)Rule evaluation error
IoError(std::io::Error)File I/O error
Timeout { timeout_ms }Evaluation timeout exceeded

ParseError

Errors during magic file parsing.

VariantDescription
InvalidSyntax { line, message }Invalid syntax in magic file
UnsupportedFeature { line, feature }Unsupported feature encountered
InvalidOffset { line, offset }Invalid offset specification
InvalidType { line, type_spec }Invalid type specification
InvalidOperator { line, operator }Invalid operator
InvalidValue { line, value }Invalid value
UnsupportedFormat { line, format_type, message }Unsupported file format
IoError(std::io::Error)I/O error during parsing

EvaluationError

Errors during rule evaluation.

VariantDescription
BufferOverrun { offset }Read beyond buffer bounds
InvalidOffset { offset }Invalid offset calculation
UnsupportedType { type_name }Unsupported type during evaluation
RecursionLimitExceeded { depth }Max recursion depth exceeded
StringLengthExceeded { length, max_length }String too long
InvalidStringEncoding { offset }Invalid string encoding
Timeout { timeout_ms }Evaluation timeout
InternalError { message }Internal error (bug)

Example

#![allow(unused)]
fn main() {
use libmagic_rs::{MagicDatabase, LibmagicError, ParseError};

match MagicDatabase::load_from_file("invalid.magic") {
    Ok(db) => println!("Loaded successfully"),
    Err(LibmagicError::ParseError(ParseError::InvalidSyntax { line, message })) => {
        eprintln!("Syntax error at line {}: {}", line, message);
    }
    Err(LibmagicError::IoError(e)) => {
        eprintln!("I/O error: {}", e);
    }
    Err(e) => eprintln!("Error: {}", e),
}
}

Evaluator Module

EvaluationContext

Maintains evaluation state during rule processing.

#![allow(unused)]
fn main() {
use libmagic_rs::EvaluationContext;
}

Methods

MethodDescription
new(config)Create new context
current_offset()Get current position
set_current_offset(offset)Set current position
recursion_depth()Get recursion depth
increment_recursion_depth()Increment depth (with limit check)
decrement_recursion_depth()Decrement depth
should_stop_at_first_match()Check stop behavior
max_string_length()Get max string length
enable_mime_types()Check MIME type setting
timeout_ms()Get timeout value
reset()Reset to initial state

MatchResult (Evaluator)

Result from internal evaluation.

#![allow(unused)]
fn main() {
use libmagic_rs::evaluator::MatchResult;
}
FieldTypeDescription
messageStringMatch description
offsetusizeMatch offset
levelu32Rule level
valueValueMatched value
type_kindTypeKindType used to read value (added in v0.5.0)
confidencef64Confidence score

Output Module

MatchResult (Output)

Structured match result for output formatting.

#![allow(unused)]
fn main() {
use libmagic_rs::output::MatchResult;
}

Fields

FieldTypeDescription
messageStringFile type description
offsetusizeMatch offset
lengthusizeBytes examined
valueValueMatched value
rule_pathVec<String>Rule hierarchy
confidenceu8Confidence (0-100)
mime_typeOption<String>MIME type

Methods

#![allow(unused)]
fn main() {
// Create basic result
let result = MatchResult::new(
    "PNG image".to_string(),
    0,
    Value::Bytes(vec![0x89, 0x50, 0x4e, 0x47])
);

// Create with full metadata
let result = MatchResult::with_metadata(
    "JPEG image".to_string(),
    0,
    2,
    Value::Bytes(vec![0xff, 0xd8]),
    vec!["image".to_string(), "jpeg".to_string()],
    85,
    Some("image/jpeg".to_string())
);

// Modify result
result.set_confidence(90);
result.add_rule_path("subtype".to_string());
result.set_mime_type(Some("image/jpeg".to_string()));
}

JSON Output

#![allow(unused)]
fn main() {
use libmagic_rs::output::json::{format_json_output, format_json_line_output};

// Pretty-printed JSON (single file)
let json = format_json_output(&matches)?;

// JSON Lines (multiple files)
let json_line = format_json_line_output(path, &matches)?;
}

Type Aliases

AliasDefinitionDescription
Result<T>std::result::Result<T, LibmagicError>Library result type

Re-exports

The following types are re-exported from the root module for convenience:

#![allow(unused)]
fn main() {
// AST types
pub use parser::ast::{Endianness, MagicRule, OffsetSpec, Operator, StrengthModifier, TypeKind, Value};

// Evaluator types
pub use evaluator::{EvaluationContext, MatchResult};

// Error types
pub use error::{EvaluationError, LibmagicError, ParseError};
}

Thread Safety

  • MagicDatabase is not Send or Sync by default due to internal state
  • EvaluationConfig is Send + Sync (plain data)
  • For multi-threaded use, create separate MagicDatabase instances per thread or use appropriate synchronization

Version Compatibility

  • Minimum Rust Version: 1.85
  • Edition: 2024
  • License: Apache-2.0
  • Current Version: 0.5.0

Breaking Changes in v0.5.0

  • TypeKind enum: Added Float { endian } and Double { endian } variants for IEEE 754 floating-point support
  • TypeKind::String discriminant changed from 4 to 6 to accommodate new float types
  • Value enum: Added Float(f64) variant for floating-point values
  • Value enum: No longer derives Eq trait (only PartialEq is available due to floating-point values)
  • RuleMatch struct: Added type_kind: TypeKind field to indicate the type used for matching

Breaking Changes in v0.2.0

  • TypeKind::Byte changed from a unit variant to a struct variant Byte { signed } to support explicit signedness
  • Added comparison operators: LessThan, GreaterThan, LessEqual, GreaterEqual to the Operator enum (breaking change due to exhaustive enum)

For complete API documentation with examples, run:

cargo doc --open