Skip to main content

Crate embedded_i18n

Crate embedded_i18n 

Source
Expand description

Compile-time internationalization for embedded and no_std Rust, with a rust-i18n style API.

Translations are read from locale files at build time by procedural macros and embedded in the binary as &'static str literals: no runtime parsing, no allocator, no file system, and a missing translation is a compile error at the call site.

§Quick start

Put locale files in a locales/ directory next to Cargo.toml:

{
  "greeting": "Hello",
  "files": { "one": "{count} file", "other": "{count} files" }
}

Call i18n! once at the crate root, before any mod declaration, then translate with t!:

embedded_i18n::i18n!("locales");
use core::fmt::Write;
use embedded_i18n::t;

const GREETING: &str = t!("greeting");
assert_eq!(GREETING, "Hello");

let mut output = String::new();
write!(output, "{}", t!("with_arg", value = 42))?;
assert_eq!(output, "Value: 42");

assert_eq!(t!("files", count = 2).to_string(), "2 files");

§Macros

MacroResult
i18n!Configures the translations of the crate, once at its root
t!&'static str (or &'static CStr) without arguments, a core::fmt::Display value with arguments or count
locale!Name of the locale the crate translates into
available_locales!Locales embedded in the crate

§Configuration

i18n! takes the locale directory and options, read from [package.metadata.i18n] in Cargo.toml when not given:

i18n! argument[package.metadata.i18n] keyDefaultMeaning
first positional stringload-path"locales"Locale directory, relative to Cargo.toml
fallback = "en" or ["en", "es"]fallback["en"]Fallback chain after the locale and its parents
default_locale = "fr"default-locale"en"Locale active at startup
available_locales = [..]available-locales[default_locale]Embedded locales; more than one enables runtime selection
strict = truestrictfalseForbids falling back for messages missing from the primary locale
bidi_isolation = truebidi-isolationfalseIsolates placeholders of right-to-left locales

The EMBEDDED_I18N_LOCALE and EMBEDDED_I18N_LOCALES (comma separated) environment variables override default_locale and available_locales in every crate of the build, to build one firmware per language. Cargo rebuilds the crate when a locale file, Cargo.toml or one of these variables changes.

Locales are normalized like BCP 47 tags and resolved from the most specific to the most generic (fr-CA, fr, then the fallbacks). The special locale pseudo generates a pseudo-localization of the fallback locales.

§Runtime locales

With several available_locales, set_locale selects the locale at runtime, for every crate of the program: each one translates into its closest embedded locale, or its default_locale. t!("key", locale = "fr") translates into a given locale without touching the global one.

embedded_i18n::i18n!("locales", available_locales = ["en", "fr"]);
use embedded_i18n::{locale, set_locale, t};

fn main() {
    assert_eq!(t!("greeting", locale = "fr-CA"), "Bonjour");
    set_locale("fr");
    assert_eq!(t!("greeting"), "Bonjour");
    assert_eq!(locale!(), "fr");
    set_locale("de");
    assert_eq!(t!("greeting"), "Hello");
}

§Locale file formats

Each format is enabled by a Cargo feature; all parsing happens in the procedural macro, so formats add nothing to the binary.

FeatureFiles
backend-json (default).json, nested objects flattened to dotted keys
backend-yaml.yaml, .yml
backend-toml.toml
backend-poGNU gettext .po, with msgctxt, plural forms and Plural-Forms
backend-moCompiled GNU gettext .mo
backend-fluentFluent .ftl simple messages and whole-message selects

§Runtime helpers

§Features

  • alloc: String and Vec returning variants of the helpers.
  • std: enables alloc and system_locale(), the locale of the operating system.

§Guide

The guide follows the Diátaxis structure:

Modules§

guide
User guide for embedded-i18n, organized in four parts:

Macros§

available_locales
Lists the locales embedded in the calling crate, as &'static [&'static str], in configuration order.
i18n
Configures the translations of the calling crate.
locale
Returns the name of the locale the calling crate translates into, as a &'static str.
t
Translates a message key, at compile time.

Structs§

DateTimeDisplay
Timestamp formatted on display, returned by DateTimeFormatter::display.
DateTimeFormatter
Formats Unix timestamps with strftime-style patterns, localized and without allocation.
DateTimeLocale
Month and weekday names, AM/PM markers and default patterns of a locale, used by DateTimeFormatter.
Locale
A locale, packed into a 32-bit identifier.

Constants§

ARABIC
Arabic code points, as a half-open range.
ARABIC_SUPPLEMENT
Arabic Supplement code points, as a half-open range.
BASIC_LATIN
Basic Latin (printable ASCII) code points, as a half-open range.
CJK_UNIFIED_IDEOGRAPHS
CJK Unified Ideographs code points, as a half-open range.
CYRILLIC
Cyrillic code points, as a half-open range.
CYRILLIC_SUPPLEMENT
Cyrillic Supplement code points, as a half-open range.
DEVANAGARI
Devanagari code points, as a half-open range.
ENGLISH
English (United States) names and patterns.
GREEK
Greek and Coptic code points, as a half-open range.
GREEK_EXTENDED
Greek Extended code points, as a half-open range.
HANGUL_SYLLABLES
Hangul Syllables code points, as a half-open range.
HEBREW
Hebrew code points, as a half-open range.
HIRAGANA
Hiragana code points, as a half-open range.
KATAKANA
Katakana code points, as a half-open range.
LATIN_1_SUPPLEMENT
Latin-1 Supplement code points, as a half-open range.
LATIN_EXTENDED_A
Latin Extended-A code points, as a half-open range.
LATIN_EXTENDED_ADDITIONAL
Latin Extended Additional code points, as a half-open range.
LATIN_EXTENDED_B
Latin Extended-B code points, as a half-open range.
THAI
Thai code points, as a half-open range.
VIETNAMESE_EXTENSIONS
Vietnamese letters of Latin Extended Additional code points, as a half-open range.

Functions§

date_time_locale
Returns the built-in names and patterns of a locale, English if the language is not covered.
find_date_time_locale
Returns the built-in names and patterns of a locale, or None if the language is not covered.
format_range
Formats a range like write_range. Available with the alloc feature.
format_ranges
Formats ranges like write_ranges. Available with the alloc feature.
format_unix_timestamp
Formats a Unix timestamp into a String, in English and UTC. For another locale, use DateTimeFormatter. Available with the alloc feature.
get_locale_ranges
Returns the Unicode ranges needed to render a language, to subset fonts.
is_right_to_left
Returns whether a locale is written right to left.
merge_contiguous_ranges
Sorts ranges and merges overlapping or adjacent ones. Available with the alloc feature.
merge_contiguous_ranges_in_place
Sorts ranges and merges overlapping or adjacent ones, in place and without allocation.
set_locale
Selects the current locale used by t! and locale!.
system_locale
Returns the locale of the operating system, from the LC_ALL, LC_MESSAGES and LANG environment variables, as a BCP 47 style tag (fr_FR.UTF-8 becomes fr-FR). Available with the std feature.
write_range
Writes a range as start-end (inclusive end), or start for a single code point.
write_ranges
Writes ranges as a comma separated list, as accepted by font subsetting tools.
write_unix_timestamp
Writes a Unix timestamp formatted with a pattern, in English and UTC. For another locale, use DateTimeFormatter. See DateTimeFormatter for the tokens.