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)
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。
| 归档时间: |
|
| 查看次数: |
1788 次 |
| 最近记录: |