Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from std::io::Bytes to &[u8]

Tags:

rust

I am trying to write the contents of an HTTP Response to a file.

extern crate reqwest;

use std::io::Write;
use std::fs::File;

fn main() {
    let mut resp = reqwest::get("https://www.rust-lang.org").unwrap();
    assert!(resp.status().is_success());

    // Write contents to disk.
    let mut f = File::create("download_file").expect("Unable to create file");
    f.write_all(resp.bytes());
}

But I get the following compile error:

error[E0308]: mismatched types
  --> src/main.rs:12:17
   |
12 |     f.write_all(resp.bytes());
   |                 ^^^^^^^^^^^^ expected &[u8], found struct `std::io::Bytes`
   |
   = note: expected type `&[u8]`
              found type `std::io::Bytes<reqwest::Response>`
like image 329
phoenix Avatar asked Jun 08 '17 14:06

phoenix


People also ask

How to convert int to bytes in c++?

We split the input integer (5000) into each byte by using the >> operator. The second operand represents the lowest bit index for each byte in the array. To obtain the 8 least significant bits for each byte, we & the result with 0xFF . Finally, we print each byte using the print function.

How do you represent bytes in Rust?

A Bytes handle can be created directly from an existing byte store (such as &[u8] or Vec<u8> ), but usually a BytesMut is used first and written to. For example: use bytes::{BytesMut, BufMut}; let mut buf = BytesMut::with_capacity(1024); buf.

What is u8 in Rust?

u8 : The 8-bit unsigned integer type. u16 : The 16-bit unsigned integer type. u32 : The 32-bit unsigned integer type. u64 : The 64-bit unsigned integer type.


1 Answers

You cannot. Checking the docs for io::Bytes, there are no appropriate methods. That's because io::Bytes is an iterator that returns things byte-by-byte so there may not even be a single underlying slice of data.

It you only had io::Bytes, you would need to collect the iterator into a Vec:

let data: Result<Vec<_>, _> = resp.bytes().collect();
let data = data.expect("Unable to read data");
f.write_all(&data).expect("Unable to write data");

However, in most cases you have access to the type that implements Read, so you could instead use Read::read_to_end:

let mut data = Vec::new();
resp.read_to_end(&mut data).expect("Unable to read data");
f.write_all(&data).expect("Unable to write data");

In this specific case, you can use io::copy to directly copy from the Request to the file because Request implements io::Read and File implements io::Write:

extern crate reqwest;

use std::io;
use std::fs::File;

fn main() {
    let mut resp = reqwest::get("https://www.rust-lang.org").unwrap();
    assert!(resp.status().is_success());

    // Write contents to disk.
    let mut f = File::create("download_file").expect("Unable to create file");
    io::copy(&mut resp, &mut f).expect("Unable to copy data");
}
like image 184
Shepmaster Avatar answered Oct 24 '22 08:10

Shepmaster