Skip to content

Commit 20660cc

Browse files
committed
dedup high-cost localization setup
Co-authored-by: oech3 <79379754+oech3@users.noreply.github.com>
1 parent e6a3bb5 commit 20660cc

1 file changed

Lines changed: 12 additions & 2 deletions

File tree

src/uucore/src/lib/mods/locale.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use crate::error::UError;
99
use fluent::{FluentArgs, FluentBundle, FluentResource};
1010
use fluent_syntax::parser::ParserError;
1111

12+
use std::cell::Cell;
1213
use std::fs;
1314
use std::path::{Path, PathBuf};
1415
use std::str::FromStr;
@@ -407,14 +408,22 @@ fn detect_system_locale() -> Result<LanguageIdentifier, LocalizationError> {
407408
/// }
408409
/// ```
409410
pub fn setup_localization(p: &str) -> Result<(), LocalizationError> {
411+
// Avoid duplicated and high-cost localizer setup
412+
thread_local! {
413+
static LOCALIZER_IS_SET: Cell<bool> = const { Cell::new(false) };
414+
}
415+
if LOCALIZER_IS_SET.with(Cell::get) {
416+
return Ok(());
417+
}
418+
410419
let locale = detect_system_locale().unwrap_or_else(|_| {
411420
LanguageIdentifier::from_str(DEFAULT_LOCALE).expect("Default locale should always be valid")
412421
});
413422

414423
// Load common strings along with utility-specific strings
415424
if let Ok(locales_dir) = get_locales_dir(p) {
416425
// Load both utility-specific and common strings
417-
init_localization(&locale, &locales_dir, p)
426+
init_localization(&locale, &locales_dir, p)?;
418427
} else {
419428
// No locales directory found, use embedded English with common strings directly
420429
let default_locale = LanguageIdentifier::from_str(DEFAULT_LOCALE)
@@ -426,8 +435,9 @@ pub fn setup_localization(p: &str) -> Result<(), LocalizationError> {
426435
lock.set(localizer)
427436
.map_err(|_| LocalizationError::Bundle("Localizer already initialized".into()))
428437
})?;
429-
Ok(())
430438
}
439+
LOCALIZER_IS_SET.with(|f| f.set(true));
440+
Ok(())
431441
}
432442

433443
#[cfg(not(debug_assertions))]

0 commit comments

Comments
 (0)