# DESIGN.md — utf8-forge 架构与算法设计
> **Tool**: `utf8-forge` — a focused, idempotent, bidirectional charset transcoder for Windows source trees.
> **Edition**: Rust 2024 (`rust-version = "1.99"`). Resolver `"3"` implied.
> **Status**: Designed against the P1 phase of *Source UTF-8 Unification & Cross-Platform Charset — Executable
Playbook*.
---
## 1. Goals & Non-Goals
### 1.1 Goals
| G1 | Default output **UTF-8 without BOM** | Byte-level verification on every `convert` |
| G2 | **Idempotent**: second run changes 0 bytes | `converted == 0` on re-run |
| G3 | **Lossless round-trip** across all supported encodings | `A→B→A == A` in unit tests |
| G4 | **Whitelist-driven recursion** (never touch binaries / `dep/`) | `dry-run` audit passes |
| G5 | **Atomic writes** (crash-safe) | Temp file + `rename` |
| G6 | **Optional remote download** → transcode → save | `--url` flag works for HTTP/HTTPS |
| G7 | Human-readable + JSON report | `--report` emits stable schema |
| G8 | **Parallel** file processing | `rayon`; report re-sorted by path |
### 1.2 Non-Goals
- No line-ending normalization (CRLF/LF preserved verbatim).
- No BOM-less UTF-16 guessing (only BOM-sniffed UTF-16 is recognized).
- `.rc` excluded by default (`--include-rc` opt-in) — rc.exe has limited UTF-8 support.
- No SVN/Git operations. No compilation. No GUI.
- Remote download is **single-URL fetch**, not recursive crawl / mirroring.
---
## 2. Encoding Model
### 2.1 Detectable Source Encodings
| `Utf8` | No BOM + `str::from_utf8` OK | Fast path; pure ASCII hits here |
| `Utf8Bom` | Starts with `EF BB BF` | BOM stripped on decode |
| `Utf16Le` | Starts with `FF FE` | BOM stripped before decoding |
| `Utf16Be` | Starts with `FE FF` | Same |
| `Gb18030` | UTF-8 strict fail → `GB18030.decode` with `had_errors == false` | Covers GB2312/GBK/GB18030 |
| `Unknown` | All above fail | Reported & skipped — **never guessed** |
**Detection order is frozen**: UTF-8 → GB18030. Reordering breaks idempotence on ASCII-only files.
### 2.2 Target Encodings
| `utf-8` (default) | `text.as_bytes().to_vec()` — **no BOM** |
| `utf-8-bom` | `[EF,BB,BF] ++ text.as_bytes()` — BOM **manual** |
| `gb18030` | `GB18030.encode(text)` |
| `utf-16le` | `[FF,FE] ++ UTF_16LE.encode(text)` — BOM **manual** |
| `utf-16be` | `[FE,FF] ++ UTF_16BE.encode(text)` — BOM **manual** |
> **Critical invariant**: `encoding_rs`’s `UTF_16LE/BE` encoders **do not emit BOM**. The BOM must be prepended by
> `utf8-forge` itself. Forgetting this produces files that `detect()` would classify as `Utf8` or `Unknown`.
### 2.3 Line Endings & Surrogates
`encoding_rs` performs **no newline normalization**. `"\r\n"` survives UTF-16 ↔ UTF-8 round-trips byte-identically.
Invalid UTF-16 surrogate pairs set `had_errors = true` → hard error, never a half-written file.
---
## 3. Detection Algorithm (frozen)
```rust
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
}
```
**Why not `chardetng`?** The target tree is known to be GB18030 + some UTF-16 + UTF-8. Statistical detection produces
false positives on short files and destroys determinism. Rule-based detection is auditable and reproducible.
---
## 4. Transcoding
### 4.1 Fast Path
```rust
if src == DetectedEncoding::Utf8 & & target == TargetEncoding::Utf8 {
return TranscodeOutcome::Unchanged; // zero byte allocation
}
```
### 4.2 Strict Decode
| `Utf8` | `str::from_utf8(bytes)?` |
| `Utf8Bom` | `str::from_utf8(&bytes[3..])?` |
| `Utf16Le` | `UTF_16LE.decode(&bytes[2..])`; reject on `had_errors` |
| `Utf16Be` | `UTF_16BE.decode(&bytes[2..])`; reject on `had_errors` |
| `Gb18030` | `GB18030.decode(bytes)`; reject on `had_errors` |
| `Unknown` | `Err(UnknownEncoding)` — **no guessing** |
### 4.3 Encode (BOM handling)
```rust
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
}
}
}
```
### 4.4 Idempotence Proof
- `Utf8` (no BOM) + `target = utf-8` → `Unchanged` (fast path).
- `Utf8Bom` + `target = utf-8` → BOM stripped; second run sees `Utf8` → `Unchanged`.
- `Gb18030` + `target = utf-8` → UTF-8; second run sees `Utf8` → `Unchanged`.
✅ **Any input converges to `Utf8` in one pass; second pass is a no-op.**
---
## 5. File Selection
### 5.1 Default Extension Whitelist
```rust
// Source code + config/data + docs (safe set)
const DEFAULT_EXTENSIONS: &[&str] = &[
// C / C++
"c", "cc", "cpp", "cxx", "c++", "h", "hh", "hpp", "hxx", "h++",
"inl", "ipp", "tpp", "ixx", "m", "mm",
// .NET / JVM
"cs", "csx", "java", "kt", "kts",
// Other languages
"rs", "go", "py", "pyi", "rb", "php", "pl", "pm", "lua",
"js", "jsx", "ts", "tsx", "mjs", "cjs",
"sh", "bash", "zsh", "ps1", "bat", "cmd",
// Data / config
"json", "jsonc", "yaml", "yml", "toml", "ini", "cfg", "conf",
"xml", "csv", "tsv", "sql",
// Docs / protocol
"md", "markdown", "txt", "rst", "proto",
];
// Opt-in only (not enabled by default)
const OPT_IN_EXTENSIONS: &[&str] = &[
"rc", "rc2", "dlg", // rc.exe limited UTF-8
"sln", "vcxproj", "vcproj", "props", "targets", "filters", "user", // VS re-saves with BOM
];
```
### 5.2 Excluded Directories (case-insensitive + prefix rules)
```rust
const DEFAULT_EXCLUDE_DIRS: &[&str] = &[
"dep", "deps", "third_party", "third-party", "3rdparty", "vendor", "external", "extern",
"_tools", "tools_bin",
".svn", ".git", ".hg", ".vs", ".idea", ".vscode",
"build", "out", "bin", "obj", "debug", "release", "target",
"node_modules", "__pycache__", ".venv", "venv",
"temp", "tmp", "cache",
];
const DEFAULT_EXCLUDE_PREFIXES: &[&str] = &[
"outputfile", // OutputFile* / OutputFiles*
];
```
### 5.3 Additional Skips
- Symlinks: `follow_links(false)` — walker prunes automatically.
- Extension matching: `to_ascii_lowercase()`.
- `--max-file-size` (default 200 MiB) → recorded as `too_large`.
- Hidden files (`.`-prefixed) skipped unless `--include-hidden`.
---
## 6. Traversal & Concurrency
```rust
// Phase 1: collect candidates (prune dirs early)
let files: Vec<PathBuf> = WalkDir::new(root)
.follow_links(false)
.into_iter()
.filter_entry( | e| ! is_excluded_dir(e.file_name(), & cfg))
.filter_map(Result::ok)
.collect();
// Phase 2: parallel process
let results: Vec<FileOutcome> = files
.par_iter()
// Phase 3: deterministic order
results.sort_by( | a, b| a.path.cmp( & b.path));
```
No shared mutable state between files. IO-bound workload; default rayon thread pool is appropriate. `--threads`
overrides via `ThreadPoolBuilder`.
---
## 7. Atomic Writes
```rust
pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
let parent = path.parent().unwrap_or(Path::new("."));
let tmp = unique_tmp_path(parent, path);
{
let mut f = fs::File::create(&tmp)?;
f.write_all(bytes)?;
f.sync_all()?;
}
if let Ok(meta) = fs::metadata(path) {
let _ = fs::set_permissions(&tmp, meta.permissions());
}
fs::rename(&tmp, path)?; // atomic on same volume
Ok(())
}
```
**Never truncate-then-write**: a crash mid-write destroys source code. Temp file + rename guarantees either old or new
content, never neither.
`--backup-dir` copies original bytes **before** rename, preserving relative path structure.
`--dry-run` records `would_convert` without touching disk.
---
## 8. Remote Download (Optional Feature)
### 8.1 Design
A new **`--url` flag** on `convert` enables:
```
Fetch URL → temp buffer (streaming) → detect → transcode → save to --output (or derived filename)
```
This reuses the **exact same** `detect()` / `transcode()` pipeline; only the source of `raw_bytes` changes.
### 8.2 CLI Surface
```text
utf8-forge convert --url <URL> --output <PATH> [--target utf-8] [--report out.json]
# If --output omitted, derive from URL last path segment
# https://example.com/data/legacy.cpp → legacy.cpp
# https://example.com/foo (no segment) → foo.utf8
```
### 8.3 Streaming vs Buffering
| `--max-file-size` respected | Default | `bytes()` buffers whole response; cap enforced via `Content-Length` + reader limit |
| Streaming (future) | Files > 200 MiB | `chunk()` loop to temp file |
Current implementation: **`reqwest::blocking` with `bytes()`**, capped by `--max-file-size`. This is simple,
predictable, and correct for source files (almost always < 10 MiB). `reqwest` blocking API is explicitly documented for
CLI use.
### 8.4 HTTPS & Redirects
`reqwest::blocking::Client` is built with:
- `redirect::Policy::limited(5)`
- `danger_accept_invalid_certs(false)` (default; configurable via future flag)
- Timeout 30 s (connect) / 120 s (total)
### 8.5 Security Notes
- URL is **user-supplied**; no recursive link following.
- Downloaded content is treated as **untrusted text** — detection + strict decoding prevents injection via malformed
byte sequences.
- No shell execution.
### 8.6 Implementation Sketch
```rust
fn fetch_bytes(url: &str, max_size: usize) -> Result<Vec<u8>> {
let client = reqwest::blocking::Client::builder()
.timeout(Duration::from_secs(120))
.redirect(reqwest::redirect::Policy::limited(5))
.build()?;
let resp = client.get(url).send()?.error_for_status()?;
if let Some(len) = resp.content_length() {
if len as usize > max_size { bail!("remote file exceeds --max-file-size"); }
}
let bytes = resp.bytes()?.to_vec();
if bytes.len() > max_size { bail!("remote file exceeds --max-file-size"); }
Ok(bytes)
}
fn derive_output_path(url: &str) -> PathBuf {
let seg = url::Url::parse(url).ok()
.and_then(|u| u.path_segments()?.next_back().map(str::to_owned))
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "download.bin".into());
PathBuf::from(seg).with_extension("utf8")
}
```
---
## 9. CLI Interface (v0.2)
```text
utf8-forge <COMMAND> [OPTIONS]
COMMANDS:
scan Detect only; report distribution (no writes)
convert Detect + transcode + atomic write (supports --dry-run)
verify Assert all whitelisted files are UTF-8 without BOM
GLOBAL OPTIONS:
-r, --root <PATH> Root directory (default .)
-e, --ext <LIST> Override default extension whitelist
-x, --exclude <LIST> Extra excluded directories
-X, --exclude-ext <LIST> Extra excluded extensions
--exclude-glob <GLOB> Extra directory glob exclusion
--include-rc Include .rc/.rc2/.dlg
--include-msbuild Include .sln/.vcxproj/...
--include-hidden Process dot-prefixed files/dirs
--backup-dir <PATH> Backup original bytes before overwrite
--max-file-size <BYTES> Skip files above this size (default 200 MiB)
--threads <N> Rayon thread count
--report <PATH> Write JSON report
-q, --quiet Errors only
-v, --verbose Per-file detail
REMOTE DOWNLOAD (convert only):
--url <URL> Fetch remote file and transcode
--output <PATH> Destination for --url (derived if omitted)
EXAMPLES:
utf8-forge scan --root D:\server --report scan.json
utf8-forge convert --root D:\server --dry-run
utf8-forge convert --url https://example.com/legacy.cpp --output ./legacy.cpp
```
---
## 10. Dependencies (Latest as of 2026-11)
```toml
[package]
name = "utf8-forge"
version = "0.2.0"
edition = "2024"
rust-version = "1.85" # edition 2024 MSRV
[[bin]]
name = "utf8-forge"
path = "src/main.rs"
[dependencies]
anyhow = "1.0.104" # latest
clap = { version = "4.6.7", features = ["derive"] } # latest stable
encoding_rs = "0.8.42" # latest
rayon = "1.12.0" # latest
reqwest = { version = "0.13.5", features = ["blocking"], optional = true } # latest stable; 0.13.0-rc.1 available if RC is desired
serde = { version = "1.0.228", features = ["derive"] } # latest
serde_json = "1.0.154" # latest
url = "2.5" # for path derivation
walkdir = "2.5.0" # latest
[dev-dependencies]
tempfile = "3.27.0" # latest
[features]
default = ["remote"]
remote = ["reqwest"] # disable with --no-default-features
```
**RC/Beta note**: User permits RC/beta. If desired, replace `reqwest = "0.13.5"` with `reqwest = "0.13.0-rc.1"` — but
stable `0.13.5` is already available and newer. No other crate currently has a meaningful RC/beta that improves this
tool.
### 10.1 Rust 2024 Considerations
| `unsafe extern` blocks | No `extern` blocks used |
| RPIT lifetime capture | No RPIT-heavy code |
| `gen` reserved keyword | No `gen` identifiers |
| Prelude adds `Future`/`IntoFuture` | No ambiguity in current traits |
| Resolver = "3" implied | Correct; dependencies resolve by MSRV |
No migration shims required.
---
## 11. Key Invariants (Maintainer Must Preserve)
| 1 | Default target = UTF-8 **without BOM** | Breaks Playbook Strategy A |
| 2 | UTF-16 encoders **manually prepend BOM** | Output misidentified |
| 3 | No line-ending normalization | Diff noise |
| 4 | Whitelist + blacklist double gate | Binary/third-party corruption |
| 5 | Byte-identical → skip write | Spurious mtime / SVN churn |
| 6 | Temp file + `rename` atomic write | Source destruction on crash |
| 7 | `had_errors == true` → hard error | Half-written / mojibake files |
| 8 | Report sorted by `path` | Non-reproducible audits |
| 9 | No symlink recursion | Infinite loops / collateral damage |
| 10 | Second `convert` changes 0 bytes | Non-idempotent regression |
---
## 12. Module Layout
```
utf8-forge/
├── Cargo.toml
├── README.md # English (default)
├── README.zh-CN.md # Chinese
├── AGENT.md
├── EXECUTION.md
├── DESIGN.md
├── docs/
│ ├── USAGE.md # English usage guide
│ └── USAGE.zh-CN.md # Chinese usage guide
├── src/
│ ├── main.rs # Entry, subcommand dispatch, exit codes
│ ├── cli.rs # clap definitions
│ ├── detector.rs # detect() + DetectedEncoding
│ ├── transcoder.rs # decode_strict / encode / transcode
│ ├── filter.rs # Extension & directory filtering
│ ├── walker.rs # walkdir wrapper + candidate collection
│ ├── writer.rs # Atomic write + backup
│ ├── fetcher.rs # Optional remote download (reqwest)
│ ├── reporter.rs # Console summary + JSON serialization
│ └── error.rs # Custom error types
└── tests/
├── detect.rs
├── transcode.rs
├── filter.rs
├── fetch.rs
└── end_to_end.rs
```
**English comment policy**: Every public function, module, and non-trivial code block carries a `///` or `//` comment in
English. Chinese comments are permitted only in `docs/USAGE.zh-CN.md` and `README.zh-CN.md`. No mixed-language comments
in `src/`.
---
## 13. Testing Strategy
| `detect(b"hello")` | `Utf8` |
| `detect(b"\xEF\xBB\xBFhello")` | `Utf8Bom` |
| `detect(b"\xFF\xFEh\0i\0")` | `Utf16Le` |
| `detect(GBK "你好")` | `Gb18030` |
| `detect(b"\xFF\xFF\xFF")` | `Unknown` |
| `transcode(Utf8, Utf8)` | `Unchanged` (fast path) |
| `transcode(Utf8Bom, Utf8)` twice | 2nd `Unchanged` (idempotent) |
| `transcode(GBK "你好", Utf8)` → `transcode(…, Gb18030)` | Bytes identical to original GBK |
| `filter`: `foo.PNG` | Not whitelisted |
| `filter`: `dep/` | Pruned |
| `fetch`: mock HTTP server returns GBK | Transcodes to UTF-8 |
| `fetch`: oversized response | `Err(too_large)` |
| `end_to_end`: mixed temp tree | Summary counts match |
CI gates: `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings`, `cargo test`.
---
## 14. ADR (v0.2 Deltas)
| Edition | **2024** | MSRV 1.85; resolver 3; modern idioms |
| `reqwest` | **0.13.5** stable | Latest stable; RC available but unnecessary |
| Remote download | **Opt-in `--url`** | Reuses pipeline; zero risk to local path |
| Streaming | **Deferred** | Source files are small; `bytes()` + cap is sufficient |
| English comments | **Mandatory in `src/`** | Cross-team auditability |
| README | **English default + zh-CN** | Matches user request |
---
*DESIGN.md v0.2 — All maintainers must read §11 before modifying code.*