qubit_fs/read/random_access_reader.rs
1// =============================================================================
2// Copyright (c) 2025 - 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8
9//! Application-facing handle for bounded offset reads.
10use std::fmt::Debug;
11use std::fmt::Formatter;
12use std::fmt::Result as FmtResult;
13
14use crate::error::FsError;
15use crate::error::FsErrorKind;
16use crate::error::FsOperation;
17use crate::error::FsResult;
18use crate::metadata::FileSystemLimit;
19use crate::metadata::OpenedFileInfo;
20use crate::read::RandomAccessReadPolicy;
21use crate::spi::RandomAccessReadSession;
22
23/// A random-access session bound to one opened object and its open-time length.
24///
25/// # Examples
26///
27/// This small example assumes each requested window fits the configured
28/// `max_read_range_bytes`; a larger single `read_at` request returns
29/// `ResourceLimitExceeded`. See the user guide for a fixture-backed helper
30/// that splits a larger sample across bounded reads.
31///
32/// ```rust
33/// use qubit_fs::{FileSystem, FsResult, Path};
34/// use qubit_fs::read::{RandomAccessReader, ReadOptions};
35///
36/// fn sample(filesystem: &FileSystem, path: &Path) -> FsResult<Vec<u8>> {
37/// let mut reader: RandomAccessReader = filesystem.open_random_access_reader(path, ReadOptions::default())?;
38/// let mut bytes = [0; 16];
39/// let mut filled = 0;
40/// while filled < bytes.len() {
41/// match reader.read_at(filled as u64, &mut bytes[filled..])? {
42/// 0 => break, // EOF; a short read is not an error.
43/// count => filled += count,
44/// }
45/// }
46/// Ok(bytes[..filled].to_vec())
47/// }
48/// ```
49///
50/// If `read_at` returns `Err`, the output may already contain partial bytes;
51/// discard the incomplete sample. The open-time length is not a content
52/// snapshot.
53pub struct RandomAccessReader {
54 /// Identity and metadata captured when the object was opened.
55 info: OpenedFileInfo,
56 /// Open-time readable upper bound; this is not a content snapshot.
57 len: u64,
58 /// Maximum size of one request after clipping to `len`.
59 limit: FileSystemLimit,
60 /// Provider identifier added to read errors for context.
61 provider_id: String,
62 /// Session retaining ownership of the already opened object.
63 session: Box<dyn RandomAccessReadSession>,
64}
65impl RandomAccessReader {
66 /// Builds a reader from the validated result of a provider open.
67 ///
68 /// # Parameters
69 /// - `info`: File identity and metadata captured at open time.
70 /// - `len`: Readable upper bound captured at open time.
71 /// - `limit`: Maximum size of each clipped provider request.
72 /// - `provider_id`: Provider identity included in read errors.
73 /// - `session`: Provider session owning the already-open object.
74 ///
75 /// # Returns
76 /// A reader retaining the open object and applying the supplied bounds.
77 pub(crate) fn new(
78 info: OpenedFileInfo,
79 len: u64,
80 limit: FileSystemLimit,
81 provider_id: String,
82 session: Box<dyn RandomAccessReadSession>,
83 ) -> Self {
84 Self {
85 info,
86 len,
87 limit,
88 provider_id,
89 session,
90 }
91 }
92 /// Returns the identity and metadata captured at open time.
93 #[inline]
94 #[must_use]
95 pub fn info(&self) -> &OpenedFileInfo {
96 &self.info
97 }
98 /// Returns the open-time readable upper bound.
99 ///
100 /// This bound does not change if the object grows and does not make the
101 /// object's contents a snapshot.
102 #[inline]
103 #[must_use]
104 pub fn len(&self) -> u64 {
105 self.len
106 }
107 /// Returns whether the open-time length is zero.
108 #[inline]
109 #[must_use]
110 pub fn is_empty(&self) -> bool {
111 self.len == 0
112 }
113 /// Reads into caller storage at an explicit offset. Requests past `len` are
114 /// clipped.
115 ///
116 /// # Parameters
117 /// - `offset`: Byte offset from the beginning of the opened object.
118 /// - `output`: Caller-owned destination buffer.
119 ///
120 /// # Returns
121 /// Returns the number of bytes read. An empty output buffer returns zero
122 /// without observing EOF. A non-overflowing request at or beyond the
123 /// open-time length also returns zero without provider I/O. For a non-empty
124 /// request within that bound, a provider result of zero indicates EOF
125 /// observed by that request. A positive count may be shorter than the
126 /// clipped request.
127 ///
128 /// # Errors
129 /// Returns `InvalidOptions` for an overflowing offset range,
130 /// `ResourceLimitExceeded` when the clipped request exceeds the provider
131 /// limit, a provider read error with path/provider/source context, or
132 /// `ProviderContractViolation` if the provider over-reports bytes. On an
133 /// error, the buffer may contain partial bytes and should be discarded.
134 /// Provider-supplied path and provider context is preserved; missing fields
135 /// are filled from this session. The operation is reported as `Read`.
136 pub fn read_at(&mut self, offset: u64, output: &mut [u8]) -> FsResult<usize> {
137 let count = RandomAccessReadPolicy::validate_read(offset, output.len(), self.len, self.limit)
138 .map_err(|e| e.with_path(self.info.path().clone()).with_provider(&self.provider_id))?;
139 if count == 0 {
140 return Ok(0);
141 }
142 let n = self.session.read_at(offset, &mut output[..count]).map_err(|e| {
143 e.with_missing_context(self.info.path(), None, &self.provider_id)
144 .with_operation(FsOperation::Read)
145 })?;
146 if n > count {
147 return Err(FsError::new(
148 FsErrorKind::ProviderContractViolation,
149 FsOperation::Read,
150 "provider returned more bytes than supplied buffer",
151 )
152 .with_path(self.info.path().clone())
153 .with_provider(&self.provider_id));
154 }
155 Ok(n)
156 }
157}
158impl Debug for RandomAccessReader {
159 /// Formats the open-time information and length without exposing the
160 /// provider session.
161 ///
162 /// # Parameters
163 /// - `f`: Destination for the debug representation.
164 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
165 f.debug_struct("RandomAccessReader")
166 .field("info", &self.info)
167 .field("len", &self.len)
168 .finish_non_exhaustive()
169 }
170}