Compile-time internationalization with runtime language switch and plural/genders support
Created
December 14, 2022 12:05
-
-
Save ivanstepanovftw/62617e381dda3fb811c4e8f91d716025 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub enum Plural { | |
One, | |
Two, | |
Few, | |
Many, | |
Other, | |
} | |
pub enum Gender { | |
Male, | |
Female, | |
Other, | |
} | |
pub mod en { | |
use super::*; | |
pub struct Plural(pub i32); | |
/// https://www.gnu.org/software/gettext/manual/html_node/Plural-forms.html | |
impl Into<super::Plural> for Plural { | |
fn into(self) -> super::Plural { | |
match self.0 { | |
1 => super::Plural::One, | |
_ => super::Plural::Other, | |
} | |
} | |
} | |
} | |
pub mod ru { | |
pub struct Plural(pub i32); | |
/// https://www.gnu.org/software/gettext/manual/html_node/Plural-forms.html | |
/// Plural-Forms: nplurals=3; \ | |
/// plural=n%10==1 && n%100!=11 ? 0 : \ | |
/// n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2; | |
impl Into<super::Plural> for Plural { | |
fn into(self) -> super::Plural { | |
match self.0 { | |
1 => super::Plural::One, | |
_ => super::Plural::Other, | |
} | |
} | |
} | |
} | |
/// Project Fluent, FTL syntax: | |
/// ```FTL | |
/// # Simple things are simple. | |
/// hello-user = Hello, {$userName}! | |
/// | |
/// # Complex things are possible. | |
/// shared-photos = | |
/// {$userName} {$photoCount -> | |
/// [one] added a new photo | |
/// *[other] added {$photoCount} new photos | |
/// } to {$userGender -> | |
/// [male] his stream | |
/// [female] her stream | |
/// *[other] their stream | |
/// }. | |
/// ``` | |
/// | |
/// Project Rust, Rust syntax: | |
pub fn main() { | |
let userName = "John"; | |
let photoCount = 1; | |
let userGender = Gender::Male; | |
let lang = "en"; | |
let shared_photos = match lang { | |
"en" => format!( | |
"{userName} {} to {}", | |
match en::Plural(photoCount).into() { | |
Plural::One => format!("added a new photo"), | |
_ => format!("added {} new photos", photoCount), | |
}, | |
match userGender { | |
Gender::Male => "his stream", | |
Gender::Female => "her stream", | |
_ => "their stream", | |
}), | |
"ru" => format!( | |
"{userName} {} в {}", | |
match ru::Plural(photoCount).into() { | |
Plural::One => format!("добавил новое фото"), | |
_ => format!("добавил {} новых фото", photoCount), | |
}, | |
match userGender { | |
Gender::Male => "евонный поток", | |
Gender::Female => "еёшный поток", | |
_ => "ихний поток", | |
}), | |
_ => todo!(), | |
}; | |
println!("{}", shared_photos); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment