Skip to main content

ntex_http/
value.rs

1#![allow(
2    clippy::should_implement_trait,
3    clippy::no_effect,
4    clippy::missing_safety_doc
5)]
6use std::{cmp, fmt, hash, str, str::FromStr};
7
8use ntex_bytes::{ByteString, Bytes, BytesMut};
9
10/// Represents an HTTP header field value.
11///
12/// In practice, HTTP header field values are usually valid ASCII. However, the
13/// HTTP spec allows for a header value to contain opaque bytes as well. In this
14/// case, the header field value is not able to be represented as a string.
15///
16/// To handle this, the `HeaderValue` is usable as a type and can be compared
17/// with strings and implements `Debug`. [`to_str`](Self::to_str) returns an
18/// error if the value is not valid UTF-8.
19#[derive(Clone, Eq)]
20pub struct HeaderValue {
21    inner: Bytes,
22    is_sensitive: bool,
23}
24
25#[derive(thiserror::Error, Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
26#[error("Invalid HTTP header value")]
27/// A possible error when converting a `HeaderValue` from a string or byte
28/// slice.
29pub struct InvalidHeaderValue {
30    _priv: (),
31}
32
33/// A possible error when converting a `HeaderValue` to a string representation.
34///
35/// Header field values may contain opaque bytes, in which case it is not
36/// possible to represent the value as a string. Returned if the value is not
37/// valid UTF-8.
38#[derive(thiserror::Error, Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
39#[error("failed to convert header to a str")]
40pub struct ToStrError {
41    _priv: (),
42}
43
44impl HeaderValue {
45    /// Convert a static string to a `HeaderValue`.
46    ///
47    /// This function will not perform any copying, however the string is
48    /// checked to ensure that no invalid characters are present. Only HTAB and
49    /// visible ASCII characters (32-126) are permitted.
50    ///
51    /// # Panics
52    ///
53    /// This function panics if the argument contains invalid header value
54    /// characters.
55    ///
56    /// # Examples
57    ///
58    /// ```
59    /// # use ntex_http::header::HeaderValue;
60    /// let val = HeaderValue::from_static("hello");
61    /// assert_eq!(val, "hello");
62    /// ```
63    #[inline]
64    pub const fn from_static(src: &'static str) -> HeaderValue {
65        let bytes = src.as_bytes();
66        let mut i = 0;
67        while i < bytes.len() {
68            assert!(is_visible_ascii(bytes[i]), "invalid header value");
69            i += 1;
70        }
71
72        HeaderValue {
73            inner: Bytes::from_static(bytes),
74            is_sensitive: false,
75        }
76    }
77
78    /// Attempt to convert a string to a `HeaderValue`.
79    ///
80    /// If the argument contains invalid header value characters, an error is
81    /// returned. The same bytes as in [`from_bytes`](Self::from_bytes) are
82    /// permitted, so non-ASCII characters are accepted.
83    ///
84    /// # Examples
85    ///
86    /// ```
87    /// # use ntex_http::header::HeaderValue;
88    /// let val = HeaderValue::from_str("hello").unwrap();
89    /// assert_eq!(val, "hello");
90    ///
91    /// let val = HeaderValue::from_str("caf\u{e9}").unwrap();
92    /// assert_eq!(val.to_str().unwrap(), "caf\u{e9}");
93    /// ```
94    ///
95    /// An invalid value
96    ///
97    /// ```
98    /// # use ntex_http::header::HeaderValue;
99    /// let val = HeaderValue::from_str("\n");
100    /// assert!(val.is_err());
101    /// ```
102    #[inline]
103    pub fn from_str(src: &str) -> Result<HeaderValue, InvalidHeaderValue> {
104        HeaderValue::try_from_generic(src, |s| Bytes::copy_from_slice(s.as_bytes()))
105    }
106
107    /// Attempt to convert a byte slice to a `HeaderValue`.
108    ///
109    /// If the argument contains invalid header value bytes, an error is
110    /// returned. Only HTAB and byte values between 32 and 255 (inclusive) are
111    /// permitted, excluding byte 127 (DEL).
112    ///
113    /// # Examples
114    ///
115    /// ```
116    /// # use ntex_http::header::HeaderValue;
117    /// let val = HeaderValue::from_bytes(b"hello\xfa").unwrap();
118    /// assert_eq!(val, &b"hello\xfa"[..]);
119    /// ```
120    ///
121    /// An invalid value
122    ///
123    /// ```
124    /// # use ntex_http::header::HeaderValue;
125    /// let val = HeaderValue::from_bytes(b"\n");
126    /// assert!(val.is_err());
127    /// ```
128    #[inline]
129    pub fn from_bytes(src: &[u8]) -> Result<HeaderValue, InvalidHeaderValue> {
130        HeaderValue::try_from_generic(src, Bytes::copy_from_slice)
131    }
132
133    /// Attempt to convert a `Bytes` buffer to a `HeaderValue`.
134    ///
135    /// The conversion avoids copying when `src` can be converted into the
136    /// internal [`Bytes`] representation without allocation. The same bytes as
137    /// in [`from_bytes`](Self::from_bytes) are permitted.
138    pub fn from_shared<T>(src: T) -> Result<HeaderValue, InvalidHeaderValue>
139    where
140        Bytes: From<T>,
141    {
142        let inner = Bytes::from(src);
143        for &b in inner.as_ref() {
144            if !is_valid(b) {
145                return Err(InvalidHeaderValue { _priv: () });
146            }
147        }
148
149        Ok(HeaderValue {
150            inner,
151            is_sensitive: false,
152        })
153    }
154
155    /// Creates a header value from bytes without validation.
156    ///
157    /// # Safety
158    ///
159    /// `src` must contain only bytes allowed in an HTTP header field value:
160    /// HTAB and bytes 32 through 255, excluding 127.
161    pub unsafe fn from_shared_unchecked(src: Bytes) -> HeaderValue {
162        HeaderValue {
163            inner: src,
164            is_sensitive: false,
165        }
166    }
167
168    fn try_from_generic<T: AsRef<[u8]>, F: FnOnce(T) -> Bytes>(
169        src: T,
170        into: F,
171    ) -> Result<HeaderValue, InvalidHeaderValue> {
172        for &b in src.as_ref() {
173            if !is_valid(b) {
174                return Err(InvalidHeaderValue { _priv: () });
175            }
176        }
177        Ok(HeaderValue {
178            inner: into(src),
179            is_sensitive: false,
180        })
181    }
182
183    /// Yields a `&str` slice if the `HeaderValue` is valid UTF-8.
184    ///
185    /// This function validates the whole header value as UTF-8. Unlike the
186    /// `http` crate, which accepts only visible ASCII, non-ASCII UTF-8 such as
187    /// `café` succeeds. Check [`str::is_ascii`] on the result if a value must be
188    /// ASCII.
189    ///
190    /// # Examples
191    ///
192    /// ```
193    /// # use ntex_http::header::HeaderValue;
194    /// let val = HeaderValue::from_static("hello");
195    /// assert_eq!(val.to_str().unwrap(), "hello");
196    ///
197    /// let val = HeaderValue::from_bytes(b"caf\xe9").unwrap();
198    /// assert!(val.to_str().is_err());
199    /// ```
200    pub fn to_str(&self) -> Result<&str, ToStrError> {
201        simdutf8::basic::from_utf8(self.as_ref()).map_err(|_| ToStrError { _priv: () })
202    }
203
204    /// Returns the length of `self`.
205    ///
206    /// This length is in bytes.
207    ///
208    /// # Examples
209    ///
210    /// ```
211    /// # use ntex_http::header::HeaderValue;
212    /// let val = HeaderValue::from_static("hello");
213    /// assert_eq!(val.len(), 5);
214    /// ```
215    #[inline]
216    pub fn len(&self) -> usize {
217        self.as_ref().len()
218    }
219
220    /// Returns `true` if the header value is empty.
221    ///
222    /// # Examples
223    ///
224    /// ```
225    /// # use ntex_http::header::HeaderValue;
226    /// let val = HeaderValue::from_static("");
227    /// assert!(val.is_empty());
228    ///
229    /// let val = HeaderValue::from_static("hello");
230    /// assert!(!val.is_empty());
231    /// ```
232    #[inline]
233    pub fn is_empty(&self) -> bool {
234        self.len() == 0
235    }
236
237    /// Returns the header value as a byte slice.
238    ///
239    /// # Examples
240    ///
241    /// ```
242    /// # use ntex_http::header::HeaderValue;
243    /// let val = HeaderValue::from_static("hello");
244    /// assert_eq!(val.as_bytes(), b"hello");
245    /// ```
246    #[inline]
247    pub fn as_bytes(&self) -> &[u8] {
248        self.as_ref()
249    }
250
251    /// Returns the underlying shared byte buffer.
252    ///
253    /// # Examples
254    ///
255    /// ```
256    /// # use ntex_http::header::HeaderValue;
257    /// # use ntex_bytes::Bytes;
258    /// let val = HeaderValue::from_static("hello");
259    /// assert_eq!(val.as_shared(), &Bytes::from_static(b"hello"));
260    /// ```
261    #[inline]
262    pub fn as_shared(&self) -> &Bytes {
263        &self.inner
264    }
265
266    /// Marks whether the header value contains sensitive information.
267    ///
268    /// # Examples
269    ///
270    /// ```
271    /// # use ntex_http::header::HeaderValue;
272    /// let mut val = HeaderValue::from_static("my secret");
273    ///
274    /// val.set_sensitive(true);
275    /// assert!(val.is_sensitive());
276    ///
277    /// val.set_sensitive(false);
278    /// assert!(!val.is_sensitive());
279    /// ```
280    #[inline]
281    pub fn set_sensitive(&mut self, val: bool) {
282        self.is_sensitive = val;
283    }
284
285    /// Returns `true` if the value represents sensitive data.
286    ///
287    /// Sensitive data could represent passwords or other data that should not
288    /// be stored on disk or in memory. By marking header values as sensitive,
289    /// components using this crate can be instructed to treat them with special
290    /// care for security reasons. For example, caches can avoid storing
291    /// sensitive values, and HPACK encoders used by HTTP/2.0 implementations
292    /// can choose not to compress them.
293    ///
294    /// Additionally, sensitive values will be masked by the `Debug`
295    /// implementation of `HeaderValue`.
296    ///
297    /// Note that sensitivity is not factored into equality or ordering.
298    ///
299    /// # Examples
300    ///
301    /// ```
302    /// # use ntex_http::header::HeaderValue;
303    /// let mut val = HeaderValue::from_static("my secret");
304    ///
305    /// val.set_sensitive(true);
306    /// assert!(val.is_sensitive());
307    ///
308    /// val.set_sensitive(false);
309    /// assert!(!val.is_sensitive());
310    /// ```
311    #[inline]
312    pub fn is_sensitive(&self) -> bool {
313        self.is_sensitive
314    }
315}
316
317impl AsRef<[u8]> for HeaderValue {
318    #[inline]
319    fn as_ref(&self) -> &[u8] {
320        self.inner.as_ref()
321    }
322}
323
324impl fmt::Debug for HeaderValue {
325    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326        if self.is_sensitive {
327            f.write_str("Sensitive")
328        } else {
329            f.write_str("\"")?;
330            let mut from = 0;
331            let bytes = self.as_bytes();
332            for (i, &b) in bytes.iter().enumerate() {
333                if !is_visible_ascii(b) || b == b'"' {
334                    if from != i {
335                        f.write_str(visible_ascii(&bytes[from..i])?)?;
336                    }
337                    if b == b'"' {
338                        f.write_str("\\\"")?;
339                    } else {
340                        write!(f, "\\x{b:x}")?;
341                    }
342                    from = i + 1;
343                }
344            }
345
346            f.write_str(visible_ascii(&bytes[from..])?)?;
347            f.write_str("\"")
348        }
349    }
350}
351
352/// Converts a run of visible ASCII bytes collected by `HeaderValue`'s `Debug` impl.
353fn visible_ascii(bytes: &[u8]) -> Result<&str, fmt::Error> {
354    str::from_utf8(bytes).map_err(|_| fmt::Error)
355}
356
357impl FromStr for HeaderValue {
358    type Err = InvalidHeaderValue;
359
360    #[inline]
361    fn from_str(s: &str) -> Result<HeaderValue, Self::Err> {
362        HeaderValue::from_str(s)
363    }
364}
365
366impl<'a> From<&'a HeaderValue> for HeaderValue {
367    #[inline]
368    fn from(t: &'a HeaderValue) -> Self {
369        t.clone()
370    }
371}
372
373impl From<http::header::HeaderValue> for HeaderValue {
374    #[inline]
375    fn from(t: http::header::HeaderValue) -> Self {
376        let inner = Bytes::copy_from_slice(t.as_ref());
377        HeaderValue {
378            inner,
379            is_sensitive: t.is_sensitive(),
380        }
381    }
382}
383
384impl<'a> From<&'a http::header::HeaderValue> for HeaderValue {
385    #[inline]
386    fn from(t: &'a http::header::HeaderValue) -> Self {
387        let inner = Bytes::copy_from_slice(t.as_ref());
388        HeaderValue {
389            inner,
390            is_sensitive: t.is_sensitive(),
391        }
392    }
393}
394
395impl<'a> TryFrom<&'a str> for HeaderValue {
396    type Error = InvalidHeaderValue;
397
398    #[inline]
399    fn try_from(t: &'a str) -> Result<Self, Self::Error> {
400        t.parse()
401    }
402}
403
404impl<'a> TryFrom<&'a String> for HeaderValue {
405    type Error = InvalidHeaderValue;
406    #[inline]
407    fn try_from(s: &'a String) -> Result<Self, Self::Error> {
408        Self::from_bytes(s.as_bytes())
409    }
410}
411
412impl<'a> TryFrom<&'a ByteString> for HeaderValue {
413    type Error = InvalidHeaderValue;
414    #[inline]
415    fn try_from(s: &'a ByteString) -> Result<Self, Self::Error> {
416        Self::from_shared(s.as_bytes().clone())
417    }
418}
419
420impl<'a> TryFrom<&'a [u8]> for HeaderValue {
421    type Error = InvalidHeaderValue;
422
423    #[inline]
424    fn try_from(t: &'a [u8]) -> Result<Self, Self::Error> {
425        HeaderValue::from_bytes(t)
426    }
427}
428
429impl TryFrom<String> for HeaderValue {
430    type Error = InvalidHeaderValue;
431
432    #[inline]
433    fn try_from(s: String) -> Result<Self, Self::Error> {
434        HeaderValue::from_shared(s)
435    }
436}
437
438impl TryFrom<ByteString> for HeaderValue {
439    type Error = InvalidHeaderValue;
440    #[inline]
441    fn try_from(s: ByteString) -> Result<Self, Self::Error> {
442        Self::from_shared(s.into_bytes())
443    }
444}
445
446impl TryFrom<Vec<u8>> for HeaderValue {
447    type Error = InvalidHeaderValue;
448
449    #[inline]
450    fn try_from(vec: Vec<u8>) -> Result<Self, Self::Error> {
451        HeaderValue::from_shared(vec)
452    }
453}
454
455impl TryFrom<Bytes> for HeaderValue {
456    type Error = InvalidHeaderValue;
457
458    #[inline]
459    fn try_from(bytes: Bytes) -> Result<Self, Self::Error> {
460        HeaderValue::from_shared(bytes)
461    }
462}
463
464impl TryFrom<BytesMut> for HeaderValue {
465    type Error = InvalidHeaderValue;
466
467    #[inline]
468    fn try_from(bytes: BytesMut) -> Result<Self, Self::Error> {
469        HeaderValue::from_shared(bytes)
470    }
471}
472
473impl From<HeaderValue> for http::header::HeaderValue {
474    #[inline]
475    fn from(t: HeaderValue) -> Self {
476        let mut hdr = Self::from_bytes(t.as_bytes()).unwrap();
477        hdr.set_sensitive(t.is_sensitive());
478        hdr
479    }
480}
481
482impl<'a> From<&'a HeaderValue> for http::header::HeaderValue {
483    #[inline]
484    fn from(t: &'a HeaderValue) -> Self {
485        let mut hdr = Self::from_bytes(t.as_bytes()).unwrap();
486        hdr.set_sensitive(t.is_sensitive());
487        hdr
488    }
489}
490
491const fn is_visible_ascii(b: u8) -> bool {
492    b >= 32 && b < 127 || b == b'\t'
493}
494
495#[inline]
496fn is_valid(b: u8) -> bool {
497    b >= 32 && b != 127 || b == b'\t'
498}
499
500// ===== Hash / PartialEq / PartialOrd =====
501
502// Must agree with `PartialEq`, which ignores the sensitive flag
503impl hash::Hash for HeaderValue {
504    #[inline]
505    fn hash<H: hash::Hasher>(&self, state: &mut H) {
506        self.inner.hash(state);
507    }
508}
509
510impl PartialEq for HeaderValue {
511    #[inline]
512    fn eq(&self, other: &HeaderValue) -> bool {
513        self.inner == other.inner
514    }
515}
516
517impl PartialOrd for HeaderValue {
518    #[inline]
519    fn partial_cmp(&self, other: &HeaderValue) -> Option<cmp::Ordering> {
520        Some(self.cmp(other))
521    }
522}
523
524impl Ord for HeaderValue {
525    #[inline]
526    fn cmp(&self, other: &Self) -> cmp::Ordering {
527        self.inner.cmp(&other.inner)
528    }
529}
530
531impl PartialEq<str> for HeaderValue {
532    #[inline]
533    fn eq(&self, other: &str) -> bool {
534        self.inner == other.as_bytes()
535    }
536}
537
538impl PartialEq<[u8]> for HeaderValue {
539    #[inline]
540    fn eq(&self, other: &[u8]) -> bool {
541        self.inner == other
542    }
543}
544
545impl PartialOrd<str> for HeaderValue {
546    #[inline]
547    fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
548        (*self.inner).partial_cmp(other.as_bytes())
549    }
550}
551
552impl PartialOrd<[u8]> for HeaderValue {
553    #[inline]
554    fn partial_cmp(&self, other: &[u8]) -> Option<cmp::Ordering> {
555        (*self.inner).partial_cmp(other)
556    }
557}
558
559impl PartialEq<HeaderValue> for str {
560    #[inline]
561    fn eq(&self, other: &HeaderValue) -> bool {
562        *other == *self
563    }
564}
565
566impl PartialEq<HeaderValue> for [u8] {
567    #[inline]
568    fn eq(&self, other: &HeaderValue) -> bool {
569        *other == *self
570    }
571}
572
573impl PartialOrd<HeaderValue> for str {
574    #[inline]
575    fn partial_cmp(&self, other: &HeaderValue) -> Option<cmp::Ordering> {
576        self.as_bytes().partial_cmp(other.as_bytes())
577    }
578}
579
580impl PartialOrd<HeaderValue> for [u8] {
581    #[inline]
582    fn partial_cmp(&self, other: &HeaderValue) -> Option<cmp::Ordering> {
583        self.partial_cmp(other.as_bytes())
584    }
585}
586
587impl PartialEq<String> for HeaderValue {
588    #[inline]
589    fn eq(&self, other: &String) -> bool {
590        *self == other[..]
591    }
592}
593
594impl PartialOrd<String> for HeaderValue {
595    #[inline]
596    fn partial_cmp(&self, other: &String) -> Option<cmp::Ordering> {
597        self.inner.partial_cmp(other.as_bytes())
598    }
599}
600
601impl PartialEq<HeaderValue> for String {
602    #[inline]
603    fn eq(&self, other: &HeaderValue) -> bool {
604        *other == *self
605    }
606}
607
608impl PartialOrd<HeaderValue> for String {
609    #[inline]
610    fn partial_cmp(&self, other: &HeaderValue) -> Option<cmp::Ordering> {
611        self.as_bytes().partial_cmp(other.as_bytes())
612    }
613}
614
615impl PartialEq<HeaderValue> for &HeaderValue {
616    #[inline]
617    fn eq(&self, other: &HeaderValue) -> bool {
618        **self == *other
619    }
620}
621
622impl PartialOrd<HeaderValue> for &HeaderValue {
623    #[inline]
624    fn partial_cmp(&self, other: &HeaderValue) -> Option<cmp::Ordering> {
625        (**self).partial_cmp(other)
626    }
627}
628
629impl<'a, T: ?Sized> PartialEq<&'a T> for HeaderValue
630where
631    HeaderValue: PartialEq<T>,
632{
633    #[inline]
634    fn eq(&self, other: &&'a T) -> bool {
635        *self == **other
636    }
637}
638
639impl<'a, T: ?Sized> PartialOrd<&'a T> for HeaderValue
640where
641    HeaderValue: PartialOrd<T>,
642{
643    #[inline]
644    fn partial_cmp(&self, other: &&'a T) -> Option<cmp::Ordering> {
645        self.partial_cmp(*other)
646    }
647}
648
649impl PartialEq<HeaderValue> for &str {
650    #[inline]
651    fn eq(&self, other: &HeaderValue) -> bool {
652        *other == *self
653    }
654}
655
656impl PartialOrd<HeaderValue> for &str {
657    #[inline]
658    fn partial_cmp(&self, other: &HeaderValue) -> Option<cmp::Ordering> {
659        self.as_bytes().partial_cmp(other.as_bytes())
660    }
661}
662
663macro_rules! from_integers {
664    ($($name:ident: $t:ident => $max_len:expr),*) => {$(
665        impl From<$t> for HeaderValue {
666            fn from(num: $t) -> HeaderValue {
667                let mut b = itoa::Buffer::new();
668                let inner = Bytes::copy_from_slice(b.format(num).as_ref());
669                HeaderValue {
670                    inner,
671                    is_sensitive: false,
672                }
673            }
674        }
675
676        /// STATEMENT: `HeaderValue::from` for each integer type writes the decimal form, including
677        /// the type's maximum value.
678        ///
679        /// HOW:
680        /// - Convert 55 and `MAX` of the integer type.
681        /// - Expect each value to equal `to_string()` of the number.
682        #[test]
683        fn $name() {
684            let n: $t = 55;
685            let val = HeaderValue::from(n);
686            assert_eq!(val, &n.to_string());
687
688            let n = $t::MAX;
689            let val = HeaderValue::from(n);
690            assert_eq!(val, &n.to_string());
691        }
692    )*};
693}
694
695from_integers! {
696    // integer type => maximum decimal length
697
698    // u8 purposely left off... HeaderValue::from(b'3') could be confusing
699    from_u16: u16 => 5,
700    from_i16: i16 => 6,
701    from_u32: u32 => 10,
702    from_i32: i32 => 11,
703    from_u64: u64 => 20,
704    from_i64: i64 => 20
705}
706
707#[cfg(target_pointer_width = "16")]
708from_integers! {
709    from_usize: usize => 5,
710    from_isize: isize => 6
711}
712
713#[cfg(target_pointer_width = "32")]
714from_integers! {
715    from_usize: usize => 10,
716    from_isize: isize => 11
717}
718
719#[cfg(target_pointer_width = "64")]
720from_integers! {
721    from_usize: usize => 20,
722    from_isize: isize => 20
723}
724
725#[cfg(test)]
726mod tests {
727    use super::*;
728
729    /// STATEMENT: The sensitive flag affects neither equality nor the hash of a `HeaderValue`.
730    ///
731    /// HOW:
732    /// - Clone a value and mark the clone sensitive.
733    /// - Expect both values equal and with the same `RandomState` hash.
734    #[test]
735    fn test_hash_ignores_sensitive() {
736        use std::hash::{BuildHasher, RandomState};
737
738        let state = RandomState::new();
739        let hdr = HeaderValue::from_static("secret");
740        let mut sensitive = hdr.clone();
741        sensitive.set_sensitive(true);
742        assert_eq!(hdr, sensitive);
743        assert_eq!(state.hash_one(&hdr), state.hash_one(&sensitive));
744    }
745
746    /// STATEMENT: `HeaderValue` built by every constructor and conversion holds the same bytes,
747    /// and compares with strings and byte slices in both directions.
748    ///
749    /// HOW:
750    /// - Build values from bytes, `Bytes`, `http::HeaderValue`, `String`, `&String` and
751    ///   `ByteString`; expect the same bytes.
752    /// - Compare with `&str`, `String` and `&[u8]` for equality and ordering, both ways.
753    #[test]
754    #[allow(clippy::op_ref, clippy::cmp_owned)]
755    fn test_basics() {
756        assert!(HeaderValue::from_str("").unwrap().is_empty());
757
758        let hdr = HeaderValue::from_bytes(b"upgrade").unwrap();
759        let hdr2 = HeaderValue::from(&hdr);
760        assert_eq!(hdr, hdr2);
761
762        let hdr3 = HeaderValue::from_shared(Bytes::from_static(b"upgrade")).unwrap();
763        assert_eq!(hdr, hdr3);
764
765        let hdr = http::header::HeaderValue::from_bytes(b"upgrade").unwrap();
766        let hdr2 = HeaderValue::from(&hdr);
767        assert_eq!(hdr2.as_bytes(), b"upgrade");
768        assert_eq!(hdr2.as_shared(), &Bytes::from_static(b"upgrade"));
769        let hdr2 = HeaderValue::from(hdr);
770        assert_eq!(hdr2.as_bytes(), b"upgrade");
771
772        let hdr = HeaderValue::try_from("upgrade".to_string()).unwrap();
773        assert_eq!(hdr.as_bytes(), b"upgrade");
774        let hdr = HeaderValue::try_from(&("upgrade".to_string())).unwrap();
775        assert_eq!(hdr.as_bytes(), b"upgrade");
776        let hdr = HeaderValue::try_from(ByteString::from("upgrade")).unwrap();
777        assert_eq!(hdr.as_bytes(), b"upgrade");
778        let hdr = HeaderValue::try_from(&ByteString::from("upgrade")).unwrap();
779        assert_eq!(hdr.as_bytes(), b"upgrade");
780        let hdr2 = HeaderValue::try_from(&ByteString::from("upgrade2")).unwrap();
781
782        assert_eq!(hdr, hdr);
783        assert_eq!(hdr, &hdr);
784        assert_eq!(hdr, "upgrade");
785        assert_eq!(hdr, "upgrade".to_string());
786        assert_eq!(hdr, b"upgrade".as_ref());
787        assert_eq!("upgrade", hdr);
788        assert_eq!("upgrade", &hdr);
789        assert_eq!("upgrade".to_string(), hdr);
790        assert_eq!(b"upgrade".as_ref(), &hdr);
791        assert!(hdr < hdr2);
792        assert!(hdr < &hdr2);
793        assert!(&hdr < &hdr2);
794        assert!(hdr2 > hdr);
795        assert!(&hdr2 > hdr);
796        assert!(&hdr < "upgrade2");
797        assert!(hdr < "upgrade2");
798        assert!(hdr < "upgrade2".to_string());
799        assert!(hdr < &b"upgrade2"[..]);
800        assert!(hdr < b"upgrade2"[..]);
801        assert_ne!(hdr, &b"upgrade2"[..]);
802        assert_ne!(hdr, b"upgrade2"[..]);
803        assert!("upgrade2" > hdr);
804        assert!("upgrade2" > &hdr);
805        assert!("upgrade2".to_string() > hdr);
806        assert!(b"upgrade2"[..] > hdr);
807        assert_ne!("upgrade2"[..], hdr);
808    }
809
810    /// STATEMENT: `TryFrom` for `Vec<u8>`, `Bytes` and `BytesMut` rejects invalid header bytes.
811    ///
812    /// HOW:
813    /// - Convert a vector containing byte 127; expect an error.
814    /// - Convert `upgrade` and `\n` from `Bytes` and `BytesMut`; expect success and an error.
815    #[test]
816    fn test_try_from() {
817        HeaderValue::try_from(vec![127]).unwrap_err();
818
819        let hdr = HeaderValue::try_from(Bytes::from_static(b"upgrade")).unwrap();
820        assert_eq!(hdr, "upgrade");
821        HeaderValue::try_from(Bytes::from_static(b"\n")).unwrap_err();
822        let hdr = HeaderValue::try_from(BytesMut::copy_from_slice(b"upgrade")).unwrap();
823        assert_eq!(hdr, "upgrade");
824        HeaderValue::try_from(BytesMut::copy_from_slice(b"\n")).unwrap_err();
825    }
826
827    /// STATEMENT: Converting a `HeaderValue` into `http::HeaderValue`, by reference or by
828    /// value, keeps its bytes and its sensitive flag.
829    ///
830    /// HOW:
831    /// - Mark a value sensitive, convert it by reference and by value, and check both results
832    ///   have the same bytes and are sensitive.
833    /// - Convert a plain value and check the result is not sensitive.
834    #[test]
835    fn into_http_value() {
836        let mut hdr = HeaderValue::from_bytes(b"upgrade").unwrap();
837        hdr.set_sensitive(true);
838
839        let by_ref = http::header::HeaderValue::from(&hdr);
840        assert_eq!(by_ref.as_bytes(), b"upgrade");
841        assert!(by_ref.is_sensitive());
842
843        let by_val = http::header::HeaderValue::from(hdr);
844        assert_eq!(by_val.as_bytes(), b"upgrade");
845        assert!(by_val.is_sensitive());
846
847        let plain = http::header::HeaderValue::from(HeaderValue::from_static("plain"));
848        assert_eq!(plain.as_bytes(), b"plain");
849        assert!(!plain.is_sensitive());
850    }
851
852    /// STATEMENT: `HeaderValue` `Debug` quotes and escapes the value and hides sensitive values.
853    ///
854    /// HOW:
855    /// - Format plain, quoted and non-ASCII values; expect the escaped strings.
856    /// - Format a sensitive value; expect `Sensitive`.
857    #[test]
858    fn test_fmt() {
859        let cases = &[
860            ("hello", "\"hello\""),
861            ("hello \"world\"", "\"hello \\\"world\\\"\""),
862            ("\u{7FFF}hello", "\"\\xe7\\xbf\\xbfhello\""),
863        ];
864
865        for &(value, expected) in cases {
866            let val = HeaderValue::from_bytes(value.as_bytes()).unwrap();
867            let actual = format!("{val:?}");
868            assert_eq!(expected, actual);
869        }
870
871        let mut sensitive = HeaderValue::from_static("password");
872        sensitive.set_sensitive(true);
873        assert_eq!("Sensitive", format!("{sensitive:?}"));
874    }
875
876    /// STATEMENT: `HeaderValue::from_static` panics on invalid bytes.
877    ///
878    /// HOW:
879    /// - Pass a runtime string containing `\n`.
880    /// - Expect a panic with `invalid header value`.
881    #[test]
882    #[should_panic(expected = "invalid header value")]
883    fn from_static_invalid() {
884        let src: &'static str = std::hint::black_box("bad\nvalue");
885        let _ = HeaderValue::from_static(src);
886    }
887}