qubit-io 0.17.0

Runtime-neutral synchronous and asynchronous item-stream I/O for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================

//! Extension operations for standard byte readers.

use std::io::ErrorKind;
use std::io::Read;
use std::io::Result;
use std::io::Write;
use std::io::copy as copy_all;

use crate::Streams;
use crate::std_io::ext::internal::read_ext_impl;
use crate::util::SliceRange;
use crate::util::UncheckedSlice;
use crate::util::allocation_error;
use crate::util::try_reserve_string;

/// Default stack buffer size used by discard operations.
const DISCARD_BUFFER_SIZE: usize = 8 * 1024;

/// Extension methods for [`Read`] values.
///
/// `ReadExt` fills small semantic gaps in the standard [`Read`] trait while
/// keeping the same blocking and error model. The methods are implemented for
/// every type that implements [`Read`], including `dyn Read` trait objects.
///
/// # Examples
/// ```
/// use qubit_io::std_io::ext::ReadExt;
/// use std::io::Cursor;
///
/// let mut input = Cursor::new(b"abcdef".to_vec());
/// let header = input.read_exact_array::<2>()?;
/// let payload = input.read_exact_vec_limited(4, 16)?;
///
/// assert_eq!(*b"ab", header);
/// assert_eq!(b"cdef", payload.as_slice());
/// # Ok::<(), std::io::Error>(())
/// ```
pub trait ReadExt: Read {
    /// Reads bytes into a range of `buffer` without checking the range bounds
    /// in release builds.
    ///
    /// This method delegates to [`Read::read`] after creating the target slice
    /// with raw pointer arithmetic. It performs at most one read operation and
    /// returns the number of bytes read, keeping the same short-read and error
    /// behavior as [`Read::read`].
    ///
    /// # Parameters
    /// - `buffer`: Destination buffer.
    /// - `start_index`: Start offset inside `buffer`.
    /// - `count`: Maximum number of bytes to read.
    ///
    /// # Returns
    /// The number of bytes written into `buffer[start_index..start_index +
    /// count]`. The value is in `0..=count`.
    ///
    /// # Errors
    /// Returns the error reported by [`Read::read`].
    ///
    /// # Panics
    /// Panics in debug builds if the requested destination range does not fit.
    ///
    /// # Safety
    /// The caller must guarantee that `start_index..start_index + count` is a
    /// valid range within `buffer` and that `start_index + count` does not
    /// overflow `usize`.
    unsafe fn read_unchecked(&mut self, buffer: &mut [u8], start_index: usize, count: usize) -> Result<usize>;

    /// Reads exactly `count` bytes into a range of `buffer` without checking
    /// the range bounds in release builds.
    ///
    /// This method delegates to [`Read::read_exact`] after creating the target
    /// slice with raw pointer arithmetic. It keeps the same blocking and error
    /// behavior as [`Read::read_exact`].
    ///
    /// # Parameters
    /// - `buffer`: Destination buffer.
    /// - `start_index`: Start offset inside `buffer`.
    /// - `count`: Number of bytes to read.
    ///
    /// # Returns
    /// `Ok(())` after the requested range has been filled.
    ///
    /// # Errors
    /// Returns the error reported by [`Read::read_exact`], including
    /// [`ErrorKind::UnexpectedEof`] when EOF is reached before `count` bytes
    /// are read.
    ///
    /// # Panics
    /// Panics in debug builds if the requested destination range does not fit.
    ///
    /// # Safety
    /// The caller must guarantee that `start_index..start_index + count` is a
    /// valid range within `buffer` and that `start_index + count` does not
    /// overflow `usize`.
    unsafe fn read_exact_unchecked(&mut self, buffer: &mut [u8], start_index: usize, count: usize) -> Result<()>;

    /// Reads bytes into a range of `buffer` until that range is full or EOF is
    /// reached, without checking the range bounds in release builds.
    ///
    /// This method has the same EOF and retry behavior as
    /// [`ReadExt::read_exact_or_eof`], but writes into
    /// `buffer[start_index..start_index + count]` using raw pointer
    /// arithmetic.
    ///
    /// # Parameters
    /// - `buffer`: Destination buffer.
    /// - `start_index`: Start offset inside `buffer`.
    /// - `count`: Number of bytes to try to read.
    ///
    /// # Returns
    /// The number of bytes written into `buffer[start_index..start_index +
    /// count]`. The value is in `0..=count`.
    ///
    /// # Errors
    /// Returns the first non-[`ErrorKind::Interrupted`] error reported by the
    /// underlying reader. Interrupted reads are retried.
    ///
    /// # Panics
    /// Panics in debug builds if the requested destination range does not fit.
    ///
    /// # Safety
    /// The caller must guarantee that `start_index..start_index + count` is a
    /// valid range within `buffer` and that `start_index + count` does not
    /// overflow `usize`.
    unsafe fn read_exact_or_eof_unchecked(
        &mut self,
        buffer: &mut [u8],
        start_index: usize,
        count: usize,
    ) -> Result<usize>;

    /// Reads bytes until `buffer` is full or EOF is reached.
    ///
    /// This method differs from [`Read::read_exact`] by treating EOF as a
    /// successful partial result. It keeps retrying short reads until the
    /// caller-provided buffer is full, EOF is reached, or a non-interrupted
    /// I/O error occurs.
    ///
    /// # Parameters
    /// - `buffer`: Destination buffer to fill.
    ///
    /// # Returns
    /// The number of bytes written into `buffer`. The value is in
    /// `0..=buffer.len()`.
    ///
    /// # Errors
    /// Returns the first non-[`ErrorKind::Interrupted`] error reported by the
    /// underlying reader. Interrupted reads are retried.
    fn read_exact_or_eof(&mut self, buffer: &mut [u8]) -> Result<usize>;

    /// Reads exactly `N` bytes into a stack-allocated array.
    ///
    /// This method uses [`Read::read_exact`] and therefore requires the reader
    /// to provide exactly `N` bytes before EOF.
    ///
    /// # Type Parameters
    /// - `N`: Number of bytes in the returned array.
    ///
    /// # Returns
    /// An array containing exactly `N` bytes read from this reader.
    ///
    /// # Errors
    /// Returns the error reported by [`Read::read_exact`], including
    /// [`ErrorKind::UnexpectedEof`] when EOF is reached before the array is
    /// full.
    fn read_exact_array<const N: usize>(&mut self) -> Result<[u8; N]>;

    /// Reads exactly `len` bytes into a new vector after checking a limit.
    ///
    /// If `len` is greater than `max_len`, this method returns
    /// [`ErrorKind::InvalidData`] before reading any bytes.
    ///
    /// # Parameters
    /// - `len`: Exact number of bytes to read.
    /// - `max_len`: Maximum accepted exact read length.
    ///
    /// # Returns
    /// A vector containing exactly `len` bytes.
    ///
    /// # Errors
    /// Returns [`ErrorKind::InvalidData`] when `len > max_len`. Returns the
    /// [`ErrorKind::OutOfMemory`] error when the result vector cannot be
    /// allocated. Returns the error reported by [`Read::read_exact`], including
    /// [`ErrorKind::UnexpectedEof`] when EOF is reached before `len` bytes are
    /// read.
    fn read_exact_vec_limited(&mut self, len: usize, max_len: usize) -> Result<Vec<u8>>;

    /// Reads exactly `len` bytes and appends them to `output`.
    ///
    /// If `len` is greater than `max_len`, this method returns
    /// [`ErrorKind::InvalidData`] before reading any bytes and leaves `output`
    /// unchanged. On a read error, `output` is truncated back to its original
    /// length. The underlying reader may still have consumed bytes before the
    /// error because [`Read`] does not provide rollback.
    ///
    /// # Parameters
    /// - `output`: Destination vector to append to.
    /// - `len`: Exact number of bytes to read.
    /// - `max_len`: Maximum accepted exact read length.
    ///
    /// # Returns
    /// `Ok(())` after exactly `len` bytes have been appended to `output`.
    ///
    /// # Errors
    /// Returns [`ErrorKind::InvalidData`] when `len > max_len`,
    /// [`ErrorKind::InvalidInput`] when `output.len() + len` overflows, or
    /// [`ErrorKind::OutOfMemory`] when `output` cannot reserve the appended
    /// bytes. Returns the error reported by [`Read::read_exact`], including
    /// [`ErrorKind::UnexpectedEof`] when EOF is reached before `len` bytes are
    /// read.
    fn read_exact_vec_limited_into(&mut self, output: &mut Vec<u8>, len: usize, max_len: usize) -> Result<()>;

    /// Discards up to `bytes` bytes from this reader.
    ///
    /// The method repeatedly reads into an internal stack buffer until the
    /// requested number of bytes has been consumed or EOF is reached. It does
    /// not allocate and does not require seeking support.
    ///
    /// # Parameters
    /// - `bytes`: Maximum number of bytes to discard.
    ///
    /// # Returns
    /// The number of bytes actually discarded. The value may be smaller than
    /// `bytes` when EOF is reached first.
    ///
    /// # Errors
    /// Returns the first non-[`ErrorKind::Interrupted`] error reported by the
    /// underlying reader. Interrupted reads are retried.
    fn discard_exact_or_eof(&mut self, bytes: u64) -> Result<u64>;

    /// Copies all remaining bytes from this reader into `writer`.
    ///
    /// This method is a method-style wrapper around [`std::io::copy`]. It
    /// copies from the current reader position until EOF and does not close or
    /// flush either stream.
    ///
    /// # Parameters
    /// - `writer`: Destination writer.
    ///
    /// # Returns
    /// The number of bytes copied.
    ///
    /// # Errors
    /// Returns the first read or write error reported by the underlying
    /// streams, using the same error behavior as [`std::io::copy`].
    fn copy_to(&mut self, writer: &mut dyn Write) -> Result<u64>;

    /// Copies at most `max_bytes` bytes from this reader into `writer`.
    ///
    /// This method stops successfully when either EOF is reached or
    /// `max_bytes` bytes have been copied. It does not close or flush either
    /// stream.
    ///
    /// # Parameters
    /// - `writer`: Destination writer.
    /// - `max_bytes`: Maximum number of bytes to copy.
    ///
    /// # Returns
    /// The number of bytes copied.
    ///
    /// # Errors
    /// Returns [`ErrorKind::OutOfMemory`] if the temporary copy buffer cannot
    /// be allocated. Returns the first non-[`ErrorKind::Interrupted`] read
    /// error or write error reported by the underlying streams. Interrupted
    /// reads are retried.
    fn copy_to_at_most(&mut self, writer: &mut dyn Write, max_bytes: u64) -> Result<u64>;

    /// Copies the remaining input if its total length is at most `max_bytes`.
    ///
    /// This method copies from the current reader position until EOF. If EOF is
    /// not reached within `max_bytes` bytes, it returns
    /// [`ErrorKind::InvalidData`]. Detecting oversized input consumes one
    /// excess byte from this reader; that excess byte is not written to
    /// `writer`.
    ///
    /// Unlike bounded reads into in-memory collections, this method cannot roll
    /// back bytes already accepted by `writer` when the limit is exceeded
    /// because [`Write`] does not provide truncation. On
    /// [`ErrorKind::InvalidData`], up to `max_bytes` bytes may remain in
    /// `writer`.
    ///
    /// # Parameters
    /// - `writer`: Destination writer.
    /// - `max_bytes`: Maximum accepted number of bytes in the remaining input.
    ///
    /// # Returns
    /// The number of bytes copied when EOF is reached within the limit.
    ///
    /// # Errors
    /// Returns [`ErrorKind::InvalidData`] when the remaining input is longer
    /// than `max_bytes`. Returns [`ErrorKind::OutOfMemory`] if the temporary
    /// copy buffer cannot be allocated. Returns the first
    /// non-[`ErrorKind::Interrupted`] read error or write error reported by the
    /// underlying streams. Interrupted reads are retried.
    fn copy_to_end_limited(&mut self, writer: &mut dyn Write, max_bytes: u64) -> Result<u64>;

    /// Reads the remaining bytes into a vector with a maximum accepted length.
    ///
    /// This method consumes bytes from the current reader position until EOF is
    /// reached. If the stream contains more than `max_len` bytes, it returns
    /// [`ErrorKind::InvalidData`] after detecting the first excess byte. No
    /// vector is returned on failure.
    ///
    /// # Parameters
    /// - `max_len`: Maximum number of bytes accepted in the returned vector.
    ///
    /// # Returns
    /// A vector containing all remaining bytes when the stream length is within
    /// the limit.
    ///
    /// # Errors
    /// Returns [`ErrorKind::InvalidData`] when the stream contains more than
    /// `max_len` bytes. Returns [`ErrorKind::OutOfMemory`] when the result
    /// vector cannot grow. Returns the first non-[`ErrorKind::Interrupted`]
    /// error reported by the underlying reader; interrupted reads are
    /// retried.
    fn read_to_end_limited(&mut self, max_len: usize) -> Result<Vec<u8>>;

    /// Reads the remaining bytes into `output` with a maximum accepted length.
    ///
    /// This method appends at most `max_len` bytes from the current reader
    /// position to `output`. If the stream contains more than `max_len` bytes,
    /// it returns [`ErrorKind::InvalidData`] after detecting the first excess
    /// byte and truncates `output` back to its original length. The underlying
    /// reader may still have consumed bytes before the error because [`Read`]
    /// does not provide rollback.
    ///
    /// # Parameters
    /// - `output`: Destination vector to append to.
    /// - `max_len`: Maximum number of bytes accepted from this reader.
    ///
    /// # Returns
    /// The number of bytes appended to `output`.
    ///
    /// # Errors
    /// Returns [`ErrorKind::InvalidData`] when the stream contains more than
    /// `max_len` bytes. Returns [`ErrorKind::OutOfMemory`] when `output` cannot
    /// grow. Returns the first non-[`ErrorKind::Interrupted`] error reported by
    /// the underlying reader; interrupted reads are retried.
    fn read_to_end_limited_into(&mut self, output: &mut Vec<u8>, max_len: usize) -> Result<usize>;

    /// Reads the remaining bytes as UTF-8 text with a maximum accepted length.
    ///
    /// This method has the same size limit and read semantics as
    /// [`ReadExt::read_to_end_limited`], then validates the collected bytes as
    /// UTF-8.
    ///
    /// # Parameters
    /// - `max_len`: Maximum number of bytes accepted before UTF-8 decoding.
    ///
    /// # Returns
    /// The decoded UTF-8 string.
    ///
    /// # Errors
    /// Returns [`ErrorKind::InvalidData`] when the stream contains more than
    /// `max_len` bytes or when the collected bytes are not valid UTF-8. Returns
    /// [`ErrorKind::OutOfMemory`] when the result buffer cannot grow. Returns
    /// the first non-[`ErrorKind::Interrupted`] error reported by the
    /// underlying reader; interrupted reads are retried.
    fn read_to_string_limited(&mut self, max_len: usize) -> Result<String>;

    /// Reads the remaining bytes as UTF-8 text and appends to `output`.
    ///
    /// This method accepts at most `max_len` bytes from the current reader
    /// position, validates them as UTF-8, and appends the decoded text to
    /// `output`. If the input is oversized or invalid UTF-8, `output` is
    /// truncated back to its original length. Oversized input may still consume
    /// up to `max_len + 1` bytes from the reader while detecting the limit
    /// violation.
    ///
    /// # Parameters
    /// - `output`: Destination string to append to.
    /// - `max_len`: Maximum number of bytes accepted before UTF-8 decoding.
    ///
    /// # Returns
    /// The number of bytes appended to `output`.
    ///
    /// # Errors
    /// Returns [`ErrorKind::InvalidData`] when the stream contains more than
    /// `max_len` bytes or when the collected bytes are not valid UTF-8. Returns
    /// [`ErrorKind::OutOfMemory`] when the temporary byte buffer or `output`
    /// cannot grow. Returns the first non-[`ErrorKind::Interrupted`] error
    /// reported by the underlying reader; interrupted reads are retried.
    fn read_to_string_limited_into(&mut self, output: &mut String, max_len: usize) -> Result<usize>;
}

/// Reads an indexed range to EOF through a type-erased reader.
///
/// # Parameters
/// - `reader`: Reader that supplies the bytes.
/// - `buffer`: Destination buffer.
/// - `start_index`: Start offset inside `buffer`.
/// - `count`: Number of bytes to try to read.
///
/// # Returns
/// The number of bytes written into the requested range.
///
/// # Errors
/// Returns the first non-interrupted read error.
///
/// # Panics
/// Panics in debug builds if the requested output range does not fit.
///
/// # Safety
/// The caller must guarantee that `start_index..start_index + count` is valid
/// inside `buffer` and that the addition does not overflow.
unsafe fn read_exact_or_eof_unchecked_impl(
    reader: &mut dyn Read,
    buffer: &mut [u8],
    start_index: usize,
    count: usize,
) -> Result<usize> {
    debug_assert!(
        SliceRange::range_fits(buffer.len(), start_index, count),
        "unchecked read range exceeds buffer"
    );
    let mut total = 0;
    while total < count {
        // SAFETY: The caller guarantees that `start_index..start_index + count`
        // is valid for `buffer`; `total < count`, so this suffix is valid.
        let target = unsafe { UncheckedSlice::subslice_mut(buffer, start_index + total, count - total) };
        match reader.read(target) {
            Ok(0) => break,
            Ok(read) => total += read,
            Err(error) => {
                if error.kind() == ErrorKind::Interrupted {
                    continue;
                }
                return Err(error);
            }
        }
    }
    Ok(total)
}

/// Reads a fixed-size byte array through a type-erased reader.
///
/// # Type Parameters
/// - `N`: Number of bytes in the returned array.
///
/// # Parameters
/// - `reader`: Reader that supplies the bytes.
///
/// # Returns
/// An array containing exactly `N` bytes.
///
/// # Errors
/// Returns the error reported by [`Read::read_exact`].
#[inline]
fn read_exact_array_impl<const N: usize>(reader: &mut dyn Read) -> Result<[u8; N]> {
    let mut buffer = [0; N];
    reader.read_exact(&mut buffer)?;
    Ok(buffer)
}

/// Reads an exactly sized bounded vector through a type-erased reader.
///
/// # Parameters
/// - `reader`: Reader that supplies the bytes.
/// - `len`: Exact number of bytes to read.
/// - `max_len`: Maximum accepted exact read length.
///
/// # Returns
/// A vector containing exactly `len` bytes.
///
/// # Errors
/// Returns [`ErrorKind::OutOfMemory`] if the result vector cannot be allocated,
/// a read error, or [`ErrorKind::InvalidData`] when `len > max_len`.
#[inline]
fn read_exact_vec_limited_impl(reader: &mut dyn Read, len: usize, max_len: usize) -> Result<Vec<u8>> {
    let mut output = Vec::new();
    read_ext_impl::read_exact_vec_limited_into(reader, &mut output, len, max_len)?;
    Ok(output)
}

/// Discards a bounded byte count through a type-erased reader.
///
/// # Parameters
/// - `reader`: Reader whose bytes are discarded.
/// - `bytes`: Maximum number of bytes to discard.
///
/// # Returns
/// The number of bytes discarded before the limit or EOF was reached.
///
/// # Errors
/// Returns the first non-interrupted read error.
fn discard_exact_or_eof_impl(reader: &mut dyn Read, bytes: u64) -> Result<u64> {
    let mut buffer = [0; DISCARD_BUFFER_SIZE];
    let mut remaining = bytes;
    let mut discarded = 0;
    while remaining > 0 {
        let requested = remaining.min(DISCARD_BUFFER_SIZE as u64) as usize;
        match reader.read(&mut buffer[..requested]) {
            Ok(0) => break,
            Ok(count) => {
                let count = count as u64;
                remaining -= count;
                discarded += count;
            }
            Err(error) => {
                if error.kind() == ErrorKind::Interrupted {
                    continue;
                }
                return Err(error);
            }
        }
    }
    Ok(discarded)
}

/// Reads bounded UTF-8 text through a type-erased reader.
///
/// # Parameters
/// - `reader`: Reader that supplies the text bytes.
/// - `max_len`: Maximum accepted byte length.
///
/// # Returns
/// The decoded UTF-8 string.
///
/// # Errors
/// Returns [`ErrorKind::OutOfMemory`] if the result buffer cannot grow, a read
/// error, or [`ErrorKind::InvalidData`] when the input exceeds `max_len` or is
/// not valid UTF-8.
#[inline]
fn read_to_string_limited_impl(reader: &mut dyn Read, max_len: usize) -> Result<String> {
    let bytes = read_ext_impl::read_to_end_limited(reader, max_len)?;
    String::from_utf8(bytes).map_err(read_ext_impl::invalid_utf8_error)
}

/// Appends bounded UTF-8 text read through a type-erased reader.
///
/// # Parameters
/// - `reader`: Reader that supplies the text bytes.
/// - `output`: String that receives the decoded text.
/// - `max_len`: Maximum accepted byte length.
///
/// # Returns
/// The number of bytes appended to `output`.
///
/// # Errors
/// Returns [`ErrorKind::OutOfMemory`] if the temporary byte buffer or `output`
/// cannot grow, a read error, or [`ErrorKind::InvalidData`] when the input
/// exceeds `max_len` or is not valid UTF-8.
#[inline]
fn read_to_string_limited_into_impl(reader: &mut dyn Read, output: &mut String, max_len: usize) -> Result<usize> {
    let bytes = read_ext_impl::read_to_end_limited(reader, max_len)?;
    let text = String::from_utf8(bytes).map_err(read_ext_impl::invalid_utf8_error)?;
    let count = text.len();
    try_reserve_string(output, count).map_err(allocation_error)?;
    output.push_str(&text);
    Ok(count)
}

impl<T> ReadExt for T
where
    T: Read + ?Sized,
{
    /// Reads bytes from an unchecked range into a standard [`Read`] value.
    ///
    /// # Parameters
    /// - `buffer`: Destination buffer.
    /// - `start_index`: Start offset inside `buffer`.
    /// - `count`: Maximum number of bytes to read.
    ///
    /// # Returns
    /// The number of bytes read into the requested range.
    ///
    /// # Errors
    /// Returns the error reported by [`Read::read`].
    ///
    /// # Panics
    /// Panics in debug builds if the requested output range does not fit.
    ///
    /// # Safety
    /// The caller must guarantee that `start_index..start_index + count` is
    /// valid inside `buffer` and that the addition does not overflow.
    #[inline(always)]
    unsafe fn read_unchecked(&mut self, buffer: &mut [u8], start_index: usize, count: usize) -> Result<usize> {
        // SAFETY: The caller guarantees that the requested range is valid for
        // `buffer`.
        let target = unsafe { UncheckedSlice::subslice_mut(buffer, start_index, count) };
        self.read(target)
    }

    /// Reads an unchecked range until it is full or EOF is reached.
    ///
    /// # Parameters
    /// - `buffer`: Destination buffer.
    /// - `start_index`: Start offset inside `buffer`.
    /// - `count`: Number of bytes to try to read.
    ///
    /// # Returns
    /// The number of bytes read into the requested range.
    ///
    /// # Errors
    /// Returns the first non-interrupted read error.
    ///
    /// # Panics
    /// Panics in debug builds if the requested output range does not fit.
    ///
    /// # Safety
    /// The caller must guarantee that `start_index..start_index + count` is
    /// valid inside `buffer` and that the addition does not overflow.
    #[inline(always)]
    unsafe fn read_exact_or_eof_unchecked(
        &mut self,
        buffer: &mut [u8],
        start_index: usize,
        count: usize,
    ) -> Result<usize> {
        let mut reader = self;
        // SAFETY: Forwarded from the trait caller.
        unsafe { read_exact_or_eof_unchecked_impl(&mut reader, buffer, start_index, count) }
    }

    /// Reads exactly the requested unchecked range.
    ///
    /// # Parameters
    /// - `buffer`: Destination buffer.
    /// - `start_index`: Start offset inside `buffer`.
    /// - `count`: Number of bytes to read.
    ///
    /// # Returns
    /// `Ok(())` after the requested range has been filled.
    ///
    /// # Errors
    /// Returns the error reported by [`Read::read_exact`].
    ///
    /// # Panics
    /// Panics in debug builds if the requested output range does not fit.
    ///
    /// # Safety
    /// The caller must guarantee that `start_index..start_index + count` is
    /// valid inside `buffer` and that the addition does not overflow.
    #[inline(always)]
    unsafe fn read_exact_unchecked(&mut self, buffer: &mut [u8], start_index: usize, count: usize) -> Result<()> {
        // SAFETY: The caller guarantees that the requested range is valid for
        // `buffer`.
        let target = unsafe { UncheckedSlice::subslice_mut(buffer, start_index, count) };
        self.read_exact(target)
    }

    /// Reads the destination until it is full or EOF is reached.
    ///
    /// # Parameters
    /// - `buffer`: Destination buffer.
    ///
    /// # Returns
    /// The number of bytes read into `buffer`.
    ///
    /// # Errors
    /// Returns the first non-interrupted read error.
    #[inline(always)]
    fn read_exact_or_eof(&mut self, buffer: &mut [u8]) -> Result<usize> {
        let mut reader = self;
        read_ext_impl::read_exact_or_eof(&mut reader, buffer)
    }

    /// Reads exactly `N` bytes into an array.
    ///
    /// # Type Parameters
    /// - `N`: Number of bytes in the returned array.
    ///
    /// # Returns
    /// An array containing exactly `N` bytes.
    ///
    /// # Errors
    /// Returns the error reported by [`Read::read_exact`].
    #[inline(always)]
    fn read_exact_array<const N: usize>(&mut self) -> Result<[u8; N]> {
        let mut reader = self;
        read_exact_array_impl(&mut reader)
    }

    /// Reads an exactly sized vector within a configured limit.
    ///
    /// # Parameters
    /// - `len`: Exact number of bytes to read.
    /// - `max_len`: Maximum accepted exact read length.
    ///
    /// # Returns
    /// A vector containing exactly `len` bytes.
    ///
    /// # Errors
    /// Returns [`ErrorKind::OutOfMemory`] if the result vector cannot be
    /// allocated, a read error, or [`ErrorKind::InvalidData`] when
    /// `len > max_len`.
    #[inline(always)]
    fn read_exact_vec_limited(&mut self, len: usize, max_len: usize) -> Result<Vec<u8>> {
        let mut reader = self;
        read_exact_vec_limited_impl(&mut reader, len, max_len)
    }

    /// Reads exactly `len` bytes and appends them to a vector.
    ///
    /// # Parameters
    /// - `output`: Destination vector.
    /// - `len`: Exact number of bytes to read.
    /// - `max_len`: Maximum accepted exact read length.
    ///
    /// # Returns
    /// `Ok(())` after exactly `len` bytes have been appended.
    ///
    /// # Errors
    /// Returns [`ErrorKind::OutOfMemory`] if `output` cannot grow, a read
    /// error, [`ErrorKind::InvalidData`] when `len > max_len`, or
    /// [`ErrorKind::InvalidInput`] when `output.len() + len` overflows.
    #[inline(always)]
    fn read_exact_vec_limited_into(&mut self, output: &mut Vec<u8>, len: usize, max_len: usize) -> Result<()> {
        let mut reader = self;
        read_ext_impl::read_exact_vec_limited_into(&mut reader, output, len, max_len)
    }

    /// Discards at most the requested number of bytes.
    ///
    /// # Parameters
    /// - `bytes`: Maximum number of bytes to discard.
    ///
    /// # Returns
    /// The number of bytes discarded before the limit or EOF was reached.
    ///
    /// # Errors
    /// Returns the first non-interrupted read error.
    #[inline(always)]
    fn discard_exact_or_eof(&mut self, bytes: u64) -> Result<u64> {
        let mut reader = self;
        discard_exact_or_eof_impl(&mut reader, bytes)
    }

    /// Copies all remaining bytes to a writer.
    ///
    /// # Parameters
    /// - `writer`: Destination writer.
    ///
    /// # Returns
    /// The number of bytes copied.
    ///
    /// # Errors
    /// Returns the first read or write error.
    #[inline(always)]
    fn copy_to(&mut self, writer: &mut dyn Write) -> Result<u64> {
        copy_all(self, writer)
    }

    /// Copies at most the requested number of bytes to a writer.
    ///
    /// # Parameters
    /// - `writer`: Destination writer.
    /// - `max_bytes`: Maximum number of bytes to copy.
    ///
    /// # Returns
    /// The number of bytes copied.
    ///
    /// # Errors
    /// Returns [`ErrorKind::OutOfMemory`] if the temporary copy buffer cannot
    /// be allocated, or the first non-interrupted read error or write error.
    #[inline(always)]
    fn copy_to_at_most(&mut self, writer: &mut dyn Write, max_bytes: u64) -> Result<u64> {
        let mut reader = self;
        Streams::copy_at_most(&mut reader, writer, max_bytes)
    }

    /// Copies the remaining input when it fits within a configured limit.
    ///
    /// # Parameters
    /// - `writer`: Destination writer.
    /// - `max_bytes`: Maximum accepted remaining byte count.
    ///
    /// # Returns
    /// The number of bytes copied.
    ///
    /// # Errors
    /// Returns [`ErrorKind::OutOfMemory`] if the temporary copy buffer cannot
    /// be allocated, a read or write error, or [`ErrorKind::InvalidData`] when
    /// the remaining input exceeds `max_bytes`.
    #[inline(always)]
    fn copy_to_end_limited(&mut self, writer: &mut dyn Write, max_bytes: u64) -> Result<u64> {
        let mut reader = self;
        Streams::copy_to_end_limited(&mut reader, writer, max_bytes)
    }

    /// Reads the remaining bytes into a bounded vector.
    ///
    /// # Parameters
    /// - `max_len`: Maximum accepted remaining byte count.
    ///
    /// # Returns
    /// A vector containing all remaining bytes.
    ///
    /// # Errors
    /// Returns [`ErrorKind::OutOfMemory`] if the result vector cannot grow, a
    /// read error, or [`ErrorKind::InvalidData`] when the remaining input
    /// exceeds `max_len`.
    #[inline(always)]
    fn read_to_end_limited(&mut self, max_len: usize) -> Result<Vec<u8>> {
        let mut reader = self;
        read_ext_impl::read_to_end_limited(&mut reader, max_len)
    }

    /// Appends the remaining bytes to a bounded vector.
    ///
    /// # Parameters
    /// - `output`: Destination vector.
    /// - `max_len`: Maximum accepted remaining byte count.
    ///
    /// # Returns
    /// The number of bytes appended to `output`.
    ///
    /// # Errors
    /// Returns [`ErrorKind::OutOfMemory`] if `output` cannot grow, a read
    /// error, or [`ErrorKind::InvalidData`] when the remaining input
    /// exceeds `max_len`.
    #[inline(always)]
    fn read_to_end_limited_into(&mut self, output: &mut Vec<u8>, max_len: usize) -> Result<usize> {
        let mut reader = self;
        read_ext_impl::read_to_end_limited_into(&mut reader, output, max_len)
    }

    /// Reads the remaining bytes as bounded UTF-8 text.
    ///
    /// # Parameters
    /// - `max_len`: Maximum accepted remaining byte count.
    ///
    /// # Returns
    /// The decoded UTF-8 string.
    ///
    /// # Errors
    /// Returns [`ErrorKind::OutOfMemory`] if the result buffer cannot grow, a
    /// read error, or [`ErrorKind::InvalidData`] when the input exceeds
    /// `max_len` or is not valid UTF-8.
    #[inline(always)]
    fn read_to_string_limited(&mut self, max_len: usize) -> Result<String> {
        let mut reader = self;
        read_to_string_limited_impl(&mut reader, max_len)
    }

    /// Appends the remaining bounded UTF-8 text to a string.
    ///
    /// # Parameters
    /// - `output`: Destination string.
    /// - `max_len`: Maximum accepted remaining byte count.
    ///
    /// # Returns
    /// The number of bytes appended to `output`.
    ///
    /// # Errors
    /// Returns [`ErrorKind::OutOfMemory`] if the temporary byte buffer or
    /// `output` cannot grow, a read error, or [`ErrorKind::InvalidData`] when
    /// the input exceeds `max_len` or is not valid UTF-8.
    #[inline(always)]
    fn read_to_string_limited_into(&mut self, output: &mut String, max_len: usize) -> Result<usize> {
        let mut reader = self;
        read_to_string_limited_into_impl(&mut reader, output, max_len)
    }
}