Skip to main content

i18n_next/
args.rs

1//! Parameters of `t_with` (DESIGN 2.2, spike S4): up to four live inline, so building
2//! them allocates nothing; a fifth and later go to a `Vec`. Lookup is a linear scan from
3//! the newest, which beats hashing for the real 1–4 parameters (spike S3).
4
5#[cfg(feature = "format")]
6use crate::json::push_js_number;
7use crate::json::{Out, push_u64, u64_len};
8use crate::plural::{Whole, shortest_whole};
9use crate::text::{Key, MAX_NESTING, Text};
10use std::borrow::Cow;
11use std::fmt;
12use std::sync::Arc;
13
14/// One parameter value, printed like JS `String(value)`.
15///
16/// A [`Text`] takes `Arg<'static>`: literals, owned strings (`String`, `&String` is
17/// copied), numbers, booleans, a `char`, and other `Text` / [`Key`] values, resolved when
18/// the outer text is shown; any other [`Display`](fmt::Display) value through
19/// [`Arg::display`]. [`Args`] also borrows (`Arg::Str`).
20#[derive(Debug, Clone)]
21#[non_exhaustive]
22pub enum Arg<'a> {
23    /// Text, inserted as is.
24    Str(&'a str),
25    /// Owned text, shared on clone: what a `String` becomes.
26    String(Arc<str>),
27    /// An integer: its decimal digits.
28    Int(i64),
29    /// A number as JS prints it: `1.5`, `1e+21`, `NaN`, `Infinity`, `-0` as `0`. With the
30    /// `format` feature: shortest float printing costs ~17 KB of `.wasm` (DESIGN 2.4).
31    #[cfg(feature = "format")]
32    Float(f64),
33    /// `true` / `false`.
34    Bool(bool),
35    /// `null`.
36    Null,
37    /// A translation inside a translation, resolved each time the outer one is shown.
38    Text(Box<Text>),
39    /// A number formatted when shown (JS `tn`), in the outer `Text`'s instance and locale
40    /// (in `t_with`: the nearest scope's, else the global instance's), with the named
41    /// `format` of that locale or the defaults. Feature `format`.
42    ///
43    /// ```
44    /// use i18n_next::{Arg, I18n};
45    ///
46    /// let i18n = I18n::builder().messages("de", None, r#"{"sum": "Summe: {n}"}"#).locale("de").build()?;
47    /// let n = Arg::Number { value: 1234.5.into(), format: None };
48    /// assert_eq!(i18n.text("sum").arg("n", n), "Summe: 1.234,5");
49    /// # Ok::<(), i18n_next::Error>(())
50    /// ```
51    #[cfg(feature = "format")]
52    Number {
53        /// The number.
54        value: crate::Number,
55        /// A named format ([`I18n::tn_as`](crate::I18n::tn_as)), else the defaults.
56        format: Option<Cow<'a, str>>,
57    },
58    /// A date (JS `td`) or a relative date (`tdr`) formatted when shown, like
59    /// [`Arg::Number`]: in the outer `Text`'s instance and locale, with a named format of
60    /// that locale or the defaults. Built by [`Arg::date`], [`Arg::date_as`],
61    /// [`Arg::relative`]. Feature `format`.
62    #[cfg(feature = "format")]
63    Date(crate::DateArg<'a>),
64}
65
66#[cfg(feature = "format")]
67impl<'a> Arg<'a> {
68    /// A date formatted when shown with the default options (JS `td(date)`).
69    ///
70    /// ```
71    /// use i18n_next::{Arg, I18n};
72    ///
73    /// let i18n = I18n::builder().time_zone("UTC").messages("en", None, r#"{"due": "Due {at}"}"#).build()?;
74    /// assert_eq!(i18n.text("due").arg("at", Arg::date(1_704_428_640_000i64)), "Due 1/5/2024");
75    /// # Ok::<(), i18n_next::Error>(())
76    /// ```
77    #[must_use]
78    pub fn date(at: impl Into<crate::Timestamp>) -> Self {
79        Arg::Date(crate::DateArg::date(at.into(), None))
80    }
81
82    /// A date formatted when shown with the named date format `name` (JS `td(date, name)`).
83    ///
84    /// ```
85    /// use i18n_next::{Arg, I18n, t};
86    ///
87    /// let i18n = I18n::builder()
88    ///     .time_zone("UTC")
89    ///     .datetime_formats(r#"{"en": {"short": {"month": "short", "day": "numeric"}}}"#)
90    ///     .messages("en", None, r#"{"due": "Due {at}"}"#)
91    ///     .build()?;
92    /// assert_eq!(t!(i18n => "due", at = Arg::date_as(1_704_428_640_000i64, "short")), "Due Jan 5");
93    /// # Ok::<(), i18n_next::Error>(())
94    /// ```
95    #[must_use]
96    pub fn date_as(at: impl Into<crate::Timestamp>, name: impl Into<Cow<'a, str>>) -> Self {
97        Arg::Date(crate::DateArg::date(at.into(), Some(name.into())))
98    }
99
100    /// An instant relative to the instance's clock when shown (JS `tdr(date)`): `3 days ago`.
101    ///
102    /// ```
103    /// use i18n_next::{Arg, I18n};
104    ///
105    /// let now = 1_704_428_640_000i64;
106    /// let i18n = I18n::builder().clock(move || now).messages("en", None, r#"{"seen": "Seen {at}"}"#).build()?;
107    /// assert_eq!(i18n.text("seen").arg("at", Arg::relative(now - 7_200_000)), "Seen 2 hours ago");
108    /// # Ok::<(), i18n_next::Error>(())
109    /// ```
110    #[must_use]
111    pub fn relative(at: impl Into<crate::Timestamp>) -> Self {
112        Arg::Date(crate::DateArg::relative(at.into()))
113    }
114}
115
116impl PartialEq for Arg<'_> {
117    fn eq(&self, other: &Self) -> bool {
118        match (self, other) {
119            (a, b) if a.as_str().is_some() || b.as_str().is_some() => a.as_str() == b.as_str(),
120            (Arg::Int(a), Arg::Int(b)) => a == b,
121            #[cfg(feature = "format")]
122            (Arg::Float(a), Arg::Float(b)) => a == b,
123            (Arg::Bool(a), Arg::Bool(b)) => a == b,
124            (Arg::Null, Arg::Null) => true,
125            (Arg::Text(a), Arg::Text(b)) => a.same(b),
126            #[cfg(feature = "format")]
127            (
128                Arg::Number {
129                    value: a,
130                    format: fa,
131                },
132                Arg::Number {
133                    value: b,
134                    format: fb,
135                },
136            ) => a == b && fa == fb,
137            #[cfg(feature = "format")]
138            (Arg::Date(a), Arg::Date(b)) => a == b,
139            _ => false,
140        }
141    }
142}
143
144/// A stack buffer for one number, boolean or `null` ([`MAX_SCALAR_LEN`] fits).
145pub(crate) struct Small {
146    bytes: [u8; 32],
147    len: usize,
148}
149
150impl Small {
151    pub(crate) fn new() -> Self {
152        Small {
153            bytes: [0; 32],
154            len: 0,
155        }
156    }
157
158    pub(crate) fn as_str(&self) -> &str {
159        std::str::from_utf8(self.bytes.get(..self.len).unwrap_or(&[])).unwrap_or("")
160    }
161}
162
163impl Out for Small {
164    fn push_str(&mut self, s: &str) {
165        let end = self.len + s.len();
166        if let Some(slot) = self.bytes.get_mut(self.len..end) {
167            slot.copy_from_slice(s.as_bytes());
168            self.len = end;
169        }
170    }
171
172    fn push(&mut self, c: char) {
173        self.push_str(c.encode_utf8(&mut [0; 4]));
174    }
175}
176
177/// `&<>"'` as HTML entities, like JS `escapeHtml`.
178pub(crate) fn escape_html(out: &mut dyn fmt::Write, s: &str) -> fmt::Result {
179    let mut from = 0;
180    for (i, b) in s.bytes().enumerate() {
181        let entity = match b {
182            b'&' => "&amp;",
183            b'<' => "&lt;",
184            b'>' => "&gt;",
185            b'"' => "&quot;",
186            b'\'' => "&#39;",
187            _ => continue,
188        };
189        out.write_str(s.get(from..i).unwrap_or(""))?;
190        out.write_str(entity)?;
191        from = i + 1;
192    }
193    out.write_str(s.get(from..).unwrap_or(""))
194}
195
196/// A writer that escapes what goes through it ([`escape_html`]).
197pub(crate) struct Escape<'w>(pub(crate) &'w mut dyn fmt::Write);
198
199impl fmt::Write for Escape<'_> {
200    fn write_str(&mut self, s: &str) -> fmt::Result {
201        escape_html(self.0, s)
202    }
203}
204
205impl Arg<'_> {
206    fn as_str(&self) -> Option<&str> {
207        match self {
208            Arg::Str(s) => Some(s),
209            Arg::String(s) => Some(s),
210            _ => None,
211        }
212    }
213
214    pub(crate) fn write(&self, out: &mut String) {
215        match self {
216            Arg::Str(s) => out.push_str(s),
217            Arg::String(s) => out.push_str(s),
218            Arg::Text(t) => {
219                // Writing to a `String` cannot fail.
220                let _ = t.show(out);
221            }
222            #[cfg(feature = "format")]
223            Arg::Number { value, format } => {
224                let _ = crate::format::api::write_in(None, None, *value, format.as_deref(), out);
225            }
226            #[cfg(feature = "format")]
227            Arg::Date(d) => {
228                let _ = d.write_in(None, None, out);
229            }
230            other => other.scalar(out),
231        }
232    }
233
234    /// Numbers, booleans and `null`; text kinds write nothing.
235    fn scalar<O: Out + ?Sized>(&self, out: &mut O) {
236        match *self {
237            Arg::Int(n) => {
238                if n < 0 {
239                    out.push('-');
240                }
241                push_u64(out, n.unsigned_abs());
242            }
243            #[cfg(feature = "format")]
244            Arg::Float(v) => push_js_number(out, v),
245            Arg::Bool(b) => out.push_str(if b { "true" } else { "false" }),
246            Arg::Null => out.push_str("null"),
247            Arg::Str(_) | Arg::String(_) | Arg::Text(_) => {}
248            #[cfg(feature = "format")]
249            Arg::Number { .. } | Arg::Date(_) => {}
250        }
251    }
252
253    /// Writes the value to a formatter: text escaped under `html` (JS `escapeParams`:
254    /// numbers and booleans are not), numbers through a stack buffer.
255    pub(crate) fn emit(&self, out: &mut dyn fmt::Write, html: bool) -> fmt::Result {
256        match self {
257            Arg::Str(s) if html => escape_html(out, s),
258            Arg::String(s) if html => escape_html(out, s),
259            Arg::Str(s) => out.write_str(s),
260            Arg::String(s) => out.write_str(s),
261            // an `html` Text is markup already; a plain one is text to escape
262            Arg::Text(t) if html && !t.is_html() => t.emit(&mut Escape(out)),
263            Arg::Text(t) => t.emit(out),
264            #[cfg(feature = "format")]
265            Arg::Number { value, format } => {
266                crate::format::api::write_in(None, None, *value, format.as_deref(), out)
267            }
268            #[cfg(feature = "format")]
269            Arg::Date(d) => d.write_in(None, None, out),
270            other => {
271                let mut b = Small::new();
272                other.scalar(&mut b);
273                out.write_str(b.as_str())
274            }
275        }
276    }
277
278    /// Bytes [`Arg::write`] appends: exact, an upper bound for a float, a guess for a
279    /// `Text` (it only sizes a buffer).
280    pub(crate) fn len(&self) -> usize {
281        match self {
282            Arg::Str(s) => s.len(),
283            Arg::String(s) => s.len(),
284            Arg::Int(n) => usize::from(*n < 0) + u64_len(n.unsigned_abs()),
285            #[cfg(feature = "format")]
286            Arg::Float(_) => MAX_SCALAR_LEN,
287            Arg::Bool(true) | Arg::Null => 4,
288            Arg::Bool(false) => 5,
289            Arg::Text(_) => MAX_SCALAR_LEN,
290            // a guess: it only sizes a buffer
291            #[cfg(feature = "format")]
292            Arg::Number { .. } | Arg::Date(_) => 2 * MAX_SCALAR_LEN,
293        }
294    }
295}
296
297impl<'a> From<&'a str> for Arg<'a> {
298    fn from(s: &'a str) -> Self {
299        Arg::Str(s)
300    }
301}
302
303/// Copied (one allocation), so it fits a `Text`; [`Args::str`] borrows instead.
304impl From<&String> for Arg<'_> {
305    fn from(s: &String) -> Self {
306        Arg::String(Arc::from(s.as_str()))
307    }
308}
309
310impl From<String> for Arg<'_> {
311    fn from(s: String) -> Self {
312        Arg::String(Arc::from(s))
313    }
314}
315
316impl From<Arc<str>> for Arg<'_> {
317    fn from(s: Arc<str>) -> Self {
318        Arg::String(s)
319    }
320}
321
322impl From<Box<str>> for Arg<'_> {
323    fn from(s: Box<str>) -> Self {
324        Arg::String(Arc::from(s))
325    }
326}
327
328impl<'a> From<Cow<'a, str>> for Arg<'a> {
329    fn from(s: Cow<'a, str>) -> Self {
330        match s {
331            Cow::Borrowed(s) => Arg::Str(s),
332            Cow::Owned(s) => Arg::from(s),
333        }
334    }
335}
336
337macro_rules! int_args {
338    ($($t:ty),*) => {$(
339        impl From<$t> for Arg<'_> {
340            fn from(n: $t) -> Self {
341                Arg::Int(i64::from(n))
342            }
343        }
344    )*};
345}
346int_args!(i8, i16, i32, i64, u8, u16, u32);
347
348/// Past 2^53 the value is what JS would hold, the nearest `f64`, as for [`Count`]:
349/// `2^53 + 1` shows `9007199254740992`, `u64::MAX` `18446744073709552000`.
350impl From<u64> for Arg<'_> {
351    fn from(n: u64) -> Self {
352        if n <= SAFE {
353            Arg::Int(n as i64)
354        } else {
355            big(n as f64)
356        }
357    }
358}
359
360/// Past ±2^53 the nearest `f64`, printed as JS prints it (`1e+21` and up with an exponent),
361/// as for `u64`. Feature `format` (float printing).
362#[cfg(feature = "format")]
363impl From<u128> for Arg<'_> {
364    fn from(n: u128) -> Self {
365        match u64::try_from(n) {
366            Ok(n) => Arg::from(n),
367            Err(_) => Arg::Float(n as f64),
368        }
369    }
370}
371
372/// Like `u128`. Feature `format` (float printing).
373#[cfg(feature = "format")]
374impl From<i128> for Arg<'_> {
375    fn from(n: i128) -> Self {
376        if n.unsigned_abs() <= u128::from(SAFE) {
377            Arg::Int(n as i64)
378        } else {
379            Arg::Float(n as f64)
380        }
381    }
382}
383
384/// The character as text (one allocation).
385impl From<char> for Arg<'_> {
386    fn from(c: char) -> Self {
387        Arg::String(Arc::from(&*c.encode_utf8(&mut [0; 4])))
388    }
389}
390
391/// An integer past 2^53 as JS holds it: a float with `format`, else its digits as text
392/// (below 2^64 a rounded whole number never needs an exponent).
393fn big(x: f64) -> Arg<'static> {
394    #[cfg(feature = "format")]
395    return Arg::Float(x);
396    #[cfg(not(feature = "format"))]
397    {
398        let mut s = String::new();
399        Count(CountRepr::Big(x)).write(&mut s);
400        Arg::String(Arc::from(s))
401    }
402}
403
404impl<'a> Arg<'a> {
405    /// Any [`Display`](fmt::Display) value as text, formatted now (one allocation): a
406    /// path, an error, a type of your own.
407    ///
408    /// ```
409    /// use i18n_next::{Arg, I18n, t};
410    ///
411    /// let i18n = I18n::builder().messages("en", None, r#"{"io": "Cannot read {path}"}"#).build()?;
412    /// let path = std::path::Path::new("/tmp/a.json");
413    /// assert_eq!(t!(i18n => "io", path = Arg::display(path.display())), "Cannot read /tmp/a.json");
414    /// # Ok::<(), i18n_next::Error>(())
415    /// ```
416    #[must_use]
417    pub fn display(value: impl fmt::Display) -> Self {
418        Arg::String(Arc::from(value.to_string()))
419    }
420}
421
422/// Past `i64::MAX` (only on a 128-bit `usize`) the value saturates.
423impl From<usize> for Arg<'_> {
424    fn from(n: usize) -> Self {
425        Arg::Int(i64::try_from(n).unwrap_or(i64::MAX))
426    }
427}
428
429#[cfg(feature = "format")]
430impl From<f64> for Arg<'_> {
431    fn from(v: f64) -> Self {
432        Arg::Float(v)
433    }
434}
435
436#[cfg(feature = "format")]
437impl From<f32> for Arg<'_> {
438    fn from(v: f32) -> Self {
439        Arg::Float(f64::from(v))
440    }
441}
442
443impl From<bool> for Arg<'_> {
444    fn from(b: bool) -> Self {
445        Arg::Bool(b)
446    }
447}
448
449impl From<Text> for Arg<'_> {
450    fn from(t: Text) -> Self {
451        Arg::Text(Box::new(t))
452    }
453}
454
455impl From<Key> for Arg<'_> {
456    fn from(k: Key) -> Self {
457        Arg::Text(Box::new(k.args()))
458    }
459}
460
461/// The longest spelling of a number, boolean or `null`, a count included: an `f64`'s,
462/// `-0.0000012345678901234567` (17 digits after `0.00000`), one more than
463/// `-2.2250738585072014e-308`.
464pub(crate) const MAX_SCALAR_LEN: usize = 25;
465
466/// 2^53: integers up to it are exact in an `f64`, as JS holds every number.
467const SAFE: u64 = 1 << 53;
468
469/// The count of [`I18n::tc`](crate::I18n::tc): an integer, or (feature `format`) an `f64`.
470///
471/// It picks the plural form and fills `{count}`, printed as JS prints the number. A
472/// negative, fractional or non-finite count takes the last form, as in JS. An integer past
473/// ±2^53 is what JS would hold: the nearest `f64` (`2^53 + 1` is `9007199254740992`,
474/// `u64::MAX` is `18446744073709552000`), for the form and for `{count}` alike.
475///
476/// ```
477/// use i18n_next::Count;
478///
479/// let _ = [Count::from(3), Count::from(3u64), Count::from(3usize), Count::from(-1i64)];
480/// ```
481#[derive(Debug, Clone, Copy, PartialEq)]
482pub struct Count(CountRepr);
483
484#[derive(Debug, Clone, Copy, PartialEq)]
485enum CountRepr {
486    /// 0..=2^53.
487    Whole(u64),
488    /// -2^53..0.
489    Negative(i64),
490    /// An integer past ±2^53, rounded to the nearest `f64` (no `format` feature needed).
491    Big(f64),
492    #[cfg(feature = "format")]
493    Float(f64),
494}
495
496impl Count {
497    /// The count as `pluralForm` reads it: whole and not negative, else `None` (last form).
498    pub(crate) fn whole(self) -> Option<Whole> {
499        match self.0 {
500            CountRepr::Whole(n) => Some(Whole::Int(n)),
501            CountRepr::Negative(_) => None,
502            CountRepr::Big(x) if x > 0.0 => Some(Whole::Big(x)),
503            CountRepr::Big(_) => None,
504            // `-0.0 >= 0.0`: JS `Number.isInteger(-0) && !(-0 < 0)`, the zero form.
505            #[cfg(feature = "format")]
506            CountRepr::Float(x) if x >= 0.0 && x.fract() == 0.0 => {
507                // Up to 2^53 every whole f64 is exact and spelled with its own digits.
508                if x <= SAFE as f64 {
509                    Some(Whole::Int(x as u64))
510                } else {
511                    Some(Whole::Big(x))
512                }
513            }
514            #[cfg(feature = "format")]
515            CountRepr::Float(_) => None,
516        }
517    }
518
519    /// The count as a JS number (a custom plural rule gets it).
520    pub(crate) fn as_f64(self) -> f64 {
521        match self.0 {
522            CountRepr::Whole(n) => n as f64,
523            CountRepr::Negative(n) => n as f64,
524            CountRepr::Big(x) => x,
525            #[cfg(feature = "format")]
526            CountRepr::Float(x) => x,
527        }
528    }
529
530    /// Appends the count as JS `String(count)` writes it.
531    pub(crate) fn write<O: Out + ?Sized>(self, out: &mut O) {
532        match self.0 {
533            CountRepr::Whole(n) => push_u64(out, n),
534            CountRepr::Negative(n) => {
535                out.push('-');
536                push_u64(out, n.unsigned_abs());
537            }
538            CountRepr::Big(x) => {
539                if x < 0.0 {
540                    out.push('-');
541                }
542                // Past 2^53 and at most 2^64: never `None`, never an exponent.
543                let (digits, zeros) = shortest_whole(x.abs()).unwrap_or((0, 0));
544                push_u64(out, digits);
545                out.push_zeros(zeros as usize);
546            }
547            #[cfg(feature = "format")]
548            CountRepr::Float(v) => push_js_number(out, v),
549        }
550    }
551
552    /// Bytes [`Count::write`] appends: exact, an upper bound for a float.
553    pub(crate) fn len(self) -> usize {
554        match self.0 {
555            CountRepr::Whole(n) => u64_len(n),
556            CountRepr::Negative(n) => 1 + u64_len(n.unsigned_abs()),
557            // `-18446744073709552000`
558            CountRepr::Big(_) => 21,
559            #[cfg(feature = "format")]
560            CountRepr::Float(_) => MAX_SCALAR_LEN,
561        }
562    }
563}
564
565impl From<i64> for Count {
566    fn from(n: i64) -> Self {
567        match u64::try_from(n) {
568            Ok(n) => Count::from(n),
569            Err(_) if n.unsigned_abs() <= SAFE => Count(CountRepr::Negative(n)),
570            Err(_) => Count(CountRepr::Big(n as f64)),
571        }
572    }
573}
574
575impl From<i32> for Count {
576    fn from(n: i32) -> Self {
577        Count::from(i64::from(n))
578    }
579}
580
581impl From<u64> for Count {
582    fn from(n: u64) -> Self {
583        Count(if n <= SAFE {
584            CountRepr::Whole(n)
585        } else {
586            CountRepr::Big(n as f64)
587        })
588    }
589}
590
591impl From<u32> for Count {
592    fn from(n: u32) -> Self {
593        Count(CountRepr::Whole(u64::from(n)))
594    }
595}
596
597impl From<usize> for Count {
598    fn from(n: usize) -> Self {
599        Count::from(n as u64)
600    }
601}
602
603#[cfg(feature = "format")]
604impl From<f64> for Count {
605    fn from(v: f64) -> Self {
606        Count(CountRepr::Float(v))
607    }
608}
609
610/// What [`Args::find`] found: a stored value, or the `{length}` of a list. `Copy`, not a
611/// `Cow`: a lookup has no drop glue, so the callers' `put` stays inlined (~2 ns a
612/// placeholder, `t_with` with ten arguments -10 ns).
613#[derive(Clone, Copy)]
614pub(crate) enum Hit<'x, 'a> {
615    Arg(&'x Arg<'a>),
616    Len(i64),
617}
618
619impl<'a> Hit<'_, 'a> {
620    /// Runs `f` on the value (`{length}` as an [`Arg::Int`]).
621    #[inline]
622    pub(crate) fn with<R>(self, f: impl FnOnce(&Arg<'a>) -> R) -> R {
623        match self {
624            Hit::Arg(a) => f(a),
625            Hit::Len(n) => f(&Arg::Int(n)),
626        }
627    }
628}
629
630#[derive(Debug, Clone, PartialEq)]
631enum Name<'a> {
632    Named(&'a str),
633    /// A name built at run time (a `Text` argument named by a `String`).
634    Shared(Arc<str>),
635    /// A list item: `{0}`, `{1}`…
636    Index(usize),
637}
638
639type Slot<'a> = (Name<'a>, Arg<'a>);
640
641const INLINE: usize = 4;
642
643const EMPTY: Slot<'static> = (Name::Index(0), Arg::Null);
644
645/// Parameters for `{name}` placeholders, plus an optional default text.
646///
647/// ```
648/// use i18n_next::{Args, I18n};
649///
650/// let i18n = I18n::builder()
651///     .messages("en", None, r#"{"hi": "Hi, {name}! {n} new", "pair": "{0} and {1}"}"#)
652///     .build()?;
653/// assert_eq!(i18n.t_with("hi", &Args::new().str("name", "Ann").int("n", 3)), "Hi, Ann! 3 new");
654/// assert_eq!(i18n.t_with("pair", &Args::list(["Ann", "Bob"])), "Ann and Bob");
655/// assert_eq!(i18n.t_with("nope", &Args::new().int("n", 1).or("Default {n}")), "Default 1");
656/// # Ok::<(), i18n_next::Error>(())
657/// ```
658///
659/// A name that is not given leaves `{name}` as written. A name given twice: the last wins.
660#[derive(Clone)]
661pub struct Args<'a> {
662    inline: [Slot<'a>; INLINE],
663    len: usize,
664    overflow: Vec<Slot<'a>>,
665    /// Items of [`Args::list`]: `{length}` reads it, as on a JS array.
666    list_len: Option<usize>,
667    default: Option<&'a str>,
668}
669
670/// The parameters as a map (`{"name": Str("Ann"), 0: Int(1)}`) and the default.
671impl fmt::Debug for Args<'_> {
672    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673        let mut m = f.debug_map();
674        for (name, value) in self.slots() {
675            match name {
676                Name::Named(n) => m.entry(n, value),
677                Name::Shared(n) => m.entry(n, value),
678                Name::Index(i) => m.entry(i, value),
679            };
680        }
681        if let Some(d) = self.default {
682            m.entry(&"or", &d);
683        }
684        m.finish()
685    }
686}
687
688impl Default for Args<'_> {
689    fn default() -> Self {
690        Self::new()
691    }
692}
693
694impl<'a> Args<'a> {
695    /// No parameters.
696    #[must_use]
697    pub const fn new() -> Self {
698        Args {
699            inline: [EMPTY; INLINE],
700            len: 0,
701            overflow: Vec::new(),
702            list_len: None,
703            default: None,
704        }
705    }
706
707    /// Positional parameters `{0}`, `{1}`… and `{length}`, like a JS array.
708    #[must_use]
709    pub fn list<I>(items: I) -> Self
710    where
711        I: IntoIterator,
712        I::Item: Into<Arg<'a>>,
713    {
714        let mut args = Self::new();
715        args.extend_list(items.into_iter().map(Into::into));
716        args
717    }
718
719    /// Appends list items, numbered after those already there.
720    pub(crate) fn extend_list(&mut self, items: impl Iterator<Item = Arg<'a>>) {
721        let mut n = self.list_len.unwrap_or(0);
722        for item in items {
723            // too deep a `Text` (see `Text`): dropped, `{n}` shows as written
724            if !matches!(&item, Arg::Text(t) if t.depth >= MAX_NESTING) {
725                self.push(Name::Index(n), item);
726            }
727            n += 1;
728        }
729        self.list_len = Some(n);
730    }
731
732    pub(crate) fn push_named(&mut self, name: Cow<'a, str>, value: Arg<'a>) {
733        let name = match name {
734            Cow::Borrowed(n) => Name::Named(n),
735            Cow::Owned(n) => Name::Shared(Arc::from(n)),
736        };
737        self.push(name, value);
738    }
739
740    /// Same parameters, same order (`Text` equality inside an [`Arg`]).
741    pub(crate) fn same(&self, other: &Self) -> bool {
742        self.list_len == other.list_len && self.slots() == other.slots()
743    }
744
745    /// Whether there is no parameter at all.
746    pub(crate) fn is_empty(&self) -> bool {
747        self.len == 0 && self.overflow.is_empty() && self.list_len.is_none()
748    }
749
750    fn push(&mut self, name: Name<'a>, value: Arg<'a>) {
751        if let Some(slot) = self.inline.get_mut(self.len) {
752            *slot = (name, value);
753            self.len += 1;
754        } else {
755            // A fifth parameter moves all of them to the `Vec`, so lookups scan one slice.
756            if self.overflow.is_empty() {
757                self.overflow.reserve(2 * INLINE);
758                self.overflow
759                    .extend(self.inline.iter_mut().map(|s| std::mem::replace(s, EMPTY)));
760            }
761            self.overflow.push((name, value));
762        }
763    }
764
765    /// Adds a parameter of any [`Arg`] kind.
766    #[must_use]
767    pub fn arg(mut self, name: &'a str, value: impl Into<Arg<'a>>) -> Self {
768        self.push(Name::Named(name), value.into());
769        self
770    }
771
772    /// Adds a text parameter.
773    #[must_use]
774    pub fn str(self, name: &'a str, value: &'a str) -> Self {
775        self.arg(name, Arg::Str(value))
776    }
777
778    /// Adds an integer parameter.
779    #[must_use]
780    pub fn int(self, name: &'a str, value: i64) -> Self {
781        self.arg(name, Arg::Int(value))
782    }
783
784    /// Adds a number parameter, printed as JS prints numbers (feature `format`).
785    #[cfg(feature = "format")]
786    #[must_use]
787    pub fn float(self, name: &'a str, value: f64) -> Self {
788        self.arg(name, Arg::Float(value))
789    }
790
791    /// Adds a boolean parameter.
792    #[must_use]
793    pub fn bool(self, name: &'a str, value: bool) -> Self {
794        self.arg(name, Arg::Bool(value))
795    }
796
797    /// Adds a parameter printed as `null`.
798    #[must_use]
799    pub fn null(self, name: &'a str) -> Self {
800        self.arg(name, Arg::Null)
801    }
802
803    /// The text returned when the key is missing everywhere, interpolated with these
804    /// parameters. An empty default counts as none (the key is returned), as in JS.
805    #[must_use]
806    pub fn or(mut self, default: &'a str) -> Self {
807        self.default = Some(default);
808        self
809    }
810
811    pub(crate) fn default_text(&self) -> Option<&'a str> {
812        self.default.filter(|d| !d.is_empty())
813    }
814
815    /// The default as given: `tc` keeps an empty one (JS `defaultValue ?? key`).
816    pub(crate) fn default_raw(&self) -> Option<&'a str> {
817        self.default
818    }
819
820    /// Every parameter, oldest first: the inline ones, or all of them in the `Vec` once
821    /// there are more than four.
822    fn slots(&self) -> &[Slot<'a>] {
823        if self.overflow.is_empty() {
824            self.inline.get(..self.len).unwrap_or(&[])
825        } else {
826            &self.overflow
827        }
828    }
829
830    /// The value of placeholder `name`: the newest named match, a list item for a canonical
831    /// index (`0`, `12`, never `01`), or the list length for `length`.
832    #[inline]
833    pub(crate) fn find(&self, name: &str) -> Option<Hit<'_, 'a>> {
834        self.lookup(name, true)
835    }
836
837    /// What JS `{ ...args }` holds under `name`: [`Args::find`] without `length` (a spread
838    /// array has none).
839    #[inline]
840    pub(crate) fn spread(&self, name: &str) -> Option<Hit<'_, 'a>> {
841        self.lookup(name, false)
842    }
843
844    // One function for both: as two (`spread` + a `length` fallback) `t_with` with one
845    // argument took +20 ns.
846    #[inline]
847    fn lookup(&self, name: &str, length: bool) -> Option<Hit<'_, 'a>> {
848        // Only `list` makes index slots.
849        let index = self.list_len.and_then(|_| canonical_index(name));
850        for (slot, value) in self.slots().iter().rev() {
851            let hit = match slot {
852                Name::Named(n) => same_name(n, name),
853                Name::Shared(n) => same_name(n, name),
854                Name::Index(i) => index == Some(*i),
855            };
856            if hit {
857                return Some(Hit::Arg(value));
858            }
859        }
860        match self.list_len {
861            Some(n) if length && name == "length" => Some(Hit::Len(n as i64)),
862            _ => None,
863        }
864    }
865
866    /// At least the longest [`Arg::len`] of the parameters, `{length}` of a list included:
867    /// exact for text, [`MAX_SCALAR_LEN`] for anything else (no digit counting: it only
868    /// sizes the cheap bound of an interpolation).
869    pub(crate) fn max_value_len(&self) -> usize {
870        let list = if self.list_len.is_some() {
871            MAX_SCALAR_LEN
872        } else {
873            0
874        };
875        self.slots()
876            .iter()
877            .map(|(_, v)| match v {
878                Arg::Str(s) => s.len(),
879                Arg::String(s) => s.len(),
880                _ => MAX_SCALAR_LEN,
881            })
882            .fold(list, usize::max)
883    }
884}
885
886// An inlined byte loop: names are short, and a `memcmp` call per slot made many parameters
887// cost ~25 ns each.
888#[inline(always)]
889fn same_name(n: &str, name: &str) -> bool {
890    n.len() == name.len() && n.bytes().zip(name.bytes()).all(|(a, b)| a == b)
891}
892
893/// `name` as an array index the way JS reads one: digits, no leading zero but `0` itself.
894fn canonical_index(name: &str) -> Option<usize> {
895    let b = name.as_bytes();
896    if b.is_empty() || (b.len() > 1 && b[0] == b'0') || !b.iter().all(u8::is_ascii_digit) {
897        return None;
898    }
899    name.parse().ok()
900}