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

1

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()
}
Staal answered 18/12, 2018 at 21:42 Comment(1)
What should happen if the bytes aren't valid UTF8?Urger
L
20

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.

Laminar answered 18/12, 2018 at 21:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.