pleroma groups!!!!!! try it ->
https://piggo.space/hob
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
2.1 KiB
82 lines
2.1 KiB
4 years ago
|
//! magic for custom translations and strings
|
||
|
|
||
|
use std::collections::HashMap;
|
||
|
use once_cell::sync::Lazy;
|
||
|
|
||
|
#[derive(Debug,Clone,Serialize,Deserialize,Default)]
|
||
|
pub struct TranslationTable {
|
||
|
#[serde(flatten)]
|
||
|
entries: Option<HashMap<String, String>>,
|
||
|
}
|
||
|
|
||
|
pub const EMPTY_TRANSLATION_TABLE : TranslationTable = TranslationTable {
|
||
|
entries: None,
|
||
|
};
|
||
|
|
||
|
impl TranslationTable {
|
||
|
pub fn new() -> Self {
|
||
|
Self::default()
|
||
|
}
|
||
|
|
||
|
pub fn add_translation(&mut self, key : impl ToString, subs : impl ToString) {
|
||
|
if self.entries.is_none() {
|
||
|
self.entries = Some(Default::default());
|
||
|
}
|
||
|
self.entries.as_mut().unwrap().insert(key.to_string(), subs.to_string());
|
||
|
}
|
||
|
|
||
|
pub fn subs(&self, key : &str, substitutions: &[&str]) -> String {
|
||
|
if let Some(ee) = &self.entries {
|
||
|
match ee.get(key) {
|
||
|
Some(s) => {
|
||
|
// TODO optimize
|
||
|
let mut s = s.clone();
|
||
|
for pair in substitutions.chunks(2) {
|
||
|
if pair.len() != 2 {
|
||
|
continue;
|
||
|
}
|
||
|
s = s.replace(&format!("{{{}}}", pair[0]), pair[1]);
|
||
|
}
|
||
|
s
|
||
|
}
|
||
|
None => key.to_owned()
|
||
|
}
|
||
|
} else {
|
||
|
key.to_owned()
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
#[cfg(test)]
|
||
|
mod tests {
|
||
|
use crate::tr::TranslationTable;
|
||
|
|
||
|
#[test]
|
||
|
fn deser_tr_table() {
|
||
|
let tr : TranslationTable = serde_json::from_str(r#"{"foo":"bar"}"#).unwrap();
|
||
|
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),*
|
||
|
])
|
||
|
};
|
||
|
}
|