Skip to main content

qubit_fs/read/
file_reader.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//! Concrete synchronous file reader handle.
9
10use std::fmt::Debug;
11use std::fmt::Formatter;
12use std::fmt::Result as FmtResult;
13use std::io::Error as IoError;
14use std::io::ErrorKind as IoErrorKind;
15use std::io::Result as IoResult;
16
17use qubit_io::ByteInput;
18use qubit_io::Input;
19
20use crate::error::FsEffectState;
21use crate::error::FsError;
22use crate::error::FsErrorKind;
23use crate::metadata::OpenedFileInfo;
24
25/// Type-erased byte input explicitly associated with an opened file.
26///
27/// Aggregate reads retry ordinary interruptions and typed interruptions whose
28/// effect is absent or [`FsEffectState::Unchanged`]. A typed interruption with
29/// another effect, or with a conflicting error kind, is returned with outer
30/// [`IoErrorKind::Other`]; its original [`FsError`] remains the direct error
31/// payload. A failed aggregate read may already have written bytes into its
32/// destination buffer; those bytes are not rolled back.
33///
34/// # Examples
35///
36/// The example runs against an isolated in-memory fixture. Applications obtain
37/// their configured facade from a provider or registry integration.
38///
39/// ```rust
40/// # mod support { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/common/rustdoc_support.rs")); }
41/// # let filesystem = support::rustdoc_provider::filesystem();
42/// use qubit_fs::Path;
43/// use qubit_fs::read::ReadOptions;
44/// use qubit_io::Input;
45///
46/// let mut reader = filesystem.open_reader(&Path::parse("/report")?, ReadOptions::default())?;
47/// let mut prefix = [0; 3];
48/// assert_eq!(3, reader.read_fully(&mut prefix)?);
49/// assert_eq!(*b"rep", prefix);
50/// # Ok::<(), Box<dyn std::error::Error>>(())
51/// ```
52pub struct FileReader {
53    /// Provider byte input.
54    inner: Box<dyn ByteInput + Send>,
55    /// Stable identity and metadata captured at open time.
56    info: OpenedFileInfo,
57}
58
59impl FileReader {
60    /// Wraps a provider byte input with its fixed file identity.
61    ///
62    /// Calling this constructor is the explicit provider adaptation step. An
63    /// arbitrary [`Input`] does not automatically become a file reader.
64    ///
65    /// # Parameters
66    /// - `info`: File identity and optional open-time metadata snapshot.
67    /// - `inner`: Already-open byte input.
68    ///
69    /// # Returns
70    /// A concrete file reader handle.
71    #[inline]
72    #[must_use]
73    pub(crate) fn new(info: OpenedFileInfo, inner: Box<dyn ByteInput + Send>) -> Self {
74        Self { inner, info }
75    }
76
77    /// Returns the fixed identity and open-time metadata snapshot.
78    ///
79    /// # Returns
80    /// Information captured when the reader was opened.
81    #[inline]
82    #[must_use]
83    pub fn info(&self) -> &OpenedFileInfo {
84        &self.info
85    }
86}
87
88impl Input for FileReader {
89    /// Byte value yielded by this synchronous reader.
90    type Item = u8;
91
92    /// Reports whether the wrapped byte input can satisfy reads from its
93    /// buffer.
94    #[inline]
95    fn is_buffered(&self) -> bool {
96        self.inner.is_buffered()
97    }
98
99    /// Reads the requested byte range under the caller's `Input` safety
100    /// contract.
101    ///
102    /// # Parameters
103    /// - `output`: Caller-owned destination buffer.
104    /// - `index`: Start index of the requested output range.
105    /// - `count`: Number of bytes requested from that range.
106    ///
107    /// # Safety
108    /// `index..index + count` must be a valid range within `output`, and the
109    /// addition must not overflow.
110    #[inline]
111    unsafe fn read_unchecked(&mut self, output: &mut [u8], index: usize, count: usize) -> IoResult<usize> {
112        // SAFETY: The caller guarantees the same range contract required by
113        // the wrapped input.
114        unsafe { self.inner.read_unchecked(output, index, count) }.map_err(|error| {
115            if error.kind() != IoErrorKind::Interrupted {
116                return error;
117            }
118            let unsafe_typed = error
119                .get_ref()
120                .and_then(|source| source.downcast_ref::<FsError>())
121                .is_some_and(|typed| {
122                    typed.kind() != FsErrorKind::Interrupted
123                        || !matches!(typed.effect_state(), None | Some(FsEffectState::Unchanged))
124                });
125            if unsafe_typed {
126                let source = error.into_inner().expect("typed interruption retains its source");
127                IoError::other(source)
128            } else {
129                error
130            }
131        })
132    }
133}
134
135impl Debug for FileReader {
136    /// Formats the reader's stable file information without exposing its input.
137    ///
138    /// # Parameters
139    /// - `formatter`: Destination for the debug representation.
140    #[inline]
141    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
142        formatter
143            .debug_struct("FileReader")
144            .field("info", &self.info)
145            .finish_non_exhaustive()
146    }
147}