actix_http/header/
utils.rs

1//! Header parsing utilities.
2
3use std::{fmt, str::FromStr};
4
5use super::HeaderValue;
6use crate::{error::ParseError, header::HTTP_VALUE};
7
8/// Reads a comma-delimited raw header into a Vec.
9#[inline]
10pub fn from_comma_delimited<'a, I, T>(all: I) -> Result<Vec<T>, ParseError>
11where
12    I: Iterator<Item = &'a HeaderValue> + 'a,
13    T: FromStr,
14{
15    let size_guess = all.size_hint().1.unwrap_or(2);
16    let mut result = Vec::with_capacity(size_guess);
17
18    for h in all {
19        let s = h.to_str().map_err(|_| ParseError::Header)?;
20
21        result.extend(
22            s.split(',')
23                .filter_map(|x| match x.trim() {
24                    "" => None,
25                    y => Some(y),
26                })
27                .filter_map(|x| x.trim().parse().ok()),
28        )
29    }
30
31    Ok(result)
32}
33
34/// Reads a single string when parsing a header.
35#[inline]
36pub fn from_one_raw_str<T: FromStr>(val: Option<&HeaderValue>) -> Result<T, ParseError> {
37    if let Some(line) = val {
38        let line = line.to_str().map_err(|_| ParseError::Header)?;
39
40        if !line.is_empty() {
41            return T::from_str(line).or(Err(ParseError::Header));
42        }
43    }
44
45    Err(ParseError::Header)
46}
47
48/// Format an array into a comma-delimited string.
49#[inline]
50pub fn fmt_comma_delimited<T>(f: &mut fmt::Formatter<'_>, parts: &[T]) -> fmt::Result
51where
52    T: fmt::Display,
53{
54    let mut iter = parts.iter();
55
56    if let Some(part) = iter.next() {
57        fmt::Display::fmt(part, f)?;
58    }
59
60    for part in iter {
61        f.write_str(", ")?;
62        fmt::Display::fmt(part, f)?;
63    }
64
65    Ok(())
66}
67
68/// Percent encode a sequence of bytes with a character set defined in [RFC 5987 §3.2].
69///
70/// [RFC 5987 §3.2]: https://datatracker.ietf.org/doc/html/rfc5987#section-3.2
71#[inline]
72pub fn http_percent_encode(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result {
73    let encoded = percent_encoding::percent_encode(bytes, HTTP_VALUE);
74    fmt::Display::fmt(&encoded, f)
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    fn comma_delimited_parsing() {
83        let headers = [];
84        let res: Vec<usize> = from_comma_delimited(headers.iter()).unwrap();
85        assert_eq!(res, vec![0; 0]);
86
87        let headers = [
88            HeaderValue::from_static("1, 2"),
89            HeaderValue::from_static("3,4"),
90        ];
91        let res: Vec<usize> = from_comma_delimited(headers.iter()).unwrap();
92        assert_eq!(res, vec![1, 2, 3, 4]);
93
94        let headers = [
95            HeaderValue::from_static(""),
96            HeaderValue::from_static(","),
97            HeaderValue::from_static("  "),
98            HeaderValue::from_static("1    ,"),
99            HeaderValue::from_static(""),
100        ];
101        let res: Vec<usize> = from_comma_delimited(headers.iter()).unwrap();
102        assert_eq!(res, vec![1]);
103    }
104}