Skip to content

Commit bf6a2d1

Browse files
committed
impl AsyncBufRead for Encoder
1 parent c3c5f37 commit bf6a2d1

File tree

1 file changed

+26
-21
lines changed

1 file changed

+26
-21
lines changed

src/encoder.rs

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use async_std::io::Read as AsyncRead;
1+
use async_std::io::{BufRead as AsyncBufRead, Read as AsyncRead};
22
use async_std::prelude::*;
33
use async_std::task::{ready, Context, Poll};
44

@@ -50,26 +50,31 @@ impl AsyncRead for Encoder {
5050
}
5151
}
5252

53-
// impl AsyncBufRead for Encoder {
54-
// fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
55-
// match ready!(self.project().receiver.poll_next(cx)) {
56-
// Some(buf) => match &self.buf {
57-
// None => self.project().buf = &mut Some(buf),
58-
// Some(local_buf) => local_buf.extend(buf),
59-
// },
60-
// None => {
61-
// if let None = self.buf {
62-
// self.project().buf = &mut Some(vec![]);
63-
// };
64-
// }
65-
// };
66-
// Poll::Ready(Ok(self.buf.as_ref().unwrap()))
67-
// }
68-
69-
// fn consume(self: Pin<&mut Self>, amt: usize) {
70-
// Pin::new(self).cursor += amt;
71-
// }
72-
// }
53+
impl AsyncBufRead for Encoder {
54+
fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
55+
let mut this = self.project();
56+
// Request a new buffer if current one is exhausted.
57+
if this.buf.len() <= *this.cursor {
58+
match ready!(this.receiver.as_mut().poll_next(cx)) {
59+
Some(buf) => {
60+
log::trace!("> Received a new buffer with len {}", buf.len());
61+
*this.buf = buf.into_boxed_slice();
62+
*this.cursor = 0;
63+
}
64+
None => {
65+
log::trace!("> Encoder done reading");
66+
return Poll::Ready(Ok(&[]));
67+
}
68+
};
69+
}
70+
Poll::Ready(Ok(&this.buf[*this.cursor..]))
71+
}
72+
73+
fn consume(self: Pin<&mut Self>, amt: usize) {
74+
let this = self.project();
75+
*this.cursor += amt;
76+
}
77+
}
7378

7479
/// The sending side of the encoder.
7580
#[derive(Debug, Clone)]

0 commit comments

Comments
 (0)