utf8-forge 0.1.0

A focused, idempotent, bidirectional charset transcoder for source trees. Default output: UTF-8 without BOM.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
# 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

| #  | Goal                                                           | Acceptance                                 |
|----|----------------------------------------------------------------|--------------------------------------------|
| 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

| Tag       | Detection                                                       | Notes                                  |
|-----------|-----------------------------------------------------------------|----------------------------------------|
| `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

| Target            | Output bytes                                        |
|-------------------|-----------------------------------------------------|
| `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

| Source    | Action                                                 |
|-----------|--------------------------------------------------------|
| `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)
.filter( | e| e.file_type().is_file() & & is_whitelisted_ext(e.path(), & cfg.exts))
.map( | e| e.into_path())
.collect();

// Phase 2: parallel process
let results: Vec<FileOutcome> = files
.par_iter()
.map( | p| process_file(p, & cfg))
.collect();

// 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

| Mode                        | When            | Memory                                                                             |
|-----------------------------|-----------------|------------------------------------------------------------------------------------|
| `--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
  -t, --target <ENC>           utf-8 | utf-8-bom | gb18030 | utf-16le | utf-16be
      --dry-run                No writes; report only
      --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

| Change                             | Impact on this tool                   |
|------------------------------------|---------------------------------------|
| `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)

| #  | Invariant                                | Violation Consequence              |
|----|------------------------------------------|------------------------------------|
| 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

| Test                                                    | Expected                        |
|---------------------------------------------------------|---------------------------------|
| `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)

| Decision         | Choice                      | Rationale                                             |
|------------------|-----------------------------|-------------------------------------------------------|
| 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.*