Skip to main content

embedded_i18n/
locale.rs

1//! Locale identifiers, the global current locale and the `Display` wrapper of `t!`.
2
3use core::fmt;
4use core::sync::atomic::{AtomicU32, Ordering};
5
6/// Language value of tags that are not a 1 to 3 letter language code.
7const OTHER_LANGUAGE: u32 = 0x7FFF;
8
9const FNV_OFFSET: u32 = 0x811C_9DC5;
10const FNV_PRIME: u32 = 0x0100_0193;
11
12/// Normalizes one byte of a tag: ASCII lowercase, `_` as `-`.
13const fn normalize(byte: u8) -> u8 {
14    match byte {
15        b'_' => b'-',
16        byte => byte.to_ascii_lowercase(),
17    }
18}
19
20/// Hashes the normalized bytes of `bytes[start..end]` with FNV-1a, folded to
21/// 17 bits and never zero.
22const fn hash(bytes: &[u8], start: usize, end: usize) -> u32 {
23    if start >= end {
24        return 0;
25    }
26    let mut h = FNV_OFFSET;
27    let mut index = start;
28    while index < end {
29        h ^= normalize(bytes[index]) as u32;
30        h = h.wrapping_mul(FNV_PRIME);
31        index += 1;
32    }
33    let low = (h ^ (h >> 17)) & 0x1_FFFF;
34    if low == 0 { 1 } else { low }
35}
36
37/// Packs a locale tag into its identifier.
38const fn pack(tag: &str) -> u32 {
39    let bytes = tag.as_bytes();
40    let mut start = 0;
41    let mut end = bytes.len();
42    while start < end && bytes[start].is_ascii_whitespace() {
43        start += 1;
44    }
45    while end > start && bytes[end - 1].is_ascii_whitespace() {
46        end -= 1;
47    }
48    if start == end {
49        return 0;
50    }
51
52    let mut separator = start;
53    while separator < end && normalize(bytes[separator]) != b'-' {
54        separator += 1;
55    }
56
57    let length = separator - start;
58    let mut language = 0u32;
59    let mut is_language = length >= 1 && length <= 3;
60    let mut index = start;
61    while is_language && index < separator {
62        let byte = normalize(bytes[index]);
63        if byte.is_ascii_lowercase() {
64            language = language * 32 + (byte - b'a' + 1) as u32;
65        } else {
66            is_language = false;
67        }
68        index += 1;
69    }
70
71    if is_language {
72        let rest = if separator < end { separator + 1 } else { end };
73        (language << 17) | hash(bytes, rest, end)
74    } else {
75        (OTHER_LANGUAGE << 17) | hash(bytes, start, end)
76    }
77}
78
79/// A locale, packed into a 32-bit identifier.
80///
81/// The identifier is computed from the locale tag by a `const fn`, so tags
82/// cost nothing at runtime when converted in `const` context. The tag is
83/// normalized first (surrounding ASCII whitespace trimmed, ASCII lowercase,
84/// `_` as `-`), so `fr_CA`, `FR-ca` and ` fr-CA ` are the same locale.
85///
86/// The top 15 bits hold the language when it is 1 to 3 ASCII letters (5 bits
87/// per letter, `a` is 1); the low 17 bits hold a hash of the rest of the tag
88/// (region, script, variants), or `0` when there is none. Tags that do not
89/// start with a 1 to 3 letter language (`pseudo`) use the language value
90/// `0x7FFF` and hash the whole tag. [`Locale::NONE`] (identifier `0`) is the
91/// empty tag.
92///
93/// ```
94/// use embedded_i18n::Locale;
95///
96/// assert_eq!(Locale::new("fr_CA"), Locale::new("FR-ca"));
97/// assert_eq!(Locale::new("en").id(), 0x015C_0000);
98/// assert_eq!(Locale::NONE.id(), 0);
99/// ```
100#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
101pub struct Locale(u32);
102
103impl Locale {
104    /// The empty locale, identifier `0`: no locale was selected.
105    pub const NONE: Locale = Locale(0);
106
107    /// Packs a locale tag into a [`Locale`]. Usable in `const` context.
108    pub const fn new(tag: &str) -> Locale {
109        Locale(pack(tag))
110    }
111
112    /// Returns the packed 32-bit identifier.
113    pub const fn id(self) -> u32 {
114        self.0
115    }
116}
117
118impl From<&str> for Locale {
119    fn from(tag: &str) -> Locale {
120        Locale::new(tag)
121    }
122}
123
124static CURRENT: AtomicU32 = AtomicU32::new(0);
125
126/// Selects the current locale used by [`t!`](crate::t) and [`locale!`](crate::locale).
127///
128/// The locale is stored as a [`Locale`] identifier in an atomic with a plain
129/// store, so this works on targets without compare-and-swap and needs no
130/// allocation. An empty tag restores the unset state.
131///
132/// ```
133/// embedded_i18n::set_locale("fr");
134/// ```
135pub fn set_locale(locale: &str) {
136    CURRENT.store(Locale::new(locale).id(), Ordering::Relaxed);
137}
138
139/// Returns the identifier of the current locale, `0` when it was never set.
140#[doc(hidden)]
141pub fn __current_locale() -> u32 {
142    CURRENT.load(Ordering::Relaxed)
143}
144
145/// Formats with a closure: the value of a `t!` call with arguments.
146#[doc(hidden)]
147pub struct __FormatWith<F>(pub F);
148
149impl<F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result> fmt::Display for __FormatWith<F> {
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        (self.0)(f)
152    }
153}
154
155/// The plural operand of a `count` argument of `t!`: the absolute value of an
156/// integer, saturated to `u64`.
157///
158/// Only integers implement it, so `count = 2.5` or `count = true` does not
159/// compile:
160///
161/// ```compile_fail
162/// embedded_i18n::i18n!();
163///
164/// fn main() {
165///     let _ = embedded_i18n::t!("files", count = 2.5);
166/// }
167/// ```
168#[doc(hidden)]
169pub trait __PluralCount {
170    /// Returns the absolute value, saturated to `u64`.
171    fn __plural_operand(&self) -> u64;
172}
173
174impl<T: __PluralCount + ?Sized> __PluralCount for &T {
175    fn __plural_operand(&self) -> u64 {
176        (**self).__plural_operand()
177    }
178}
179
180macro_rules! plural_count {
181    (unsigned: $($unsigned:ty),*; signed: $($signed:ty),*) => {
182        $(
183            impl __PluralCount for $unsigned {
184                fn __plural_operand(&self) -> u64 {
185                    u64::try_from(*self).unwrap_or(u64::MAX)
186                }
187            }
188        )*
189        $(
190            impl __PluralCount for $signed {
191                fn __plural_operand(&self) -> u64 {
192                    u64::try_from(self.unsigned_abs()).unwrap_or(u64::MAX)
193                }
194            }
195        )*
196    };
197}
198
199plural_count!(
200    unsigned: u8, u16, u32, u64, u128, usize;
201    signed: i8, i16, i32, i64, i128, isize
202);
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn packs_reference_tags() {
210        assert_eq!(Locale::new("en").id(), 0x015C_0000);
211        assert_eq!(Locale::new("fr").id(), 0x01A4_0000);
212        assert_eq!(Locale::new("de").id(), 0x010A_0000);
213        assert_eq!(Locale::new("fr-CA").id(), 0x01A5_B85D);
214        assert_eq!(Locale::new("fr-FR").id(), 0x01A4_FD60);
215        assert_eq!(Locale::new("zh-Hant").id(), 0x0690_220D);
216        assert_eq!(Locale::new("zh-Hans").id(), 0x0690_3E88);
217        assert_eq!(Locale::new("pt-BR").id(), 0x0429_E320);
218        assert_eq!(Locale::new("pseudo").id(), 0xFFFE_7D15);
219        assert_eq!(Locale::new("x-a").id(), 0x0030_5B2A);
220        assert_eq!(Locale::new(""), Locale::NONE);
221    }
222
223    #[test]
224    fn normalizes_before_packing() {
225        assert_eq!(Locale::new("FR_ca"), Locale::new("fr-CA"));
226        assert_eq!(Locale::new(" fr-ca "), Locale::new("fr-CA"));
227        assert_eq!(Locale::from("pt_br"), Locale::new("pt-BR"));
228    }
229
230    #[test]
231    fn global_locale_round_trips() {
232        // single test touching the global, so no lock is needed
233        assert_eq!(__current_locale(), 0);
234        set_locale("fr_CA");
235        assert_eq!(__current_locale(), 0x01A5_B85D);
236        set_locale("");
237        assert_eq!(__current_locale(), 0);
238    }
239
240    #[test]
241    fn plural_operand_is_the_saturated_absolute_value() {
242        assert_eq!(3u8.__plural_operand(), 3);
243        assert_eq!((-1i32).__plural_operand(), 1);
244        assert_eq!(i64::MIN.__plural_operand(), 1 << 63);
245        assert_eq!(u64::MAX.__plural_operand(), u64::MAX);
246        assert_eq!(u128::MAX.__plural_operand(), u64::MAX);
247        assert_eq!(i128::MIN.__plural_operand(), u64::MAX);
248        assert_eq!((&&7usize).__plural_operand(), 7);
249    }
250
251    const _: () = assert!(Locale::new("en").id() == 0x015C_0000); // const fn
252}