qubit_io/traits/async_output.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
9use std::io::Result;
10use std::pin::Pin;
11use std::task::Context;
12use std::task::Poll;
13
14use crate::FlushFuture;
15use crate::WriteFullyFuture;
16use crate::WriteFuture;
17use crate::traits::normalize_async_error;
18use crate::traits::validate_write_count;
19
20/// Minimal runtime-independent asynchronous output interface over items.
21///
22/// `AsyncOutput` expresses readiness through [`Poll`] and does not depend on a
23/// particular executor. File publication operations such as commit and abort
24/// intentionally do not belong to this byte-transfer abstraction.
25///
26/// # Examples
27///
28/// Implement the trait for an in-memory output and inspect its buffering
29/// behavior through the public API:
30///
31/// ```
32/// use std::io::Result;
33/// use std::pin::Pin;
34/// use std::task::Context;
35/// use std::task::Poll;
36/// use std::task::Waker;
37///
38/// use qubit_io::AsyncOutput;
39///
40/// #[derive(Default)]
41/// struct VecOutput {
42/// items: Vec<u8>,
43/// }
44///
45/// impl AsyncOutput for VecOutput {
46/// type Item = u8;
47///
48/// unsafe fn poll_write_unchecked(
49/// self: Pin<&mut Self>,
50/// _cx: &mut Context<'_>,
51/// input: &[Self::Item],
52/// index: usize,
53/// count: usize,
54/// ) -> Poll<Result<usize>> {
55/// let this = self.get_mut();
56/// this.items.extend_from_slice(&input[index..index + count]);
57/// Poll::Ready(Ok(count))
58/// }
59///
60/// fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> {
61/// Poll::Ready(Ok(()))
62/// }
63/// }
64///
65/// let mut output = VecOutput::default();
66/// assert!(!output.is_buffered());
67/// let mut cx = Context::from_waker(Waker::noop());
68/// assert!(matches!(Pin::new(&mut output).poll_write(&mut cx, b"data"),
69/// Poll::Ready(Ok(4))));
70/// assert!(matches!(Pin::new(&mut output).poll_flush(&mut cx),
71/// Poll::Ready(Ok(()))));
72/// assert_eq!(b"data", output.items.as_slice());
73/// ```
74pub trait AsyncOutput {
75 /// The item type written to this output.
76 type Item;
77
78 /// Returns whether this output already buffers items internally.
79 ///
80 /// # Returns
81 ///
82 /// `true` when callers should avoid automatically adding another generic
83 /// item buffer.
84 #[inline(always)]
85 #[must_use]
86 fn is_buffered(&self) -> bool {
87 false
88 }
89
90 /// Polls an indexed write without checking the source range.
91 ///
92 /// # Parameters
93 ///
94 /// * `cx` - Task context used to register interest when output is pending.
95 /// * `input` - Source storage.
96 /// * `index` - Start index inside `input`.
97 /// * `count` - Maximum number of items to write.
98 ///
99 /// # Returns
100 ///
101 /// [`Poll::Pending`] when no result is currently available, or a ready I/O
102 /// result containing a count in `0..=count`. A zero `count` must
103 /// immediately return `Poll::Ready(Ok(0))`.
104 ///
105 /// Before returning [`Poll::Pending`], the implementation must arrange for
106 /// `cx`'s waker to be notified when progress may be possible. Neither
107 /// `Poll::Pending` nor `Poll::Ready(Err(_))` may accept items.
108 /// `WouldBlock` and `Interrupted` must not cross this asynchronous
109 /// boundary; implementations must respectively register readiness or retry
110 /// internally.
111 ///
112 /// # Errors
113 ///
114 /// Returns the output error reported by the implementation.
115 ///
116 /// # Safety
117 ///
118 /// The caller must guarantee that `index..index + count` is a valid range
119 /// inside `input` and that the addition does not overflow.
120 unsafe fn poll_write_unchecked(
121 self: Pin<&mut Self>,
122 cx: &mut Context<'_>,
123 input: &[Self::Item],
124 index: usize,
125 count: usize,
126 ) -> Poll<Result<usize>>;
127
128 /// Polls one write from the full source slice.
129 ///
130 /// # Parameters
131 ///
132 /// * `cx` - Task context used to register interest when output is pending.
133 /// * `input` - Source storage.
134 ///
135 /// # Returns
136 ///
137 /// [`Poll::Pending`] or a ready result containing the accepted item count.
138 ///
139 /// # Errors
140 ///
141 /// The default implementation converts `WouldBlock` and `Interrupted`
142 /// errors from the underlying operation to
143 /// [`std::io::ErrorKind::InvalidData`], retaining the original error in
144 /// the cause chain. Other errors are returned unchanged. It also
145 /// returns `InvalidData` if the implementation reports more items than
146 /// requested.
147 #[inline]
148 fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, input: &[Self::Item]) -> Poll<Result<usize>> {
149 if input.is_empty() {
150 return Poll::Ready(Ok(0));
151 }
152 let requested = input.len();
153 // SAFETY: The full input slice is a valid source range.
154 match unsafe { self.poll_write_unchecked(cx, input, 0, requested) } {
155 Poll::Ready(Ok(written)) => Poll::Ready(validate_write_count(written, requested).map(|()| written)),
156 Poll::Ready(Err(error)) => Poll::Ready(Err(normalize_async_error(error))),
157 Poll::Pending => Poll::Pending,
158 }
159 }
160
161 /// Polls the flushing of internally buffered items.
162 ///
163 /// # Parameters
164 ///
165 /// * `cx` - Task context used to register interest when flushing is
166 /// pending.
167 ///
168 /// # Returns
169 ///
170 /// [`Poll::Pending`] or the ready flush result.
171 ///
172 /// Before returning [`Poll::Pending`], the implementation must arrange for
173 /// `cx`'s waker to be notified when flushing may progress. `WouldBlock` and
174 /// `Interrupted` must not cross this asynchronous boundary.
175 ///
176 /// # Errors
177 ///
178 /// Returns the flush error reported by the implementation.
179 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>;
180
181 /// Creates a future that performs one asynchronous write operation.
182 ///
183 /// # Type Parameters
184 ///
185 /// * `'a` - Shared lifetime of the output borrow and source slice.
186 ///
187 /// # Parameters
188 ///
189 /// * `input` - Source storage.
190 ///
191 /// # Returns
192 ///
193 /// A future that resolves with the number of accepted items.
194 #[inline(always)]
195 fn write_async<'a>(&'a mut self, input: &'a [Self::Item]) -> WriteFuture<'a, Self>
196 where
197 Self: Sized + Unpin,
198 {
199 WriteFuture::new(Pin::new(self), input)
200 }
201
202 /// Creates a future that writes the entire source slice.
203 ///
204 /// The returned future reports [`std::io::ErrorKind::WriteZero`] when
205 /// output makes no progress.
206 ///
207 /// # Type Parameters
208 ///
209 /// * `'a` - Shared lifetime of the output borrow and source slice.
210 ///
211 /// # Parameters
212 ///
213 /// * `input` - Source storage.
214 ///
215 /// # Returns
216 ///
217 /// A future that resolves when every item has been accepted.
218 #[inline(always)]
219 fn write_fully_async<'a>(&'a mut self, input: &'a [Self::Item]) -> WriteFullyFuture<'a, Self>
220 where
221 Self: Sized + Unpin,
222 {
223 WriteFullyFuture::new(Pin::new(self), input)
224 }
225
226 /// Creates a future that flushes internally buffered items.
227 ///
228 /// # Returns
229 ///
230 /// A future that resolves with the flush result.
231 #[inline(always)]
232 fn flush_async(&mut self) -> FlushFuture<'_, Self>
233 where
234 Self: Sized + Unpin,
235 {
236 FlushFuture::new(Pin::new(self))
237 }
238}