### Install rust-i18n-cli Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Install the `cargo-i18n` command-line tool for extracting untranslated texts into YAML files. ```bash $ cargo install rust-i18n-cli ``` -------------------------------- ### Install rust-i18n CLI Source: https://docs.rs/rust-i18n/latest/index.html Install the rust-i18n command-line tool using cargo. This command provides the `cargo i18n` functionality. ```bash cargo install rust-i18n-cli ``` -------------------------------- ### Example Usage of `replace_patterns` Source: https://docs.rs/rust-i18n/latest/src/rust_i18n/lib.rs.html Demonstrates how to use the `replace_patterns` function to substitute placeholders in a string. Ensure the `rust_i18n` crate is imported. ```rust use rust_i18n::replace_patterns; let input = "Hello, %{name}!"; let patterns = &["name"]; let values = &["world".to_string()]; let output = replace_patterns(input, patterns, values); assert_eq!(output, "Hello, world!"); ``` -------------------------------- ### YAML Locale File (_version: 1) Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Example of a locale file in YAML format using _version 1, where each locale is in a separate file. ```yaml _version: 1 hello: "Hello world" messages.hello: "Hello, %{name}" t_4Cct6Q289b12SkvF47dXIx: "Hello, %{name}" ``` -------------------------------- ### JSON Locale File (_version: 1) Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Example of a locale file in JSON format using _version 1, where each locale is in a separate file. ```json { "_version": 1, "hello": "Hello world", "messages.hello": "Hello, %{name}", "t_4Cct6Q289b12SkvF47dXIx": "Hello, %{name}" } ``` -------------------------------- ### YAML Locale File (_version: 2) Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Example of a locale file in YAML format using _version 2, where all localized texts are in the same file. ```yaml _version: 2 hello: en: Hello world zh-CN: 你好世界 messages.hello: en: Hello, %{name} zh-CN: 你好,%{name} ``` -------------------------------- ### Import and Use t! Macro Source: https://docs.rs/rust-i18n/latest/index.html Import the `t!` macro and initialize `i18n!` in each file where you intend to use it. This example shows basic usage of `t!` and `available_locales!`. ```rust use rust_i18n::t; rust_i18n::i18n!("locales"); fn main() { // Find the translation for the string literal `Hello` using the manually provided key `hello`. println!("{}", t!("hello")); // Use `available_locales!` method to get all available locales. println!("{:?}", rust_i18n::available_locales!()); } ``` -------------------------------- ### Get Available Locales Source: https://docs.rs/rust-i18n/latest/src/rust_i18n/lib.rs.html The available_locales! macro retrieves a list of all locales that are currently available in the project. The example shows how to call the macro and indicates the expected output format. ```rust #[macro_use] extern crate rust_i18n; # pub fn _rust_i18n_available_locales() -> Vec<&'static str> { todo!() } # fn main() { rust_i18n::available_locales!(); # } // => ["en", "zh-CN"] ``` -------------------------------- ### TOML Locale File (_version: 1) Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Example of a locale file in TOML format using _version 1, where each locale is in a separate file. ```toml hello = "Hello world" t_4Cct6Q289b12SkvF47dXIx = "Hello, %{name}" [messages] hello = "Hello, %{name}" ``` -------------------------------- ### Using t! Macro and available_locales! Macro Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Import the `t!` macro and demonstrate its usage for translating strings. Also shows how to get a list of all available locales. ```rust // You must import in each files when you wants use `t!` macro. use rust_i18n::t; rust_i18n::i18n!("locales"); fn main() { // Find the translation for the string literal `Hello` using the manually provided key `hello`. println!("{}", t!("hello")); // Use `available_locales!` method to get all available locales. println!("{:?}", rust_i18n::available_locales!()); } ``` -------------------------------- ### Get help for cargo i18n Source: https://docs.rs/rust-i18n/latest/index.html Display the help message for the `cargo i18n` command to understand its available options and usage. ```bash cargo i18n -h ``` -------------------------------- ### Get Available Locales Source: https://docs.rs/rust-i18n/latest/rust_i18n/macro.available_locales.html Use the available_locales macro to get a list of all supported locales. Ensure the rust_i18n crate is included and the macro is properly invoked. ```rust #[macro_use] extern crate rust_i18n; rust_i18n::available_locales!(); // => ["en", "zh-CN"] ``` -------------------------------- ### Basic Translation with `t!` Macro Source: https://docs.rs/rust-i18n/latest/src/rust_i18n/lib.rs.html Shows how to get a translated string using the current locale. This is the simplest form of translation. ```rust #[macro_use] extern crate rust_i18n; # macro_rules! t { ($($all:tt)*) => {} } # fn main() { // Simple get text with current locale t!("greeting"); // greeting: "Hello world" => "Hello world" # } ``` -------------------------------- ### Get available locales from SimpleBackend Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.SimpleBackend.html Retrieves a list of all locales for which translations are currently available in the SimpleBackend. ```rust fn available_locales(&self) -> Vec> ``` -------------------------------- ### Set and Get Current Locale Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Manage the global locale at runtime using `set_locale()` and retrieve it with `locale()`. ```rust rust_i18n::set_locale("zh-CN"); let locale = rust_i18n::locale(); assert_eq!(&*locale, "zh-CN"); ``` -------------------------------- ### Run cargo i18n command Source: https://docs.rs/rust-i18n/latest/index.html Execute the `cargo i18n` command to extract untranslated texts from your project's source code and generate YAML files for translations. This example shows running it for multiple locales. ```bash cd your_project_root_directory cargo i18n ``` -------------------------------- ### Simple text retrieval with current locale Source: https://docs.rs/rust-i18n/latest/rust_i18n/macro.t.html Use the `t` macro to get translated text for the current locale. The output shows the key and its translation. ```rust #[macro_use] extern crate rust_i18n; // Simple get text with current locale t!("greeting"); // greeting: "Hello world" => "Hello world" ``` -------------------------------- ### Get all messages for a locale Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.SimpleBackend.html Retrieves all translation key-value pairs for a specified locale from the SimpleBackend. Returns None if the locale is not found. ```rust fn messages_for_locale( &self, locale: &str, ) -> Option, Cow<'_, str>)>> ``` -------------------------------- ### Define the available_locales! Macro Source: https://docs.rs/rust-i18n/latest/src/rust_i18n/lib.rs.html This macro provides a simple interface to get the list of available locales by calling the internal _rust_i18n_available_locales function. ```rust macro_rules! available_locales { () => { crate::_rust_i18n_available_locales() }; } ``` -------------------------------- ### Translate Messages with Locale and Variables Source: https://docs.rs/rust-i18n/latest/src/rust_i18n/lib.rs.html Translate messages using a specific locale and provide variables for substitution. This example demonstrates translating a message with the 'de' locale and a 'name' variable. ```rust t!("messages.hello", locale = "de", name = "Jason"); // messages.hello: "Hallo, %{name}" => "Hallo, Jason" ``` -------------------------------- ### Create a new SimpleBackend Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.SimpleBackend.html Instantiates a new SimpleBackend. This is the entry point for using the SimpleBackend for storing translations. ```rust pub fn new() -> SimpleBackend ``` -------------------------------- ### SimpleBackend::new Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.SimpleBackend.html Creates a new instance of SimpleBackend. This is the entry point for using the SimpleBackend for storing translations. ```APIDOC ## SimpleBackend::new ### Description Creates a new SimpleBackend. ### Method `new()` ### Returns - `SimpleBackend`: A new, empty SimpleBackend instance. ``` -------------------------------- ### Default SimpleBackend creation Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.SimpleBackend.html Provides a default SimpleBackend instance, equivalent to calling `SimpleBackend::new()`. ```rust fn default() -> SimpleBackend ``` -------------------------------- ### Default::default Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.SimpleBackend.html Provides a default SimpleBackend instance. This is equivalent to calling `SimpleBackend::new()`. ```APIDOC ## Default::default ### Description Returns the “default value” for a type. ### Method `default() -> SimpleBackend` ### Returns - `SimpleBackend`: A default SimpleBackend instance. ``` -------------------------------- ### Get TypeId of AtomicStr Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.AtomicStr.html Implements the Any trait for AtomicStr, providing a method to retrieve the TypeId of the instance. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Initialize i18n with Custom Backend Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Initialize the rust-i18n framework with your custom backend, which will be prioritized over local translations. ```rust fn messages_for_locale(&self, locale: &str) -> Option, Cow<'_, str>)>> { todo!() } rust_i18n::i18n!("locales", backend = RemoteI18n::new()); ``` -------------------------------- ### Get Current Locale Source: https://docs.rs/rust-i18n/latest/rust_i18n/fn.locale.html Retrieves the current locale as a string slice. This function is part of the rust_i18n crate for managing internationalization settings. ```rust pub fn locale() -> impl Deref ``` -------------------------------- ### Get Current Locale Source: https://docs.rs/rust-i18n/latest/src/rust_i18n/lib.rs.html Retrieves the current locale as a Deref type. This allows easy access to the active locale string. ```rust pub fn locale() -> impl Deref { CURRENT_LOCALE.as_str() } ``` -------------------------------- ### CowStr Conversions Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Demonstrates the various ways to convert different types into CowStr. ```APIDOC ## Trait Implementations for CowStr ### `From<&'a str>` Converts a string slice `&'a str` into `CowStr<'a>`. ### `From<&'a String>` Converts a reference to a `String` `&'a String` into `CowStr<'a>`. ### `From` Converts an owned `String` into `CowStr<'a>`. ### `From>` Converts an `Arc` containing a string slice `Arc<&'a str>` into `CowStr<'a>`. ### `From>` Converts an `Arc` containing a `String` `Arc` into `CowStr<'a>`. ### `From>` Converts an `Arc` containing a string slice `Arc` into `CowStr<'a>`. ### `From>` Converts a `Box` containing a string slice `Box<&'a str>` into `CowStr<'a>`. ### `From>` Converts a `Box` containing a `String` `Box` into `CowStr<'a>`. ### `From>` Converts a `Box` containing a string slice `Box` into `CowStr<'a>`. ### Numeric Conversions `CowStr<'a>` can also be created from various integer types: - `From` - `From` - `From` - `From` - `From` - `From` - `From` - `From` - `From` - `From` - `From` - `From` Each of these implementations converts the numeric value into its string representation before creating the `CowStr`. ``` -------------------------------- ### Cargo i18n Help Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html View the help information for the `cargo i18n` command to understand its usage, options, and arguments. ```bash $ cargo i18n -h cargo-i18n 3.1.0 --------------------------------------- Rust I18n command to help you extract all untranslated texts from source code. It will iterate all Rust files in the source directory and extract all untranslated texts that used `t!` macro. Then it will generate a YAML file and merge with the existing translations. https://github.com/longbridge/rust-i18n Usage: cargo i18n [OPTIONS] [-- ] Arguments: [SOURCE] Extract all untranslated I18n texts from source code [default: ./] Options: -t, --translate ... Manually add a translation to the localization file. This is useful for non-literal values in the `t!` macro. For example, if you have `t!(format!("Hello, {}!", "world"))` in your code, you can add a translation for it using `-t "Hello, world!"`, or provide a translated message using `-t "Hello, world! => Hola, world!"`. NOTE: The whitespace before and after the key and value will be trimmed. -h, --help Print help (see a summary with '-h') -V, --version Print version ``` -------------------------------- ### Get String Slice from AtomicStr Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.AtomicStr.html Retrieves a string slice (&str) from an AtomicStr instance. This allows read-only access to the underlying string data. ```rust pub fn as_str(&self) -> impl Deref ``` -------------------------------- ### Initialize Translations with Default Configuration Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Load the I18n macro and initialize translations using the `i18n!` macro. This uses the default configuration from Cargo.toml or built-in defaults. ```rust # Load I18n macro, for allow you use `t!` macro in anywhere. #[macro_use] extern crate rust_i18n; // Init translations for current crate. // This will load Configuration using the `[package.metadata.i18n]` section in `Cargo.toml` if exists. // Or you can pass arguments by `i18n!` to override it. i18n!("locales"); // If no any argument, use config from Cargo.toml or default. i18n!(); ``` -------------------------------- ### Use tkv macro for translation Source: https://docs.rs/rust-i18n/latest/rust_i18n/macro.tkv.html Demonstrates how to use the tkv macro to generate a translation key and value pair. The key can be minified if hints are present. ```rust use rust_i18n::{t, tkv}; let (key, msg) = tkv!("Hello world"); // => key is "Hello world" and msg is the translated message. // => If there is hints the minify_key logic, the key will returns a minify key. ``` -------------------------------- ### Initialize Translations with i18n! Macro Source: https://docs.rs/rust-i18n/latest/index.html Load the I18n macro and initialize translations in your `lib.rs` or `main.rs`. This macro can load configuration from `Cargo.toml` or accept arguments to override settings. ```rust #[macro_use] extern crate rust_i18n; i18n!("locales"); ``` ```rust #[macro_use] extern crate rust_i18n; i18n!("locales", fallback = "en"); ``` ```rust #[macro_use] extern crate rust_i18n; i18n!("locales", fallback = ["en", "es"]); ``` ```rust #[macro_use] extern crate rust_i18n; i18n!("locales", minify_key = true); ``` ```rust #[macro_use] extern crate rust_i18n; i18n!("locales", minify_key = true, minify_key_len = 12, minify_key_prefix = "t_", minify_key_thresh = 64 ); ``` ```rust #[macro_use] extern crate rust_i18n; i18n!(); ``` -------------------------------- ### FromIterator::from_iter Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.SimpleBackend.html Creates a SimpleBackend from an iterator of locale-to-translation-map pairs. This is a convenient way to initialize the backend with multiple locales and their translations. ```APIDOC ## FromIterator::from_iter ### Description Creates a value from an iterator. ### Method `from_iter(iter: I) -> SimpleBackend` ### Type Parameters - `I`: An iterator that yields tuples of `(Cow<'static, str>, HashMap, Cow<'static, str>>)`. ### Parameters - **iter** (`I`): An iterator providing locale and translation data. ### Returns - `SimpleBackend`: A SimpleBackend populated with translations from the iterator. ``` -------------------------------- ### Extend SimpleBackend with another Backend Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.SimpleBackend.html Combines the current SimpleBackend with another Backend implementation, creating a CombinedBackend that can serve translations from both. ```rust fn extend(self, other: T) -> CombinedBackend where T: Backend, Self: Sized, ``` -------------------------------- ### Create SimpleBackend from an iterator Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.SimpleBackend.html Constructs a SimpleBackend from an iterator yielding locale-translation map pairs. Useful for bulk initialization. ```rust fn from_iter(iter: I) -> SimpleBackend where I: IntoIterator, HashMap, Cow<'static, str>>)>, ``` -------------------------------- ### MinifyKey Implementation for Cow<'a, str> Source: https://docs.rs/rust-i18n/latest/rust_i18n/trait.MinifyKey.html Provides an implementation of the MinifyKey trait for an owned Cow<'a, str>. This allows key generation directly from a Cow<'a, str> value. ```rust impl<'a> MinifyKey<'a> for Cow<'a, str> { fn minify_key( &'a self, len: usize, prefix: &str, threshold: usize, ) -> Cow<'a, str> } ``` -------------------------------- ### Specify locale for cargo i18n Source: https://docs.rs/rust-i18n/latest/index.html Use the `--locale` option with `cargo i18n` to specify a particular locale for extracting untranslated texts. This example demonstrates generating translations for the 'fr' locale. ```bash cargo i18n --locale fr ``` -------------------------------- ### Benchmark t! Method Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Performance benchmarks for the `t!` macro and its variants, showing execution times in nanoseconds. ```text t time: [32.637 ns 33.139 ns 33.613 ns] t_with_locale time: [24.616 ns 24.812 ns 25.071 ns] t_with_args time: [128.70 ns 128.97 ns 129.24 ns] t_with_args (str) time: [129.48 ns 130.08 ns 130.76 ns] t_with_args (many) time: [370.28 ns 374.46 ns 380.56 ns] t_with_threads time: [38.619 ns 39.506 ns 40.419 ns] t_lorem_ipsum time: [33.867 ns 34.286 ns 34.751 ns] ``` -------------------------------- ### Initialize Translations with Minified Keys Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Enable minified keys for long string literals to optimize memory usage and lookup speed. This can be configured with custom length, prefix, and threshold. ```rust # Load I18n macro, for allow you use `t!` macro in anywhere. #[macro_use] extern crate rust_i18n; // Use a short hashed key as an identifier for long string literals // to optimize memory usage and lookup speed. // The key generation algorithm is `${Prefix}${Base62(SipHash13("msg"))}`. i18n!("locales", minify_key = true); // // Alternatively, you can customize the key length, prefix, // and threshold for the short hashed key. i18n!("locales", minify_key = true, minify_key_len = 12, minify_key_prefix = "t_", minify_key_thresh = 64 ); // Now, if the message length exceeds 64, the `t!` macro will automatically generate // a 12-byte short hashed key with a "t_" prefix for it, if not, it will use the original. ``` -------------------------------- ### MinifyKey Implementation for &Cow<'a, str> Source: https://docs.rs/rust-i18n/latest/rust_i18n/trait.MinifyKey.html Provides an implementation of the MinifyKey trait for a reference to a Cow<'a, str>. This allows generating translation keys from borrowed or owned string data. ```rust impl<'a> MinifyKey<'a> for &Cow<'a, str> { fn minify_key( &'a self, len: usize, prefix: &str, threshold: usize, ) -> Cow<'a, str> } ``` -------------------------------- ### MinifyKey Implementation for &String Source: https://docs.rs/rust-i18n/latest/rust_i18n/trait.MinifyKey.html Provides an implementation of the MinifyKey trait for a reference to a String. This enables key generation from owned String objects. ```rust impl<'a> MinifyKey<'a> for &String { fn minify_key( &'a self, len: usize, prefix: &str, threshold: usize, ) -> Cow<'a, str> } ``` -------------------------------- ### MinifyKey Implementation for str Source: https://docs.rs/rust-i18n/latest/rust_i18n/trait.MinifyKey.html Provides an implementation of the MinifyKey trait for a raw str. This allows key generation from string slices directly. ```rust impl<'a> MinifyKey<'a> for str { fn minify_key( &'a self, len: usize, prefix: &str, threshold: usize, ) -> Cow<'a, str> } ``` -------------------------------- ### From<&'a String> for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from a reference to a String to CowStr. ```rust fn from(s: &'a String) -> CowStr<'a> ``` -------------------------------- ### From for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from a String to CowStr. ```rust fn from(s: String) -> CowStr<'a> ``` -------------------------------- ### BackendExt::extend Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.SimpleBackend.html Extends the current SimpleBackend with translations from another Backend. This allows combining multiple translation sources. ```APIDOC ## BackendExt::extend ### Description Extend backend to add more translations. ### Method `extend(self, other: T) -> CombinedBackend` ### Type Parameters - `T`: The type of the other Backend to combine with. ### Parameters - **other** (`T`): The other Backend instance to merge translations from. ### Returns - `CombinedBackend`: A new backend that combines translations from both the original and the `other` backend. ``` -------------------------------- ### From for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from an i64 integer to CowStr. ```rust fn from(val: i64) -> CowStr<'a> ``` -------------------------------- ### From for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from a u64 integer to CowStr. ```rust fn from(val: u64) -> CowStr<'a> ``` -------------------------------- ### Translation with Variables Source: https://docs.rs/rust-i18n/latest/src/rust_i18n/lib.rs.html Illustrates how to include variables within translation keys. The variables are defined using `key = value` syntax. ```rust #[macro_use] extern crate rust_i18n; # macro_rules! t { ($($all:tt)*) => {} } # fn main() { // With variables t!("messages.hello", name = "world"); // messages.hello: "Hello, %{name}" => "Hello, world" t!("messages.foo", name = "Foo", other ="Bar"); // messages.foo: "Hello, %{name} and %{other}" => "Hello, Foo and Bar" # } ``` -------------------------------- ### Add translations to SimpleBackend Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.SimpleBackend.html Adds a set of translations for a specific locale to the SimpleBackend. Ensure translations are provided as a HashMap where keys and values are Cow<'static, str>. ```rust let mut trs = HashMap::new(); trs.insert("hello".into(), "Hello".into()); trs.insert("foo".into(), "Foo bar".into()); backend.add_translations("en".into(), trs); ``` -------------------------------- ### AtomicStr Methods Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.AtomicStr.html This section details the core methods available for the AtomicStr struct, including creation, accessing the underlying string slice, and replacing the string's content. ```APIDOC ## pub fn new(value: &str) -> AtomicStr ### Description Creates a new `AtomicStr` with the given string value. ### Method `new` ### Parameters * `value` (&str) - The string slice to initialize the `AtomicStr` with. ### Returns A new `AtomicStr` instance. ## pub fn as_str(&self) -> impl Deref ### Description Retrieves a reference to the underlying string slice managed by `AtomicStr`. ### Method `as_str` ### Returns An object that dereferences to a string slice (`&str`). ## pub fn replace(&self, src: impl Into) ### Description Replaces the current string value held by `AtomicStr` with a new one provided by `src`. ### Method `replace` ### Parameters * `src` (impl Into) - The new string value to set. Can be any type that can be converted into a `String`. ``` -------------------------------- ### From for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from an i32 integer to CowStr. ```rust fn from(val: i32) -> CowStr<'a> ``` -------------------------------- ### Initialize Translations with Fallback Locale Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Configure a fallback locale for translations. If a translation is missing in the current locale, it will attempt to use the fallback locale. ```rust # Load I18n macro, for allow you use `t!` macro in anywhere. #[macro_use] extern crate rust_i18n; // Config fallback missing translations to "en" locale. // Use `fallback` option to set fallback locale. // i18n!("locales", fallback = "en"); // Or more than one fallback with priority. // i18n!("locales", fallback = ["en", "es"]); ``` -------------------------------- ### Custom Remote Translation Backend Source: https://docs.rs/rust-i18n/latest/index.html Implement a custom `Backend` for `rust-i18n` to fetch translations from a remote server using HTTP and YAML parsing. ```rust use rust_i18n::Backend; pub struct RemoteI18n { trs: HashMap>, } impl RemoteI18n { fn new() -> Self { // fetch translations from remote URL let response = reqwest::blocking::get("https://your-host.com/assets/locales.yml").unwrap(); let trs = serde_yaml::from_str::>>(&response.text().unwrap()).unwrap(); return Self { trs }; } } impl Backend for RemoteI18n { fn available_locales(&self) -> Vec> { return self.trs.keys().map(|k| Cow::from(k.as_str())).collect(); } fn translate(&self, locale: &str, key: &str) -> Option> { // Write your own lookup logic here. // For example load from database return self.trs.get(locale)?.get(key).map(|k| Cow::from(k.as_str())); } fn messages_for_locale(&self, locale: &str) -> Option, Cow<'_, str>)>> { None } } ``` -------------------------------- ### Custom Remote Translation Backend Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Implement the `Backend` trait to create a custom translation provider, such as fetching translations from a remote server. ```rust use rust_i18n::Backend; use std::borrow::Cow; use std::collections::HashMap; pub struct RemoteI18n { trs: HashMap>, } impl RemoteI18n { fn new() -> Self { // fetch translations from remote URL let response = reqwest::blocking::get("https://your-host.com/assets/locales.yml").unwrap(); let trs = serde_yaml::from_str::>>(&response.text().unwrap()).unwrap(); return Self { trs }; } } impl Backend for RemoteI18n { fn available_locales(&self) -> Vec> { return self.trs.keys().map(|k| Cow::from(k.as_str())).collect(); } fn translate(&self, locale: &str, key: &str) -> Option> { // Write your own lookup logic here. // For example load from database return self.trs.get(locale)?.get(key).map(|k| Cow::from(k.as_str())); } fn messages_for_locale(&self, locale: &str) -> Option, Cow<'_, str>)>> { None } } ``` -------------------------------- ### MinifyKey Implementation for String Source: https://docs.rs/rust-i18n/latest/rust_i18n/trait.MinifyKey.html Provides an implementation of the MinifyKey trait for an owned String. This enables key generation from String objects. ```rust impl<'a> MinifyKey<'a> for String { fn minify_key( &'a self, len: usize, prefix: &str, threshold: usize, ) -> Cow<'a, str> } ``` -------------------------------- ### MinifyKey Implementation for &str Source: https://docs.rs/rust-i18n/latest/rust_i18n/trait.MinifyKey.html Provides an implementation of the MinifyKey trait for a string slice (&str). This is a common use case for generating keys from string literals or borrowed string data. ```rust impl<'a> MinifyKey<'a> for &str { fn minify_key( &'a self, len: usize, prefix: &str, threshold: usize, ) -> Cow<'a, str> } ``` -------------------------------- ### From for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from an i8 integer to CowStr. ```rust fn from(val: i8) -> CowStr<'a> ``` -------------------------------- ### From for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from an isize integer to CowStr. ```rust fn from(val: isize) -> CowStr<'a> ``` -------------------------------- ### From for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from a u32 integer to CowStr. ```rust fn from(val: u32) -> CowStr<'a> ``` -------------------------------- ### Add rust-i18n Dependency Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Add the rust-i18n crate to your project's Cargo.toml file. ```toml [dependencies] rust-i18n = "3" ``` -------------------------------- ### CowStr Blanket Implementations Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html This section details the blanket implementations provided for CowStr<'a>, showing how it conforms to various standard Rust traits. ```APIDOC ## Blanket Implementations for CowStr<'a> ### `impl Any for T where T: 'static + ?Sized` #### `fn type_id(&self) -> TypeId` Gets the `TypeId` of `self`. ### `impl Borrow for T where T: ?Sized` #### `fn borrow(&self) -> &T` Immutably borrows from an owned value. ### `impl BorrowMut for T where T: ?Sized` #### `fn borrow_mut(&mut self) -> &mut T` Mutably borrows from an owned value. ### `impl From for T` #### `fn from(t: T) -> T` Returns the argument unchanged. ### `impl Into for T where U: From` #### `fn into(self) -> U` Calls `U::from(self)`. ### `impl TryFrom for T where U: Into` #### `type Error = Infallible` The type returned in the event of a conversion error. #### `fn try_from(value: U) -> Result>::Error>` Performs the conversion. ### `impl TryInto for T where U: TryFrom` #### `type Error = >::Error` The type returned in the event of a conversion error. #### `fn try_into(self) -> Result>::Error>` Performs the conversion. ``` -------------------------------- ### From<&'a str> for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from a string slice to CowStr. ```rust fn from(s: &'a str) -> CowStr<'a> ``` -------------------------------- ### Import t! Macro Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Import the `t!` macro from the rust_i18n crate to use it in your Rust code. ```rust use rust_i18n::t; ``` -------------------------------- ### From for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from a usize integer to CowStr. ```rust fn from(val: usize) -> CowStr<'a> ``` -------------------------------- ### From for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from an i16 integer to CowStr. ```rust fn from(val: i16) -> CowStr<'a> ``` -------------------------------- ### AtomicStr Trait Implementations Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.AtomicStr.html This section outlines the various trait implementations for AtomicStr, including Display, From<&str>, and other auto and blanket implementations that define its behavior and interoperability. ```APIDOC ### impl Display for AtomicStr #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> ##### Description Formats the `AtomicStr` value using the given formatter. This allows `AtomicStr` to be used with formatting macros like `println!`. ##### Parameters * `f` (&mut Formatter<'_>) - The formatter to use. ##### Returns A `Result` indicating success or an error during formatting. ### impl From<&str> for AtomicStr #### fn from(value: &str) -> AtomicStr ##### Description Converts a string slice (`&str`) into an `AtomicStr`. This provides a convenient way to create `AtomicStr` instances from existing string literals or slices. ##### Parameters * `value` (&str) - The string slice to convert. ##### Returns A new `AtomicStr` instance initialized with the provided string slice. ``` -------------------------------- ### From> for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from a Box-referenced string slice to CowStr. ```rust fn from(s: Box<&'a str>) -> CowStr<'a> ``` -------------------------------- ### Define the t macro Source: https://docs.rs/rust-i18n/latest/rust_i18n/macro.t.html This shows the basic definition of the `t` macro. ```rust macro_rules! t { ($($all:tt)*) => { ... }; } ``` -------------------------------- ### From> for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from a Box-boxed string slice to CowStr. ```rust fn from(s: Box) -> CowStr<'a> ``` -------------------------------- ### Create New AtomicStr Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.AtomicStr.html Creates a new AtomicStr instance initialized with a given string slice. This is the primary way to create an AtomicStr. ```rust pub fn new(value: &str) -> AtomicStr ``` -------------------------------- ### From> for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from a Box-referenced String to CowStr. ```rust fn from(s: Box) -> CowStr<'a> ``` -------------------------------- ### fn extend(self, other: T) -> CombinedBackend Source: https://docs.rs/rust-i18n/latest/rust_i18n/trait.BackendExt.html Extends a backend with another backend to add more translations. This method allows for combining multiple translation sources into a single, unified backend. ```APIDOC ## fn extend(self, other: T) -> CombinedBackend ### Description Extend backend to add more translations ### Method Signature ```rust fn extend(self, other: T) -> CombinedBackend where T: Backend, Self: Sized ``` ### Generics - **T**: A type that implements the `Backend` trait. ### Type Parameters - **Self**: The type of the backend instance, must implement `BackendExt` and `Sized`. ### Return Value - `CombinedBackend`: A new backend that combines the translations from `self` and `other`. ``` -------------------------------- ### Define tkv macro Source: https://docs.rs/rust-i18n/latest/rust_i18n/macro.tkv.html Defines the basic structure of the tkv macro, accepting a literal string. ```rust macro_rules! tkv { ($msg:literal) => { ... }; } ``` -------------------------------- ### Basic t! Macro Usage Source: https://docs.rs/rust-i18n/latest/index.html Use the `t!` macro to retrieve localized strings. The default locale is used if not specified. ```rust // use rust_i18n::t; t!( ``` -------------------------------- ### Basic t! Macro Usage Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Use the `t!` macro to retrieve localized strings. You can specify a locale or let it use the default. ```rust // use rust_i18n::t; t!( ``` ```rust hello"); // => "Hello world" t!("hello", locale = "zh-CN"); // => "你好世界" ``` -------------------------------- ### From for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from a u8 integer to CowStr. ```rust fn from(val: u8) -> CowStr<'a> ``` -------------------------------- ### Default Minify Key Constant Source: https://docs.rs/rust-i18n/latest/rust_i18n/constant.DEFAULT_MINIFY_KEY.html Shows the default value for the minify_key feature, which is set to false. ```rust pub const DEFAULT_MINIFY_KEY: bool = false; ``` -------------------------------- ### Default Minify Key Prefix Constant Source: https://docs.rs/rust-i18n/latest/rust_i18n/constant.DEFAULT_MINIFY_KEY_PREFIX.html This constant specifies the prefix used for automatically generated translation keys. It is a static string slice. ```rust pub const DEFAULT_MINIFY_KEY_PREFIX: &'static str; ``` -------------------------------- ### Text retrieval with locale and variables Source: https://docs.rs/rust-i18n/latest/rust_i18n/macro.t.html Combine locale specification with variable substitution for targeted, personalized translations. ```rust // With locale and variables t!("messages.hello", locale = "de", name = "Jason"); // messages.hello: "Hallo, %{name}" => "Hallo, Jason" ``` -------------------------------- ### From for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from a u16 integer to CowStr. ```rust fn from(val: u16) -> CowStr<'a> ``` -------------------------------- ### available_locales! macro Source: https://docs.rs/rust-i18n/latest/src/rust_i18n/lib.rs.html The `available_locales!` macro retrieves a list of all locales that are currently available and configured for the application. ```APIDOC ## available_locales! macro ### Description This macro returns a vector of strings, where each string represents an available locale supported by the application. This is useful for dynamically displaying language options or for debugging purposes. ### Returns A `Vec<&'static str>` containing the identifiers of all available locales. ### Example ```rust use rust_i18n::available_locales; let locales = available_locales!(); // If 'en' and 'zh-CN' are configured, locales might be `["en", "zh-CN"]`. ``` ``` -------------------------------- ### Enable codegen debugging Source: https://docs.rs/rust-i18n/latest/index.html Enable debugging information during the code generation process by setting the `RUST_I18N_DEBUG` environment variable to '1'. This is useful for troubleshooting. ```bash RUST_I18N_DEBUG=1 cargo build ``` -------------------------------- ### Backend::translate Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.SimpleBackend.html Retrieves a specific translation for a given locale and key from the SimpleBackend. ```APIDOC ## Backend::translate ### Description Get the translation for the given locale and key. ### Method `translate(&self, locale: &str, key: &str) -> Option>` ### Parameters - **locale** (`&str`): The locale for which to retrieve the translation. - **key** (`&str`): The key of the translation to retrieve. ### Returns - `Option>`: An `Option` containing the translated string if found, otherwise `None`. ``` -------------------------------- ### From<&&'a str> for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from a double-referenced string slice to CowStr. ```rust fn from(s: &&'a str) -> CowStr<'a> ``` -------------------------------- ### Translate a key for a specific locale Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.SimpleBackend.html Fetches the translated string for a given locale and key from the SimpleBackend. Returns None if the locale or key is not found. ```rust fn translate(&self, locale: &str, key: &str) -> Option> ``` -------------------------------- ### Generate Translation Key-Value Pairs Source: https://docs.rs/rust-i18n/latest/src/rust_i18n/lib.rs.html Use the tkv! macro to create a key-value pair from a literal string. This is useful for long messages where you want to avoid repeating the string as a key. The macro returns a tuple of (key, msg). ```rust use rust_i18n::{t, tkv}; # macro_rules! t { ($($all:tt)*) => { } } # macro_rules! tkv { ($($all:tt)*) => { (1,2) } } let (key, msg) = tkv!("Hello world"); // => key is "Hello world" and msg is the translated message. // => If there is hints the minify_key logic, the key will returns a minify key. ``` -------------------------------- ### From for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from an i128 integer to CowStr. ```rust fn from(val: i128) -> CowStr<'a> ``` -------------------------------- ### Debug Codegen Process Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Enable debugging information during the code generation process by setting the `RUST_I18N_DEBUG` environment variable. ```bash $ RUST_I18N_DEBUG=1 cargo build ``` -------------------------------- ### Translation with Specific Locale Source: https://docs.rs/rust-i18n/latest/src/rust_i18n/lib.rs.html Demonstrates how to specify a locale for translation, overriding the current global locale. Useful for testing or specific language outputs. ```rust #[macro_use] extern crate rust_i18n; # macro_rules! t { ($($all:tt)*) => {} } # fn main() { // Get a special locale's text t!("greeting", locale = "de"); // greeting: "Hallo Welt!" => "Hallo Welt!" # } ``` -------------------------------- ### Try Convert To AtomicStr Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.AtomicStr.html Implements the TryInto trait for AtomicStr, enabling fallible conversions from AtomicStr to other types. ```rust fn try_into(self) -> Result>::Error> ``` -------------------------------- ### Translate with Locale and Arguments Source: https://docs.rs/rust-i18n/latest/index.html Combine locale specification with argument passing in the `t!` macro for complex translations. ```rust t!("messages.hello", locale = "zh-CN", name = "Jason", count = 2); // => "你好,Jason (2)" t!("messages.hello", locale = "zh-CN", "name" => "Jason", "count" => 3 + 2); // => "你好,Jason (5)" ``` -------------------------------- ### Backend::available_locales Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.SimpleBackend.html Retrieves a list of all locales that have translations available in the SimpleBackend. ```APIDOC ## Backend::available_locales ### Description Return the available locales. ### Method `available_locales(&self) -> Vec>` ### Returns - `Vec>`: A vector of strings, where each string is an available locale. ``` -------------------------------- ### From> for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from an Arc-boxed string slice to CowStr. ```rust fn from(s: Arc) -> CowStr<'a> ``` -------------------------------- ### From for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from a u128 integer to CowStr. ```rust fn from(val: u128) -> CowStr<'a> ``` -------------------------------- ### Translate with Arguments Source: https://docs.rs/rust-i18n/latest/index.html Pass arguments to the `t!` macro to fill in placeholders in the translated strings. Arguments can be specified using named parameters or tuple-like syntax. ```rust t!("messages.hello", name = "world"); // => "Hello, world" t!("messages.hello", "name" => "world"); // => "Hello, world" ``` -------------------------------- ### Translate with Complex Placeholders Source: https://docs.rs/rust-i18n/latest/index.html Use the `t!` macro to translate strings with complex placeholders, including formatted numbers. ```rust t!("Hello, %{name}, you serial number is: %{sn}", name = "Jason", sn = 123 : {:08}); // => "Hello, Jason, you serial number is: 000000123" ``` -------------------------------- ### locale Source: https://docs.rs/rust-i18n/latest/rust_i18n/fn.locale.html Retrieves the current locale as a string slice. This function is part of the rust_i18n crate and provides access to the system's current locale setting. ```APIDOC ## locale ### Description Get current locale ### Signature ```rust pub fn locale() -> impl Deref ``` ### Returns An object that dereferences to a string slice representing the current locale. ``` -------------------------------- ### Text retrieval with variables Source: https://docs.rs/rust-i18n/latest/rust_i18n/macro.t.html Use the `t` macro to include variables in translated messages. Variables in the message string are denoted by `%{}`, and passed as key-value pairs. ```rust // With variables t!("messages.hello", name = "world"); // messages.hello: "Hello, %{name}" => "Hello, world" t!("messages.foo", name = "Foo", other ="Bar"); // messages.foo: "Hello, %{name} and %{other}" => "Hello, Foo and Bar" ``` -------------------------------- ### From> for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from an Arc-referenced String to CowStr. ```rust fn from(s: Arc) -> CowStr<'a> ``` -------------------------------- ### From> for CowStr<'a> Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Implements conversion from an Arc-referenced string slice to CowStr. ```rust fn from(s: Arc<&'a str>) -> CowStr<'a> ``` -------------------------------- ### Format AtomicStr for Display Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.AtomicStr.html Implements the Display trait for AtomicStr, allowing it to be formatted for output using standard formatting mechanisms. ```rust fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> ``` -------------------------------- ### CowStr Methods Source: https://docs.rs/rust-i18n/latest/rust_i18n/struct.CowStr.html Provides methods to access the underlying string slice or the owned string. ```APIDOC ## Struct CowStr ### Description A wrapper for `Cow<'a, str>` that is specifically designed for use with the `t!` macro. This wrapper provides additional functionality or optimizations when handling strings in the `t!` macro. ### Methods #### `as_str(&self) -> &str` Returns a string slice view of the `CowStr`. #### `into_inner(self) -> Cow<'a, str>` Consumes the `CowStr` and returns the inner `Cow<'a, str>`. ``` -------------------------------- ### t! Macro with Placeholders Source: https://docs.rs/rust-i18n/latest/rust_i18n/index.html Pass arguments to the `t!` macro to fill in placeholders in the translated strings. Placeholders can be named or positional. ```rust t!("messages.hello", name = "world"); // => "Hello, world" t!("messages.hello", "name" => "world"); // => "Hello, world" ``` ```rust t!("messages.hello", locale = "zh-CN", name = "Jason", count = 2); // => "你好,Jason (2)" t!("messages.hello", locale = "zh-CN", "name" => "Jason", "count" => 3 + 2); // => "你好,Jason (5)" ``` ```rust t!("Hello, %{name}, you serial number is: %{sn}", name = "Jason", sn = 123 : {:08}); // => "Hello, Jason, you serial number is: 000000123" ```