Skip to main content

vtcode_commons/
utf8_stream.rs

1//! Incremental UTF-8 decoding across chunk boundaries (network streams, pipe reads).
2
3use std::borrow::Cow;
4
5/// Incrementally decodes a byte stream into UTF-8 text.
6///
7/// Chunks can split a multibyte code point (CJK, emoji, accented characters,
8/// smart quotes) across boundaries. Decoding each chunk independently with
9/// `String::from_utf8_lossy` corrupts such code points into `U+FFFD`
10/// replacement characters. This decoder buffers any trailing incomplete
11/// sequence until the rest of its bytes arrive, while still replacing genuinely
12/// invalid bytes with `U+FFFD` (matching `from_utf8_lossy` semantics). Call
13/// [`Utf8StreamDecoder::finish`] at end of stream so a truncated final sequence
14/// becomes `U+FFFD` instead of vanishing.
15#[derive(Debug, Default)]
16pub struct Utf8StreamDecoder {
17    pending: Vec<u8>,
18}
19
20impl Utf8StreamDecoder {
21    pub fn new() -> Self {
22        Self::default()
23    }
24
25    /// Appends `bytes` and returns the decodable UTF-8 prefix. A trailing
26    /// incomplete multibyte sequence is retained for the next call.
27    pub fn push(&mut self, bytes: &[u8]) -> String {
28        let mut out = Vec::with_capacity(bytes.len());
29        self.push_bytes(bytes, &mut out);
30        // `push_bytes` only ever writes valid UTF-8, so this never allocates a lossy copy.
31        String::from_utf8(out).unwrap_or_else(|error| String::from_utf8_lossy(error.as_bytes()).into_owned())
32    }
33
34    /// Like [`Utf8StreamDecoder::push`], but borrows `bytes` without copying when
35    /// nothing is pending and the chunk is valid UTF-8 (the common case for
36    /// process output), so hot read loops avoid a per-chunk allocation.
37    pub fn push_cow<'a>(&mut self, bytes: &'a [u8]) -> Cow<'a, str> {
38        if self.pending.is_empty()
39            && let Ok(text) = std::str::from_utf8(bytes)
40        {
41            return Cow::Borrowed(text);
42        }
43        Cow::Owned(self.push(bytes))
44    }
45
46    /// Appends `bytes` and writes the decodable UTF-8 prefix directly into
47    /// `out`. A trailing incomplete multibyte sequence is retained for the
48    /// next call.
49    ///
50    /// This avoids the intermediate `String` allocation that `push` creates
51    /// when the caller only needs bytes (e.g. feeding an SSE byte buffer).
52    #[expect(
53        clippy::indexing_slicing,
54        reason = "offset advances only over validated bytes within pending"
55    )]
56    pub fn push_bytes(&mut self, bytes: &[u8], out: &mut Vec<u8>) {
57        self.pending.extend_from_slice(bytes);
58        let mut offset = 0;
59        loop {
60            match std::str::from_utf8(&self.pending[offset..]) {
61                Ok(text) => {
62                    out.extend_from_slice(text.as_bytes());
63                    self.pending.clear();
64                    break;
65                }
66                Err(err) => {
67                    let valid = err.valid_up_to();
68                    if let Some(valid_bytes) = self.pending.get(offset..offset + valid) {
69                        // `valid_bytes` is guaranteed valid UTF-8 by `valid_up_to`.
70                        out.extend_from_slice(valid_bytes);
71                    }
72                    match err.error_len() {
73                        // Genuinely invalid sequence: emit replacement and skip it.
74                        Some(invalid_len) => {
75                            out.extend_from_slice("\u{FFFD}".as_bytes());
76                            offset += valid + invalid_len;
77                        }
78                        // Incomplete trailing sequence: keep it for the next push.
79                        None => {
80                            let _ = self.pending.drain(..offset + valid);
81                            break;
82                        }
83                    }
84                }
85            }
86        }
87    }
88
89    /// Ends the stream: returns any retained incomplete sequence lossily
90    /// decoded (as `U+FFFD`), leaving the decoder empty.
91    pub fn finish(&mut self) -> String {
92        let pending = std::mem::take(&mut self.pending);
93        String::from_utf8_lossy(&pending).into_owned()
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    #[test]
102    fn push_bytes_matches_push_byte_by_byte() {
103        let full = "data: {\"hello\":\"world\"} xin chào 世界\n\n".as_bytes();
104        let mut dec_str = Utf8StreamDecoder::new();
105        let mut dec_bytes = Utf8StreamDecoder::new();
106        let mut joined = String::new();
107        for (i, &byte) in full.iter().enumerate() {
108            let mut out = Vec::new();
109            dec_bytes.push_bytes(std::slice::from_ref(&byte), &mut out);
110            let s = dec_str.push(std::slice::from_ref(&byte));
111            assert_eq!(out, s.clone().into_bytes(), "byte {i}: push_bytes must match push");
112            joined.push_str(&s);
113        }
114        assert_eq!(joined.as_bytes(), full);
115        assert!(dec_str.finish().is_empty());
116    }
117
118    #[test]
119    fn split_multibyte_is_held_until_complete() {
120        // U+00E9 = 0xC3 0xA9 split across chunks.
121        let mut dec = Utf8StreamDecoder::new();
122        assert!(dec.push(&[0xC3]).is_empty(), "incomplete multibyte should produce no output");
123        assert_eq!(dec.push(&[0xA9, b'h', b'i']), "\u{00E9}hi");
124    }
125
126    #[test]
127    fn invalid_bytes_become_replacement_characters() {
128        // 0xFF is never a valid UTF-8 lead byte.
129        let mut dec = Utf8StreamDecoder::new();
130        assert_eq!(dec.push(&[b'a', 0xFF, b'b']), "a\u{FFFD}b");
131    }
132
133    #[test]
134    fn invalid_bytes_and_split_suffix_match_lossy_decoding() {
135        let mut decoder = Utf8StreamDecoder::new();
136        let first = [b'a', 0xff, b'b', 0xfe, 0xe2, 0x80];
137        let second = [0x94, 0xff, b'z'];
138        let mut decoded = decoder.push(&first);
139        decoded.push_str(&decoder.push(&second));
140        decoded.push_str(&decoder.finish());
141        let bytes = [first.as_slice(), second.as_slice()].concat();
142        assert_eq!(decoded, String::from_utf8_lossy(&bytes));
143    }
144
145    #[test]
146    fn push_cow_borrows_valid_chunks_and_buffers_splits() {
147        let mut dec = Utf8StreamDecoder::new();
148        assert!(matches!(dec.push_cow("plain 世".as_bytes()), Cow::Borrowed("plain 世")));
149        // `界` = E7 95 8C split across chunks: nothing until complete, then owned.
150        assert_eq!(dec.push_cow(&[0xE7, 0x95]), "");
151        let completed = dec.push_cow(&[0x8C, b'!']);
152        assert!(matches!(completed, Cow::Owned(_)));
153        assert_eq!(completed, "界!");
154        assert!(dec.finish().is_empty());
155    }
156
157    #[test]
158    fn finish_flushes_a_truncated_final_sequence() {
159        let mut dec = Utf8StreamDecoder::new();
160        // First two bytes of the three-byte `—` (0xE2 0x80 0x94).
161        assert_eq!(dec.push(&[b'x', 0xE2, 0x80]), "x");
162        assert_eq!(dec.finish(), "\u{FFFD}");
163        assert!(dec.finish().is_empty(), "finish leaves the decoder empty");
164    }
165}