Skip to main content

Crate pure_magic

Crate pure_magic 

Source
Expand description

§pure-magic: A pure and safe Rust Reimplementation of libmagic

Unlike many file identification crates, pure-magic is highly compatible with the standard magic rule format, allowing seamless reuse of existing rules. This makes it an ideal drop-in replacement for crates relying on libmagic C bindings, where memory safety is critical.

Key Features:

  • File type detection
  • MIME type inference
  • Custom magic rule parsing

§Installation

Add pure-magic to your Cargo.toml:

[dependencies]
pure-magic = "0.1"  # Replace with the latest version

Or add the latest version with cargo:

cargo add pure-magic

§Quick Start

§Detect File Types Programmatically

use pure_magic::{MagicDb, MagicSource, DataReader};
use std::fs::File;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut db = MagicDb::new();
    // Create a MagicSource from a file
    let rust_magic = MagicSource::open("../magic-db/src/magdir/rust")?;
    db.load(rust_magic);
    // Verification is not mandatory
    db.verify()?;

    // Detect file type
    let magic = db.first_magic_file("src/lib.rs")?;

    println!(
        "File type: {} (MIME: {}, strength: {})",
        magic.message(),
        magic.mime_type(),
        magic.strength()
    );
    Ok(())
}

§Get All Matching Rules

use pure_magic::{MagicDb, MagicSource, DataReader};
use std::fs::File;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut db = MagicDb::new();
    // Create a MagicSource from a file
    let rust_magic = MagicSource::open("../magic-db/src/magdir/rust")?;
    db.load(rust_magic);

    // Get all matching rules, sorted by strength
    let magics = db.all_magics_file("src/lib.rs")?;

    // Must contain rust file magic and default text magic
    assert!(magics.len() > 1);

    for magic in magics {
        println!(
            "Match: {} (strength: {}, source: {})",
            magic.message(),
            magic.strength(),
            magic.source().unwrap_or("unknown")
        );
    }
    Ok(())
}

§Serialize a Database to Disk

use pure_magic::{MagicDb, MagicSource};
use std::fs::File;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut db = MagicDb::new();
    // Create a MagicSource from a file
    let rust_magic = MagicSource::open("../magic-db/src/magdir/rust")?;
    db.load(rust_magic);

    // Serialize the database to a file
    let mut output = File::create("/tmp/compiled.db")?;
    db.serialize(&mut output)?;

    println!("Database saved to file");
    Ok(())
}

§Deserialize a Database

use pure_magic::{MagicDb, MagicSource};
use std::fs::File;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut db = MagicDb::new();
    // Create a MagicSource from a file
    let rust_magic = MagicSource::open("../magic-db/src/magdir/rust")?;
    db.load(rust_magic);

    // Serialize the database in a vector
    let mut ser = vec![];
    db.serialize(&mut ser)?;
    println!("Database saved to vector");

    // We deserialize from slice
    let db = MagicDb::deserialize(&mut ser.as_slice())?;

    assert!(!db.rules().is_empty());

    Ok(())
}

§License

This project is dual-licensed under either:

  • GPL-3.0
  • BSD-2-Clause

§Contributing

Contributions are welcome! Open an issue or submit a pull request.

§Acknowledgments

  • Inspired by the original libmagic (part of the file command).

Re-exports§

pub use readers::DataReader;

Modules§

readers
Data readers for magic number detection.

Structs§

Magic
Represents a file magic detection result
MagicDb
Represents a database of MagicRule
MagicRule
Represents a parsed magic rule
MagicSource
A parsed source of magic rules

Enums§

Error
Represents all possible errors that can occur during file type detection and processing.
StreamKind
Represents the kind of encountered data
TextEncoding
The encoding encountered for a given StreamKind::Text

Constants§

DEFAULT_BIN_MIMETYPE
Default mimetype for un-identified binary data
DEFAULT_TEXT_MIMETYPE
Default mimetype for un-identified text data
FILE_BYTES_MAX
Maximum number of bytes to read for search tests.