Search

Lib.rs

› Database interfaces
#libmagic #magic-file #mime #file-identification #identification

magic-rs

Safe Rust re-implementation of libmagic

by Quentin JEROME

  • Install
  • API reference
  • GitHub repo (qjerome)

1 unstable release

Uses new Rust 2024

0.1.0 Nov 14, 2025

#7 in #libmagic

GPL-3.0 license

255KB
6K SLoC

magic-rs: A Safe Rust Reimplementation of libmagic

This crate provides a high-performance, memory-safe alternative to the traditional libmagic (used by the file command). It supports file type detection, MIME type inference, and custom magic rule parsing.

Installation

Add magic-rs to your Cargo.toml:

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

Or add the latest version with cargo:

cargo add magic-rs

Quick Start

Detect File Types Programmatically

use magic_rs::{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)?;

    // Open a file and detect its type
    let mut file = File::open("src/lib.rs")?;
    let magic = db.magic_first(&mut file, None)?;

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

Get All Matching Rules

use magic_rs::{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)?;

    // Open a file and detect its type
    let mut file = File::open("src/lib.rs")?;

    // Get all matching rules, sorted by strength
    let magics = db.magic_all(&mut file)?;

    // 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 magic_rs::{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 magic_rs::{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 licensed under the GPL-3.0 License.

Contributing

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

Acknowledgments

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

Dependencies

~11–20MB
~296K SLoC

  • bincode 2.0+serde
  • chrono
  • csv
  • dyf+serde
  • flagset+serde
  • flate2
  • lazy-cache
  • memchr
  • pest
  • pest_derive
  • regex
  • serde+serde_derive
  • serde_json
  • tar
  • thiserror 2.0
  • tracing
  • uuid
  • dev tracing-subscriber
Related: magic-db, magic-embed, lazy-cache, pure-magic, wiza
See also: libmagic-rs, magic, mimetype-detector, magika, tika-magic, prek-identify, file-identify, bindet, palate, filemagic, magic-sys

Lib.rs is an unofficial list of Rust/Cargo crates, created by kornelski. It contains data from multiple sources, including heuristics, and manually curated data. Content of this page is not necessarily endorsed by the authors of the crate. This site is not affiliated with nor endorsed by the Rust Project. If something is missing or incorrect, please file a bug.