pub trait Read {
// Required method
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: ReadBufCursor<'_>,
) -> Poll<Result<(), Error>>;
}Expand description
Reads bytes from a source.
This trait is similar to std::io::Read, but supports asynchronous reads.
§Implementing Read
Implementations should read data into the provided ReadBufCursor and
advance the cursor to indicate how many bytes were written. The simplest
and safest approach is to use ReadBufCursor::put_slice:
use hyper::rt::{Read, ReadBufCursor};
use std::pin::Pin;
use std::task::{Context, Poll};
use std::io;
struct MyReader {
data: Vec<u8>,
position: usize,
}
impl Read for MyReader {
fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
mut buf: ReadBufCursor<'_>,
) -> Poll<Result<(), io::Error>> {
let remaining_data = &self.data[self.position..];
if remaining_data.is_empty() {
// No more data to read, signal EOF by returning Ok without
// advancing the buffer
return Poll::Ready(Ok(()));
}
// Calculate how many bytes we can write
let to_copy = remaining_data.len().min(buf.remaining());
// Use put_slice to safely copy data and advance the cursor
buf.put_slice(&remaining_data[..to_copy]);
self.position += to_copy;
Poll::Ready(Ok(()))
}
}For more advanced use cases where you need direct access to the buffer
(e.g., when interfacing with APIs that write directly to a pointer),
you can use the unsafe ReadBufCursor::as_mut and ReadBufCursor::advance
methods. See their documentation for safety requirements.
Required Methods§
Sourcefn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: ReadBufCursor<'_>,
) -> Poll<Result<(), Error>>
fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: ReadBufCursor<'_>, ) -> Poll<Result<(), Error>>
Attempts to read bytes into the buf.
On success, returns Poll::Ready(Ok(())) and places data in the
unfilled portion of buf. If no data was read (buf.remaining() is
unchanged), it implies that EOF has been reached.
If no data is available for reading, the method returns Poll::Pending
and arranges for the current task (via cx.waker()) to receive a
notification when the object becomes readable or is closed.