### Example: Match Reader Extension Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-matcher.md Demonstrates how to use `match_reader_extension` with a file reader to check its extension. ```rust use mimetype_detector::match_reader_extension; use std::fs::File; let file = File::open("image.png")?; let is_png = match_reader_extension(file, ".png")?; ``` -------------------------------- ### Example: Match File Extension Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-matcher.md Shows how to use `match_file_extension` to verify if a file's extension is PNG. ```rust use mimetype_detector::match_file_extension; if match_file_extension("image.png", ".png")? { println!("File extension is PNG!"); } ``` -------------------------------- ### Example MIME Type Constants Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/types.md Provides examples of string constants for common MIME types. These are organized by category in the library. ```rust pub const IMAGE_PNG: &str = "image/png"; pub const IMAGE_JPEG: &str = "image/jpeg"; pub const APPLICATION_PDF: &str = "application/pdf"; pub const APPLICATION_ZIP: &str = "application/zip"; pub const TEXT_HTML: &str = "text/html; charset=utf-8"; ``` -------------------------------- ### MimeKind Comparison Example Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Shows how to use PartialEq to assert equality and inequality between detected MIME kinds and predefined constants. ```rust use mimetype_detector::{detect, MimeKind}; let mime = detect(b"\x89PNG\r\n\x1a\n"); assert_eq!(mime.kind(), MimeKind::IMAGE); assert_ne!(mime.kind(), MimeKind::VIDEO); ``` -------------------------------- ### MimeKind Detection Example Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Demonstrates detecting MIME types for PNG and DOCX files, and printing their kinds. Also shows printing the UNKNOWN kind. ```rust use mimetype_detector::{detect, MimeKind}; let png = detect(b"\x89PNG\r\n\x1a\n"); println!("{}", png.kind()); // "IMAGE" let docx = detect(b"PK\x03\x04word/"); println!("{}", docx.kind()); // "DOCUMENT | ARCHIVE" let unknown = MimeKind::UNKNOWN; println!("{}", unknown); // "UNKNOWN" ``` -------------------------------- ### Kind Inheritance Example Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/INDEX.md Demonstrates how to check the kind of a detected MIME type, showing inherited categories like DOCUMENT and ARCHIVE. ```rust let docx = detect(docx_bytes); // DOCX has kind: DOCUMENT | ARCHIVE (inherited from ZIP parent) assert!(docx.kind().is_document()); assert!(docx.kind().is_archive()); ``` -------------------------------- ### Get Format Name Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-type.md Retrieves the human-readable name of the detected file format. Use this to display a user-friendly description of the file type. ```Rust use mimetype_detector::detect; let mime = detect(b"%PDF-1.4"); println!("Format: {}", mime.name()); // "Portable Document Format" ``` -------------------------------- ### Custom Error Handling for File Detection Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/usage-patterns.md Implement robust error handling for file-based MIME type detection. This example shows how to map specific IO errors to user-friendly messages. ```rust use mimetype_detector::detect_file; use std::io; fn safe_detection(path: &str) -> Result { match detect_file(path) { Ok(mime) => Ok(mime.name().to_string()), Err(e) => match e.kind() { io::ErrorKind::NotFound => Err(format!("File not found: {}", path)), io::ErrorKind::PermissionDenied => Err(format!("Permission denied: {}", path)), _ => Err(format!("Error reading {}: {}", path, e)) } } } ``` -------------------------------- ### Process Files Based on MIME Type Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/INDEX.md Execute specific processing logic based on the detected MIME type of the data. This example shows handling for PNG, JPEG, PDF, and a fallback for unknown types. ```rust match detect(data).mime() { "image/png" => process_png(data), "image/jpeg" => process_jpeg(data), "application/pdf" => process_pdf(data), _ => process_unknown(data), } ``` -------------------------------- ### Navigate Type Hierarchy Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/usage-patterns.md Use the `detect` function to get a `MimeType` object and then access its `name()`, `mime()`, and `parent()` methods to understand format details and relationships. The `parent()` method returns an `Option` which can be used to check for container types. ```rust use mimetype_detector::detect; let docx = detect(b"PK\x03\x04word/"); println!("Format: {}", docx.name()); // "Word 2007+" println!("MIME: {}", docx.mime()); // "application/vnd.openxmlformats-ứt" if let Some(parent) = docx.parent() { println!("Container: {}", parent.name()); // "ZIP Archive" println!("Container MIME: {}", parent.mime()); // "application/zip" } // Check container categories if let Some(parent) = docx.parent() { if parent.kind().is_archive() { println!("This document is stored in an archive container"); } } ``` -------------------------------- ### Typical Cargo Compilation Commands Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/configuration.md Provides standard commands for building the project. Use `cargo build` for a quick debug build and `cargo build --release` for an optimized release build. ```bash # Debug build (fast compilation) cargo build # Release build (optimized for performance and size) cargo build --release ``` -------------------------------- ### Core Detection Functions Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/00-GENERATION-NOTES.txt Documentation for core detection functions like `detect` and `detect_file`. ```APIDOC ## API Reference: Detection Functions This section details the core functions for detecting MIME types. ### `detect` Detects the MIME type of a given byte slice. #### Parameters - `data` (*&[u8]*) - The byte slice to analyze. #### Returns - `MimeType` - The detected MIME type. ### `detect_file` Detects the MIME type of a file by reading its content. #### Parameters - `file_path` (*&str*) - The path to the file. #### Returns - `Result` - The detected MIME type or an error if detection fails. ``` -------------------------------- ### Get MIME Type Aliases Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-type.md Retrieves a slice of all alternative MIME type strings for the detected format. Useful when dealing with different representations of the same file type. ```Rust use mimetype_detector::detect; let pdf = detect(b"%PDF-1.4"); println!("Aliases: {:?}", pdf.aliases()); // Output: ["application/x-pdf"] ``` -------------------------------- ### new Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-type.md Creates a new MimeType with minimal configuration. This is the primary constructor for defining a new MIME type. ```APIDOC ## new ### Description Creates a new `MimeType` with minimal configuration. ### Method Associated Function ### Parameters #### Path Parameters - **mime** (`&'static str`) - Required - The MIME type string - **name** (`&'static str`) - Required - Human-readable format name - **extension** (`&'static str`) - Required - Primary file extension - **matcher** (`fn(&[u8]) -> bool`) - Required - Detection function - **children** (`&'static [&'static MimeType]`) - Required - Child MIME types ``` -------------------------------- ### Get Combined MIME Kind Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-type.md Retrieves a bitmask representing the combined kind of the MIME type and all its ancestors. Allows checking for multiple category types simultaneously. ```Rust use mimetype_detector::{detect, MimeKind}; let docx = detect(b"PK\x03\x04word/"); println!("Kind: {}", docx.kind()); // "DOCUMENT | ARCHIVE" if docx.kind().contains(MimeKind::ARCHIVE) { println!("It's an archive!"); } if docx.kind().contains(MimeKind::DOCUMENT) { println!("It's a document!"); } ``` -------------------------------- ### Detect MIME type from bytes and file Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/INDEX.md Demonstrates how to detect the MIME type from a byte slice and a file path. Includes checking the MIME type against known constants and its category. ```rust use mimetype_detector::{detect, detect_file, constants::*}; // From bytes let mime = detect(b"\x89PNG\r\n\x1a\n"); assert_eq!(mime.mime(), IMAGE_PNG); assert_eq!(mime.name(), "Portable Network Graphics"); // From file let mime = detect_file("document.pdf")?; if mime.is(APPLICATION_PDF) { println!("Detected: {}", mime.name()); } // Check category if mime.kind().is_image() { println!("This is an image!"); } ``` -------------------------------- ### Get Parent MIME Type Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-type.md Retrieves the parent MIME type in the detection hierarchy. This is useful for understanding type relationships, such as DOCX being a type of ZIP archive. ```Rust use mimetype_detector::detect; let docx = detect(b"PK\x03\x04"); // ZIP signature with DOCX content if let Some(parent) = docx.parent() { println!("Parent type: {}", parent.name()); // "ZIP Archive" } ``` -------------------------------- ### Get Primary File Extension Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-type.md Retrieves the primary file extension associated with the detected MIME type. Returns an empty string if no standard extension is found. ```Rust use mimetype_detector::detect; let mime = detect(b"\x89PNG\r\n\x1a\n"); assert_eq!(mime.extension(), ".png"); ``` -------------------------------- ### Using Re-exported vs. Explicit Paths Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/module-organization.md Demonstrates that both the re-exported path and the explicit path to a type like MimeType work identically. ```rust // Both work identically: use mimetype_detector::MimeType; // Via root re-export use mimetype_detector::mime_type::MimeType; // Explicit path ``` -------------------------------- ### Get MIME Type Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-type.md Retrieves the primary MIME type string for a given byte signature. Useful for identifying the content type of a file or data buffer. ```Rust use mimetype_detector::detect; let mime = detect(b"\x89PNG\r\n\x1a\n"); assert_eq!(mime.mime(), "image/png"); ``` -------------------------------- ### Type Checking with Fallback Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/INDEX.md Demonstrates how to select a specific handler for known MIME types (PNG, JPEG) and fall back to generic handlers for images or any other type. ```rust let mime = detect(data); let handler = match mime.mime() { "image/png" => png_handler, "image/jpeg" => jpeg_handler, _ if mime.kind().is_image() => generic_image_handler, _ => generic_handler, }; handler(data)?; ``` -------------------------------- ### Import MIME Type Constants Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/constants-reference.md Demonstrates how to import MIME type constants from the `constants` module. You can import all constants using `*` or specific constants by their explicit paths. ```rust use mimetype_detector::constants::*; // Constants are organized in the module but can be imported with * // For selective imports, use explicit paths: use mimetype_detector::constants::{IMAGE_PNG, APPLICATION_PDF}; ``` -------------------------------- ### Get File Extension Aliases Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-type.md Retrieves a slice of all alternative file extensions for the detected MIME type. Helps in scenarios where multiple extensions are commonly used for the same file format. ```Rust use mimetype_detector::detect; let mime = detect(b"\x89PNG\r\n\x1a\n"); // Example usage for extension_aliases would go here, similar to aliases() ``` -------------------------------- ### Using MIME Type Constants in Rust Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/constants-reference.md Demonstrates how to use predefined MIME type constants for direct comparison, pattern matching, and checking against collections of allowed types. Ensure you import the constants using `use mimetype_detector::constants::*;`. ```rust use mimetype_detector::constants::*; // Direct comparison if mime.is(IMAGE_PNG) { println!("PNG image!"); } // Pattern matching match mime.mime() { IMAGE_PNG | IMAGE_JPEG => println!("Image"), APPLICATION_PDF => println!("PDF"), _ => println!("Other"), } // Collections let allowed_types = [IMAGE_PNG, IMAGE_JPEG, IMAGE_WEBP]; if allowed_types.contains(&mime.mime()) { println!("Allowed image format"); } ``` -------------------------------- ### Import Core Mimetype Detector Functions Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/INDEX.md Import all detection, matching, registration, and query functions from the root module of the mimetype-detector crate. This provides access to the library's primary functionalities. ```rust use mimetype_detector::{ // Detection detect, detect_file, detect_reader, detect_with_limit, detect_file_with_limit, detect_reader_with_limit, // Matching match_mime, match_file, match_reader, match_extension, match_file_extension, match_reader_extension, // Registration register_mime, register_extension, // Queries is_supported, is_supported_extension, equals_any, // Types MimeType, MimeKind, }; ``` -------------------------------- ### Filtering Collections by MIME Type Category Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/usage-patterns.md Filter collections of file data based on their MIME type category. This example demonstrates how to separate images and documents from a vector of file data. ```rust use mimetype_detector::{detect, MimeKind}; let files: Vec<&[u8]> = vec![/* file data */]; let images: Vec<_> = files.iter() .filter(|data| detect(data).kind().is_image()) .collect(); let documents: Vec<_> = files.iter() .filter(|data| detect(data).kind().is_document()) .collect(); ``` -------------------------------- ### Register Custom MIME Type Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/INDEX.md Shows how to extend the library by registering a custom MIME type with a specific matching function. ```rust register_mime("application/x-custom", |data| { data.starts_with(b"MAGIC_BYTES") }); ``` -------------------------------- ### Custom MIME Kind Logic with Combinations Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Demonstrates checking for compound MIME types (e.g., document and archive) and creating custom filters using the union of multiple kinds. ```rust use mimetype_detector::{detect, MimeKind}; let mime = detect(b"PK\x03\x04word/"); // Check if it's a document that can also be treated as an archive if mime.kind().is_document() && mime.kind().is_archive() { println!("This is an Office document (compound archive)"); } // Use union to create custom filter let media_kinds = MimeKind::IMAGE.union(MimeKind::VIDEO).union(MimeKind::AUDIO); if mime.kind().contains(media_kinds.as_ref()) { println!("Media file detected"); } ``` -------------------------------- ### Add Alternative File Extensions Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-type.md Associates alternative file extensions with the MimeType. ```rust pub const fn with_extension_aliases( mut self, extension_aliases: &'static [&'static str], ) -> Self ``` -------------------------------- ### Error Handling for File Detection Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/usage-patterns.md Demonstrates how to handle potential I/O errors when detecting MIME types from files using `detect_file` and the `?` operator. ```rust use mimetype_detector::detect_file; use std::io; fn analyze_file(path: &str) -> io::Result<()> { let mime = detect_file(path)?; println!("Detected: {} ({})", mime.name(), mime.mime()); Ok(()) } ``` -------------------------------- ### Import All MIME Type Constants Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/constants-reference.md Use this to import all available MIME type constants from the library. This is useful when you need access to a wide range of constants. ```rust use mimetype_detector::constants::*; ``` -------------------------------- ### Pattern Matching on MIME Type Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/usage-patterns.md Use pattern matching to handle different file types by matching against specific MIME type constants. This is useful when you need to perform distinct actions for known file formats. ```rust use mimetype_detector::{detect, constants::*}; let mime = detect(data); match mime.mime() { IMAGE_PNG | IMAGE_JPEG | IMAGE_GIF => println!("Image format"), VIDEO_MP4 | VIDEO_WEBM | VIDEO_X_MATROSKA => println!("Video format"), APPLICATION_PDF => println!("PDF document"), APPLICATION_ZIP => println!("ZIP archive"), _ => println!("Other format: {}", mime.name()), } ``` -------------------------------- ### PRESENTATION MimeKind Constant Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Represents presentation formats such as PPTX and ODP. Use this for slide-based content files. ```rust pub const PRESENTATION: MimeKind = MimeKind(1 << 12); ``` -------------------------------- ### Batch Process Files by Mimetype Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/usage-patterns.md Iterate through a directory, detect the mimetype of each file, and categorize them into predefined groups like images, audio, video, or documents. Errors during file reading are printed to stderr. ```rust use mimetype_detector::{detect_file, MimeKind}; use std::path::Path; use std::collections::HashMap; fn categorize_files(directory: &Path) -> std::io::Result>> { let mut categories: HashMap<&str, Vec> = HashMap::new(); for entry in std::fs::read_dir(directory)? { let entry = entry?; let path = entry.path(); if path.is_file() { match detect_file(&path) { Ok(mime) => { let category = if mime.kind().is_image() { "images" } else if mime.kind().is_audio() { "audio" } else if mime.kind().is_video() { "video" } else if mime.kind().is_document() { "documents" } else { "other" }; categories.entry(category) .or_insert_with(Vec::new) .push(path.to_string_lossy().to_string()); }, Err(e) => eprintln!("Error reading {:?}: {}", path, e), } } } Ok(categories) } ``` -------------------------------- ### Match File Extension Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-matcher.md Checks if a file at a given path matches a specific file extension. Opens the file and uses `match_reader_extension`. ```rust pub fn match_file_extension>(path: P, extension: &str) -> io::Result ``` -------------------------------- ### Check Format Support Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/usage-patterns.md Use `is_supported` to check if a MIME type is recognized by the library, and `is_supported_extension` for file extensions. This is useful for validating input before processing. ```rust use mimetype_detector::{is_supported, is_supported_extension}; // Check if MIME type is supported if is_supported("image/png") { println!("PNG is supported"); } // Check if extension is supported if is_supported_extension(".webp") { println!("WebP is supported"); } // Fallback handling if !is_supported("application/x-proprietary") { println!("This format is not natively supported"); } ``` -------------------------------- ### MimeType Query and Utility Methods Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/module-organization.md Provides methods for registering MimeTypes, retrieving their MIME string and name, and matching byte slices against them. ```rust pub fn register(&'static self) pub fn mime(&self) -> &'static str pub fn name(&self) -> &'static str pub fn match_bytes(&'static self, input: &[u8]) -> &'static MimeType // ... more methods ``` -------------------------------- ### Root Module Public API Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/module-organization.md Import all necessary functions and types from the crate root for detection and utility operations. This includes functions for detecting MIME types from various sources and registering new MIME types. ```rust use mimetype_detector::{ detect, detect_file, detect_reader, detect_with_limit, detect_file_with_limit, detect_reader_with_limit, match_mime, match_file, match_reader, match_extension, match_file_extension, register_mime, register_extension, is_supported, is_supported_extension, equals_any, MimeType, MimeKind, }; ``` -------------------------------- ### Generic Path Support for File Detection Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/usage-patterns.md Shows that `detect_file` accepts various path types, including string slices, owned Strings, PathBuf, and references to Path. ```rust use mimetype_detector::detect_file; use std::path::PathBuf; // All of these work: detect_file("file.png")?; // &str detect_file(String::from("file.png"))?; // String detect_file(PathBuf::from("file.png"))?; // PathBuf detect_file(std::path::Path::new("file.png"))?; // &Path ``` -------------------------------- ### Release Profile Optimization Settings Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/configuration.md Configures the release build profile for enhanced performance and size optimization. Link-Time Optimization (LTO) is enabled, and codegen-units are set to 1 for maximum optimization, potentially increasing compile times. ```toml [profile.release] lto = "fat" codegen-units = 1 ``` -------------------------------- ### Project Dependencies Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/configuration.md Defines project dependencies, including development dependencies for benchmarking. ```toml [dependencies] # (empty) [dev-dependencies] criterion = { version = "0.8", features = ["html_reports"] } ``` -------------------------------- ### Matching and Validation Functions in lib.rs Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/module-organization.md Offers functions to match byte data against a MIME type and to validate file types based on their paths. ```rust pub fn match_mime(data: &[u8], mime_type: &str) -> bool pub fn match_file(path: P, mime_type: &str) -> io::Result // ... more matching variants ``` -------------------------------- ### Register Custom MIME Type and Extension Matcher Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/configuration.md Register custom MIME types and file extensions with their corresponding matcher functions. Ensure registration happens early in your application's lifecycle. Matcher functions should be pure and free of side effects. ```rust use mimetype_detector::{register_mime, register_extension, detect, match_mime}; // Register custom MIME type register_mime("application/x-custom-format", |data| { data.starts_with(b"CUSTOM_MAGIC_BYTES") }); // Register extension matcher register_extension(".custom", |data| { data.len() > 4 && &data[0..6] == b"CUSTOM" }); // Now detection works let result = detect(b"CUSTOM_MAGIC_BYTES some data"); assert!(match_mime(b"CUSTOM_MAGIC_BYTES", "application/x-custom-format")); ``` -------------------------------- ### Create New MimeType Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-type.md Initializes a new MimeType with essential details like MIME string, name, extension, a detection function, and child MIME types. ```rust pub const fn new( mime: &'static str, name: &'static str, extension: &'static str, matcher: fn(&[u8]) -> bool, children: &'static [&'static MimeType], ) -> Self ``` -------------------------------- ### Complete Import in Rust Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/module-organization.md Use this import pattern to bring all public items from the mimetype-detector crate and its constants module into scope. ```rust use mimetype_detector::*; use mimetype_detector::constants::*; ``` -------------------------------- ### Tree Module Organization Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/module-organization.md Details the structure of the tree.rs file, including its module documentation, prefix vector building macro, and root definition. ```rust 1. Module documentation (lines 1-26) 2. Prefix vector building macro (lines 32-141) 3. ROOT definition and child declarations (lines 143+) 4. MIME type definitions (auto-generated from declarations) 5. Initialization function (not shown in excerpt) ``` -------------------------------- ### PartialEq and Eq Implementations for MimeKind Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Enables direct comparison of MimeKind values. ```rust impl PartialEq for MimeKind { ... } impl Eq for MimeKind { ... } ``` -------------------------------- ### Match File MIME Type Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-matcher.md Checks if a file at a given path matches a specific MIME type. It reads the file and delegates to `match_reader`, automatically handling path conversion. ```rust pub fn match_file>(path: P, mime_type: &str) -> io::Result ``` ```rust use mimetype_detector::match_file; if match_file("image.png", "image/png")? { println!("File is a PNG!"); } ``` -------------------------------- ### Match Data by File Extension Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-matcher.md Checks if the given byte data matches a specific file extension. It uses registered matchers and limits input to 3072 bytes. Returns false if the extension is not registered. ```rust pub fn match_extension(data: &[u8], extension: &str) -> bool ``` ```rust use mimetype_detector::match_extension; let data = b"\x89PNG\r\n\x1a\n"; assert!(match_extension(data, ".png")); assert!(!match_extension(data, ".jpg")); ``` -------------------------------- ### is_executable Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Checks if this MimeKind represents an executable or binary format. ```APIDOC ## is_executable ### Description Checks if this is an executable/binary format. ### Method `const fn is_executable(&self) -> bool` ### Returns `bool` - `true` if this is an executable/binary format, `false` otherwise. ``` -------------------------------- ### is_supported_extension Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-support.md Checks if a given file extension is supported by the library. It performs a case-sensitive comparison to see if the extension has been registered. ```APIDOC ## is_supported_extension ### Description Checks if a file extension is supported by the library. ### Method N/A (Rust function) ### Endpoint N/A (Rust function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response - **bool**: `true` if the extension is supported, `false` otherwise. ### Response Example N/A ### Behavior - Checks if the extension has been registered - Initializes the detection tree on first call - Case-sensitive comparison - Returns `false` for unknown extensions ### Panics Panics if the extension registry RwLock is poisoned. ``` -------------------------------- ### Custom Matcher Registration Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/00-GENERATION-NOTES.txt Information on registering and using custom matchers. ```APIDOC ## API Reference: Matcher This section explains how to register and use custom matchers. ### Registering Custom Matchers Users can register custom matching logic to extend the detector's capabilities. #### `register_matcher` Function Registers a new matcher. ##### Parameters - `matcher`: A closure or function implementing the `Matcher` trait. ##### Example ```rust struct MyCustomMatcher; impl Matcher for MyCustomMatcher { fn matches(&self, data: &[u8]) -> Option { // Custom matching logic here Some(MimeType::new("application", "custom")) } } register_matcher(Box::new(MyCustomMatcher)); ``` ``` -------------------------------- ### is_presentation Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Checks if this MimeKind represents a presentation format. ```APIDOC ## is_presentation ### Description Checks if this is a presentation format. ### Method `const fn is_presentation(&self) -> bool` ### Returns `bool` - `true` if this is a presentation format, `false` otherwise. ``` -------------------------------- ### Matcher Registration Functions in lib.rs Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/module-organization.md Provides functions to register custom MIME type matchers based on MIME type strings or file extensions. ```rust pub fn register_mime(mime_type: &str, matcher: fn(&[u8]) -> bool) pub fn register_extension(extension: &str, matcher: fn(&[u8]) -> bool) ``` -------------------------------- ### Basic MIME Type Checking Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Demonstrates checking if a detected MIME type belongs to the image category using the `is_image()` method. ```rust use mimetype_detector::{detect, MimeKind}; let data = b"\x89PNG\r\n\x1a\n"; let mime = detect(data); if mime.kind().is_image() { println!("This is an image!"); } ``` -------------------------------- ### is_application Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Checks if this MimeKind represents an application-specific format. ```APIDOC ## is_application ### Description Checks if this is an application-specific format. ### Method `const fn is_application(&self) -> bool` ### Returns `bool` - `true` if this is an application-specific format, `false` otherwise. ``` -------------------------------- ### Check for Audio MimeKind Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Use `is_audio` to determine if the MimeKind represents an audio format. ```rust pub const fn is_audio(&self) -> bool ``` -------------------------------- ### IMAGE MimeKind Constant Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Represents image formats like PNG, JPEG, and GIF. Use this for static visual media. ```rust pub const IMAGE: MimeKind = MimeKind(1 << 3); ``` -------------------------------- ### match_file Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-matcher.md Checks if a file at the specified path matches a given MIME type. It reads the file content and delegates the matching process. ```APIDOC ## match_file Checks if a file matches a specific MIME type. ### Description Checks if a file at the specified path matches a given MIME type. It reads the file content and delegates the matching process. ### Parameters #### Path Parameters - **path** (`P: AsRef`) - Required - The file system path to the file - **mime_type** (`&str`) - Required - The MIME type to match against ### Returns A `Result` containing `true` if the file matches, or an `io::Error` if the file cannot be opened or read. ### Example ```rust use mimetype_detector::match_file; if match_file("image.png", "image/png")? { println!("File is a PNG!"); } ``` ``` -------------------------------- ### EXECUTABLE MimeKind Constant Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Represents executable or binary formats like ELF, PE/EXE, and WASM. Use this for program files. ```rust pub const EXECUTABLE: MimeKind = MimeKind(1 << 7); ``` -------------------------------- ### Check for Presentation MimeKind Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Use `is_presentation` to determine if the MimeKind represents a presentation format. ```rust pub const fn is_presentation(&self) -> bool ``` -------------------------------- ### Categorize Files by Type Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/INDEX.md Automatically categorize files into predefined groups (images, audio, video, documents, archives) based on their detected MIME kind. Returns 'other' for unrecognized types. ```rust fn categorize(data: &[u8]) -> &'static str { let kind = detect(data).kind(); match kind { k if k.is_image() => "images", k if k.is_audio() => "audio", k if k.is_video() => "video", k if k.is_document() => "documents", k if k.is_archive() => "archives", _ => "other", } } ``` -------------------------------- ### Thread-Safe Initialization with Once Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/configuration.md Ensures that the library's internal tree is initialized only once, even in concurrent environments. Subsequent calls to detection functions will skip this initialization. ```rust static INIT: Once = Once::new(); fn ensure_init() { INIT.call_once(|| { tree::init_tree(); }); } ``` -------------------------------- ### Thread-Safe Custom Matcher Registries Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/configuration.md Provides thread-safe mechanisms for registering custom MIME type and extension matchers using RwLock for concurrent access. Panics if a lock is poisoned. ```rust static MIME_REGISTRY: LazyLock>> = LazyLock::new(|| RwLock::new(HashMap::new())); static EXT_REGISTRY: LazyLock>> = LazyLock::new(|| RwLock::new(HashMap::new())); ``` -------------------------------- ### Check for Executable MimeKind Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Use `is_executable` to determine if the MimeKind represents an executable or binary format. ```rust pub const fn is_executable(&self) -> bool ``` -------------------------------- ### Constants File Organization Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/module-organization.md Outlines the structure of the constants.rs file, which is organized by categories of format constants. ```rust 1. Module documentation (lines 1-31) 2. Text format constants (lines 34-71) 3. Document format constants (lines 74-103) 4. Archive format constants (lines 108-231) 5. Image format constants (lines 234-445) 6. Audio format constants (lines 448-561) 7. Video format constants (lines 564-664) 8. Executable format constants (lines 667-719) 9. Font format constants (lines 722-749) 10. Web & multimedia constants (lines 752-762) 11. Specialized format constants (lines 765-799+) ``` -------------------------------- ### APPLICATION MimeKind Constant Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Represents application-specific formats such as APK and JAR. Use this for files tied to specific software. ```rust pub const APPLICATION: MimeKind = MimeKind(1 << 8); ``` -------------------------------- ### Safe File Processing Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/INDEX.md Illustrates how to safely process a file based on its detected MIME type, handling documents and archives specifically. ```rust match detect_file(path) { Ok(mime) => { if mime.kind().is_document() { process_document(path) } else if mime.kind().is_archive() { process_archive(path) } else { eprintln!("Unsupported type: {}", mime.name()); } } Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Checking Multiple MIME Categories Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Illustrates how to check if a detected MIME type belongs to multiple categories, such as document and archive for DOCX files. ```rust use mimetype_detector::{detect, MimeKind}; let docx = detect(b"PK\x03\x04word/"); // DOCX is both a document and an archive println!("Is document: {}", docx.kind().is_document()); // true println!("Is archive: {}", docx.kind().is_archive()); // true println!("Is image: {}", docx.kind().is_image()); // false ``` -------------------------------- ### Check for Video MimeKind Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Use `is_video` to determine if the MimeKind represents a video format. ```rust pub const fn is_video(&self) -> bool ``` -------------------------------- ### Security Scan for Dangerous File Types Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/INDEX.md Implement security scanning by rejecting executable files and general application types. This helps prevent the execution of malicious code. ```rust fn is_safe(data: &[u8]) -> bool { let mime = detect(data); // Reject executables and potentially dangerous formats !mime.kind().contains(MimeKind::EXECUTABLE) && !mime.kind().contains(MimeKind::APPLICATION) } ``` -------------------------------- ### MimeType Struct from Submodule Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/module-organization.md Demonstrates importing the MimeType struct directly from the `mime_type` submodule. It is also available from the crate root. ```rust use mimetype_detector::mime_type::MimeType; // Also available from root use mimetype_detector::MimeType; ``` -------------------------------- ### Default MimeKind Implementation Source: https://github.com/asuan/mimetype-detector/blob/main/_autodocs/api-reference-mime-kind.md Provides the default value for MimeKind, which is UNKNOWN. ```rust impl Default for MimeKind { fn default() -> Self { MimeKind::UNKNOWN } } ```