headers/util/
value_string.rs1use 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#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub(crate) struct HeaderValueString {
15 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 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 HeaderValueString {
41 value: HeaderValue::from_static(src),
42 }
43 }
44
45 pub(crate) fn as_str(&self) -> &str {
46 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 src.parse()
91 .map(|value| HeaderValueString { value })
92 .map_err(|_| FromStrError(()))
93 }
94}