embedded_platform/io/
read_exact.rs

1use core::future;
2use core::pin;
3use core::task;
4
5#[derive(Debug)]
6#[must_use = "futures do nothing unless you `.await` or poll them"]
7pub struct ReadExact<'a, A>
8where
9    A: super::Read + Unpin + ?Sized,
10{
11    reader: &'a mut A,
12    buffer: &'a mut [u8],
13    position: usize,
14}
15
16pub fn read_exact<'a, A>(reader: &'a mut A, buffer: &'a mut [u8]) -> ReadExact<'a, A>
17where
18    A: super::Read + Unpin + ?Sized,
19{
20    let position = 0;
21    ReadExact {
22        reader,
23        buffer,
24        position,
25    }
26}
27
28impl<A> future::Future for ReadExact<'_, A>
29where
30    A: super::Read + Unpin + ?Sized,
31{
32    type Output = Result<usize, A::Error>;
33
34    fn poll(mut self: pin::Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
35        use super::ReadError;
36
37        loop {
38            // if our buffer is empty, then we need to read some data to continue.
39            if self.position < self.buffer.len() {
40                let this = &mut *self;
41                let n = futures::ready!(pin::Pin::new(&mut *this.reader)
42                    .poll_read(cx, &mut this.buffer[this.position..]))?;
43                this.position += n;
44                if n == 0 {
45                    return Err(A::Error::eof()).into();
46                }
47            }
48
49            if self.position >= self.buffer.len() {
50                return task::Poll::Ready(Ok(self.position));
51            }
52        }
53    }
54}