Skip to main content

rama_http_headers/util/
value_string.rs

1use std::{
2    fmt,
3    str::{self, FromStr},
4};
5
6use rama_core::bytes::Bytes;
7use rama_http_types::header::{HeaderValue, InvalidHeaderValue};
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 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 fn from_val(val: &HeaderValue) -> Result<Self, Error> {
23        if val.to_str().is_ok() {
24            Ok(Self { value: val.clone() })
25        } else {
26            Err(Error::invalid())
27        }
28    }
29
30    #[must_use]
31    pub fn from_string(src: String) -> Option<Self> {
32        // A valid `str` (the argument)...
33        let bytes = Bytes::from(src);
34        HeaderValue::from_maybe_shared(bytes)
35            .ok()
36            .map(|value| Self { value })
37    }
38
39    #[must_use]
40    pub const fn from_static(src: &'static str) -> Self {
41        // A valid `str` (the argument)...
42        Self {
43            value: HeaderValue::from_static(src),
44        }
45    }
46
47    pub fn as_str(&self) -> &str {
48        // HeaderValueString is only created from HeaderValues
49        // that have validated they are also UTF-8 strings.
50        unsafe { str::from_utf8_unchecked(self.value.as_bytes()) }
51    }
52}
53
54impl fmt::Debug for HeaderValueString {
55    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56        fmt::Debug::fmt(self.as_str(), f)
57    }
58}
59
60impl fmt::Display for HeaderValueString {
61    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62        fmt::Display::fmt(self.as_str(), f)
63    }
64}
65
66impl super::TryFromValues for HeaderValueString {
67    fn try_from_values<'i, I>(values: &mut I) -> Result<Self, Error>
68    where
69        I: Iterator<Item = &'i HeaderValue>,
70    {
71        values
72            .just_one()
73            .map(Self::from_val)
74            .unwrap_or_else(|| Err(Error::invalid()))
75    }
76}
77
78impl<'a> From<&'a HeaderValueString> for HeaderValue {
79    fn from(src: &'a HeaderValueString) -> Self {
80        src.value.clone()
81    }
82}
83
84impl FromStr for HeaderValueString {
85    type Err = InvalidHeaderValue;
86
87    fn from_str(src: &str) -> Result<Self, Self::Err> {
88        // A valid `str` (the argument)...
89        src.parse().map(|value| Self { value })
90    }
91}