diff options
author | metamuffin <metamuffin@disroot.org> | 2024-09-16 20:34:05 +0200 |
---|---|---|
committer | metamuffin <metamuffin@disroot.org> | 2024-09-16 20:34:05 +0200 |
commit | 9a1a3fd088b9839c654241188172234ab558729d (patch) | |
tree | 624d253b9e2bbeadf7adfb0dd61565b820777d42 /pixel-client/src/strings.rs | |
parent | ae6ca47c264a4fc3b15e99b1424e11472923d4be (diff) | |
download | hurrycurry-9a1a3fd088b9839c654241188172234ab558729d.tar hurrycurry-9a1a3fd088b9839c654241188172234ab558729d.tar.bz2 hurrycurry-9a1a3fd088b9839c654241188172234ab558729d.tar.zst |
pc: localization
Diffstat (limited to 'pixel-client/src/strings.rs')
-rw-r--r-- | pixel-client/src/strings.rs | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/pixel-client/src/strings.rs b/pixel-client/src/strings.rs new file mode 100644 index 00000000..cf225c7d --- /dev/null +++ b/pixel-client/src/strings.rs @@ -0,0 +1,42 @@ +use anyhow::{anyhow, Result}; +use std::{ + collections::HashMap, + fs::read_to_string, + ops::Index, + path::Path, + sync::{LazyLock, Mutex}, +}; + +pub struct Strings(HashMap<String, String>); +impl Index<&'static str> for Strings { + type Output = str; + fn index(&self, index: &'static str) -> &Self::Output { + self.0.get(index).map(|s| s.as_str()).unwrap_or(index) + } +} + +impl Strings { + pub fn load(path: &Path) -> Result<Self> { + Ok(Self( + read_to_string(path)? + .lines() + .skip(1) + .map(|l| { + let (k, v) = l.split_once("=").ok_or(anyhow!("'=' missing"))?; + Ok::<_, anyhow::Error>((k.to_owned(), v.replace("%n", "\n"))) + }) + .try_collect()?, + )) + } +} + +static TR_LOAD: Mutex<Option<Strings>> = Mutex::new(None); +static TR: LazyLock<Strings> = LazyLock::new(|| TR_LOAD.lock().unwrap().take().unwrap()); + +pub fn tr<'a>(s: &'static str) -> &'a str { + &TR[s] +} +pub fn set_language(lang: &str) { + *TR_LOAD.lock().unwrap() = + Some(Strings::load(Path::new(&format!("locale/{lang}.ini"))).unwrap()); +} |