1use core::fmt::Write as _;
4
5use crate::arena::{ScratchArena, StrRef};
6
7use super::locale::{Locale, PluralCategory};
8
9#[derive(Copy, Clone, Debug)]
11pub struct MessageEntry {
12 pub key: &'static str,
13 pub value: &'static str,
14}
15
16impl MessageEntry {
17 #[inline(always)]
19 pub const fn new(key: &'static str, value: &'static str) -> Self {
20 Self { key, value }
21 }
22}
23
24#[derive(Copy, Clone, Debug)]
26pub struct StaticLocaleTable {
27 pub locale: Locale,
28 pub entries: &'static [MessageEntry],
29}
30
31impl StaticLocaleTable {
32 #[inline(always)]
34 pub const fn new(locale: Locale, entries: &'static [MessageEntry]) -> Self {
35 Self { locale, entries }
36 }
37
38 #[inline]
40 pub fn lookup(&self, key: &str) -> Option<&'static str> {
41 if let Ok(idx) = self.entries.binary_search_by(|e| e.key.cmp(key)) {
42 return Some(self.entries[idx].value);
43 }
44 self.entries
45 .iter()
46 .find(|e| e.key == key)
47 .map(|e| e.value)
48 }
49}
50
51#[derive(Copy, Clone, Debug)]
53pub struct StaticCatalog {
54 pub fallback: Locale,
56 pub tables: &'static [StaticLocaleTable],
58}
59
60impl StaticCatalog {
61 #[inline(always)]
63 pub const fn new(fallback: Locale, tables: &'static [StaticLocaleTable]) -> Self {
64 Self { fallback, tables }
65 }
66
67 #[inline]
68 fn find_exact(&self, locale: Locale, key: &str) -> Option<&'static str> {
69 self.tables
70 .iter()
71 .find(|t| t.locale == locale)
72 .and_then(|t| t.lookup(key))
73 }
74
75 #[inline]
76 fn find_same_lang(&self, locale: Locale, key: &str) -> Option<&'static str> {
77 self.tables
78 .iter()
79 .find(|t| t.locale.same_language(locale))
80 .and_then(|t| t.lookup(key))
81 }
82
83 pub fn lookup(&self, locale: Locale, key: &str) -> Option<&'static str> {
89 if let Some(v) = self.find_exact(locale, key) {
90 return Some(v);
91 }
92 let no_script = locale.without_script();
93 if no_script != locale {
94 if let Some(v) = self.find_exact(no_script, key) {
95 return Some(v);
96 }
97 }
98 let lang_only = locale.language_only();
99 if lang_only != locale {
100 if let Some(v) = self.find_exact(lang_only, key) {
101 return Some(v);
102 }
103 }
104 if let Some(v) = self.find_same_lang(locale, key) {
105 return Some(v);
106 }
107 if self.fallback != locale {
108 if let Some(v) = self.find_exact(self.fallback, key) {
109 return Some(v);
110 }
111 if let Some(v) = self.find_same_lang(self.fallback, key) {
112 return Some(v);
113 }
114 }
115 None
116 }
117
118 pub fn lookup_plural(&self, locale: Locale, key: &str, count: i64) -> Option<&'static str> {
120 let cat = locale.plural_category(count);
121 let mut buf = [0u8; 96];
122 let cat_key = format_plural_key(&mut buf, key, cat);
123 if let Some(v) = self.lookup(locale, cat_key) {
124 return Some(v);
125 }
126 if cat != PluralCategory::Other {
127 let other_key = format_plural_key(&mut buf, key, PluralCategory::Other);
128 if let Some(v) = self.lookup(locale, other_key) {
129 return Some(v);
130 }
131 }
132 self.lookup(locale, key)
133 }
134}
135
136#[inline]
138pub fn format_plural_key<'a>(
139 buf: &'a mut [u8; 96],
140 base_key: &'a str,
141 cat: PluralCategory,
142) -> &'a str {
143 let suffix = cat.suffix();
144 let kb = base_key.as_bytes();
145 let sb = suffix.as_bytes();
146 let total = kb.len() + 1 + sb.len();
147 if total > buf.len() {
148 return base_key;
149 }
150 buf[..kb.len()].copy_from_slice(kb);
151 buf[kb.len()] = b'.';
152 buf[kb.len() + 1..total].copy_from_slice(sb);
153 core::str::from_utf8(&buf[..total]).unwrap_or(base_key)
154}
155
156#[derive(Copy, Clone, Debug)]
158pub enum I18nArg<'a> {
159 Str(&'a str),
160 Int(i64),
161 Uint(u64),
162 Float(f64, u8),
164}
165
166impl<'a> From<&'a str> for I18nArg<'a> {
167 #[inline(always)]
168 fn from(v: &'a str) -> Self {
169 Self::Str(v)
170 }
171}
172
173impl<'a> From<StrRef<'a>> for I18nArg<'a> {
174 #[inline(always)]
175 fn from(v: StrRef<'a>) -> Self {
176 Self::Str(v.as_str())
177 }
178}
179
180impl From<i32> for I18nArg<'_> {
181 #[inline(always)]
182 fn from(v: i32) -> Self {
183 Self::Int(v as i64)
184 }
185}
186
187impl From<i64> for I18nArg<'_> {
188 #[inline(always)]
189 fn from(v: i64) -> Self {
190 Self::Int(v)
191 }
192}
193
194impl From<u8> for I18nArg<'_> {
195 #[inline(always)]
196 fn from(v: u8) -> Self {
197 Self::Uint(v as u64)
198 }
199}
200
201impl From<u16> for I18nArg<'_> {
202 #[inline(always)]
203 fn from(v: u16) -> Self {
204 Self::Uint(v as u64)
205 }
206}
207
208impl From<u32> for I18nArg<'_> {
209 #[inline(always)]
210 fn from(v: u32) -> Self {
211 Self::Uint(v as u64)
212 }
213}
214
215impl From<u64> for I18nArg<'_> {
216 #[inline(always)]
217 fn from(v: u64) -> Self {
218 Self::Uint(v)
219 }
220}
221
222impl From<usize> for I18nArg<'_> {
223 #[inline(always)]
224 fn from(v: usize) -> Self {
225 Self::Uint(v as u64)
226 }
227}
228
229impl From<f32> for I18nArg<'_> {
230 #[inline(always)]
231 fn from(v: f32) -> Self {
232 Self::Float(v as f64, 1)
233 }
234}
235
236impl From<f64> for I18nArg<'_> {
237 #[inline(always)]
238 fn from(v: f64) -> Self {
239 Self::Float(v, 2)
240 }
241}
242
243struct FixedBufWriter<const N: usize> {
244 buf: [u8; N],
245 len: usize,
246}
247
248impl<const N: usize> FixedBufWriter<N> {
249 #[inline]
250 fn new() -> Self {
251 Self {
252 buf: [0; N],
253 len: 0,
254 }
255 }
256
257 #[inline]
258 fn as_str(&self) -> &str {
259 core::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
260 }
261}
262
263impl<const N: usize> core::fmt::Write for FixedBufWriter<N> {
264 fn write_str(&mut self, s: &str) -> core::fmt::Result {
265 let bytes = s.as_bytes();
266 let avail = N.saturating_sub(self.len);
267 let mut take = bytes.len().min(avail);
268 while take > 0 && !s.is_char_boundary(take) {
269 take -= 1;
270 }
271 self.buf[self.len..self.len + take].copy_from_slice(&bytes[..take]);
272 self.len += take;
273 Ok(())
274 }
275}
276
277fn write_arg(out: &mut impl core::fmt::Write, arg: I18nArg<'_>) {
278 match arg {
279 I18nArg::Str(s) => {
280 let _ = out.write_str(s);
281 }
282 I18nArg::Int(v) => {
283 let _ = write!(out, "{}", v);
284 }
285 I18nArg::Uint(v) => {
286 let _ = write!(out, "{}", v);
287 }
288 I18nArg::Float(v, prec) => {
289 let p = (prec as usize).min(6);
290 let _ = write!(out, "{:.*}", p, v);
291 }
292 }
293}
294
295pub fn format_template<'a>(
299 arena: &'a ScratchArena,
300 template: &str,
301 args: &[(&str, I18nArg<'_>)],
302) -> StrRef<'a> {
303 if args.is_empty() && !template.contains("{{") && !template.contains("}}") {
304 return arena.alloc_str(template);
305 }
306
307 let mut writer = FixedBufWriter::<512>::new();
308 let bytes = template.as_bytes();
309 let mut i = 0usize;
310 while i < bytes.len() {
311 if bytes[i] == b'{' {
312 if i + 1 < bytes.len() && bytes[i + 1] == b'{' {
313 let _ = writer.write_char('{');
314 i += 2;
315 continue;
316 }
317 if let Some(rel_end) = template[i + 1..].find('}') {
318 let placeholder = &template[i + 1..i + 1 + rel_end];
319 let mut matched = false;
320 for &(k, v) in args {
321 if k == placeholder {
322 write_arg(&mut writer, v);
323 matched = true;
324 break;
325 }
326 }
327 if !matched {
328 if let Ok(pos_idx) = placeholder.parse::<usize>() {
329 if let Some(&(_, v)) = args.get(pos_idx) {
330 write_arg(&mut writer, v);
331 matched = true;
332 }
333 }
334 }
335 if !matched {
336 let _ = writer.write_str(&template[i..=i + 1 + rel_end]);
337 }
338 i += rel_end + 2;
339 continue;
340 }
341 } else if bytes[i] == b'}' && i + 1 < bytes.len() && bytes[i + 1] == b'}' {
342 let _ = writer.write_char('}');
343 i += 2;
344 continue;
345 }
346 let ch = template[i..].chars().next().unwrap_or(' ');
347 let _ = writer.write_char(ch);
348 i += ch.len_utf8();
349 }
350
351 arena.alloc_str(writer.as_str())
352}
353
354#[derive(Clone, Debug)]
356pub struct DynamicCatalog {
357 fallback: Locale,
358 tables: std::collections::HashMap<Locale, std::collections::HashMap<std::string::String, std::string::String>>,
359}
360
361impl Default for DynamicCatalog {
362 fn default() -> Self {
363 Self::new(Locale::EN_US)
364 }
365}
366
367impl DynamicCatalog {
368 pub fn new(fallback: Locale) -> Self {
370 Self {
371 fallback,
372 tables: std::collections::HashMap::new(),
373 }
374 }
375
376 pub fn merge_static(&mut self, catalog: &StaticCatalog) {
378 for tbl in catalog.tables {
379 let entry_map = self.tables.entry(tbl.locale).or_default();
380 for e in tbl.entries {
381 entry_map
382 .entry(std::string::String::from(e.key))
383 .or_insert_with(|| std::string::String::from(e.value));
384 }
385 }
386 }
387
388 pub fn insert(
390 &mut self,
391 locale: Locale,
392 key: impl Into<std::string::String>,
393 value: impl Into<std::string::String>,
394 ) {
395 self.tables
396 .entry(locale)
397 .or_default()
398 .insert(key.into(), value.into());
399 }
400
401 pub fn load_kv(&mut self, locale: Locale, content: &str) -> usize {
403 let mut count = 0usize;
404 let map = self.tables.entry(locale).or_default();
405 for raw_line in content.lines() {
406 let line = raw_line.trim();
407 if line.is_empty() || line.starts_with('#') || line.starts_with("//") {
408 continue;
409 }
410 if let Some((k, v)) = line.split_once('=') {
411 let key = k.trim();
412 let val = unescape_simple(v.trim());
413 if !key.is_empty() {
414 map.insert(std::string::String::from(key), val);
415 count += 1;
416 }
417 }
418 }
419 count
420 }
421
422 pub fn load_json(&mut self, locale: Locale, json: &str) -> usize {
424 let mut count = 0usize;
425 let map = self.tables.entry(locale).or_default();
426 let bytes = json.as_bytes();
427 let mut i = 0usize;
428 while i < bytes.len() {
429 while i < bytes.len() && bytes[i] != b'"' {
430 i += 1;
431 }
432 let Some((key, next_i)) = parse_json_string(json, i) else {
433 break;
434 };
435 i = next_i;
436 while i < bytes.len() && bytes[i].is_ascii_whitespace() {
437 i += 1;
438 }
439 if i >= bytes.len() || bytes[i] != b':' {
440 continue;
441 }
442 i += 1;
443 while i < bytes.len() && bytes[i].is_ascii_whitespace() {
444 i += 1;
445 }
446 if i >= bytes.len() || bytes[i] != b'"' {
447 continue;
448 }
449 let Some((val, val_next)) = parse_json_string(json, i) else {
450 break;
451 };
452 i = val_next;
453 if !key.is_empty() {
454 map.insert(key, val);
455 count += 1;
456 }
457 }
458 count
459 }
460
461 #[inline]
462 fn find_exact(&self, locale: Locale, key: &str) -> Option<&str> {
463 self.tables
464 .get(&locale)
465 .and_then(|m| m.get(key))
466 .map(|s| s.as_str())
467 }
468
469 #[inline]
470 fn find_same_lang(&self, locale: Locale, key: &str) -> Option<&str> {
471 self.tables
472 .iter()
473 .find(|(loc, _)| loc.same_language(locale))
474 .and_then(|(_, m)| m.get(key))
475 .map(|s| s.as_str())
476 }
477
478 pub fn lookup(&self, locale: Locale, key: &str) -> Option<&str> {
480 if let Some(v) = self.find_exact(locale, key) {
481 return Some(v);
482 }
483 let no_script = locale.without_script();
484 if no_script != locale {
485 if let Some(v) = self.find_exact(no_script, key) {
486 return Some(v);
487 }
488 }
489 let lang_only = locale.language_only();
490 if lang_only != locale {
491 if let Some(v) = self.find_exact(lang_only, key) {
492 return Some(v);
493 }
494 }
495 if let Some(v) = self.find_same_lang(locale, key) {
496 return Some(v);
497 }
498 if self.fallback != locale {
499 if let Some(v) = self.find_exact(self.fallback, key) {
500 return Some(v);
501 }
502 if let Some(v) = self.find_same_lang(self.fallback, key) {
503 return Some(v);
504 }
505 }
506 None
507 }
508
509 pub fn lookup_plural(&self, locale: Locale, key: &str, count: i64) -> Option<&str> {
511 let cat = locale.plural_category(count);
512 let mut buf = [0u8; 96];
513 let cat_key = format_plural_key(&mut buf, key, cat);
514 if let Some(v) = self.lookup(locale, cat_key) {
515 return Some(v);
516 }
517 if cat != PluralCategory::Other {
518 let other_key = format_plural_key(&mut buf, key, PluralCategory::Other);
519 if let Some(v) = self.lookup(locale, other_key) {
520 return Some(v);
521 }
522 }
523 self.lookup(locale, key)
524 }
525}
526
527fn unescape_simple(raw: &str) -> std::string::String {
528 let mut out = std::string::String::with_capacity(raw.len());
529 let mut chars = raw.chars();
530 while let Some(ch) = chars.next() {
531 if ch == '\\' {
532 match chars.next() {
533 Some('n') => out.push('\n'),
534 Some('t') => out.push('\t'),
535 Some('r') => out.push('\r'),
536 Some('\\') => out.push('\\'),
537 Some(other) => {
538 out.push('\\');
539 out.push(other);
540 }
541 None => out.push('\\'),
542 }
543 } else {
544 out.push(ch);
545 }
546 }
547 out
548}
549
550fn parse_json_string(src: &str, start_quote: usize) -> Option<(std::string::String, usize)> {
551 let bytes = src.as_bytes();
552 if bytes.get(start_quote) != Some(&b'"') {
553 return None;
554 }
555 let mut out = std::string::String::new();
556 let mut i = start_quote + 1;
557 while i < bytes.len() {
558 let b = bytes[i];
559 if b == b'"' {
560 return Some((out, i + 1));
561 }
562 if b == b'\\' {
563 i += 1;
564 if i >= bytes.len() {
565 return None;
566 }
567 match bytes[i] {
568 b'"' => out.push('"'),
569 b'\\' => out.push('\\'),
570 b'/' => out.push('/'),
571 b'n' => out.push('\n'),
572 b'r' => out.push('\r'),
573 b't' => out.push('\t'),
574 b'u' if i + 4 < bytes.len() => {
575 let hex = &src[i + 1..i + 5];
576 if let Ok(cp) = u32::from_str_radix(hex, 16) {
577 if let Some(ch) = char::from_u32(cp) {
578 out.push(ch);
579 }
580 }
581 i += 4;
582 }
583 other => out.push(other as char),
584 }
585 i += 1;
586 continue;
587 }
588 let ch = src[i..].chars().next()?;
589 out.push(ch);
590 i += ch.len_utf8();
591 }
592 None
593}