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