qubit_io/wrappers/async_counting_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;
10use std::pin::Pin;
11use std::task::Context;
12use std::task::Poll;
13
14use crate::AsyncClose;
15use crate::AsyncOutput;
16use crate::traits::normalize_async_error;
17
18/// Asynchronous output that counts successfully accepted items.
19///
20/// # Type Parameters
21///
22/// - `O`: Wrapped asynchronous output type.
23#[must_use]
24#[derive(Debug)]
25pub struct AsyncCountingOutput<O> {
26 /// Output whose successful writes are counted.
27 inner: O,
28 /// Saturating count of accepted items.
29 items_written: u64,
30}
31
32impl<O> AsyncClose for AsyncCountingOutput<O>
33where
34 O: AsyncClose,
35{
36 /// Polls closing through the wrapped output.
37 ///
38 /// # Parameters
39 ///
40 /// - `cx`: Task context used to register a wake-up.
41 ///
42 /// # Returns
43 ///
44 /// Returns [`Poll::Pending`] while closing is incomplete, otherwise a
45 /// ready success result.
46 ///
47 /// # Errors
48 ///
49 /// Returns an error reported by the wrapped output. Invalid asynchronous
50 /// error kinds are normalized to [`io::ErrorKind::InvalidData`].
51 #[inline(always)]
52 fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
53 // SAFETY: `inner` is never moved while projecting this pinned wrapper.
54 let this = unsafe { self.get_unchecked_mut() };
55 // SAFETY: The pinned wrapper keeps `inner` at a stable address.
56 unsafe { Pin::new_unchecked(&mut this.inner) }
57 .poll_close(cx)
58 .map(|result| result.map_err(normalize_async_error))
59 }
60}
61
62impl<O> AsyncCountingOutput<O> {
63 /// Creates a counting asynchronous output.
64 ///
65 /// # Parameters
66 ///
67 /// - `inner`: Asynchronous output to wrap.
68 ///
69 /// # Returns
70 ///
71 /// Returns an output whose item count starts at zero.
72 #[inline(always)]
73 pub const fn new(inner: O) -> Self {
74 Self {
75 inner,
76 items_written: 0,
77 }
78 }
79
80 /// Returns the successfully accepted item count.
81 ///
82 /// # Returns
83 ///
84 /// Returns a count that saturates at [`u64::MAX`].
85 #[inline(always)]
86 #[must_use]
87 pub const fn items_written(&self) -> u64 {
88 self.items_written
89 }
90
91 /// Returns a shared reference to the wrapped output.
92 ///
93 /// # Returns
94 ///
95 /// Returns the wrapped asynchronous output.
96 #[inline(always)]
97 #[must_use]
98 pub const fn inner(&self) -> &O {
99 &self.inner
100 }
101
102 /// Returns a mutable reference to the wrapped output.
103 ///
104 /// Writes performed directly on the returned output are not included in
105 /// this wrapper's item count.
106 ///
107 /// # Returns
108 ///
109 /// Returns the wrapped asynchronous output.
110 #[inline(always)]
111 #[must_use]
112 pub fn inner_mut(&mut self) -> &mut O {
113 &mut self.inner
114 }
115
116 /// Consumes this wrapper and returns the wrapped output.
117 ///
118 /// # Returns
119 ///
120 /// Returns the asynchronous output.
121 #[inline(always)]
122 #[must_use]
123 pub fn into_inner(self) -> O {
124 self.inner
125 }
126}
127
128impl<O> AsyncCountingOutput<O>
129where
130 O: AsyncOutput<Item = u8>,
131{
132 /// Returns the successfully accepted byte count.
133 ///
134 /// # Returns
135 ///
136 /// Returns the same value as [`Self::items_written`].
137 #[inline(always)]
138 #[must_use]
139 pub const fn bytes_written(&self) -> u64 {
140 self.items_written
141 }
142}
143
144impl<O> AsyncOutput for AsyncCountingOutput<O>
145where
146 O: AsyncOutput,
147{
148 /// Item type counted after successful writes.
149 type Item = O::Item;
150
151 /// Preserves the wrapped output's buffering declaration.
152 ///
153 /// # Returns
154 ///
155 /// Returns the wrapped output's buffering declaration.
156 #[inline(always)]
157 fn is_buffered(&self) -> bool {
158 self.inner.is_buffered()
159 }
160
161 /// Polls a write and counts only a successful ready result.
162 ///
163 /// # Parameters
164 ///
165 /// - `cx`: Task context used to register a wake-up.
166 /// - `input`: Source item slice.
167 /// - `index`: Starting source index.
168 /// - `count`: Maximum number of items to write.
169 ///
170 /// # Returns
171 ///
172 /// Returns [`Poll::Pending`] when the output is not ready. A ready success
173 /// contains the number of items accepted and added to the saturating count.
174 ///
175 /// # Errors
176 ///
177 /// Returns an I/O error reported by the wrapped output without changing the
178 /// count.
179 ///
180 /// # Safety
181 ///
182 /// The range `index..index + count` must be valid for `input`.
183 unsafe fn poll_write_unchecked(
184 mut self: Pin<&mut Self>,
185 cx: &mut Context<'_>,
186 input: &[Self::Item],
187 index: usize,
188 count: usize,
189 ) -> Poll<io::Result<usize>> {
190 // SAFETY: `inner` is never moved while projecting this pinned wrapper.
191 let this = unsafe { self.as_mut().get_unchecked_mut() };
192 let source = &input[index..index + count];
193 // SAFETY: The pinned wrapper keeps `inner` at a stable address.
194 let inner = unsafe { Pin::new_unchecked(&mut this.inner) };
195 match inner.poll_write(cx, source) {
196 Poll::Ready(Ok(written)) => {
197 let written_u64 = u64::try_from(written).unwrap_or(u64::MAX);
198 this.items_written = this.items_written.saturating_add(written_u64);
199 Poll::Ready(Ok(written))
200 }
201 Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
202 Poll::Pending => Poll::Pending,
203 }
204 }
205
206 /// Polls the wrapped output's flush operation.
207 ///
208 /// # Parameters
209 ///
210 /// - `cx`: Task context used to register a wake-up.
211 ///
212 /// # Returns
213 ///
214 /// Returns [`Poll::Pending`] while flushing is incomplete, otherwise a
215 /// ready success result.
216 ///
217 /// # Errors
218 ///
219 /// Returns an error reported by the wrapped output. Invalid asynchronous
220 /// error kinds are normalized to [`io::ErrorKind::InvalidData`].
221 #[inline(always)]
222 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
223 // SAFETY: `inner` is never moved while projecting this pinned wrapper.
224 let this = unsafe { self.get_unchecked_mut() };
225 // SAFETY: The pinned wrapper keeps `inner` at a stable address.
226 unsafe { Pin::new_unchecked(&mut this.inner) }
227 .poll_flush(cx)
228 .map(|result| result.map_err(normalize_async_error))
229 }
230}