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

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;

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 {
    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")?;

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)

Validation#

let config = EvaluationConfig {
    max_recursion_depth: 25,
    max_string_length: 16384,
    ..Default::default()
};

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

AST Types#

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

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 }Indirect through pointer
Relative(i64)Relative to previous match
FromEnd(i64)Offset from end of file

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

use libmagic_rs::evaluator::MatchResult;
FieldTypeDescription
messageStringMatch description
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 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.89
  • Edition: 2024
  • License: Apache-2.0