1use futures_core::ready;
2use futures_core::task::{Context, Poll};
3use futures_io::{AsyncRead, IoSliceMut};
4use std::fmt;
5use std::io;
6use std::pin::Pin;
7
8/// Reader for the [`repeat()`] function.
9#[must_use = "readers do nothing unless polled"]
10pub struct Repeat {
11 byte: u8,
12}
13
14/// Creates an instance of a reader that infinitely repeats one byte.
15///
16/// All reads from this reader will succeed by filling the specified buffer with
17/// the given byte.
18///
19/// # Examples
20///
21/// ```
22/// # futures::executor::block_on(async {
23/// use futures::io::{self, AsyncReadExt};
24///
25/// let mut buffer = [0; 3];
26/// let mut reader = io::repeat(0b101);
27/// reader.read_exact(&mut buffer).await.unwrap();
28/// assert_eq!(buffer, [0b101, 0b101, 0b101]);
29/// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
30/// ```
31pub fn repeat(byte: u8) -> Repeat {
32 Repeat { byte }
33}
34
35impl AsyncRead for Repeat {
36 #[inline]
37 fn poll_read(
38 self: Pin<&mut Self>,
39 _: &mut Context<'_>,
40 buf: &mut [u8],
41 ) -> Poll<io::Result<usize>> {
42 for slot in &mut *buf {
43 *slot = self.byte;
44 }
45 Poll::Ready(Ok(buf.len()))
46 }
47
48 #[inline]
49 fn poll_read_vectored(
50 mut self: Pin<&mut Self>,
51 cx: &mut Context<'_>,
52 bufs: &mut [IoSliceMut<'_>],
53 ) -> Poll<io::Result<usize>> {
54 let mut nwritten = 0;
55 for buf in bufs {
56 nwritten += ready!(self.as_mut().poll_read(cx, buf))?;
57 }
58 Poll::Ready(Ok(nwritten))
59 }
60}
61
62impl fmt::Debug for Repeat {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 f.pad("Repeat { .. }")
65 }
66}
67