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 tag_name(kind: &str, id: &str) -> String {
40 let registry = yog_ids::registry_of(kind).replace(yog_ids::sep::PATH, ".");
41 let key = format!("tag.{registry}.{}", id.replace([':', '/'], "."));
42 translation(&key).map_or_else(|| id.to_string(), |text| format_translation(&text, &[]))
43}
44
45pub fn tr_args(key: &str, args: &[&dyn Display]) -> String {
48 format_translation(&translation(key).unwrap_or_else(|| key.to_string()), args)
49}
50
51pub fn format_translation(pattern: &str, args: &[&dyn Display]) -> String {
56 let mut out = String::with_capacity(pattern.len());
57 let mut next = 0;
58 let mut rest = pattern;
59 while let Some(pos) = rest.find('%') {
60 out.push_str(&rest[..pos]);
61 let spec = &rest[pos + 1..];
62 if let Some(after) = spec.strip_prefix('%') {
63 out.push('%');
64 rest = after;
65 continue;
66 }
67 if let Some(after) = spec.strip_prefix(['s', 'd']) {
68 match args.get(next) {
69 Some(arg) => {
70 let _ = write!(out, "{arg}");
71 }
72 None => out.push_str(&rest[pos..pos + 2]),
73 }
74 next += 1;
75 rest = after;
76 continue;
77 }
78 let digits = spec.bytes().take_while(u8::is_ascii_digit).count();
79 let numbered = (digits > 0)
80 .then(|| spec[digits..].strip_prefix('$'))
81 .flatten()
82 .and_then(|s| s.strip_prefix(['s', 'd']));
83 match (numbered, spec[..digits].parse::<usize>()) {
84 (Some(after), Ok(n)) if n >= 1 => {
85 match args.get(n - 1) {
86 Some(arg) => {
87 let _ = write!(out, "{arg}");
88 }
89 None => out.push_str(&rest[pos..rest.len() - after.len()]),
90 }
91 rest = after;
92 }
93 _ => {
94 out.push('%');
95 rest = spec;
96 }
97 }
98 }
99 out.push_str(rest);
100 out
101}
102
103#[macro_export]
107macro_rules! tr {
108 ($key:expr_2021 $(,)?) => {
109 $crate::tr($key)
110 };
111 ($key:expr_2021, $($arg:expr_2021),+ $(,)?) => {
112 $crate::tr_args($key, &[$(&$arg as &dyn ::std::fmt::Display),+])
113 };
114}
115
116#[cfg(test)]
117mod tests {
118 use super::*;
119
120 #[test]
121 fn formats_like_minecraft() {
122 assert_eq!(
123 format_translation("%s of %s mods", &[&3, &"58"]),
124 "3 of 58 mods"
125 );
126 assert_eq!(format_translation("%2$s, %1$s", &[&"a", &"b"]), "b, a");
127 assert_eq!(format_translation("100%% by %s", &[&"X"]), "100% by X");
128 assert_eq!(format_translation("%d items", &[&5]), "5 items");
129 assert_eq!(
130 format_translation("missing %s and %3$s", &[]),
131 "missing %s and %3$s"
132 );
133 assert_eq!(format_translation("50% off %x", &[&1]), "50% off %x");
134 assert_eq!(format_translation("trailing %", &[]), "trailing %");
135 assert_eq!(format_translation("Привет, %s!", &[&"мир"]), "Привет, мир!");
136 }
137
138 #[test]
139 fn unknown_key_without_runtime_is_the_key() {
140 assert_eq!(tr("mymod.nothing"), "mymod.nothing");
141 assert_eq!(crate::tr!("count %s", 4), "count 4");
142 }
143}