如何在不制作任何副本的情况下将字节::字节转换为 &str?



i具有 bytes::Bytes(在这种情况下为actix-web中的一个请求主体)和另一个期望字符串slice参数的函数: foo: &str。将bytes::Bytes转换为&str的正确方法是什么,以免副本进行副本?我尝试了&body.into(),但我得到了:

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

这是基本功能签名:

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[u8]的删除,因此您可以使用任何现有机制将&[u8]转换为字符串。

use bytes::Bytes; // 0.4.10
use std::str;
fn example(b: &Bytes) -> Result<&str, str::Utf8Error> {
    str::from_utf8(b)
}

另请参见:

  • 如何将字节向量(U8)转换为字符串

我已经尝试了&body.into()

FromInto仅适用于可靠的转换。并非所有任意数据的数据都是有效的UTF-8。

最新更新