fif/src/mimedb.rs

73 lines
1.4 KiB
Rust
Raw Normal View History

use mime_guess::Mime;
#[cfg(feature = "infer-backend")]
use std::str::FromStr;
pub trait MimeDb {
fn init() -> Self;
fn get_type(&self, data: &[u8]) -> Option<Mime>;
}
#[cfg(feature = "infer-backend")]
pub struct InferDb {
db: infer::Infer
}
#[cfg(feature = "infer-backend")]
impl MimeDb for InferDb {
fn init() -> Self {
let mut info = infer::Infer::new();
// add a random file type just to make sure adding works and such
info.add(
"image/jpeg2000",
".jp2",
|buf| {
buf.len() > 23
&& buf[0] == 0x00
&& buf[1] == 0x00
&& buf[2] == 0x00
&& buf[3] == 0x0C
&& buf[4] == 0x6A
&& buf[5] == 0x50
&& buf[6] == 0x20
&& buf[7] == 0x20
&& buf[8] == 0x0D
&& buf[9] == 0x0A
&& buf[10] == 0x87
&& buf[11] == 0x0A
&& buf[20] == 0x6A
&& buf[21] == 0x70
&& buf[22] == 0x32
&& buf[23] == 0x20
}
);
// unmut
let info = info;
Self { db: info }
}
fn get_type(&self, data: &[u8]) -> Option<Mime> {
self.db
.get(data)
.map(|f| Mime::from_str(f.mime_type()).unwrap())
}
}
#[cfg(feature = "xdg-mime-backend")]
pub struct XdgDb {
db: xdg_mime::SharedMimeInfo
}
#[cfg(feature = "xdg-mime-backend")]
impl MimeDb for XdgDb {
fn init() -> Self {
Self {
db: xdg_mime::SharedMimeInfo::new()
}
}
fn get_type(&self, data: &[u8]) -> Option<Mime> {
self.db.get_mime_type_for_data(&data).map(|m| m.0)
}
}