utopia-locale 0.1.0

Translations: languages, default and fallback locales, and placeholders.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
//! Translate text into the user's language, with a fallback language and
//! `{{placeholder}}` substitution.
//!
//! Register every language once in a [`Languages`] value, from maps or JSON
//! files, then create a [`Locale`] per request that borrows it and looks up
//! texts with [`Locale::text`]. Whether a missing language or key is an
//! error is a setting of the [`Languages`].
//!
//! PHP: ports `utopia-php/locale`. PHP keeps every language, and whether
//! missing keys throw, in static state shared by all `Locale` objects; here
//! that state is the [`Languages`] value.
//!
//! | PHP | Rust |
//! |---|---|
//! | `Locale::$language` (static) | [`Languages`] |
//! | `Locale::$exceptions` (static) | [`Languages::set_exceptions`], [`Languages::exceptions`] |
//! | `Locale::setLanguageFromArray($name, $translations)` | [`Languages::insert`] |
//! | `Locale::setLanguageFromJSON($name, $path)` | [`Languages::load`] (reading) and [`Languages::insert_json`] (decoding) |
//! | `Locale::getLanguages()` | [`Languages::names`] |
//! | `new Locale($default)` | [`Locale::new`] |
//! | `$locale->setDefault($name)`, `setFallback($name)` | [`Locale::set_default`], [`Locale::set_fallback`] |
//! | `public $default`, `public $fallback` | [`Locale::default`], [`Locale::fallback`]; assigned unchecked with [`Locale::with`] |
//! | `$locale->getText($key, $default, $placeholders)` | [`Locale::text`], `$default` as [`Missing`] |
//! | `Locale::DEFAULT_DYNAMIC_KEY` | [`DEFAULT_DYNAMIC_KEY`] |
//! | `$locale->getTranslations()` | [`Locale::translations`] |
//! | `\Exception`, `\TypeError` | [`Error::Exception`], [`Error::Type`] |
//!
//! PHP: translations are strings. PHP stores whatever `json_decode` returns for a
//! translation file; a file that is not JSON (or is unreadable) becomes a
//! language PHP cannot use, and so it is here: lookups in it fail with the
//! same `TypeError` (see [`Error::Type`]). A file whose values are not all
//! strings is refused ([`Error::Unsupported`]), a recorded deviation.

#![warn(missing_docs)]

use std::borrow::Cow;
use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, OnceLock};

use indexmap::IndexMap;
use php_std::Value;
use php_std::json::{self, Flags};
use php_std::types::KeyRef;

/// The getting started guide (`guide.md`), compiled and run with the doctests.
#[cfg(doctest)]
#[doc = include_str!("../guide.md")]
pub struct GettingStarted;

/// A marker text that, passed as [`Missing::Text`], means [`Missing::Key`].
///
/// PHP: `Locale::DEFAULT_DYNAMIC_KEY`.
pub const DEFAULT_DYNAMIC_KEY: &str = "[[defaultDynamicKey]]";

/// The hasher of every map here: keys are looked up on each text read, and
/// foldhash is several times faster than SipHash on them.
type Hasher = foldhash::fast::RandomState;

/// Translations of one language, in file order.
pub type Translations = IndexMap<String, String, Hasher>;

/// Why a lookup or a language registration failed.
///
/// PHP: each variant matches the exception class PHP throws, given by
/// [`Error::php_class`].
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Error {
    /// An unknown language, a missing translation file or a missing key,
    /// reported only while [`Languages::exceptions`] is on.
    ///
    /// PHP: `\Exception`.
    #[error("{0}")]
    Exception(String),
    /// A lookup in a language that holds no translations: one loaded from
    /// an unreadable or invalid file or from a JSON scalar, or an unknown
    /// default language while exceptions are off.
    ///
    /// PHP: `\TypeError`, raised on a language PHP stored as something
    /// other than an array.
    #[error("{0}")]
    Type(String),
    /// A translation file whose values are not all strings.
    ///
    /// PHP stores such a file and returns the non-string values; Rust
    /// refuses it (a deviation).
    #[error("{0}")]
    Unsupported(String),
}

impl Error {
    /// The name of the exception class this error matches: `Exception` or
    /// `TypeError`.
    ///
    /// PHP: the class of the exception `utopia-php/locale` throws for the
    /// same call.
    pub fn php_class(&self) -> &'static str {
        match self {
            Error::Exception(_) | Error::Unsupported(_) => "Exception",
            Error::Type(_) => "TypeError",
        }
    }
}

/// What [`Locale::text`] returns for a key no language has.
///
/// PHP: the `$default` argument of `getText()`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Missing<'a> {
    /// The key in double braces, `{{key}}`.
    ///
    /// PHP: the default, [`DEFAULT_DYNAMIC_KEY`].
    #[default]
    Key,
    /// This text.
    Text(&'a str),
    /// Nothing (`null`).
    Null,
}

/// A registered language.
#[derive(Debug, Clone)]
enum Language {
    Texts(Translations),
    /// A translation file that is a JSON object of strings, kept as its text and
    /// decoded on first use, then shared by every name registered from the same
    /// text.
    Json(Arc<Json>),
    /// What PHP holds instead of an array, by the name its type errors use
    /// (`null`, `true`, `false`, `int`, `float`, `string`).
    Unusable(&'static str),
}

impl PartialEq for Language {
    fn eq(&self, other: &Self) -> bool {
        match (self.resolve(), other.resolve()) {
            (Ok(a), Ok(b)) => a == b,
            (Err(a), Err(b)) => a == b,
            _ => false,
        }
    }
}

impl Language {
    /// The translations, or the name of what PHP holds instead of an array.
    fn resolve(&self) -> Result<&Translations, &'static str> {
        match self {
            Language::Texts(texts) => Ok(texts),
            Language::Json(json) => Ok(json.texts()),
            Language::Unusable(given) => Err(given),
        }
    }
}

/// The text of a translation file that is a JSON object of strings, checked when
/// it was registered and decoded on first use. Most registered languages are
/// never read in a given process, so this keeps them as their JSON text.
#[derive(Debug)]
struct Json {
    text: Arc<[u8]>,
    texts: OnceLock<Translations>,
}

impl Json {
    fn texts(&self) -> &Translations {
        self.texts.get_or_init(|| {
            serde_json::from_slice(&self.text).expect("checked to be a JSON object of strings when it was registered")
        })
    }
}

/// Whether `json` is a JSON object whose values are all strings: what
/// `serde_json::from_slice::<Translations>` accepts, checked without building
/// anything.
fn is_object_of_strings(json: &[u8]) -> bool {
    use serde::de::{self, Deserialize, Deserializer, MapAccess, Visitor};

    struct AnyString;
    impl<'de> Deserialize<'de> for AnyString {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            struct V;
            impl Visitor<'_> for V {
                type Value = AnyString;
                fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    f.write_str("a string")
                }
                fn visit_str<E: de::Error>(self, _: &str) -> Result<AnyString, E> {
                    Ok(AnyString)
                }
            }
            deserializer.deserialize_string(V)
        }
    }

    struct Object;
    impl<'de> Deserialize<'de> for Object {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            struct V;
            impl<'de> Visitor<'de> for V {
                type Value = Object;
                fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    f.write_str("an object of strings")
                }
                fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Object, A::Error> {
                    while map.next_entry::<AnyString, AnyString>()?.is_some() {}
                    Ok(Object)
                }
            }
            deserializer.deserialize_map(V)
        }
    }

    serde_json::from_slice::<Object>(json).is_ok()
}

/// Every registered language, and whether missing languages and keys are
/// errors.
///
/// PHP: the static state of `Locale`.
#[derive(Debug, Clone)]
pub struct Languages {
    languages: IndexMap<String, Language, Hasher>,
    exceptions: bool,
    /// The translation files registered so far, by their text, so names
    /// registered from the same file share it and its decoding.
    files: HashMap<Arc<[u8]>, Arc<Json>, Hasher>,
}

impl PartialEq for Languages {
    /// Equal when they hold the same languages, in the same order, with the
    /// same translations, and the same exceptions setting.
    fn eq(&self, other: &Self) -> bool {
        self.exceptions == other.exceptions && self.languages == other.languages
    }
}

impl Default for Languages {
    /// No languages, with exceptions on; the same as [`Languages::new`].
    fn default() -> Self {
        Self::new()
    }
}

impl Languages {
    /// No languages, with exceptions on.
    ///
    /// PHP: exceptions are on by default, as in PHP.
    pub fn new() -> Self {
        Self { languages: IndexMap::default(), exceptions: true, files: HashMap::default() }
    }

    /// Whether an unknown language or a missing key or file is an error.
    ///
    /// PHP: `Locale::$exceptions`.
    pub fn exceptions(&self) -> bool {
        self.exceptions
    }

    /// Turns errors for unknown languages and missing keys or files on or
    /// off.
    ///
    /// PHP: `Locale::$exceptions = $on`.
    pub fn set_exceptions(&mut self, on: bool) {
        self.exceptions = on;
    }

    /// The names of the registered languages, in registration order.
    ///
    /// PHP: `Locale::getLanguages()`.
    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.languages.keys().map(String::as_str)
    }

    /// Whether a language is registered (usable or not).
    pub fn contains(&self, name: &str) -> bool {
        self.languages.contains_key(name)
    }

    /// Registers or replaces a language; a replaced one keeps its position.
    ///
    /// PHP: `Locale::setLanguageFromArray($name, $translations)`.
    pub fn insert(&mut self, name: impl Into<String>, translations: Translations) {
        self.languages.insert(name.into(), Language::Texts(translations));
    }

    /// Registers a language from a JSON translation file.
    ///
    /// With exceptions on, a path that does not exist fails with
    /// `Translation file not found.`. Otherwise an unreadable file registers
    /// a language that holds no translations, as does content that is not a
    /// JSON object or list (see [`Languages::insert_json`]).
    ///
    /// PHP: `Locale::setLanguageFromJSON($name, $path)`.
    pub fn load(&mut self, name: impl Into<String>, path: &Path) -> Result<(), Error> {
        if self.exceptions && std::fs::metadata(path).is_err() {
            return Err(Error::Exception("Translation file not found.".into()));
        }
        let content = std::fs::read(path).unwrap_or_default();
        self.insert_json(name, &content)
    }

    /// Registers a language from JSON text: the decoding half of
    /// [`Languages::load`].
    ///
    /// A JSON object of strings, as every translation file is, is kept as its
    /// text and decoded on the language's first lookup, once per distinct text:
    /// names registered from the same file share it. Anything else is decoded
    /// now, so its errors are returned here as before.
    ///
    /// Invalid JSON and scalars register a language that holds no
    /// translations, so lookups in it fail with [`Error::Type`]. An object or
    /// list must hold strings only ([`Error::Unsupported`] otherwise); a list
    /// is keyed by position.
    ///
    /// PHP: reads `json` the way `json_decode($json, true)` does.
    pub fn insert_json(&mut self, name: impl Into<String>, json: &[u8]) -> Result<(), Error> {
        // A JSON object of strings, as every translation file is, is kept as its
        // text and decoded straight into the map on first use, once per distinct
        // file; anything else takes PHP's decoder now.
        if is_object_of_strings(json) {
            let file = match self.files.get(json) {
                Some(file) => Arc::clone(file),
                None => {
                    let text: Arc<[u8]> = json.into();
                    let file = Arc::new(Json { text: Arc::clone(&text), texts: OnceLock::new() });
                    self.files.insert(text, Arc::clone(&file));
                    file
                }
            };
            self.languages.insert(name.into(), Language::Json(file));
            return Ok(());
        }
        let language = match json::decode(json, Some(true), 512, Flags::NONE) {
            Err(_) | Ok(Value::Null) => Language::Unusable("null"),
            Ok(Value::Bool(true)) => Language::Unusable("true"),
            Ok(Value::Bool(false)) => Language::Unusable("false"),
            Ok(Value::Int(_)) => Language::Unusable("int"),
            Ok(Value::Float(_)) => Language::Unusable("float"),
            Ok(Value::Str(_)) => Language::Unusable("string"),
            Ok(Value::Object(_)) => Language::Texts(Translations::default()),
            Ok(Value::Array(array)) => {
                let mut texts = Translations::with_capacity_and_hasher(array.len(), Hasher::default());
                for (key, value) in array.iter() {
                    let key = match key {
                        KeyRef::Int(i) => i.to_string(),
                        KeyRef::Str(s) => String::from_utf8_lossy(s).into_owned(),
                    };
                    let Value::Str(text) = value else {
                        return Err(Error::Unsupported(format!("Translation \"{key}\" is not a string.")));
                    };
                    texts.insert(key, String::from_utf8_lossy(text).into_owned());
                }
                Language::Texts(texts)
            }
            Ok(Value::Ext(never)) => match never {},
        };
        self.languages.insert(name.into(), language);
        Ok(())
    }

    fn check(&self, name: &str) -> Result<(), Error> {
        if self.exceptions && !self.languages.contains_key(name) {
            return Err(Error::Exception("Locale not found".into()));
        }
        Ok(())
    }

    /// The language a lookup reads, or the type error PHP's
    /// `array_key_exists()` raises on what it finds instead.
    fn lookup(&self, name: &str) -> Result<&Translations, Error> {
        match self.languages.get(name).map(Language::resolve) {
            Some(Ok(t)) => Ok(t),
            Some(Err(given)) => Err(key_exists_error(given)),
            None => Err(key_exists_error("null")),
        }
    }
}

fn key_exists_error(given: &str) -> Error {
    Error::Type(format!("array_key_exists(): Argument #2 ($array) must be of type array, {given} given"))
}

/// A view of [`Languages`] with a default and an optional fallback language.
#[derive(Debug, Clone)]
pub struct Locale<'a> {
    languages: &'a Languages,
    default: Cow<'a, str>,
    fallback: Option<Cow<'a, str>>,
}

impl<'a> Locale<'a> {
    /// A locale reading the `default` language, with no fallback.
    ///
    /// Fails with `Locale not found` for an unknown language while
    /// exceptions are on.
    ///
    /// PHP: `new Locale($default)`.
    pub fn new(languages: &'a Languages, default: &'a str) -> Result<Self, Error> {
        languages.check(default)?;
        Ok(Self { languages, default: Cow::Borrowed(default), fallback: None })
    }

    /// A locale with this default and fallback language, without checking
    /// that they are registered.
    ///
    /// PHP: assigning the public `$default` and `$fallback` properties.
    pub fn with(
        languages: &'a Languages,
        default: impl Into<Cow<'a, str>>,
        fallback: Option<impl Into<Cow<'a, str>>>,
    ) -> Self {
        Self { languages, default: default.into(), fallback: fallback.map(Into::into) }
    }

    /// The name of the language texts are read from first.
    ///
    /// PHP: `$locale->default`.
    pub fn default(&self) -> &str {
        &self.default
    }

    /// The name of the language read for keys the default one lacks.
    ///
    /// PHP: `$locale->fallback`.
    pub fn fallback(&self) -> Option<&str> {
        self.fallback.as_deref()
    }

    /// Switches the default language.
    ///
    /// Fails with `Locale not found` for an unknown language while
    /// exceptions are on.
    ///
    /// PHP: `$locale->setDefault($name)`.
    pub fn set_default(&mut self, name: &str) -> Result<&mut Self, Error> {
        self.languages.check(name)?;
        self.default = Cow::Owned(name.to_owned());
        Ok(self)
    }

    /// Sets the language read for keys the default one lacks.
    ///
    /// Fails with `Locale not found` for an unknown language while
    /// exceptions are on.
    ///
    /// PHP: `$locale->setFallback($name)`.
    pub fn set_fallback(&mut self, name: &str) -> Result<&mut Self, Error> {
        self.languages.check(name)?;
        self.fallback = Some(Cow::Owned(name.to_owned()));
        Ok(self)
    }

    /// The translation of `key`, with its placeholders filled in.
    ///
    /// The default language's text, else the fallback's, else `missing`;
    /// an empty text counts as missing (with exceptions on, a key neither
    /// has fails with
    /// `Key named "<key>" not found`). Each `{{name}}` of `placeholders` is
    /// then replaced in turn, so a value can itself hold a later
    /// placeholder. `Ok(None)` only for [`Missing::Null`].
    ///
    /// Without a fallback, the language named `""` serves as the fallback.
    ///
    /// PHP: `$locale->getText($key, $default, $placeholders)`. PHP reads the
    /// language named `""` without a fallback, and so does this.
    pub fn text<'s>(
        &'s self,
        key: &str,
        missing: Missing<'s>,
        placeholders: &[(&str, &str)],
    ) -> Result<Option<Cow<'s, str>>, Error> {
        self.text_with(key, missing, placeholders.iter().copied())
    }

    /// [`Locale::text`], with the placeholders as any sequence of name and value pairs.
    pub fn text_with<'s, N: AsRef<str>, V: AsRef<str>>(
        &'s self,
        key: &str,
        missing: Missing<'s>,
        placeholders: impl IntoIterator<Item = (N, V)>,
    ) -> Result<Option<Cow<'s, str>>, Error> {
        let default = self.languages.lookup(&self.default)?.get(key);
        let fallback = match self.languages.languages.get(self.fallback.as_deref().unwrap_or("")).map(Language::resolve)
        {
            None | Some(Err("null")) => None,
            Some(Err(given)) => return Err(key_exists_error(given)),
            Some(Ok(t)) => t.get(key),
        };
        // An empty text counts as missing, so the next source is used.
        let usable = |text: Option<&'s String>| text.filter(|text| !text.is_empty());
        let text = match (usable(default), usable(fallback)) {
            (Some(text), _) | (None, Some(text)) => Some(Cow::Borrowed(text.as_str())),
            _ if default.is_none() && fallback.is_none() && self.languages.exceptions => {
                return Err(Error::Exception(format!("Key named \"{key}\" not found")));
            }
            _ => match missing {
                Missing::Key | Missing::Text(DEFAULT_DYNAMIC_KEY) => Some(Cow::Owned(format!("{{{{{key}}}}}"))),
                Missing::Text(text) => Some(Cow::Borrowed(text)),
                Missing::Null => None,
            },
        };
        Ok(text.map(|text| replace_placeholders(text, placeholders)))
    }

    /// Every text of the default language.
    ///
    /// Fails with [`Error::Type`] when the default language is unknown or
    /// holds no translations.
    ///
    /// PHP: `$locale->getTranslations()`.
    pub fn translations(&self) -> Result<&'a Translations, Error> {
        match self.languages.languages.get(self.default.as_ref()).map(Language::resolve) {
            Some(Ok(t)) => Ok(t),
            Some(Err(given)) => Err(returned_error(given)),
            None => Err(returned_error("null")),
        }
    }
}

/// `str_replace("{{name}}", $value, $text)` for each placeholder in turn
/// (a later placeholder also replaces what an earlier value brought in).
///
/// Each pass writes into a spare buffer only when the text holds the
/// placeholder, and the two buffers swap, so a text with any number of
/// placeholders costs at most two allocations. Placeholders are found in
/// place, without building the `{{name}}` string.
fn replace_placeholders<'s, N: AsRef<str>, V: AsRef<str>>(
    mut text: Cow<'s, str>,
    placeholders: impl IntoIterator<Item = (N, V)>,
) -> Cow<'s, str> {
    let mut spare = String::new();
    for (name, value) in placeholders {
        let (name, value) = (name.as_ref(), value.as_ref());
        let width = name.len() + 4;
        let (mut copied, mut from) = (0, 0);
        let mut out = std::mem::take(&mut spare);
        out.clear();
        let bytes = text.as_bytes();
        while let Some(found) = bytes[from..].windows(2).position(|pair| pair == b"{{") {
            let at = from + found;
            let rest = &text[at + 2..];
            if rest.starts_with(name) && rest[name.len()..].starts_with("}}") {
                // Leftmost, non-overlapping matches, as `str_replace` takes them.
                if copied == 0 {
                    out.reserve(text.len() + value.len());
                }
                out.push_str(&text[copied..at]);
                out.push_str(value);
                copied = at + width;
                from = copied;
            } else {
                from = at + 1;
            }
        }
        if copied == 0 {
            spare = out;
            continue;
        }
        out.push_str(&text[copied..]);
        spare = match std::mem::replace(&mut text, Cow::Owned(out)) {
            Cow::Owned(previous) => previous,
            Cow::Borrowed(_) => String::new(),
        };
    }
    text
}

fn returned_error(given: &str) -> Error {
    Error::Type(format!(
        "Utopia\\Locale\\Locale::getTranslations(): Return value must be of type array, {given} returned"
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// PHP's loop: `str_replace('{{'.$name.'}}', $value, $text)` per placeholder.
    fn str_replaced(text: &str, placeholders: &[(&str, &str)]) -> String {
        let mut text = text.as_bytes().to_vec();
        for (name, value) in placeholders {
            let search = format!("{{{{{name}}}}}");
            text = php_std::string::str_replace(search.as_bytes(), value.as_bytes(), &text).0.into_owned();
        }
        String::from_utf8(text).unwrap()
    }

    #[test]
    fn placeholders_replace_like_str_replace() {
        const PIECES: [&str; 12] = ["{{", "}}", "{", "}", "a", "b", "{{a}}", "{{b}}", "é", "{{{a}}}", "", "{{}}"];
        let mut seed = 0x9e37_79b9_7f4a_7c15_u64;
        let mut next = |n: usize| {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            (seed % n as u64) as usize
        };
        for _ in 0..20_000 {
            let mut pick = |n: usize| (0..n).map(|_| PIECES[next(PIECES.len())]).collect::<String>();
            let text = pick(6);
            let (n1, v1, n2, v2) = (pick(1), pick(2), pick(1), pick(2));
            let placeholders = [(n1.as_str(), v1.as_str()), (n2.as_str(), v2.as_str())];
            assert_eq!(
                replace_placeholders(Cow::Borrowed(&text), placeholders),
                str_replaced(&text, &placeholders),
                "{text:?} {placeholders:?}"
            );
        }
    }

    fn languages() -> Languages {
        let mut l = Languages::new();
        l.insert(
            "en-US",
            Translations::from_iter([
                ("hello".to_owned(), "Hello".to_owned()),
                ("world".to_owned(), "World".to_owned()),
                ("helloPlaceholder".to_owned(), "Hello {{name}} {{surname}}!".to_owned()),
            ]),
        );
        l.insert("he-IL", Translations::from_iter([("hello".to_owned(), "שלום".to_owned())]));
        l
    }

    #[test]
    fn texts_and_fallbacks() {
        let mut l = languages();
        l.set_exceptions(false);
        let mut locale = Locale::new(&l, "he-IL").unwrap();
        assert_eq!(locale.text("world", Missing::Key, &[]).unwrap().as_deref(), Some("{{world}}"));
        locale.set_fallback("en-US").unwrap();
        assert_eq!(locale.text("world", Missing::Key, &[]).unwrap().as_deref(), Some("World"));
        assert_eq!(locale.text("missing", Missing::Null, &[]).unwrap(), None);
        locale.set_default("en-US").unwrap();
        let text = locale.text("helloPlaceholder", Missing::Key, &[("name", "{{surname}}"), ("surname", "B")]).unwrap();
        assert_eq!(text.as_deref(), Some("Hello B B!"));
    }

    #[test]
    fn errors_like_php() {
        let l = languages();
        assert_eq!(Locale::new(&l, "xx").unwrap_err(), Error::Exception("Locale not found".into()));
        let locale = Locale::new(&l, "he-IL").unwrap();
        assert_eq!(locale.text("world", Missing::Key, &[]).unwrap_err().to_string(), "Key named \"world\" not found");
        let mut l = Languages::new();
        l.insert_json("bad", b"{").unwrap();
        l.insert_json("num", b"5").unwrap();
        let bad = Locale::new(&l, "bad").unwrap();
        assert_eq!(bad.text("a", Missing::Key, &[]).unwrap_err().php_class(), "TypeError");
        assert!(bad.translations().unwrap_err().to_string().ends_with("null returned"));
        let num = Locale::with(&l, "num", None::<&str>);
        assert!(num.text("a", Missing::Key, &[]).unwrap_err().to_string().ends_with("int given"));
    }

    /// The check that keeps a file as JSON accepts exactly what decoding it
    /// straight into the map accepts, so nothing moves between the lazy path and
    /// PHP's decoder.
    #[test]
    fn object_of_strings_check_matches_the_decoder() {
        let inputs: &[&[u8]] = &[
            br#"{"a":"b"}"#,
            br#"{}"#,
            br#" {"a" : "b" } "#,
            br#"{"a":"b","a":"c"}"#,
            br#"{"a":1}"#,
            br#"{"a":null}"#,
            br#"{"a":["b"]}"#,
            br#"{"a":{"b":"c"}}"#,
            br#"{"\u00e9":"\u00e9\n"}"#,
            br#"{"a":"\ud800"}"#,
            br#"{"a":"b"} x"#,
            br#"{"a":"b""#,
            br#"[]"#,
            br#"["a"]"#,
            br#""a""#,
            b"null",
            b"1",
            b"",
            b"\xff",
        ];
        for input in inputs {
            assert_eq!(
                is_object_of_strings(input),
                serde_json::from_slice::<Translations>(input).is_ok(),
                "{}",
                String::from_utf8_lossy(input)
            );
        }
    }

    /// Names registered from the same file share its text and decode it once, on
    /// first use, to what decoding it at once gives.
    #[test]
    fn json_files_are_shared_and_decoded_on_first_use() {
        let json = br#"{"hello":"Hello","bye":"Bye"}"#;
        let mut lazy = Languages::new();
        lazy.insert_json("en", json).unwrap();
        lazy.insert_json("en-us", json).unwrap();
        lazy.insert_json("fr", br#"{"hello":"Bonjour"}"#).unwrap();
        assert_eq!(lazy.files.len(), 2);
        let (Some(Language::Json(en)), Some(Language::Json(en_us))) =
            (lazy.languages.get("en"), lazy.languages.get("en-us"))
        else {
            panic!("a JSON object of strings is kept as its text");
        };
        assert!(Arc::ptr_eq(en, en_us));
        assert!(en.texts.get().is_none(), "nothing is decoded before a lookup");

        let locale = Locale::new(&lazy, "en-us").unwrap();
        assert_eq!(locale.text("hello", Missing::Null, &[]).unwrap().as_deref(), Some("Hello"));
        assert!(en.texts.get().is_some() && Arc::ptr_eq(en, en_us), "decoded once, for both names");

        let mut eager = Languages::new();
        for (name, texts) in [("en", json.as_slice()), ("en-us", json), ("fr", br#"{"hello":"Bonjour"}"#)] {
            eager.insert(name, serde_json::from_slice(texts).unwrap());
        }
        assert_eq!(lazy, eager);
    }
}