use std::cell::RefCell;
use std::collections::HashMap;
use std::future::Future;
use std::path::Path;
use std::sync::OnceLock;
tokio::task_local! {
static LOCALE_OVERRIDE: RefCell<Option<String>>;
}
pub async fn with_locale_scope<F: Future>(fut: F) -> F::Output {
LOCALE_OVERRIDE.scope(RefCell::new(None), fut).await
}
pub fn set_current_locale(locale: String) {
let _ = LOCALE_OVERRIDE.try_with(|cell| {
*cell.borrow_mut() = Some(locale);
});
}
const DEFAULT_LOCALE: &str = "en";
pub fn current_locale() -> String {
LOCALE_OVERRIDE
.try_with(|cell| cell.borrow().clone())
.ok()
.flatten()
.unwrap_or_else(|| {
larust_core::try_config()
.map(|config| config.app_locale.clone())
.unwrap_or_else(|| DEFAULT_LOCALE.to_string())
})
}
fn catalog() -> &'static HashMap<String, HashMap<String, String>> {
static CATALOG: OnceLock<HashMap<String, HashMap<String, String>>> = OnceLock::new();
CATALOG.get_or_init(|| load_catalog_from(Path::new("resources/lang")))
}
fn load_catalog_from(dir: &Path) -> HashMap<String, HashMap<String, String>> {
let mut catalog = HashMap::new();
let Ok(entries) = std::fs::read_dir(dir) else {
return catalog;
};
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
continue;
}
let Some(locale) = path.file_stem().and_then(|stem| stem.to_str()) else {
continue;
};
let Ok(contents) = std::fs::read_to_string(&path) else {
continue;
};
let Ok(map) = serde_json::from_str::<HashMap<String, String>>(&contents) else {
continue;
};
catalog.insert(locale.to_string(), map);
}
catalog
}
fn lookup(key: &str) -> Option<&'static str> {
let catalog = catalog();
let locale = current_locale();
let fallback_locale = larust_core::try_config()
.map(|config| config.app_fallback_locale.clone())
.unwrap_or_else(|| DEFAULT_LOCALE.to_string());
catalog
.get(&locale)
.and_then(|entries| entries.get(key))
.or_else(|| {
catalog
.get(&fallback_locale)
.and_then(|entries| entries.get(key))
})
.map(String::as_str)
}
pub fn t(key: &str) -> String {
t_with(key, &[])
}
pub fn t_with(key: &str, params: &[(&str, &str)]) -> String {
substitute(pluralize(lookup(key).unwrap_or(key), params), params)
}
pub fn t_or(key: &str, default: &str) -> String {
t_or_with(key, default, &[])
}
pub fn t_or_with(key: &str, default: &str, params: &[(&str, &str)]) -> String {
substitute(pluralize(lookup(key).unwrap_or(default), params), params)
}
fn pluralize<'a>(template: &'a str, params: &[(&str, &str)]) -> &'a str {
if !template.contains('|') {
return template;
}
let segments: Vec<&str> = template.split('|').collect();
let count: Option<i64> = params
.iter()
.find(|(name, _)| *name == "count")
.and_then(|(_, value)| value.parse().ok());
if segments.len() == 2 && parse_selector(segments[0]).is_none() {
return match count {
Some(1) => segments[0],
_ => segments[1],
};
}
let Some(count) = count else {
return segments
.last()
.expect("split always yields at least one segment");
};
for segment in &segments {
if let Some((selector, rest)) = parse_selector(segment) {
if selector.matches(count) {
return rest;
}
}
}
segments
.last()
.expect("split always yields at least one segment")
}
enum PluralSelector {
Exact(i64),
Range(i64, Option<i64>),
}
impl PluralSelector {
fn matches(&self, count: i64) -> bool {
match self {
PluralSelector::Exact(n) => count == *n,
PluralSelector::Range(min, Some(max)) => count >= *min && count <= *max,
PluralSelector::Range(min, None) => count >= *min,
}
}
}
fn parse_selector(segment: &str) -> Option<(PluralSelector, &str)> {
let segment = segment.trim_start();
if let Some(rest) = segment.strip_prefix('{') {
let (num, rest) = rest.split_once('}')?;
let n: i64 = num.trim().parse().ok()?;
return Some((PluralSelector::Exact(n), rest.trim_start()));
}
if let Some(rest) = segment.strip_prefix('[') {
let (range, rest) = rest.split_once(']')?;
let (min_str, max_str) = range.split_once(',')?;
let min: i64 = min_str.trim().parse().ok()?;
let max = match max_str.trim() {
"*" => None,
bound => Some(bound.parse().ok()?),
};
return Some((PluralSelector::Range(min, max), rest.trim_start()));
}
None
}
fn substitute(template: &str, params: &[(&str, &str)]) -> String {
let mut result = template.to_string();
for (name, value) in params {
result = result.replace(&format!(":{name}"), value);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
fn write_locale_file(dir: &Path, locale: &str, contents: &str) {
std::fs::write(dir.join(format!("{locale}.json")), contents).unwrap();
}
#[test]
fn load_catalog_from_a_missing_directory_is_empty() {
let catalog = load_catalog_from(Path::new("/nonexistent/path/that/does/not/exist"));
assert!(catalog.is_empty());
}
#[test]
fn load_catalog_reads_every_json_file_by_its_own_stem_as_the_locale() {
let dir = tempfile::tempdir().unwrap();
write_locale_file(dir.path(), "en", r#"{"messages.welcome": "Welcome!"}"#);
write_locale_file(dir.path(), "es", r#"{"messages.welcome": "¡Bienvenido!"}"#);
std::fs::write(dir.path().join("README.md"), "not json, ignored").unwrap();
let catalog = load_catalog_from(dir.path());
assert_eq!(
catalog.get("en").unwrap().get("messages.welcome").unwrap(),
"Welcome!"
);
assert_eq!(
catalog.get("es").unwrap().get("messages.welcome").unwrap(),
"¡Bienvenido!"
);
assert_eq!(catalog.len(), 2);
}
#[test]
fn load_catalog_skips_a_file_that_isnt_a_flat_string_map() {
let dir = tempfile::tempdir().unwrap();
write_locale_file(dir.path(), "broken", r#"{"nested": {"not": "flat"}}"#);
let catalog = load_catalog_from(dir.path());
assert!(catalog.is_empty());
}
#[test]
fn substitute_replaces_every_named_placeholder() {
assert_eq!(
substitute(
"Hello, :name! You have :count messages.",
&[("name", "Alice"), ("count", "3"),]
),
"Hello, Alice! You have 3 messages."
);
}
#[test]
fn substitute_with_no_params_leaves_the_template_unchanged() {
assert_eq!(substitute("Welcome!", &[]), "Welcome!");
}
#[test]
fn pluralize_leaves_a_plain_template_with_no_pipe_untouched() {
assert_eq!(pluralize("Welcome!", &[("count", "5")]), "Welcome!");
}
#[test]
fn pluralize_simple_form_picks_singular_for_exactly_one() {
assert_eq!(pluralize("apple|apples", &[("count", "1")]), "apple");
}
#[test]
fn pluralize_simple_form_picks_plural_for_zero_and_for_many() {
assert_eq!(pluralize("apple|apples", &[("count", "0")]), "apples");
assert_eq!(pluralize("apple|apples", &[("count", "2")]), "apples");
}
#[test]
fn pluralize_explicit_selectors_pick_the_matching_exact_or_range_segment() {
let template = "{0} no apples|{1} one apple|[2,*] :count apples";
assert_eq!(pluralize(template, &[("count", "0")]), "no apples");
assert_eq!(pluralize(template, &[("count", "1")]), "one apple");
assert_eq!(pluralize(template, &[("count", "2")]), ":count apples");
assert_eq!(pluralize(template, &[("count", "100")]), ":count apples");
}
#[test]
fn pluralize_closed_range_selector_only_matches_within_bounds() {
let template = "[0,1] a few|[2,5] several|[6,*] many";
assert_eq!(pluralize(template, &[("count", "1")]), "a few");
assert_eq!(pluralize(template, &[("count", "4")]), "several");
assert_eq!(pluralize(template, &[("count", "6")]), "many");
assert_eq!(pluralize(template, &[("count", "1000")]), "many");
}
#[test]
fn pluralize_degrades_to_the_last_segment_when_count_is_missing() {
assert_eq!(pluralize("apple|apples", &[]), "apples");
}
#[test]
fn pluralize_degrades_to_the_last_segment_when_count_does_not_parse() {
assert_eq!(
pluralize("apple|apples", &[("count", "not-a-number")]),
"apples"
);
}
#[test]
fn pluralize_end_to_end_through_t_with_also_substitutes_count() {
let dir = tempfile::tempdir().unwrap();
write_locale_file(
dir.path(),
"en",
r#"{"cart.items": "{0} no items|{1} one item|[2,*] :count items"}"#,
);
let catalog = load_catalog_from(dir.path());
let template = catalog
.get("en")
.and_then(|entries| entries.get("cart.items"))
.unwrap();
assert_eq!(
substitute(pluralize(template, &[("count", "3")]), &[("count", "3")]),
"3 items"
);
}
fn init_config() {
larust_core::Application::new(|| serde_json::json!({"app_locale": "en"})).unwrap();
}
#[tokio::test]
async fn current_locale_falls_back_to_config_default_outside_a_scope() {
init_config();
assert_eq!(current_locale(), "en");
}
#[tokio::test]
async fn set_current_locale_overrides_only_within_its_own_scope() {
init_config();
with_locale_scope(async {
assert_eq!(current_locale(), "en");
set_current_locale("es".to_string());
assert_eq!(current_locale(), "es");
})
.await;
with_locale_scope(async {
assert_eq!(current_locale(), "en");
})
.await;
}
#[tokio::test]
async fn set_current_locale_outside_a_scope_is_a_no_op() {
init_config();
set_current_locale("es".to_string());
assert_eq!(current_locale(), "en");
}
#[tokio::test]
async fn t_or_falls_back_to_the_given_default_not_the_bare_key() {
init_config();
assert_eq!(
t_or("nonexistent.key", "a sensible default"),
"a sensible default"
);
}
#[tokio::test]
async fn t_or_with_substitutes_placeholders_in_the_default_too() {
init_config();
assert_eq!(
t_or_with("nonexistent.key", "Hello, :name!", &[("name", "Alice")]),
"Hello, Alice!"
);
}
}