0

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?

E_net4
  • 27,810
  • 13
  • 101
  • 139
user656449
  • 2,950
  • 2
  • 30
  • 43

1 Answers1

2

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]);
}
Aplet123
  • 33,825
  • 1
  • 29
  • 55