Crate ctb_formats_detection

Crate ctb_formats_detection 

Source
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:

§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 file test 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
PolyFile attribution, 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.c in file.
text
Text and character encoding detection subsystem ported from file (ascmagic.c, encoding.c) and PolyFile.
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 DcMstring and Rust’s String.
DiskPayloadSource
A payload source reading from an on-disk file.
ExtensionRule
A rule describing a file extension associated with a file format.
FileEntity
A complete, self-describing file entity holding identity, metadata, streams, and payload descriptor.
InodeKey
Unique filesystem inode identifier across mounts.
MemoryPayloadSource
An in-memory payload source for streams, forks, or small files.
ReaderPayloadSource
A streaming payload source wrapping an unseekable reader (e.g. stdin or pipe).

Enums§

CaseSensitivity
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.
FileEntityKind
The concrete filesystem or archive kind of a file entity.
FileEntityType
Canonical categorical type of a file entity without payload details.
FileOrigin
The origin source where a file was discovered or extracted from.
FormatId
Standardized format identifier enum derived from formats category tables.

Traits§

PayloadSource
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/file File and produces the top matching FormatId, optionally restricted to a specific category.
detect_file_report
Evaluates multiple detection signals for an io/file File (i.e. FileEntity) and its payload, inspecting file identity, Apple Type codes,
detect_file_report_with_hint
Evaluates multiple detection signals for an io/file File with custom detection hint.
detect_format_id
Backward-compatible detection function picking the top candidate’s FormatId.
detect_format_id_in_categories
Detects FormatId restricting candidates strictly to the provided categories.
guess_and_report_dcs
Guesses format candidates and generates a detection report from a DcString. The report populates file_origin as FileOrigin::Synthetic.
guess_and_report_file
Guesses format candidates and generates a detection report directly from an io/file File.
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_origin as FileOrigin::Synthetic.
guess_and_report_vec
Guesses format candidates and generates a detection report from raw bytes. The report populates file_origin as FileOrigin::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/file File.
guess_format_candidates
Evaluates magic byte rules, extensions, and environment priors to produce ranked format candidates.
guess_format_id
Detects FormatId using 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.

Type Aliases§

File
Canonical type alias for FileEntity.
OsPath