Read file to BytesMut

It's strange that I could not read the file to BytesMut. But I could do it with u8 slice.

    let mut f = File::open(path).unwrap();
    let mut buf = BytesMut::with_capacity(1024*10);
    let count = f.read(&mut buf[..]).unwrap();
    println!("read {:?}", count);

The count is 0.

Don't confuse capacity with length. That's a 0-len buffer and &mut buf[..] is an empty slice.

1 Like

with_capacity doesn't initialize the bytes, so your slice has length 0. Try:

     let mut f = File::open(path).unwrap();
     let mut buf = BytesMut::with_capacity(1024*10);
+    buf.resize(2014 * 10, 0);
     let count = f.read(&mut buf[..]).unwrap();
     println!("read {:?}", count);
+    buf.truncate(count);

The io::Read interface is not good fit for this. It only knows how to append to a Vec. Read into a Vec, and if you have to have a Buf, then convert the Vec to Buf later (I hope it has a no-copy way for these).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.