Debian Codegraph @

third_party/rust/headers/src/disabled/util/extended_value.rs

raw
1 /// An extended header parameter value (i.e., tagged with a character set and optionally,
2 /// a language), as defined in [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2).
3 #[derive(Clone, Debug, PartialEq)]
4 pub struct ExtendedValue {
5 /// The character set that is used to encode the `value` to a string.
6 pub charset: Charset,
7 /// The human language details of the `value`, if available.
8 pub language_tag: Option<LanguageTag>,
9 /// The parameter value, as expressed in octets.
10 pub value: Vec<u8>,
11 }
12
13 /// Parses extended header parameter values (`ext-value`), as defined in
14 /// [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2).
15 ///
16 /// Extended values are denoted by parameter names that end with `*`.
17 ///
18 /// ## ABNF
19 ///
20 /// ```text
21 /// ext-value = charset "'" [ language ] "'" value-chars
22 /// ; like RFC 2231's <extended-initial-value>
23 /// ; (see [RFC2231], Section 7)
24 ///
25 /// charset = "UTF-8" / "ISO-8859-1" / mime-charset
26 ///
27 /// mime-charset = 1*mime-charsetc
28 /// mime-charsetc = ALPHA / DIGIT
29 /// / "!" / "#" / "$" / "%" / "&"
30 /// / "+" / "-" / "^" / "_" / "`"
31 /// / "{" / "}" / "~"
32 /// ; as <mime-charset> in Section 2.3 of [RFC2978]
33 /// ; except that the single quote is not included
34 /// ; SHOULD be registered in the IANA charset registry
35 ///
36 /// language = <Language-Tag, defined in [RFC5646], Section 2.1>
37 ///
38 /// value-chars = *( pct-encoded / attr-char )
39 ///
40 /// pct-encoded = "%" HEXDIG HEXDIG
41 /// ; see [RFC3986], Section 2.1
42 ///
43 /// attr-char = ALPHA / DIGIT
44 /// / "!" / "#" / "$" / "&" / "+" / "-" / "."
45 /// / "^" / "_" / "`" / "|" / "~"
46 /// ; token except ( "*" / "'" / "%" )
47 /// ```
48 pub fn parse_extended_value(val: &str) -> ::Result<ExtendedValue> {
49
50 // Break into three pieces separated by the single-quote character
51 let mut parts = val.splitn(3,'\'');
52
53 // Interpret the first piece as a Charset
54 let charset: Charset = match parts.next() {
55 None => return Err(::Error::Header),
56 Some(n) => try!(FromStr::from_str(n)),
57 };
58
59 // Interpret the second piece as a language tag
60 let lang: Option<LanguageTag> = match parts.next() {
61 None => return Err(::Error::Header),
62 Some("") => None,
63 Some(s) => match s.parse() {
64 Ok(lt) => Some(lt),
65 Err(_) => return Err(::Error::Header),
66 }
67 };
68
69 // Interpret the third piece as a sequence of value characters
70 let value: Vec<u8> = match parts.next() {
71 None => return Err(::Error::Header),
72 Some(v) => percent_encoding::percent_decode(v.as_bytes()).collect(),
73 };
74
75 Ok(ExtendedValue {
76 charset: charset,
77 language_tag: lang,
78 value: value,
79 })
80 }
81
82
83 impl Display for ExtendedValue {
84 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85 let encoded_value =
86 percent_encoding::percent_encode(&self.value[..], self::percent_encoding_http::HTTP_VALUE);
87 if let Some(ref lang) = self.language_tag {
88 write!(f, "{}'{}'{}", self.charset, lang, encoded_value)
89 } else {
90 write!(f, "{}''{}", self.charset, encoded_value)
91 }
92 }
93 }
94
95 /// Percent encode a sequence of bytes with a character set defined in
96 /// [https://tools.ietf.org/html/rfc5987#section-3.2][url]
97 ///
98 /// [url]: https://tools.ietf.org/html/rfc5987#section-3.2
99 pub fn http_percent_encode(f: &mut fmt::Formatter, bytes: &[u8]) -> fmt::Result {
100 let encoded = percent_encoding::percent_encode(bytes, self::percent_encoding_http::HTTP_VALUE);
101 fmt::Display::fmt(&encoded, f)
102 }
103
104 mod percent_encoding_http {
105 use percent_encoding;
106
107 // internal module because macro is hard-coded to make a public item
108 // but we don't want to public export this item
109 define_encode_set! {
110 // This encode set is used for HTTP header values and is defined at
111 // https://tools.ietf.org/html/rfc5987#section-3.2
112 pub HTTP_VALUE = [percent_encoding::SIMPLE_ENCODE_SET] | {
113 ' ', '"', '%', '\'', '(', ')', '*', ',', '/', ':', ';', '<', '-', '>', '?',
114 '[', '\\', ']', '{', '}'
115 }
116 }
117 }
118
119 #[cfg(test)]
120 mod tests {
121 use shared::Charset;
122 use super::{ExtendedValue, parse_extended_value};
123 use language_tags::LanguageTag;
124
125 #[test]
126 fn test_parse_extended_value_with_encoding_and_language_tag() {
127 let expected_language_tag = "en".parse::<LanguageTag>().unwrap();
128 // RFC 5987, Section 3.2.2
129 // Extended notation, using the Unicode character U+00A3 (POUND SIGN)
130 let result = parse_extended_value("iso-8859-1'en'%A3%20rates");
131 assert!(result.is_ok());
132 let extended_value = result.unwrap();
133 assert_eq!(Charset::Iso_8859_1, extended_value.charset);
134 assert!(extended_value.language_tag.is_some());
135 assert_eq!(expected_language_tag, extended_value.language_tag.unwrap());
136 assert_eq!(vec![163, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value);
137 }
138
139 #[test]
140 fn test_parse_extended_value_with_encoding() {
141 // RFC 5987, Section 3.2.2
142 // Extended notation, using the Unicode characters U+00A3 (POUND SIGN)
143 // and U+20AC (EURO SIGN)
144 let result = parse_extended_value("UTF-8''%c2%a3%20and%20%e2%82%ac%20rates");
145 assert!(result.is_ok());
146 let extended_value = result.unwrap();
147 assert_eq!(Charset::Ext("UTF-8".to_string()), extended_value.charset);
148 assert!(extended_value.language_tag.is_none());
149 assert_eq!(vec![194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value);
150 }
151
152 #[test]
153 fn test_parse_extended_value_missing_language_tag_and_encoding() {
154 // From: https://greenbytes.de/tech/tc2231/#attwithfn2231quot2
155 let result = parse_extended_value("foo%20bar.html");
156 assert!(result.is_err());
157 }
158
159 #[test]
160 fn test_parse_extended_value_partially_formatted() {
161 let result = parse_extended_value("UTF-8'missing third part");
162 assert!(result.is_err());
163 }
164
165 #[test]
166 fn test_parse_extended_value_partially_formatted_blank() {
167 let result = parse_extended_value("blank second part'");
168 assert!(result.is_err());
169 }
170
171 #[test]
172 fn test_fmt_extended_value_with_encoding_and_language_tag() {
173 let extended_value = ExtendedValue {
174 charset: Charset::Iso_8859_1,
175 language_tag: Some("en".parse().expect("Could not parse language tag")),
176 value: vec![163, b' ', b'r', b'a', b't', b'e', b's'],
177 };
178 assert_eq!("ISO-8859-1'en'%A3%20rates", format!("{}", extended_value));
179 }
180
181 #[test]
182 fn test_fmt_extended_value_with_encoding() {
183 let extended_value = ExtendedValue {
184 charset: Charset::Ext("UTF-8".to_string()),
185 language_tag: None,
186 value: vec![194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a',
187 b't', b'e', b's'],
188 };
189 assert_eq!("UTF-8''%C2%A3%20and%20%E2%82%AC%20rates",
190 format!("{}", extended_value));
191 }
192 }