use super::*;
use std::cmp::Ordering;
use std::str::FromStr;
use icu::collator::options::CollatorOptions;
use icu::collator::Collator;
use icu::datetime::DateTimeFormatter;
use icu::datetime::fieldsets::YMD;
use icu::datetime::input::{Date, DateTime, Time};
use icu::decimal::DecimalFormatter;
use icu::decimal::input::Decimal;
use icu::decimal::options::DecimalFormatterOptions;
use icu::locale::Locale;
use icu::plurals::{PluralCategory, PluralRules, PluralRulesOptions};
use writeable::Writeable;
fn plural_category_name(category: PluralCategory) -> &'static str {
match category {
PluralCategory::Zero => "Zero",
PluralCategory::One => "One",
PluralCategory::Two => "Two",
PluralCategory::Few => "Few",
PluralCategory::Many => "Many",
PluralCategory::Other => "Other",
}
}
impl HttpI18nFormatter {
pub fn new(locale: &str) -> Result<Self, I18nError> {
let parsed = Locale::from_str(locale).map_err(|e| I18nError::InvalidLocale {
input: locale.to_string(),
reason: e.to_string(),
})?;
let decimal_formatter =
DecimalFormatter::try_new(parsed.clone().into(), DecimalFormatterOptions::default())
.map_err(|e| I18nError::FormatError(e.to_string()))?;
let plural_rules =
PluralRules::try_new(parsed.clone().into(), PluralRulesOptions::default())
.map_err(|e| I18nError::FormatError(e.to_string()))?;
let collator = Collator::try_new(parsed.clone().into(), CollatorOptions::default())
.map_err(|e| I18nError::FormatError(e.to_string()))?;
Ok(Self {
locale: parsed,
decimal_formatter,
plural_rules,
collator,
})
}
pub fn from_accept_language(header: &str) -> Result<Self, I18nError> {
let locales = parse_accept_language(header);
for locale in &locales {
if let Ok(fmt) = Self::new(locale) {
return Ok(fmt);
}
}
Err(I18nError::NoValidLocale {
header: header.to_string(),
})
}
pub fn format_number(&self, value: f64) -> Result<String, I18nError> {
if !value.is_finite() {
return Err(I18nError::InvalidNumber {
input: value.to_string(),
reason: "value is not finite (NaN or Infinity)".into(),
});
}
let repr = format!("{value}");
let decimal = Decimal::from_str(&repr).map_err(|e| I18nError::InvalidNumber {
input: repr,
reason: e.to_string(),
})?;
let formatted = self.decimal_formatter.format(&decimal);
Ok(formatted.write_to_string().into_owned())
}
pub fn format_error_message(&self, code: u16, count: u64) -> Result<String, I18nError> {
let count_str = self.format_number(count as f64)?;
let category = self.plural_rules.category_for(count);
let plural_name = plural_category_name(category);
let noun = match category {
PluralCategory::One => "error",
_ => "errors",
};
Ok(format!("HTTP {code}: {count_str} {noun} ({plural_name})"))
}
pub fn format_timestamp(&self, year: i32, month: u8, day: u8) -> Result<String, I18nError> {
let date =
Date::try_new_iso(year, month, day).map_err(|e| I18nError::DateError(e.to_string()))?;
let time = Time::try_new(0, 0, 0, 0).map_err(|e| I18nError::DateError(e.to_string()))?;
let datetime = DateTime { date, time };
let dtf = DateTimeFormatter::try_new(self.locale.clone().into(), YMD::medium())
.map_err(|e| I18nError::FormatError(e.to_string()))?;
let formatted = dtf.format(&datetime);
Ok(formatted.write_to_string().into_owned())
}
pub fn compare_headers(&self, a: &str, b: &str) -> Result<Ordering, I18nError> {
Ok(self.collator.compare(a, b))
}
}
pub fn parse_accept_language(header: &str) -> Vec<String> {
let mut entries: Vec<(String, f64)> = Vec::new();
for part in header.split(',') {
let part = part.trim();
if part.is_empty() {
continue;
}
let mut segments = part.split(';');
let locale = segments.next().unwrap_or("").trim().to_string();
if locale.is_empty() {
continue;
}
let mut q = DEFAULT_Q_VALUE;
for seg in segments {
let seg = seg.trim();
if let Some(q_str) = seg.strip_prefix("q=")
&& let Ok(parsed) = q_str.trim().parse::<f64>()
{
q = parsed;
}
}
if q > 0.0 {
entries.push((locale, q));
}
}
entries.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(Ordering::Equal));
entries.into_iter().map(|(locale, _)| locale).collect()
}