use dashmap::DashMap;
use serde_json::Value;
use std::{fs, path::Path, sync::Arc};
pub type LocaleStore = Arc<DashMap<String, serde_json::Map<String, Value>>>;
pub fn new_store() -> LocaleStore {
Arc::new(DashMap::new())
}
pub fn load_dir(dir: impl AsRef<Path>, default_locale: &str) -> LocaleStore {
let store = new_store();
if let Ok(entries) = fs::read_dir(dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
let Some(lang) = path
.file_stem()
.and_then(|s| s.to_str())
.map(str::to_lowercase)
else {
continue;
};
if let Ok(content) = fs::read_to_string(&path) {
if let Ok(Value::Object(map)) = serde_json::from_str(&content) {
store.insert(lang, map);
}
}
}
}
store.entry(default_locale.to_string()).or_default();
store
}
pub fn load_from_pairs(entries: impl IntoIterator<Item = (&'static str, Value)>) -> LocaleStore {
let store = new_store();
for (lang, value) in entries {
if let Value::Object(map) = value {
store.insert(lang.to_lowercase(), map);
}
}
store
}