|
| 1 | +pub(crate) struct Utf8StreamDecoder { |
| 2 | + pending: Vec<u8>, |
| 3 | +} |
| 4 | + |
| 5 | +impl Utf8StreamDecoder { |
| 6 | + pub(crate) fn new() -> Self { |
| 7 | + Self { |
| 8 | + pending: Vec::new(), |
| 9 | + } |
| 10 | + } |
| 11 | + |
| 12 | + pub(crate) fn push(&mut self, chunk: &[u8]) -> String { |
| 13 | + if chunk.is_empty() { |
| 14 | + return String::new(); |
| 15 | + } |
| 16 | + |
| 17 | + self.pending.extend_from_slice(chunk); |
| 18 | + let mut output = String::new(); |
| 19 | + |
| 20 | + loop { |
| 21 | + match std::str::from_utf8(&self.pending) { |
| 22 | + Ok(valid) => { |
| 23 | + output.push_str(valid); |
| 24 | + self.pending.clear(); |
| 25 | + break; |
| 26 | + } |
| 27 | + Err(error) => { |
| 28 | + let valid_up_to = error.valid_up_to(); |
| 29 | + if valid_up_to > 0 { |
| 30 | + let valid = |
| 31 | + std::str::from_utf8(&self.pending[..valid_up_to]).unwrap_or_default(); |
| 32 | + output.push_str(valid); |
| 33 | + self.pending.drain(..valid_up_to); |
| 34 | + } |
| 35 | + |
| 36 | + match error.error_len() { |
| 37 | + Some(len) => { |
| 38 | + output.push('\u{FFFD}'); |
| 39 | + self.pending.drain(..len); |
| 40 | + } |
| 41 | + None => break, |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + output |
| 48 | + } |
| 49 | + |
| 50 | + pub(crate) fn finish(&mut self) -> String { |
| 51 | + if self.pending.is_empty() { |
| 52 | + return String::new(); |
| 53 | + } |
| 54 | + let flushed = String::from_utf8_lossy(&self.pending).to_string(); |
| 55 | + self.pending.clear(); |
| 56 | + flushed |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +#[cfg(test)] |
| 61 | +mod tests { |
| 62 | + use super::Utf8StreamDecoder; |
| 63 | + |
| 64 | + #[test] |
| 65 | + fn decodes_multibyte_characters_split_across_chunks() { |
| 66 | + let mut decoder = Utf8StreamDecoder::new(); |
| 67 | + |
| 68 | + let first = decoder.push(&[0xE4, 0xBD]); |
| 69 | + let second = decoder.push(&[0xA0, 0xE5, 0xA5, 0xBD]); |
| 70 | + let flushed = decoder.finish(); |
| 71 | + |
| 72 | + assert_eq!(first, ""); |
| 73 | + assert_eq!(second, "你好"); |
| 74 | + assert_eq!(flushed, ""); |
| 75 | + } |
| 76 | + |
| 77 | + #[test] |
| 78 | + fn preserves_invalid_bytes_with_replacement_and_continues() { |
| 79 | + let mut decoder = Utf8StreamDecoder::new(); |
| 80 | + |
| 81 | + let output = decoder.push(&[0x66, 0x80, 0x6F, 0x6F]); |
| 82 | + |
| 83 | + assert_eq!(output, "f\u{FFFD}oo"); |
| 84 | + } |
| 85 | +} |
0 commit comments