### SQLx Database Persistence Example Source: https://context7.com/hack-ink/language/llms.txt Demonstrates using `Language` with SQLx for database operations. Shows how `Language` is encoded as its tag string for inserts and decoded from the string for selects. Includes an example of updating an array column in PostgreSQL. ```rust use language::Language; use sqlx::PgPool; #[derive(sqlx::FromRow)] struct UserRow { id: i64, username: String, lang: Language, } #[tokio::main] async fn main() -> Result<(), Box> { let pool = PgPool::connect("postgres://user:pass@localhost/mydb").await?; // INSERT: Language encodes as its tag string, e.g. "ja" let lang = Language::Ja; sqlx::query("INSERT INTO users (username, lang) VALUES ($1, $2)") .bind("alice") .bind(lang) .execute(&pool) .await?; // SELECT: Language decodes from the stored tag string let row: UserRow = sqlx::query_as("SELECT id, username, lang FROM users WHERE username = $1") .bind("alice") .fetch_one(&pool) .await?; assert_eq!(row.lang, Language::Ja); // Postgres array column (requires PgHasArrayType) sqlx::query("UPDATE users SET supported_langs = $1 WHERE id = $2") .bind(vec![Language::En, Language::FrCa, Language::ZhHans]) .bind(row.id) .execute(&pool) .await?; Ok(()) } ``` -------------------------------- ### Lingua Language Conversion Example Source: https://context7.com/hack-ink/language/llms.txt Demonstrates bidirectional conversion between `language::Language` and `lingua::Language` using `TryFrom`. Handles specific mappings like Chinese to `zh-Hans` and Tagalog to `fil`, and shows error handling for unsupported languages. ```rust use language::{Language, error::Error}; use lingua::Language as LinguaLanguage; fn main() -> Result<(), Box> { // lingua::Language -> Language assert_eq!(Language::try_from(LinguaLanguage::Japanese)?, Language::Ja); assert_eq!(Language::try_from(LinguaLanguage::Ukrainian)?, Language::Uk); // lingua Chinese maps to zh-Hans (Simplified) assert_eq!(Language::try_from(LinguaLanguage::Chinese)?, Language::ZhHans); // lingua Tagalog maps to BCP47 "fil" assert_eq!(Language::try_from(LinguaLanguage::Tagalog)?, Language::Fil); // Language -> lingua::Language assert_eq!(LinguaLanguage::try_from(Language::Ja)?, LinguaLanguage::Japanese); assert_eq!(LinguaLanguage::try_from(Language::Fil)?, LinguaLanguage::Tagalog); // Region variants strip to base for lookup assert_eq!(LinguaLanguage::try_from(Language::DeAt)?, LinguaLanguage::German); // Languages absent from lingua produce a typed error let err = LinguaLanguage::try_from(Language::Ba).unwrap_err(); // Bashkir assert!(matches!(err, Error::UnsupportedLinguaBase(_))); Ok(()) } ``` -------------------------------- ### Utoipa Schema Generation Example Source: https://context7.com/hack-ink/language/llms.txt Demonstrates generating an OpenAPI schema for the `Language` enum using `utoipa::PartialSchema`. The generated schema is a string enum with 243 possible values, including examples like `en`, `zh-Hans`, `pt-BR`, and `ar-SA`. ```rust use language::Language; use utoipa::PartialSchema; fn main() { let schema = Language::schema(); // Serialize to inspect the generated JSON schema let value = serde_json::to_value(schema).unwrap(); // The schema is a string enum assert_eq!(value["type"], "string"); let enum_values = value["enum"].as_array().unwrap(); assert_eq!(enum_values.len(), 243); // Spot-check a few tags let has = |tag: &str| enum_values.iter().any(|v| v.as_str() == Some(tag)); assert!(has("en")); assert!(has("zh-Hans")); assert!(has("pt-BR")); assert!(has("ar-SA")); // Use Language as a field type inside a utoipa-annotated handler // #[derive(utoipa::ToSchema)] // struct CreateUserRequest { // #[schema(example = "fr-CA")] // preferred_language: Language, // } } ``` -------------------------------- ### Serde Serialization and Deserialization Source: https://github.com/hack-ink/language/blob/main/README.md Example of using the `serde` feature to serialize and deserialize language tags within a struct. Ensure the `serde` feature is enabled. ```rust use language::Language; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize, PartialEq)] struct Payload { lang: Language, } let json = r#"{"lang":"es-MX"}"#; let payload: Payload = serde_json::from_str(json)?; assert_eq!(payload.lang, Language::EsMx); ``` -------------------------------- ### Rust Declaration Order Example Source: https://github.com/hack-ink/language/blob/main/docs/guide/rust_style_guide.md Illustrates the recommended order for module-level items in Rust files. `pub` items precede non-`pub` items, and non-`async` functions precede `async` functions within the same visibility level. ```rust pub fn build_request() -> Request { // ... } pub async fn fetch_response() -> Response { // ... } ``` -------------------------------- ### Rust Numeric Literals with Suffixes and Underscores Source: https://github.com/hack-ink/language/blob/main/docs/guide/rust_style_guide.md Provides examples of allowed numeric literals, showing the use of underscores for type suffixes and digit separation for readability. ```rust 10_f64 ``` ```rust 1_u32 ``` ```rust 0_i64 ``` ```rust 1_000 ``` ```rust 10_000 ``` ```rust 1_000_000 ``` -------------------------------- ### Rust Struct and Impl Block Example (Allowed) Source: https://github.com/hack-ink/language/blob/main/docs/guide/rust_style_guide.md Demonstrates the correct usage of `Self` within `impl` blocks for referring to the implementing type. This applies to method signatures, including references, slices, and generic containers. ```rust struct A; impl A { fn new() -> Self { Self } fn from_owned(value: Self) -> Self { value } fn from_ref(value: &Self) -> &Self { value } fn collect_all(values: &[Self]) -> Vec { values.to_vec() } } ``` -------------------------------- ### Basic Language Tag Usage Source: https://github.com/hack-ink/language/blob/main/README.md Demonstrates basic usage of the `Language` enum for getting tag, parsing, and retrieving names. Ensure the `language` crate is added as a dependency. ```rust use language::Language; let en = Language::En; assert_eq!(en.tag(), "en"); assert_eq!(Language::try_from("en").unwrap(), Language::En); assert_eq!(en.name(), "English"); assert_eq!(en.local_name(), "English"); ``` -------------------------------- ### Get English Name with `Language::name()` Source: https://context7.com/hack-ink/language/llms.txt Retrieves the English name of a language. Useful for displaying human-readable labels in English UIs or logs. ```rust use language::Language; assert_eq!(Language::En.name(), "English"); assert_eq!(Language::PtBr.name(), "Portuguese (Brazil)"); assert_eq!(Language::ZhHans.name(), "Chinese (Simplified)"); assert_eq!(Language::Fil.name(), "Filipino"); assert_eq!(Language::NbNo.name(), "Norwegian, Bokmål (Norway)") ``` -------------------------------- ### Rust Struct and Impl Block Example (Forbidden) Source: https://github.com/hack-ink/language/blob/main/docs/guide/rust_style_guide.md Shows the incorrect way to refer to the implementing type within `impl` blocks. Using the concrete type name instead of `Self` is forbidden. ```rust struct A; impl A { fn new() -> A { A } fn from_owned(value: A) -> A { value } fn from_ref(value: &A) -> &A { value } fn collect_all(values: &[A]) -> Vec { values.to_vec() } } ``` -------------------------------- ### Parse Language Tag and Handle Errors in Rust Source: https://context7.com/hack-ink/language/llms.txt Demonstrates parsing a language tag into a `Language` enum and handling potential errors using `language::error::Result`. Includes examples of matching specific error variants like `UnsupportedLanguageTag` and general error handling. ```rust use language::error::{Error, Result}; use language::Language; fn parse_language(tag: &str) -> Result { Language::try_from(tag) } fn main() { match parse_language("de-DE") { Ok(lang) => println!("Parsed: {} ({})", lang.name(), lang.tag()), Err(Error::UnsupportedLanguageTag(t)) => eprintln!("Unknown tag: {t}"), Err(e) => eprintln!("Other error: {e}"), } // Error implements Display via thiserror let e = parse_language("xx-FAKE").unwrap_err(); assert_eq!(e.to_string(), "Unsupported language tag `xx-FAKE`."); // Feature-gated variants (available when the corresponding feature is enabled) // Error::IcuLocaleParse – ICU4X parse failure // Error::UnsupportedIcuLocale(String) – locale not in Language set // Error::UnsupportedLinguaBase(&'static str) – lingua base subtag missing // Error::UnsupportedLinguaLanguage(lingua::Language) – lingua variant unmapped // Error::UnsupportedWhatlangBase(&'static str) – whatlang base subtag missing // Error::UnsupportedWhatlangLang(whatlang::Lang) – whatlang variant unmapped } ``` -------------------------------- ### Get BCP47 Tag String with `Language::tag()` Source: https://context7.com/hack-ink/language/llms.txt Retrieves the canonical BCP47 tag string for a `Language` variant. This is the authoritative identifier used for serialization and storage. ```rust use language::Language; assert_eq!(Language::En.tag(), "en"); assert_eq!(Language::PtBr.tag(), "pt-BR"); assert_eq!(Language::ZhHans.tag(), "zh-Hans"); assert_eq!(Language::ArSa.tag(), "ar-SA"); assert_eq!(Language::AzCyrlAz.tag(), "az-Cyrl-AZ") ``` -------------------------------- ### Get Native Name with `Language::local_name()` Source: https://context7.com/hack-ink/language/llms.txt Retrieves the language's name written in its own script (autonym). Useful for native-script language pickers and locale-sensitive UIs. ```rust use language::Language; assert_eq!(Language::De.local_name(), "Deutsch"); assert_eq!(Language::Ja.local_name(), "日本語"); assert_eq!(Language::Ar.local_name(), "العربية\u{200f}"); assert_eq!(Language::ZhCn.local_name(), "中文(中华人民共和国)"); assert_eq!(Language::Hi.local_name(), "हिंदी") ``` -------------------------------- ### SQLx Integration for Databases Source: https://github.com/hack-ink/language/blob/main/README.md Illustrates how to use `language::Language` with SQLx for PostgreSQL, MySQL, or SQLite. Requires one of the `sqlx-*` features to be enabled. ```rust use language::Language; use sqlx::types::Json; // Language stores as a text tag; works with Postgres/MySQL/SQLite feature flags. let stored = Language::Ja; let row = sqlx::query!(r#"select $1 as lang"#, stored) .fetch_one(&pool) .await?; assert_eq!(row.lang, Language::Ja); ``` -------------------------------- ### Convert Between Language and Whatlang Lang Source: https://context7.com/hack-ink/language/llms.txt Demonstrates `TryFrom` conversions between `language::Language` and `whatlang::Lang`. Shows how base subtags are matched and region/script variants are stripped. Handles unsupported base subtags. ```rust use language::{Language, error::Error}; use whatlang::{detect, Lang}; fn main() -> Result<(), Box> { // whatlang::Lang -> Language assert_eq!(Language::try_from(Lang::Ukr)?, Language::Uk); assert_eq!(Language::try_from(Lang::Spa)?, Language::Es); // whatlang Cmn (Mandarin) maps to zh-Hans assert_eq!(Language::try_from(Lang::Cmn)?, Language::ZhHans); // whatlang Tgl (Tagalog) maps to fil (Filipino BCP47) assert_eq!(Language::try_from(Lang::Tgl)?, Language::Fil); // Language -> whatlang::Lang assert_eq!(Lang::try_from(Language::Uk)?, Lang::Ukr); // Region variants strip to their base assert_eq!(Lang::try_from(Language::PtBr)?, Lang::Por); // Tagalog: use Language::Fil (not Language::Tl) for whatlang compatibility assert_eq!(Lang::try_from(Language::Fil)?, Lang::Tgl); // Unsupported base produces typed error let err = Lang::try_from(Language::Ba).unwrap_err(); // Bashkir assert!(matches!(err, Error::UnsupportedWhatlangBase(_))); // Real-world: detect language from text and convert to BCP47 let info = detect("Привіт, як справи?").unwrap(); let lang = Language::try_from(info.lang())?; assert_eq!(lang, Language::Uk); Ok(()) } ``` -------------------------------- ### Build Project with Cargo Source: https://github.com/hack-ink/language/blob/main/docs/guide/index.md Use `cargo build` to compile the project. `cargo test` runs the test suite. ```bash cargo build ``` ```bash cargo test ``` -------------------------------- ### whatlang Interoperability Source: https://github.com/hack-ink/language/blob/main/README.md Demonstrates converting from `whatlang::Lang` to `language::Language`. Ensure the `whatlang` feature is enabled. ```rust use language::Language; use whatlang::Lang; let lang = Language::try_from(Lang::Ukr)?; assert_eq!(lang, Language::Uk); ``` -------------------------------- ### Optional Task Wrappers with Cargo Make Source: https://github.com/hack-ink/language/blob/main/docs/guide/index.md Execute optional development tasks like formatting and linting using `cargo make`. ```bash cargo make fmt ``` ```bash cargo make clippy ``` ```bash cargo make nextest ``` -------------------------------- ### Rust Logging with Structured Fields (Allowed) Source: https://github.com/hack-ink/language/blob/main/docs/guide/rust_style_guide.md Demonstrates the correct way to use tracing macros with fully qualified paths and structured fields for dynamic values. Message strings should not encode these values. ```rust tracing::info!(user_id, org_id, "User logged in."); ``` -------------------------------- ### Iterating Over All Languages Source: https://github.com/hack-ink/language/blob/main/README.md Demonstrates how to iterate over all supported languages at compile time without any heap allocation using `Language::all()`. ```rust use language::Language; let tags: Vec<&'static str> = Language::all().iter().map(Language::tag).collect(); assert!(tags.contains(&"fr-CA")); ``` -------------------------------- ### Generate Code with Cargo Features Source: https://github.com/hack-ink/language/blob/main/docs/guide/index.md Run the code generation binary with the `codegen` feature enabled. Specify an output path using `--out`. ```bash cargo run --features codegen --bin language ``` ```bash cargo run --features codegen --bin language --out /path/to/output.rs ``` -------------------------------- ### TryFrom<&str> / TryFrom for Language Source: https://context7.com/hack-ink/language/llms.txt Enables parsing BCP47 tag strings into `Language` variants. Supports both `&str` and `String` inputs, returning an error for unsupported tags. ```APIDOC ## `TryFrom<&str>` / `TryFrom` for `Language` Parses a BCP47 tag string into a `Language` variant. Returns `Err(Error::UnsupportedLanguageTag)` for any tag not present in the generated set. Both `&str` and `String` are supported. ```rust use language::{Language, error::Error}; // Valid tags assert_eq!(Language::try_from("en").unwrap(), Language::En); assert_eq!(Language::try_from("zh-Hant").unwrap(), Language::ZhHant); assert_eq!(Language::try_from("pt-BR").unwrap(), Language::PtBr); // Owned String let tag = String::from("es-MX"); assert_eq!(Language::try_from(tag).unwrap(), Language::EsMx); // Invalid tag produces typed error let err = Language::try_from("zz-INVALID").unwrap_err(); assert!(matches!(err, Error::UnsupportedLanguageTag(_))); println!("{err}"); // "Unsupported language tag `zz-INVALID`." // Round-trip guarantee: every Language can be re-parsed from its own tag for language in Language::all() { assert_eq!(Language::try_from(language.tag()).unwrap(), language); } ``` ``` -------------------------------- ### Use `language::prelude` for Simplified Imports in Rust Source: https://context7.com/hack-ink/language/llms.txt Shows how to use the `language::prelude::*` import to bring `Error`, `Result`, and all generated `Language` items into scope with a single statement. This simplifies working with language tags and enum variants. ```rust use language::prelude::*; // Language, Error, and Result are all in scope let lang = Language::try_from("ko")?; assert_eq!(lang.tag(), "ko"); assert_eq!(lang.name(), "Korean"); assert_eq!(lang.local_name(), "한국어"); // Iterate and find let japanese = Language::all() .iter() .find(|l| l.tag() == "ja") .copied() .unwrap(); assert_eq!(japanese, Language::Ja); # Ok::<(), Error>(()) ``` -------------------------------- ### Language::all() Source: https://context7.com/hack-ink/language/llms.txt Provides a compile-time constant array of all 243 supported `Language` variants, enabling zero-allocation iteration. ```APIDOC ## `Language::all()` Returns a `const` array `[Language; 243]` of every supported language, enabling zero-allocation iteration over the full set at compile time. ```rust use language::Language; // Collect every BCP47 tag let tags: Vec<&'static str> = Language::all().iter().map(Language::tag).collect(); assert!(tags.contains(&"fr-CA")); assert!(tags.contains(&"zh-Hant")); assert_eq!(tags.len(), 243); // Build a dropdown list with English name + tag let options: Vec = Language::all() .iter() .map(|l| format!("{} ({})", l.name(), l.tag())) .collect(); // Verify all tags are unique let mut seen = std::collections::HashSet::new(); for language in Language::all() { assert!(seen.insert(language.tag())); } ``` ``` -------------------------------- ### Run All Features Tests Source: https://github.com/hack-ink/language/blob/main/docs/guide/index.md Execute all tests, including those requiring all features, using `cargo test --all-features`. ```bash cargo test --all-features ``` -------------------------------- ### Language Enum Usage Source: https://context7.com/hack-ink/language/llms.txt Demonstrates direct variant access and comparison for the `Language` enum. This method is zero-cost and does not involve heap allocation. ```APIDOC ## `Language` enum A generated enum covering all 243 BCP47 tags sourced from translation.io. Each variant is `Copy`, `Clone`, `PartialEq`, `Eq`, `PartialOrd`, and `Ord`. The enum is the central type of the crate and is re-exported from the crate root and from `language::prelude`. ```rust use language::Language; // Direct variant access – zero-cost, no heap allocation let en = Language::En; let pt_br = Language::PtBr; let zh_hant = Language::ZhHant; assert_eq!(en, Language::En); assert!(en < pt_br); // Ord derived from declaration order ``` ``` -------------------------------- ### Enable SQLx Feature for Database Persistence Source: https://context7.com/hack-ink/language/llms.txt Enable one or more SQLx features (`sqlx-postgres`, `sqlx-mysql`, `sqlx-sqlite`) to implement SQLx `Type`, `Encode`, and `Decode` for `Language`. Language is mapped to its BCP47 tag string. Postgres also supports array columns. ```toml [dependencies] language = { version = "0.4", features = ["sqlx-postgres"] } sqlx = { version = "0.8", features = ["postgres", "runtime-tokio"] } ``` -------------------------------- ### Serialize and Deserialize Language with Serde Source: https://context7.com/hack-ink/language/llms.txt Demonstrates serializing a `UserProfile` struct containing a `Language` enum to JSON and deserializing it back. Also shows direct serialization/deserialization of bare `Language` values. ```rust use language::Language; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize, PartialEq)] struct UserProfile { name: String, preferred_language: Language, } fn main() -> Result<(), Box> { // Serialize let profile = UserProfile { name: "Alice".into(), preferred_language: Language::FrCa, }; let json = serde_json::to_string(&profile)?; assert_eq!(json, r#"{"name":"Alice","preferred_language":"fr-CA"}"#); // Deserialize let json = r#"{"name":"Bob","preferred_language":"es-MX"}"#; let parsed: UserProfile = serde_json::from_str(json)?; assert_eq!(parsed.preferred_language, Language::EsMx); // Bare Language value let lang = Language::En; assert_eq!(serde_json::to_string(&lang)?, "\"en\""); let back: Language = serde_json::from_str("\"en\"")?; assert_eq!(back, Language::En); Ok(()) } ``` -------------------------------- ### Lingua Interoperability Source: https://github.com/hack-ink/language/blob/main/README.md Shows conversion from `lingua::Language` to `language::Language`. Requires the `lingua` feature to be enabled. ```rust use language::Language; use lingua::Language as LinguaLanguage; let lang = Language::try_from(LinguaLanguage::Japanese)?; assert_eq!(lang, Language::Ja); ``` -------------------------------- ### Convert Between Language and ICU4X Locale/LanguageIdentifier Source: https://context7.com/hack-ink/language/llms.txt Demonstrates `TryFrom` conversions between the `language::Language` enum and ICU4X's `Locale` and `LanguageIdentifier` types. Shows handling of unsupported ICU locales. ```rust use std::str::FromStr; use icu_locale_core::{LanguageIdentifier, Locale}; use language::{Language, error::Error}; fn main() -> Result<(), Box> { // Language -> Locale let locale = Locale::try_from(Language::PtBr)?; assert_eq!(locale.to_string(), "pt-BR"); // Locale -> Language let locale: Locale = "pt-BR".parse()?; let lang = Language::try_from(locale)?; assert_eq!(lang, Language::PtBr); // Language -> LanguageIdentifier let langid = LanguageIdentifier::try_from(Language::ZhHans)?; assert_eq!(langid.to_string(), "zh-Hans"); // LanguageIdentifier -> Language let langid = LanguageIdentifier::from_str("de-AT")?; let lang = Language::try_from(langid)?; assert_eq!(lang, Language::DeAt); // Locale not in the generated set produces a typed error let locale = Locale::from_str("es-419")?; let err = Language::try_from(locale).unwrap_err(); assert!(matches!(err, Error::UnsupportedIcuLocale(_))); Ok(()) } ``` -------------------------------- ### Enable Lingua Feature for Language Interoperability Source: https://context7.com/hack-ink/language/llms.txt Enable the `lingua` feature to provide `TryFrom` conversions between `language::Language` and `lingua::Language`. ISO 639-1 codes are prioritized, with ISO 639-3 as a fallback. ```toml [dependencies] language = { version = "0.4", features = ["lingua"] } lingua = "1.7" ``` -------------------------------- ### Safe Parsing of User Input Source: https://github.com/hack-ink/language/blob/main/README.md Shows how to safely parse user-provided language tags using `try_from`. Invalid tags will result in a typed error, preventing panics. ```rust use language::Language; let parsed: Result = Language::try_from("zh-Hant"); assert!(parsed.is_ok()); let bad = Language::try_from("zz-INVALID"); assert!(bad.is_err()); ``` -------------------------------- ### Parse BCP47 Tag String with `TryFrom<&str>` / `TryFrom` Source: https://context7.com/hack-ink/language/llms.txt Parses a BCP47 tag string into a `Language` variant. Returns an error for unsupported tags. Demonstrates parsing from both `&str` and `String`, and includes a round-trip guarantee check. ```rust use language::{Language, error::Error}; // Valid tags assert_eq!(Language::try_from("en").unwrap(), Language::En); assert_eq!(Language::try_from("zh-Hant").unwrap(), Language::ZhHant); assert_eq!(Language::try_from("pt-BR").unwrap(), Language::PtBr); // Owned String let tag = String::from("es-MX"); assert_eq!(Language::try_from(tag).unwrap(), Language::EsMx); // Invalid tag produces typed error let err = Language::try_from("zz-INVALID").unwrap_err(); assert!(matches!(err, Error::UnsupportedLanguageTag(_))); println!("{err}"); // "Unsupported language tag `zz-INVALID`." // Round-trip guarantee: every Language can be re-parsed from its own tag for language in Language::all() { assert_eq!(Language::try_from(language.tag()).unwrap(), language); } ``` -------------------------------- ### SQLx Integration Source: https://github.com/hack-ink/language/blob/main/docs/spec/index.md Defines how the Language enum interacts with SQLx for database encoding and decoding. ```APIDOC ## SQLx Integration - Encode and decode as text tags. - Implementations exist only for enabled backends. ``` -------------------------------- ### Enable Whatlang Feature for Language Detection Interop Source: https://context7.com/hack-ink/language/llms.txt Enable the `whatlang` feature in Cargo.toml for `TryFrom` conversions between `language::Language` and `whatlang::Lang`. Note that region/script variants are stripped. ```toml [dependencies] language = { version = "0.4", features = ["whatlang"] } whatlang = "0.18" ``` -------------------------------- ### Whatlang Integration Source: https://github.com/hack-ink/language/blob/main/docs/spec/index.md Defines how the Language enum interacts with the whatlang library. ```APIDOC ## Whatlang Integration - Use only the base language subtag. - `Language::Fil` maps to `whatlang::Lang::Tgl`. - Unsupported values return the relevant `Error` variant. ``` -------------------------------- ### Rust Language Enum Variants Source: https://context7.com/hack-ink/language/llms.txt Demonstrates direct access to `Language` enum variants. These variants are `Copy`, `Clone`, `PartialEq`, `Eq`, `PartialOrd`, and `Ord`, offering zero-cost operations. ```rust use language::Language; // Direct variant access – zero-cost, no heap allocation let en = Language::En; let pt_br = Language::PtBr; let zh_hant = Language::ZhHant; assert_eq!(en, Language::En); assert!(en < pt_br); // Ord derived from declaration order ``` -------------------------------- ### Serde Integration Source: https://github.com/hack-ink/language/blob/main/docs/spec/index.md Defines how the Language enum interacts with Serde for serialization and deserialization. ```APIDOC ## Serde Integration - Serialize to the canonical tag string. - Deserialize from a string tag only. - Unknown tags fail deserialization. ``` -------------------------------- ### Language::name() Source: https://context7.com/hack-ink/language/llms.txt Provides the English name of the language. This is useful for displaying human-readable labels in English interfaces or logs. ```APIDOC ## `Language::name()` Returns the language's English name as a `&str`. Useful for human-readable UI labels in English-language interfaces or logging. ```rust use language::Language; assert_eq!(Language::En.name(), "English"); assert_eq!(Language::PtBr.name(), "Portuguese (Brazil)"); assert_eq!(Language::ZhHans.name(), "Chinese (Simplified)"); assert_eq!(Language::Fil.name(), "Filipino"); assert_eq!(Language::NbNo.name(), "Norwegian, Bokmål (Norway)"); ``` ``` -------------------------------- ### Error Handling and Parsing Source: https://github.com/hack-ink/language/blob/main/docs/spec/index.md Defines the Error type for parsing and interop, and the Result alias. Parsing expects canonical tag format without normalization, returning Error::UnsupportedLanguageTag for unknown tags. ```APIDOC ## Error Handling and Parsing - `Error`: Error type for parsing and interop. - `Result`: Alias for `std::result::Result`. ### Parsing Rules - `TryFrom` expects canonical tag format. - No case or separator normalization. - Unknown tags return `Error::UnsupportedLanguageTag`. ``` -------------------------------- ### ICU4X Locale Conversion Source: https://github.com/hack-ink/language/blob/main/README.md Shows how to convert between ICU4X `Locale` and the `language::Language` type. Requires the `icu_locale_core` feature to be enabled. ```rust use icu_locale_core::Locale; use language::Language; let locale: Locale = "pt-BR".parse()?; let language = Language::try_from(&locale)?; assert_eq!(language.tag(), "pt-BR"); ``` -------------------------------- ### Enable Utoipa Feature for OpenAPI Schema Generation Source: https://context7.com/hack-ink/language/llms.txt Enable the `utoipa` feature to implement `PartialSchema` and `ToSchema` for `Language`. This generates a JSON Schema with a `string` type and an exhaustive `enum` array of all 243 BCP47 tag strings. ```toml [dependencies] language = { version = "0.4", features = ["utoipa"] } utoipa = "5" ``` -------------------------------- ### Rust Error Wrapping with Context Source: https://github.com/hack-ink/language/blob/main/docs/guide/rust_style_guide.md Use `#[error(transparent)]` for thin error wrappers that add no new context. Prefer short, action-oriented messages that include the source error. ```rust #[derive(Debug, thiserror::Error)] pub enum Error { #[error(transparent)] Utf8(#[from] std::str::Utf8Error), #[error("Failed to serialize JetStream payload: {0}.")] Json(#[from] serde_json::Error), } ``` -------------------------------- ### Rust Generics and Trait Bounds (Allowed) Source: https://github.com/hack-ink/language/blob/main/docs/guide/rust_style_guide.md Illustrates the preferred way to define trait bounds using a `where` clause. Inline trait bounds are forbidden. ```rust fn render(value: T) -> String where T: Display, { ``` -------------------------------- ### Enable Serde Feature for Language Serialization Source: https://context7.com/hack-ink/language/llms.txt Enable the `serde` feature in Cargo.toml to serialize and deserialize `Language` enum variants. `Language` is serialized as its BCP47 tag string and deserialized by parsing that string. ```toml # Cargo.toml [dependencies] language = { version = "0.4", features = ["serde"] } serde = { version = "1", features = ["derive"] } serde_json = "1" ``` -------------------------------- ### Rust Logging without Structured Fields (Forbidden) Source: https://github.com/hack-ink/language/blob/main/docs/guide/rust_style_guide.md Shows the forbidden method of logging where dynamic values are only included in the message string, rather than using structured fields. ```rust tracing::info!("User {user_id} logged in (org {org_id})."); ``` -------------------------------- ### Language::tag() Source: https://context7.com/hack-ink/language/llms.txt Retrieves the canonical BCP47 tag string for a `Language` variant. This is the authoritative identifier used for serialization and storage. ```APIDOC ## `Language::tag()` Returns the canonical BCP47 tag string (e.g. `"en"`, `"pt-BR"`, `"zh-Hant"`) as a `&'static str`. The tag is the authoritative identity of the language and is used as the wire format for serialization and database storage. ```rust use language::Language; assert_eq!(Language::En.tag(), "en"); assert_eq!(Language::PtBr.tag(), "pt-BR"); assert_eq!(Language::ZhHans.tag(), "zh-Hans"); assert_eq!(Language::ArSa.tag(), "ar-SA"); assert_eq!(Language::AzCyrlAz.tag(), "az-Cyrl-AZ"); ``` ``` -------------------------------- ### Rust Generics and Trait Bounds (Forbidden) Source: https://github.com/hack-ink/language/blob/main/docs/guide/rust_style_guide.md Shows the forbidden inline syntax for defining trait bounds. All bounds should be placed in a `where` clause. ```rust fn render(value: T) -> String { ``` -------------------------------- ### Enable ICU4X Locale Interop Feature Source: https://context7.com/hack-ink/language/llms.txt Enable the `icu_locale_core` feature in Cargo.toml for interoperation with ICU4X `Locale` and `LanguageIdentifier` types. Requires `icu_locale_core` dependency. ```toml [dependencies] language = { version = "0.4", features = ["icu_locale_core"] } icu_locale_core = "2.1" ``` -------------------------------- ### Language Enum and Methods Source: https://github.com/hack-ink/language/blob/main/docs/spec/index.md The Language enum represents supported BCP47 tags. It provides methods to retrieve canonical tag, English name, local name, and all supported tags. ```APIDOC ## Language Enum Generated enum for supported BCP47 tags. ### Methods - `tag() -> &'static str`: Canonical tag. - `name() -> &str`: English name. - `local_name() -> &'static str`: Autonym. - `all() -> [Language; N]`: All supported tags. ``` -------------------------------- ### Language::local_name() Source: https://context7.com/hack-ink/language/llms.txt Returns the language's name written in its native script (autonym). This is valuable for native-script language pickers and locale-sensitive user interfaces. ```APIDOC ## `Language::local_name()` Returns the language's name written in the language itself (autonym) as a `&'static str`. Useful for native-script language pickers and locale-sensitive UI. ```rust use language::Language; assert_eq!(Language::De.local_name(), "Deutsch"); assert_eq!(Language::Ja.local_name(), "日本語"); assert_eq!(Language::Ar.local_name(), "العربية\u{200f}"); assert_eq!(Language::ZhCn.local_name(), "中文(中华人民共和国)"); assert_eq!(Language::Hi.local_name(), "हिंदी"); ``` ``` -------------------------------- ### Icu Locale Core Integration Source: https://github.com/hack-ink/language/blob/main/docs/spec/index.md Defines how the Language enum interacts with icu_locale_core for locale conversions. ```APIDOC ## Icu Locale Core Integration - Convert via tag strings. - Unsupported mappings return `Error::UnsupportedIcuLocale`. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.