Skip to main content

Lang

Struct Lang 

Source
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

Source

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");
Source

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");
Source

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");
Source

pub fn locale() -> &'static str

Returns the currently active locale.

§Examples
use lang_lib::Lang;

Lang::set_locale("fr");
assert_eq!(Lang::locale(), "fr");
Source

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()]);
Source

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();
Source

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();
Source

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"));
Source

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"]);
Source

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"));
Source

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");
Source

pub fn translate<'a>( key: &'a str, locale: Option<&'a str>, fallback: Option<&'a str>, ) -> Cow<'a, str>

Translates a key.

Lookup order:

  1. The requested locale (or active locale if None)
  2. Each locale in the fallback chain, in order
  3. The inline fallback string if provided
  4. 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");

Auto Trait Implementations§

§

impl Freeze for Lang

§

impl RefUnwindSafe for Lang

§

impl Send for Lang

§

impl Sync for Lang

§

impl Unpin for Lang

§

impl UnsafeUnpin for Lang

§

impl UnwindSafe for Lang

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.