headers/util/
value_string.rs

1use std::{
2    fmt,
3    str::{self, FromStr},
4};
5
6use bytes::Bytes;
7use http::header::HeaderValue;
8
9use super::IterExt;
10use crate::Error;
11
12/// A value that is both a valid `HeaderValue` and `String`.
13#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub(crate) struct HeaderValueString {
15    /// Care must be taken to only set this value when it is also
16    /// a valid `String`, since `as_str` will convert to a `&str`
17    /// in an unchecked manner.
18    value: HeaderValue,
19}
20
21impl HeaderValueString {
22    pub(crate) fn from_val(val: &HeaderValue) -> Result<Self, Error> {
23        if val.to_str().is_ok() {
24            Ok(HeaderValueString { value: val.clone() })
25        } else {
26            Err(Error::invalid())
27        }
28    }
29
30    pub(crate) fn from_string(src: String) -> Option<Self> {
31        // A valid `str` (the argument)...
32        let bytes = Bytes::from(src);
33        HeaderValue::from_maybe_shared(bytes)
34            .ok()
35            .map(|value| HeaderValueString { value })
36    }
37
38    pub(crate) const fn from_static(src: &'static str) -> HeaderValueString {
39        // A valid `str` (the argument)...
40        HeaderValueString {
41            value: HeaderValue::from_static(src),
42        }
43    }
44
45    pub(crate) fn as_str(&self) -> &str {
46        // HeaderValueString is only created from HeaderValues
47        // that have validated they are also UTF-8 strings.
48        unsafe { str::from_utf8_unchecked(self.value.as_bytes()) }
49    }
50}
51
52impl fmt::Debug for HeaderValueString {
53    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54        fmt::Debug::fmt(self.as_str(), f)
55    }
56}
57
58impl fmt::Display for HeaderValueString {
59    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60        fmt::Display::fmt(self.as_str(), f)
61    }
62}
63
64impl super::TryFromValues for HeaderValueString {
65    fn try_from_values<'i, I>(values: &mut I) -> Result<Self, Error>
66    where
67        I: Iterator<Item = &'i HeaderValue>,
68    {
69        values
70            .just_one()
71            .map(HeaderValueString::from_val)
72            .unwrap_or_else(|| Err(Error::invalid()))
73    }
74}
75
76impl<'a> From<&'a HeaderValueString> for HeaderValue {
77    fn from(src: &'a HeaderValueString) -> HeaderValue {
78        src.value.clone()
79    }
80}
81
82#[derive(Debug)]
83pub(crate) struct FromStrError(());
84
85impl FromStr for HeaderValueString {
86    type Err = FromStrError;
87
88    fn from_str(src: &str) -> Result<Self, Self::Err> {
89        // A valid `str` (the argument)...
90        src.parse()
91            .map(|value| HeaderValueString { value })
92            .map_err(|_| FromStrError(()))
93    }
94}