1 use crate::io::{AsyncBufRead, AsyncRead, ReadBuf};
2
3 use pin_project_lite::pin_project;
4 use std::pin::Pin;
5 use std::task::{Context, Poll};
6 use std::{cmp, io};
7
8 pin_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
take<R: AsyncRead>(inner: R, limit: u64) -> Take<R>21 pub(super) fn take<R: AsyncRead>(inner: R, limit: u64) -> Take<R> {
22 Take {
23 inner,
24 limit_: limit,
25 }
26 }
27
28 impl<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.
limit(&self) -> u6436 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.
set_limit(&mut self, limit: u64)44 pub fn set_limit(&mut self, limit: u64) {
45 self.limit_ = limit
46 }
47
48 /// Gets a reference to the underlying reader.
get_ref(&self) -> &R49 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`.
get_mut(&mut self) -> &mut R58 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`.
get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut R>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.
into_inner(self) -> R72 pub fn into_inner(self) -> R {
73 self.inner
74 }
75 }
76
77 impl<R: AsyncRead> AsyncRead for Take<R> {
poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<Result<(), io::Error>>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 ready!(me.inner.poll_read(cx, &mut b))?;
90 let n = b.filled().len();
91
92 // We need to update the original ReadBuf
93 unsafe {
94 buf.assume_init(n);
95 }
96 buf.advance(n);
97 *me.limit_ -= n as u64;
98 Poll::Ready(Ok(()))
99 }
100 }
101
102 impl<R: AsyncBufRead> AsyncBufRead for Take<R> {
poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>>103 fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
104 let me = self.project();
105
106 // Don't call into inner reader at all at EOF because it may still block
107 if *me.limit_ == 0 {
108 return Poll::Ready(Ok(&[]));
109 }
110
111 let buf = ready!(me.inner.poll_fill_buf(cx)?);
112 let cap = cmp::min(buf.len() as u64, *me.limit_) as usize;
113 Poll::Ready(Ok(&buf[..cap]))
114 }
115
consume(self: Pin<&mut Self>, amt: usize)116 fn consume(self: Pin<&mut Self>, amt: usize) {
117 let me = self.project();
118 // Don't let callers reset the limit by passing an overlarge value
119 let amt = cmp::min(amt as u64, *me.limit_) as usize;
120 *me.limit_ -= amt as u64;
121 me.inner.consume(amt);
122 }
123 }
124
125 #[cfg(test)]
126 mod tests {
127 use super::*;
128
129 #[test]
assert_unpin()130 fn assert_unpin() {
131 crate::is_unpin::<Take<()>>();
132 }
133 }
134