Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a bytes::Bytes to a &str without making any copies?

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()
}
like image 787
JoshAdel Avatar asked Dec 23 '22 02:12

JoshAdel


1 Answers

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:

  • How do I convert a Vector of bytes (u8) to a string

I've tried &body.into()

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

like image 169
Shepmaster Avatar answered Dec 26 '22 00:12

Shepmaster