use super::data::{self, LOCALE_KEYS, LOCALES, Loc};
use crate::plural::{Buf, subtags};
use std::borrow::Cow;
fn index(name: &str) -> Option<usize> {
let i = LOCALE_KEYS.binary_search(&data::key(name)?).ok()?;
(i != data::UND).then_some(i)
}
fn row<T: Copy>(keys: &[u128], rows: &[T], key: &str) -> Option<T> {
let i = keys.binary_search(&data::key(key)?).ok()?;
rows.get(i).copied()
}
fn alias(lang: &str, variants: Option<&str>, tag: &str) -> Option<&'static str> {
for v in variants.into_iter().flat_map(|v| v.split('-')) {
let mut key = Buf::<17>::of(lang, |b| b);
key.push("-", |b| b);
key.push(v, |b| b.to_ascii_lowercase());
if let Some((to, _)) = row(&data::ALIASES_KEYS, &data::ALIASES, key.as_str()) {
return Some(data::s(to));
}
}
let (to, lone) = row(&data::ALIASES_KEYS, &data::ALIASES, lang)?;
(lone || tag != lang).then(|| data::s(to))
}
pub(crate) fn resolve(tag: &str) -> &'static Loc {
let i = find(tag).unwrap_or(data::EN);
LOCALES.get(i).unwrap_or(&LOCALES[data::EN])
}
pub(crate) fn find(tag: &str) -> Option<usize> {
let tag: Cow<'_, str> = if tag.contains('_') {
Cow::Owned(tag.replace('_', "-"))
} else {
Cow::Borrowed(tag)
};
let t = subtags(&tag)?;
let mut lang = t.language;
let mut script = t.script.map(Buf::<4>::title);
let mut region = t
.region
.map(|r| Buf::<3>::of(r, |b| b.to_ascii_uppercase()));
if let Some(to) = alias(lang.as_str(), t.variants, &tag) {
let mut parts = to.split('-');
lang = Buf::of(parts.next().unwrap_or(""), |b| b);
for p in parts {
if p.len() == 4 && script.is_none() {
script = Some(Buf::of(p, |b| b));
} else if region.is_none() {
region = Some(Buf::of(p, |b| b));
}
}
}
if let Some(r) = region
&& let Some(to) = row(&data::REGIONS_KEYS, &data::REGIONS, r.as_str())
{
region = Some(Buf::of(data::s(to), |b| b));
}
let mut cand = Buf::<17>::of(lang.as_str(), |b| b);
let base = cand.len();
let explicit = script.is_some();
if script.is_none()
&& let Some(r) = ®ion
{
cand.push("-", |b| b);
cand.push(r.as_str(), |b| b);
script = row(&data::SCRIPTS_KEYS, &data::SCRIPTS, cand.as_str())
.map(|s| Buf::of(data::s(s), |b| b));
cand.truncate(base);
if script.as_ref().is_some_and(|s| s.as_str() == "-") {
return Some(data::UND);
}
}
let mut root_parent = false;
if let Some(s) = &script {
cand.push("-", |b| b);
cand.push(s.as_str(), |b| b);
let with_script = cand.len();
if let Some(r) = ®ion {
cand.push("-", |b| b);
cand.push(r.as_str(), |b| b);
if let Some(i) = index(cand.as_str()) {
return Some(i);
}
cand.truncate(with_script);
}
if let Some(i) = index(cand.as_str()) {
return Some(i);
}
root_parent =
data::key(cand.as_str()).is_some_and(|k| data::ROOT_SCRIPTS.binary_search(&k).is_ok());
cand.truncate(base);
}
if !explicit && let Some(r) = ®ion {
cand.push("-", |b| b);
cand.push(r.as_str(), |b| b);
if let Some(i) = index(cand.as_str()) {
return Some(i);
}
cand.truncate(base);
}
if root_parent {
return Some(data::UND);
}
index(cand.as_str())
}
pub(crate) fn autonym(tag: &str) -> Option<&'static str> {
let loc = LOCALES.get(find(tag)?)?;
let name = data::s(loc.autonym);
(!name.is_empty()).then_some(name)
}
#[cfg(test)]
mod tests {
use super::*;
fn name(i: usize) -> String {
let bytes = LOCALE_KEYS[i].to_be_bytes();
String::from_utf8(bytes.iter().copied().take_while(|&b| b != 0).collect()).unwrap()
}
#[test]
fn keys_find_every_locale() {
assert!(LOCALE_KEYS.windows(2).all(|w| w[0] < w[1]));
for i in 0..LOCALES.len() {
let want = (i != data::UND).then_some(i);
assert_eq!(index(&name(i)), want, "{}", name(i));
}
assert_eq!(name(data::UND), "und");
assert_eq!(index("a-name-over-sixteen-bytes"), None);
}
#[test]
fn explicit_script_truncates_past_the_region() {
for (tag, want) in [
("de-Latn-AT", "de"),
("en-Latn-IN", "en"),
("de-AT", "de-AT"),
] {
assert_eq!(find(tag).map(name), Some(want.to_owned()), "{tag}");
}
if index("zh-Hant").is_some() {
assert_eq!(find("zh-TW").map(name), Some("zh-Hant".to_owned()));
}
}
#[test]
fn root_parent_scripts_go_to_the_root() {
for k in data::ROOT_SCRIPTS {
let bytes = k.to_be_bytes();
let tag =
String::from_utf8(bytes.iter().copied().take_while(|&b| b != 0).collect()).unwrap();
assert_eq!(find(&tag), Some(data::UND), "{tag}");
assert_eq!(find(&format!("{tag}-XX")), Some(data::UND), "{tag}-XX");
}
assert_eq!(find("az-Arab"), find("az"));
}
#[test]
fn plural_rule_of_each_locale() {
for (i, loc) in LOCALES.iter().enumerate() {
let want = crate::plural::rule_index(&name(i)).map_or(u8::MAX, |r| r as u8);
assert_eq!(loc.plural, want, "{}", name(i));
}
}
}