Search code examples
rustrust-tokio

Rust: How do I convert/read a BytesMut to a file?


I have a value of type BytesMut (from bytes)

The source of this value is a file that I have downloaded from a remote source (an AWS S3 bucket, in this case). I want to store(write) these bytes (it's an image) to a file so that I can then go ahead and read the image file, do some processing, etc.

What's the best/easiest way to do this?

I've taken a look at this question, but it hasn't helped me as I think it's doing the reverse of what I'm attempting. Any help would be appreciated, thanks!


Solution

  • A BytesMut derefs into a slice of u8, so you can access its whole contents with &b[..]. To write it to a file, use the write_all method on Write values, which accepts a slice:

    let b: BytesMut = ...;
    File::create("filename").write_all(&b[..])?;