11

I have a bytes::Bytes (in this case its the body of a request in actix-web) and another function that expects a string slice argument: foo: &str. What is the proper way to convert the bytes::Bytes to &str so that no copy is made? I've tried &body.into() but I get:

the trait `std::convert::From<bytes::bytes::Bytes>` is not implemented for `str`

Here are the basic function signatures:

pub fn parse_body(data: &str) -> Option<&str> {
    // Do stuff
    // ....
    Ok("xyz")
}

fn consume_data(req: HttpRequest<AppState>, body: bytes::Bytes) -> HttpResponse {
    let foo = parse_body(&body);
    // Do stuff
    HttpResponse::Ok().into()
}
Peter Hall
  • 53,120
  • 14
  • 139
  • 204
JoshAdel
  • 66,734
  • 27
  • 141
  • 140

1 Answers1

19

Bytes dereferences to [u8], so you can use any existing mechanism to convert &[u8] to a string.

use bytes::Bytes; // 0.4.10
use std::str;

fn example(b: &Bytes) -> Result<&str, str::Utf8Error> {
    str::from_utf8(b)
}

See also:

I've tried &body.into()

From and Into are only for infallible conversions. Not all arbitrary chunks of data are valid UTF-8.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366