首页 > 解决方案 > read in chunks with async-std

问题描述

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?

标签: rustrust-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]);
}

推荐阅读