Principle:20000419 Fauxnix Output Encoding And Clipping
| Knowledge Sources | |
|---|---|
| Domains | Encoding, Output_Normalization |
| Last Updated | 2026-10-26 00:00 GMT |
Overview
An output-handling technique that decodes native tool output with a strict-UTF-8-first-then-GBK-fallback strategy and clips caller-visible text to a byte budget at UTF-8 codepoint boundaries without splitting surrogate pairs.
Description
On Windows, PowerShell 5.1 has a single console-encoding knob, so GBK-native admin tools (ipconfig, tasklist) and UTF-8-native dev tools (node, curl) cannot both decode cleanly with one setting. The solution is a preference-driven decoder: in UTF-8 mode it sniffs strictly first (genuine UTF-8 never falls back) and only falls back to GBK when the bytes are invalid UTF-8; in GBK mode (FAUXNIX_NATIVE_ENCODING=ansi) it trusts the setting for admin tools. The clipper keeps the longest whole-codepoint prefix within a caller's byte budget. It never splits a UTF-8 surrogate pair and uses a backward-trim path when the overshoot is small (the common case) or a forward iterator otherwise — both avoid allocating a second full UTF-8 buffer.
Usage
Use this principle when you must return bounded text from a process whose encoding is not fully under your control. The strict-first-fallback-later approach prevents mojibake on genuine UTF-8 while still handling legacy codepages.
Theoretical Basis
decode(buf, prefer):
if prefer == 'gbk': return iconv.decode(buf, 'gbk')
try: return strictUtf8.decode(buf) # genuine UTF-8 → never falls back
catch: return iconv.decode(buf, 'gbk') # not valid UTF-8 → assume ANSI codepage
clipUtf8(text, limit):
total = byteLength(text, 'utf8')
if total <= limit: return {text, truncated: false}
# trim backward (small overshoot) or forward (large overshoot),
# never splitting a surrogate pair