mod catalog;
mod locale;
use std::sync::Arc;
use crate::arena::{ScratchArena, StrRef};
pub use catalog::DynamicCatalog;
pub use catalog::{
format_plural_key, format_template, I18nArg, MessageEntry, StaticCatalog, StaticLocaleTable,
};
pub use locale::detect_system_locale;
pub use locale::{Locale, PluralCategory, TextDirection};
pub struct I18nContext {
pub locale: Locale,
pub static_catalog: Option<&'static StaticCatalog>,
pub dynamic_catalog: Option<Arc<DynamicCatalog>>,
}
impl Default for I18nContext {
#[inline]
fn default() -> Self {
Self::new(Locale::EN_US)
}
}
impl I18nContext {
#[inline]
pub const fn new(locale: Locale) -> Self {
Self {
locale,
static_catalog: None,
dynamic_catalog: None,
}
}
#[inline]
pub fn lookup_template(&self, key: &str) -> Option<&str> {
if let Some(dyn_cat) = &self.dynamic_catalog {
if let Some(v) = dyn_cat.lookup(self.locale, key) {
return Some(v);
}
}
if let Some(st_cat) = self.static_catalog {
if let Some(v) = st_cat.lookup(self.locale, key) {
return Some(v);
}
}
None
}
#[inline]
pub fn lookup_plural_template(&self, key: &str, count: i64) -> Option<&str> {
if let Some(dyn_cat) = &self.dynamic_catalog {
if let Some(v) = dyn_cat.lookup_plural(self.locale, key, count) {
return Some(v);
}
}
if let Some(st_cat) = self.static_catalog {
if let Some(v) = st_cat.lookup_plural(self.locale, key, count) {
return Some(v);
}
}
None
}
#[inline]
pub fn translate<'a>(&self, arena: &'a ScratchArena, key: &str) -> StrRef<'a> {
if let Some(dyn_cat) = &self.dynamic_catalog {
if let Some(v) = dyn_cat.lookup(self.locale, key) {
return arena.alloc_str(v);
}
}
if let Some(st_cat) = self.static_catalog {
if let Some(v) = st_cat.lookup(self.locale, key) {
return StrRef::from(v);
}
}
arena.alloc_str(key)
}
#[inline]
pub fn translate_args<'a>(
&self,
arena: &'a ScratchArena,
key: &str,
args: &[(&str, I18nArg<'_>)],
) -> StrRef<'a> {
let tmpl = self.lookup_template(key).unwrap_or(key);
format_template(arena, tmpl, args)
}
#[inline]
pub fn translate_plural<'a>(
&self,
arena: &'a ScratchArena,
key: &str,
count: i64,
) -> StrRef<'a> {
let tmpl = self.lookup_plural_template(key, count).unwrap_or(key);
format_template(arena, tmpl, &[("count", I18nArg::Int(count))])
}
}