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()
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With