http
http copied to clipboard
Expose `http::byte_str::ByteStr` to the public API
When using the HTTP1.1 protocol, we can convert the entire buffer into bytes:: Bytes, and then convert a portion of it into ByteStr for use (for example, as HeaderName) for zero-copy network programming.I think it's very useful and important
We just need to restore the implementation TryFrom<Bytes>
I don't think we need to expose the actual ByteStr
type. But if there's parts that cannot be created via zero copy, we can add ways.
I have a similar use case for ByteStr
. For given PathAndQuery
type it's possible to match on the path and slice the Bytes to avoid copy.
for example:
fn main() {
use bytes::Bytes;
use http::uri::PathAndQuery;
use std::fmt;
#[derive(Debug)]
struct User {
name: Bytes,
age: Bytes,
}
impl fmt::Display for User {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = std::str::from_utf8(self.name.as_ref()).unwrap();
let age = std::str::from_utf8(self.age.as_ref()).unwrap();
write!(f, "User {{ name: {name}, age: {age} }}")
}
}
let path = PathAndQuery::from_static("/john/21");
let bytes = Bytes::copy_from_slice(path.path().as_bytes()); // if path return ByteStr or Bytes this copy can be elimnated.
let name = bytes.slice(1..=4);
let age = bytes.slice(6..=7);
println!("{}", User { name, age });
}