Skip to content

Commit

Permalink
Optimize fallback initialization on static loader macro (#77)
Browse files Browse the repository at this point in the history
  • Loading branch information
mondeja authored Aug 19, 2024
1 parent f6a9793 commit b6a4929
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ keywords = ["handlebars", "tera", "fluent", "internationalization", "localizatio
categories = ["internationalization", "localization", "template-engine"]

[workspace.dependencies]
unic-langid = "0.9"
unic-langid = { version = "0.9", features = ["macros"] }
ignore = "0.4"
flume = { version = "0.11", default-features = false }
once_cell = "1.19"
Expand Down
25 changes: 18 additions & 7 deletions macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,11 +208,24 @@ pub fn static_loader(input: proc_macro::TokenStream) -> proc_macro::TokenStream
quote!(None)
};

let fallback_language_value = fallback_language.value();
if !fallback_language_value.parse::<unic_langid::LanguageIdentifier>().is_ok() {
return syn::Error::new(
fallback_language.span(),
format!(
"Invalid language identifier \"{}\" for fallback language",
&fallback_language_value
),
)
.to_compile_error()
.into();
}

let mut insert_resources: Vec<_> = build_resources(locales_directory).into_iter().collect();

if !insert_resources
.iter()
.any(|(lang, _)| *lang == fallback_language.value())
.any(|(lang, _)| *lang == fallback_language_value)
{
return syn::Error::new(
fallback_language.span(),
Expand Down Expand Up @@ -271,18 +284,16 @@ pub fn static_loader(input: proc_macro::TokenStream) -> proc_macro::TokenStream
)
});

static LOCALES:
#LAZY<Vec<#LANGUAGE_IDENTIFIER>> =
#LAZY::new(|| RESOURCES.keys().cloned().collect());

static FALLBACKS:
#LAZY<#HASHMAP<#LANGUAGE_IDENTIFIER, Vec<#LANGUAGE_IDENTIFIER>>> =
#LAZY::new(|| #CRATE_NAME::loader::build_fallbacks(&*LOCALES));
#LAZY::new(|| #CRATE_NAME::loader::build_fallbacks(
&RESOURCES.keys().cloned().collect::<Vec<#LANGUAGE_IDENTIFIER>>()
));

#CRATE_NAME::StaticLoader::new(
&BUNDLES,
&FALLBACKS,
#fallback_language.parse().expect("invalid fallback language")
#CRATE_NAME::langid!(#fallback_language_value)
)
});
};
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,8 @@ pub mod loader;
#[cfg(feature = "macros")]
pub use fluent_template_macros::static_loader;
pub use unic_langid::LanguageIdentifier;
#[cfg(feature = "macros")]
pub use unic_langid::langid;

#[doc(hidden)]
pub use once_cell;
Expand Down

0 comments on commit b6a4929

Please sign in to comment.