pub struct Lang;Expand description
The main entry point for configuring and querying the localization system.
Lang manages process-global state behind a lock-free arc_swap::ArcSwap
snapshot. Configure it once during startup, load the locales your
application needs, and then use t! or Lang::translate
wherever translated text is needed.
Concurrent calls to Lang::translate do not contend on any lock. Write
operations (set_*, Lang::load, Lang::unload) briefly serialize
against each other but never block readers.
Implementations§
Source§impl Lang
impl Lang
Sourcepub fn set_path(path: impl AsRef<str>)
pub fn set_path(path: impl AsRef<str>)
Sets the directory where language files are looked up.
Defaults to "locales". Call this before the first Lang::load if
your project stores files elsewhere.
§Examples
use lang_lib::Lang;
Lang::set_path("assets/lang");Sourcepub fn path() -> &'static str
pub fn path() -> &'static str
Returns the current language file path.
§Examples
use lang_lib::Lang;
Lang::set_path("assets/locales");
assert_eq!(Lang::path(), "assets/locales");Sourcepub fn set_locale(locale: impl AsRef<str>)
pub fn set_locale(locale: impl AsRef<str>)
Sets the active locale used when no locale is specified in t!.
The locale does not need to be loaded before calling this, but translations will be empty until it is.
This method is a good fit for single-user applications, CLIs, and
startup-time configuration. In request-driven servers, prefer passing
an explicit locale to Lang::translate or t! so one
request does not change another request’s active locale.
§Examples
use lang_lib::Lang;
Lang::set_locale("es");Sourcepub fn locale() -> &'static str
pub fn locale() -> &'static str
Returns the currently active locale.
§Examples
use lang_lib::Lang;
Lang::set_locale("fr");
assert_eq!(Lang::locale(), "fr");Sourcepub fn set_fallbacks(chain: Vec<String>)
pub fn set_fallbacks(chain: Vec<String>)
Sets the fallback locale chain.
When a key is not found in the requested locale, each fallback is
checked in order. The last resort is the inline fallback: argument
in t!, and if that is absent, the key itself is returned.
§Examples
use lang_lib::Lang;
Lang::set_fallbacks(vec!["en".to_string()]);Sourcepub fn load(locale: impl AsRef<str>) -> Result<(), LangError>
pub fn load(locale: impl AsRef<str>) -> Result<(), LangError>
Loads a locale from disk.
Reads {path}/{locale}.toml and stores all translations in memory.
Calling this a second time for the same locale replaces the existing
translations with a fresh load from disk.
Locale names must be single file stems such as en, en-US, or
pt_BR. Path separators and relative path components are rejected.
§Errors
Returns LangError::Io if the file cannot be read, or
LangError::Parse if the TOML is invalid.
§Examples
use lang_lib::Lang;
Lang::set_path("locales");
Lang::load("en").unwrap();
Lang::load("es").unwrap();Sourcepub fn load_from(locale: impl AsRef<str>, path: &str) -> Result<(), LangError>
pub fn load_from(locale: impl AsRef<str>, path: &str) -> Result<(), LangError>
Loads a locale from a specific path, ignoring the global path setting.
Useful when a project stores one locale separately from the others.
Locale names follow the same validation rules as Lang::load.
§Errors
Returns LangError::Io or LangError::Parse on failure.
§Examples
use lang_lib::Lang;
Lang::load_from("en", "tests/fixtures/locales").unwrap();Sourcepub fn is_loaded(locale: &str) -> bool
pub fn is_loaded(locale: &str) -> bool
Returns true if the locale has been loaded.
§Examples
use lang_lib::Lang;
Lang::load_from("en", "tests/fixtures/locales").unwrap();
assert!(Lang::is_loaded("en"));Sourcepub fn loaded() -> Vec<&'static str>
pub fn loaded() -> Vec<&'static str>
Returns a sorted list of all loaded locale identifiers.
Sorting keeps diagnostics and tests deterministic.
§Examples
use lang_lib::Lang;
Lang::load_from("es", "tests/fixtures/locales").unwrap();
Lang::load_from("en", "tests/fixtures/locales").unwrap();
assert_eq!(Lang::loaded(), vec!["en", "es"]);Sourcepub fn unload(locale: &str)
pub fn unload(locale: &str)
Unloads a locale and removes it from the lookup table.
Unloading a locale does not change the active locale or fallback chain. If either of those still references the removed locale, translation will simply skip it.
Note: in 1.1.x, translation strings are interned into a process-wide
pool, so unloading a locale removes it from the lookup table but does
not reclaim the interned bytes themselves. The 1.2.x hot-reload
milestone revisits this so long-running reloaders do not grow the
interner without bound.
§Examples
use lang_lib::Lang;
Lang::load_from("en", "tests/fixtures/locales").unwrap();
Lang::unload("en");
assert!(!Lang::is_loaded("en"));Sourcepub fn translator(locale: impl AsRef<str>) -> Translator
pub fn translator(locale: impl AsRef<str>) -> Translator
Creates a request-scoped Translator for the provided locale.
This is a convenience wrapper around Translator::new. It is most
useful in server code where locale is resolved per request and passed
through the handler stack.
§Examples
use lang_lib::Lang;
let translator = Lang::translator("es");
assert_eq!(translator.locale(), "es");Sourcepub fn translate<'a>(
key: &'a str,
locale: Option<&'a str>,
fallback: Option<&'a str>,
) -> Cow<'a, str>
pub fn translate<'a>( key: &'a str, locale: Option<&'a str>, fallback: Option<&'a str>, ) -> Cow<'a, str>
Translates a key.
Lookup order:
- The requested locale (or active locale if
None) - Each locale in the fallback chain, in order
- The inline
fallbackstring if provided - The key itself (never returns an empty string)
The hot path is lock-free and zero-allocation: a hit returns
Cow::Borrowed backed by the interned translation store; a miss
with an inline fallback returns Cow::Borrowed of the user-supplied
fallback; a complete miss returns Cow::Borrowed of the key.
The returned value derefs to &str and works transparently with
format!, println!, and equality against &str.
This is the function called by the t! macro. Prefer
using the macro directly in application code.
In concurrent server code, passing Some(locale) is usually the safest
policy because it avoids mutating the process-wide active locale.
§Examples
use lang_lib::Lang;
Lang::load_from("en", "tests/fixtures/locales").unwrap();
let text = Lang::translate("welcome", Some("en"), Some("Welcome"));
assert_eq!(text, "Welcome");