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
).
https://docs.rs/infer
This crate works with Cargo and is on
crates.io. Add it to your Cargo.toml
like so:
toml
[dependencies]
infer = "0.1"
```rust use infer::Infer;
let v = vec![0xFF, 0xD8, 0xFF, 0xAA]; let info = Infer::new();
asserteq!("image/jpeg", info.get(&v).unwrap().mime); asserteq!("jpg", info.get(&v).unwrap().ext); ```
```rust use infer::Infer;
let info = Infer::new(); let res = info.getfrompath("testdata/sample.jpg");
assert!(res.isok()); let o = res.unwrap(); assert!(o.issome()); let typ = o.unwrap();
asserteq!("image/jpeg", typ.mime); asserteq!("jpg", typ.ext); ```
rust
let v = vec![0xFF, 0xD8, 0xFF, 0xAA];
assert!(infer::image::is_jpeg(&v));
Note individual matcher functions do not require init
rust
let v = vec![0xFF, 0xD8, 0xFF, 0xAA];
let info = infer::Infer::new();
assert!(info.is_image(&v));
```rust 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 v = vec![0x10, 0x11, 0x12, 0x13]; let res = info.get(&v).unwrap();
asserteq!("custom/foo", res.mime); asserteq!("foo", res.ext); ```
image/jpeg
image/png
image/gif
image/webp
image/x-canon-cr2
image/tiff
image/bmp
image/heif
image/vnd.ms-photo
image/vnd.adobe.photoshop
image/vnd.microsoft.icon
video/mp4
video/x-m4v
video/x-matroska
video/webm
video/quicktime
video/x-msvideo
video/x-ms-wmv
video/mpeg
video/x-flv
audio/midi
audio/mpeg
audio/m4a
audio/ogg
audio/x-flac
audio/x-wav
audio/amr
audio/aac
application/epub+zip
application/zip
application/x-tar
application/vnd.rar
application/gzip
application/x-bzip2
application/x-7z-compressed
application/x-xz
application/pdf
application/x-shockwave-flash
application/rtf
application/octet-stream
application/postscript
application/vnd.sqlite3
application/x-nintendo-nes-rom
application/x-google-chrome-extension
application/vnd.ms-cab-compressed
application/vnd.debian.binary-package
application/x-unix-archive
application/x-compress
application/x-lzip
application/x-rpm
application/dicom
application/zstd
application/msword
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/vnd.ms-excel
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.ms-powerpoint
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/font-woff
application/font-woff
application/font-sfnt
application/font-sfnt
application/wasm
application/vnd.microsoft.portable-executable
application/x-executable
application/llvm
application/java
doc
, ppt
, xls
all have the same magic number so it's not possible to tell which one just based on the binary data. doc
is returned for all.MIT