From c0fffbb21235f11b1947e11e66cb69ca6c3c5421 Mon Sep 17 00:00:00 2001 From: Vincent Flyson Date: Fri, 23 Aug 2019 18:48:08 -0400 Subject: [PATCH] Get rid of mime-sniffer dependency --- Cargo.toml | 5 ++-- src/utils.rs | 64 +++++++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 63 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index c0ae12f..11b9328 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "monolith" -version = "2.0.6" +version = "2.0.7" authors = ["Sunshine "] description = "CLI tool to save webpages as a single HTML file" @@ -9,8 +9,7 @@ base64 = "0.10.1" clap = "2.33.0" html5ever = "0.24.0" indicatif = "0.11.0" -mime-sniffer = "0.1.2" +lazy_static = "1.3.0" regex = "1.2.1" reqwest = "0.9.20" url = "2.1.0" -lazy_static = "1.3.0" diff --git a/src/utils.rs b/src/utils.rs index f459a02..2f91337 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,8 +1,31 @@ extern crate base64; -extern crate mime_sniffer; use self::base64::encode; -use self::mime_sniffer::MimeTypeSniffer; + +static MAGIC: [[&[u8]; 2]; 19] = [ + // Image + [b"GIF87a", b"image/gif"], + [b"GIF89a", b"image/gif"], + [b"\xFF\xD8\xFF", b"image/jpeg"], + [b"\x89PNG\x0D\x0A\x1A\x0A", b"image/png"], + [b" String { let mimetype = if mime == "" { @@ -14,7 +37,16 @@ pub fn data_to_dataurl(mime: &str, data: &[u8]) -> String { } fn detect_mimetype(data: &[u8]) -> String { - data.sniff_mime_type().unwrap_or("").to_string() + let mut re = String::new(); + + for item in MAGIC.iter() { + if data.starts_with(item[0]) { + re = String::from_utf8(item[1].to_vec()).unwrap(); + break; + } + } + + re } #[cfg(test)] @@ -31,4 +63,30 @@ mod tests { "data:application/javascript;base64,dmFyIHdvcmQgPSAnaGVsbG8nOwphbGVydCh3b3JkKTsK" ); } + + #[test] + fn test_detect_mimetype() { + // Image + assert_eq!(detect_mimetype(b"GIF87a"), "image/gif"); + assert_eq!(detect_mimetype(b"GIF89a"), "image/gif"); + assert_eq!(detect_mimetype(b"\xFF\xD8\xFF"), "image/jpeg"); + assert_eq!(detect_mimetype(b"\x89PNG\x0D\x0A\x1A\x0A"), "image/png"); + assert_eq!(detect_mimetype(b"