diff options
| -rw-r--r-- | embassy/src/io/util/drain.rs | 43 | ||||
| -rw-r--r-- | embassy/src/io/util/mod.rs | 10 |
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 @@ | |||
| 1 | use core::iter::Iterator; | ||
| 2 | use core::pin::Pin; | ||
| 3 | use futures::future::Future; | ||
| 4 | use futures::ready; | ||
| 5 | use futures::task::{Context, Poll}; | ||
| 6 | |||
| 7 | use super::super::error::{Error, Result}; | ||
| 8 | use super::super::traits::AsyncBufRead; | ||
| 9 | |||
| 10 | pub struct Drain<'a, R: ?Sized> { | ||
| 11 | reader: &'a mut R, | ||
| 12 | } | ||
| 13 | |||
| 14 | impl<R: ?Sized + Unpin> Unpin for Drain<'_, R> {} | ||
| 15 | |||
| 16 | impl<'a, R: AsyncBufRead + ?Sized + Unpin> Drain<'a, R> { | ||
| 17 | pub(super) fn new(reader: &'a mut R) -> Self { | ||
| 18 | Self { reader } | ||
| 19 | } | ||
| 20 | } | ||
| 21 | |||
| 22 | impl<'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; | |||
| 24 | mod skip_while; | 24 | mod skip_while; |
| 25 | pub use self::skip_while::SkipWhile; | 25 | pub use self::skip_while::SkipWhile; |
| 26 | 26 | ||
| 27 | mod drain; | ||
| 28 | pub use self::drain::Drain; | ||
| 29 | |||
| 27 | mod write; | 30 | mod write; |
| 28 | pub use self::write::Write; | 31 | pub 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, |
