use super::*;
use std::cmp::Ordering;
use std::str::FromStr;
use icu::collator::Collator;
use icu::collator::options::CollatorOptions;
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",
}
}
fn get_message(locale: &Locale, key: &str) -> &'static str {
let lang = locale.id.language.as_str();
match (lang, key) {
("zh", "migration") => "已应用 {count} 个迁移",
("de", "migration") => "{count} Migrationen angewendet",
("ja", "migration") => "{count} 件のマイグレーションを適用しました",
("fr", "migration") => "{count} migrations appliquées",
(_, "migration") => "{count} migrations applied",
("zh", "hello_world") => "你好,世界!",
("de", "hello_world") => "Hallo, Welt!",
("ja", "hello_world") => "こんにちは、世界!",
("fr", "hello_world") => "Bonjour, le monde !",
(_, "hello_world") => "Hello, World!",
_ => "",
}
}
fn substitute_count(template: &str, formatted_count: &str) -> String {
template.replace("{count}", formatted_count)
}
impl DbI18nFormatter {
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 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_row_count(&self, count: u64) -> Result<String, I18nError> {
self.format_number(count as f64)
}
pub fn format_migration_message(&self, count: u64) -> Result<String, I18nError> {
let count_str = self.format_number(count as f64)?;
let template = get_message(&self.locale, "migration");
Ok(substitute_count(template, &count_str))
}
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 plural_category(&self, count: u64) -> Result<String, I18nError> {
Ok(plural_category_name(self.plural_rules.category_for(count)).to_string())
}
pub fn compare_strings(&self, a: &str, b: &str) -> Result<Ordering, I18nError> {
Ok(self.collator.compare(a, b))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_plural_category_name_all_variants() {
let fmt_ar = DbI18nFormatter::new("ar").expect("ar locale");
let cat = fmt_ar.plural_category(0).expect("ar plural 0");
assert_eq!(cat, "Zero", "Arabic count=0 should be Zero, got: {cat}");
let fmt_en = DbI18nFormatter::new("en").expect("en locale");
assert_eq!(fmt_en.plural_category(1).unwrap(), "One");
let cat2 = fmt_ar.plural_category(2).expect("ar plural 2");
assert_eq!(cat2, "Two", "Arabic count=2 should be Two, got: {cat2}");
let fmt_pl = DbI18nFormatter::new("pl").expect("pl locale");
let cat_few = fmt_pl.plural_category(2).expect("pl plural 2");
assert_eq!(cat_few, "Few", "Polish count=2 should be Few, got: {cat_few}");
let cat_many = fmt_ar.plural_category(11).expect("ar plural 11");
assert_eq!(cat_many, "Many", "Arabic count=11 should be Many, got: {cat_many}");
let cat_other = fmt_en.plural_category(0).expect("en plural 0");
assert_eq!(cat_other, "Other", "English count=0 should be Other, got: {cat_other}");
}
#[test]
fn test_get_message_via_migration_all_locales() {
let locales_and_expected = vec![("zh-CN", "迁移"), ("en-US", "migrations applied")];
for (locale, expected) in locales_and_expected {
let fmt = DbI18nFormatter::new(locale).unwrap_or_else(|_| panic!("locale {locale}"));
let msg = fmt
.format_migration_message(5)
.unwrap_or_else(|_| panic!("migration msg for {locale}"));
assert!(
msg.contains(expected),
"locale {locale}: expected '{expected}' in '{msg}'"
);
}
}
#[test]
fn test_format_number_zh() {
let fmt = DbI18nFormatter::new("zh-CN").expect("zh-CN locale");
let result = fmt.format_number(1234567.0).expect("format number zh");
assert!(!result.is_empty());
}
#[test]
fn test_format_timestamp_invalid_date() {
let fmt = DbI18nFormatter::new("en-US").expect("en-US locale");
let result = fmt.format_timestamp(2026, 13, 1);
assert!(result.is_err(), "invalid month should return error");
}
#[test]
fn test_format_timestamp_invalid_day() {
let fmt = DbI18nFormatter::new("en-US").expect("en-US locale");
let result = fmt.format_timestamp(2026, 1, 32);
assert!(result.is_err(), "invalid day should return error");
}
#[test]
fn test_format_migration_message_fr() {
let fmt = DbI18nFormatter::new("fr-FR").expect("fr-FR locale");
let msg = fmt.format_migration_message(10).expect("fr migration message");
assert!(msg.contains("migrations"), "fr message: got '{msg}'");
}
#[test]
fn test_get_message_hello_world_all_locales() {
use icu::locale::Locale;
use std::str::FromStr;
let zh = Locale::from_str("zh").unwrap();
assert_eq!(get_message(&zh, "hello_world"), "你好,世界!");
let en = Locale::from_str("en").unwrap();
assert_eq!(get_message(&en, "hello_world"), "Hello, World!");
}
#[test]
fn test_get_message_unknown_key_returns_empty() {
use icu::locale::Locale;
use std::str::FromStr;
let en = Locale::from_str("en").unwrap();
assert_eq!(get_message(&en, "nonexistent_key"), "");
let zh = Locale::from_str("zh").unwrap();
assert_eq!(get_message(&zh, "nonexistent_key"), "");
}
#[test]
fn test_substitute_count() {
assert_eq!(
substitute_count("{count} migrations applied", "5"),
"5 migrations applied"
);
assert_eq!(substitute_count("no placeholder", "5"), "no placeholder");
assert_eq!(substitute_count("{count} of {count}", "3"), "3 of 3");
}
}