Skip to main content

Crate lang_lib

Crate lang_lib 

Source
Expand description

A lightweight, high-performance localization library.

lang-lib loads TOML language files, supports runtime locale switching, configurable file paths, and automatic fallback chains. It is designed to be dropped into any project without ceremony.

§What This Crate Does Well

  • Keeps the runtime model simple: load files once, then translate by key.
  • Uses plain TOML so translators and developers can inspect files easily.
  • Works across platforms by resolving file paths with native path handling.
  • Fails predictably with typed errors when files are missing or invalid.

§Quick Start

use lang_lib::{t, Lang};

// Configure once at startup
Lang::set_path("locales");
Lang::load("en").unwrap();
Lang::load("es").unwrap();
Lang::set_locale("en");

// Translate anywhere
let msg = t!("bad_password");
let msg_es = t!("bad_password", "es");
let msg_fb = t!("missing_key", fallback: "Default message");

§Small Tutorial

  1. Create a directory for locale files.
  2. Add one TOML file per locale.
  3. Load the locales your application needs at startup.
  4. Set the active locale for the current process.
  5. Use t! anywhere you need translated text.

Example layout:

your-app/
|- Cargo.toml
|- src/
|  \- main.rs
\- locales/
   |- en.toml
   \- es.toml

§File Format

Language files are plain TOML, one key per line:

bad_password = "Your password is incorrect."
welcome_user = "Welcome back"
not_found    = "The page you requested does not exist."

Files are resolved as {path}/{locale}.toml.

§Behavior Notes

Lookup order is deterministic:

  1. Requested locale, or the active locale when none is provided
  2. Each configured fallback locale in order
  3. The inline fallback passed to t!
  4. The key itself

Non-string TOML values are ignored on purpose. That keeps translation data flat and avoids surprising coercions at runtime.

§Examples

See the runnable example in examples/basic.rs for a complete setup using real locale files. See examples/server.rs for a server-oriented pattern that resolves a locale per request and passes it explicitly during translation. See examples/axum_server.rs for the same pattern inside a real HTTP handler using axum. See examples/actix_server.rs for the same pattern using actix-web. Locale names must be a single file stem such as en, en-US, or pt_BR.

Macros§

t
Translates a key using the active locale.

Structs§

Lang
The main entry point for configuring and querying the localization system.
Translator
A lightweight, request-scoped translation helper.

Enums§

LangError
Errors produced by lang-lib.

Functions§

resolve_accept_language
Resolves an Accept-Language header against a supported locale list.
resolve_accept_language_owned
Resolves an Accept-Language header against a runtime locale list and returns an owned String.