Skip to main content

Crate localize_it

Crate localize_it 

Source
Expand description

§localize_it

Tests Crates.io Documentation License

A tiny, fast, and zero-dependency localization system with #![no_std] support.

This crate provides a macro-based API to define compile-time locales and localized expressions without dynamic memory, hash maps, or external dependencies. All localized expressions are stored as static arrays, allowing localization via simple indexing. You can manage the locale manually (via init_locale!), or use the built-in AtomicUsize locale storage with Relaxed ordering (via init_locale_with_storage!).


§Example

A program that asks the user to choose a language, enter their name, and then greets them in the selected language:

use localize_it::{expressions, init_locale_with_storage, localize};
use std::io::{stdin, stdout, Write};

// Define available locales
init_locale_with_storage!(En, Ru);

// Expressions can be any type allowed in compile-time context
expressions!(
    ENTER_LANGUAGE => {
        En: "Enter En or Ru: ",
        Ru: "Введите En или Ru: ",
    },
    ENTER_YOUR_NAME => {
        En: "Please, enter your name: ",
        Ru: "Пожалуйста, введите ваше имя: ",
    },
    HELLO: fn(&str) -> String => {
        En: |name: &str| format!("Hello, {name}!"),
        Ru: |name: &str| format!("Привет, {name}!"),
    },
);

// Input helper for the demonstration
fn input() -> String {
    let mut temp = String::new();

    stdout().flush().unwrap();
    stdin().read_line(&mut temp).unwrap();
    temp.trim().to_string()
}

fn main() {
    // You can set locale manually
    print!("{}", localize!(ENTER_LANGUAGE, Locale::En));

    let lang = input();

    // Set the selected locale
    set_locale_from_caseless_str(&lang);

    // Uses the currently selected locale automatically
    print!("{}", localize!(ENTER_YOUR_NAME));

    let name = input();

    // Use callable expression
    println!("{}", localize!(HELLO as (&name)));
}

A recommended way to organize your project is to create a dedicated locale module that handles locale initialization and contains grouped expression modules. For example:

src/
├─ main.rs
└─ locale/
   ├─ mod.rs     # Initialization locale here
   ├─ error.rs   # First module with expressions
   └─ ui.rs      # Second module with expressions

§Design Constraints

  • Not possible to update or add the translations without recompiling
  • No plans to add automatic gender agreement, numeral declension, etc

§Usage

Add the following to your Cargo.toml:

[dependencies]
localize_it = "1.5.0"

§License

This project is licensed under either of

at your option.

Macros§

expression
Initializes a localized expression.
expressions
Initializes localized expressions.
init_locale
Initializes the localization system.
init_locale_with_storage
Initializes the localization system and the mechanism for storing the current locale.
localize
Returns the translation of an expression.