Expand description
Combined multi-signal format detection, hierarchical pattern matching, and multipart extension chain parsing.
This crate (partial/incomplete but seems to be working for basic cases) provides file format guessing by synthesizing multiple orthogonal signals:
- Magic pattern matching: Hierarchical, bitmask-aware rules compiled from file signatures and fine-grained offsets.
- PRONOM / DROID signatures: Dual-anchored header and trailer patterns with variable-length gaps.
- Extension analysis: Multipart extension chains (e.g.
.tar.gz) with case sensitivity rules and path classification. - Structural inspection: Container and polyglot detection for ZIP, OLE2, AppleSingle/Double, and archive structures.
- Text encoding heuristics: Multi-encoding validation (UTF-8, UTF-16, ASCII, Latin-1) and XML/HTML markup pattern scoring.
- Platform knowledge: Target operating system compatibility scoring to resolve format ambiguities.
§High-Level Convenience Functions
For most use cases, convenience functions provide quick format guessing or full diagnostic reporting across common input types:
- Filesystem paths:
guess_pathandguess_and_report_path - UTF-8 / String data:
guess_stringandguess_and_report_string - Document strings:
guess_dcsandguess_and_report_dcs - Raw byte buffers:
guess_vecandguess_and_report_vec - Structured
Fileentities:guess_fileandguess_and_report_file
§Examples
§Inspecting a Filesystem Path
Identify a format directly from an on-disk path or generate a report:
use ctb_formats_detection::{
guess_and_report_path, guess_path, FormatId, OsPath,
};
let dir = tempfile::tempdir()?;
let path: OsPath = dir.path().join("archive.tar.gz");
let gz_header = [0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00];
std::fs::write(&path, gz_header)?;
// Fast authoritative format identification:
let format = guess_path(&path)?;
assert_eq!(format, FormatId::Gzip);
// Comprehensive detection report with ranked candidates:
let report = guess_and_report_path(&path)?;
assert_eq!(report.candidates[0].format_id, Some(FormatId::Gzip));§Inspecting a String
Detect markup, source code, or text formats from a String or &str:
use ctb_formats_detection::{
guess_and_report_string, guess_string, FormatId,
};
let html = String::from(
"<!DOCTYPE html><html><body><h1>Header</h1></body></html>",
);
let format = guess_string(html.clone())?;
assert_eq!(format, FormatId::Html);
let report = guess_and_report_string(html)?;
assert_eq!(report.candidates[0].format_id, Some(FormatId::Html));§Inspecting a Document Character String (DcString)
Detect formats directly from a DcString:
use ctb_formats_detection::{
guess_and_report_dcs, guess_dcs, DcString, FormatId,
};
let dcs = DcString::from_dcutf(
b"<!DOCTYPE html><html><body>Test</body></html>".to_vec(),
)?;
let format = guess_dcs(&dcs)?;
assert_eq!(format, FormatId::Html);
let report = guess_and_report_dcs(&dcs)?;
assert_eq!(report.candidates[0].format_id, Some(FormatId::Html));§Inspecting Raw Byte Vectors
Detect binary or text formats from an in-memory Vec<u8>:
use ctb_formats_detection::{guess_and_report_vec, guess_vec, FormatId};
let gz_bytes: Vec<u8> =
vec![0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00];
let format = guess_vec(gz_bytes.clone())?;
assert_eq!(format, FormatId::Gzip);
let report = guess_and_report_vec(gz_bytes)?;
assert_eq!(report.candidates[0].format_id, Some(FormatId::Gzip));§Inspecting an io/file File Entity
Detect formats when working with structured File entities:
use ctb_formats_detection::{
guess_and_report_file, guess_file, File, FormatId,
};
let dir = tempfile::tempdir()?;
let path = dir.path().join("archive.tar.gz");
let gz_header = [0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00];
std::fs::write(&path, gz_header)?;
let file = File::from_filesystem(&path, None)?;
let format = guess_file(&file)?;
assert_eq!(format, FormatId::Gzip);
let report = guess_and_report_file(&file)?;
assert_eq!(report.candidates[0].format_id, Some(FormatId::Gzip));Re-exports§
pub use crate as detection;pub use platform::format_matches_platform;pub use source::DetectionSource;pub use source::EmptySource;pub use types::*;
Modules§
- chain
- Multipart filename extension peeling, format candidate chain derivation, and format chain specification formatting.
- cli
- Command-line interface runner and reporting for file format detection.
- conflict
- Candidate conflict resolution, subsumption hierarchies, and MIME specialization scoring for format detection.
- container
- Specialized deep parsers and container inspection subsystem.
- decompression
- Transparent and deep recursive decompression inspection for format detection.
- der
- ASN.1 DER (Distinguished Encoding Rules) tag scanner, parser, and
comparator matching upstream
file(src/der.c,src/der.h). - droid
- DROID and PRONOM signature evaluation and container inspection subsystem.
- encoding
- Character encoding definitions and settings for table-driven single-byte encodings. @generated by ctb-build-support::encoding_codegen from format category data tables. Do not edit by hand.
- extension
- File extension registry and matching utilities for format identification.
- extra_
rules - Detection of small specialized formats including IP address strings, checksums, UUIDs, mathematical expressions/relations, and base numerals.
- file_
upstream_ suite - Upstream
filetest suite evaluation and live differential testing harness. - format_
id - @generated by ctb-formats-dcdata::updater from format category data tables. Do not edit by hand.
- magic
- Hierarchical magic byte pattern evaluation engine for format identification.
- magic_
data - Centralized registry of magic header signatures across format types.
- magic_
parser - Parser for libmagic-style hierarchical magic signature rule files (
Magdir). - mime_
derivation - Build-time and runtime derivation of MIME type and extension mappings to authoritative Document Characters (Dcs) and Format IDs.
- platform
- Platform association, operating system compatibility matching, and environment prior scoring for format detection.
- polyfile
PolyFileattribution, polyglot container detection, and nested format parsing subsystem.- readelf
- In-depth ELF container introspection and structural analysis matching
readelf.c. - resource_
fork - Safe extraction of resource type codes from classic Macintosh resource forks.
- source
- Streamed and buffered payload abstractions for format detection.
- special
- Filesystem and inode special file detection subsystem ported from
fsmagic.cinfile. - text
- Text and character encoding detection subsystem ported from
file(ascmagic.c,encoding.c) andPolyFile. - types
- Core data types, candidate representations, and report structures for the format detection engine.
Structs§
- DcString
- An owned, growable string buffer containing valid DcTF data. Analogous to
DcMstringand Rust’sString. - Disk
Payload Source - A payload source reading from an on-disk file.
- Extension
Rule - A rule describing a file extension associated with a file format.
- File
Entity - A complete, self-describing file entity holding identity, metadata, streams, and payload descriptor.
- Inode
Key - Unique filesystem inode identifier across mounts.
- Memory
Payload Source - An in-memory payload source for streams, forks, or small files.
- Reader
Payload Source - A streaming payload source wrapping an unseekable reader (e.g. stdin or pipe).
Enums§
- Case
Sensitivity - Defines whether an extension comparison is case-sensitive or case-insensitive.
- Extent
- A contiguous extent within a file, either holding data or representing a hole.
- File
Entity Kind - The concrete filesystem or archive kind of a file entity.
- File
Entity Type - Canonical categorical type of a file entity without payload details.
- File
Origin - The origin source where a file was discovered or extracted from.
- Format
Id - Standardized format identifier enum derived from formats category tables.
Traits§
- Payload
Source - Abstract streaming provider for file payload data and extents.
Functions§
- current_
platform_ os - Infers the host platform operating system as an authoritative
FormatId. - detect_
file_ format - Evaluates multiple detection signals for an
io/fileFileand produces the top matchingFormatId, optionally restricted to a specific category. - detect_
file_ report - Evaluates multiple detection signals for an
io/fileFile(i.e.FileEntity) and its payload, inspecting file identity, Apple Type codes, - detect_
file_ report_ with_ hint - Evaluates multiple detection signals for an
io/fileFilewith custom detection hint. - detect_
format_ id - Backward-compatible detection function picking the top candidate’s
FormatId. - detect_
format_ id_ in_ categories - Detects
FormatIdrestricting candidates strictly to the provided categories. - guess_
and_ report_ dcs - Guesses format candidates and generates a detection report from a
DcString. The report populatesfile_originasFileOrigin::Synthetic. - guess_
and_ report_ file - Guesses format candidates and generates a detection report directly from an
io/fileFile. - guess_
and_ report_ path - Guesses format candidates and generates a detection report for a filesystem path.
- guess_
and_ report_ path_ with_ hint - Guesses format candidates and generates a detection report for a filesystem path with custom detection hint.
- guess_
and_ report_ string - Guesses format candidates and generates a detection report from a String.
The report populates
file_originasFileOrigin::Synthetic. - guess_
and_ report_ vec - Guesses format candidates and generates a detection report from raw bytes.
The report populates
file_originasFileOrigin::Synthetic. - guess_
and_ report_ vec_ with_ hint - Guesses format candidates and generates a detection report from raw bytes with custom hint.
- guess_
dcs - Guesses the authoritative format for a given
DcString. - guess_
file - Guesses the authoritative format directly from an
io/fileFile. - guess_
format_ candidates - Evaluates magic byte rules, extensions, and environment priors to produce ranked format candidates.
- guess_
format_ id - Detects
FormatIdusing magic byte signatures, extension matching, and category filtering. - guess_
format_ report - Primary format detection function returning a comprehensive report.
- guess_
path - Guesses the authoritative format for a given filesystem path.
- guess_
string - Guesses the authoritative format for a given String content.
- guess_
vec - Guesses the authoritative format for raw bytes.
- is_
os_ match - Determines whether a format’s associated operating system is compatible with a target operating system context.