http icon indicating copy to clipboard operation
http copied to clipboard

add `TryFrom<Cow<'static, str>>` for `HeaderName`/`HeaderValue`

Open hawkw opened this issue 4 years ago • 1 comments

When a string value may be a constant or may be formatted dynamically, it's often useful to use std::borrow::Cow to represent that value. That way, when the string is a constant, a new String does not have to be allocated. If a Cow is used to represent a string that will later be used as an HTTP header name or value, we would prefer to continue not allocating when it is static.

This commit adds TryFrom<Cow<'static, str>> implementations for the HeaderName and HeaderValue types. These conversions call HeaderName/HeaderValue::from_static when the Cow is Borrowed, and convert the string into a HeaderName/HeaderValue when the Cow is owned. This allows &'static strs to be converted to headers without needing to allocate.

Of course, user code can also implement the same match that I wrote in these TryFrom impls, but having TryFrom implementations in http should make this require less effort and hopefully encourage users to use Cows where possible.

hawkw avatar Sep 09 '21 21:09 hawkw

Just wanted to say that I hit this today and was very surprised Cow did not work as a header (value in my case), as it usually works fine.

While I didn't hit that, I think it'd also make sense to implement for Cow<'_, &[u8]> since HeaderName/HeaderValue also implement both TryFrom &[u8] and TryFrom Vec<u8>.

xmo-odoo avatar Nov 13 '23 12:11 xmo-odoo