aboutsummaryrefslogtreecommitdiff
path: root/base
diff options
context:
space:
mode:
Diffstat (limited to 'base')
-rw-r--r--base/src/locale.rs48
1 files changed, 33 insertions, 15 deletions
diff --git a/base/src/locale.rs b/base/src/locale.rs
index a1c5ef2..188ab63 100644
--- a/base/src/locale.rs
+++ b/base/src/locale.rs
@@ -1,26 +1,44 @@
-use std::{borrow::Cow, collections::HashMap};
+use std::{borrow::Cow, collections::HashMap, sync::LazyLock};
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Language {
English,
German,
}
-pub fn tr<'a>(lang: Language, key: &str, args: &[(&str, &str)]) -> Cow<'a, str> {
- let source_str = match lang {
- Language::English => include_str!("../../locale/en.ini"),
- Language::German => include_str!("../../locale/de.ini"),
- };
- let tr_map = source_str
- .lines()
- .filter_map(|line| {
- let (key, value) = line.split_once("=")?;
- Some((key.trim(), value.trim()))
- })
- .collect::<HashMap<&'static str, &'static str>>();
+static LANG_TABLES: LazyLock<HashMap<Language, HashMap<&'static str, &'static str>>> =
+ LazyLock::new(|| {
+ let mut k = HashMap::new();
+ for (lang, source) in [
+ (Language::English, include_str!("../../locale/en.ini")),
+ (Language::German, include_str!("../../locale/de.ini")),
+ ] {
+ let tr_map = source
+ .lines()
+ .filter_map(|line| {
+ let (key, value) = line.split_once("=")?;
+ Some((key.trim(), value.trim()))
+ })
+ .collect::<HashMap<&'static str, &'static str>>();
+ k.insert(lang, tr_map);
+ }
+ k
+ });
+pub fn tr(lang: Language, key: &str, args: &[(&str, &str)]) -> Cow<'static, str> {
+ let tr_map = LANG_TABLES.get(&lang).unwrap();
match tr_map.get(key) {
- Some(value) => Cow::Borrowed(value),
+ Some(value) => {
+ if args.is_empty() {
+ Cow::Borrowed(value)
+ } else {
+ let mut s = value.to_string();
+ for (k, v) in args {
+ s = s.replace(&format!("{{{k}}}"), v)
+ }
+ Cow::Owned(s)
+ }
+ }
None => Cow::Owned(format!("TR[{key}]")),
}
}