http icon indicating copy to clipboard operation
http copied to clipboard

A type to represent a valid HeaderValue and String

Open seanmonstar opened this issue 7 years ago • 9 comments

A HeaderValue may not always be a valid UTF-8 String, and so there is a to_str(&self) -> Result<&str, ToStrError> method that validates the bytes first. To create a String, one could instead do String::from_utf8(value.as_bytes()), but once you have that String, you'll need to re-validate it to turn it back into a HeaderValue.

It would be useful to have a type that represents being both a valid HeaderValue and a valid String at the same time. This type would have a free as_str() method, since it's already been validated, and conversely a free into_value() method (again, because it's already validated).

seanmonstar avatar Oct 04 '18 18:10 seanmonstar

Naming is hard, but to keep it simple, it could just be HeaderValueString...

seanmonstar avatar Oct 04 '18 18:10 seanmonstar

Could you provide examples in which HeaderValueString would be helpful?

carllerche avatar Oct 04 '18 18:10 carllerche

As I work on typed headers, a few types are most useful as strings (such as UserAgent). It'd be useful to allow UserAgent::as_str() for free, while still being to able to encode its inner value as a HeaderValue for free.

Other types, while having more specific semantics, still essentially need just a string underneath (like Authorization, Cookie, Server, Referer, and likely others).

seanmonstar avatar Oct 04 '18 18:10 seanmonstar

At what point would the UTF-8 check happen?

carllerche avatar Oct 04 '18 18:10 carllerche

I'd expect the UTF-8 check to happen when parsing to a typed version, so if it weren't valid UTF-8, the typed version would not parse.

// essentially `struct UserAgent(HeaderValueString)`
let ua = req.headers().typed_get::<UserAgent>();
println!("user-agent: {}", ua.as_str());

seanmonstar avatar Oct 04 '18 19:10 seanmonstar

Naming is hard, but to keep it simple, it could just be HeaderValueString...

Another possibility would be Utf8HeaderValue or HeaderValueUtf8. Would make it a little easier to guess what it's about IMHO.

jplatte avatar Oct 04 '18 22:10 jplatte

Another option would be for you to use the String type from the string crate. It would be a private dependency and would not require adding a new type.

You would do String<HeaderValue>.

carllerche avatar Oct 04 '18 23:10 carllerche

Indeed, for now, I've implemented a HeaderValueString externally, it just requires some unsafe blocks. They could be removed if the type were part of http, but it may not be worth it. I'll continue on externally for now.

seanmonstar avatar Oct 05 '18 00:10 seanmonstar

SafeHeaderString or HeaderSafeString ?

hh9527 avatar Mar 05 '19 08:03 hh9527