monolith/src/utils.rs

35 lines
855 B
Rust
Raw Normal View History

2019-08-23 05:17:15 +02:00
extern crate base64;
extern crate mime_sniffer;
use self::base64::encode;
use self::mime_sniffer::MimeTypeSniffer;
pub fn data_to_dataurl(mime: &str, data: &[u8]) -> String {
2019-08-23 20:24:45 +02:00
let mimetype = if mime == "" {
detect_mimetype(data)
2019-08-23 05:17:15 +02:00
} else {
2019-08-23 20:24:45 +02:00
mime.to_string()
};
2019-08-23 05:17:15 +02:00
format!("data:{};base64,{}", mimetype, encode(data))
}
fn detect_mimetype(data: &[u8]) -> String {
2019-08-23 10:49:29 +02:00
data.sniff_mime_type().unwrap_or("").to_string()
2019-08-23 05:17:15 +02:00
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_data_to_dataurl() {
let mime = "application/javascript";
let data = "var word = 'hello';\nalert(word);\n";
let datauri = data_to_dataurl(mime, data.as_bytes());
2019-08-23 10:49:29 +02:00
assert_eq!(
&datauri,
"data:application/javascript;base64,dmFyIHdvcmQgPSAnaGVsbG8nOwphbGVydCh3b3JkKTsK"
);
2019-08-23 05:17:15 +02:00
}
}