maybe_fut/api/io/
repeat.rs

1use super::Read;
2
3/// A reader which yields one byte over and over and over and over and over and…
4///
5/// This struct is generally created by calling [`repeat`]. Please see the documentation of [`repeat`] for more details.
6#[derive(Debug, Clone, Copy, Default)]
7pub struct Repeat {
8    byte: u8,
9}
10
11impl Read for Repeat {
12    async fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
13        // Fill the buffer with the byte.
14        for b in buf.iter_mut() {
15            *b = self.byte;
16        }
17        Ok(buf.len())
18    }
19}
20
21/// Creates a new [`Repeat`] instance with the specified byte to repeat.
22pub const fn repeat(byte: u8) -> Repeat {
23    Repeat { byte }
24}
25
26#[cfg(test)]
27mod test {
28    use super::*;
29    use crate::api::io::Read;
30
31    #[tokio::test]
32    async fn test_repeat() {
33        let mut repeat = repeat(b'A');
34        let mut buf = [0; 10];
35        let n = repeat.read(&mut buf).await.unwrap();
36        assert_eq!(n, buf.len());
37        assert_eq!(buf, [b'A'; 10]);
38    }
39}