Skip to main content

qubit_fs/read/
async_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 asynchronous file reader handle.
9
10use std::fmt::Debug;
11use std::fmt::Formatter;
12use std::fmt::Result as FmtResult;
13use std::io::Result as IoResult;
14use std::pin::Pin;
15use std::task::Context;
16use std::task::Poll;
17
18use qubit_io::AsyncByteInput;
19use qubit_io::AsyncInput;
20use qubit_io::BoxAsyncInput;
21
22use crate::metadata::OpenedFileInfo;
23
24/// Type-erased asynchronous byte input associated with an opened file.
25///
26/// Asynchronous providers must report temporary unavailability as
27/// `Poll::Pending` and arrange to wake the registered task. Returning
28/// `WouldBlock` or `Interrupted` violates the async I/O contract. The safe
29/// `qubit-io` read methods expose these errors as `InvalidData` while retaining
30/// the original cause chain. Consequently, `read_all` and `read_prefix`
31/// classify them as `FsErrorKind::Io`; they do not promote a nested `FsError`
32/// to the outer error or promise that a nested error's type/effect is
33/// recoverable through `Error::source`. A directly transported typed business
34/// error keeps its type, kind, provider, and effect state, but a failed read
35/// may already have changed the caller's buffer, so its kind does not prove
36/// that the buffer is unchanged. Synchronous interruption retry rules do not
37/// apply to asynchronous inputs.
38///
39/// # Examples
40///
41/// The application supplies a configured filesystem and a validated path.
42///
43/// ```rust
44/// use qubit_fs::AsyncFileSystem;
45/// use qubit_fs::Path;
46/// use qubit_fs::read::ReadOptions;
47/// use qubit_io::AsyncInput;
48///
49/// async fn read_prefix(
50///     filesystem: &AsyncFileSystem,
51///     path: &Path,
52/// ) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
53///     let mut reader = filesystem.open_reader(path, ReadOptions::default()).await?;
54///     let mut prefix = vec![0; 16];
55///     let count = reader.read_fully_async(&mut prefix).await?;
56///     prefix.truncate(count);
57///     Ok(prefix)
58/// }
59/// ```
60pub struct AsyncFileReader {
61    /// Pinned provider byte input.
62    inner: BoxAsyncInput<dyn AsyncByteInput + Send>,
63    /// Stable identity and metadata captured at open time.
64    info: OpenedFileInfo,
65}
66
67impl AsyncFileReader {
68    /// Wraps an already-open asynchronous provider byte input.
69    ///
70    /// # Parameters
71    /// - `inner`: Runtime-neutral asynchronous byte input.
72    /// - `info`: File identity and optional open-time metadata snapshot.
73    ///
74    /// # Returns
75    /// A pinned, type-erased asynchronous file reader.
76    #[inline]
77    #[must_use]
78    pub(crate) fn new(info: OpenedFileInfo, inner: Box<dyn AsyncByteInput + Send>) -> Self {
79        Self {
80            inner: BoxAsyncInput::new(inner),
81            info,
82        }
83    }
84
85    /// Returns the fixed identity and open-time metadata snapshot.
86    ///
87    /// # Returns
88    /// Information captured when the reader was opened.
89    #[inline]
90    #[must_use]
91    pub fn info(&self) -> &OpenedFileInfo {
92        &self.info
93    }
94}
95
96impl AsyncInput for AsyncFileReader {
97    /// Byte value yielded by this asynchronous reader.
98    type Item = u8;
99
100    /// Reports whether the provider input can satisfy reads from buffered data.
101    ///
102    /// # Returns
103    /// `true` when the wrapped input already buffers bytes for subsequent
104    /// reads.
105    #[inline]
106    fn is_buffered(&self) -> bool {
107        self.inner.is_buffered()
108    }
109
110    /// Polls the provider input using the caller's unsafe range contract.
111    ///
112    /// # Parameters
113    /// - `cx`: Task context used to register readiness when the read is
114    ///   pending.
115    /// - `output`: Destination storage receiving the read bytes.
116    /// - `index`: Start of the destination range.
117    /// - `count`: Maximum number of bytes requested.
118    ///
119    /// # Returns
120    /// The wrapped input's pending state or its ready byte count/error.
121    ///
122    /// # Safety
123    /// `index..index + count` must be a valid range within `output`, and the
124    /// addition must not overflow.
125    #[inline]
126    unsafe fn poll_read_unchecked(
127        self: Pin<&mut Self>,
128        cx: &mut Context<'_>,
129        output: &mut [u8],
130        index: usize,
131        count: usize,
132    ) -> Poll<IoResult<usize>> {
133        let this = self.get_mut();
134        // SAFETY: The caller guarantees the same range contract required by
135        // the wrapped asynchronous input.
136        unsafe {
137            Pin::new(&mut this.inner)
138                .get_pin_mut()
139                .poll_read_unchecked(cx, output, index, count)
140        }
141    }
142}
143
144impl Debug for AsyncFileReader {
145    /// Formats the open-time file information without exposing the input.
146    ///
147    /// # Parameters
148    /// - `formatter`: Destination for the debug representation.
149    #[inline]
150    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
151        formatter
152            .debug_struct("AsyncFileReader")
153            .field("info", &self.info)
154            .finish_non_exhaustive()
155    }
156}