pub struct Task<'f, T> { /* private fields */ }Expand description
A suspended computation that reads a stream: run it with run, or
drive it yourself with resume.
Code that reads is written once, as straight-line async code over an Io:
async fn first_byte(io: &mut Io) -> Result<u8> {
let mut b = [0u8; 1];
io.read_at(0, &mut b).await?;
Ok(b[0])
}
let data = [7u8, 8, 9];
let mut task = Task::new(data.len() as u64, |mut io| async move {
first_byte(&mut io).await
});
let first = loop {
match task.resume()? {
// The task has nothing to read from; it asks. Answer however you like.
Progress::Read(mut req) => {
let at = req.offset() as usize;
req.buffer().extend_from_slice(&data[at..]);
}
Progress::Done(v) => break v,
_ => unreachable!(),
}
};
assert_eq!(first, 7);The task does not read anything itself. When it needs bytes that its Io does
not already hold, it suspends, and resume returns a
ReadRequest: where to read and how much. The caller reads however it likes
(blocking, async, from a network buffer it already has), puts the bytes in the
request’s buffer, and resumes. run is the blocking driver for a
Read + Seek. No runtime is involved and no I/O trait is required: the task is
driven by plain method calls, so it is Send and works under any executor.
Io keeps a window of the stream, so a run of tiny reads (a chunk header, a
box header) becomes one request for a few KiB, and the code makes no system call
of its own.
Implementations§
Source§impl<'f, T> Task<'f, T>
impl<'f, T> Task<'f, T>
Sourcepub fn new<F>(total: u64, make: impl FnOnce(Io) -> F) -> Self
pub fn new<F>(total: u64, make: impl FnOnce(Io) -> F) -> Self
A task for the stream of total bytes that make reads through the Io it
is given. Nothing runs until the first resume.
Sourcepub fn resume(&mut self) -> Result<Progress<'_, T>>
pub fn resume(&mut self) -> Result<Progress<'_, T>>
Run until the task needs bytes it does not have, or finishes.
On Progress::Read, fill the request’s buffer and call resume again.
An error is final. Calling resume after the task has finished is an
error.