如何将 bytes::Bytes 转换为 &str 而不进行任何复制?

Jos*_*del 2 type-conversion binary-data rust

我有一个bytes::Bytes(在Actix的的web请求在这种情况下,它的身体),并且需要一个字符串参数切片另一个函数:foo: &str。将 转换bytes::Bytes&str以便不制作副本的正确方法是什么?我试过了,&body.into()但我得到:

the trait `std::convert::From<bytes::bytes::Bytes>` is not implemented for `str`
Run Code Online (Sandbox Code Playgroud)

以下是基本的函数签名:

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()
}
Run Code Online (Sandbox Code Playgroud)

She*_*ter 8

Bytes取消引用[u8],因此您可以使用任何现有机制转换&[u8]为字符串。

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

fn example(b: &Bytes) -> Result<&str, str::Utf8Error> {
    str::from_utf8(b)
}
Run Code Online (Sandbox Code Playgroud)

也可以看看:

我试过了 &body.into()

From并且Into仅用于可靠的转换。并非所有任意数据块都是有效的 UTF-8。