Skip to content

Instantly share code, notes, and snippets.

@mmstick
Last active November 13, 2017 15:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmstick/0f7c08b4a26db822ffad2d542b3509b6 to your computer and use it in GitHub Desktop.
Save mmstick/0f7c08b4a26db822ffad2d542b3509b6 to your computer and use it in GitHub Desktop.
Rust Mime Types Detection (Videos)
use std::fs;
use std::io::Read;
/// Obtains a list of video extensions from the `/etc/mime.types` file on Linux.
pub fn get_video_extensions() -> Result<Vec<String>, &'static str> {
fs::File::open("/etc/mime.types").ok()
// Return an error if /etc/mime.types could not be found.
.map_or(Err("tv-renamer: unable to open /etc/mime.types"), |mut file| {
// Create a buffer with the capacity of the file
let mut contents = String::with_capacity(file.metadata().map(|x| x.len()).unwrap_or(0) as usize);
// Store the contents of the file into the `contents variable`.
file.read_to_string(&mut contents).ok()
// Return an error if the file could not be read to the string.
.map_or(Err("tv-renamer: unable to read file to string"), |_| {
// Create a vector that will hold the list of video extensions.
let mut extension_list = Vec::new();
// Collect all the lines that start with "video" because they contain the video extensions.
for item in contents.lines().filter(|x| x.starts_with("video")) {
// Collect the pairs of extensions associated with that video type.
for extension in item.split_whitespace().skip(1).map(String::from).collect::<Vec<String>>() {
// Push each of the extensions that are discovered to the list of extensions.
extension_list.push(extension);
}
}
// Return the collected list of extensions as an `Ok(Vec<String>)`.
Ok(extension_list)
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment