lang_id/maps/max_id.rs
1use compact_str::ToCompactString;
2use tap::{Pipe, Tap};
3
4use crate::{LangID, maps::TinyID};
5
6/// Represents a maximized language identifier with memory-efficient storage
7/// variants
8///
9/// Combines standard Unicode locale identifiers with optimized tiny
10/// representations for common cases, following Unicode CLDR's locale
11/// maximization rules.
12///
13/// # Variants
14/// - `Regular`: Regular Language identifier.
15/// - `Tiny`: Precomputed optimized representation for frequent locales
16#[derive(Debug, Clone)]
17pub enum MaxLangID {
18 Regular(LangID),
19 Tiny(TinyID),
20}
21
22impl core::fmt::Display for MaxLangID {
23 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
24 write!(
25 f,
26 "{}-{}-{}",
27 self.get_language(),
28 self.get_script(),
29 self.get_region()
30 )
31 }
32}
33
34impl MaxLangID {
35 /// Constructs a maximized locale identifier using CLDR supplementation data
36 ///
37 /// # Behavior
38 /// 1. Checks against precomputed frequent locale map
39 /// 2. Returns optimized TinyID if exists in map
40 /// 3. Otherwise maximizes the input ID and stores full representation
41 ///
42 /// # Examples
43 /// ```
44 /// use lang_id::maps::MaxLangID;
45 ///
46 /// let id = lang_id::consts::lang_id_en();
47 /// assert_eq!(id.region, None);
48 ///
49 /// let max_id = MaxLangID::new(&id);
50 ///
51 /// assert_eq!(max_id.get_region(), "US");
52 /// ```
53 pub fn new(language: &LangID) -> Self {
54 let map = crate::maps::max::map();
55
56 match map.get(&language.to_compact_string()) {
57 Some(id) => Self::Tiny(*id),
58 _ => language
59 .clone()
60 .tap_mut(|x| {
61 x.maximize();
62 })
63 .pipe(MaxLangID::Regular),
64 }
65 }
66
67 /// Retrieves the base language code (ISO 639 alpha-2/3)
68 ///
69 /// ## Returns
70 ///
71 /// - Normalized lowercase language code
72 /// - Empty string for invalid/unknown codes
73 pub fn get_language(&self) -> &str {
74 match self {
75 Self::Regular(id) => id.language.as_str(),
76 Self::Tiny(id) => id.language.as_str(),
77 }
78 }
79
80 /// Retrieves the script code if available
81 pub fn get_script(&self) -> &str {
82 match self {
83 Self::Regular(id) => match &id.script {
84 Some(s) => s.as_str(),
85 _ => "",
86 },
87 Self::Tiny(id) => id.script.as_str(),
88 }
89 }
90
91 /// Retrieves the region code if available
92 ///
93 /// ## Returns
94 ///
95 /// - Uppercase region code when explicitly defined
96 /// - Empty string for inferred regions
97 pub fn get_region(&self) -> &str {
98 match self {
99 Self::Regular(id) => match &id.region {
100 Some(s) => s.as_str(),
101 _ => "",
102 },
103 Self::Tiny(id) => id.region.as_str(),
104 }
105 }
106}