qubit-io 0.13.0

Byte-stream buffering and std::io utilities 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
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
// qubit-style: allow coverage-cfg
#[cfg(coverage)]
use std::cell::Cell;
use std::cmp::Ordering;
use std::io::{
    Error,
    ErrorKind,
    Read,
    Result,
    Write,
};

use crate::ReadExt;
use crate::capacity_const::{
    DEFAULT_BUFFER_CAPACITY,
    DEFAULT_COMPARE_BUFFER_SIZE,
    DEFAULT_COPY_BUFFER_SIZE,
};
use crate::traits::validate_read_count;
use crate::util::{
    create_vec,
    try_reserve_vec,
};
use crate::{
    Input,
    Output,
};

/// Stream utility namespace.
///
/// This type is an uninstantiable namespace for operations involving one or
/// more [`Read`] or [`Write`] values. The methods do not close or flush the
/// supplied streams unless the underlying standard-library operation documents
/// otherwise.
///
/// # Examples
/// ```
/// use qubit_io::Streams;
/// use std::io::Cursor;
///
/// let mut input = Cursor::new(b"abcdef".to_vec());
/// let mut output = Vec::new();
///
/// let copied = Streams::copy_at_most(&mut input, &mut output, 4)?;
///
/// assert_eq!(4, copied);
/// assert_eq!(b"abcd", output.as_slice());
/// # Ok::<(), std::io::Error>(())
/// ```
pub enum Streams {}

impl Streams {
    /// Copies all remaining bytes from `reader` to `writer`.
    ///
    /// This is a namespace-style wrapper around [`std::io::copy`]. It preserves
    /// the standard-library behavior, including platform-specific optimized
    /// copy paths when available.
    ///
    /// # Parameters
    /// - `reader`: Source reader.
    /// - `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`].
    #[inline]
    pub fn copy<R, W>(reader: &mut R, writer: &mut W) -> Result<u64>
    where
        R: Read + ?Sized,
        W: Write + ?Sized,
    {
        std::io::copy(reader, writer)
    }

    /// Copies at most `max_bytes` bytes from `reader` to `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
    /// - `reader`: Source reader.
    /// - `writer`: Destination writer.
    /// - `max_bytes`: Maximum number of bytes to copy.
    ///
    /// # Returns
    /// The number of bytes copied.
    ///
    /// # Errors
    /// Returns the first non-interrupted read error or write error reported by
    /// the underlying streams. Interrupted reads are retried.
    #[inline]
    pub fn copy_at_most<R, W>(
        reader: &mut R,
        writer: &mut W,
        max_bytes: u64,
    ) -> Result<u64>
    where
        R: Read + ?Sized,
        W: Write + ?Sized,
    {
        let mut reader = reader;
        let mut writer = writer;
        copy_at_most_impl(
            &mut reader,
            &mut writer,
            max_bytes,
            DEFAULT_COPY_BUFFER_SIZE,
        )
    }

    /// Copies at most `max_bytes` bytes from `reader` to `writer` using a
    /// caller-selected heap buffer.
    ///
    /// This method has the same copy semantics as [`Self::copy_at_most`], but
    /// allocates a buffer on the heap with `buffer_size` bytes. Use it when
    /// the default chunk size is too large for the caller's stack budget or
    /// when a smaller copy window is desirable.
    ///
    /// # Parameters
    /// - `reader`: Source reader.
    /// - `writer`: Destination writer.
    /// - `max_bytes`: Maximum number of bytes to copy.
    /// - `buffer_size`: Number of bytes in the copy buffer.
    ///
    /// # Returns
    /// The number of bytes copied.
    ///
    /// # Errors
    /// Returns [`ErrorKind::InvalidInput`] when `buffer_size == 0`. Returns an
    /// allocation error if the copy buffer cannot be allocated. Returns the
    /// first non-interrupted read error or write error reported by the
    /// underlying streams. Interrupted reads are retried.
    #[inline]
    pub fn copy_at_most_with_buffer_size<R, W>(
        reader: &mut R,
        writer: &mut W,
        max_bytes: u64,
        buffer_size: usize,
    ) -> Result<u64>
    where
        R: Read + ?Sized,
        W: Write + ?Sized,
    {
        let mut reader = reader;
        let mut writer = writer;
        copy_at_most_impl(&mut reader, &mut writer, max_bytes, buffer_size)
    }

    /// 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
    /// [`std::io::ErrorKind::InvalidData`]. Detecting oversized input consumes
    /// one excess byte from `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
    /// [`std::io::ErrorKind::InvalidData`], up to `max_bytes` bytes may remain
    /// in `writer`.
    ///
    /// # Parameters
    /// - `reader`: Source reader.
    /// - `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 [`std::io::ErrorKind::InvalidData`] when the remaining input is
    /// longer than `max_bytes`. Returns the first non-interrupted read error or
    /// write error reported by the underlying streams. Interrupted reads are
    /// retried.
    #[inline]
    pub fn copy_to_end_limited<R, W>(
        reader: &mut R,
        writer: &mut W,
        max_bytes: u64,
    ) -> Result<u64>
    where
        R: Read + ?Sized,
        W: Write + ?Sized,
    {
        let mut reader = reader;
        let mut writer = writer;
        let copied = copy_at_most_impl(
            &mut reader,
            &mut writer,
            max_bytes,
            DEFAULT_COPY_BUFFER_SIZE,
        )?;
        if copied < max_bytes {
            return Ok(copied);
        }
        let mut byte = [0];
        loop {
            match reader.read(&mut byte) {
                Ok(0) => return Ok(copied),
                Ok(_) => {
                    return Err(Error::new(
                        ErrorKind::InvalidData,
                        format!(
                            "input exceeds maximum length of {max_bytes} bytes"
                        ),
                    ));
                }
                Err(error) => {
                    if error.kind() == ErrorKind::Interrupted {
                        continue;
                    }
                    return Err(error);
                }
            }
        }
    }

    /// Copies all remaining items from `input` to `output`.
    ///
    /// This method allocates a reusable item buffer and copies until EOF. It
    /// does not close or flush `output`.
    ///
    /// # Parameters
    /// - `input`: Source item input.
    /// - `output`: Destination item output.
    ///
    /// # Returns
    /// The number of items copied.
    ///
    /// # Errors
    /// Returns the first non-interrupted read error or output error reported by
    /// the underlying streams. Returns [`ErrorKind::InvalidData`] if an input
    /// or output reports an impossible item count.
    pub fn copy_input_to_output<I, O>(
        input: &mut I,
        output: &mut O,
    ) -> Result<u64>
    where
        I: Input + ?Sized,
        O: Output<Item = I::Item> + ?Sized,
        I::Item: Copy + Default,
    {
        let mut buffer =
            create_vec(DEFAULT_BUFFER_CAPACITY, I::Item::default())?;
        let mut copied = 0_u64;
        loop {
            let read = input.read_fully(&mut buffer)?;
            validate_read_count(read, buffer.len())?;
            if read == 0 {
                return Ok(copied);
            }
            // SAFETY: `read` is bounded by `buffer.len()`.
            unsafe {
                output.write_fully_unchecked(&buffer, 0, read)?;
            }
            copied = add_item_count(copied, read)?;
        }
    }

    /// Copies at most `max_items` items from `input` to `output`.
    ///
    /// This method stops successfully when either EOF is reached or `max_items`
    /// items have been copied. It does not close or flush `output`.
    ///
    /// # Parameters
    /// - `input`: Source item input.
    /// - `output`: Destination item output.
    /// - `max_items`: Maximum number of items to copy.
    ///
    /// # Returns
    /// The number of items copied.
    ///
    /// # Errors
    /// Returns the first non-interrupted read error or output error reported by
    /// the underlying streams. Returns [`ErrorKind::InvalidData`] if an input
    /// or output reports an impossible item count.
    pub fn copy_input_to_output_at_most<I, O>(
        input: &mut I,
        output: &mut O,
        max_items: u64,
    ) -> Result<u64>
    where
        I: Input + ?Sized,
        O: Output<Item = I::Item> + ?Sized,
        I::Item: Copy + Default,
    {
        if max_items == 0 {
            return Ok(0);
        }
        let mut buffer =
            create_vec(DEFAULT_BUFFER_CAPACITY, I::Item::default())?;
        let mut remaining = max_items;
        let mut copied = 0_u64;
        while remaining > 0 {
            let requested = remaining.min(buffer.len() as u64) as usize;
            // SAFETY: `requested` is a valid prefix length inside `buffer`.
            let read = unsafe {
                input.read_fully_unchecked(&mut buffer, 0, requested)?
            };
            validate_read_count(read, requested)?;
            if read == 0 {
                break;
            }
            // SAFETY: `read` is bounded by the requested prefix.
            unsafe {
                output.write_fully_unchecked(&buffer, 0, read)?;
            }
            let read = read as u64;
            remaining -= read;
            copied = add_item_count(copied, read as usize)?;
        }
        Ok(copied)
    }

    /// Copies the remaining input if its total length is at most `max_items`.
    ///
    /// This method copies from the current input position until EOF. If EOF is
    /// not reached within `max_items` items, it returns
    /// [`ErrorKind::InvalidData`]. Detecting oversized input consumes one
    /// excess item from `input`; that excess item is not written to
    /// `output`.
    ///
    /// Oversized input, read errors, and allocation failures before output
    /// flushing leave `output` unchanged. Once EOF is reached and collected
    /// items are written to `output`, a write error may leave partial items
    /// accepted by `output` because [`Output`] has no rollback operation.
    ///
    /// # Parameters
    /// - `input`: Source item input.
    /// - `output`: Destination item output.
    /// - `max_items`: Maximum accepted number of remaining input items.
    ///
    /// # Returns
    /// The number of items copied when EOF is reached within the limit.
    ///
    /// # Errors
    /// Returns [`ErrorKind::InvalidData`] when the remaining input is longer
    /// than `max_items`, or when an input reports an impossible item count.
    /// Returns the first non-interrupted read error or output error reported by
    /// the underlying streams.
    pub fn copy_input_to_output_end_limited<I, O>(
        input: &mut I,
        output: &mut O,
        max_items: u64,
    ) -> Result<u64>
    where
        I: Input + ?Sized,
        O: Output<Item = I::Item> + ?Sized,
        I::Item: Copy + Default,
    {
        let mut buffer =
            create_vec(DEFAULT_BUFFER_CAPACITY, I::Item::default())?;
        let mut collected = Vec::new();
        let mut remaining = max_items;
        let mut copied = 0_u64;
        loop {
            let requested =
                remaining.saturating_add(1).min(buffer.len() as u64) as usize;
            // SAFETY: `requested` is a valid prefix length inside `buffer`.
            let read = unsafe {
                input.read_fully_unchecked(&mut buffer, 0, requested)?
            };
            validate_read_count(read, requested)?;
            if read == 0 {
                let count = collected.len();
                if count == 0 {
                    return Ok(copied);
                }
                // SAFETY: The full collected range is valid.
                unsafe {
                    output.write_fully_unchecked(&collected, 0, count)?;
                }
                return Ok(copied);
            }
            if (read as u64) > remaining {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!(
                        "input exceeds maximum length of {max_items} items"
                    ),
                ));
            }
            try_reserve_vec(&mut collected, read)?;
            collected.extend_from_slice(&buffer[..read]);
            let read = read as u64;
            remaining -= read;
            copied = add_item_count(copied, read as usize)?;
        }
    }

    /// Tests whether two readable streams have equal remaining contents.
    ///
    /// The comparison starts at each reader's current position and reads both
    /// streams in fixed-size chunks. A mismatch stops comparison immediately
    /// after the differing chunks are read, so each reader may have advanced
    /// past the first differing byte within that chunk.
    ///
    /// # Parameters
    /// - `left`: First stream.
    /// - `right`: Second stream.
    ///
    /// # Returns
    /// `true` when both streams produce the same bytes until EOF.
    ///
    /// # Errors
    /// Returns the first read error reported by either stream.
    #[inline]
    pub fn content_eq(
        left: &mut dyn Read,
        right: &mut dyn Read,
    ) -> Result<bool> {
        Ok(Self::compare_content(left, right)? == Ordering::Equal)
    }

    /// Lexicographically compares the remaining contents of two readable
    /// streams.
    ///
    /// The comparison starts at each reader's current position and reads both
    /// streams in fixed-size chunks. A mismatch stops comparison immediately
    /// after the differing chunks are read, so each reader may have advanced
    /// past the first differing byte within that chunk.
    ///
    /// # Parameters
    /// - `left`: First stream.
    /// - `right`: Second stream.
    ///
    /// # Returns
    /// The lexicographic ordering of the remaining bytes.
    ///
    /// # Errors
    /// Returns the first read error reported by either stream.
    pub fn compare_content(
        left: &mut dyn Read,
        right: &mut dyn Read,
    ) -> Result<Ordering> {
        Self::compare_content_with_buffer_size(
            left,
            right,
            DEFAULT_COMPARE_BUFFER_SIZE,
        )
    }

    /// Lexicographically compares the remaining contents of two readable
    /// streams using caller-selected heap buffers.
    ///
    /// This method has the same comparison and stream-advance semantics as
    /// [`Self::compare_content`], but allocates two buffers on the heap with
    /// `buffer_size` bytes each. Use it when the default chunk size is too
    /// large for the caller's stack budget or when a smaller comparison window
    /// is desirable.
    ///
    /// # Parameters
    /// - `left`: First stream.
    /// - `right`: Second stream.
    /// - `buffer_size`: Number of bytes in each comparison buffer.
    ///
    /// # Returns
    /// The lexicographic ordering of the remaining bytes.
    ///
    /// # Errors
    /// Returns [`ErrorKind::InvalidInput`] when `buffer_size == 0`. Returns an
    /// allocation error if the comparison buffers cannot be allocated. Returns
    /// the first read error reported by either stream.
    pub fn compare_content_with_buffer_size(
        left: &mut dyn Read,
        right: &mut dyn Read,
        buffer_size: usize,
    ) -> Result<Ordering> {
        if buffer_size == 0 {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                "compare buffer size must be greater than zero",
            ));
        }
        let mut left_buffer = create_vec(buffer_size, 0)?;
        let mut right_buffer = create_vec(buffer_size, 0)?;
        debug_assert_eq!(
            left_buffer.len(),
            right_buffer.len(),
            "compare buffers must have identical lengths",
        );
        debug_assert!(
            !left_buffer.is_empty(),
            "compare buffers must not be empty",
        );
        loop {
            let left_count = left.read_exact_or_eof(&mut left_buffer)?;
            let right_count = right.read_exact_or_eof(&mut right_buffer)?;
            let n = left_count.min(right_count);
            for index in 0..n {
                match left_buffer[index].cmp(&right_buffer[index]) {
                    Ordering::Equal => {}
                    ordering => return Ok(ordering),
                }
            }
            match left_count.cmp(&right_count) {
                Ordering::Equal if left_count == 0 => {
                    return Ok(Ordering::Equal);
                }
                Ordering::Equal => {}
                ordering => return Ok(ordering),
            }
        }
    }
}

/// Copies at most `max_bytes` bytes using trait-object I/O endpoints.
///
/// # Parameters
/// - `reader`: Source reader.
/// - `writer`: Destination writer.
/// - `max_bytes`: Maximum number of bytes to copy.
/// - `buffer_size`: Number of bytes in the copy buffer.
///
/// # Returns
/// The number of bytes copied.
///
/// # Errors
/// Returns [`ErrorKind::InvalidInput`] when `buffer_size == 0`. Returns an
/// allocation error if the copy buffer cannot be allocated. Returns the first
/// non-interrupted read error or write error reported by the underlying
/// streams. Interrupted reads are retried.
fn copy_at_most_impl(
    reader: &mut dyn Read,
    writer: &mut dyn Write,
    max_bytes: u64,
    buffer_size: usize,
) -> Result<u64> {
    if buffer_size == 0 {
        return Err(Error::new(
            ErrorKind::InvalidInput,
            "copy buffer size must be greater than zero",
        ));
    }
    let mut buffer = create_vec(buffer_size, 0)?;
    let mut remaining = max_bytes;
    let mut copied = 0;
    while remaining > 0 {
        let requested = remaining.min(buffer_size as u64) as usize;
        match reader.read(&mut buffer[..requested]) {
            Ok(0) => break,
            Ok(count) => {
                writer.write_all(&buffer[..count])?;
                let count = count as u64;
                remaining -= count;
                copied += count;
            }
            Err(error) => {
                if error.kind() == ErrorKind::Interrupted {
                    continue;
                }
                return Err(error);
            }
        }
    }
    Ok(copied)
}

#[cfg(coverage)]
thread_local! {
    static COVERAGE_FAIL_NEXT_ADD_ITEM_COUNT: Cell<bool> = const { Cell::new(false) };
}

/// Makes the next [`add_item_count`] call fail.
///
/// Coverage-only helper for exercising overflow propagation inside copy loops.
#[cfg(coverage)]
#[doc(hidden)]
pub fn coverage_fail_next_add_item_count() {
    COVERAGE_FAIL_NEXT_ADD_ITEM_COUNT.with(|state| state.set(true));
}

/// Clears coverage-only [`add_item_count`] hooks between tests.
#[cfg(coverage)]
#[doc(hidden)]
pub fn coverage_reset_add_item_count_hooks() {
    COVERAGE_FAIL_NEXT_ADD_ITEM_COUNT.with(|state| state.set(false));
}

/// Adds a copied item count to an accumulated total.
///
/// # Parameters
/// - `copied`: Existing copied item count.
/// - `count`: Newly copied item count.
///
/// # Returns
/// The updated copied item count.
///
/// # Errors
/// Returns [`ErrorKind::InvalidData`] if the count overflows `u64`.
#[inline(always)]
fn add_item_count(copied: u64, count: usize) -> Result<u64> {
    #[cfg(coverage)]
    if COVERAGE_FAIL_NEXT_ADD_ITEM_COUNT.with(|state| {
        let fail = state.get();
        if fail {
            state.set(false);
        }
        fail
    }) {
        return Err(Error::new(
            ErrorKind::InvalidData,
            "copied item count overflows u64",
        ));
    }
    copied.checked_add(count as u64).ok_or_else(|| {
        Error::new(ErrorKind::InvalidData, "copied item count overflows u64")
    })
}

/// Exercises the copied-item overflow branch in coverage builds.
#[cfg(coverage)]
#[doc(hidden)]
pub fn coverage_add_item_count_overflow() -> Result<u64> {
    add_item_count(u64::MAX, 1)
}