-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathread_exact.rs
37 lines (32 loc) · 862 Bytes
/
read_exact.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use core::pin::Pin;
use futures_core::{future::Future, task::Poll};
use futures_util::{future::poll_fn, ready};
use embrio_core::io::Read;
#[derive(Debug)]
pub enum Error<T> {
UnexpectedEof,
Other(T),
}
impl<T> From<T> for Error<T> {
fn from(err: T) -> Self {
Error::Other(err)
}
}
pub fn read_exact<'a, R: Read + 'a>(
mut this: Pin<&'a mut R>,
mut buf: impl AsMut<[u8]> + 'a,
) -> impl Future<Output = Result<(), Error<R::Error>>> + 'a {
let mut position = 0;
poll_fn(move |cx| {
let buf = buf.as_mut();
while position < buf.len() {
let amount =
ready!(this.as_mut().poll_read(cx, &mut buf[position..]))?;
position += amount;
if amount == 0 {
Err(Error::UnexpectedEof)?;
}
}
Poll::Ready(Ok(()))
})
}