Skip to content

Commit 6389570

Browse files
huacnleeyk0n9KKRainbow
authored
Fix lazy init always "en" (#90)
Co-authored-by: yk0n9 <ykonghao@icloud.com> Co-authored-by: KKRainbow <sijie.sun@smartx.com>
1 parent 5d4b561 commit 6389570

File tree

3 files changed

+18
-5
lines changed

3 files changed

+18
-5
lines changed

crates/macro/src/lib.rs

+9-1
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,8 @@ fn generate_code(
324324
quote! {
325325
use rust_i18n::{BackendExt, CowStr, MinifyKey};
326326
use std::borrow::Cow;
327+
use std::sync::Mutex;
328+
use rust_i18n::once_cell::sync::Lazy;
327329

328330
/// I18n backend instance
329331
///
@@ -334,11 +336,17 @@ fn generate_code(
334336
#(#all_translations)*
335337
#extend_code
336338

337-
#default_locale
339+
if *_RUST_I18N_INITIALIZED_DEFAULT_LOCALE.lock().unwrap() == false {
340+
*_RUST_I18N_INITIALIZED_DEFAULT_LOCALE.lock().unwrap() = true;
341+
#default_locale
342+
}
338343

339344
Box::new(backend)
340345
});
341346

347+
/// To mark the default locale has been initialized
348+
static _RUST_I18N_INITIALIZED_DEFAULT_LOCALE: Lazy<Mutex<bool>> = Lazy::new(|| Mutex::new(false));
349+
342350
static _RUST_I18N_FALLBACK_LOCALE: Option<&[&'static str]> = #fallback;
343351
static _RUST_I18N_MINIFY_KEY: bool = #minify_key;
344352
static _RUST_I18N_MINIFY_KEY_LEN: usize = #minify_key_len;

crates/support/src/backend.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -74,10 +74,7 @@ impl SimpleBackend {
7474
.map(|(k, v)| ((*k).into(), (*v).into()))
7575
.collect::<HashMap<_, _>>();
7676

77-
let trs = self
78-
.translations
79-
.entry(locale.into())
80-
.or_insert(HashMap::new());
77+
let trs = self.translations.entry(locale.into()).or_default();
8178
trs.extend(data);
8279
}
8380
}

tests/integration_tests.rs

+8
Original file line numberDiff line numberDiff line change
@@ -315,4 +315,12 @@ mod tests {
315315
"This is missing key fallbacked to en."
316316
);
317317
}
318+
319+
#[test]
320+
fn test_set_locale() {
321+
rust_i18n::set_locale("zh-CN");
322+
for _ in 0..5 {
323+
assert_eq!(t!("hello"), "Bar - 你好世界!");
324+
}
325+
}
318326
}

0 commit comments

Comments
 (0)