Skip to content

Commit a4d42e7

Browse files
bors[bot]tirr-c
andauthored
Merge #197
197: Add io::repeat r=stjepang a=tirr-c Co-authored-by: Wonwoo Choi <[email protected]>
2 parents 03f5022 + 689b3c6 commit a4d42e7

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

src/io/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ pub use buf_reader::BufReader;
3030
pub use copy::copy;
3131
pub use empty::{empty, Empty};
3232
pub use read::Read;
33+
pub use repeat::{repeat, Repeat};
3334
pub use seek::Seek;
3435
pub use sink::{sink, Sink};
3536
pub use stderr::{stderr, Stderr};
@@ -43,6 +44,7 @@ mod buf_reader;
4344
mod copy;
4445
mod empty;
4546
mod read;
47+
mod repeat;
4648
mod seek;
4749
mod sink;
4850
mod stderr;

src/io/repeat.rs

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

0 commit comments

Comments
 (0)