Skip to main content

utopia_locale/
lib.rs

1//! Translate text into the user's language, with a fallback language and
2//! `{{placeholder}}` substitution.
3//!
4//! Register every language once in a [`Languages`] value, from maps or JSON
5//! files, then create a [`Locale`] per request that borrows it and looks up
6//! texts with [`Locale::text`]. Whether a missing language or key is an
7//! error is a setting of the [`Languages`].
8//!
9//! PHP: ports `utopia-php/locale`. PHP keeps every language, and whether
10//! missing keys throw, in static state shared by all `Locale` objects; here
11//! that state is the [`Languages`] value.
12//!
13//! | PHP | Rust |
14//! |---|---|
15//! | `Locale::$language` (static) | [`Languages`] |
16//! | `Locale::$exceptions` (static) | [`Languages::set_exceptions`], [`Languages::exceptions`] |
17//! | `Locale::setLanguageFromArray($name, $translations)` | [`Languages::insert`] |
18//! | `Locale::setLanguageFromJSON($name, $path)` | [`Languages::load`] (reading) and [`Languages::insert_json`] (decoding) |
19//! | `Locale::getLanguages()` | [`Languages::names`] |
20//! | `new Locale($default)` | [`Locale::new`] |
21//! | `$locale->setDefault($name)`, `setFallback($name)` | [`Locale::set_default`], [`Locale::set_fallback`] |
22//! | `public $default`, `public $fallback` | [`Locale::default`], [`Locale::fallback`]; assigned unchecked with [`Locale::with`] |
23//! | `$locale->getText($key, $default, $placeholders)` | [`Locale::text`], `$default` as [`Missing`] |
24//! | `Locale::DEFAULT_DYNAMIC_KEY` | [`DEFAULT_DYNAMIC_KEY`] |
25//! | `$locale->getTranslations()` | [`Locale::translations`] |
26//! | `\Exception`, `\TypeError` | [`Error::Exception`], [`Error::Type`] |
27//!
28//! PHP: translations are strings. PHP stores whatever `json_decode` returns for a
29//! translation file; a file that is not JSON (or is unreadable) becomes a
30//! language PHP cannot use, and so it is here: lookups in it fail with the
31//! same `TypeError` (see [`Error::Type`]). A file whose values are not all
32//! strings is refused ([`Error::Unsupported`]), a recorded deviation.
33
34#![warn(missing_docs)]
35
36use std::borrow::Cow;
37use std::collections::HashMap;
38use std::path::Path;
39use std::sync::{Arc, OnceLock};
40
41use indexmap::IndexMap;
42use php_std::Value;
43use php_std::json::{self, Flags};
44use php_std::types::KeyRef;
45
46/// The getting started guide (`guide.md`), compiled and run with the doctests.
47#[cfg(doctest)]
48#[doc = include_str!("../guide.md")]
49pub struct GettingStarted;
50
51/// A marker text that, passed as [`Missing::Text`], means [`Missing::Key`].
52///
53/// PHP: `Locale::DEFAULT_DYNAMIC_KEY`.
54pub const DEFAULT_DYNAMIC_KEY: &str = "[[defaultDynamicKey]]";
55
56/// The hasher of every map here: keys are looked up on each text read, and
57/// foldhash is several times faster than SipHash on them.
58type Hasher = foldhash::fast::RandomState;
59
60/// Translations of one language, in file order.
61pub type Translations = IndexMap<String, String, Hasher>;
62
63/// Why a lookup or a language registration failed.
64///
65/// PHP: each variant matches the exception class PHP throws, given by
66/// [`Error::php_class`].
67#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
68pub enum Error {
69    /// An unknown language, a missing translation file or a missing key,
70    /// reported only while [`Languages::exceptions`] is on.
71    ///
72    /// PHP: `\Exception`.
73    #[error("{0}")]
74    Exception(String),
75    /// A lookup in a language that holds no translations: one loaded from
76    /// an unreadable or invalid file or from a JSON scalar, or an unknown
77    /// default language while exceptions are off.
78    ///
79    /// PHP: `\TypeError`, raised on a language PHP stored as something
80    /// other than an array.
81    #[error("{0}")]
82    Type(String),
83    /// A translation file whose values are not all strings.
84    ///
85    /// PHP stores such a file and returns the non-string values; Rust
86    /// refuses it (a deviation).
87    #[error("{0}")]
88    Unsupported(String),
89}
90
91impl Error {
92    /// The name of the exception class this error matches: `Exception` or
93    /// `TypeError`.
94    ///
95    /// PHP: the class of the exception `utopia-php/locale` throws for the
96    /// same call.
97    pub fn php_class(&self) -> &'static str {
98        match self {
99            Error::Exception(_) | Error::Unsupported(_) => "Exception",
100            Error::Type(_) => "TypeError",
101        }
102    }
103}
104
105/// What [`Locale::text`] returns for a key no language has.
106///
107/// PHP: the `$default` argument of `getText()`.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
109pub enum Missing<'a> {
110    /// The key in double braces, `{{key}}`.
111    ///
112    /// PHP: the default, [`DEFAULT_DYNAMIC_KEY`].
113    #[default]
114    Key,
115    /// This text.
116    Text(&'a str),
117    /// Nothing (`null`).
118    Null,
119}
120
121/// A registered language.
122#[derive(Debug, Clone)]
123enum Language {
124    Texts(Translations),
125    /// A translation file that is a JSON object of strings, kept as its text and
126    /// decoded on first use, then shared by every name registered from the same
127    /// text.
128    Json(Arc<Json>),
129    /// What PHP holds instead of an array, by the name its type errors use
130    /// (`null`, `true`, `false`, `int`, `float`, `string`).
131    Unusable(&'static str),
132}
133
134impl PartialEq for Language {
135    fn eq(&self, other: &Self) -> bool {
136        match (self.resolve(), other.resolve()) {
137            (Ok(a), Ok(b)) => a == b,
138            (Err(a), Err(b)) => a == b,
139            _ => false,
140        }
141    }
142}
143
144impl Language {
145    /// The translations, or the name of what PHP holds instead of an array.
146    fn resolve(&self) -> Result<&Translations, &'static str> {
147        match self {
148            Language::Texts(texts) => Ok(texts),
149            Language::Json(json) => Ok(json.texts()),
150            Language::Unusable(given) => Err(given),
151        }
152    }
153}
154
155/// The text of a translation file that is a JSON object of strings, checked when
156/// it was registered and decoded on first use. Most registered languages are
157/// never read in a given process, so this keeps them as their JSON text.
158#[derive(Debug)]
159struct Json {
160    text: Arc<[u8]>,
161    texts: OnceLock<Translations>,
162}
163
164impl Json {
165    fn texts(&self) -> &Translations {
166        self.texts.get_or_init(|| {
167            serde_json::from_slice(&self.text).expect("checked to be a JSON object of strings when it was registered")
168        })
169    }
170}
171
172/// Whether `json` is a JSON object whose values are all strings: what
173/// `serde_json::from_slice::<Translations>` accepts, checked without building
174/// anything.
175fn is_object_of_strings(json: &[u8]) -> bool {
176    use serde::de::{self, Deserialize, Deserializer, MapAccess, Visitor};
177
178    struct AnyString;
179    impl<'de> Deserialize<'de> for AnyString {
180        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
181            struct V;
182            impl Visitor<'_> for V {
183                type Value = AnyString;
184                fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185                    f.write_str("a string")
186                }
187                fn visit_str<E: de::Error>(self, _: &str) -> Result<AnyString, E> {
188                    Ok(AnyString)
189                }
190            }
191            deserializer.deserialize_string(V)
192        }
193    }
194
195    struct Object;
196    impl<'de> Deserialize<'de> for Object {
197        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
198            struct V;
199            impl<'de> Visitor<'de> for V {
200                type Value = Object;
201                fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202                    f.write_str("an object of strings")
203                }
204                fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Object, A::Error> {
205                    while map.next_entry::<AnyString, AnyString>()?.is_some() {}
206                    Ok(Object)
207                }
208            }
209            deserializer.deserialize_map(V)
210        }
211    }
212
213    serde_json::from_slice::<Object>(json).is_ok()
214}
215
216/// Every registered language, and whether missing languages and keys are
217/// errors.
218///
219/// PHP: the static state of `Locale`.
220#[derive(Debug, Clone)]
221pub struct Languages {
222    languages: IndexMap<String, Language, Hasher>,
223    exceptions: bool,
224    /// The translation files registered so far, by their text, so names
225    /// registered from the same file share it and its decoding.
226    files: HashMap<Arc<[u8]>, Arc<Json>, Hasher>,
227}
228
229impl PartialEq for Languages {
230    /// Equal when they hold the same languages, in the same order, with the
231    /// same translations, and the same exceptions setting.
232    fn eq(&self, other: &Self) -> bool {
233        self.exceptions == other.exceptions && self.languages == other.languages
234    }
235}
236
237impl Default for Languages {
238    /// No languages, with exceptions on; the same as [`Languages::new`].
239    fn default() -> Self {
240        Self::new()
241    }
242}
243
244impl Languages {
245    /// No languages, with exceptions on.
246    ///
247    /// PHP: exceptions are on by default, as in PHP.
248    pub fn new() -> Self {
249        Self { languages: IndexMap::default(), exceptions: true, files: HashMap::default() }
250    }
251
252    /// Whether an unknown language or a missing key or file is an error.
253    ///
254    /// PHP: `Locale::$exceptions`.
255    pub fn exceptions(&self) -> bool {
256        self.exceptions
257    }
258
259    /// Turns errors for unknown languages and missing keys or files on or
260    /// off.
261    ///
262    /// PHP: `Locale::$exceptions = $on`.
263    pub fn set_exceptions(&mut self, on: bool) {
264        self.exceptions = on;
265    }
266
267    /// The names of the registered languages, in registration order.
268    ///
269    /// PHP: `Locale::getLanguages()`.
270    pub fn names(&self) -> impl Iterator<Item = &str> {
271        self.languages.keys().map(String::as_str)
272    }
273
274    /// Whether a language is registered (usable or not).
275    pub fn contains(&self, name: &str) -> bool {
276        self.languages.contains_key(name)
277    }
278
279    /// Registers or replaces a language; a replaced one keeps its position.
280    ///
281    /// PHP: `Locale::setLanguageFromArray($name, $translations)`.
282    pub fn insert(&mut self, name: impl Into<String>, translations: Translations) {
283        self.languages.insert(name.into(), Language::Texts(translations));
284    }
285
286    /// Registers a language from a JSON translation file.
287    ///
288    /// With exceptions on, a path that does not exist fails with
289    /// `Translation file not found.`. Otherwise an unreadable file registers
290    /// a language that holds no translations, as does content that is not a
291    /// JSON object or list (see [`Languages::insert_json`]).
292    ///
293    /// PHP: `Locale::setLanguageFromJSON($name, $path)`.
294    pub fn load(&mut self, name: impl Into<String>, path: &Path) -> Result<(), Error> {
295        if self.exceptions && std::fs::metadata(path).is_err() {
296            return Err(Error::Exception("Translation file not found.".into()));
297        }
298        let content = std::fs::read(path).unwrap_or_default();
299        self.insert_json(name, &content)
300    }
301
302    /// Registers a language from JSON text: the decoding half of
303    /// [`Languages::load`].
304    ///
305    /// A JSON object of strings, as every translation file is, is kept as its
306    /// text and decoded on the language's first lookup, once per distinct text:
307    /// names registered from the same file share it. Anything else is decoded
308    /// now, so its errors are returned here as before.
309    ///
310    /// Invalid JSON and scalars register a language that holds no
311    /// translations, so lookups in it fail with [`Error::Type`]. An object or
312    /// list must hold strings only ([`Error::Unsupported`] otherwise); a list
313    /// is keyed by position.
314    ///
315    /// PHP: reads `json` the way `json_decode($json, true)` does.
316    pub fn insert_json(&mut self, name: impl Into<String>, json: &[u8]) -> Result<(), Error> {
317        // A JSON object of strings, as every translation file is, is kept as its
318        // text and decoded straight into the map on first use, once per distinct
319        // file; anything else takes PHP's decoder now.
320        if is_object_of_strings(json) {
321            let file = match self.files.get(json) {
322                Some(file) => Arc::clone(file),
323                None => {
324                    let text: Arc<[u8]> = json.into();
325                    let file = Arc::new(Json { text: Arc::clone(&text), texts: OnceLock::new() });
326                    self.files.insert(text, Arc::clone(&file));
327                    file
328                }
329            };
330            self.languages.insert(name.into(), Language::Json(file));
331            return Ok(());
332        }
333        let language = match json::decode(json, Some(true), 512, Flags::NONE) {
334            Err(_) | Ok(Value::Null) => Language::Unusable("null"),
335            Ok(Value::Bool(true)) => Language::Unusable("true"),
336            Ok(Value::Bool(false)) => Language::Unusable("false"),
337            Ok(Value::Int(_)) => Language::Unusable("int"),
338            Ok(Value::Float(_)) => Language::Unusable("float"),
339            Ok(Value::Str(_)) => Language::Unusable("string"),
340            Ok(Value::Object(_)) => Language::Texts(Translations::default()),
341            Ok(Value::Array(array)) => {
342                let mut texts = Translations::with_capacity_and_hasher(array.len(), Hasher::default());
343                for (key, value) in array.iter() {
344                    let key = match key {
345                        KeyRef::Int(i) => i.to_string(),
346                        KeyRef::Str(s) => String::from_utf8_lossy(s).into_owned(),
347                    };
348                    let Value::Str(text) = value else {
349                        return Err(Error::Unsupported(format!("Translation \"{key}\" is not a string.")));
350                    };
351                    texts.insert(key, String::from_utf8_lossy(text).into_owned());
352                }
353                Language::Texts(texts)
354            }
355            Ok(Value::Ext(never)) => match never {},
356        };
357        self.languages.insert(name.into(), language);
358        Ok(())
359    }
360
361    fn check(&self, name: &str) -> Result<(), Error> {
362        if self.exceptions && !self.languages.contains_key(name) {
363            return Err(Error::Exception("Locale not found".into()));
364        }
365        Ok(())
366    }
367
368    /// The language a lookup reads, or the type error PHP's
369    /// `array_key_exists()` raises on what it finds instead.
370    fn lookup(&self, name: &str) -> Result<&Translations, Error> {
371        match self.languages.get(name).map(Language::resolve) {
372            Some(Ok(t)) => Ok(t),
373            Some(Err(given)) => Err(key_exists_error(given)),
374            None => Err(key_exists_error("null")),
375        }
376    }
377}
378
379fn key_exists_error(given: &str) -> Error {
380    Error::Type(format!("array_key_exists(): Argument #2 ($array) must be of type array, {given} given"))
381}
382
383/// A view of [`Languages`] with a default and an optional fallback language.
384#[derive(Debug, Clone)]
385pub struct Locale<'a> {
386    languages: &'a Languages,
387    default: Cow<'a, str>,
388    fallback: Option<Cow<'a, str>>,
389}
390
391impl<'a> Locale<'a> {
392    /// A locale reading the `default` language, with no fallback.
393    ///
394    /// Fails with `Locale not found` for an unknown language while
395    /// exceptions are on.
396    ///
397    /// PHP: `new Locale($default)`.
398    pub fn new(languages: &'a Languages, default: &'a str) -> Result<Self, Error> {
399        languages.check(default)?;
400        Ok(Self { languages, default: Cow::Borrowed(default), fallback: None })
401    }
402
403    /// A locale with this default and fallback language, without checking
404    /// that they are registered.
405    ///
406    /// PHP: assigning the public `$default` and `$fallback` properties.
407    pub fn with(
408        languages: &'a Languages,
409        default: impl Into<Cow<'a, str>>,
410        fallback: Option<impl Into<Cow<'a, str>>>,
411    ) -> Self {
412        Self { languages, default: default.into(), fallback: fallback.map(Into::into) }
413    }
414
415    /// The name of the language texts are read from first.
416    ///
417    /// PHP: `$locale->default`.
418    pub fn default(&self) -> &str {
419        &self.default
420    }
421
422    /// The name of the language read for keys the default one lacks.
423    ///
424    /// PHP: `$locale->fallback`.
425    pub fn fallback(&self) -> Option<&str> {
426        self.fallback.as_deref()
427    }
428
429    /// Switches the default language.
430    ///
431    /// Fails with `Locale not found` for an unknown language while
432    /// exceptions are on.
433    ///
434    /// PHP: `$locale->setDefault($name)`.
435    pub fn set_default(&mut self, name: &str) -> Result<&mut Self, Error> {
436        self.languages.check(name)?;
437        self.default = Cow::Owned(name.to_owned());
438        Ok(self)
439    }
440
441    /// Sets the language read for keys the default one lacks.
442    ///
443    /// Fails with `Locale not found` for an unknown language while
444    /// exceptions are on.
445    ///
446    /// PHP: `$locale->setFallback($name)`.
447    pub fn set_fallback(&mut self, name: &str) -> Result<&mut Self, Error> {
448        self.languages.check(name)?;
449        self.fallback = Some(Cow::Owned(name.to_owned()));
450        Ok(self)
451    }
452
453    /// The translation of `key`, with its placeholders filled in.
454    ///
455    /// The default language's text, else the fallback's, else `missing`;
456    /// an empty text counts as missing (with exceptions on, a key neither
457    /// has fails with
458    /// `Key named "<key>" not found`). Each `{{name}}` of `placeholders` is
459    /// then replaced in turn, so a value can itself hold a later
460    /// placeholder. `Ok(None)` only for [`Missing::Null`].
461    ///
462    /// Without a fallback, the language named `""` serves as the fallback.
463    ///
464    /// PHP: `$locale->getText($key, $default, $placeholders)`. PHP reads the
465    /// language named `""` without a fallback, and so does this.
466    pub fn text<'s>(
467        &'s self,
468        key: &str,
469        missing: Missing<'s>,
470        placeholders: &[(&str, &str)],
471    ) -> Result<Option<Cow<'s, str>>, Error> {
472        self.text_with(key, missing, placeholders.iter().copied())
473    }
474
475    /// [`Locale::text`], with the placeholders as any sequence of name and value pairs.
476    pub fn text_with<'s, N: AsRef<str>, V: AsRef<str>>(
477        &'s self,
478        key: &str,
479        missing: Missing<'s>,
480        placeholders: impl IntoIterator<Item = (N, V)>,
481    ) -> Result<Option<Cow<'s, str>>, Error> {
482        let default = self.languages.lookup(&self.default)?.get(key);
483        let fallback = match self.languages.languages.get(self.fallback.as_deref().unwrap_or("")).map(Language::resolve)
484        {
485            None | Some(Err("null")) => None,
486            Some(Err(given)) => return Err(key_exists_error(given)),
487            Some(Ok(t)) => t.get(key),
488        };
489        // An empty text counts as missing, so the next source is used.
490        let usable = |text: Option<&'s String>| text.filter(|text| !text.is_empty());
491        let text = match (usable(default), usable(fallback)) {
492            (Some(text), _) | (None, Some(text)) => Some(Cow::Borrowed(text.as_str())),
493            _ if default.is_none() && fallback.is_none() && self.languages.exceptions => {
494                return Err(Error::Exception(format!("Key named \"{key}\" not found")));
495            }
496            _ => match missing {
497                Missing::Key | Missing::Text(DEFAULT_DYNAMIC_KEY) => Some(Cow::Owned(format!("{{{{{key}}}}}"))),
498                Missing::Text(text) => Some(Cow::Borrowed(text)),
499                Missing::Null => None,
500            },
501        };
502        Ok(text.map(|text| replace_placeholders(text, placeholders)))
503    }
504
505    /// Every text of the default language.
506    ///
507    /// Fails with [`Error::Type`] when the default language is unknown or
508    /// holds no translations.
509    ///
510    /// PHP: `$locale->getTranslations()`.
511    pub fn translations(&self) -> Result<&'a Translations, Error> {
512        match self.languages.languages.get(self.default.as_ref()).map(Language::resolve) {
513            Some(Ok(t)) => Ok(t),
514            Some(Err(given)) => Err(returned_error(given)),
515            None => Err(returned_error("null")),
516        }
517    }
518}
519
520/// `str_replace("{{name}}", $value, $text)` for each placeholder in turn
521/// (a later placeholder also replaces what an earlier value brought in).
522///
523/// Each pass writes into a spare buffer only when the text holds the
524/// placeholder, and the two buffers swap, so a text with any number of
525/// placeholders costs at most two allocations. Placeholders are found in
526/// place, without building the `{{name}}` string.
527fn replace_placeholders<'s, N: AsRef<str>, V: AsRef<str>>(
528    mut text: Cow<'s, str>,
529    placeholders: impl IntoIterator<Item = (N, V)>,
530) -> Cow<'s, str> {
531    let mut spare = String::new();
532    for (name, value) in placeholders {
533        let (name, value) = (name.as_ref(), value.as_ref());
534        let width = name.len() + 4;
535        let (mut copied, mut from) = (0, 0);
536        let mut out = std::mem::take(&mut spare);
537        out.clear();
538        let bytes = text.as_bytes();
539        while let Some(found) = bytes[from..].windows(2).position(|pair| pair == b"{{") {
540            let at = from + found;
541            let rest = &text[at + 2..];
542            if rest.starts_with(name) && rest[name.len()..].starts_with("}}") {
543                // Leftmost, non-overlapping matches, as `str_replace` takes them.
544                if copied == 0 {
545                    out.reserve(text.len() + value.len());
546                }
547                out.push_str(&text[copied..at]);
548                out.push_str(value);
549                copied = at + width;
550                from = copied;
551            } else {
552                from = at + 1;
553            }
554        }
555        if copied == 0 {
556            spare = out;
557            continue;
558        }
559        out.push_str(&text[copied..]);
560        spare = match std::mem::replace(&mut text, Cow::Owned(out)) {
561            Cow::Owned(previous) => previous,
562            Cow::Borrowed(_) => String::new(),
563        };
564    }
565    text
566}
567
568fn returned_error(given: &str) -> Error {
569    Error::Type(format!(
570        "Utopia\\Locale\\Locale::getTranslations(): Return value must be of type array, {given} returned"
571    ))
572}
573
574#[cfg(test)]
575mod tests {
576    use super::*;
577
578    /// PHP's loop: `str_replace('{{'.$name.'}}', $value, $text)` per placeholder.
579    fn str_replaced(text: &str, placeholders: &[(&str, &str)]) -> String {
580        let mut text = text.as_bytes().to_vec();
581        for (name, value) in placeholders {
582            let search = format!("{{{{{name}}}}}");
583            text = php_std::string::str_replace(search.as_bytes(), value.as_bytes(), &text).0.into_owned();
584        }
585        String::from_utf8(text).unwrap()
586    }
587
588    #[test]
589    fn placeholders_replace_like_str_replace() {
590        const PIECES: [&str; 12] = ["{{", "}}", "{", "}", "a", "b", "{{a}}", "{{b}}", "é", "{{{a}}}", "", "{{}}"];
591        let mut seed = 0x9e37_79b9_7f4a_7c15_u64;
592        let mut next = |n: usize| {
593            seed ^= seed << 13;
594            seed ^= seed >> 7;
595            seed ^= seed << 17;
596            (seed % n as u64) as usize
597        };
598        for _ in 0..20_000 {
599            let mut pick = |n: usize| (0..n).map(|_| PIECES[next(PIECES.len())]).collect::<String>();
600            let text = pick(6);
601            let (n1, v1, n2, v2) = (pick(1), pick(2), pick(1), pick(2));
602            let placeholders = [(n1.as_str(), v1.as_str()), (n2.as_str(), v2.as_str())];
603            assert_eq!(
604                replace_placeholders(Cow::Borrowed(&text), placeholders),
605                str_replaced(&text, &placeholders),
606                "{text:?} {placeholders:?}"
607            );
608        }
609    }
610
611    fn languages() -> Languages {
612        let mut l = Languages::new();
613        l.insert(
614            "en-US",
615            Translations::from_iter([
616                ("hello".to_owned(), "Hello".to_owned()),
617                ("world".to_owned(), "World".to_owned()),
618                ("helloPlaceholder".to_owned(), "Hello {{name}} {{surname}}!".to_owned()),
619            ]),
620        );
621        l.insert("he-IL", Translations::from_iter([("hello".to_owned(), "שלום".to_owned())]));
622        l
623    }
624
625    #[test]
626    fn texts_and_fallbacks() {
627        let mut l = languages();
628        l.set_exceptions(false);
629        let mut locale = Locale::new(&l, "he-IL").unwrap();
630        assert_eq!(locale.text("world", Missing::Key, &[]).unwrap().as_deref(), Some("{{world}}"));
631        locale.set_fallback("en-US").unwrap();
632        assert_eq!(locale.text("world", Missing::Key, &[]).unwrap().as_deref(), Some("World"));
633        assert_eq!(locale.text("missing", Missing::Null, &[]).unwrap(), None);
634        locale.set_default("en-US").unwrap();
635        let text = locale.text("helloPlaceholder", Missing::Key, &[("name", "{{surname}}"), ("surname", "B")]).unwrap();
636        assert_eq!(text.as_deref(), Some("Hello B B!"));
637    }
638
639    #[test]
640    fn errors_like_php() {
641        let l = languages();
642        assert_eq!(Locale::new(&l, "xx").unwrap_err(), Error::Exception("Locale not found".into()));
643        let locale = Locale::new(&l, "he-IL").unwrap();
644        assert_eq!(locale.text("world", Missing::Key, &[]).unwrap_err().to_string(), "Key named \"world\" not found");
645        let mut l = Languages::new();
646        l.insert_json("bad", b"{").unwrap();
647        l.insert_json("num", b"5").unwrap();
648        let bad = Locale::new(&l, "bad").unwrap();
649        assert_eq!(bad.text("a", Missing::Key, &[]).unwrap_err().php_class(), "TypeError");
650        assert!(bad.translations().unwrap_err().to_string().ends_with("null returned"));
651        let num = Locale::with(&l, "num", None::<&str>);
652        assert!(num.text("a", Missing::Key, &[]).unwrap_err().to_string().ends_with("int given"));
653    }
654
655    /// The check that keeps a file as JSON accepts exactly what decoding it
656    /// straight into the map accepts, so nothing moves between the lazy path and
657    /// PHP's decoder.
658    #[test]
659    fn object_of_strings_check_matches_the_decoder() {
660        let inputs: &[&[u8]] = &[
661            br#"{"a":"b"}"#,
662            br#"{}"#,
663            br#" {"a" : "b" } "#,
664            br#"{"a":"b","a":"c"}"#,
665            br#"{"a":1}"#,
666            br#"{"a":null}"#,
667            br#"{"a":["b"]}"#,
668            br#"{"a":{"b":"c"}}"#,
669            br#"{"\u00e9":"\u00e9\n"}"#,
670            br#"{"a":"\ud800"}"#,
671            br#"{"a":"b"} x"#,
672            br#"{"a":"b""#,
673            br#"[]"#,
674            br#"["a"]"#,
675            br#""a""#,
676            b"null",
677            b"1",
678            b"",
679            b"\xff",
680        ];
681        for input in inputs {
682            assert_eq!(
683                is_object_of_strings(input),
684                serde_json::from_slice::<Translations>(input).is_ok(),
685                "{}",
686                String::from_utf8_lossy(input)
687            );
688        }
689    }
690
691    /// Names registered from the same file share its text and decode it once, on
692    /// first use, to what decoding it at once gives.
693    #[test]
694    fn json_files_are_shared_and_decoded_on_first_use() {
695        let json = br#"{"hello":"Hello","bye":"Bye"}"#;
696        let mut lazy = Languages::new();
697        lazy.insert_json("en", json).unwrap();
698        lazy.insert_json("en-us", json).unwrap();
699        lazy.insert_json("fr", br#"{"hello":"Bonjour"}"#).unwrap();
700        assert_eq!(lazy.files.len(), 2);
701        let (Some(Language::Json(en)), Some(Language::Json(en_us))) =
702            (lazy.languages.get("en"), lazy.languages.get("en-us"))
703        else {
704            panic!("a JSON object of strings is kept as its text");
705        };
706        assert!(Arc::ptr_eq(en, en_us));
707        assert!(en.texts.get().is_none(), "nothing is decoded before a lookup");
708
709        let locale = Locale::new(&lazy, "en-us").unwrap();
710        assert_eq!(locale.text("hello", Missing::Null, &[]).unwrap().as_deref(), Some("Hello"));
711        assert!(en.texts.get().is_some() && Arc::ptr_eq(en, en_us), "decoded once, for both names");
712
713        let mut eager = Languages::new();
714        for (name, texts) in [("en", json.as_slice()), ("en-us", json), ("fr", br#"{"hello":"Bonjour"}"#)] {
715            eager.insert(name, serde_json::from_slice(texts).unwrap());
716        }
717        assert_eq!(lazy, eager);
718    }
719}