async_std/io/
repeat.rs

1use std::fmt;
2use std::pin::Pin;
3
4use crate::io::{self, Read};
5use crate::task::{Context, Poll};
6
7/// Creates an instance of a reader that infinitely repeats one byte.
8///
9/// All reads from this reader will succeed by filling the specified buffer with the given byte.
10///
11/// ## Examples
12///
13/// ```rust
14/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
15/// #
16/// use async_std::io;
17/// use async_std::prelude::*;
18///
19/// let mut buffer = [0; 3];
20/// io::repeat(0b101).read_exact(&mut buffer).await?;
21///
22/// assert_eq!(buffer, [0b101, 0b101, 0b101]);
23/// #
24/// # Ok(()) }) }
25/// ```
26pub fn repeat(byte: u8) -> Repeat {
27    Repeat { byte }
28}
29
30/// A reader which yields one byte over and over and over and over and over and...
31///
32/// This reader is created by the [`repeat`] function. See its
33/// documentation for more.
34///
35/// [`repeat`]: fn.repeat.html
36pub struct Repeat {
37    byte: u8,
38}
39
40impl fmt::Debug for Repeat {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        f.pad("Empty { .. }")
43    }
44}
45
46impl Read for Repeat {
47    #[inline]
48    fn poll_read(
49        self: Pin<&mut Self>,
50        _: &mut Context<'_>,
51        buf: &mut [u8],
52    ) -> Poll<io::Result<usize>> {
53        for b in &mut *buf {
54            *b = self.byte;
55        }
56        Poll::Ready(Ok(buf.len()))
57    }
58}