vtcode_commons/
utf8_stream.rs1use std::borrow::Cow;
4
5#[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 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 String::from_utf8(out).unwrap_or_else(|error| String::from_utf8_lossy(error.as_bytes()).into_owned())
32 }
33
34 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 #[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 out.extend_from_slice(valid_bytes);
71 }
72 match err.error_len() {
73 Some(invalid_len) => {
75 out.extend_from_slice("\u{FFFD}".as_bytes());
76 offset += valid + invalid_len;
77 }
78 None => {
80 let _ = self.pending.drain(..offset + valid);
81 break;
82 }
83 }
84 }
85 }
86 }
87 }
88
89 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 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 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 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 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}