utf8-forge 0.1.0

A focused, idempotent, bidirectional charset transcoder for source trees. Default output: UTF-8 without BOM.
Documentation
//! Strict decode / encode / transcode (`DESIGN.md §4`).
//!
//! Invariants enforced here:
//! - UTF-16 encoders never emit a BOM by themselves — the BOM is prepended
//!   manually by [`encode`] (invariant #2).
//! - Any decode that reports `had_errors` is a hard error, never a
//!   replacement-char pass-through (invariant #7).
//! - No newline normalization — `encoding_rs` preserves `\r\n` verbatim
//!   (invariant #3).

use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;

use encoding_rs::{GB18030, UTF_16BE, UTF_16LE};

use crate::detector::{detect, DetectedEncoding};
use crate::error::ForgeError;

/// Encodings the tool can write.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TargetEncoding {
    /// UTF-8 without BOM (default; Playbook Strategy A).
    Utf8,
    /// UTF-8 with `EF BB BF` prepended.
    Utf8Bom,
    /// GB18030 (superset of GB2312 / GBK).
    Gb18030,
    /// UTF-16 little endian with `FF FE` prepended.
    Utf16Le,
    /// UTF-16 big endian with `FE FF` prepended.
    Utf16Be,
}

impl TargetEncoding {
    /// Default target: UTF-8 without BOM (invariant #1).
    pub fn utf8_default() -> TargetEncoding {
        TargetEncoding::Utf8
    }

    /// Parse a CLI value. Case-insensitive. Only canonical tags are accepted.
    pub fn parse(s: &str) -> Option<TargetEncoding> {
        match s.to_ascii_lowercase().as_str() {
            "utf-8" => Some(TargetEncoding::Utf8),
            "utf-8-bom" => Some(TargetEncoding::Utf8Bom),
            "gb18030" => Some(TargetEncoding::Gb18030),
            "utf-16le" => Some(TargetEncoding::Utf16Le),
            "utf-16be" => Some(TargetEncoding::Utf16Be),
            _ => None,
        }
    }

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

impl fmt::Display for TargetEncoding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.tag())
    }
}

impl Default for TargetEncoding {
    /// `utf-8` — required by `#[derive(Default)]` on the CLI arg structs.
    fn default() -> Self {
        TargetEncoding::Utf8
    }
}

impl FromStr for TargetEncoding {
    type Err = String;

    /// Enables clap `value_parser` semantics; parse failure → exit code 2.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        TargetEncoding::parse(s).ok_or_else(|| {
            format!(
                "invalid target encoding `{s}` (expected utf-8 | utf-8-bom | gb18030 | utf-16le | utf-16be)"
            )
        })
    }
}

/// Result of transcoding a byte stream.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TranscodeOutcome {
    /// Encoded output is byte-identical to the input (or the fast path hit) —
    /// caller must not write (invariant #5).
    Unchanged,
    /// New bytes to persist.
    Changed(Vec<u8>),
}

/// Strictly decode `bytes` according to a prior [`detect`] verdict.
///
/// BOMs are stripped before decoding. Any `had_errors` from `encoding_rs`
/// aborts with [`ForgeError::DecodeError`] — mojibake is never written.
pub fn decode_strict(bytes: &[u8], enc: DetectedEncoding) -> Result<Cow<'_, str>, ForgeError> {
    match enc {
        DetectedEncoding::Utf8 => std::str::from_utf8(bytes)
            .map(Cow::Borrowed)
            .map_err(|e| ForgeError::DecodeError(format!("invalid utf-8: {e}"))),
        DetectedEncoding::Utf8Bom => std::str::from_utf8(&bytes[3..])
            .map(Cow::Borrowed)
            .map_err(|e| ForgeError::DecodeError(format!("invalid utf-8 after BOM: {e}"))),
        DetectedEncoding::Utf16Le => {
            let (cow, _, had_errors) = UTF_16LE.decode(&bytes[2..]);
            if had_errors {
                return Err(ForgeError::DecodeError("invalid utf-16le sequence".into()));
            }
            Ok(cow)
        }
        DetectedEncoding::Utf16Be => {
            let (cow, _, had_errors) = UTF_16BE.decode(&bytes[2..]);
            if had_errors {
                return Err(ForgeError::DecodeError("invalid utf-16be sequence".into()));
            }
            Ok(cow)
        }
        DetectedEncoding::Gb18030 => {
            let (cow, _, had_errors) = GB18030.decode(bytes);
            if had_errors {
                return Err(ForgeError::DecodeError("invalid gb18030 sequence".into()));
            }
            Ok(cow)
        }
        DetectedEncoding::Unknown => Err(ForgeError::UnknownEncoding),
    }
}

/// Encode `text` into `target`. BOMs for `utf-8-bom` / `utf-16le` /
/// `utf-16be` are prepended manually — `encoding_rs` never emits them.
pub fn encode(text: &str, target: TargetEncoding) -> Vec<u8> {
    match target {
        TargetEncoding::Utf8 => text.as_bytes().to_vec(),
        TargetEncoding::Utf8Bom => {
            let mut v = Vec::with_capacity(3 + text.len());
            v.extend_from_slice(&[0xEF, 0xBB, 0xBF]);
            v.extend_from_slice(text.as_bytes());
            v
        }
        TargetEncoding::Gb18030 => {
            let (cow, _, _) = GB18030.encode(text);
            cow.into_owned()
        }
        TargetEncoding::Utf16Le => {
            let mut v = Vec::with_capacity(2 + text.len() * 2);
            v.extend_from_slice(&[0xFF, 0xFE]);
            let (cow, _, _) = UTF_16LE.encode(text);
            v.extend_from_slice(&cow);
            v
        }
        TargetEncoding::Utf16Be => {
            let mut v = Vec::with_capacity(2 + text.len() * 2);
            v.extend_from_slice(&[0xFE, 0xFF]);
            let (cow, _, _) = UTF_16BE.encode(text);
            v.extend_from_slice(&cow);
            v
        }
    }
}

/// Detect + transcode in one call. Prefer [`transcode_detected`] when the
/// detection verdict is already known (avoids a second sniff).
pub fn transcode(bytes: &[u8], target: TargetEncoding) -> Result<TranscodeOutcome, ForgeError> {
    transcode_detected(bytes, detect(bytes), target)
}

/// Transcode with a pre-computed detection verdict.
///
/// Fast path: `Utf8` → `utf-8` returns [`TranscodeOutcome::Unchanged`] with
/// zero allocation. Otherwise strict-decode, encode, and compare: a
/// byte-identical result is reported as `Unchanged` so callers skip the write
/// (invariants #5 and #10).
pub fn transcode_detected(
    bytes: &[u8],
    detected: DetectedEncoding,
    target: TargetEncoding,
) -> Result<TranscodeOutcome, ForgeError> {
    if detected == DetectedEncoding::Utf8 && target == TargetEncoding::Utf8 {
        return Ok(TranscodeOutcome::Unchanged);
    }
    let text = decode_strict(bytes, detected)?;
    let encoded = encode(&text, target);
    if encoded == bytes {
        Ok(TranscodeOutcome::Unchanged)
    } else {
        Ok(TranscodeOutcome::Changed(encoded))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::detector::detect;

    #[test]
    fn parse_accepts_canonical_tags_case_insensitive() {
        assert_eq!(TargetEncoding::parse("utf-8"), Some(TargetEncoding::Utf8));
        assert_eq!(TargetEncoding::parse("UTF-16LE"), Some(TargetEncoding::Utf16Le));
        assert_eq!(TargetEncoding::parse("gb18030"), Some(TargetEncoding::Gb18030));
        assert_eq!(TargetEncoding::parse("utf-8-bom"), Some(TargetEncoding::Utf8Bom));
        assert_eq!(TargetEncoding::parse("utf-16be"), Some(TargetEncoding::Utf16Be));
        assert_eq!(TargetEncoding::parse("gbk"), None);
        assert_eq!(TargetEncoding::parse(""), None);
    }

    #[test]
    fn utf16_targets_manually_prepend_bom() {
        // "hi" encoded to UTF-16LE must start with FF FE — encoding_rs alone
        // would not emit it (invariant #2).
        assert_eq!(
            encode("hi", TargetEncoding::Utf16Le),
            vec![0xFF, 0xFE, b'h', 0, b'i', 0]
        );
        assert_eq!(
            encode("hi", TargetEncoding::Utf16Be),
            vec![0xFE, 0xFF, 0, b'h', 0, b'i']
        );
        assert_eq!(encode("hi", TargetEncoding::Utf8Bom), {
            let mut v = vec![0xEF, 0xBB, 0xBF];
            v.extend_from_slice(b"hi");
            v
        });
    }

    #[test]
    fn fast_path_utf8_to_utf8_is_unchanged() {
        assert_eq!(
            transcode(b"hello", TargetEncoding::Utf8).unwrap(),
            TranscodeOutcome::Unchanged
        );
    }

    #[test]
    fn empty_bom_only_file_converges_idempotently() {
        let bom = [0xEF, 0xBB, 0xBF];
        let out = match transcode(&bom, TargetEncoding::Utf8).unwrap() {
            TranscodeOutcome::Changed(v) => v,
            TranscodeOutcome::Unchanged => panic!("BOM-only file must change"),
        };
        assert!(out.is_empty());
        // Second pass: empty file detects as Utf8 → fast path.
        assert_eq!(
            transcode(&out, TargetEncoding::Utf8).unwrap(),
            TranscodeOutcome::Unchanged
        );
    }

    #[test]
    fn byte_identical_output_skips_write() {
        // ASCII is identical in GB18030 — must not be reported as Changed.
        assert_eq!(
            transcode(b"plain ascii", TargetEncoding::Gb18030).unwrap(),
            TranscodeOutcome::Unchanged
        );
    }
}