aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDario Nieuwenhuis <[email protected]>2020-10-19 21:13:26 +0200
committerDario Nieuwenhuis <[email protected]>2020-10-19 21:13:26 +0200
commit0e1adc58f48a65c6af1d2ededa8712426fb3ab6e (patch)
treebbccfa695d2fbbe4f8615da0b49aee5e038ae1bb
parent58bd708ccb67d317d1a5ccbf07dc1c8363cd0d6a (diff)
Add AsyncBufReadExt::drain
-rw-r--r--embassy/src/io/util/drain.rs43
-rw-r--r--embassy/src/io/util/mod.rs10
2 files changed, 53 insertions, 0 deletions
diff --git a/embassy/src/io/util/drain.rs b/embassy/src/io/util/drain.rs
new file mode 100644
index 000000000..d3f21d071
--- /dev/null
+++ b/embassy/src/io/util/drain.rs
@@ -0,0 +1,43 @@
1use core::iter::Iterator;
2use core::pin::Pin;
3use futures::future::Future;
4use futures::ready;
5use futures::task::{Context, Poll};
6
7use super::super::error::{Error, Result};
8use super::super::traits::AsyncBufRead;
9
10pub struct Drain<'a, R: ?Sized> {
11 reader: &'a mut R,
12}
13
14impl<R: ?Sized + Unpin> Unpin for Drain<'_, R> {}
15
16impl<'a, R: AsyncBufRead + ?Sized + Unpin> Drain<'a, R> {
17 pub(super) fn new(reader: &'a mut R) -> Self {
18 Self { reader }
19 }
20}
21
22impl<'a, R: AsyncBufRead + ?Sized + Unpin> Future for Drain<'a, R> {
23 type Output = Result<usize>;
24
25 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
26 let Self { reader } = &mut *self;
27 let mut reader = Pin::new(reader);
28
29 let mut n = 0;
30
31 loop {
32 match reader.as_mut().poll_fill_buf(cx) {
33 Poll::Pending => return Poll::Ready(Ok(n)),
34 Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
35 Poll::Ready(Ok(buf)) => {
36 let len = buf.len();
37 n += len;
38 reader.as_mut().consume(len);
39 }
40 }
41 }
42 }
43}
diff --git a/embassy/src/io/util/mod.rs b/embassy/src/io/util/mod.rs
index c95a23f0a..a0bda6e36 100644
--- a/embassy/src/io/util/mod.rs
+++ b/embassy/src/io/util/mod.rs
@@ -24,6 +24,9 @@ pub use self::read_to_end::ReadToEnd;
24mod skip_while; 24mod skip_while;
25pub use self::skip_while::SkipWhile; 25pub use self::skip_while::SkipWhile;
26 26
27mod drain;
28pub use self::drain::Drain;
29
27mod write; 30mod write;
28pub use self::write::Write; 31pub use self::write::Write;
29 32
@@ -79,6 +82,13 @@ pub trait AsyncBufReadExt: AsyncBufRead {
79 SkipWhile::new(self, f) 82 SkipWhile::new(self, f)
80 } 83 }
81 84
85 fn drain<'a>(&'a mut self) -> Drain<'a, Self>
86 where
87 Self: Unpin,
88 {
89 Drain::new(self)
90 }
91
82 fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self> 92 fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self>
83 where 93 where
84 Self: Unpin, 94 Self: Unpin,