Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API using Read trait #76

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,27 @@ fn custom_matcher(buf: &[u8]) -> bool {
return buf.len() >= 3 && buf[0] == 0x10 && buf[1] == 0x11 && buf[2] == 0x12;
}

fn custom_matcher_read(r: &mut dyn Read) -> Result<bool> {
let mut buffer = [0; 4];
r.read_exact(&mut buffer[..])?;
Ok(custom_matcher(&buffer))
}

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

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

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

let mut f = Cursor::new(buf);
kind = info.get_read(&mut f).unwrap().expect("file type is known");

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

```

## Supported types
Expand Down
235 changes: 130 additions & 105 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,31 @@ Here we actually need to use the `Infer` struct to be able to declare custom mat

```rust
# #[cfg(feature = "alloc")]
# #[cfg(feature = "std")]
# fn run() {
use std::io::{Result, Read};

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

fn custom_matcher_read(r: &mut dyn Read) -> Result<bool> {
let mut buffer = [0; 4];
r.read_exact(&mut buffer[..])?;
Ok(custom_matcher(&buffer))
}

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

let buf = [0x10, 0x11, 0x12, 0x13, 0x14];
let mut kind = info.get(&buf).unwrap();

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

let buf = [0x10, 0x11, 0x12, 0x13];
let kind = info.get(&buf).unwrap();
let mut f = std::io::Cursor::new(buf);
kind = info.get_read(&mut f).unwrap().expect("file type is known");

assert_eq!(kind.mime_type(), "custom/foo");
assert_eq!(kind.extension(), "foo");
Expand All @@ -76,10 +91,13 @@ extern crate alloc;

mod map;
mod matchers;
mod matchtype;

#[cfg(feature = "std")]
mod read;

#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::fmt;
#[cfg(feature = "std")]
use std::fs::File;
#[cfg(feature = "std")]
Expand All @@ -88,102 +106,17 @@ use std::io::{self, Read};
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()
}
}
#[cfg(feature = "std")]
use map::{WrapMatcher, WrapReadMatcher};

impl fmt::Display for Type {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.mime_type, f)
}
}
use map::MATCHER_MAP;

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
}
}
#[cfg(feature = "std")]
pub use crate::read::*;
/// All the supported matchers categorized and exposed as functions
pub use matchers::*;
pub use matchtype::*;

/// Infer allows to use a custom set of `Matcher`s for infering a MIME type.
///
Expand Down Expand Up @@ -280,6 +213,28 @@ impl Infer {
.any(|kind| kind.extension() == extension)
}

/// Returns the type for the mime type if supported.
///
/// # Examples
///
/// See [`is_supported`](./fn.get_type_by_mime.html).
pub fn get_type_by_mime(&self, mime_type: &str) -> Option<Type> {
self.iter_matchers()
.find(|kind| kind.mime_type() == mime_type)
.copied()
}

/// Returns the type for the extension if supported.
///
/// # Examples
///
/// See [`is_supported`](./fn.get_type_by_extension.html).
pub fn get_type_by_extension(&self, extension: &str) -> Option<Type> {
self.iter_matchers()
.find(|kind| kind.extension() == extension)
.copied()
}

/// Returns whether a mime type is supported.
///
/// # Examples
Expand Down Expand Up @@ -368,13 +323,14 @@ impl Infer {
///
/// ```rust
/// # #[cfg(feature = "alloc")]
/// # #[cfg(feature = "std")]
/// # 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);
/// info.add("custom/foo", "foo", custom_matcher, None);
/// let buf = [0x10, 0x11, 0x12, 0x13];
/// assert!(info.is_custom(&buf));
/// # }
Expand All @@ -391,25 +347,37 @@ impl Infer {
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "alloc")]
/// # #[cfg(feature = "std")]
/// # 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);
/// info.add("custom/foo", "foo", custom_matcher, None);
/// 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) {
#[cfg(feature = "std")]
pub fn add(
&mut self,
mime_type: &'static str,
extension: &'static str,
m: Matcher,
rm: Option<ReadMatcher>,
) {
self.mmap.push(Type::new_static(
MatcherType::Custom,
mime_type,
extension,
WrapMatcher(m),
rm.map(WrapReadMatcher),
));
}

Expand All @@ -432,9 +400,8 @@ static INFER: Infer = Infer::new();
/// # Examples
///
/// ```rust
/// let info = infer::Infer::new();
/// let buf = [0xFF, 0xD8, 0xFF, 0xAA];
/// let kind = info.get(&buf).expect("file type is known");
/// let kind = infer::get(&buf).expect("file type is known");
///
/// assert_eq!(kind.mime_type(), "image/jpeg");
/// assert_eq!(kind.extension(), "jpg");
Expand Down Expand Up @@ -606,10 +573,43 @@ pub fn is_video(buf: &[u8]) -> bool {
INFER.is_video(buf)
}

/// Returns the file type for the mime type if supported.
///
/// # Examples
///
/// ```rust
/// let kind = infer::get_type_by_mime("image/jpeg").expect("mime type is known");
///
/// assert_eq!(kind.mime_type(), "image/jpeg");
/// assert_eq!(kind.extension(), "jpg");
/// ```
pub fn get_type_by_mime(mime_type: &str) -> Option<Type> {
INFER.get_type_by_mime(mime_type)
}

/// Returns the type for the extension if supported.
///
/// # Examples
///
/// ```rust
/// let kind = infer::get_type_by_extension("jpg").expect("extension is known");
///
/// assert_eq!(kind.mime_type(), "image/jpeg");
/// assert_eq!(kind.extension(), "jpg");
/// ```
pub fn get_type_by_extension(extension: &str) -> Option<Type> {
INFER.get_type_by_extension(extension)
}

#[cfg(test)]
mod tests {
#[cfg(feature = "alloc")]
#[cfg(feature = "std")]
use super::Infer;
#[cfg(feature = "std")]
use std::fs::File;
#[cfg(feature = "std")]
use std::io::{self, Cursor, Read};

#[test]
fn test_get_unknown() {
Expand All @@ -633,6 +633,7 @@ mod tests {
}

#[cfg(feature = "alloc")]
#[cfg(feature = "std")]
#[test]
fn test_custom_matcher_ordering() {
// overrides jpeg matcher
Expand All @@ -645,18 +646,42 @@ mod tests {
buf.len() > 3 && buf[0] == 0x89 && buf[1] == 0x50 && buf[2] == 0x4E && buf[3] == 0x47
}

fn bar_matcher_read(r: &mut dyn Read) -> io::Result<bool> {
let mut buffer = [0; 4];
r.read_exact(&mut buffer[..])?;
Ok(bar_matcher(&buffer))
}

let mut info = Infer::new();
info.add("custom/foo", "foo", foo_matcher);
info.add("custom/bar", "bar", bar_matcher);
info.add("custom/foo", "foo", foo_matcher, None);
info.add("custom/bar", "bar", bar_matcher, Some(bar_matcher_read));

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 buf_bar = &[0x89, 0x50, 0x4E, 0x47, 0x12];
let typ = info.get(buf_bar).expect("type is matched");
assert_eq!(typ.mime_type(), "custom/bar");
assert_eq!(typ.extension(), "bar");

let mut f = Cursor::new(buf_bar);
let kind = info.get_read(&mut f).unwrap().expect("type is matched");

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

#[cfg(feature = "std")]
#[test]
fn test_is_wasm_read() {
let fr = File::open("testdata/sample.wasm");
if fr.is_err() {
assert!(fr.is_err(), "{:?}", fr.unwrap_err());
}
let mut f = fr.unwrap();
let result = crate::app::is_wasm_read(&mut f).unwrap();
assert!(result);
}
}
Loading