代码之家  ›  专栏  ›  技术社区  ›  JoshAdel

如何在不进行任何复制的情况下将bytes::bytes转换为a&str?

  •  0
  • JoshAdel  · 技术社区  · 6 年前

    我有一个 bytes::Bytes (在本例中,它是actix web中请求的主体)和另一个需要字符串切片参数的函数: foo: &str . 正确的转换方法是什么 字节::字节 &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()
    }
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   Shepmaster Tim Diekmann    6 年前

    Bytes dereferences to [u8] ,因此可以使用任何现有机制来转换 &[u8] 一个字符串。

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

    参见:

    我试过了 &body.into()

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