broker_tokio/io/util/
take.rs

1use crate::io::{AsyncBufRead, AsyncRead};
2
3use pin_project_lite::pin_project;
4use std::mem::MaybeUninit;
5use std::pin::Pin;
6use std::task::{Context, Poll};
7use std::{cmp, io};
8
9pin_project! {
10    /// Stream for the [`take`](super::AsyncReadExt::take) method.
11    #[derive(Debug)]
12    #[must_use = "streams do nothing unless you `.await` or poll them"]
13    #[cfg_attr(docsrs, doc(cfg(feature = "io-util")))]
14    pub struct Take<R> {
15        #[pin]
16        inner: R,
17        // Add '_' to avoid conflicts with `limit` method.
18        limit_: u64,
19    }
20}
21
22pub(super) fn take<R: AsyncRead>(inner: R, limit: u64) -> Take<R> {
23    Take {
24        inner,
25        limit_: limit,
26    }
27}
28
29impl<R: AsyncRead> Take<R> {
30    /// Returns the remaining number of bytes that can be
31    /// read before this instance will return EOF.
32    ///
33    /// # Note
34    ///
35    /// This instance may reach `EOF` after reading fewer bytes than indicated by
36    /// this method if the underlying [`AsyncRead`] instance reaches EOF.
37    pub fn limit(&self) -> u64 {
38        self.limit_
39    }
40
41    /// Sets the number of bytes that can be read before this instance will
42    /// return EOF. This is the same as constructing a new `Take` instance, so
43    /// the amount of bytes read and the previous limit value don't matter when
44    /// calling this method.
45    pub fn set_limit(&mut self, limit: u64) {
46        self.limit_ = limit
47    }
48
49    /// Gets a reference to the underlying reader.
50    pub fn get_ref(&self) -> &R {
51        &self.inner
52    }
53
54    /// Gets a mutable reference to the underlying reader.
55    ///
56    /// Care should be taken to avoid modifying the internal I/O state of the
57    /// underlying reader as doing so may corrupt the internal limit of this
58    /// `Take`.
59    pub fn get_mut(&mut self) -> &mut R {
60        &mut self.inner
61    }
62
63    /// Gets a pinned mutable reference to the underlying reader.
64    ///
65    /// Care should be taken to avoid modifying the internal I/O state of the
66    /// underlying reader as doing so may corrupt the internal limit of this
67    /// `Take`.
68    pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut R> {
69        self.project().inner
70    }
71
72    /// Consumes the `Take`, returning the wrapped reader.
73    pub fn into_inner(self) -> R {
74        self.inner
75    }
76}
77
78impl<R: AsyncRead> AsyncRead for Take<R> {
79    unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [MaybeUninit<u8>]) -> bool {
80        self.inner.prepare_uninitialized_buffer(buf)
81    }
82
83    fn poll_read(
84        self: Pin<&mut Self>,
85        cx: &mut Context<'_>,
86        buf: &mut [u8],
87    ) -> Poll<Result<usize, io::Error>> {
88        if self.limit_ == 0 {
89            return Poll::Ready(Ok(0));
90        }
91
92        let me = self.project();
93        let max = std::cmp::min(buf.len() as u64, *me.limit_) as usize;
94        let n = ready!(me.inner.poll_read(cx, &mut buf[..max]))?;
95        *me.limit_ -= n as u64;
96        Poll::Ready(Ok(n))
97    }
98}
99
100impl<R: AsyncBufRead> AsyncBufRead for Take<R> {
101    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
102        let me = self.project();
103
104        // Don't call into inner reader at all at EOF because it may still block
105        if *me.limit_ == 0 {
106            return Poll::Ready(Ok(&[]));
107        }
108
109        let buf = ready!(me.inner.poll_fill_buf(cx)?);
110        let cap = cmp::min(buf.len() as u64, *me.limit_) as usize;
111        Poll::Ready(Ok(&buf[..cap]))
112    }
113
114    fn consume(self: Pin<&mut Self>, amt: usize) {
115        let me = self.project();
116        // Don't let callers reset the limit by passing an overlarge value
117        let amt = cmp::min(amt as u64, *me.limit_) as usize;
118        *me.limit_ -= amt as u64;
119        me.inner.consume(amt);
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    #[test]
128    fn assert_unpin() {
129        crate::is_unpin::<Take<()>>();
130    }
131}