Skip to main content

file_system/operations/
base.rs

1//! One object-safe polling contract for device I/O.
2use super::polling::Operation;
3use crate::{Context, ControlCommandIdentifier, IoErrorKind, Position, Result, Size};
4use core::task::{Context as TaskContext, Poll, Waker};
5use shared::AnyByLayout;
6
7/// Complete an intrinsically synchronous backend operation with the polling contract.
8/// The closure runs exactly once; busy errors remain errors.
9pub fn ready<T>(operation: impl FnOnce() -> Result<T>) -> Poll<Result<T>> {
10    Poll::Ready(operation())
11}
12
13fn immediate<T>(result: Poll<Result<T>>) -> Result<T> {
14    match result {
15        Poll::Ready(result) => result,
16        // A synchronous adapter probes once: pending means "not ready now".
17        Poll::Pending => Err(IoErrorKind::WouldBlock),
18    }
19}
20
21/// Device operations return `Poll` directly, including `read`. `Pending` requires
22/// race-free waker registration and must not hide consumed bytes. Never retain
23/// caller buffers or task-context pointers. Device-owned state belongs in the
24/// opening context (or the device for context-free implementations).
25///
26/// `_sync` methods are explicit single-attempt adapters for synchronous C/OS
27/// boundaries. They cancel registrations and return busy on Pending, never retry.
28pub trait BaseOperations: Send + Sync {
29    fn read(
30        &self,
31        context: &mut Context,
32        cx: &mut TaskContext<'_>,
33        buffer: &mut [u8],
34        absolute_position: Size,
35    ) -> Poll<Result<usize>>;
36    fn write(
37        &self,
38        context: &mut Context,
39        cx: &mut TaskContext<'_>,
40        buffer: &[u8],
41        absolute_position: Size,
42    ) -> Poll<Result<usize>>;
43    fn flush(&self, _context: &mut Context, _cx: &mut TaskContext<'_>) -> Poll<Result<()>> {
44        Poll::Ready(Ok(()))
45    }
46    fn control(
47        &self,
48        _context: &mut Context,
49        _cx: &mut TaskContext<'_>,
50        _command: ControlCommandIdentifier,
51        _input: &AnyByLayout,
52        _output: &mut AnyByLayout,
53    ) -> Poll<Result<()>> {
54        Poll::Ready(Err(IoErrorKind::Unsupported))
55    }
56    fn read_until(
57        &self,
58        context: &mut Context,
59        cx: &mut TaskContext<'_>,
60        buffer: &mut [u8],
61        absolute_position: Size,
62        delimiter: &[u8],
63    ) -> Poll<Result<usize>> {
64        if delimiter.is_empty() {
65            return Poll::Ready(Err(IoErrorKind::InvalidArgument));
66        }
67        let mut total = 0;
68        while total < buffer.len() {
69            match self.read(
70                context,
71                cx,
72                &mut buffer[total..total + 1],
73                absolute_position + total as Size,
74            ) {
75                Poll::Ready(Ok(0)) => break,
76                Poll::Ready(Ok(n)) => total += n,
77                Poll::Pending if total == 0 => return Poll::Pending,
78                Poll::Ready(Err(error)) if total == 0 => return Poll::Ready(Err(error)),
79                _ => break,
80            }
81            if buffer[..total].ends_with(delimiter) {
82                break;
83            }
84        }
85        Poll::Ready(Ok(total))
86    }
87    fn write_pattern(
88        &self,
89        context: &mut Context,
90        cx: &mut TaskContext<'_>,
91        pattern: &[u8],
92        count: usize,
93        absolute_position: Size,
94    ) -> Poll<Result<usize>> {
95        let mut total = 0;
96        for buffer in core::iter::repeat_n(pattern, count) {
97            if buffer.is_empty() {
98                continue;
99            }
100            match self.write(context, cx, buffer, absolute_position + total as Size) {
101                Poll::Ready(Ok(n)) => {
102                    total += n;
103                    if n < buffer.len() {
104                        break;
105                    }
106                }
107                Poll::Pending if total == 0 => return Poll::Pending,
108                Poll::Ready(Err(error)) if total == 0 => return Poll::Ready(Err(error)),
109                _ => break,
110            }
111        }
112        Poll::Ready(Ok(total))
113    }
114    fn write_vectored(
115        &self,
116        context: &mut Context,
117        cx: &mut TaskContext<'_>,
118        buffers: &[&[u8]],
119        absolute_position: Size,
120    ) -> Poll<Result<usize>> {
121        let mut total = 0;
122        for buffer in buffers.iter().copied() {
123            if buffer.is_empty() {
124                continue;
125            }
126            match self.write(context, cx, buffer, absolute_position + total as Size) {
127                Poll::Ready(Ok(n)) => {
128                    total += n;
129                    if n < buffer.len() {
130                        break;
131                    }
132                }
133                Poll::Pending if total == 0 => return Poll::Pending,
134                Poll::Ready(Err(error)) if total == 0 => return Poll::Ready(Err(error)),
135                _ => break,
136            }
137        }
138        Poll::Ready(Ok(total))
139    }
140    fn read_sync(
141        &self,
142        context: &mut Context,
143        buffer: &mut [u8],
144        absolute_position: Size,
145    ) -> Result<usize> {
146        let mut cx = TaskContext::from_waker(Waker::noop());
147        let result = self.read(context, &mut cx, buffer, absolute_position);
148        self.cancel_operation(context, Operation::Read);
149        immediate(result)
150    }
151    fn write_sync(
152        &self,
153        context: &mut Context,
154        buffer: &[u8],
155        absolute_position: Size,
156    ) -> Result<usize> {
157        let mut cx = TaskContext::from_waker(Waker::noop());
158        let result = self.write(context, &mut cx, buffer, absolute_position);
159        self.cancel_operation(context, Operation::Write);
160        immediate(result)
161    }
162    fn flush_sync(&self, context: &mut Context) -> Result<()> {
163        let mut cx = TaskContext::from_waker(Waker::noop());
164        let result = self.flush(context, &mut cx);
165        self.cancel_operation(context, Operation::Flush);
166        immediate(result)
167    }
168    fn control_sync(
169        &self,
170        context: &mut Context,
171        command: ControlCommandIdentifier,
172        input: &AnyByLayout,
173        output: &mut AnyByLayout,
174    ) -> Result<()> {
175        let mut cx = TaskContext::from_waker(Waker::noop());
176        let result = self.control(context, &mut cx, command, input, output);
177        self.cancel_operation(context, Operation::Control);
178        immediate(result)
179    }
180    fn read_until_sync(
181        &self,
182        context: &mut Context,
183        buffer: &mut [u8],
184        absolute_position: Size,
185        delimiter: &[u8],
186    ) -> Result<usize> {
187        let mut cx = TaskContext::from_waker(Waker::noop());
188        let result = self.read_until(context, &mut cx, buffer, absolute_position, delimiter);
189        self.cancel_operation(context, Operation::Read);
190        immediate(result)
191    }
192    fn write_pattern_sync(
193        &self,
194        context: &mut Context,
195        pattern: &[u8],
196        count: usize,
197        absolute_position: Size,
198    ) -> Result<usize> {
199        let mut cx = TaskContext::from_waker(Waker::noop());
200        let result = self.write_pattern(context, &mut cx, pattern, count, absolute_position);
201        self.cancel_operation(context, Operation::Write);
202        immediate(result)
203    }
204    fn write_vectored_sync(
205        &self,
206        context: &mut Context,
207        buffers: &[&[u8]],
208        absolute_position: Size,
209    ) -> Result<usize> {
210        let mut cx = TaskContext::from_waker(Waker::noop());
211        let result = self.write_vectored(context, &mut cx, buffers, absolute_position);
212        self.cancel_operation(context, Operation::Write);
213        immediate(result)
214    }
215    /// Detach this opening's registration after completion, error or cancellation.
216    /// This hook is idempotent and must not consume data or change the cursor.
217    /// Wake and drop retired wakers outside device locks.
218    fn cancel_operation(&self, _context: &mut Context, _operation: Operation) {}
219    fn open(&self, _context: &mut Context) -> Result<()> {
220        Ok(())
221    }
222    fn close(&self, _context: &mut Context) -> Result<()> {
223        Ok(())
224    }
225    fn set_position(
226        &self,
227        _context: &mut Context,
228        current: Size,
229        position: &Position,
230    ) -> Result<Size> {
231        match position {
232            Position::Start(value) => Ok(*value),
233            Position::Current(offset) => Ok(current.wrapping_add(*offset as Size)),
234            Position::End(_) => Err(IoErrorKind::Unsupported),
235        }
236    }
237    fn clone_context(&self, context: &Context) -> Result<Context>;
238}
239
240/// Device operations return `Poll` directly, including `read`. `Pending` requires
241/// race-free waker registration and must not hide consumed bytes. Never retain
242/// caller buffers or task-context pointers. Device-owned state belongs in the
243/// opening context (or the device for context-free implementations).
244///
245/// `_sync` methods are explicit single-attempt adapters for synchronous C/OS
246/// boundaries. They cancel registrations and return busy on Pending, never retry.
247pub trait DirectBaseOperations: Send + Sync {
248    fn read(
249        &self,
250        cx: &mut TaskContext<'_>,
251        buffer: &mut [u8],
252        absolute_position: Size,
253    ) -> Poll<Result<usize>>;
254    fn write(
255        &self,
256        cx: &mut TaskContext<'_>,
257        buffer: &[u8],
258        absolute_position: Size,
259    ) -> Poll<Result<usize>>;
260    fn flush(&self, _cx: &mut TaskContext<'_>) -> Poll<Result<()>> {
261        Poll::Ready(Ok(()))
262    }
263    fn control(
264        &self,
265        _cx: &mut TaskContext<'_>,
266        _command: ControlCommandIdentifier,
267        _input: &AnyByLayout,
268        _output: &mut AnyByLayout,
269    ) -> Poll<Result<()>> {
270        Poll::Ready(Err(IoErrorKind::Unsupported))
271    }
272    fn read_until(
273        &self,
274        cx: &mut TaskContext<'_>,
275        buffer: &mut [u8],
276        absolute_position: Size,
277        delimiter: &[u8],
278    ) -> Poll<Result<usize>> {
279        if delimiter.is_empty() {
280            return Poll::Ready(Err(IoErrorKind::InvalidArgument));
281        }
282        let mut total = 0;
283        while total < buffer.len() {
284            match self.read(
285                cx,
286                &mut buffer[total..total + 1],
287                absolute_position + total as Size,
288            ) {
289                Poll::Ready(Ok(0)) => break,
290                Poll::Ready(Ok(n)) => total += n,
291                Poll::Pending if total == 0 => return Poll::Pending,
292                Poll::Ready(Err(error)) if total == 0 => return Poll::Ready(Err(error)),
293                _ => break,
294            }
295            if buffer[..total].ends_with(delimiter) {
296                break;
297            }
298        }
299        Poll::Ready(Ok(total))
300    }
301    fn write_pattern(
302        &self,
303        cx: &mut TaskContext<'_>,
304        pattern: &[u8],
305        count: usize,
306        absolute_position: Size,
307    ) -> Poll<Result<usize>> {
308        let mut total = 0;
309        for buffer in core::iter::repeat_n(pattern, count) {
310            if buffer.is_empty() {
311                continue;
312            }
313            match self.write(cx, buffer, absolute_position + total as Size) {
314                Poll::Ready(Ok(n)) => {
315                    total += n;
316                    if n < buffer.len() {
317                        break;
318                    }
319                }
320                Poll::Pending if total == 0 => return Poll::Pending,
321                Poll::Ready(Err(error)) if total == 0 => return Poll::Ready(Err(error)),
322                _ => break,
323            }
324        }
325        Poll::Ready(Ok(total))
326    }
327    fn write_vectored(
328        &self,
329        cx: &mut TaskContext<'_>,
330        buffers: &[&[u8]],
331        absolute_position: Size,
332    ) -> Poll<Result<usize>> {
333        let mut total = 0;
334        for buffer in buffers.iter().copied() {
335            if buffer.is_empty() {
336                continue;
337            }
338            match self.write(cx, buffer, absolute_position + total as Size) {
339                Poll::Ready(Ok(n)) => {
340                    total += n;
341                    if n < buffer.len() {
342                        break;
343                    }
344                }
345                Poll::Pending if total == 0 => return Poll::Pending,
346                Poll::Ready(Err(error)) if total == 0 => return Poll::Ready(Err(error)),
347                _ => break,
348            }
349        }
350        Poll::Ready(Ok(total))
351    }
352    fn read_sync(&self, buffer: &mut [u8], absolute_position: Size) -> Result<usize> {
353        let mut cx = TaskContext::from_waker(Waker::noop());
354        let result = self.read(&mut cx, buffer, absolute_position);
355        self.cancel_operation(Operation::Read);
356        immediate(result)
357    }
358    fn write_sync(&self, buffer: &[u8], absolute_position: Size) -> Result<usize> {
359        let mut cx = TaskContext::from_waker(Waker::noop());
360        let result = self.write(&mut cx, buffer, absolute_position);
361        self.cancel_operation(Operation::Write);
362        immediate(result)
363    }
364    fn flush_sync(&self) -> Result<()> {
365        let mut cx = TaskContext::from_waker(Waker::noop());
366        let result = self.flush(&mut cx);
367        self.cancel_operation(Operation::Flush);
368        immediate(result)
369    }
370    fn control_sync(
371        &self,
372        command: ControlCommandIdentifier,
373        input: &AnyByLayout,
374        output: &mut AnyByLayout,
375    ) -> Result<()> {
376        let mut cx = TaskContext::from_waker(Waker::noop());
377        let result = self.control(&mut cx, command, input, output);
378        self.cancel_operation(Operation::Control);
379        immediate(result)
380    }
381    fn read_until_sync(
382        &self,
383        buffer: &mut [u8],
384        absolute_position: Size,
385        delimiter: &[u8],
386    ) -> Result<usize> {
387        let mut cx = TaskContext::from_waker(Waker::noop());
388        let result = self.read_until(&mut cx, buffer, absolute_position, delimiter);
389        self.cancel_operation(Operation::Read);
390        immediate(result)
391    }
392    fn write_pattern_sync(
393        &self,
394        pattern: &[u8],
395        count: usize,
396        absolute_position: Size,
397    ) -> Result<usize> {
398        let mut cx = TaskContext::from_waker(Waker::noop());
399        let result = self.write_pattern(&mut cx, pattern, count, absolute_position);
400        self.cancel_operation(Operation::Write);
401        immediate(result)
402    }
403    fn write_vectored_sync(&self, buffers: &[&[u8]], absolute_position: Size) -> Result<usize> {
404        let mut cx = TaskContext::from_waker(Waker::noop());
405        let result = self.write_vectored(&mut cx, buffers, absolute_position);
406        self.cancel_operation(Operation::Write);
407        immediate(result)
408    }
409    /// Detach the current operation's registration; see `BaseOperations`.
410    fn cancel_operation(&self, _operation: Operation) {}
411    fn open(&self) -> Result<()> {
412        Ok(())
413    }
414    fn close(&self) -> Result<()> {
415        Ok(())
416    }
417    fn set_position(&self, current: Size, position: &Position) -> Result<Size> {
418        match position {
419            Position::Start(value) => Ok(*value),
420            Position::Current(offset) => Ok(current.wrapping_add(*offset as Size)),
421            Position::End(_) => Err(IoErrorKind::Unsupported),
422        }
423    }
424}
425
426impl<T: DirectBaseOperations> BaseOperations for T {
427    fn read(
428        &self,
429        _: &mut Context,
430        cx: &mut TaskContext<'_>,
431        buffer: &mut [u8],
432        absolute_position: Size,
433    ) -> Poll<Result<usize>> {
434        DirectBaseOperations::read(self, cx, buffer, absolute_position)
435    }
436    fn write(
437        &self,
438        _: &mut Context,
439        cx: &mut TaskContext<'_>,
440        buffer: &[u8],
441        absolute_position: Size,
442    ) -> Poll<Result<usize>> {
443        DirectBaseOperations::write(self, cx, buffer, absolute_position)
444    }
445    fn flush(&self, _: &mut Context, cx: &mut TaskContext<'_>) -> Poll<Result<()>> {
446        DirectBaseOperations::flush(self, cx)
447    }
448    fn control(
449        &self,
450        _: &mut Context,
451        cx: &mut TaskContext<'_>,
452        command: ControlCommandIdentifier,
453        input: &AnyByLayout,
454        output: &mut AnyByLayout,
455    ) -> Poll<Result<()>> {
456        DirectBaseOperations::control(self, cx, command, input, output)
457    }
458    fn read_until(
459        &self,
460        _: &mut Context,
461        cx: &mut TaskContext<'_>,
462        buffer: &mut [u8],
463        absolute_position: Size,
464        delimiter: &[u8],
465    ) -> Poll<Result<usize>> {
466        DirectBaseOperations::read_until(self, cx, buffer, absolute_position, delimiter)
467    }
468    fn write_pattern(
469        &self,
470        _: &mut Context,
471        cx: &mut TaskContext<'_>,
472        pattern: &[u8],
473        count: usize,
474        absolute_position: Size,
475    ) -> Poll<Result<usize>> {
476        DirectBaseOperations::write_pattern(self, cx, pattern, count, absolute_position)
477    }
478    fn write_vectored(
479        &self,
480        _: &mut Context,
481        cx: &mut TaskContext<'_>,
482        buffers: &[&[u8]],
483        absolute_position: Size,
484    ) -> Poll<Result<usize>> {
485        DirectBaseOperations::write_vectored(self, cx, buffers, absolute_position)
486    }
487    fn open(&self, _: &mut Context) -> Result<()> {
488        DirectBaseOperations::open(self)
489    }
490    fn close(&self, _: &mut Context) -> Result<()> {
491        DirectBaseOperations::close(self)
492    }
493    fn set_position(&self, _: &mut Context, current: Size, position: &Position) -> Result<Size> {
494        DirectBaseOperations::set_position(self, current, position)
495    }
496    fn clone_context(&self, _: &Context) -> Result<Context> {
497        Ok(Context::new_empty())
498    }
499    fn cancel_operation(&self, _: &mut Context, operation: Operation) {
500        DirectBaseOperations::cancel_operation(self, operation)
501    }
502}
503pub fn open_close_operation<D: DirectBaseOperations, R>(
504    device: &D,
505    operation: impl Fn(&D) -> Result<R>,
506) -> Result<R> {
507    device.open()?;
508    let result = operation(device);
509    device.close()?;
510    result
511}