Coverage Report

Created: 2026-12-01 06:53

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/quick-xml/src/encoding.rs
Line
Count
Source
1
//! A module for wrappers that encode / decode data.
2
3
use std::str::Utf8Error;
4
5
#[cfg(feature = "encoding")]
6
use encoding_rs;
7
#[cfg(feature = "encoding")]
8
use std::borrow::Cow;
9
#[cfg(feature = "encoding")]
10
use std::io::{self, BufRead, Read};
11
12
/// Unicode "byte order mark" (\u{FEFF}) encoded as UTF-8.
13
/// See <https://unicode.org/faq/utf_bom.html#bom1>
14
pub(crate) const UTF8_BOM: &[u8] = &[0xEF, 0xBB, 0xBF];
15
/// Unicode "byte order mark" (\u{FEFF}) encoded as UTF-16 with little-endian byte order.
16
/// See <https://unicode.org/faq/utf_bom.html#bom1>
17
pub(crate) const UTF16_LE_BOM: &[u8] = &[0xFF, 0xFE];
18
/// Unicode "byte order mark" (\u{FEFF}) encoded as UTF-16 with big-endian byte order.
19
/// See <https://unicode.org/faq/utf_bom.html#bom1>
20
pub(crate) const UTF16_BE_BOM: &[u8] = &[0xFE, 0xFF];
21
22
/// Returns `true` if `encoding` is UTF-16 in any byte order.
23
///
24
/// The byte order of a UTF-16 document is determined by its BOM or by the bytes
25
/// of the XML declaration, not by the encoding name: the declaration says just
26
/// `encoding="UTF-16"` for both byte orders. Because [`Encoding::for_label`]
27
/// maps the `UTF-16` label to UTF-16LE, the encoding named in the declaration
28
/// must not replace a byte order that was already detected from the content.
29
///
30
/// [`Encoding::for_label`]: encoding_rs::Encoding::for_label
31
#[cfg(feature = "encoding")]
32
pub(crate) fn is_utf16(encoding: &'static encoding_rs::Encoding) -> bool {
33
    encoding == encoding_rs::UTF_16BE || encoding == encoding_rs::UTF_16LE
34
}
35
36
/// An error when decoding or encoding
37
///
38
/// If feature [`encoding`] is disabled, the [`EncodingError`] is always [`EncodingError::Utf8`]
39
///
40
/// [`encoding`]: ../index.html#encoding
41
#[derive(Clone, Debug, PartialEq, Eq)]
42
#[non_exhaustive]
43
pub enum EncodingError {
44
    /// Input was not valid UTF-8
45
    Utf8(Utf8Error),
46
    /// Input did not adhere to the given encoding
47
    #[cfg(feature = "encoding")]
48
    Other(&'static encoding_rs::Encoding),
49
}
50
51
impl From<Utf8Error> for EncodingError {
52
    #[inline]
53
    fn from(e: Utf8Error) -> Self {
54
        Self::Utf8(e)
55
    }
56
}
57
58
impl std::error::Error for EncodingError {
59
0
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
60
0
        match self {
61
0
            Self::Utf8(e) => e.source(),
62
            #[cfg(feature = "encoding")]
63
            Self::Other(_) => None,
64
        }
65
0
    }
66
}
67
68
impl std::fmt::Display for EncodingError {
69
0
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70
0
        match self {
71
0
            Self::Utf8(e) => e.fmt(f),
72
            #[cfg(feature = "encoding")]
73
            Self::Other(encoding) => write!(f, "cannot decode input using {}", encoding.name()),
74
        }
75
0
    }
76
}
77
78
/// Decoder of byte slices into strings.
79
///
80
/// If feature [`encoding`] is enabled, this encoding taken from the `"encoding"`
81
/// XML declaration or assumes UTF-8, if XML has no <?xml ?> declaration, encoding
82
/// key is not defined or contains unknown encoding.
83
///
84
/// The library supports any UTF-8 compatible encodings that crate `encoding_rs`
85
/// is supported. [*UTF-16 and ISO-2022-JP are not supported at the present*][utf16].
86
///
87
/// If feature [`encoding`] is disabled, the decoder is always UTF-8 decoder:
88
/// any XML declarations are ignored.
89
///
90
/// [utf16]: https://github.com/tafia/quick-xml/issues/158
91
/// [`encoding`]: ../index.html#encoding
92
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
93
pub struct Decoder {
94
    #[cfg(feature = "encoding")]
95
    pub(crate) encoding: &'static encoding_rs::Encoding,
96
}
97
98
/// Decodes the provided bytes using the specified encoding.
99
///
100
/// Returns an error in case of malformed or non-representable sequences in the `bytes`.
101
#[cfg(feature = "encoding")]
102
pub fn decode<'b>(
103
    bytes: &'b [u8],
104
    encoding: &'static encoding_rs::Encoding,
105
) -> Result<Cow<'b, str>, EncodingError> {
106
    encoding
107
        .decode_without_bom_handling_and_without_replacement(bytes)
108
        .ok_or(EncodingError::Other(encoding))
109
}
110
111
/// Like [`decode`] but using a pre-allocated buffer.
112
#[cfg(feature = "encoding")]
113
pub fn decode_into(
114
    bytes: &[u8],
115
    encoding: &'static encoding_rs::Encoding,
116
    buf: &mut String,
117
) -> Result<(), EncodingError> {
118
    if encoding == encoding_rs::UTF_8 {
119
        buf.push_str(std::str::from_utf8(bytes)?);
120
        return Ok(());
121
    }
122
123
    let mut decoder = encoding.new_decoder_without_bom_handling();
124
    buf.reserve(
125
        decoder
126
            .max_utf8_buffer_length_without_replacement(bytes.len())
127
            // SAFETY: None can be returned only if required size will overflow usize,
128
            // but in that case String::reserve also panics
129
            .unwrap(),
130
    );
131
    let (result, read) = decoder.decode_to_string_without_replacement(bytes, buf, true);
132
    match result {
133
        encoding_rs::DecoderResult::InputEmpty => {
134
            debug_assert_eq!(read, bytes.len());
135
            Ok(())
136
        }
137
        encoding_rs::DecoderResult::Malformed(_, _) => Err(EncodingError::Other(encoding)),
138
        // SAFETY: We allocate enough space above
139
        encoding_rs::DecoderResult::OutputFull => unreachable!(),
140
    }
141
}
142
143
/// Automatic encoding detection of XML files based using the
144
/// [recommended algorithm](https://www.w3.org/TR/xml11/#sec-guessing).
145
///
146
/// If encoding is detected, `Some` is returned with a [`DetectedEncoding`] that provides
147
/// the BOM size in bytes (or zero if no BOM was present).
148
///
149
/// IF encoding was not recognized, `None` is returned.
150
///
151
/// Because the [`encoding_rs`] crate supports only subset of those encodings, only
152
/// the supported subset are detected, which is UTF-8, UTF-16 BE and UTF-16 LE.
153
///
154
/// The algorithm suggests examine up to the first 4 bytes to determine encoding
155
/// according to the following table:
156
///
157
/// | Bytes       |Detected encoding
158
/// |-------------|------------------------------------------
159
/// | **BOM**
160
/// |`FE_FF_##_##`|UTF-16, big-endian
161
/// |`FF FE ## ##`|UTF-16, little-endian
162
/// |`EF BB BF`   |UTF-8
163
/// | **No BOM**
164
/// |`00 3C 00 3F`|UTF-16 BE or ISO-10646-UCS-2 BE or similar 16-bit BE (use declared encoding to find the exact one)
165
/// |`3C 00 3F 00`|UTF-16 LE or ISO-10646-UCS-2 LE or similar 16-bit LE (use declared encoding to find the exact one)
166
/// |`3C 3F 78 6D`|UTF-8, ISO 646, ASCII, some part of ISO 8859, Shift-JIS, EUC, or any other 7-bit, 8-bit, or mixed-width encoding which ensures that the characters of ASCII have their normal positions, width, and values; the actual encoding declaration must be read to detect which of these applies, but since all of these encodings use the same bit patterns for the relevant ASCII characters, the encoding declaration itself may be read reliably
167
0
pub fn detect_encoding(bytes: &[u8]) -> Option<DetectedEncoding> {
168
    // Prevent suggesting "<?xm". We want to have the same formatted lines for all arms.
169
    #[allow(clippy::byte_char_slices)]
170
0
    match bytes {
171
        // with BOM
172
0
        _ if bytes.starts_with(UTF16_BE_BOM) => Some(DetectedEncoding::Utf16BeBom),
173
0
        _ if bytes.starts_with(UTF16_LE_BOM) => Some(DetectedEncoding::Utf16LeBom),
174
0
        _ if bytes.starts_with(UTF8_BOM) => Some(DetectedEncoding::Utf8Bom),
175
176
        // without BOM
177
0
        _ if bytes.starts_with(&[0x00, b'<', 0x00, b'?']) => Some(DetectedEncoding::Utf16BeLike), // Some BE encoding, for example, UTF-16 or ISO-10646-UCS-2
178
0
        _ if bytes.starts_with(&[b'<', 0x00, b'?', 0x00]) => Some(DetectedEncoding::Utf16LeLike), // Some LE encoding, for example, UTF-16 or ISO-10646-UCS-2
179
0
        _ if bytes.starts_with(&[b'<', b'?', b'x', b'm']) => {
180
0
            Some(DetectedEncoding::AsciiCompatible)
181
        } // Some ASCII compatible
182
183
0
        _ => None,
184
    }
185
0
}
186
187
/// Possible scenarios for start-of-xml detection of encoding
188
///
189
/// See the documentation of [`detect_encoding`]
190
pub enum DetectedEncoding {
191
    /// Matches UTF-8 or some other ascii-compatible encoding
192
    AsciiCompatible,
193
    /// We saw a UTF-8 BOM
194
    Utf8Bom,
195
    /// Matches UTF-16-LE or some other UTF-16 compatible encoding (e.g. ISO-10646-UCS-2)
196
    Utf16LeLike,
197
    /// We saw a UTF-16 BOM in little-endian orientation
198
    Utf16LeBom,
199
    /// Matches UTF-16-BE or some other UTF-16 compatible encoding (e.g. ISO-10646-UCS-2)
200
    Utf16BeLike,
201
    /// We saw a UTF-16 BOM in big-endian orientation
202
    Utf16BeBom,
203
}
204
205
impl DetectedEncoding {
206
    /// Return an Encoding object appropriate for the detected encoding
207
    #[cfg(feature = "encoding")]
208
    pub const fn encoding(&self) -> &'static encoding_rs::Encoding {
209
        match self {
210
            DetectedEncoding::AsciiCompatible | DetectedEncoding::Utf8Bom => encoding_rs::UTF_8,
211
            DetectedEncoding::Utf16LeLike | DetectedEncoding::Utf16LeBom => encoding_rs::UTF_16LE,
212
            DetectedEncoding::Utf16BeLike | DetectedEncoding::Utf16BeBom => encoding_rs::UTF_16BE,
213
        }
214
    }
215
216
    /// Length of the BOM, which may need to be stripped from the input
217
0
    pub const fn bom_len(&self) -> usize {
218
0
        match self {
219
0
            DetectedEncoding::Utf8Bom => 3,
220
0
            DetectedEncoding::Utf16LeBom | DetectedEncoding::Utf16BeBom => 2,
221
            DetectedEncoding::AsciiCompatible
222
            | DetectedEncoding::Utf16LeLike
223
0
            | DetectedEncoding::Utf16BeLike => 0,
224
        }
225
0
    }
226
}
227
228
// Size of the buffer that holds the start of the input undecoded. The
229
// encoding is detected from its first bytes, and it is then decoded only up
230
// to the end of the XML declaration, so that `set_encoding()` can be called
231
// before anything after the declaration is decoded. This is not a limit on
232
// the declaration: a longer one is read in several chunks of this size.
233
#[cfg(feature = "encoding")]
234
const PREFIX_CAP: usize = 128;
235
236
#[cfg(feature = "encoding")]
237
struct Prefix {
238
    buf: [u8; PREFIX_CAP],
239
    len: usize,
240
    detected: bool,
241
    /// Whether the XML declaration may continue past the bytes read so far,
242
    /// that is, the UTF-8 decoder has not decoded a `>` yet
243
    decl_open: bool,
244
}
245
246
/// A reader wrapper that decodes a byte stream from any encoding into UTF-8.
247
///
248
/// This reader wraps a [`BufRead`] source and uses [`encoding_rs::Decoder`] to
249
/// transcode the input into valid UTF-8. On first access, it detects the encoding
250
/// from BOM or XML declaration byte patterns and configures the appropriate decoder.
251
///
252
/// For UTF-8 input, this acts as a validating passthrough. For UTF-16 or other
253
/// encodings, the bytes are transcoded into UTF-8 in an internal buffer.
254
///
255
/// # Encoding detection
256
///
257
/// UTF-16 is recognized by a BOM or by the bytes of `<?` at the very start of
258
/// the input. Any other input is assumed to be in an ASCII-compatible encoding
259
/// and is decoded as UTF-8 up to the first `>`, which ends the XML declaration
260
/// if there is one. At that point [`set_encoding()`] can switch to the declared
261
/// encoding. This relies on the declaration being pure ASCII, as the XML
262
/// grammar requires: bytes before the first `>` that are not valid UTF-8 are
263
/// an error.
264
///
265
/// [`set_encoding()`]: Self::set_encoding
266
///
267
/// # Examples
268
///
269
/// ```
270
/// use std::io::Read;
271
/// use quick_xml::encoding::DecodingReader;
272
///
273
/// // UTF-8 input passes through:
274
/// let data = b"Hello, World!";
275
/// let mut reader = DecodingReader::new(&data[..]);
276
/// let mut buf = Vec::new();
277
/// reader.read_to_end(&mut buf).unwrap();
278
/// assert_eq!(buf, data);
279
/// ```
280
///
281
/// The example below shows how you can read documents using `DecodingReader`:
282
/// ```
283
/// use quick_xml::encoding::DecodingReader;
284
/// use quick_xml::events::Event;
285
/// use quick_xml::reader::Reader;
286
///
287
/// # fn to_utf16le_with_bom(string: &str) -> Vec<u8> {
288
/// #     let mut bytes = Vec::new();
289
/// #     bytes.extend_from_slice(&[0xFF, 0xFE]); // UTF-16 LE BOM
290
/// #     for ch in string.encode_utf16() {
291
/// #         bytes.extend_from_slice(&ch.to_le_bytes());
292
/// #     }
293
/// #     bytes
294
/// # }
295
/// let xml = to_utf16le_with_bom("<?xml encoding='UTF-16'?><element/>");
296
/// let mut decoder = DecodingReader::new(xml.as_ref());
297
/// let mut reader = Reader::from_reader(decoder);
298
///
299
/// let mut buf = Vec::new();
300
/// loop {
301
///     buf.clear();
302
///     match reader.read_event_into(&mut buf).unwrap() {
303
///         Event::Decl(e) => {
304
///             // If XML declaration contains unknown encoding name, None is returned
305
///             match e.encoder() {
306
///                 Some(encoding) => reader.get_mut().set_encoding(encoding),
307
///                 None => panic!("Unsupported encoding {:?}", e.encoding()),
308
///             }
309
///         }
310
///         Event::Eof => break,
311
///         _ => {}
312
///     }
313
/// }
314
/// ```
315
#[cfg(feature = "encoding")]
316
pub struct DecodingReader<R> {
317
    inner: R,
318
    decoder: encoding_rs::Decoder,
319
    /// `encoding_rs::Decoder` panics if called after finalization (`last=true`).
320
    /// This flag prevents that by short-circuiting `fill_buf` after completion.
321
    decoder_finished: bool,
322
    /// Decoded UTF-8 output buffer
323
    out_buf: Box<[u8]>,
324
    /// Start of unconsumed data in out_buf
325
    out_pos: usize,
326
    /// End of valid data in out_buf
327
    out_len: usize,
328
    /// Bytes read upfront for encoding detection and XML declaration buffering.
329
    /// `Some` until the prefix is fully drained; `None` afterward (main decode
330
    /// path takes over and the allocation is freed).
331
    prefix: Option<Box<Prefix>>,
332
    /// Whether the inner reader has reached EOF
333
    inner_eof: bool,
334
}
335
336
#[cfg(feature = "encoding")]
337
impl<R: std::fmt::Debug> std::fmt::Debug for DecodingReader<R> {
338
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
339
        f.debug_struct("DecodingReader")
340
            .field("inner", &self.inner)
341
            .field("encoding", &self.decoder.encoding())
342
            .field("out_pos", &self.out_pos)
343
            .field("out_len", &self.out_len)
344
            .field("inner_eof", &self.inner_eof)
345
            .field("prefix_active", &self.prefix.is_some())
346
            .finish()
347
    }
348
}
349
350
#[cfg(feature = "encoding")]
351
impl<R> DecodingReader<R> {
352
    /// Creates a new decoding reader.
353
    ///
354
    /// The encoding is auto-detected from BOM or XML declaration patterns on
355
    /// first access. Defaults to UTF-8 if no pattern is recognized.
356
    pub fn new(inner: R) -> Self {
357
        Self {
358
            inner,
359
            decoder: encoding_rs::UTF_8.new_decoder_without_bom_handling(),
360
            decoder_finished: false,
361
            out_buf: vec![0u8; 8192].into_boxed_slice(),
362
            out_pos: 0,
363
            out_len: 0,
364
            prefix: Some(Box::new(Prefix {
365
                buf: [0; PREFIX_CAP],
366
                len: 0,
367
                detected: false,
368
                decl_open: true,
369
            })),
370
            inner_eof: false,
371
        }
372
    }
373
374
    /// Returns a reference to the underlying reader
375
    pub const fn get_ref(&self) -> &R {
376
        &self.inner
377
    }
378
379
    /// Returns a mutable reference to the underlying reader
380
    pub const fn get_mut(&mut self) -> &mut R {
381
        &mut self.inner
382
    }
383
384
    /// Consumes this reader and returns the underlying reader
385
    pub fn into_inner(self) -> R {
386
        self.inner
387
    }
388
389
    /// Returns the encoding currently used by the decoder.
390
    ///
391
    /// Before the first read, this is always UTF-8. After encoding detection
392
    /// it reflects the detected (or overridden) encoding.
393
    pub fn encoding(&self) -> &'static encoding_rs::Encoding {
394
        self.decoder.encoding()
395
    }
396
397
    /// Replaces the decoder with one for the given encoding. The encoding
398
    /// must be ASCII-compatible (the parser cannot read the declaration otherwise).
399
    ///
400
    /// If UTF-16 was detected from the BOM or the first bytes, a request for an
401
    /// ASCII-compatible encoding is ignored: the declaration was read as UTF-16,
402
    /// so the document cannot be in the encoding it names.
403
    ///
404
    /// If the stream was detected as UTF-16, requesting UTF-16 of either byte
405
    /// order keeps the detected byte order, because the `UTF-16` encoding name
406
    /// does not specify it (the BOM or the first bytes of the document do).
407
    ///
408
    /// # Panics
409
    ///
410
    /// Panics if the encoding changes after the reader has started decoding
411
    /// the input that follows the XML declaration. Call this right after the
412
    /// declaration is parsed, before reading the next event. The declaration
413
    /// itself may be of any length.
414
    pub fn set_encoding(&mut self, encoding: &'static encoding_rs::Encoding) {
415
        // No-op when the encoding matches - replacing the decoder would discard
416
        // its internal state (e.g. a partial multi-byte sequence), corrupting output.
417
        // Also a no-op when a UTF-16 stream names an ASCII-compatible encoding.
418
        // These checks are safe regardless of prefix state since nothing changes.
419
        //
420
        // The same applies when both encodings are UTF-16: the byte order was
421
        // detected from the BOM or from the first bytes of the document, and the
422
        // name in the XML declaration (`UTF-16`, which resolves to UTF-16LE)
423
        // cannot override it. Replacing the decoder would byte-swap the rest of
424
        // a big-endian document.
425
        let current = self.decoder.encoding();
426
        if current == encoding
427
            || (!current.is_ascii_compatible() && encoding.is_ascii_compatible())
428
            || (is_utf16(current) && is_utf16(encoding))
429
        {
430
            return;
431
        }
432
        assert!(
433
            self.prefix.is_some(),
434
            "set_encoding() called after prefix buffer was drained; \
435
             encoding can only be changed while the prefix is still active"
436
        );
437
        self.decoder = encoding.new_decoder_without_bom_handling();
438
        self.decoder_finished = false;
439
    }
440
}
441
442
#[cfg(feature = "encoding")]
443
impl<R: BufRead> BufRead for DecodingReader<R> {
444
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
445
        // Fast path: serve already-decoded data
446
        if self.out_pos < self.out_len {
447
            return Ok(&self.out_buf[self.out_pos..self.out_len]);
448
        }
449
450
        // Reset output buffer
451
        self.out_pos = 0;
452
        self.out_len = 0;
453
454
        if let Some(prefix) = &mut self.prefix {
455
            // Fill the prefix buffer on first access, and again while the XML
456
            // declaration is longer than what was read so far, ensuring
457
            // set_encoding() can be called before the greedy main decode path
458
            // consumes from inner.
459
            while prefix.decl_open && !self.inner_eof && prefix.len < PREFIX_CAP {
460
                match self.inner.read(&mut prefix.buf[prefix.len..]) {
461
                    Ok(0) => self.inner_eof = true,
462
                    Ok(n) => prefix.len += n,
463
                    Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
464
                    Err(e) => return Err(e),
465
                }
466
            }
467
468
            // On first access, detect encoding.
469
            if !prefix.detected {
470
                prefix.detected = true;
471
472
                let detection_bytes = &prefix.buf[..prefix.len];
473
                if let Some(detected) = detect_encoding(detection_bytes) {
474
                    let bom_len = detected.bom_len();
475
                    if bom_len > 0 {
476
                        prefix.buf.copy_within(bom_len..prefix.len, 0);
477
                        prefix.len -= bom_len;
478
                    }
479
                    let encoding = detected.encoding();
480
                    if encoding != encoding_rs::UTF_8 {
481
                        self.decoder = encoding.new_decoder_without_bom_handling();
482
                    }
483
                }
484
            }
485
486
            if self.decoder_finished {
487
                return Ok(&[]);
488
            }
489
490
            // Prefix fully decoded on a previous call - drop it and fall
491
            // through to the main decode path.
492
            if prefix.len == 0 {
493
                self.prefix = None;
494
            } else {
495
                // Decode from prefix buffer.
496
                //
497
                // While the decoder is still the default UTF-8 one, the encoding
498
                // named in the XML declaration has not been applied yet:
499
                // set_encoding() runs only after the reader has parsed the `Decl`
500
                // event. Decoding the whole prefix now would consume the bytes
501
                // that follow the declaration using UTF-8 instead of the declared
502
                // encoding, which silently mis-decodes (multi-byte encodings) or
503
                // rejects as malformed (single-byte encodings) any non-ASCII
504
                // content that happens to land within the prefix. Markup
505
                // delimiters are ASCII in every ASCII-compatible encoding, so stop
506
                // at the first `>`: that yields the complete `<?xml ... ?>`
507
                // declaration and nothing past it, letting set_encoding() take
508
                // effect before the remainder of the prefix is decoded.
509
                //
510
                // If there is no `>` yet, the declaration continues past the
511
                // prefix. Everything read so far is assumed to be part of it and
512
                // therefore ASCII, which UTF-8 decodes exactly as the declared
513
                // encoding would. Those bytes are emitted now and never decoded
514
                // again; the next call refills the prefix.
515
                let end = if self.decoder.encoding() == encoding_rs::UTF_8 {
516
                    match memchr::memchr(b'>', &prefix.buf[..prefix.len]) {
517
                        Some(i) => {
518
                            prefix.decl_open = false;
519
                            i + 1
520
                        }
521
                        None => prefix.len,
522
                    }
523
                } else {
524
                    prefix.decl_open = false;
525
                    prefix.len
526
                };
527
                let src = &prefix.buf[..end];
528
                let (result, read, written) = self.decoder.decode_to_utf8_without_replacement(
529
                    src,
530
                    &mut self.out_buf[..],
531
                    false,
532
                );
533
                prefix.buf.copy_within(read..prefix.len, 0);
534
                prefix.len -= read;
535
                self.out_len = written;
536
537
                match result {
538
                    encoding_rs::DecoderResult::InputEmpty if written > 0 => {
539
                        return Ok(&self.out_buf[..self.out_len]);
540
                    }
541
                    encoding_rs::DecoderResult::InputEmpty => {
542
                        // prefix.len is now 0; keep prefix alive for
543
                        // set_encoding() - it will be dropped on the next call.
544
                    }
545
                    encoding_rs::DecoderResult::OutputFull => {
546
                        return Ok(&self.out_buf[..self.out_len]);
547
                    }
548
                    encoding_rs::DecoderResult::Malformed(_, _) => {
549
                        return Err(io::Error::new(
550
                            io::ErrorKind::InvalidData,
551
                            EncodingError::Other(self.decoder.encoding()),
552
                        ));
553
                    }
554
                }
555
                // InputEmpty with written == 0: prefix drained, decoder may
556
                // hold partial internal state (e.g. a lone byte of UTF-16).
557
                // Drop prefix and fall through to the main decode path.
558
                if prefix.len == 0 {
559
                    self.prefix = None;
560
                }
561
            }
562
        }
563
564
        if self.decoder_finished {
565
            return Ok(&[]);
566
        }
567
568
        // Loop until we produce output, hit EOF, or get an error.
569
        // The decoder may consume input into internal state (e.g., partial
570
        // UTF-16 code unit) without producing output - we must keep feeding
571
        // it more input rather than returning an empty slice (which signals EOF).
572
        loop {
573
            // EOF flush path: tell decoder this is the last chunk
574
            if self.inner_eof {
575
                let (result, _, written) = self.decoder.decode_to_utf8_without_replacement(
576
                    b"",
577
                    &mut self.out_buf[..],
578
                    true,
579
                );
580
                self.out_len = written;
581
                match result {
582
                    encoding_rs::DecoderResult::InputEmpty => {
583
                        self.decoder_finished = true;
584
                        return Ok(&self.out_buf[..self.out_len]);
585
                    }
586
                    encoding_rs::DecoderResult::OutputFull => {
587
                        return Ok(&self.out_buf[..self.out_len]);
588
                    }
589
                    encoding_rs::DecoderResult::Malformed(_, _) => {
590
                        return Err(io::Error::new(
591
                            io::ErrorKind::InvalidData,
592
                            EncodingError::Other(self.decoder.encoding()),
593
                        ));
594
                    }
595
                }
596
            }
597
598
            // Main decode path: read from inner, decode into out_buf
599
            let (result, read, written) = {
600
                let src = self.inner.fill_buf()?;
601
                if src.is_empty() {
602
                    self.inner_eof = true;
603
                    continue; // will hit EOF flush path on next iteration
604
                }
605
                self.decoder
606
                    .decode_to_utf8_without_replacement(src, &mut self.out_buf[..], false)
607
            };
608
            self.inner.consume(read);
609
            self.out_len = written;
610
611
            match result {
612
                encoding_rs::DecoderResult::InputEmpty if written > 0 => {
613
                    return Ok(&self.out_buf[..self.out_len]);
614
                }
615
                encoding_rs::DecoderResult::InputEmpty => {
616
                    // Decoder consumed all input but produced no output
617
                    // (e.g., 1 byte of a 2-byte UTF-16 code unit stored
618
                    // in decoder internal state). Loop to get more input.
619
                }
620
                encoding_rs::DecoderResult::OutputFull => {
621
                    // Output buffer full; return what we have. Remaining
622
                    // input will be decoded on the next fill_buf call.
623
                    return Ok(&self.out_buf[..self.out_len]);
624
                }
625
                encoding_rs::DecoderResult::Malformed(_, _) => {
626
                    return Err(io::Error::new(
627
                        io::ErrorKind::InvalidData,
628
                        EncodingError::Other(self.decoder.encoding()),
629
                    ));
630
                }
631
            }
632
        }
633
    }
634
635
    fn consume(&mut self, amt: usize) {
636
        debug_assert!(
637
            self.out_pos + amt <= self.out_len,
638
            "consume({amt}) out of range: out_pos={}, out_len={}",
639
            self.out_pos,
640
            self.out_len,
641
        );
642
        self.out_pos += amt;
643
    }
644
}
645
646
#[cfg(feature = "encoding")]
647
impl<R: BufRead> Read for DecodingReader<R> {
648
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
649
        if buf.is_empty() {
650
            return Ok(0);
651
        }
652
        let available = self.fill_buf()?;
653
        if available.is_empty() {
654
            return Ok(0);
655
        }
656
        let len = available.len().min(buf.len());
657
        buf[..len].copy_from_slice(&available[..len]);
658
        self.consume(len);
659
        Ok(len)
660
    }
661
}
662
663
#[cfg(all(test, feature = "encoding"))]
664
mod decoding_reader {
665
    use super::*;
666
    use std::io::{BufReader, Read};
667
668
    /// Helper reader that returns data in fixed-size chunks
669
    struct ChunkedReader<'a> {
670
        data: &'a [u8],
671
        pos: usize,
672
        chunk_size: usize,
673
    }
674
675
    impl<'a> ChunkedReader<'a> {
676
        fn new(data: &'a [u8], chunk_size: usize) -> Self {
677
            Self {
678
                data,
679
                pos: 0,
680
                chunk_size,
681
            }
682
        }
683
    }
684
685
    impl<'a> Read for ChunkedReader<'a> {
686
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
687
            if self.pos >= self.data.len() {
688
                return Ok(0);
689
            }
690
            let len = self
691
                .chunk_size
692
                .min(buf.len())
693
                .min(self.data.len() - self.pos);
694
            buf[..len].copy_from_slice(&self.data[self.pos..self.pos + len]);
695
            self.pos += len;
696
            Ok(len)
697
        }
698
    }
699
700
    /// Helper reader that fails with the given error kinds, one per `read`
701
    /// call, before delegating to the wrapped data
702
    struct FailingReader<'a> {
703
        failures: Vec<io::ErrorKind>,
704
        data: &'a [u8],
705
    }
706
707
    impl<'a> Read for FailingReader<'a> {
708
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
709
            if let Some(kind) = self.failures.pop() {
710
                return Err(kind.into());
711
            }
712
            self.data.read(buf)
713
        }
714
    }
715
716
    /// Encode a string as UTF-16 LE bytes with BOM
717
    fn utf16le_with_bom(s: &str) -> Vec<u8> {
718
        let mut out = vec![0xFF, 0xFE]; // UTF-16 LE BOM
719
        for code_unit in s.encode_utf16() {
720
            out.extend_from_slice(&code_unit.to_le_bytes());
721
        }
722
        out
723
    }
724
725
    /// Encode a string as UTF-16 BE bytes with BOM
726
    fn utf16be_with_bom(s: &str) -> Vec<u8> {
727
        let mut out = vec![0xFE, 0xFF]; // UTF-16 BE BOM
728
        for code_unit in s.encode_utf16() {
729
            out.extend_from_slice(&code_unit.to_be_bytes());
730
        }
731
        out
732
    }
733
734
    /// Encode a string as UTF-16 LE bytes without BOM
735
    fn utf16le_no_bom(s: &str) -> Vec<u8> {
736
        let mut out = Vec::new();
737
        for code_unit in s.encode_utf16() {
738
            out.extend_from_slice(&code_unit.to_le_bytes());
739
        }
740
        out
741
    }
742
743
    /// Encode a string as UTF-16 BE bytes without BOM
744
    fn utf16be_no_bom(s: &str) -> Vec<u8> {
745
        let mut out = Vec::new();
746
        for code_unit in s.encode_utf16() {
747
            out.extend_from_slice(&code_unit.to_be_bytes());
748
        }
749
        out
750
    }
751
752
    /// Read all bytes from a reader into a String
753
    fn read_all(reader: &mut DecodingReader<impl BufRead>) -> io::Result<String> {
754
        let mut result = Vec::new();
755
        reader.read_to_end(&mut result)?;
756
        Ok(String::from_utf8(result).expect("DecodingReader should produce valid UTF-8"))
757
    }
758
759
    /// Simple edge cases and degenerate inputs
760
    mod edge_cases {
761
        use super::*;
762
        use pretty_assertions::assert_eq;
763
764
        /// Zero-length input should immediately return EOF (n == 0).
765
        #[test]
766
        fn empty_input() {
767
            let data = b"";
768
            let mut reader = DecodingReader::new(&data[..]);
769
            let mut buf = [0u8; 10];
770
            let n = reader.read(&mut buf).unwrap();
771
            assert_eq!(n, 0);
772
        }
773
774
        /// A UTF-8 BOM with no payload should decode to an empty string.
775
        #[test]
776
        fn utf8_bom_only() {
777
            let data = b"\xEF\xBB\xBF";
778
            let mut reader = DecodingReader::new(&data[..]);
779
            assert_eq!(read_all(&mut reader).unwrap(), "");
780
        }
781
782
        /// A UTF-16 LE BOM with no payload should decode to an empty string.
783
        #[test]
784
        fn utf16le_bom_only() {
785
            let data = &[0xFF, 0xFE];
786
            let mut reader = DecodingReader::new(&data[..]);
787
            assert_eq!(read_all(&mut reader).unwrap(), "");
788
        }
789
790
        /// A UTF-16 BE BOM with no payload should decode to an empty string.
791
        #[test]
792
        fn utf16be_bom_only() {
793
            let data = &[0xFE, 0xFF];
794
            let mut reader = DecodingReader::new(&data[..]);
795
            assert_eq!(read_all(&mut reader).unwrap(), "");
796
        }
797
798
        /// Invalid UTF-8 (no BOM, so treated as UTF-8) must produce an error.
799
        #[test]
800
        fn invalid_utf8_is_rejected() {
801
            let data: &[u8] = &[0x48, 0x65, 0x6C, 0xFF, 0xFE];
802
            let mut reader = DecodingReader::new(&data[..]);
803
            let err = read_all(&mut reader).unwrap_err();
804
            assert_eq!(err.kind(), io::ErrorKind::InvalidData);
805
        }
806
807
        /// An odd trailing byte in UTF-16 is malformed and must produce an error.
808
        #[test]
809
        fn truncated_utf16_at_eof() {
810
            // UTF-16 LE BOM + one valid code unit + one incomplete byte
811
            let data: &[u8] = &[0xFF, 0xFE, 0x48, 0x00, 0x65];
812
            let mut reader = DecodingReader::new(&data[..]);
813
            let err = read_all(&mut reader).unwrap_err();
814
            assert_eq!(err.kind(), io::ErrorKind::InvalidData);
815
        }
816
817
        /// A 1-byte output buffer forces one byte per read() call; verifies
818
        /// multi-byte UTF-8 sequences are still assembled correctly.
819
        #[test]
820
        fn read_with_one_byte_buffer() {
821
            let data = "Hello, δΈ–η•Œ!".as_bytes();
822
            let mut reader = DecodingReader::new(&data[..]);
823
            let mut result = Vec::new();
824
            let mut buf = [0u8; 1];
825
            loop {
826
                let n = reader.read(&mut buf).unwrap();
827
                if n == 0 {
828
                    break;
829
                }
830
                result.extend_from_slice(&buf[..n]);
831
            }
832
            assert_eq!(String::from_utf8(result).unwrap(), "Hello, δΈ–η•Œ!");
833
        }
834
    }
835
836
    /// Tests that exercise the BufRead contract (fill_buf + consume) directly,
837
    /// as opposed to the Read-based helpers used elsewhere.
838
    mod bufread_interface {
839
        use super::*;
840
        use pretty_assertions::assert_eq;
841
        use std::io::BufRead;
842
843
        /// Basic fill_buf/consume cycle: partial consume leaves remaining
844
        /// data available on the next fill_buf call.
845
        #[test]
846
        fn fill_buf_and_consume() {
847
            let data = b"Hello, World!";
848
            let mut reader = DecodingReader::new(&data[..]);
849
850
            let buf = reader.fill_buf().unwrap();
851
            assert!(!buf.is_empty());
852
            assert_eq!(buf[0], b'H');
853
854
            // Consume only part of the buffer
855
            reader.consume(5);
856
857
            let buf = reader.fill_buf().unwrap();
858
            assert!(!buf.is_empty());
859
            assert_eq!(buf[0], b',');
860
        }
861
862
        /// The prefix is not refilled after the XML declaration: everything past
863
        /// the first `PREFIX_CAP` bytes is decoded by the main path in one chunk.
864
        #[test]
865
        fn prefix_ends_after_declaration() {
866
            let mut data = b"<?xml version='1.0'?>".to_vec();
867
            data.extend_from_slice(&[b'a'; 1000]);
868
            let mut reader = DecodingReader::new(&data[..]);
869
870
            let mut chunks = Vec::new();
871
            loop {
872
                let len = reader.fill_buf().unwrap().len();
873
                if len == 0 {
874
                    break;
875
                }
876
                chunks.push(len);
877
                reader.consume(len);
878
            }
879
            assert_eq!(chunks, [21, PREFIX_CAP - 21, data.len() - PREFIX_CAP]);
880
        }
881
882
        /// An interrupted read of the prefix is retried
883
        #[test]
884
        fn prefix_read_retries_interrupted() {
885
            let inner = FailingReader {
886
                failures: vec![io::ErrorKind::Interrupted; 2],
887
                data: b"<?xml version='1.0'?><a/>",
888
            };
889
            let mut reader = DecodingReader::new(BufReader::with_capacity(1, inner));
890
            assert_eq!(read_all(&mut reader).unwrap(), "<?xml version='1.0'?><a/>");
891
        }
892
893
        /// An I/O error while reading the prefix is returned to the caller
894
        #[test]
895
        fn prefix_read_propagates_error() {
896
            let inner = FailingReader {
897
                failures: vec![io::ErrorKind::BrokenPipe],
898
                data: b"<?xml version='1.0'?><a/>",
899
            };
900
            let mut reader = DecodingReader::new(BufReader::new(inner));
901
            let err = reader.fill_buf().unwrap_err();
902
            assert_eq!(err.kind(), io::ErrorKind::BrokenPipe);
903
        }
904
905
        /// Drain the reader via fill_buf/consume, then confirm it stays at EOF.
906
        #[test]
907
        fn partial_consume_then_read_more() {
908
            let data = b"Hello, World!";
909
            let mut reader = DecodingReader::new(&data[..]);
910
911
            // Collect all output via fill_buf/consume
912
            let mut result = Vec::new();
913
            loop {
914
                let buf = reader.fill_buf().unwrap();
915
                if buf.is_empty() {
916
                    break;
917
                }
918
                result.extend_from_slice(buf);
919
                let len = buf.len();
920
                reader.consume(len);
921
            }
922
            assert_eq!(std::str::from_utf8(&result).unwrap(), "Hello, World!");
923
924
            // Should remain at EOF
925
            let buf = reader.fill_buf().unwrap();
926
            assert!(buf.is_empty());
927
        }
928
929
        /// Calling fill_buf() repeatedly after EOF must keep returning empty
930
        /// (and not panic - encoding_rs::Decoder panics if called after finalization).
931
        #[test]
932
        fn fill_buf_after_eof_is_idempotent() {
933
            let data = b"Hello";
934
            let mut reader = DecodingReader::new(&data[..]);
935
936
            loop {
937
                let buf = reader.fill_buf().unwrap();
938
                if buf.is_empty() {
939
                    break;
940
                }
941
                let len = buf.len();
942
                reader.consume(len);
943
            }
944
945
            for _ in 0..3 {
946
                let buf = reader.fill_buf().unwrap();
947
                assert!(buf.is_empty());
948
            }
949
        }
950
951
        /// consume() past the buffered length must trigger a debug_assert panic.
952
        #[test]
953
        #[should_panic(expected = "consume")]
954
        fn consume_overflow_panics_in_debug() {
955
            let data = b"Hi";
956
            let mut reader = DecodingReader::new(&data[..]);
957
            let _ = reader.fill_buf().unwrap();
958
            reader.consume(100);
959
        }
960
    }
961
962
    mod accessors {
963
        use super::*;
964
        use pretty_assertions::assert_eq;
965
        use std::io::Cursor;
966
967
        #[test]
968
        fn get_ref() {
969
            let data = b"Hello";
970
            let cursor = Cursor::new(data.to_vec());
971
            let reader = DecodingReader::new(cursor);
972
            assert_eq!(reader.get_ref().get_ref(), data);
973
        }
974
975
        #[test]
976
        fn get_mut() {
977
            let data = b"Hello";
978
            let cursor = Cursor::new(data.to_vec());
979
            let mut reader = DecodingReader::new(cursor);
980
            reader.get_mut().set_position(2);
981
            assert_eq!(reader.get_ref().position(), 2);
982
        }
983
984
        #[test]
985
        fn into_inner() {
986
            let data = b"Hello";
987
            let cursor = Cursor::new(data.to_vec());
988
            let reader = DecodingReader::new(cursor);
989
            let inner = reader.into_inner();
990
            assert_eq!(inner.get_ref(), data);
991
        }
992
993
        /// Default encoding before any reads is UTF-8.
994
        #[test]
995
        fn encoding_default_is_utf8() {
996
            let reader = DecodingReader::new(&b"Hello"[..]);
997
            assert_eq!(reader.encoding(), encoding_rs::UTF_8);
998
        }
999
    }
1000
1001
    // TODO: These tests emulate the updating of the internal decoder after reading the XML decl.
1002
    // Since `Reader` currently only speaks the `BufRead` trait, we can't test that directly.
1003
    // Eventually once `Reader` knows about the underlying `DecodingReader` we should test
1004
    // that directly.
1005
1006
    /// Tests for encoding() and set_encoding(): detection, switching,
1007
    /// same-encoding no-op safety, and mid-stream override behavior.
1008
    mod encoding_switching {
1009
        use super::*;
1010
        use pretty_assertions::assert_eq;
1011
        use std::io::BufRead;
1012
1013
        /// Encoding reflects BOM detection after first read.
1014
        #[test]
1015
        fn encoding_reflects_detection() {
1016
            let data = utf16le_with_bom("Hello");
1017
            let mut reader = DecodingReader::new(&data[..]);
1018
            let _ = read_all(&mut reader).unwrap();
1019
            assert_eq!(reader.encoding(), encoding_rs::UTF_16LE);
1020
        }
1021
1022
        /// set_encoding switches the active decoder.
1023
        #[test]
1024
        fn set_encoding_changes_encoding() {
1025
            let mut reader = DecodingReader::new(&b"Hello"[..]);
1026
            assert_eq!(reader.encoding(), encoding_rs::UTF_8);
1027
            reader.set_encoding(encoding_rs::UTF_16LE);
1028
            assert_eq!(reader.encoding(), encoding_rs::UTF_16LE);
1029
        }
1030
1031
        /// set_encoding after reading preserves already-buffered output.
1032
        #[test]
1033
        fn set_encoding_preserves_buffered_output() {
1034
            let data = b"Hello";
1035
            let mut reader = DecodingReader::new(&data[..]);
1036
1037
            let buf = reader.fill_buf().unwrap();
1038
            assert_eq!(buf, b"Hello");
1039
1040
            reader.set_encoding(encoding_rs::WINDOWS_1252);
1041
            assert_eq!(reader.encoding(), encoding_rs::WINDOWS_1252);
1042
1043
            // Buffered data is unchanged
1044
            let buf = reader.fill_buf().unwrap();
1045
            assert_eq!(buf, b"Hello");
1046
        }
1047
1048
        /// Calling set_encoding with the already-active encoding is a no-op:
1049
        /// the decoder's internal state is preserved and decoding continues
1050
        /// without corruption.
1051
        #[test]
1052
        fn set_encoding_same_as_detected_is_noop() {
1053
            let data = b"Hello, World!";
1054
            let mut reader = DecodingReader::new(&data[..]);
1055
1056
            // Trigger detection and consume the first chunk
1057
            let first_chunk;
1058
            {
1059
                let buf = reader.fill_buf().unwrap();
1060
                assert!(buf.len() > 0);
1061
                first_chunk = std::str::from_utf8(buf).unwrap().to_string();
1062
                let n = buf.len();
1063
                reader.consume(n);
1064
            }
1065
            assert_eq!(reader.encoding(), encoding_rs::UTF_8);
1066
1067
            // "Re-set" to the same encoding - must not reset decoder state
1068
            reader.set_encoding(encoding_rs::UTF_8);
1069
            assert_eq!(reader.encoding(), encoding_rs::UTF_8);
1070
1071
            // Read the rest - combined output must equal the original string
1072
            let rest = read_all(&mut reader).unwrap();
1073
            assert_eq!(format!("{first_chunk}{rest}"), "Hello, World!");
1074
        }
1075
1076
        /// The `UTF-16` label resolves to UTF-16LE, but the byte order of the
1077
        /// stream is given by its BOM: requesting UTF-16 of the other byte order
1078
        /// must keep the detected one instead of byte-swapping the remaining data.
1079
        mod set_encoding_utf16_keeps_detected_byte_order {
1080
            use super::*;
1081
            use pretty_assertions::assert_eq;
1082
1083
            #[test]
1084
            fn detected_be_then_set_le() {
1085
                let data = utf16be_with_bom("Hello, World!");
1086
                let mut reader = DecodingReader::new(&data[..]);
1087
1088
                // Trigger detection and consume the first chunk
1089
                let first_chunk;
1090
                {
1091
                    let buf = reader.fill_buf().unwrap();
1092
                    assert!(buf.len() > 0);
1093
                    first_chunk = std::str::from_utf8(buf).unwrap().to_string();
1094
                    let n = buf.len();
1095
                    reader.consume(n);
1096
                }
1097
                assert_eq!(reader.encoding(), encoding_rs::UTF_16BE);
1098
1099
                reader.set_encoding(encoding_rs::UTF_16LE);
1100
                assert_eq!(reader.encoding(), encoding_rs::UTF_16BE);
1101
1102
                let rest = read_all(&mut reader).unwrap();
1103
                assert_eq!(format!("{first_chunk}{rest}"), "Hello, World!");
1104
            }
1105
1106
            #[test]
1107
            fn detected_le_then_set_be() {
1108
                let data = utf16le_with_bom("Hello, World!");
1109
                let mut reader = DecodingReader::new(&data[..]);
1110
1111
                // Trigger detection and consume the first chunk
1112
                let first_chunk;
1113
                {
1114
                    let buf = reader.fill_buf().unwrap();
1115
                    assert!(buf.len() > 0);
1116
                    first_chunk = std::str::from_utf8(buf).unwrap().to_string();
1117
                    let n = buf.len();
1118
                    reader.consume(n);
1119
                }
1120
                assert_eq!(reader.encoding(), encoding_rs::UTF_16LE);
1121
1122
                reader.set_encoding(encoding_rs::UTF_16BE);
1123
                assert_eq!(reader.encoding(), encoding_rs::UTF_16LE);
1124
1125
                let rest = read_all(&mut reader).unwrap();
1126
                assert_eq!(format!("{first_chunk}{rest}"), "Hello, World!");
1127
            }
1128
        }
1129
1130
        /// set_encoding mid-stream: read some UTF-8 data, switch encoding,
1131
        /// then verify the encoding accessor reflects the change.
1132
        #[test]
1133
        fn set_encoding_mid_stream() {
1134
            let data = b"Hello, World!";
1135
            let mut reader = DecodingReader::new(&data[..]);
1136
1137
            // Read a few bytes under UTF-8
1138
            let buf = reader.fill_buf().unwrap();
1139
            let n = std::cmp::min(buf.len(), 5);
1140
            reader.consume(n);
1141
1142
            assert_eq!(reader.encoding(), encoding_rs::UTF_8);
1143
            reader.set_encoding(encoding_rs::WINDOWS_1252);
1144
            assert_eq!(reader.encoding(), encoding_rs::WINDOWS_1252);
1145
1146
            // Remaining data still readable (ASCII is identical in both encodings)
1147
            let rest = read_all(&mut reader).unwrap();
1148
            assert_eq!(rest, ", World!");
1149
        }
1150
    }
1151
1152
    /// Tests exercised across a matrix of (input text x encoding x read strategy).
1153
    /// Each test encodes a string, feeds it through DecodingReader, and asserts the
1154
    /// decoded output matches the original. This covers BOM detection, UTF-16
1155
    /// transcoding, surrogate pairs, and multi-byte UTF-8 characters in one sweep.
1156
    ///
1157
    /// Examples:
1158
    ///
1159
    /// - UTF-8 passthrough (ASCII and multibyte) with and without BOM
1160
    /// - UTF-16 LE/BE decoding with and without BOM
1161
    /// - BOM-less UTF-16 detection via `<?xml` byte pattern
1162
    /// - UTF-16 surrogate pairs (astral plane characters)
1163
    /// - Chunked input at misaligned boundaries (odd chunk sizes vs 2-byte code units)
1164
    /// - One-byte-at-a-time delivery for all encodings
1165
    /// - Inputs larger than the 8192-byte internal output buffer
1166
    /// - Empty and single-character inputs (prefix-only decode path)
1167
    mod matrix_decoding_tests {
1168
        use super::*;
1169
        use pretty_assertions::assert_eq;
1170
1171
        struct TestCase {
1172
            label: &'static str,
1173
            text: &'static str,
1174
        }
1175
1176
        /// Short inputs that exercise different Unicode categories.
1177
        const CASES: &[TestCase] = &[
1178
            TestCase {
1179
                label: "empty",
1180
                text: "",
1181
            },
1182
            TestCase {
1183
                label: "single_multibyte",
1184
                // Single 3-byte character - entire content fits in the prefix buffer
1185
                text: "€",
1186
            },
1187
            TestCase {
1188
                label: "ascii",
1189
                text: "Hello",
1190
            },
1191
            TestCase {
1192
                label: "multibyte",
1193
                // 3-byte CJK + 4-byte emoji
1194
                text: "Hello, δΈ–η•Œ! πŸ˜€",
1195
            },
1196
            TestCase {
1197
                label: "surrogate_pairs",
1198
                // U+1D11E and U+1F3B5 require surrogate pairs in UTF-16
1199
                text: "Music: π„žπŸŽ΅",
1200
            },
1201
            TestCase {
1202
                label: "xml_declaration",
1203
                // Enables BOM-less UTF-16 detection via the <?xml byte pattern
1204
                text: "<?xml version=\"1.0\"?><root/>",
1205
            },
1206
        ];
1207
1208
        /// Inputs larger than the 8192-byte internal output buffer.
1209
        fn large_cases() -> Vec<(&'static str, String)> {
1210
            vec![
1211
                ("large_ascii", "abcdefghij".repeat(1000)),
1212
                ("large_multibyte", "Hello, δΈ–η•Œ! πŸ˜€ ".repeat(500)),
1213
            ]
1214
        }
1215
1216
        enum Encoding {
1217
            Utf8,
1218
            Utf8Bom,
1219
            Utf16Le,
1220
            Utf16Be,
1221
            Utf16LeNoBom,
1222
            Utf16BeNoBom,
1223
        }
1224
1225
        impl Encoding {
1226
            fn encode(&self, text: &str) -> Vec<u8> {
1227
                match self {
1228
                    Encoding::Utf8 => text.as_bytes().to_vec(),
1229
                    Encoding::Utf8Bom => {
1230
                        let mut out = vec![0xEF, 0xBB, 0xBF];
1231
                        out.extend_from_slice(text.as_bytes());
1232
                        out
1233
                    }
1234
                    Encoding::Utf16Le => utf16le_with_bom(text),
1235
                    Encoding::Utf16Be => utf16be_with_bom(text),
1236
                    Encoding::Utf16LeNoBom => utf16le_no_bom(text),
1237
                    Encoding::Utf16BeNoBom => utf16be_no_bom(text),
1238
                }
1239
            }
1240
1241
            fn label(&self) -> &'static str {
1242
                match self {
1243
                    Encoding::Utf8 => "utf8",
1244
                    Encoding::Utf8Bom => "utf8_bom",
1245
                    Encoding::Utf16Le => "utf16le",
1246
                    Encoding::Utf16Be => "utf16be",
1247
                    Encoding::Utf16LeNoBom => "utf16le_no_bom",
1248
                    Encoding::Utf16BeNoBom => "utf16be_no_bom",
1249
                }
1250
            }
1251
1252
            /// BOM-less UTF-16 detection requires a `<?xml` prefix, so those
1253
            /// encodings are only included for inputs that start with one.
1254
            fn all_for(text: &str) -> Vec<Encoding> {
1255
                let mut encs = vec![
1256
                    Encoding::Utf8,
1257
                    Encoding::Utf8Bom,
1258
                    Encoding::Utf16Le,
1259
                    Encoding::Utf16Be,
1260
                ];
1261
                if text.starts_with("<?xml") {
1262
                    encs.push(Encoding::Utf16LeNoBom);
1263
                    encs.push(Encoding::Utf16BeNoBom);
1264
                }
1265
                encs
1266
            }
1267
        }
1268
1269
        /// Encode -> decode with the entire input available at once.
1270
        #[test]
1271
        fn bulk_read() {
1272
            for case in CASES {
1273
                for enc in Encoding::all_for(case.text) {
1274
                    let data = enc.encode(case.text);
1275
                    let mut reader = DecodingReader::new(&data[..]);
1276
                    assert_eq!(
1277
                        read_all(&mut reader).unwrap(),
1278
                        case.text,
1279
                        "bulk_read failed: case={}, encoding={}",
1280
                        case.label,
1281
                        enc.label(),
1282
                    );
1283
                }
1284
            }
1285
            for (label, text) in large_cases() {
1286
                for enc in Encoding::all_for(&text) {
1287
                    let data = enc.encode(&text);
1288
                    let mut reader = DecodingReader::new(&data[..]);
1289
                    assert_eq!(
1290
                        read_all(&mut reader).unwrap(),
1291
                        text,
1292
                        "bulk_read failed: case={}, encoding={}",
1293
                        label,
1294
                        enc.label(),
1295
                    );
1296
                }
1297
            }
1298
        }
1299
1300
        /// Encode -> decode with the input delivered in fixed-size chunks via
1301
        /// ChunkedReader, testing that the decoder handles arbitrary byte
1302
        /// boundaries (mid-BOM, mid-code-unit, mid-surrogate-pair).
1303
        #[test]
1304
        fn chunked_read() {
1305
            for case in CASES {
1306
                for enc in Encoding::all_for(case.text) {
1307
                    for chunk_size in [1, 2, 3, 4, 5] {
1308
                        let data = enc.encode(case.text);
1309
                        let mut reader = DecodingReader::new(BufReader::new(ChunkedReader::new(
1310
                            &data, chunk_size,
1311
                        )));
1312
                        assert_eq!(
1313
                            read_all(&mut reader).unwrap(),
1314
                            case.text,
1315
                            "chunked_read failed: case={}, encoding={}, chunk_size={}",
1316
                            case.label,
1317
                            enc.label(),
1318
                            chunk_size,
1319
                        );
1320
                    }
1321
                }
1322
            }
1323
        }
1324
1325
        /// Same as chunked_read but with inputs exceeding the 8192-byte
1326
        /// internal output buffer, exercising the multi-fill_buf decode loop.
1327
        #[test]
1328
        fn large_chunked_read() {
1329
            for (label, text) in large_cases() {
1330
                for enc in Encoding::all_for(&text) {
1331
                    for chunk_size in [1, 2, 3, 4, 5] {
1332
                        let data = enc.encode(&text);
1333
                        let mut reader = DecodingReader::new(BufReader::new(ChunkedReader::new(
1334
                            &data, chunk_size,
1335
                        )));
1336
                        assert_eq!(
1337
                            read_all(&mut reader).unwrap(),
1338
                            text,
1339
                            "large_chunked_read failed: case={}, encoding={}, chunk_size={}",
1340
                            label,
1341
                            enc.label(),
1342
                            chunk_size,
1343
                        );
1344
                    }
1345
                }
1346
            }
1347
        }
1348
    }
1349
}