use std::collections::HashMap;
use std::sync::OnceLock;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Lang {
#[default]
En,
Zh,
}
#[derive(Clone)]
pub struct I18n {
lang: Lang,
}
static EN_MESSAGES: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();
static ZH_MESSAGES: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();
fn en_messages() -> &'static HashMap<&'static str, &'static str> {
EN_MESSAGES.get_or_init(|| {
let json = include_str!("../locales/en.json");
serde_json::from_str(json).unwrap_or_else(|e| panic!("locales/en.json 解析失败: {e}"))
})
}
fn zh_messages() -> &'static HashMap<&'static str, &'static str> {
ZH_MESSAGES.get_or_init(|| {
let json = include_str!("../locales/zh.json");
serde_json::from_str(json).unwrap_or_else(|e| panic!("locales/zh.json 解析失败: {e}"))
})
}
impl I18n {
pub fn new(lang: Lang) -> Self {
Self { lang }
}
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Self {
let lang = parse_lang(s);
Self::new(lang)
}
pub fn lang(&self) -> Lang {
self.lang
}
pub fn t<'a>(&self, key: &'a str) -> &'a str {
let table = match self.lang {
Lang::En => en_messages(),
Lang::Zh => zh_messages(),
};
table.get(key).copied().unwrap_or(key)
}
pub fn tf(&self, key: &str, args: &[(&str, &str)]) -> String {
let template = self.t(key);
if args.is_empty() {
return template.to_string();
}
let mut result = template.to_string();
for (name, value) in args {
let placeholder = format!("{{{}}}", name);
result = result.replace(&placeholder, value);
}
result
}
}
impl Default for I18n {
fn default() -> Self {
Self::new(Lang::default())
}
}
fn parse_lang(s: &str) -> Lang {
#[cfg(feature = "icu")]
{
parse_lang_icu(s)
}
#[cfg(not(feature = "icu"))]
{
parse_lang_simple(s)
}
}
#[cfg(feature = "icu")]
fn parse_lang_icu(s: &str) -> Lang {
use icu::locale::Locale;
match Locale::try_from_str(s) {
Ok(locale) => {
let lang = locale.id.language;
if lang.as_str() == "zh" {
Lang::Zh
} else {
Lang::En
}
}
Err(_) => Lang::En,
}
}
#[cfg(not(feature = "icu"))]
fn parse_lang_simple(s: &str) -> Lang {
let lower = s.to_ascii_lowercase();
let primary = lower.split('-').next().unwrap_or("");
match primary {
"zh" => Lang::Zh,
_ => Lang::En,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_lang_default_is_english() {
assert_eq!(Lang::default(), Lang::En);
}
#[test]
fn test_new_creates_with_specified_lang() {
let en = I18n::new(Lang::En);
assert_eq!(en.lang(), Lang::En);
let zh = I18n::new(Lang::Zh);
assert_eq!(zh.lang(), Lang::Zh);
}
#[test]
fn test_default_is_english() {
let i18n = I18n::default();
assert_eq!(i18n.lang(), Lang::En);
}
#[test]
fn test_from_str_en() {
assert_eq!(I18n::from_str("en").lang(), Lang::En);
}
#[test]
fn test_from_str_zh() {
assert_eq!(I18n::from_str("zh").lang(), Lang::Zh);
}
#[test]
fn test_from_str_en_us() {
assert_eq!(I18n::from_str("en-US").lang(), Lang::En);
}
#[test]
fn test_from_str_en_gb() {
assert_eq!(I18n::from_str("en-GB").lang(), Lang::En);
}
#[test]
fn test_from_str_zh_cn() {
assert_eq!(I18n::from_str("zh-CN").lang(), Lang::Zh);
}
#[test]
fn test_from_str_zh_tw() {
assert_eq!(I18n::from_str("zh-TW").lang(), Lang::Zh);
}
#[test]
fn test_from_str_french_fallback_to_en() {
assert_eq!(I18n::from_str("fr").lang(), Lang::En);
}
#[test]
fn test_from_str_japanese_fallback_to_en() {
assert_eq!(I18n::from_str("ja").lang(), Lang::En);
}
#[test]
fn test_from_str_empty_string_fallback_to_en() {
assert_eq!(I18n::from_str("").lang(), Lang::En);
}
#[test]
fn test_from_str_invalid_string_fallback_to_en() {
assert_eq!(I18n::from_str("!!!").lang(), Lang::En);
}
#[test]
fn test_from_str_zhongwen_falls_back_to_en() {
let i18n = I18n::from_str("zhongwen");
assert_eq!(
i18n.lang(),
Lang::En,
"zhongwen should fall back to En, not Zh"
);
}
#[test]
fn test_from_str_zh_hans() {
assert_eq!(I18n::from_str("zh-Hans").lang(), Lang::Zh);
}
#[test]
fn test_from_str_zh_hant() {
assert_eq!(I18n::from_str("zh-Hant").lang(), Lang::Zh);
}
#[test]
fn test_from_str_zh_hans_cn() {
assert_eq!(I18n::from_str("zh-Hans-CN").lang(), Lang::Zh);
}
#[test]
fn test_from_str_zh_hant_tw() {
assert_eq!(I18n::from_str("zh-Hant-TW").lang(), Lang::Zh);
}
#[test]
fn test_from_str_zh_hans_sg() {
assert_eq!(I18n::from_str("zh-Hans-SG").lang(), Lang::Zh);
}
#[test]
fn test_from_str_zh_hant_hk() {
assert_eq!(I18n::from_str("zh-Hant-HK").lang(), Lang::Zh);
}
#[test]
fn test_from_str_zh_hans_mixed_case() {
assert_eq!(I18n::from_str("ZH-hans").lang(), Lang::Zh);
assert_eq!(I18n::from_str("zh-HANS").lang(), Lang::Zh);
}
#[test]
fn test_from_str_zh_private_use() {
assert_eq!(I18n::from_str("zh-x-calnexus").lang(), Lang::Zh);
}
#[test]
fn test_from_str_zh_latn_pinyin() {
assert_eq!(I18n::from_str("zh-Latn-pinyin").lang(), Lang::Zh);
}
#[test]
fn test_from_str_zhongwen_hans_falls_back_to_en() {
assert_eq!(I18n::from_str("zhongwen-Hans").lang(), Lang::En);
}
#[test]
fn test_from_str_case_insensitive_zh() {
assert_eq!(I18n::from_str("ZH").lang(), Lang::Zh);
assert_eq!(I18n::from_str("Zh").lang(), Lang::Zh);
}
#[test]
fn test_from_str_case_insensitive_en() {
assert_eq!(I18n::from_str("EN").lang(), Lang::En);
assert_eq!(I18n::from_str("En").lang(), Lang::En);
}
#[test]
fn test_all_message_keys_have_english_translation() {
let i18n = I18n::new(Lang::En);
let keys = [
"error.parse",
"error.eval",
"error.overflow",
"error.division_by_zero",
"error.domain",
"error.depth",
"error.nan_or_inf",
"error.undefined_symbol",
"error.timeout",
"error.usage",
"label.position",
"label.hint",
"label.error_kind",
"label.exit_code",
"label.suggestion",
"msg.unbound_variable",
"msg.invalid_bignumber",
"msg.matrix_dim_mismatch",
"msg.function_arg_count",
"msg.unknown_function",
"msg.unknown_variable",
];
for key in &keys {
let msg = i18n.t(key);
assert!(
msg != *key,
"key '{}' has no English translation (returned key itself)",
key
);
assert!(
!msg.is_empty(),
"key '{}' has empty English translation",
key
);
}
}
#[test]
fn test_all_message_keys_have_chinese_translation() {
let i18n = I18n::new(Lang::Zh);
let keys = [
"error.parse",
"error.eval",
"error.overflow",
"error.division_by_zero",
"error.domain",
"error.depth",
"error.nan_or_inf",
"error.undefined_symbol",
"error.timeout",
"error.usage",
"label.position",
"label.hint",
"label.error_kind",
"label.exit_code",
"label.suggestion",
"msg.unbound_variable",
"msg.invalid_bignumber",
"msg.matrix_dim_mismatch",
"msg.function_arg_count",
"msg.unknown_function",
"msg.unknown_variable",
];
for key in &keys {
let msg = i18n.t(key);
assert!(
msg != *key,
"key '{}' has no Chinese translation (returned key itself)",
key
);
assert!(
!msg.is_empty(),
"key '{}' has empty Chinese translation",
key
);
}
}
#[test]
fn test_en_and_zh_translations_differ() {
let en = I18n::new(Lang::En);
let zh = I18n::new(Lang::Zh);
let keys = [
"error.parse",
"error.eval",
"error.overflow",
"error.division_by_zero",
"error.domain",
"error.depth",
"error.nan_or_inf",
"error.undefined_symbol",
"error.timeout",
"error.usage",
"label.position",
"label.hint",
"label.error_kind",
"label.exit_code",
"label.suggestion",
"msg.unbound_variable",
"msg.invalid_bignumber",
"msg.matrix_dim_mismatch",
"msg.function_arg_count",
"msg.unknown_function",
"msg.unknown_variable",
];
for key in &keys {
assert_ne!(
en.t(key),
zh.t(key),
"key '{}' has identical en/zh translations",
key
);
}
}
#[test]
fn test_unknown_key_returns_key_itself() {
let en = I18n::new(Lang::En);
assert_eq!(en.t("nonexistent.key"), "nonexistent.key");
let zh = I18n::new(Lang::Zh);
assert_eq!(zh.t("nonexistent.key"), "nonexistent.key");
}
#[test]
fn test_empty_key_returns_empty_string() {
let en = I18n::new(Lang::En);
assert_eq!(en.t(""), "");
}
#[test]
fn test_specific_english_translations() {
let en = I18n::new(Lang::En);
assert_eq!(en.t("error.parse"), "Parse error");
assert_eq!(en.t("error.eval"), "Evaluation error");
assert_eq!(en.t("error.overflow"), "Arithmetic overflow");
assert_eq!(en.t("error.division_by_zero"), "Division by zero");
assert_eq!(en.t("error.domain"), "Domain error");
assert_eq!(en.t("error.depth"), "Maximum recursion depth exceeded");
assert_eq!(en.t("error.nan_or_inf"), "Result is NaN or infinity");
assert_eq!(en.t("error.undefined_symbol"), "Undefined symbol");
assert_eq!(en.t("error.timeout"), "Evaluation timed out");
assert_eq!(en.t("error.usage"), "Usage error");
assert_eq!(en.t("label.position"), "Position");
assert_eq!(en.t("label.hint"), "Hint");
assert_eq!(en.t("label.error_kind"), "Error Kind");
assert_eq!(en.t("label.exit_code"), "Exit Code");
assert_eq!(en.t("label.suggestion"), "Suggestion");
}
#[test]
fn test_specific_chinese_translations() {
let zh = I18n::new(Lang::Zh);
assert_eq!(zh.t("error.parse"), "解析错误");
assert_eq!(zh.t("error.eval"), "求值错误");
assert_eq!(zh.t("error.overflow"), "算术溢出");
assert_eq!(zh.t("error.division_by_zero"), "除以零");
assert_eq!(zh.t("error.domain"), "定义域错误");
assert_eq!(zh.t("error.depth"), "超过最大递归深度");
assert_eq!(zh.t("error.nan_or_inf"), "结果为 NaN 或无穷大");
assert_eq!(zh.t("error.undefined_symbol"), "未定义符号");
assert_eq!(zh.t("error.timeout"), "求值超时");
assert_eq!(zh.t("error.usage"), "用法错误");
assert_eq!(zh.t("label.position"), "位置");
assert_eq!(zh.t("label.hint"), "提示");
assert_eq!(zh.t("label.error_kind"), "错误类别");
assert_eq!(zh.t("label.exit_code"), "退出码");
assert_eq!(zh.t("label.suggestion"), "建议");
}
#[test]
fn test_tf_single_placeholder_en() {
let i18n = I18n::new(Lang::En);
assert_eq!(
i18n.tf("msg.unbound_variable", &[("name", "x")]),
"Unbound variable: x"
);
assert_eq!(
i18n.tf("msg.unknown_function", &[("name", "sin")]),
"Unknown function: sin"
);
}
#[test]
fn test_tf_single_placeholder_zh() {
let i18n = I18n::new(Lang::Zh);
assert_eq!(
i18n.tf("msg.unbound_variable", &[("name", "x")]),
"未绑定变量: x"
);
assert_eq!(
i18n.tf("msg.unknown_function", &[("name", "sin")]),
"未知函数: sin"
);
}
#[test]
fn test_tf_multiple_placeholders_en() {
let i18n = I18n::new(Lang::En);
assert_eq!(
i18n.tf(
"msg.matrix_dim_mismatch",
&[("expected", "3x3"), ("actual", "2x2")]
),
"Matrix dimension mismatch: expected 3x3, got 2x2"
);
assert_eq!(
i18n.tf(
"msg.function_arg_count",
&[("name", "sin"), ("expected", "1"), ("actual", "2")]
),
"Function sin expects 1 args, got 2"
);
}
#[test]
fn test_tf_multiple_placeholders_zh() {
let i18n = I18n::new(Lang::Zh);
assert_eq!(
i18n.tf(
"msg.matrix_dim_mismatch",
&[("expected", "3x3"), ("actual", "2x2")]
),
"矩阵维度不匹配: 期望 3x3, 实际 2x2"
);
assert_eq!(
i18n.tf(
"msg.function_arg_count",
&[("name", "sin"), ("expected", "1"), ("actual", "2")]
),
"函数 sin 期望 1 个参数, 实际 2"
);
}
#[test]
fn test_tf_unknown_key_returns_key_itself() {
let en = I18n::new(Lang::En);
assert_eq!(
en.tf("nonexistent.key", &[("name", "x")]),
"nonexistent.key"
);
let zh = I18n::new(Lang::Zh);
assert_eq!(
zh.tf("nonexistent.key", &[("name", "x")]),
"nonexistent.key"
);
}
#[test]
fn test_tf_missing_placeholder_preserved() {
let i18n = I18n::new(Lang::En);
assert_eq!(
i18n.tf("msg.function_arg_count", &[("name", "sin")]),
"Function sin expects {expected} args, got {actual}"
);
}
#[test]
fn test_tf_empty_args_equivalent_to_t() {
let en = I18n::new(Lang::En);
assert_eq!(
en.tf("msg.unbound_variable", &[]),
"Unbound variable: {name}"
);
assert_eq!(en.tf("error.parse", &[]), en.t("error.parse"));
let zh = I18n::new(Lang::Zh);
assert_eq!(zh.tf("msg.unbound_variable", &[]), "未绑定变量: {name}");
assert_eq!(zh.tf("error.parse", &[]), zh.t("error.parse"));
}
#[test]
fn test_tf_repeated_placeholder_replaces_all() {
let i18n = I18n::new(Lang::En);
let result = i18n.tf("msg.unknown_variable", &[("name", "y")]);
assert_eq!(result, "Unknown variable: y");
assert!(!result.contains('{') || result.contains("got"));
}
#[test]
fn test_en_messages_table_not_empty() {
let table = en_messages();
assert!(!table.is_empty(), "English message table must not be empty");
assert!(
table.len() >= 21,
"English table should have at least 21 entries, got {}",
table.len()
);
}
#[test]
fn test_zh_messages_table_not_empty() {
let table = zh_messages();
assert!(!table.is_empty(), "Chinese message table must not be empty");
assert!(
table.len() >= 21,
"Chinese table should have at least 21 entries, got {}",
table.len()
);
}
#[test]
fn test_en_and_zh_tables_have_same_keys() {
let en = en_messages();
let zh = zh_messages();
assert_eq!(
en.len(),
zh.len(),
"en/zh tables have different key counts: en={}, zh={}",
en.len(),
zh.len()
);
for key in en.keys() {
assert!(
zh.contains_key(key),
"key '{}' exists in en.json but missing in zh.json",
key
);
}
}
}