{"record":{"id":"4ec0f5f7be20d6e3","repo":"jdx/mise","slug":"truncated-label-text-bytes-is-not-a-whole-nu","errorCode":null,"errorMessage":"truncated {label} text: {} bytes is not a whole number of code units","messagePattern":"truncated (.+?) text: (.+?) bytes is not a whole number of code units","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"src/file.rs","lineNumber":660,"sourceCode":"/// ordinary on Windows -- see [`decode_text`], which names them.\npub(crate) fn strip_utf8_bom(s: &str) -> &str {\n    s.strip_prefix('\\u{feff}').unwrap_or(s)\n}\n\n/// Decode text that may begin with a byte-order mark.\n///\n/// `std`'s UTF-8-only readers reject UTF-16 outright, which is how a checksum file sank an install\n/// in #5399: PowerShell shipped `hashes.sha256` as UTF-16LE and mise stopped at \"stream did not\n/// contain valid UTF-8\". Windows PowerShell 5.1's `Out-File` writes UTF-16LE by default, so any\n/// project generating checksums that way produces the same thing.\n///\n/// Only a BOM switches the encoding. Detecting UTF-16 without one means guessing from the density\n/// of NUL bytes, which can misfire on binary input; `Out-File` always writes a BOM, so the guess\n/// buys nothing here. Input with no BOM is decoded as UTF-8, exactly as before.\npub(crate) fn decode_text(bytes: &[u8]) -> Result<String> {\n    fn from_utf16(bytes: &[u8], to_u16: fn([u8; 2]) -> u16, label: &str) -> Result<String> {\n        if !bytes.len().is_multiple_of(2) {\n            bail!(\n                \"truncated {label} text: {} bytes is not a whole number of code units\",\n                bytes.len()\n            );\n        }\n        let units = bytes\n            .as_chunks::<2>()\n            .0\n            .iter()\n            .map(|c| to_u16(*c))\n            .collect_vec();\n        String::from_utf16(&units).wrap_err_with(|| format!(\"invalid {label} text\"))\n    }\n\n    match bytes {\n        [0xef, 0xbb, 0xbf, rest @ ..] => {\n            String::from_utf8(rest.to_vec()).wrap_err(\"invalid UTF-8 text after a UTF-8 BOM\")\n        }\n        [0xff, 0xfe, rest @ ..] => from_utf16(rest, u16::from_le_bytes, \"UTF-16LE\"),","sourceCodeStart":642,"sourceCodeEnd":678,"githubUrl":"https://github.com/jdx/mise/blob/533346cc374382b41ec5ff70536252b2e96e725c/src/file.rs#L642-L678","documentation":"PowerShell's `Out-File` can emit UTF-16 text; `decode_text` decodes UTF-16LE/BE only when a BOM is present and requires the byte length to be a whole number of 2-byte code units. Odd-length input means the byte stream is truncated or misidentified, so decoding is refused instead of producing corrupted text.","triggerScenarios":"Calling `from_utf16` (via `decode_text`) with bytes whose length is not a multiple of 2 while a UTF-16 BOM selects that decoder — typically a truncated capture of PowerShell output.","commonSituations":"Capturing/truncating PowerShell `Out-File` output mid-code-unit; piping partial output through a tool that cut the stream at an odd byte boundary; corrupted log files.","solutions":["Re-capture the output without truncation so byte length is even","Strip the broken trailing byte only if you know it's a cut artifact, then retry","Force the producer to emit UTF-8 (e.g. `Out-File -Encoding utf8`) so the UTF-16 path is skipped"],"exampleFix":"// before\ncommand | Out-File out.txt   # utf16, truncated capture\n// after\ncommand | Out-File out.txt -Encoding utf8","handlingStrategy":"validation","validationCode":"function isEvenLength(buf) {\n  return buf.length % 2 === 0; // check before decoding UTF-16 captures\n}\n// also prefer UTF-8: strip BOMs and validate with TextDecoder('utf-8', { fatal: true })","typeGuard":"function hasUtf16Bom(bytes) {\n  return (bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0xfe && bytes[1] === 0xff);\n}\nconst isDecodableUtf16 = (bytes) => hasUtf16Bom(bytes) && bytes.length % 2 === 0;","tryCatchPattern":"try {\n  text = decodeText(bytes);\n} catch (e) {\n  if (String(e).includes('truncated')) {\n    text = new TextDecoder('utf-8').decode(bytes.subarray(0, bytes.length - (bytes.length % 2 === 0 ? 0 : 1)));\n  } else throw e;\n}","preventionTips":["Make PowerShell emit UTF-8 (`Out-File -Encoding utf8`)","Never truncate captured output mid-stream; verify complete writes","Validate capture files end on complete code units before parsing"],"tags":["encoding","utf16","filesystem"],"backgroundTag":"invalid-argument-format","analyzedSha":"533346cc374382b41ec5ff70536252b2e96e725c","analyzedAt":"2026-09-17T13:35:38.149Z","contentChangedAt":"2026-09-17T13:35:38.149Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}