I'm trying to implement something similar to reading a file in Java with AsynchronousByteChannel like
AsynchronousFileChannel channel = AsynchronousFileChannel.open(path...
channel.read(buffer,... new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result) {
...use buffer
}
i.e. read as much as OS gives, process, ask for more and so on. What would be the most straightforward way to achieve this with async_std?
You can use the read
method of the async_std::io::Read
trait:
use async_std::prelude::*;
let mut reader = obtain_read_somehow();
let mut buf = [0; 4096]; // or however large you want it
// read returns a Poll<Result> so you have to handle the result
loop {
let byte_count = reader.read(&mut buf).await?;
if byte_count == 0 {
// 0 bytes read means we're done
break;
}
// call whatever handler function on the bytes read
handle(&buf[..byte_count]);
}