1use std::collections::HashMap;
24
25use crate::plural::{PluralCategory, PluralForms, PluralRule};
26
27pub type Locale = String;
29
30#[derive(Debug, Clone)]
32pub enum I18nError {
33 InvalidLocale(String),
35 ParseError(String),
37 DuplicateKey { locale: String, key: String },
39}
40
41impl std::fmt::Display for I18nError {
42 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 match self {
44 Self::InvalidLocale(l) => write!(f, "invalid locale: {l}"),
45 Self::ParseError(msg) => write!(f, "parse error: {msg}"),
46 Self::DuplicateKey { locale, key } => {
47 write!(f, "duplicate key '{key}' in locale '{locale}'")
48 }
49 }
50 }
51}
52
53impl std::error::Error for I18nError {}
54
55#[derive(Debug, Clone)]
57pub enum StringEntry {
58 Simple(String),
60 Plural(PluralForms),
62}
63
64#[derive(Debug, Clone, Default)]
66pub struct LocaleStrings {
67 strings: HashMap<String, StringEntry>,
68}
69
70impl LocaleStrings {
71 #[must_use]
73 pub fn new() -> Self {
74 Self::default()
75 }
76
77 pub fn insert(&mut self, key: impl Into<String>, value: impl Into<String>) {
79 self.strings
80 .insert(key.into(), StringEntry::Simple(value.into()));
81 }
82
83 pub fn insert_plural(&mut self, key: impl Into<String>, forms: PluralForms) {
85 self.strings.insert(key.into(), StringEntry::Plural(forms));
86 }
87
88 #[must_use]
90 pub fn get(&self, key: &str) -> Option<&StringEntry> {
91 self.strings.get(key)
92 }
93
94 #[must_use]
96 pub fn len(&self) -> usize {
97 self.strings.len()
98 }
99
100 #[must_use]
102 pub fn is_empty(&self) -> bool {
103 self.strings.is_empty()
104 }
105
106 pub fn keys(&self) -> impl Iterator<Item = &str> {
108 self.strings.keys().map(String::as_str)
109 }
110}
111
112#[derive(Debug, Clone)]
148pub struct StringCatalog {
149 locales: HashMap<Locale, LocaleStrings>,
150 fallback_chain: Vec<Locale>,
151 plural_rules: HashMap<Locale, PluralRule>,
152}
153
154impl Default for StringCatalog {
155 fn default() -> Self {
156 Self::new()
157 }
158}
159
160impl StringCatalog {
161 #[must_use]
163 pub fn new() -> Self {
164 Self {
165 locales: HashMap::new(),
166 fallback_chain: Vec::new(),
167 plural_rules: HashMap::new(),
168 }
169 }
170
171 pub fn add_locale(&mut self, locale: impl Into<String>, strings: LocaleStrings) {
177 let locale = locale.into();
178 self.plural_rules
179 .entry(locale.clone())
180 .or_insert_with(|| PluralRule::for_locale(&locale));
181 self.locales.insert(locale, strings);
182 }
183
184 pub fn set_fallback_chain(&mut self, chain: Vec<Locale>) {
189 self.fallback_chain = chain;
190 }
191
192 pub fn set_plural_rule(&mut self, locale: impl Into<String>, rule: PluralRule) {
194 self.plural_rules.insert(locale.into(), rule);
195 }
196
197 #[must_use]
202 pub fn get(&self, locale: &str, key: &str) -> Option<&str> {
203 if let Some(entry) = self.locales.get(locale).and_then(|ls| ls.get(key)) {
205 return match entry {
206 StringEntry::Simple(s) => Some(s.as_str()),
207 StringEntry::Plural(p) => Some(&p.other),
208 };
209 }
210
211 for fallback in &self.fallback_chain {
213 if fallback == locale {
214 continue; }
216 if let Some(entry) = self
217 .locales
218 .get(fallback.as_str())
219 .and_then(|ls| ls.get(key))
220 {
221 return match entry {
222 StringEntry::Simple(s) => Some(s.as_str()),
223 StringEntry::Plural(p) => Some(&p.other),
224 };
225 }
226 }
227
228 None
229 }
230
231 #[must_use]
235 pub fn get_plural(&self, locale: &str, key: &str, count: i64) -> Option<&str> {
236 let rule = self
237 .plural_rules
238 .get(locale)
239 .cloned()
240 .unwrap_or(PluralRule::English);
241 let category = rule.categorize(count);
242
243 if let Some(result) = self.get_plural_from(locale, key, category) {
245 return Some(result);
246 }
247
248 for fallback in &self.fallback_chain {
250 if fallback == locale {
251 continue;
252 }
253 let fb_rule = self
254 .plural_rules
255 .get(fallback.as_str())
256 .cloned()
257 .unwrap_or(PluralRule::English);
258 let fb_category = fb_rule.categorize(count);
259 if let Some(result) = self.get_plural_from(fallback, key, fb_category) {
260 return Some(result);
261 }
262 }
263
264 None
265 }
266
267 fn get_plural_from(&self, locale: &str, key: &str, category: PluralCategory) -> Option<&str> {
268 self.locales
269 .get(locale)
270 .and_then(|ls| ls.get(key))
271 .map(|entry| match entry {
272 StringEntry::Plural(forms) => forms.select(category),
273 StringEntry::Simple(s) => s.as_str(),
274 })
275 }
276
277 #[must_use]
282 pub fn format(&self, locale: &str, key: &str, args: &[(&str, &str)]) -> Option<String> {
283 self.get(locale, key)
284 .map(|template| interpolate(template, args))
285 }
286
287 #[must_use]
291 pub fn format_plural(
292 &self,
293 locale: &str,
294 key: &str,
295 count: i64,
296 extra_args: &[(&str, &str)],
297 ) -> Option<String> {
298 self.get_plural(locale, key, count).map(|template| {
299 let count_str = count.to_string();
300 let mut all_args: Vec<(&str, &str)> = vec![("count", &count_str)];
301 all_args.extend_from_slice(extra_args);
302 interpolate(template, &all_args)
303 })
304 }
305
306 #[must_use]
308 pub fn locales(&self) -> Vec<&str> {
309 self.locales.keys().map(String::as_str).collect()
310 }
311
312 #[must_use]
320 pub fn all_keys(&self) -> Vec<String> {
321 let mut keys: Vec<String> = self
322 .locales
323 .values()
324 .flat_map(|ls| ls.keys().map(String::from))
325 .collect();
326 keys.sort_unstable();
327 keys.dedup();
328 keys
329 }
330
331 #[must_use]
336 pub fn missing_keys(&self, locale: &str, reference_keys: &[&str]) -> Vec<String> {
337 let mut missing = Vec::new();
338 for &key in reference_keys {
339 if self.get(locale, key).is_none() {
340 missing.push(key.to_string());
341 }
342 }
343 missing.sort_unstable();
344 missing
345 }
346
347 #[must_use]
352 pub fn coverage_report(&self) -> CoverageReport {
353 let all = self.all_keys();
354 let ref_keys: Vec<&str> = all.iter().map(String::as_str).collect();
355 let total = ref_keys.len();
356
357 let mut locale_tags: Vec<String> = self.locales.keys().cloned().collect();
358 locale_tags.sort_unstable();
359
360 let locales = locale_tags
361 .into_iter()
362 .map(|tag| {
363 let missing = self.missing_keys(&tag, &ref_keys);
364 let present = total.saturating_sub(missing.len());
365 let coverage_percent = if total == 0 {
366 100.0
367 } else {
368 (present as f32 / total as f32) * 100.0
369 };
370 LocaleCoverage {
371 locale: tag,
372 present,
373 missing,
374 coverage_percent,
375 }
376 })
377 .collect();
378
379 CoverageReport {
380 total_keys: total,
381 locales,
382 }
383 }
384}
385
386#[derive(Debug, Clone)]
391pub struct CoverageReport {
392 pub total_keys: usize,
394 pub locales: Vec<LocaleCoverage>,
396}
397
398#[derive(Debug, Clone)]
400pub struct LocaleCoverage {
401 pub locale: String,
403 pub present: usize,
405 pub missing: Vec<String>,
407 pub coverage_percent: f32,
409}
410
411fn interpolate(template: &str, args: &[(&str, &str)]) -> String {
413 let mut result = String::with_capacity(template.len());
414 let mut chars = template.chars().peekable();
415
416 while let Some(ch) = chars.next() {
417 if ch == '{' {
418 let mut placeholder = String::new();
420 let mut found_close = false;
421 for c in chars.by_ref() {
422 if c == '}' {
423 found_close = true;
424 break;
425 }
426 placeholder.push(c);
427 }
428
429 if found_close {
430 if let Some(&(_, value)) = args.iter().find(|&&(name, _)| name == placeholder) {
432 result.push_str(value);
433 } else {
434 result.push('{');
436 result.push_str(&placeholder);
437 result.push('}');
438 }
439 } else {
440 result.push('{');
442 result.push_str(&placeholder);
443 }
444 } else {
445 result.push(ch);
446 }
447 }
448
449 result
450}
451
452#[cfg(test)]
453mod tests {
454 use super::*;
455 use crate::plural::PluralForms;
456
457 fn english_catalog() -> StringCatalog {
458 let mut catalog = StringCatalog::new();
459 let mut en = LocaleStrings::new();
460 en.insert("greeting", "Hello");
461 en.insert("welcome", "Welcome, {name}!");
462 en.insert("farewell", "Goodbye, {name}. See you {when}.");
463 en.insert_plural(
464 "items",
465 PluralForms {
466 one: "{count} item".into(),
467 other: "{count} items".into(),
468 ..Default::default()
469 },
470 );
471 catalog.add_locale("en", en);
472 catalog.set_fallback_chain(vec!["en".into()]);
473 catalog
474 }
475
476 #[test]
477 fn simple_lookup() {
478 let catalog = english_catalog();
479 assert_eq!(catalog.get("en", "greeting"), Some("Hello"));
480 }
481
482 #[test]
483 fn missing_key_returns_none() {
484 let catalog = english_catalog();
485 assert_eq!(catalog.get("en", "nonexistent"), None);
486 }
487
488 #[test]
489 fn missing_locale_falls_back() {
490 let catalog = english_catalog();
491 assert_eq!(catalog.get("fr", "greeting"), Some("Hello"));
493 }
494
495 #[test]
496 fn fallback_chain_order() {
497 let mut catalog = StringCatalog::new();
498
499 let mut en = LocaleStrings::new();
500 en.insert("greeting", "Hello");
501 en.insert("color", "Color");
502
503 let mut es = LocaleStrings::new();
504 es.insert("greeting", "Hola");
505 let mut es_mx = LocaleStrings::new();
508 es_mx.insert("greeting", "Qué onda");
509 catalog.add_locale("en", en);
512 catalog.add_locale("es", es);
513 catalog.add_locale("es-MX", es_mx);
514 catalog.set_fallback_chain(vec!["es-MX".into(), "es".into(), "en".into()]);
515
516 assert_eq!(catalog.get("es-MX", "greeting"), Some("Qué onda"));
518 assert_eq!(catalog.get("es-MX", "color"), Some("Color"));
520 }
521
522 #[test]
523 fn plural_english_singular() {
524 let catalog = english_catalog();
525 assert_eq!(catalog.get_plural("en", "items", 1), Some("{count} item"));
526 }
527
528 #[test]
529 fn plural_english_plural() {
530 let catalog = english_catalog();
531 assert_eq!(catalog.get_plural("en", "items", 0), Some("{count} items"));
532 assert_eq!(catalog.get_plural("en", "items", 2), Some("{count} items"));
533 assert_eq!(
534 catalog.get_plural("en", "items", 100),
535 Some("{count} items")
536 );
537 }
538
539 #[test]
540 fn plural_russian() {
541 let mut catalog = StringCatalog::new();
542 let mut ru = LocaleStrings::new();
543 ru.insert_plural(
544 "files",
545 PluralForms {
546 one: "{count} файл".into(),
547 few: Some("{count} файла".into()),
548 many: Some("{count} файлов".into()),
549 other: "{count} файлов".into(),
550 ..Default::default()
551 },
552 );
553 catalog.add_locale("ru", ru);
554
555 assert_eq!(catalog.get_plural("ru", "files", 1), Some("{count} файл"));
556 assert_eq!(catalog.get_plural("ru", "files", 3), Some("{count} файла"));
557 assert_eq!(catalog.get_plural("ru", "files", 5), Some("{count} файлов"));
558 assert_eq!(catalog.get_plural("ru", "files", 21), Some("{count} файл"));
559 }
560
561 #[test]
562 fn plural_rule_set_before_the_strings_survives_add_locale() {
563 fn hebrew(n: i64) -> PluralCategory {
566 match n.unsigned_abs() {
567 1 => PluralCategory::One,
568 2 => PluralCategory::Two,
569 _ => PluralCategory::Other,
570 }
571 }
572 let mut catalog = StringCatalog::new();
573 catalog.set_plural_rule("he", PluralRule::Custom(hebrew));
574 let mut he = LocaleStrings::new();
575 he.insert_plural(
576 "days",
577 PluralForms {
578 one: "יום".into(),
579 two: Some("יומיים".into()),
580 other: "{count} ימים".into(),
581 ..Default::default()
582 },
583 );
584 catalog.add_locale("he", he);
585
586 assert_eq!(catalog.get_plural("he", "days", 2), Some("יומיים"));
587 }
588
589 #[test]
590 fn interpolation_single_arg() {
591 let catalog = english_catalog();
592 assert_eq!(
593 catalog.format("en", "welcome", &[("name", "Alice")]),
594 Some("Welcome, Alice!".into())
595 );
596 }
597
598 #[test]
599 fn interpolation_multiple_args() {
600 let catalog = english_catalog();
601 assert_eq!(
602 catalog.format("en", "farewell", &[("name", "Bob"), ("when", "tomorrow")]),
603 Some("Goodbye, Bob. See you tomorrow.".into())
604 );
605 }
606
607 #[test]
608 fn interpolation_missing_arg_left_as_is() {
609 let catalog = english_catalog();
610 assert_eq!(
611 catalog.format("en", "welcome", &[]),
612 Some("Welcome, {name}!".into())
613 );
614 }
615
616 #[test]
617 fn format_plural_auto_count() {
618 let catalog = english_catalog();
619 assert_eq!(
620 catalog.format_plural("en", "items", 1, &[]),
621 Some("1 item".into())
622 );
623 assert_eq!(
624 catalog.format_plural("en", "items", 42, &[]),
625 Some("42 items".into())
626 );
627 }
628
629 #[test]
630 fn interpolation_edge_cases() {
631 assert_eq!(interpolate("Hello {world", &[]), "Hello {world");
633 assert_eq!(interpolate("Hello {}", &[]), "Hello {}");
635 assert_eq!(interpolate("Hello World", &[]), "Hello World");
637 assert_eq!(interpolate("{x} and {x}", &[("x", "A")]), "A and A");
639 }
640
641 #[test]
642 fn empty_catalog() {
643 let catalog = StringCatalog::new();
644 assert_eq!(catalog.get("en", "anything"), None);
645 assert_eq!(catalog.get_plural("en", "anything", 1), None);
646 assert!(catalog.locales().is_empty());
647 }
648
649 #[test]
650 fn locale_listing() {
651 let catalog = english_catalog();
652 let locales = catalog.locales();
653 assert_eq!(locales.len(), 1);
654 assert!(locales.contains(&"en"));
655 }
656
657 #[test]
658 fn locale_strings_len() {
659 let catalog = english_catalog();
660 let en = catalog.locales.get("en").unwrap();
661 assert_eq!(en.len(), 4); assert!(!en.is_empty());
663 }
664
665 #[test]
666 fn simple_entry_from_plural_lookup() {
667 let catalog = english_catalog();
669 assert_eq!(catalog.get_plural("en", "greeting", 1), Some("Hello"));
670 }
671
672 fn multi_locale_catalog() -> StringCatalog {
677 let mut catalog = StringCatalog::new();
678
679 let mut en = LocaleStrings::new();
680 en.insert("greeting", "Hello");
681 en.insert("farewell", "Goodbye");
682 en.insert("submit", "Submit");
683 catalog.add_locale("en", en);
684
685 let mut es = LocaleStrings::new();
686 es.insert("greeting", "Hola");
687 es.insert("farewell", "Adiós");
688 catalog.add_locale("es", es);
690
691 let mut fr = LocaleStrings::new();
692 fr.insert("greeting", "Bonjour");
693 catalog.add_locale("fr", fr);
695
696 catalog.set_fallback_chain(vec!["en".into()]);
697 catalog
698 }
699
700 #[test]
701 fn locale_strings_keys() {
702 let mut ls = LocaleStrings::new();
703 ls.insert("alpha", "A");
704 ls.insert("beta", "B");
705
706 let mut keys: Vec<&str> = ls.keys().collect();
707 keys.sort_unstable();
708 assert_eq!(keys, vec!["alpha", "beta"]);
709 }
710
711 #[test]
712 fn all_keys_is_sorted_and_deduped() {
713 let catalog = multi_locale_catalog();
714 let keys = catalog.all_keys();
715 assert_eq!(keys, vec!["farewell", "greeting", "submit"]);
716 }
717
718 #[test]
719 fn all_keys_empty_catalog() {
720 let catalog = StringCatalog::new();
721 assert!(catalog.all_keys().is_empty());
722 }
723
724 #[test]
725 fn missing_keys_none_missing() {
726 let catalog = multi_locale_catalog();
727 let missing = catalog.missing_keys("en", &["greeting", "farewell", "submit"]);
728 assert!(missing.is_empty());
729 }
730
731 #[test]
732 fn missing_keys_with_fallback() {
733 let catalog = multi_locale_catalog();
734 let missing = catalog.missing_keys("es", &["greeting", "farewell", "submit"]);
735 assert!(missing.is_empty(), "fallback should resolve submit");
736 }
737
738 #[test]
739 fn missing_keys_no_fallback() {
740 let mut catalog = StringCatalog::new();
741 let mut es = LocaleStrings::new();
742 es.insert("greeting", "Hola");
743 catalog.add_locale("es", es);
744 let missing = catalog.missing_keys("es", &["greeting", "farewell"]);
745 assert_eq!(missing, vec!["farewell"]);
746 }
747
748 #[test]
749 fn missing_keys_unknown_locale() {
750 let catalog = multi_locale_catalog();
751 let missing = catalog.missing_keys("de", &["greeting", "farewell", "submit"]);
752 assert!(missing.is_empty(), "fallback to en should cover all");
753 }
754
755 #[test]
756 fn coverage_report_structure() {
757 let catalog = multi_locale_catalog();
758 let report = catalog.coverage_report();
759
760 assert_eq!(report.total_keys, 3);
761 assert_eq!(report.locales.len(), 3);
762
763 let tags: Vec<&str> = report.locales.iter().map(|l| l.locale.as_str()).collect();
764 let mut sorted_tags = tags.clone();
765 sorted_tags.sort_unstable();
766 assert_eq!(tags, sorted_tags);
767 }
768
769 #[test]
770 fn coverage_report_with_fallback() {
771 let catalog = multi_locale_catalog();
772 let report = catalog.coverage_report();
773
774 for lc in &report.locales {
775 assert_eq!(
776 lc.present, 3,
777 "{} should have all 3 keys via fallback",
778 lc.locale
779 );
780 assert!(
781 lc.missing.is_empty(),
782 "{} should have no missing keys via fallback",
783 lc.locale
784 );
785 assert!(
786 (lc.coverage_percent - 100.0).abs() < f32::EPSILON,
787 "{} should be 100% coverage",
788 lc.locale
789 );
790 }
791 }
792
793 #[test]
794 fn coverage_report_without_fallback() {
795 let mut catalog = StringCatalog::new();
796
797 let mut en = LocaleStrings::new();
798 en.insert("a", "A");
799 en.insert("b", "B");
800 en.insert("c", "C");
801 catalog.add_locale("en", en);
802
803 let mut fr = LocaleStrings::new();
804 fr.insert("a", "A-fr");
805 catalog.add_locale("fr", fr);
806
807 let report = catalog.coverage_report();
808 assert_eq!(report.total_keys, 3);
809
810 let en_cov = report.locales.iter().find(|l| l.locale == "en").unwrap();
811 assert_eq!(en_cov.present, 3);
812 assert!(en_cov.missing.is_empty());
813
814 let fr_cov = report.locales.iter().find(|l| l.locale == "fr").unwrap();
815 assert_eq!(fr_cov.present, 1);
816 assert_eq!(fr_cov.missing, vec!["b", "c"]);
817 assert!((fr_cov.coverage_percent - 33.333_332).abs() < 0.01);
818 }
819
820 #[test]
821 fn coverage_report_empty_catalog() {
822 let catalog = StringCatalog::new();
823 let report = catalog.coverage_report();
824 assert_eq!(report.total_keys, 0);
825 assert!(report.locales.is_empty());
826 }
827}