fif/src/mimedb.rs

69 lines
1.4 KiB
Rust
Raw Normal View History

#[cfg(feature = "infer-backend")]
2021-02-18 09:48:38 +00:00
use std::str::FromStr;
use mime_guess::Mime;
pub trait MimeDb {
fn init() -> Self;
fn get_type(&self, data: &[u8]) -> Option<Mime>;
}
#[cfg(feature = "infer-backend")]
pub struct InferDb {
2021-02-18 09:48:38 +00:00
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
2021-02-18 09:48:38 +00:00
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
2021-02-18 09:48:38 +00:00
});
// unmut
let info = info;
Self { db: info }
}
fn get_type(&self, data: &[u8]) -> Option<Mime> {
2021-02-18 09:48:38 +00:00
self.db.get(data).map(|f| Mime::from_str(f.mime_type()).unwrap())
}
}
#[cfg(feature = "xdg-mime-backend")]
pub struct XdgDb {
2021-02-18 09:48:38 +00:00
db: xdg_mime::SharedMimeInfo,
}
#[cfg(feature = "xdg-mime-backend")]
impl MimeDb for XdgDb {
fn init() -> Self {
Self {
2021-02-18 09:48:38 +00:00
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)
}
2021-02-18 09:48:38 +00:00
}