1use std::fmt::{Display, Write as _};
10
11use yog_abi::YogStr;
12
13pub fn translation(key: &str) -> Option<String> {
16 let api = crate::registry::global_api();
17 if api.is_null() {
18 return None;
19 }
20 let owned = unsafe { ((*api).translate)((*api).ctx, YogStr::from_str(key)) };
21 crate::registry::take_owned(unsafe { (*api).free_str }, owned)
22}
23
24pub fn tr(key: &str) -> String {
29 match translation(key) {
30 Some(text) => format_translation(&text, &[]),
31 None => key.to_string(),
32 }
33}
34
35pub fn tr_args(key: &str, args: &[&dyn Display]) -> String {
38 format_translation(&translation(key).unwrap_or_else(|| key.to_string()), args)
39}
40
41pub fn format_translation(pattern: &str, args: &[&dyn Display]) -> String {
46 let mut out = String::with_capacity(pattern.len());
47 let mut next = 0;
48 let mut rest = pattern;
49 while let Some(pos) = rest.find('%') {
50 out.push_str(&rest[..pos]);
51 let spec = &rest[pos + 1..];
52 if let Some(after) = spec.strip_prefix('%') {
53 out.push('%');
54 rest = after;
55 continue;
56 }
57 if let Some(after) = spec.strip_prefix(['s', 'd']) {
58 match args.get(next) {
59 Some(arg) => {
60 let _ = write!(out, "{arg}");
61 }
62 None => out.push_str(&rest[pos..pos + 2]),
63 }
64 next += 1;
65 rest = after;
66 continue;
67 }
68 let digits = spec.bytes().take_while(u8::is_ascii_digit).count();
69 let numbered = (digits > 0)
70 .then(|| spec[digits..].strip_prefix('$'))
71 .flatten()
72 .and_then(|s| s.strip_prefix(['s', 'd']));
73 match (numbered, spec[..digits].parse::<usize>()) {
74 (Some(after), Ok(n)) if n >= 1 => {
75 match args.get(n - 1) {
76 Some(arg) => {
77 let _ = write!(out, "{arg}");
78 }
79 None => out.push_str(&rest[pos..rest.len() - after.len()]),
80 }
81 rest = after;
82 }
83 _ => {
84 out.push('%');
85 rest = spec;
86 }
87 }
88 }
89 out.push_str(rest);
90 out
91}
92
93#[macro_export]
97macro_rules! tr {
98 ($key:expr_2021 $(,)?) => {
99 $crate::tr($key)
100 };
101 ($key:expr_2021, $($arg:expr_2021),+ $(,)?) => {
102 $crate::tr_args($key, &[$(&$arg as &dyn ::std::fmt::Display),+])
103 };
104}
105
106#[cfg(test)]
107mod tests {
108 use super::*;
109
110 #[test]
111 fn formats_like_minecraft() {
112 assert_eq!(
113 format_translation("%s of %s mods", &[&3, &"58"]),
114 "3 of 58 mods"
115 );
116 assert_eq!(format_translation("%2$s, %1$s", &[&"a", &"b"]), "b, a");
117 assert_eq!(format_translation("100%% by %s", &[&"X"]), "100% by X");
118 assert_eq!(format_translation("%d items", &[&5]), "5 items");
119 assert_eq!(
120 format_translation("missing %s and %3$s", &[]),
121 "missing %s and %3$s"
122 );
123 assert_eq!(format_translation("50% off %x", &[&1]), "50% off %x");
124 assert_eq!(format_translation("trailing %", &[]), "trailing %");
125 assert_eq!(format_translation("Привет, %s!", &[&"мир"]), "Привет, мир!");
126 }
127
128 #[test]
129 fn unknown_key_without_runtime_is_the_key() {
130 assert_eq!(tr("mymod.nothing"), "mymod.nothing");
131 assert_eq!(crate::tr!("count %s", 4), "count 4");
132 }
133}