bojand / infer

Small crate to infer file and MIME type by checking the magic number signature
MIT License
270 stars 26 forks source link
filetype hacktoberfest magic-number mime

infer

Build Status crates version documentation

Small crate to infer file and MIME type by checking the magic number signature.

Adaptation of filetype Go package ported to Rust.

Does not require magic file database (i.e. /etc/magic).

Features

Installation

This crate works with Cargo and is on crates.io. Add it to your Cargo.toml like so:

[dependencies]
infer = "0.3"

If you are not using the custom matcher or the file type from file path functionality you can make this crate even lighter by importing it with no default features, like so:

[dependencies]
infer = { version = "0.3", default-features = false }

no_std and no_alloc support

This crate supports no_std and no_alloc environments. std support is enabled by default, but you can disable it by importing the crate with no default features, making it depend only on the Rust core Library.

alloc has to be enabled to be able to use custom file matchers.

std has to be enabled to be able to get the file type from a file given the file path.

Examples

Most operations can be done via top level functions, but they are also available through the Infer struct, which must be used when dealing custom matchers.

Get the type of a buffer

let buf = [0xFF, 0xD8, 0xFF, 0xAA];
let kind = infer::get(&buf).expect("file type is known");

assert_eq!(kind.mime_type(), "image/jpeg");
assert_eq!(kind.extension(), "jpg");

Check file type by path

let kind = infer::get_from_path("testdata/sample.jpg")
    .expect("file read successfully")
    .expect("file type is known");

assert_eq!(kind.mime_type(), "image/jpeg");
assert_eq!(kind.extension(), "jpg");

Check for specific type

let buf = [0xFF, 0xD8, 0xFF, 0xAA];
assert!(infer::image::is_jpeg(&buf));

Check for specific type class

let buf = [0xFF, 0xD8, 0xFF, 0xAA];
assert!(infer::is_image(&buf));

Adds a custom file type matcher

fn custom_matcher(buf: &[u8]) -> bool {
    return buf.len() >= 3 && buf[0] == 0x10 && buf[1] == 0x11 && buf[2] == 0x12;
}

let mut info = infer::Infer::new();
info.add("custom/foo", "foo", custom_matcher);

let buf = [0x10, 0x11, 0x12, 0x13];
let kind = info.get(&buf).expect("file type is known");

assert_eq!(kind.mime_type(), "custom/foo");
assert_eq!(kind.extension(), "foo");

Supported types

Image

Video

Audio

Archive

Book

Documents

Font

Application

Known Issues

License

MIT