file-format
Determine a file or stream's format from its signature in Rust
Repository Health
Technical Analysis
file-format is a Rust crate for detecting the format of a file or byte stream by inspecting its signature (magic number). It recognizes a wide range of formats, from documents and images to archives, audio, and video, and returns rich metadata including a human-readable name, short name, MIME/media type, canonical extension, and a high-level Kind classification.
For container-style formats like ZIP, Compound File Binary, and XML, it applies specialized readers to distinguish the many formats that share a common base signature. When no signature matches, it falls back to arbitrary binary data.
What You Get
- Format detection from a file path, byte slice, or any
Read/Seekstream - Rich metadata: display name, short name, media type, extension, and
Kind - A large catalog of supported formats across documents, media, and archives
- Smart disambiguation of ZIP-, CFB-, and XML-based container formats
- A dependency-free core with sensible fallback to binary data
Common Use Cases
- Validating uploaded files by real content instead of their extension
- Choosing MIME types for HTTP responses or storage metadata
- Routing files to the right processing pipeline based on detected kind
- Security checks that reject files whose signature doesn’t match their name
Under The Hood
Architecture - The crate is organized around a generated FileFormat enum in src/formats.rs, signature tables in src/signatures.rs, and specialized src/readers.rs logic for container formats. A macros.rs file drives code generation so each variant carries its name, short name, media type, extension, and Kind. Public entry points (from_file, from_bytes, and stream-based readers) in src/lib.rs match signatures, then invoke the appropriate reader to refine ambiguous matches.
Tech Stack - Pure Rust (edition targeting Rust 1.85+), with no required runtime dependencies; internal build tooling generates the format tables. CI runs via GitHub Actions.
Code Quality - The project includes an extensive fixtures directory and tests that assert detection for real sample files across categories, and the macro-driven tables keep the large format catalog consistent and maintainable.
API Design - The API is compact and discoverable: a single FileFormat enum plus a handful of constructor functions, with each value exposing well-named accessors (name, short_name, media_type, extension, kind), making it trivial to adopt.