1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
/*!
Small crate to infer file and MIME type by checking the
[magic number](https://en.wikipedia.org/wiki/Magic_number_(programming)) signature.
# Examples
### Get the type of a buffer
```rust
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");
assert_eq!(kind.matcher_type(), infer::MatcherType::Image);
```
### Check file type by path
```rust
# #[cfg(feature = "std")]
# fn run() {
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
```rust
let buf = [0xFF, 0xD8, 0xFF, 0xAA];
assert!(infer::image::is_jpeg(&buf));
```
### Check for specific type class
```rust
let buf = [0xFF, 0xD8, 0xFF, 0xAA];
assert!(infer::is_image(&buf));
```
### Adds a custom file type matcher
Here we actually need to use the `Infer` struct to be able to declare custom matchers.
```rust
# #[cfg(feature = "alloc")]
# fn run() {
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).unwrap();
assert_eq!(kind.mime_type(), "custom/foo");
assert_eq!(kind.extension(), "foo");
# }
```
*/
#![crate_name = "infer"]
#![doc(html_root_url = "https://docs.rs/infer/latest")]
#![forbid(unsafe_code)]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "alloc")]
extern crate alloc;
mod map;
mod matchers;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::fmt;
#[cfg(feature = "std")]
use std::fs::File;
#[cfg(feature = "std")]
use std::io::{self, Read};
#[cfg(feature = "std")]
use std::path::Path;
pub use map::MatcherType;
use map::{WrapMatcher, MATCHER_MAP};
/// All the supported matchers categorized and exposed as functions
pub use matchers::*;
/// Matcher function
pub type Matcher = fn(buf: &[u8]) -> bool;
/// Generic information for a type
#[derive(Copy, Clone)]
pub struct Type {
matcher_type: MatcherType,
mime_type: &'static str,
extension: &'static str,
matcher: WrapMatcher,
}
impl Type {
pub(crate) const fn new_static(
matcher_type: MatcherType,
mime_type: &'static str,
extension: &'static str,
matcher: WrapMatcher,
) -> Self {
Self {
matcher_type,
mime_type,
extension,
matcher,
}
}
/// Returns a new `Type` with matcher and extension.
pub fn new(
matcher_type: MatcherType,
mime_type: &'static str,
extension: &'static str,
matcher: Matcher,
) -> Self {
Self::new_static(matcher_type, mime_type, extension, WrapMatcher(matcher))
}
/// Returns the type of matcher
///
/// # Examples
///
/// ```rust
/// let info = infer::Infer::new();
/// let buf = [0xFF, 0xD8, 0xFF, 0xAA];
/// let kind = info.get(&buf).expect("file type is known");
///
/// assert_eq!(kind.matcher_type(), infer::MatcherType::Image);
/// ```
pub const fn matcher_type(&self) -> MatcherType {
self.matcher_type
}
/// Returns the mime type
pub const fn mime_type(&self) -> &'static str {
self.mime_type
}
/// Returns the file extension
pub const fn extension(&self) -> &'static str {
self.extension
}
/// Checks if buf matches this Type
fn matches(&self, buf: &[u8]) -> bool {
(self.matcher.0)(buf)
}
}
impl fmt::Debug for Type {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Type")
.field("matcher_type", &self.matcher_type)
.field("mime_type", &self.mime_type)
.field("extension", &self.extension)
.finish()
}
}
impl fmt::Display for Type {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.mime_type, f)
}
}
impl PartialEq for Type {
fn eq(&self, other: &Self) -> bool {
self.matcher_type == other.matcher_type
&& self.mime_type == other.mime_type
&& self.extension == other.extension
}
}
/// Infer allows to use a custom set of `Matcher`s for infering a MIME type.
///
/// Most operations can be done by using the _top level functions_, but when custom matchers
/// are needed every call has to go through the `Infer` struct to be able
/// to see the custom matchers.
pub struct Infer {
#[cfg(feature = "alloc")]
mmap: Vec<Type>,
}
impl Infer {
/// Initialize a new instance of the infer struct.
pub const fn new() -> Infer {
#[cfg(feature = "alloc")]
return Infer { mmap: Vec::new() };
#[cfg(not(feature = "alloc"))]
return Infer {};
}
fn iter_matchers(&self) -> impl Iterator<Item = &Type> {
let mmap = MATCHER_MAP.iter();
#[cfg(feature = "alloc")]
return self.mmap.iter().chain(mmap);
#[cfg(not(feature = "alloc"))]
return mmap;
}
/// Returns the file type of the buffer.
///
/// # Examples
///
/// ```rust
/// let info = infer::Infer::new();
/// let buf = [0xFF, 0xD8, 0xFF, 0xAA];
/// let kind = info.get(&buf).expect("file type is known");
///
/// assert_eq!(kind.mime_type(), "image/jpeg");
/// assert_eq!(kind.extension(), "jpg");
/// ```
pub fn get(&self, buf: &[u8]) -> Option<Type> {
self.iter_matchers().find(|kind| kind.matches(buf)).copied()
}
/// Returns the file type of the file given a path.
///
/// # Examples
///
/// See [`get_from_path`](./fn.get_from_path.html).
#[cfg(feature = "std")]
pub fn get_from_path<P: AsRef<Path>>(&self, path: P) -> io::Result<Option<Type>> {
let file = File::open(path)?;
let limit = file
.metadata()
.map(|m| std::cmp::min(m.len(), 8192) as usize + 1)
.unwrap_or(0);
let mut bytes = Vec::with_capacity(limit);
file.take(8192).read_to_end(&mut bytes)?;
Ok(self.get(&bytes))
}
/// Determines whether a buffer is of given extension.
///
/// # Examples
///
/// See [`is`](./fn.is.html).
pub fn is(&self, buf: &[u8], extension: &str) -> bool {
self.iter_matchers()
.any(|kind| kind.extension() == extension && kind.matches(buf))
}
/// Determines whether a buffer is of given mime type.
///
/// # Examples
///
/// See [`is_mime`](./fn.is_mime.html).
pub fn is_mime(&self, buf: &[u8], mime_type: &str) -> bool {
self.iter_matchers()
.any(|kind| kind.mime_type() == mime_type && kind.matches(buf))
}
/// Returns whether an extension is supported.
///
/// # Examples
///
/// See [`is_supported`](./fn.is_supported.html).
pub fn is_supported(&self, extension: &str) -> bool {
self.iter_matchers()
.any(|kind| kind.extension() == extension)
}
/// Returns whether a mime type is supported.
///
/// # Examples
///
/// See [`is_mime_supported`](./fn.is_mime_supported.html).
pub fn is_mime_supported(&self, mime_type: &str) -> bool {
self.iter_matchers()
.any(|kind| kind.mime_type() == mime_type)
}
/// Determines whether a buffer is an application type.
///
/// # Examples
///
/// See [`is_app`](./fn.is_app.html).
pub fn is_app(&self, buf: &[u8]) -> bool {
self.is_type(buf, MatcherType::App)
}
/// Determines whether a buffer is an archive type.
///
/// # Examples
///
/// See [`is_archive`](./fn.is_archive.html).
pub fn is_archive(&self, buf: &[u8]) -> bool {
self.is_type(buf, MatcherType::Archive)
}
/// Determines whether a buffer is an audio type.
///
/// # Examples
///
/// See [`is_audio`](./fn.is_audio.html).
pub fn is_audio(&self, buf: &[u8]) -> bool {
self.is_type(buf, MatcherType::Audio)
}
/// Determines whether a buffer is a book type.
///
/// # Examples
///
/// See [`is_book`](./fn.is_book.html).
pub fn is_book(&self, buf: &[u8]) -> bool {
self.is_type(buf, MatcherType::Book)
}
/// Determines whether a buffer is a document type.
///
/// # Examples
///
/// See [`is_document`](./fn.is_document.html).
pub fn is_document(&self, buf: &[u8]) -> bool {
self.is_type(buf, MatcherType::Doc)
}
/// Determines whether a buffer is a font type.
///
/// # Examples
///
/// See [`is_font`](./fn.is_font.html).
pub fn is_font(&self, buf: &[u8]) -> bool {
self.is_type(buf, MatcherType::Font)
}
/// Determines whether a buffer is an image type.
///
/// # Examples
///
/// See [`is_image`](./fn.is_image.html).
pub fn is_image(&self, buf: &[u8]) -> bool {
self.is_type(buf, MatcherType::Image)
}
/// Determines whether a buffer is a video type.
///
/// # Examples
///
/// See [`is_video`](./fn.is_video.html).
pub fn is_video(&self, buf: &[u8]) -> bool {
self.is_type(buf, MatcherType::Video)
}
/// Determines whether a buffer is one of the custom types added.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "alloc")]
/// # fn run() {
/// 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];
/// assert!(info.is_custom(&buf));
/// # }
/// ```
pub fn is_custom(&self, buf: &[u8]) -> bool {
self.is_type(buf, MatcherType::Custom)
}
/// Adds a custom matcher.
///
/// Custom matchers are matched in order of addition and before
/// the default set of matchers.
///
/// # Examples
///
/// ```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 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");
/// ```
#[cfg(feature = "alloc")]
pub fn add(&mut self, mime_type: &'static str, extension: &'static str, m: Matcher) {
self.mmap.push(Type::new_static(
MatcherType::Custom,
mime_type,
extension,
WrapMatcher(m),
));
}
fn is_type(&self, buf: &[u8], matcher_type: MatcherType) -> bool {
self.iter_matchers()
.any(|kind| kind.matcher_type() == matcher_type && kind.matches(buf))
}
}
impl Default for Infer {
fn default() -> Self {
Infer::new()
}
}
static INFER: Infer = Infer::new();
/// Returns the file type of the buffer.
///
/// # Examples
///
/// ```rust
/// let info = infer::Infer::new();
/// let buf = [0xFF, 0xD8, 0xFF, 0xAA];
/// let kind = info.get(&buf).expect("file type is known");
///
/// assert_eq!(kind.mime_type(), "image/jpeg");
/// assert_eq!(kind.extension(), "jpg");
/// ```
pub fn get(buf: &[u8]) -> Option<Type> {
INFER.get(buf)
}
/// Returns the file type of the file given a path.
///
/// # Errors
///
/// Returns an error if we fail to read the path.
///
/// # Examples
///
/// ```rust
/// 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");
/// ```
#[cfg(feature = "std")]
pub fn get_from_path<P: AsRef<Path>>(path: P) -> io::Result<Option<Type>> {
INFER.get_from_path(path)
}
/// Determines whether a buffer is of given extension.
///
/// # Examples
///
/// ```rust
/// let buf = [0xFF, 0xD8, 0xFF, 0xAA];
/// assert!(infer::is(&buf, "jpg"));
/// ```
pub fn is(buf: &[u8], extension: &str) -> bool {
INFER.is(buf, extension)
}
/// Determines whether a buffer is of given mime type.
///
/// # Examples
///
/// ```rust
/// let buf = [0xFF, 0xD8, 0xFF, 0xAA];
/// assert!(infer::is_mime(&buf, "image/jpeg"));
/// ```
pub fn is_mime(buf: &[u8], mime_type: &str) -> bool {
INFER.is_mime(buf, mime_type)
}
/// Returns whether an extension is supported.
///
/// # Examples
///
/// ```rust
/// assert!(infer::is_supported("jpg"));
/// ```
pub fn is_supported(extension: &str) -> bool {
INFER.is_supported(extension)
}
/// Returns whether a mime type is supported.
///
/// # Examples
///
/// ```rust
/// assert!(infer::is_mime_supported("image/jpeg"));
/// ```
pub fn is_mime_supported(mime_type: &str) -> bool {
INFER.is_mime_supported(mime_type)
}
/// Determines whether a buffer is an application type.
///
/// # Examples
///
/// ```rust
/// use std::fs;
/// assert!(infer::is_app(&fs::read("testdata/sample.wasm").unwrap()));
/// ```
pub fn is_app(buf: &[u8]) -> bool {
INFER.is_app(buf)
}
/// Determines whether a buffer is an archive type.
/// # Examples
///
/// ```rust
/// use std::fs;
/// assert!(infer::is_archive(&fs::read("testdata/sample.pdf").unwrap()));
/// ```
pub fn is_archive(buf: &[u8]) -> bool {
INFER.is_archive(buf)
}
/// Determines whether a buffer is an audio type.
///
/// # Examples
///
/// ```rust
/// // mp3
/// let v = [0xff, 0xfb, 0x90, 0x44, 0x00];
/// assert!(infer::is_audio(&v));
/// ```
pub fn is_audio(buf: &[u8]) -> bool {
INFER.is_audio(buf)
}
/// Determines whether a buffer is a book type.
///
/// # Examples
///
/// ```rust
/// use std::fs;
/// assert!(infer::is_book(&fs::read("testdata/sample.epub").unwrap()));
/// ```
pub fn is_book(buf: &[u8]) -> bool {
INFER.is_book(buf)
}
/// Determines whether a buffer is a document type.
///
/// # Examples
///
/// ```rust
/// use std::fs;
/// assert!(infer::is_document(&fs::read("testdata/sample.docx").unwrap()));
/// ```
pub fn is_document(buf: &[u8]) -> bool {
INFER.is_document(buf)
}
/// Determines whether a buffer is a font type.
///
/// # Examples
///
/// ```rust
/// use std::fs;
/// assert!(infer::is_font(&fs::read("testdata/sample.ttf").unwrap()));
/// ```
pub fn is_font(buf: &[u8]) -> bool {
INFER.is_font(buf)
}
/// Determines whether a buffer is an image type.
///
/// # Examples
///
/// ```rust
/// let v = [0xFF, 0xD8, 0xFF, 0xAA];
/// assert!(infer::is_image(&v));
/// ```
pub fn is_image(buf: &[u8]) -> bool {
INFER.is_image(buf)
}
/// Determines whether a buffer is a video type.
///
/// # Examples
///
/// ```rust
/// use std::fs;
/// assert!(infer::is_video(&fs::read("testdata/sample.mov").unwrap()));
/// ```
pub fn is_video(buf: &[u8]) -> bool {
INFER.is_video(buf)
}
#[cfg(test)]
mod tests {
#[cfg(feature = "alloc")]
use super::Infer;
#[test]
fn test_get_unknown() {
let buf = [];
assert!(crate::get(&buf).is_none());
}
#[test]
fn test_get_jpeg() {
let buf = [0xFF, 0xD8, 0xFF, 0xAA];
let kind = crate::get(&buf).expect("file type is known");
assert_eq!(kind.extension(), "jpg");
assert_eq!(kind.mime_type(), "image/jpeg");
}
#[test]
fn test_matcher_type() {
let buf = [0xFF, 0xD8, 0xFF, 0xAA];
let kind = crate::get(&buf).expect("file type is known");
assert_eq!(kind.matcher_type(), crate::MatcherType::Image);
}
#[cfg(feature = "alloc")]
#[test]
fn test_custom_matcher_ordering() {
// overrides jpeg matcher
fn foo_matcher(buf: &[u8]) -> bool {
buf.len() > 2 && buf[0] == 0xFF && buf[1] == 0xD8 && buf[2] == 0xFF
}
// overrides png matcher
fn bar_matcher(buf: &[u8]) -> bool {
buf.len() > 3 && buf[0] == 0x89 && buf[1] == 0x50 && buf[2] == 0x4E && buf[3] == 0x47
}
let mut info = Infer::new();
info.add("custom/foo", "foo", foo_matcher);
info.add("custom/bar", "bar", bar_matcher);
let buf_foo = &[0xFF, 0xD8, 0xFF];
let typ = info.get(buf_foo).expect("type is matched");
assert_eq!(typ.mime_type(), "custom/foo");
assert_eq!(typ.extension(), "foo");
let buf_bar = &[0x89, 0x50, 0x4E, 0x47];
let typ = info.get(buf_bar).expect("type is matched");
assert_eq!(typ.mime_type(), "custom/bar");
assert_eq!(typ.extension(), "bar");
}
}