fluent_templates/loader/
static_loader.rsuse std::borrow::Cow;
use std::collections::HashMap;
use crate::{error::LookupError, languages::negotiate_languages, FluentBundle};
use fluent_bundle::{FluentResource, FluentValue};
pub use unic_langid::LanguageIdentifier;
pub struct StaticLoader {
bundles: &'static HashMap<LanguageIdentifier, FluentBundle<&'static FluentResource>>,
fallbacks: &'static HashMap<LanguageIdentifier, Vec<LanguageIdentifier>>,
fallback: LanguageIdentifier,
}
impl StaticLoader {
#[doc(hidden)]
pub fn new(
bundles: &'static HashMap<LanguageIdentifier, FluentBundle<&'static FluentResource>>,
fallbacks: &'static HashMap<LanguageIdentifier, Vec<LanguageIdentifier>>,
fallback: LanguageIdentifier,
) -> Self {
Self {
bundles,
fallbacks,
fallback,
}
}
pub fn lookup_single_language<S: AsRef<str>>(
&self,
lang: &LanguageIdentifier,
text_id: &str,
args: Option<&HashMap<S, FluentValue>>,
) -> Result<String, LookupError> {
super::shared::lookup_single_language(self.bundles, lang, text_id, args)
}
pub fn lookup_no_default_fallback<S: AsRef<str>>(
&self,
lang: &LanguageIdentifier,
text_id: &str,
args: Option<&HashMap<S, FluentValue>>,
) -> Option<String> {
super::shared::lookup_no_default_fallback(self.bundles, self.fallbacks, lang, text_id, args)
}
pub fn fallback(&self) -> &LanguageIdentifier {
&self.fallback
}
}
impl super::Loader for StaticLoader {
fn lookup_complete(
&self,
lang: &LanguageIdentifier,
text_id: &str,
args: Option<&HashMap<Cow<'static, str>, FluentValue>>,
) -> String {
for lang in negotiate_languages(&[lang], &self.bundles.keys().collect::<Vec<_>>(), None) {
if let Ok(val) = self.lookup_single_language(lang, text_id, args) {
return val;
}
}
if *lang != self.fallback {
if let Ok(val) = self.lookup_single_language(&self.fallback, text_id, args) {
return val;
}
}
format!("Unknown localization {text_id}")
}
fn try_lookup_complete(
&self,
lang: &LanguageIdentifier,
text_id: &str,
args: Option<&HashMap<Cow<'static, str>, FluentValue>>,
) -> Option<String> {
for lang in negotiate_languages(&[lang], &self.bundles.keys().collect::<Vec<_>>(), None) {
if let Ok(val) = self.lookup_single_language(lang, text_id, args) {
return Some(val);
}
}
if *lang != self.fallback {
if let Ok(val) = self.lookup_single_language(&self.fallback, text_id, args) {
return Some(val);
}
}
None
}
fn locales(&self) -> Box<dyn Iterator<Item = &LanguageIdentifier> + '_> {
Box::new(self.fallbacks.keys())
}
}