Coverage Report

Created: 2024-05-20 06:38

/rust/registry/src/index.crates.io-6f17d22bba15001f/futures-util-0.3.28/src/io/repeat.rs
Line
Count
Source (jump to first uncovered line)
1
use futures_core::ready;
2
use futures_core::task::{Context, Poll};
3
use futures_io::{AsyncRead, IoSliceMut};
4
use std::fmt;
5
use std::io;
6
use std::pin::Pin;
7
8
/// Reader for the [`repeat()`] function.
9
#[must_use = "readers do nothing unless polled"]
10
pub 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
/// ```
31
0
pub fn repeat(byte: u8) -> Repeat {
32
0
    Repeat { byte }
33
0
}
34
35
impl AsyncRead for Repeat {
36
    #[inline]
37
0
    fn poll_read(
38
0
        self: Pin<&mut Self>,
39
0
        _: &mut Context<'_>,
40
0
        buf: &mut [u8],
41
0
    ) -> Poll<io::Result<usize>> {
42
0
        for slot in &mut *buf {
43
0
            *slot = self.byte;
44
0
        }
45
0
        Poll::Ready(Ok(buf.len()))
46
0
    }
47
48
    #[inline]
49
0
    fn poll_read_vectored(
50
0
        mut self: Pin<&mut Self>,
51
0
        cx: &mut Context<'_>,
52
0
        bufs: &mut [IoSliceMut<'_>],
53
0
    ) -> Poll<io::Result<usize>> {
54
0
        let mut nwritten = 0;
55
0
        for buf in bufs {
56
0
            nwritten += ready!(self.as_mut().poll_read(cx, buf))?;
57
        }
58
0
        Poll::Ready(Ok(nwritten))
59
0
    }
60
}
61
62
impl fmt::Debug for Repeat {
63
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64
0
        f.pad("Repeat { .. }")
65
0
    }
66
}