Skip to main content

qubit_io/wrappers/
async_limit_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 accepts at most a fixed number of items.
19///
20/// # Type Parameters
21///
22/// - `O`: Wrapped asynchronous output type.
23#[must_use]
24#[derive(Debug)]
25pub struct AsyncLimitOutput<O> {
26    /// Output constrained by this wrapper.
27    inner: O,
28    /// Number of items still accepted.
29    remaining: u64,
30}
31
32impl<O> AsyncClose for AsyncLimitOutput<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> AsyncLimitOutput<O> {
63    /// Creates a limited asynchronous output.
64    ///
65    /// # Parameters
66    ///
67    /// - `inner`: Asynchronous output to wrap.
68    /// - `limit`: Maximum item count accepted by this wrapper.
69    ///
70    /// # Returns
71    ///
72    /// Returns an output with `limit` items remaining.
73    #[inline(always)]
74    pub const fn new(inner: O, limit: u64) -> Self {
75        Self {
76            inner,
77            remaining: limit,
78        }
79    }
80
81    /// Returns the remaining accepted item count.
82    ///
83    /// # Returns
84    ///
85    /// Returns zero after the configured limit has been consumed.
86    #[inline(always)]
87    #[must_use]
88    pub const fn remaining(&self) -> u64 {
89        self.remaining
90    }
91
92    /// Returns a shared reference to the wrapped output.
93    ///
94    /// # Returns
95    ///
96    /// Returns the wrapped asynchronous output.
97    #[inline(always)]
98    #[must_use]
99    pub const fn inner(&self) -> &O {
100        &self.inner
101    }
102
103    /// Returns a mutable reference to the wrapped output.
104    ///
105    /// Writes performed directly on the returned output bypass this wrapper's
106    /// remaining-item limit.
107    ///
108    /// # Returns
109    ///
110    /// Returns the wrapped asynchronous output.
111    #[inline(always)]
112    #[must_use]
113    pub fn inner_mut(&mut self) -> &mut O {
114        &mut self.inner
115    }
116
117    /// Consumes this wrapper and returns the wrapped output.
118    ///
119    /// # Returns
120    ///
121    /// Returns the asynchronous output.
122    #[inline(always)]
123    #[must_use]
124    pub fn into_inner(self) -> O {
125        self.inner
126    }
127}
128
129impl<O> AsyncOutput for AsyncLimitOutput<O>
130where
131    O: AsyncOutput,
132{
133    /// Item type accepted by the limited output.
134    type Item = O::Item;
135
136    /// Preserves the wrapped output's buffering declaration.
137    ///
138    /// # Returns
139    ///
140    /// Returns the wrapped output's buffering declaration.
141    #[inline(always)]
142    fn is_buffered(&self) -> bool {
143        self.inner.is_buffered()
144    }
145
146    /// Polls a write bounded by the remaining item count.
147    ///
148    /// The method completes with zero items without polling `inner` when the
149    /// limit is exhausted or `count` is zero.
150    ///
151    /// # Parameters
152    ///
153    /// - `cx`: Task context used to register a wake-up.
154    /// - `input`: Source item slice.
155    /// - `index`: Starting source index.
156    /// - `count`: Maximum number of items offered.
157    ///
158    /// # Returns
159    ///
160    /// Returns [`Poll::Pending`] when the output is not ready. A ready success
161    /// contains the number of items accepted within the remaining limit.
162    ///
163    /// # Errors
164    ///
165    /// Returns an I/O error reported by the wrapped output without consuming
166    /// the remaining limit.
167    ///
168    /// # Safety
169    ///
170    /// The range `index..index + count` must be valid for `input`.
171    unsafe fn poll_write_unchecked(
172        mut self: Pin<&mut Self>,
173        cx: &mut Context<'_>,
174        input: &[Self::Item],
175        index: usize,
176        count: usize,
177    ) -> Poll<io::Result<usize>> {
178        // SAFETY: `inner` is never moved while projecting this pinned wrapper.
179        let this = unsafe { self.as_mut().get_unchecked_mut() };
180        if this.remaining == 0 || count == 0 {
181            return Poll::Ready(Ok(0));
182        }
183        let requested = usize::try_from(this.remaining).unwrap_or(usize::MAX).min(count);
184        let source = &input[index..index + requested];
185        // SAFETY: The pinned wrapper never moves `inner`.
186        let inner = unsafe { Pin::new_unchecked(&mut this.inner) };
187        match inner.poll_write(cx, source) {
188            Poll::Ready(Ok(written)) => {
189                this.remaining -= written as u64;
190                Poll::Ready(Ok(written))
191            }
192            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
193            Poll::Pending => Poll::Pending,
194        }
195    }
196
197    /// Polls the wrapped output's flush operation.
198    ///
199    /// # Parameters
200    ///
201    /// - `cx`: Task context used to register a wake-up.
202    ///
203    /// # Returns
204    ///
205    /// Returns [`Poll::Pending`] while flushing is incomplete, otherwise a
206    /// ready success result.
207    ///
208    /// # Errors
209    ///
210    /// Returns an error reported by the wrapped output. Invalid asynchronous
211    /// error kinds are normalized to [`io::ErrorKind::InvalidData`].
212    #[inline(always)]
213    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
214        // SAFETY: `inner` is never moved while projecting this pinned wrapper.
215        let this = unsafe { self.get_unchecked_mut() };
216        // SAFETY: The pinned wrapper keeps `inner` at a stable address.
217        unsafe { Pin::new_unchecked(&mut this.inner) }
218            .poll_flush(cx)
219            .map(|result| result.map_err(normalize_async_error))
220    }
221}