utf8-forge 0.1.0

A focused, idempotent, bidirectional charset transcoder for source trees. Default output: UTF-8 without BOM.
Documentation
//! Encoding detection (frozen rule-based algorithm, `DESIGN.md §3`).
//!
//! Detection order is frozen: BOM sniffing first, then strict UTF-8, then
//! strict GB18030. Reordering breaks idempotence on ASCII-only files.

use encoding_rs::GB18030;

/// Encodings this tool can classify a byte stream as.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DetectedEncoding {
    /// No BOM + strict UTF-8 valid. Pure ASCII also lands here (fast path).
    Utf8,
    /// Starts with `EF BB BF`.
    Utf8Bom,
    /// Starts with `FF FE`.
    Utf16Le,
    /// Starts with `FE FF`.
    Utf16Be,
    /// UTF-8 strict decode failed, GB18030 strict decode succeeded.
    /// Covers GB2312 / GBK / GB18030.
    Gb18030,
    /// All detectors failed. Reported & skipped — never guessed.
    Unknown,
}

impl DetectedEncoding {
    /// Stable snake-case tag used in JSON reports and console output.
    pub fn tag(self) -> &'static str {
        match self {
            DetectedEncoding::Utf8 => "utf-8",
            DetectedEncoding::Utf8Bom => "utf-8-bom",
            DetectedEncoding::Utf16Le => "utf-16le",
            DetectedEncoding::Utf16Be => "utf-16be",
            DetectedEncoding::Gb18030 => "gb18030",
            DetectedEncoding::Unknown => "unknown",
        }
    }

    /// True when the encoding was identified purely by a byte-order mark.
    pub fn has_bom(self) -> bool {
        matches!(
            self,
            DetectedEncoding::Utf8Bom | DetectedEncoding::Utf16Le | DetectedEncoding::Utf16Be
        )
    }
}

/// Classify raw bytes. Rule-based on purpose — no statistical guessing.
pub fn detect(bytes: &[u8]) -> DetectedEncoding {
    if bytes.is_empty() {
        return DetectedEncoding::Utf8;
    }
    if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
        return DetectedEncoding::Utf8Bom;
    }
    if bytes.starts_with(&[0xFF, 0xFE]) {
        return DetectedEncoding::Utf16Le;
    }
    if bytes.starts_with(&[0xFE, 0xFF]) {
        return DetectedEncoding::Utf16Be;
    }
    if std::str::from_utf8(bytes).is_ok() {
        return DetectedEncoding::Utf8;
    }
    let (_, _, had_errors) = GB18030.decode(bytes);
    if !had_errors {
        return DetectedEncoding::Gb18030;
    }
    DetectedEncoding::Unknown
}