|
| 1 | +use std::borrow::Cow; |
| 2 | + |
| 3 | +use super::LanguageRange; |
| 4 | + |
| 5 | +fn split_tag(input: &str) -> Option<(&str, &str)> { |
| 6 | + match input.find('-') { |
| 7 | + Some(pos) if pos <= 8 => { |
| 8 | + let (tag, rest) = input.split_at(pos); |
| 9 | + Some((tag, &rest[1..])) |
| 10 | + } |
| 11 | + Some(_) => None, |
| 12 | + None => (input.len() <= 8).then(|| (input, "")), |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +// language-range = (1*8ALPHA *("-" 1*8alphanum)) / "*" |
| 17 | +// alphanum = ALPHA / DIGIT |
| 18 | +pub(crate) fn parse(input: &str) -> crate::Result<LanguageRange> { |
| 19 | + let tags = if input == "*" { |
| 20 | + vec![Cow::from(input.to_string())] |
| 21 | + } else { |
| 22 | + let mut tags = Vec::new(); |
| 23 | + |
| 24 | + let (tag, mut input) = split_tag(input).ok_or_else(|| crate::format_err!("WIP error"))?; |
| 25 | + crate::ensure!(!tag.is_empty(), "Language tag should not be empty"); |
| 26 | + crate::ensure!( |
| 27 | + tag.bytes() |
| 28 | + .all(|b| (b'a'..=b'z').contains(&b) || (b'A'..=b'Z').contains(&b)), |
| 29 | + "Language tag should be alpha" |
| 30 | + ); |
| 31 | + tags.push(Cow::from(tag.to_string())); |
| 32 | + |
| 33 | + while !input.is_empty() { |
| 34 | + let (tag, rest) = split_tag(input).ok_or_else(|| crate::format_err!("WIP error"))?; |
| 35 | + crate::ensure!(!tag.is_empty(), "Language tag should not be empty"); |
| 36 | + crate::ensure!( |
| 37 | + tag.bytes().all(|b| (b'a'..=b'z').contains(&b) |
| 38 | + || (b'A'..=b'Z').contains(&b) |
| 39 | + || (b'0'..=b'9').contains(&b)), |
| 40 | + "Language tag should be alpha numeric" |
| 41 | + ); |
| 42 | + tags.push(Cow::from(tag.to_string())); |
| 43 | + input = rest; |
| 44 | + } |
| 45 | + |
| 46 | + tags |
| 47 | + }; |
| 48 | + |
| 49 | + Ok(LanguageRange { tags }) |
| 50 | +} |
| 51 | + |
| 52 | +#[test] |
| 53 | +fn test() { |
| 54 | + let range = parse("*").unwrap(); |
| 55 | + assert_eq!(&range.tags, &["*"]); |
| 56 | + |
| 57 | + let range = parse("en").unwrap(); |
| 58 | + assert_eq!(&range.tags, &["en"]); |
| 59 | + |
| 60 | + let range = parse("en-CA").unwrap(); |
| 61 | + assert_eq!(&range.tags, &["en", "CA"]); |
| 62 | + |
| 63 | + let range = parse("zh-Hant-CN-x-private1-private2").unwrap(); |
| 64 | + assert_eq!( |
| 65 | + &range.tags, |
| 66 | + &["zh", "Hant", "CN", "x", "private1", "private2"] |
| 67 | + ); |
| 68 | +} |
0 commit comments