group-actor/src/tr.rs

84 lines
2.2 KiB
Rust
Raw Normal View History

2021-10-05 23:09:20 +00:00
//! magic for custom translations and strings
use std::collections::HashMap;
2021-11-02 22:49:00 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2021-10-05 23:09:20 +00:00
pub struct TranslationTable {
#[serde(flatten)]
entries: HashMap<String, String>,
2021-10-05 23:09:20 +00:00
}
impl TranslationTable {
#[allow(unused)]
2021-10-05 23:09:20 +00:00
pub fn new() -> Self {
Self::default()
}
/// Iterate all entries
2021-11-02 22:49:00 +00:00
pub fn entries(&self) -> impl Iterator<Item = (&String, &String)> {
self.entries.iter()
}
2021-11-02 22:49:00 +00:00
pub fn get_translation_raw(&self, key: &str) -> Option<&str> {
self.entries.get(key).map(|s| s.as_str())
}
/// Add or update a translation
2021-11-02 22:49:00 +00:00
pub fn add_translation(&mut self, key: impl ToString, subs: impl ToString) {
self.entries.insert(key.to_string(), subs.to_string());
}
2021-11-02 22:49:00 +00:00
pub fn translation_exists(&self, key: &str) -> bool {
self.entries.contains_key(key)
2021-10-05 23:09:20 +00:00
}
2021-11-02 22:49:00 +00:00
pub fn subs(&self, key: &str, substitutions: &[&str]) -> String {
match self.entries.get(key) {
Some(s) => {
// TODO optimize
let mut s = s.clone();
for pair in substitutions.chunks(2) {
if pair.len() != 2 {
continue;
2021-10-05 23:09:20 +00:00
}
s = s.replace(&format!("{{{}}}", pair[0]), pair[1]);
2021-10-05 23:09:20 +00:00
}
s
2021-10-05 23:09:20 +00:00
}
2021-11-02 22:49:00 +00:00
None => key.to_owned(),
2021-10-05 23:09:20 +00:00
}
}
}
#[cfg(test)]
mod tests {
use crate::tr::TranslationTable;
#[test]
fn deser_tr_table() {
2021-11-02 22:49:00 +00:00
let tr: TranslationTable = serde_json::from_str(r#"{"foo":"bar"}"#).unwrap();
2021-10-05 23:09:20 +00:00
assert_eq!("bar", tr.subs("foo", &[]));
assert_eq!("xxx", tr.subs("xxx", &[]));
}
#[test]
fn subs() {
let mut tr = TranslationTable::new();
tr.add_translation("hello_user", "Hello, {user}!");
assert_eq!("Hello, James!", tr.subs("hello_user", &["user", "James"]));
}
}
#[macro_export]
macro_rules! tr {
($tr_haver:expr, $key:literal) => {
$tr_haver.tr().subs($key, &[])
};
($tr_haver:expr, $key:literal, $($k:tt=$value:expr),*) => {
$tr_haver.tr().subs($key, &[
$(stringify!($k), $value),*
])
};
}