Documents
API_REFERENCE
API_REFERENCE
Type
External
Status
Published
Created
Mar 1, 2026
Updated
Apr 25, 2026
Updated by
Dosu Bot
Source
View

API Reference - libmagic-rs#

A comprehensive reference for the libmagic-rs library API.

Table of Contents#


Core Types#

MagicDatabase#

The main interface for loading magic rules and evaluating files.

use libmagic_rs::MagicDatabase;

The struct contains internal fields:

Field (Internal)TypeDescription
rulesVec<MagicRule>Top-level magic rules
name_tableArc<NameTable>Named subroutine definitions extracted from name rules
root_rulesArc<[MagicRule]>Shared immutable slice of top-level rules for indirect re-entry
configEvaluationConfigEvaluation configuration
source_pathOption<PathBuf>Optional path to the source magic file or directory
mime_mapperMimeMapperMIME type mapper

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#

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::default()
    .with_timeout_ms(Some(5000))
    .with_mime_types(true);
let db = MagicDatabase::with_builtin_rules_and_config(config)?;

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

EvaluationConfig#

Configuration for rule evaluation behavior.

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#

// 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)

Builder Methods#

EvaluationConfig is #[non_exhaustive] (as of v0.6.0); use builder-style setters:

let config = EvaluationConfig::default()
    .with_max_recursion_depth(25)
    .with_max_string_length(16384);

// Validate configuration
config.validate()?;

EvaluationResult#

Result of magic rule evaluation.

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#

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);

EvaluationMetadata#

Diagnostic information about the evaluation process.

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

Error Handling#

LibmagicError#

Main error type for all library operations.

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#

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

Parser Module#

Parser Functions#

parse_text_magic_file#

Parses a complete magic file from raw text input.

use libmagic_rs::parser::parse_text_magic_file;

let magic = "0 string \\x7fELF ELF file";
let parsed = parse_text_magic_file(magic)?;
assert_eq!(parsed.rules.len(), 1);

Returns Result<ParsedMagic, ParseError> where ParsedMagic contains the top-level rules and the name table.

load_magic_file#

Loads magic rules from a file or directory, automatically detecting the format.

use libmagic_rs::parser::load_magic_file;

let parsed = load_magic_file("/usr/share/misc/magic")?;
println!("Loaded {} magic rules", parsed.rules.len());

Returns Result<ParsedMagic, ParseError>.

load_magic_directory#

Loads and merges magic rules from all files in a directory.

use libmagic_rs::parser::load_magic_directory;

let parsed = load_magic_directory("/usr/share/file/magic.d")?;
println!("Loaded {} rules from directory", parsed.rules.len());

Returns Result<ParsedMagic, ParseError>.

AST Types#

ParsedMagic#

Result of parsing a text magic file.

use libmagic_rs::parser::ParsedMagic;

Contains the top-level rule list with any name-declared subroutines hoisted into a separate name table keyed by identifier.

FieldTypeDescription
rulesVec<MagicRule>Top-level rules after Name subroutines have been removed
name_tableNameTable (internal)Extracted name subroutine definitions, consulted by the evaluator when a rule of type TypeKind::Meta(MetaType::Use(_)) is reached

MagicRule#

Represents a parsed magic rule.

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
value_transformOption<ValueTransform>Optional value transformation (v0.6.0)

OffsetSpec#

Offset specification for locating data.

use libmagic_rs::OffsetSpec;
VariantDescription
Absolute(i64)Absolute offset from file start
Indirect { base_offset, pointer_type, adjustment, endian, base_relative, adjustment_op, result_relative }Indirect through pointer
Relative(i64)Relative to previous match
FromEnd(i64)Offset from end of file

v0.6.0 Changes: The Indirect variant added three fields: base_relative: bool, adjustment_op: Option<AdjustmentOp>, and result_relative: bool to support advanced indirect offset resolution.

TypeKind#

Data type specifications.

use libmagic_rs::TypeKind;
VariantDescription
Byte { signed }Single byte with explicit signedness (changed in v0.2.0)
Short { endian, signed }16-bit integer
Long { endian, signed }32-bit integer
Quad { endian, signed }64-bit integer
Float { endian }32-bit IEEE 754 floating-point
Double { endian }64-bit IEEE 754 floating-point
Date { endian, utc }32-bit Unix timestamp (signed seconds since epoch). The endian parameter specifies byte order (LittleEndian or BigEndian), and utc is a boolean indicating whether to format as UTC or local time. Date values are formatted as "Www Mmm DD HH:MM YYYY" strings to match GNU file output.
QDate { endian, utc }64-bit Unix timestamp (signed seconds since epoch). The endian parameter specifies byte order (LittleEndian or BigEndian), and utc is a boolean indicating whether to format as UTC or local time. QDate values are formatted as "Www Mmm DD HH:MM YYYY" strings to match GNU file output.
String { max_length }String data
Meta(MetaType)Meta-type directives for control flow, conditional execution, and named subroutines. Variants: Default, Clear, Name, Use, Indirect, Offset. See MetaType for details.
MetaType#

Control-flow directive variants carried by TypeKind::Meta.

use libmagic_rs::parser::ast::MetaType;
VariantDescription
DefaultFires when no sibling at the same indentation level has matched
ClearResets the sibling-matched flag so a later default sibling can fire even if an earlier sibling matched
Name(id)Declares a named subroutine with identifier id that can be invoked later via Use
Use(id)Invokes a named subroutine previously declared via Name
IndirectRe-applies the entire magic database at the resolved offset
OffsetReports the current file offset as Value::Uint(pos) rather than reading a typed value from the buffer; operator must be AnyValue (x)
64-bit Integer Types#

The Quad variant supports six endian-signedness combinations:

Type SpecifierEndiannessSignednessDescription
quadNativeSignedNative-endian signed 64-bit integer
uquadNativeUnsignedNative-endian unsigned 64-bit integer
lequadLittleSignedLittle-endian signed 64-bit integer
ulequadLittleUnsignedLittle-endian unsigned 64-bit integer
bequadBigSignedBig-endian signed 64-bit integer
ubequadBigUnsignedBig-endian unsigned 64-bit integer

Version Note: In v0.2.0, the Byte variant changed from a unit variant to a struct variant with a signed field.

32-bit Floating-Point Types#

The Float variant supports three endian variants:

Type SpecifierEndiannessDescription
floatNativeNative-endian 32-bit IEEE 754 float
lefloatLittleLittle-endian 32-bit IEEE 754 float
befloatBigBig-endian 32-bit IEEE 754 float
64-bit Floating-Point Types#

The Double variant supports three endian variants:

Type SpecifierEndiannessDescription
doubleNativeNative-endian 64-bit IEEE 754 double
ledoubleLittleLittle-endian 64-bit IEEE 754 double
bedoubleBigBig-endian 64-bit IEEE 754 double

Operator#

Comparison operators.

use libmagic_rs::Operator;
VariantDescription
EqualEquality comparison (= or ==)
NotEqualInequality comparison (!= or <>)
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 (&)
BitwiseAndMask(u64)Bitwise AND with mask value
BitwiseXorBitwise XOR (^)
BitwiseNotBitwise NOT/complement (~)
AnyValueMatch any value unconditionally (x)

Version Note: The comparison operators LessThan, GreaterThan, LessEqual, and GreaterEqual were added in v0.2.0.

Floating-Point Comparison Semantics#

Equality operators (Equal, NotEqual) use epsilon-aware comparison for Value::Float operands: two floats are considered equal when |a - b| <= f64::EPSILON. NaN is never equal to anything (including itself), and infinities are equal only to the same-signed infinity.

Ordering operators (LessThan, GreaterThan, LessEqual, GreaterEqual) use IEEE 754 partial_cmp semantics. All NaN comparisons return false (NaN is not comparable to any value).

Value#

Value types for matching.

use libmagic_rs::Value;
VariantDescription
Uint(u64)Unsigned integer
Int(i64)Signed integer
Float(f64)64-bit floating-point value
Bytes(Vec<u8>)Byte sequence
String(String)String value (also used for date/timestamp values formatted as human-readable strings)

Note: Value implements PartialEq but not Eq due to IEEE 754 NaN semantics (NaN is not equal to itself).

Endianness#

Byte order specification.

use libmagic_rs::Endianness;
VariantDescription
LittleLittle-endian
BigBig-endian
NativeSystem native

Evaluator Module#

EvaluationContext#

Maintains evaluation state during rule processing.

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
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

v0.6.0 Changes: The increment_recursion_depth() and decrement_recursion_depth() methods were removed.

MatchResult (Evaluator)#

Result from internal evaluation.

use libmagic_rs::evaluator::MatchResult;
FieldTypeDescription
messageStringMatch description (printf-style format specifiers like %d, %x, %s are substituted with the matched value)
offsetusizeMatch offset
levelu32Rule level
valueValueMatched value
confidencef64Confidence score

Output Module#

MatchResult (Output)#

Structured match result for output formatting.

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#

// 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#

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:

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

Feature Flags#

Currently, libmagic-rs does not have optional feature flags. All functionality is included by default.


Thread Safety#

  • MagicDatabase implements Send + Sync as of v0.6.0 and can be shared across threads
  • EvaluationConfig is Send + Sync (plain data)
  • For optimal performance in multi-threaded scenarios, consider cloning the database or using Arc<MagicDatabase>

Version Compatibility#

  • Minimum Rust Version: 1.89
  • Edition: 2024
  • License: Apache-2.0

Breaking Changes#

v0.6.0#

EvaluationConfig is now #[non_exhaustive]:

  • Struct literal construction (EvaluationConfig { field: value, .. }) is no longer supported outside the crate
  • Use builder-style setters: EvaluationConfig::default().with_max_recursion_depth(25).with_timeout_ms(Some(5000))
  • Available setters: with_max_recursion_depth(), with_max_string_length(), with_stop_at_first_match(), with_mime_types(), with_timeout_ms()

MagicRule gains value_transform field:

  • The MagicRule struct has a new value_transform: Option<ValueTransform> field
  • Existing code constructing MagicRule with struct literals must add this field

OffsetSpec::Indirect gains new fields:

  • The Indirect variant added: base_relative: bool, adjustment_op: Option<AdjustmentOp>, result_relative: bool
  • Existing pattern matches on Indirect must account for these fields or use wildcard patterns

Multiple enums marked #[non_exhaustive]:

  • OffsetSpec, LibmagicError, IoError, Operator, TypeReadError, ParseError, Value, TypeKind, EvaluationError
  • External match arms on these enums must include a wildcard pattern (_ =>)

EvaluationContext method removals:

  • increment_recursion_depth() and decrement_recursion_depth() removed (internal recursion tracking changed)

MagicDatabase now implements Send + Sync:

  • MagicDatabase can now be shared across threads safely

v0.5.0#

Meta-type directives and format substitution (PR #230):

  • Parser functions parse_text_magic_file, load_magic_file, and load_magic_directory return Result<ParsedMagic, ParseError> instead of Result<Vec<MagicRule>, ParseError>. ParsedMagic is a struct with fields rules: Vec<MagicRule> and name_table: NameTable.
  • MagicDatabase struct now includes internal fields root_rules: Arc<[MagicRule]> and name_table: Arc<NameTable> to support meta-type evaluation.
  • Printf-style format substitution (%d, %x, %s, etc.) is applied to the message field in MatchResult. Messages containing literal % characters that were previously passed through verbatim will now be interpreted as format specifiers. Escape literal % as %%.
  • TypeKind::Meta(MetaType) enum added with variants Default, Clear, Name, Use, Indirect, Offset.
API_REFERENCE | Dosu