Skip to main content

hpl_cjk_text/
decode.rs

1//! UTF-8 to UTF-16 decoding restricted to the BMP (the engine's `wchar_t` is 16-bit and its
2//! bitmap fonts look glyphs up per code unit).
3
4/// What the decoder had to replace with U+FFFD.
5#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6pub struct DecodeStats {
7    /// Malformed UTF-8 sequences (each maximal invalid run counts once, as in
8    /// `String::from_utf8_lossy`).
9    pub invalid: u32,
10    /// Valid code points above U+FFFF (never emitted as surrogate pairs).
11    pub astral: u32,
12}
13
14const REPLACEMENT: u16 = 0xFFFD;
15
16/// Decodes `bytes`; the result never contains surrogates and is never longer than the input.
17pub fn decode_utf8_bmp(bytes: &[u8]) -> (Vec<u16>, DecodeStats) {
18    let mut out = Vec::with_capacity(bytes.len());
19    let mut stats = DecodeStats::default();
20    for chunk in bytes.utf8_chunks() {
21        for c in chunk.valid().chars() {
22            let cp = c as u32;
23            if cp > 0xFFFF {
24                out.push(REPLACEMENT);
25                stats.astral = stats.astral.saturating_add(1);
26            } else {
27                out.push(cp as u16);
28            }
29        }
30        if !chunk.invalid().is_empty() {
31            out.push(REPLACEMENT);
32            stats.invalid = stats.invalid.saturating_add(1);
33        }
34    }
35    (out, stats)
36}