Skip to content

Commit f729750

Browse files
committed
feat: better translations performance
1 parent e61a668 commit f729750

File tree

1 file changed

+17
-24
lines changed

1 file changed

+17
-24
lines changed

src/translations.rs

Lines changed: 17 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,7 @@ pub struct LocalLocale {
1313
pub translations: Vec<Option<String>>,
1414
}
1515

16-
// TODO: make selected locale as index to LOCALES
17-
static mut SELECTED_LOCALE: [char; 6] = ['\0'; 6];
18-
static mut LOCALE_LENGTH: usize = 0;
19-
16+
static mut SELECTED_LOCALE: usize = usize::MAX;
2017
pub static LOCALES: Mutex<CriticalSectionRawMutex, Vec<LocalLocale>> = Mutex::new(Vec::new());
2118
macros::load_default_translations!("src/default_translation.json");
2219

@@ -28,26 +25,24 @@ pub fn clear_locales() {
2825
}
2926

3027
pub fn select_locale(locale: &str, global_state: &GlobalState) {
31-
let selected_locale = unsafe { SELECTED_LOCALE[..LOCALE_LENGTH].iter().collect::<String>() };
32-
if selected_locale == locale {
33-
return;
34-
}
35-
36-
if locale.chars().count() > 6 {
37-
log::error!("Locale too long!");
38-
return;
39-
}
28+
if let Ok(t) = LOCALES.try_lock() {
29+
let locale_idx = t
30+
.iter()
31+
.enumerate()
32+
.find(|(_, l)| l.locale == locale)
33+
.map(|(i, _)| i)
34+
.unwrap_or(usize::MAX);
35+
36+
unsafe {
37+
if locale_idx == SELECTED_LOCALE {
38+
return;
39+
}
4040

41-
unsafe {
42-
LOCALE_LENGTH = 0;
43-
for (i, c) in locale.chars().enumerate() {
44-
SELECTED_LOCALE[i] = c;
45-
LOCALE_LENGTH = i + 1;
41+
SELECTED_LOCALE = locale_idx;
42+
global_state.state.signal(); // reload locale
43+
log::info!("Selected locale: {locale}");
4644
}
4745
}
48-
49-
global_state.state.signal(); // reload locale
50-
log::info!("Selected locale: {locale}");
5146
}
5247

5348
pub fn process_locale(locale: String, records: Vec<TranslationRecord>) {
@@ -74,10 +69,8 @@ pub fn process_locale(locale: String, records: Vec<TranslationRecord>) {
7469
}
7570

7671
pub fn get_translation(key: usize) -> String {
77-
let selected_locale = unsafe { SELECTED_LOCALE[..LOCALE_LENGTH].iter().collect::<String>() };
78-
7972
if let Ok(t) = LOCALES.try_lock() {
80-
if let Some(locale) = t.iter().find(|l| l.locale == selected_locale) {
73+
if let Some(locale) = t.get(unsafe { SELECTED_LOCALE }) {
8174
return locale
8275
.translations
8376
.get(key)

0 commit comments

Comments
 (0)