qubit_fs/read/read_options.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//! Read operation options.
9
10use crate::error::FsError;
11use crate::error::FsErrorKind;
12use crate::error::FsOperation;
13use crate::metadata::FileSystemCapabilities;
14use crate::metadata::FileSystemCapability;
15use crate::metadata::ResourceVersion;
16use crate::read::ChecksumPolicy;
17
18/// Options controlling a read operation.
19///
20/// # Examples
21///
22/// ```
23/// use qubit_fs::read::ReadOptions;
24///
25/// let options = ReadOptions::default().with_length(Some(1_024));
26/// assert_eq!(Some(1_024), options.length());
27/// assert!(options.validate().is_ok());
28/// ```
29#[non_exhaustive]
30#[derive(Clone, Debug, Default, Eq, PartialEq)]
31pub struct ReadOptions {
32 /// Optional byte offset.
33 offset: Option<u64>,
34 /// Optional byte length.
35 length: Option<u64>,
36 /// Optional required ETag or provider version.
37 if_match: Option<ResourceVersion>,
38 /// Optional ETag or provider version that must not match.
39 if_none_match: Option<ResourceVersion>,
40 /// Checksum validation policy.
41 checksum: ChecksumPolicy,
42}
43
44impl ReadOptions {
45 /// Returns the optional byte offset.
46 ///
47 /// # Returns
48 /// The offset from which reading begins, or `None` to start at the
49 /// resource's beginning.
50 #[inline]
51 #[must_use]
52 pub const fn offset(&self) -> Option<u64> {
53 self.offset
54 }
55
56 /// Returns the optional byte length.
57 ///
58 /// # Returns
59 /// The maximum number of bytes to read, or `None` to read through EOF.
60 #[inline]
61 #[must_use]
62 pub const fn length(&self) -> Option<u64> {
63 self.length
64 }
65
66 /// Returns the optional positive version precondition.
67 ///
68 /// # Returns
69 /// The required resource version, if one was configured.
70 #[inline]
71 #[must_use]
72 pub const fn if_match(&self) -> Option<&ResourceVersion> {
73 self.if_match.as_ref()
74 }
75
76 /// Returns the optional negative version precondition.
77 ///
78 /// # Returns
79 /// The resource version that must not match, if one was configured.
80 #[inline]
81 #[must_use]
82 pub const fn if_none_match(&self) -> Option<&ResourceVersion> {
83 self.if_none_match.as_ref()
84 }
85
86 /// Returns the checksum policy.
87 ///
88 /// # Returns
89 /// The checksum validation policy requested for the read.
90 #[inline]
91 #[must_use]
92 pub const fn checksum(&self) -> ChecksumPolicy {
93 self.checksum
94 }
95
96 /// Returns a copy with the byte offset replaced.
97 ///
98 /// # Parameters
99 /// - `offset`: The byte offset to use, or `None` to read from the
100 /// beginning.
101 ///
102 /// # Returns
103 /// A copy of these options with the requested offset.
104 #[inline]
105 #[must_use]
106 pub const fn with_offset(mut self, offset: Option<u64>) -> Self {
107 self.offset = offset;
108 self
109 }
110
111 /// Returns a copy with the byte length replaced.
112 ///
113 /// # Parameters
114 /// - `length`: The maximum byte length, or `None` to read through EOF.
115 ///
116 /// # Returns
117 /// A copy of these options with the requested length.
118 #[inline]
119 #[must_use]
120 pub const fn with_length(mut self, length: Option<u64>) -> Self {
121 self.length = length;
122 self
123 }
124
125 /// Returns a copy with the positive version precondition replaced.
126 ///
127 /// # Parameters
128 /// - `if_match`: The required resource version, or `None` to clear the
129 /// precondition.
130 ///
131 /// # Returns
132 /// A copy of these options with the requested precondition.
133 #[inline]
134 #[must_use]
135 pub fn with_if_match(mut self, if_match: Option<ResourceVersion>) -> Self {
136 self.if_match = if_match;
137 self
138 }
139
140 /// Returns a copy with the negative version precondition replaced.
141 ///
142 /// # Parameters
143 /// - `if_none_match`: The version that must not match, or `None` to clear
144 /// the precondition.
145 ///
146 /// # Returns
147 /// A copy of these options with the requested precondition.
148 #[inline]
149 #[must_use]
150 pub fn with_if_none_match(mut self, if_none_match: Option<ResourceVersion>) -> Self {
151 self.if_none_match = if_none_match;
152 self
153 }
154
155 /// Returns a copy with the checksum policy replaced.
156 ///
157 /// # Parameters
158 /// - `checksum`: The checksum validation policy to use.
159 ///
160 /// # Returns
161 /// A copy of these options with the requested checksum policy.
162 #[inline]
163 #[must_use]
164 pub const fn with_checksum(mut self, checksum: ChecksumPolicy) -> Self {
165 self.checksum = checksum;
166 self
167 }
168
169 /// Validates provider-independent read options without performing I/O.
170 ///
171 /// A zero-length window is valid, including at the largest offset. Resource
172 /// existence and access permissions are still checked when opening it.
173 /// Offsets at or beyond EOF produce an empty window; lengths extending past
174 /// EOF are truncated. These windows do not imply a resource snapshot.
175 ///
176 /// # Errors
177 /// Returns `InvalidOptions` for mutually exclusive conditions or an
178 /// explicit range whose exclusive end cannot be represented as `u64`.
179 pub fn validate(&self) -> Result<(), FsError> {
180 if self.if_match.is_some() && self.if_none_match.is_some() {
181 return Err(FsError::new(
182 FsErrorKind::InvalidOptions,
183 FsOperation::OpenReader,
184 "if_match and if_none_match cannot both be specified",
185 ));
186 }
187 if let Some(length) = self.length
188 && self.offset.unwrap_or(0).checked_add(length).is_none()
189 {
190 return Err(FsError::new(
191 FsErrorKind::InvalidOptions,
192 FsOperation::OpenReader,
193 "read range exceeds the representable byte offset",
194 ));
195 }
196 Ok(())
197 }
198
199 /// Validates required read semantics against configured capabilities.
200 ///
201 /// Providers should call this method before opening a reader or producing
202 /// any observable side effect.
203 ///
204 /// # Parameters
205 /// - `capabilities`: The capabilities advertised by the target filesystem.
206 ///
207 /// # Returns
208 /// `Ok(())` when the requested semantics are supported.
209 ///
210 /// # Errors
211 /// Returns [`FsErrorKind::InvalidOptions`] for invalid version conditions
212 /// or an unrepresentable explicit range. Returns
213 /// [`FsErrorKind::RequirementNotMet`] with the exact missing capability
214 /// for range, conditional, or required-checksum reads.
215 pub fn validate_against(&self, capabilities: FileSystemCapabilities) -> Result<(), FsError> {
216 self.validate()?;
217 if (self.offset.is_some() || self.length.is_some()) && !capabilities.supports(FileSystemCapability::RangeRead) {
218 return Err(missing_requirement(
219 FileSystemCapability::RangeRead,
220 "byte-range reads are required but not supported",
221 ));
222 }
223 if (self.if_match.is_some() || self.if_none_match.is_some())
224 && !capabilities.supports(FileSystemCapability::ConditionalRead)
225 {
226 return Err(missing_requirement(
227 FileSystemCapability::ConditionalRead,
228 "conditional reads are required but not supported",
229 ));
230 }
231 if self.checksum == ChecksumPolicy::Required && !capabilities.supports(FileSystemCapability::ChecksumValidation)
232 {
233 return Err(missing_requirement(
234 FileSystemCapability::ChecksumValidation,
235 "checksum validation is required but not supported",
236 ));
237 }
238 Ok(())
239 }
240}
241
242/// Builds a typed error for a read requirement the filesystem cannot meet.
243///
244/// # Parameters
245/// - `capability`: The capability required by the read options.
246/// - `message`: A diagnostic describing the unsupported read behavior.
247///
248/// # Returns
249/// An error identifying the missing capability and the open-reader operation.
250fn missing_requirement(capability: FileSystemCapability, message: &str) -> FsError {
251 FsError::new(FsErrorKind::RequirementNotMet, FsOperation::OpenReader, message).with_required_capability(capability)
252}