tokio/io/util/repeat.rs
1use bytes::BufMut;
2
3use crate::io::util::poll_proceed_and_make_progress;
4use crate::io::{AsyncRead, ReadBuf};
5
6use std::io;
7use std::pin::Pin;
8use std::task::{ready, Context, Poll};
9
10cfg_io_util! {
11 /// An async reader which yields one byte over and over and over and over and
12 /// over and...
13 ///
14 /// This struct is generally created by calling [`repeat`][repeat]. Please
15 /// see the documentation of `repeat()` for more details.
16 ///
17 /// This is an asynchronous version of [`std::io::Repeat`][std].
18 ///
19 /// [repeat]: fn@repeat
20 /// [std]: std::io::Repeat
21 #[derive(Debug)]
22 pub struct Repeat {
23 byte: u8,
24 }
25
26 /// Creates an instance of an async reader that infinitely repeats one byte.
27 ///
28 /// All reads from this reader will succeed by filling the specified buffer with
29 /// the given byte.
30 ///
31 /// This is an asynchronous version of [`std::io::repeat`][std].
32 ///
33 /// [std]: std::io::repeat
34 ///
35 /// # Examples
36 ///
37 /// ```
38 /// use tokio::io::{self, AsyncReadExt};
39 ///
40 /// #[tokio::main]
41 /// async fn main() {
42 /// let mut buffer = [0; 3];
43 /// io::repeat(0b101).read_exact(&mut buffer).await.unwrap();
44 /// assert_eq!(buffer, [0b101, 0b101, 0b101]);
45 /// }
46 /// ```
47 pub fn repeat(byte: u8) -> Repeat {
48 Repeat { byte }
49 }
50}
51
52impl AsyncRead for Repeat {
53 #[inline]
54 fn poll_read(
55 self: Pin<&mut Self>,
56 cx: &mut Context<'_>,
57 buf: &mut ReadBuf<'_>,
58 ) -> Poll<io::Result<()>> {
59 ready!(crate::trace::trace_leaf(cx));
60 ready!(poll_proceed_and_make_progress(cx));
61 buf.put_bytes(self.byte, buf.remaining());
62 Poll::Ready(Ok(()))
63 }
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 #[test]
71 fn assert_unpin() {
72 crate::is_unpin::<Repeat>();
73 }
74}