1use crate::io::{AsyncBufRead, AsyncRead, ReadBuf};
2
3use pin_project_lite::pin_project;
4use std::convert::TryFrom;
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 fn poll_read(
80 self: Pin<&mut Self>,
81 cx: &mut Context<'_>,
82 buf: &mut ReadBuf<'_>,
83 ) -> Poll<Result<(), io::Error>> {
84 if self.limit_ == 0 {
85 return Poll::Ready(Ok(()));
86 }
87
88 let me = self.project();
89 let mut b = buf.take(usize::try_from(*me.limit_).unwrap_or(usize::MAX));
90
91 let buf_ptr = b.filled().as_ptr();
92 ready!(me.inner.poll_read(cx, &mut b))?;
93 assert_eq!(b.filled().as_ptr(), buf_ptr);
94
95 let n = b.filled().len();
96
97 // We need to update the original ReadBuf
98 unsafe {
99 buf.assume_init(n);
100 }
101 buf.advance(n);
102 *me.limit_ -= n as u64;
103 Poll::Ready(Ok(()))
104 }
105}
106
107impl<R: AsyncBufRead> AsyncBufRead for Take<R> {
108 fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
109 let me = self.project();
110
111 // Don't call into inner reader at all at EOF because it may still block
112 if *me.limit_ == 0 {
113 return Poll::Ready(Ok(&[]));
114 }
115
116 let buf = ready!(me.inner.poll_fill_buf(cx)?);
117 let cap = cmp::min(buf.len() as u64, *me.limit_) as usize;
118 Poll::Ready(Ok(&buf[..cap]))
119 }
120
121 fn consume(self: Pin<&mut Self>, amt: usize) {
122 let me = self.project();
123 // Don't let callers reset the limit by passing an overlarge value
124 let amt = cmp::min(amt as u64, *me.limit_) as usize;
125 *me.limit_ -= amt as u64;
126 me.inner.consume(amt);
127 }
128}
129
130#[cfg(test)]
131mod tests {
132 use super::*;
133
134 #[test]
135 fn assert_unpin() {
136 crate::is_unpin::<Take<()>>();
137 }
138}
139