Skip to main content

qubit_io/traits/
input.rs

1// =============================================================================
2//    Copyright (c) 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8
9use std::io::{
10    Error,
11    ErrorKind,
12    Result,
13};
14
15use super::validate_read_count;
16use crate::util::SliceRange;
17
18/// Minimal indexed input interface over items.
19///
20/// `Input` is intentionally smaller and lower-level than [`std::io::Read`]. It
21/// only states that an implementor can read up to `count` items into
22/// `output[index..index + count]`. The caller owns range validation so hot
23/// paths can avoid repeated slicing and bounds checks.
24///
25/// # Coherence note
26///
27/// Every [`std::io::Read`] value automatically implements `Input<Item = u8>`
28/// through the standard I/O integration. Because [`Input::Item`] is an
29/// associated type rather than a trait parameter, a concrete type that
30/// implements [`std::io::Read`] cannot also provide any other direct `Input`
31/// implementation for the same type, including one with a different item type.
32///
33/// Use a wrapper/newtype when a type needs item-oriented input semantics that
34/// differ from its byte-oriented [`std::io::Read`] implementation.
35pub trait Input {
36    /// The item type read from this input.
37    type Item;
38
39    /// Returns whether this input already buffers items internally.
40    ///
41    /// # Returns
42    ///
43    /// `true` when callers should avoid wrapping this input in another generic
44    /// item buffer automatically.
45    #[inline(always)]
46    #[must_use]
47    fn is_buffered(&self) -> bool {
48        false
49    }
50
51    /// Reads items into an indexed output range without checking the range.
52    ///
53    /// # Parameters
54    ///
55    /// * `output` - Destination storage.
56    /// * `index` - Start index inside `output`.
57    /// * `count` - Maximum number of items to read.
58    ///
59    /// # Returns
60    ///
61    /// The number of items written into `output[index..index + count]`. The
62    /// value must be in `0..=count`.
63    ///
64    /// # Errors
65    ///
66    /// Returns the input error reported by the implementation.
67    ///
68    /// # Safety
69    ///
70    /// The caller must guarantee that `index..index + count` is a valid range
71    /// inside `output` and that the addition does not overflow.
72    unsafe fn read_unchecked(
73        &mut self,
74        output: &mut [Self::Item],
75        index: usize,
76        count: usize,
77    ) -> Result<usize>;
78
79    /// Reads items into the full output slice.
80    ///
81    /// # Parameters
82    /// - `output`: Destination storage.
83    ///
84    /// # Returns
85    /// The number of items read into `output`.
86    ///
87    /// # Errors
88    ///
89    /// Returns the input error reported by the implementation. Returns
90    /// [`ErrorKind::InvalidData`] if the implementation reports reading more
91    /// items than requested.
92    #[inline(always)]
93    fn read(&mut self, output: &mut [Self::Item]) -> Result<usize> {
94        // SAFETY: The caller ensured the destination slice is valid.
95        let read = unsafe { self.read_unchecked(output, 0, output.len()) }?;
96        validate_read_count(read, output.len())?;
97        Ok(read)
98    }
99
100    /// Reads items into an indexed output range until it is full or EOF is
101    /// reached.
102    ///
103    /// This method retries interrupted reads and treats EOF as a successful
104    /// partial result.
105    ///
106    /// # Parameters
107    ///
108    /// * `output` - Destination storage.
109    /// * `index` - Start index inside `output`.
110    /// * `count` - Maximum number of items to read.
111    ///
112    /// # Returns
113    ///
114    /// The number of items written into `output[index..index + count]`.
115    ///
116    /// # Errors
117    ///
118    /// Returns the first non-[`ErrorKind::Interrupted`] input error. Returns
119    /// [`ErrorKind::InvalidData`] if the implementation reports more items than
120    /// requested.
121    ///
122    /// # Panics
123    ///
124    /// Panics in debug builds if the requested output range does not fit.
125    ///
126    /// # Safety
127    ///
128    /// The caller must guarantee that `index..index + count` is a valid range
129    /// inside `output` and that the addition does not overflow.
130    unsafe fn read_fully_unchecked(
131        &mut self,
132        output: &mut [Self::Item],
133        index: usize,
134        count: usize,
135    ) -> Result<usize> {
136        debug_assert!(
137            SliceRange::range_fits(output.len(), index, count),
138            "unchecked read-fully range exceeds output buffer"
139        );
140        let mut total = 0;
141        while total < count {
142            let remaining = count - total;
143            // SAFETY: The caller guarantees the original destination range is
144            // valid; `total < count`, so this suffix remains inside it.
145            match unsafe {
146                self.read_unchecked(output, index + total, remaining)
147            } {
148                Ok(0) => break,
149                Ok(read) => {
150                    validate_read_count(read, remaining)?;
151                    total += read;
152                }
153                Err(error) if error.kind() == ErrorKind::Interrupted => {}
154                Err(error) => return Err(error),
155            }
156        }
157        Ok(total)
158    }
159
160    /// Reads items into the full output slice until it is full or EOF is
161    /// reached.
162    ///
163    /// # Parameters
164    /// - `output`: Destination storage to fill as far as possible.
165    ///
166    /// # Returns
167    /// The number of items written into `output`.
168    ///
169    /// # Errors
170    /// Returns the first non-interrupted input error, or
171    /// [`ErrorKind::InvalidData`] if the implementation reports an impossible
172    /// item count.
173    #[inline(always)]
174    fn read_fully(&mut self, output: &mut [Self::Item]) -> Result<usize> {
175        // SAFETY: The full output slice is a valid destination range.
176        unsafe { self.read_fully_unchecked(output, 0, output.len()) }
177    }
178
179    /// Reads items until the full output slice is filled.
180    ///
181    /// # Parameters
182    ///
183    /// * `output` - Destination storage that must be filled completely.
184    ///
185    /// # Returns
186    ///
187    /// `Ok(())` after the destination has been filled completely.
188    ///
189    /// # Errors
190    ///
191    /// Returns [`ErrorKind::UnexpectedEof`] if the input ends before filling
192    /// `output`. Returns the first non-interrupted input error, or
193    /// [`ErrorKind::InvalidData`] if the implementation reports an impossible
194    /// item count.
195    #[inline]
196    fn read_exactly(&mut self, output: &mut [Self::Item]) -> Result<()> {
197        if self.read_fully(output)? == output.len() {
198            Ok(())
199        } else {
200            Err(Error::new(
201                ErrorKind::UnexpectedEof,
202                "failed to fill whole input buffer",
203            ))
204        }
205    }
206}