Debian Codegraph @

src/gettext/mod.rs

raw symbols SCIP
1 #[cfg(feature = "gettext")]
2 use std::{
3 ffi::{CStr, CString},
4 sync::OnceLock,
5 };
6
7 #[cfg(feature = "gettext")]
8 pub(crate) mod check;
9
10 #[cfg(feature = "gettext")]
11 // If the locale isn't detected to be UTF-8, or couldn't be switched, the user
12 // will get the default messages.
13 static TEXT_DOMAIN: OnceLock<&'static CStr> = OnceLock::new();
14
15 #[cfg(feature = "gettext")]
16 pub(crate) fn textdomain(domain: &'static CStr) {
17 use libc::{CODESET, LC_ALL, nl_langinfo, setlocale};
18 let utf8 = c"UTF-8";
19
20 // SAFETY: in all cases the functions are passed valid null-terminated C strings;
21 // in the case of nl_langinfo, it is guaranteed by the spec to always return a valid
22 // null-terminated C string as well, making the CStr::from_ptr call safe.
23 unsafe {
24 if setlocale(LC_ALL, CString::default().as_ptr()).is_null() {
25 return;
26 };
27 if CStr::from_ptr(nl_langinfo(CODESET)) != utf8 {
28 return;
29 }
30 if gettext_sys::bind_textdomain_codeset(domain.as_ptr(), utf8.as_ptr()).is_null() {
31 return;
32 }
33 }
34
35 TEXT_DOMAIN.set(domain).expect("only set the locale once")
36 }
37
38 #[cfg(feature = "gettext")]
39 pub(crate) mod display {
40 // Based on <https://lukaskalbertodt.github.io/2019/12/05/generalized-autoref-based-specialization.html>
41 pub struct Wrap<T: ?Sized>(pub T);
42
43 pub trait Convert {
44 fn display(&self) -> String;
45 }
46
47 pub trait Reference {
48 fn display(&self) -> &str;
49 }
50
51 impl<T: std::fmt::Display + ?Sized> Convert for Wrap<T> {
52 fn display(&self) -> String {
53 self.0.to_string()
54 }
55 }
56
57 impl<T: std::fmt::Display + AsRef<str> + ?Sized> Reference for &Wrap<T> {
58 fn display(&self) -> &str {
59 self.0.as_ref()
60 }
61 }
62 }
63
64 #[cfg(feature = "gettext")]
65 pub(crate) fn gettext(text: &'static CStr) -> &'static str {
66 // SAFETY:
67 // - dggettext expects its first argument to be NULL or a pointer to a
68 // valid C string; its second argument should always be a valid C string
69 // - dgettext() is guaranteed to return a pointer to a statically
70 // allocated null-terminated string; this string is also constant (i.e.
71 // it will be unmodified by future calls to gettext.)
72 unsafe {
73 CStr::from_ptr(gettext_sys::dgettext(
74 TEXT_DOMAIN
75 .get()
76 .map_or(std::ptr::null(), |domain| domain.as_ptr()),
77 text.as_ptr(),
78 ))
79 }
80 .to_str()
81 .expect("translation files are corrupted")
82 }
83
84 #[cfg(feature = "gettext")]
85 macro_rules! cstr {
86 ($lit:literal) => {{
87 // this `const` item produces compile time errors = it performs the checks at compile time
88 const CS: &'static std::ffi::CStr =
89 match std::ffi::CStr::from_bytes_until_nul(concat!($lit, "\0").as_bytes()) {
90 Ok(x) => x,
91 Err(_) => panic!("string literal did not pass CStr checks"),
92 };
93 CS
94 }};
95 }
96
97 #[cfg(feature = "gettext")]
98 macro_rules! xlat {
99 ($text: literal) => {{
100 const _: () = $crate::gettext::check::check_keys($text, &[]);
101 $crate::gettext::gettext(cstr!($text))
102 }};
103
104 ($text: literal $(, $id: ident = $val: expr)* $(,)?) => {{
105 #[allow(unused)]
106 use $crate::gettext::display::{Convert, Reference, Wrap};
107 use std::ops::Deref;
108
109 const _: () = $crate::gettext::check::check_keys(
110 $text,
111 &[$(stringify!($id)),*]
112 );
113
114 let result = $crate::gettext::gettext(cstr!($text));
115 $(
116 let result = result.replace(
117 concat!("{", stringify!($id), "}"),
118 (&&Wrap(&$val)).display().deref(),
119 );
120 )*
121
122 result
123 }};
124 }
125
126 #[cfg(not(feature = "gettext"))]
127 macro_rules! xlat {
128 ($text: literal) => { $text };
129
130 ($text: literal $(, $id: ident = $val: expr)* $(,)?) => {{
131 format!($text $(,$id = $val)*)
132 }};
133 }
134
135 #[cfg(feature = "gettext")]
136 macro_rules! xlat_write {
137 ($f: expr, $fmt: literal $(, $id: ident = $val: expr)* $(,)?) => {
138 write!($f, "{}", xlat!($fmt $(, $id = $val)*))
139 };
140 }
141
142 #[cfg(feature = "gettext")]
143 macro_rules! xlat_println {
144 ($fmt: literal $(, $id: ident = $val: expr)* $(,)?) => {
145 println_ignore_io_error!("{}", xlat!($fmt $(, $id = $val)*))
146 };
147 }
148
149 #[cfg(not(feature = "gettext"))]
150 macro_rules! xlat_write {
151 ($f: expr, $fmt: literal $(, $id: ident = $val: expr)* $(,)?) => {
152 write!($f, $fmt $(, $id = $val)*)
153 };
154 }
155
156 #[cfg(not(feature = "gettext"))]
157 macro_rules! xlat_println {
158 ($fmt: literal $(, $id: ident = $val: expr)* $(,)?) => {
159 println_ignore_io_error!($fmt $(, $id = $val)*)
160 };
161 }
162
163 //These are all defined in POSIX.
164 #[cfg(feature = "gettext")]
165 mod gettext_sys {
166 #[cfg_attr(target_os = "freebsd", link(name = "intl"))]
167 unsafe extern "C" {
168 pub fn dgettext(
169 domain: *const libc::c_char,
170 msgid: *const libc::c_char,
171 ) -> *mut libc::c_char;
172
173 pub fn bind_textdomain_codeset(
174 domain: *const libc::c_char,
175 codeset: *const libc::c_char,
176 ) -> *mut libc::c_char;
177 }
178 }
179
180 #[cfg(test)]
181 mod test {
182 #[test]
183 #[cfg(feature = "gettext")]
184 fn it_works() {
185 use super::*;
186 textdomain(c"libc");
187 let input = c"Hello World";
188 // inputs that are not translated are not translated
189 assert_eq!(gettext(input), input.to_str().unwrap());
190 // .. in fact they are the same object
191 assert_eq!(gettext(input).as_ptr(), input.to_str().unwrap().as_ptr());
192
193 if std::env::var("LANG").unwrap_or_default().starts_with("nl") {
194 assert_eq!(xlat!("Operation not permitted"), "Actie is niet toegestaan");
195 }
196 }
197
198 #[test]
199 fn var_subst() {
200 assert_eq!(
201 xlat!("{hello} {world}", world = "world", hello = "hello"),
202 "hello world"
203 );
204
205 assert_eq!(xlat!("five = {five}", five = 5), "five = 5");
206 }
207
208 #[test]
209 #[cfg(feature = "gettext")]
210 fn str_optimized() {
211 use super::display::{Reference, Wrap};
212
213 // in principle the assert_eq's below could be replaced by "expect(unused)" on this trait
214 #[allow(unused_imports)]
215 use super::display::Convert;
216
217 let foo: &str = "foo";
218 let addr = foo.as_ptr();
219 assert_eq!((&&Wrap(&foo)).display().as_ptr(), addr);
220 assert_eq!((&&Wrap(foo)).display().as_ptr(), addr);
221
222 let foo: String = "foo".to_string();
223 let addr = foo.as_ptr();
224 assert_eq!((&&Wrap(&foo)).display().as_ptr(), addr);
225 assert_eq!((&&Wrap(foo)).display().as_ptr(), addr);
226
227 let foo: Box<str> = "foo".to_string().into_boxed_str();
228 let addr = foo.as_ptr();
229 assert_eq!((&&Wrap(&foo)).display().as_ptr(), addr);
230 assert_eq!((&&Wrap(foo)).display().as_ptr(), addr);
231
232 use crate::common::SudoString;
233 let foo: SudoString = SudoString::new("foo".to_string()).unwrap();
234 let addr = foo.as_str().as_ptr();
235 assert_eq!((&&Wrap(&foo)).display().as_ptr(), addr);
236 assert_eq!((&&Wrap(foo)).display().as_ptr(), addr);
237 }
238 }