1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// Copyright 2024 New Vector Ltd.
// Copyright 2023, 2024 The Matrix.org Foundation C.I.C.
//
// SPDX-License-Identifier: AGPL-3.0-only
// Please see LICENSE in the repository root for full details.

use std::cmp::Reverse;

use headers::{Error, Header};
use http::{header::ACCEPT_LANGUAGE, HeaderName, HeaderValue};
use icu_locid::Locale;

#[derive(PartialEq, Eq, Debug)]
struct AcceptLanguagePart {
    // None means *
    locale: Option<Locale>,

    // Quality is between 0 and 1 with 3 decimal places
    // Which we map from 0 to 1000, e.g. 0.5 becomes 500
    quality: u16,
}

impl PartialOrd for AcceptLanguagePart {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for AcceptLanguagePart {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // When comparing two AcceptLanguage structs, we only consider the
        // quality, in reverse.
        Reverse(self.quality).cmp(&Reverse(other.quality))
    }
}

/// A header that represents the `Accept-Language` header.
#[derive(PartialEq, Eq, Debug)]
pub struct AcceptLanguage {
    parts: Vec<AcceptLanguagePart>,
}

impl AcceptLanguage {
    pub fn iter(&self) -> impl Iterator<Item = &Locale> {
        // This should stop when we hit the first None, aka the first *
        self.parts.iter().map_while(|item| item.locale.as_ref())
    }
}

/// Utility to trim ASCII whitespace from the start and end of a byte slice
const fn trim_bytes(mut bytes: &[u8]) -> &[u8] {
    // Trim leading and trailing whitespace
    while let [first, rest @ ..] = bytes {
        if first.is_ascii_whitespace() {
            bytes = rest;
        } else {
            break;
        }
    }

    while let [rest @ .., last] = bytes {
        if last.is_ascii_whitespace() {
            bytes = rest;
        } else {
            break;
        }
    }

    bytes
}

impl Header for AcceptLanguage {
    fn name() -> &'static HeaderName {
        &ACCEPT_LANGUAGE
    }

    fn decode<'i, I>(values: &mut I) -> Result<Self, Error>
    where
        Self: Sized,
        I: Iterator<Item = &'i HeaderValue>,
    {
        let mut parts = Vec::new();
        for value in values {
            for part in value.as_bytes().split(|b| *b == b',') {
                let mut it = part.split(|b| *b == b';');
                let locale = it.next().ok_or(Error::invalid())?;
                let locale = trim_bytes(locale);

                let locale = match locale {
                    b"*" => None,
                    locale => {
                        let locale =
                            Locale::try_from_bytes(locale).map_err(|_e| Error::invalid())?;
                        Some(locale)
                    }
                };

                let quality = if let Some(quality) = it.next() {
                    let quality = trim_bytes(quality);
                    let quality = quality.strip_prefix(b"q=").ok_or(Error::invalid())?;
                    let quality = std::str::from_utf8(quality).map_err(|_e| Error::invalid())?;
                    let quality = quality.parse::<f64>().map_err(|_e| Error::invalid())?;
                    // Bound the quality between 0 and 1
                    let quality = quality.clamp(0_f64, 1_f64);

                    // Make sure the iterator is empty
                    if it.next().is_some() {
                        return Err(Error::invalid());
                    }

                    #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
                    {
                        f64::round(quality * 1000_f64) as u16
                    }
                } else {
                    1000
                };

                parts.push(AcceptLanguagePart { locale, quality });
            }
        }

        parts.sort();

        Ok(AcceptLanguage { parts })
    }

    fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
        let mut value = String::new();
        let mut first = true;
        for part in &self.parts {
            if first {
                first = false;
            } else {
                value.push_str(", ");
            }

            if let Some(locale) = &part.locale {
                value.push_str(&locale.to_string());
            } else {
                value.push('*');
            }

            if part.quality != 1000 {
                value.push_str(";q=");
                value.push_str(&(f64::from(part.quality) / 1000_f64).to_string());
            }
        }

        // We know this is safe because we only use ASCII characters
        values.extend(Some(HeaderValue::from_str(&value).unwrap()));
    }
}

#[cfg(test)]
mod tests {
    use headers::HeaderMapExt;
    use http::{header::ACCEPT_LANGUAGE, HeaderMap, HeaderValue};
    use icu_locid::locale;

    use super::*;

    #[test]
    fn test_decode() {
        let headers = HeaderMap::from_iter([(
            ACCEPT_LANGUAGE,
            HeaderValue::from_str("fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5").unwrap(),
        )]);

        let accept_language: Option<AcceptLanguage> = headers.typed_get();
        assert!(accept_language.is_some());
        let accept_language = accept_language.unwrap();

        assert_eq!(
            accept_language,
            AcceptLanguage {
                parts: vec![
                    AcceptLanguagePart {
                        locale: Some(locale!("fr-CH")),
                        quality: 1000,
                    },
                    AcceptLanguagePart {
                        locale: Some(locale!("fr")),
                        quality: 900,
                    },
                    AcceptLanguagePart {
                        locale: Some(locale!("en")),
                        quality: 800,
                    },
                    AcceptLanguagePart {
                        locale: Some(locale!("de")),
                        quality: 700,
                    },
                    AcceptLanguagePart {
                        locale: None,
                        quality: 500,
                    },
                ]
            }
        );
    }

    #[test]
    /// Test that we can decode a header with multiple values unordered, and
    /// that the output is ordered by quality
    fn test_decode_order() {
        let headers = HeaderMap::from_iter([(
            ACCEPT_LANGUAGE,
            HeaderValue::from_str("*;q=0.5, fr-CH, en;q=0.8, fr;q=0.9, de;q=0.9").unwrap(),
        )]);

        let accept_language: Option<AcceptLanguage> = headers.typed_get();
        assert!(accept_language.is_some());
        let accept_language = accept_language.unwrap();

        assert_eq!(
            accept_language,
            AcceptLanguage {
                parts: vec![
                    AcceptLanguagePart {
                        locale: Some(locale!("fr-CH")),
                        quality: 1000,
                    },
                    AcceptLanguagePart {
                        locale: Some(locale!("fr")),
                        quality: 900,
                    },
                    AcceptLanguagePart {
                        locale: Some(locale!("de")),
                        quality: 900,
                    },
                    AcceptLanguagePart {
                        locale: Some(locale!("en")),
                        quality: 800,
                    },
                    AcceptLanguagePart {
                        locale: None,
                        quality: 500,
                    },
                ]
            }
        );
    }

    #[test]
    fn test_encode() {
        let accept_language = AcceptLanguage {
            parts: vec![
                AcceptLanguagePart {
                    locale: Some(locale!("fr-CH")),
                    quality: 1000,
                },
                AcceptLanguagePart {
                    locale: Some(locale!("fr")),
                    quality: 900,
                },
                AcceptLanguagePart {
                    locale: Some(locale!("de")),
                    quality: 900,
                },
                AcceptLanguagePart {
                    locale: Some(locale!("en")),
                    quality: 800,
                },
                AcceptLanguagePart {
                    locale: None,
                    quality: 500,
                },
            ],
        };

        let mut headers = HeaderMap::new();
        headers.typed_insert(accept_language);
        let header = headers.get(ACCEPT_LANGUAGE).unwrap();
        assert_eq!(
            header.to_str().unwrap(),
            "fr-CH, fr;q=0.9, de;q=0.9, en;q=0.8, *;q=0.5"
        );
    }
}