1
//! C-compatible string formatting via `strfmt`.
2
//!
3
//! Provides [`FmtValue`], [`FmtArg`], and [`FmtArgVec`] for passing
4
//! heterogeneous format arguments across FFI, and [`fmt_string`] as the
5
//! main entry point. Used by `fluent.rs` and `icu.rs` for localization.
6

            
7
use std::fmt;
8

            
9
use azul_css::{impl_option, impl_option_inner, AzString, StringVec};
10

            
11
/// A format argument value that can hold any primitive type or string.
12
/// Used in [`FmtArg`] to pass typed values into `strfmt`-based formatting.
13
#[derive(Debug, Clone, PartialEq, PartialOrd)]
14
#[repr(C, u8)]
15
pub enum FmtValue {
16
    Bool(bool),
17
    Uchar(u8),
18
    Schar(i8),
19
    Ushort(u16),
20
    Sshort(i16),
21
    Uint(u32),
22
    Sint(i32),
23
    Ulong(u64),
24
    Slong(i64),
25
    Isize(isize),
26
    Usize(usize),
27
    Float(f32),
28
    Double(f64),
29
    Str(AzString),
30
    StrVec(StringVec),
31
}
32

            
33
impl strfmt::DisplayStr for FmtValue {
34
604
    fn display_str(&self, f: &mut strfmt::Formatter<'_, '_>) -> strfmt::Result<()> {
35
        use strfmt::DisplayStr;
36
604
        match self {
37
2
            Self::Bool(v) => format!("{v}").display_str(f),
38
503
            Self::Uchar(v) => v.display_str(f),
39
3
            Self::Schar(v) => v.display_str(f),
40
2
            Self::Ushort(v) => v.display_str(f),
41
2
            Self::Sshort(v) => v.display_str(f),
42
9
            Self::Uint(v) => v.display_str(f),
43
11
            Self::Sint(v) => v.display_str(f),
44
3
            Self::Ulong(v) => v.display_str(f),
45
3
            Self::Slong(v) => v.display_str(f),
46
3
            Self::Isize(v) => v.display_str(f),
47
4
            Self::Usize(v) => v.display_str(f),
48
10
            Self::Float(v) => v.display_str(f),
49
16
            Self::Double(v) => v.display_str(f),
50
24
            Self::Str(v) => v.as_str().display_str(f),
51
9
            Self::StrVec(sv) => {
52
9
                "[".display_str(f)?;
53
15
                for (i, s) in sv.as_ref().iter().enumerate() {
54
15
                    if i != 0 {
55
7
                        ", ".display_str(f)?;
56
8
                    }
57
15
                    s.as_str().display_str(f)?;
58
                }
59
9
                "]".display_str(f)?;
60
9
                Ok(())
61
            }
62
        }
63
604
    }
64
}
65

            
66
impl fmt::Display for FmtValue {
67
100
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68
100
        match self {
69
6
            Self::Bool(v) => v.fmt(f),
70
5
            Self::Uchar(v) => v.fmt(f),
71
5
            Self::Schar(v) => v.fmt(f),
72
4
            Self::Ushort(v) => v.fmt(f),
73
5
            Self::Sshort(v) => v.fmt(f),
74
7
            Self::Uint(v) => v.fmt(f),
75
4
            Self::Sint(v) => v.fmt(f),
76
5
            Self::Ulong(v) => v.fmt(f),
77
5
            Self::Slong(v) => v.fmt(f),
78
5
            Self::Isize(v) => v.fmt(f),
79
5
            Self::Usize(v) => v.fmt(f),
80
15
            Self::Float(v) => v.fmt(f),
81
17
            Self::Double(v) => v.fmt(f),
82
7
            Self::Str(v) => v.as_str().fmt(f),
83
5
            Self::StrVec(sv) => {
84
                use std::fmt::Debug;
85
5
                let vec: Vec<&str> = sv.as_ref().iter().map(AzString::as_str).collect();
86
5
                vec.fmt(f)
87
            }
88
        }
89
100
    }
90
}
91

            
92
/// A key-value pair mapping a format placeholder name to its value.
93
#[derive(Debug, Clone, PartialEq, PartialOrd)]
94
#[repr(C)]
95
pub struct FmtArg {
96
    pub key: AzString,
97
    pub value: FmtValue,
98
}
99

            
100
azul_css::impl_option!(
101
    FmtArg,
102
    OptionFmtArg,
103
    copy = false,
104
    [Debug, Clone, PartialEq, PartialOrd]
105
);
106
azul_css::impl_vec!(
107
    FmtArg,
108
    FmtArgVec,
109
    FmtArgVecDestructor,
110
    FmtArgVecDestructorType,
111
    FmtArgVecSlice,
112
    OptionFmtArg
113
);
114
azul_css::impl_vec_clone!(FmtArg, FmtArgVec, FmtArgVecDestructor);
115
azul_css::impl_vec_debug!(FmtArg, FmtArgVec);
116
azul_css::impl_vec_partialeq!(FmtArg, FmtArgVec);
117
azul_css::impl_vec_partialord!(FmtArg, FmtArgVec);
118

            
119
/// Formats `format` by substituting placeholders with values from `args`.
120
/// Returns the error message as a string on failure (for C FFI ergonomics).
121
// FFI-exported formatter: owned AzString/FmtArgVec args are the api.json signature.
122
#[allow(clippy::needless_pass_by_value)]
123
#[must_use]
124
121
pub fn fmt_string(format: AzString, args: FmtArgVec) -> String {
125
    use strfmt::Format;
126
121
    let format_map = args
127
121
        .iter()
128
121
        .map(|a| (a.key.clone().into_library_owned_string(), a.value.clone()))
129
121
        .collect();
130
121
    match format.as_str().format(&format_map) {
131
97
        Ok(o) => o,
132
24
        Err(e) => format!("{e}"),
133
    }
134
121
}
135

            
136
#[cfg(test)]
137
mod autotest_generated {
138
    use super::*;
139

            
140
    // ------------------------------------------------------------------
141
    // Harness
142
    // ------------------------------------------------------------------
143

            
144
    fn az(s: &str) -> AzString {
145
        AzString::from(s)
146
    }
147

            
148
    fn strvec(items: &[&str]) -> StringVec {
149
        StringVec::from_vec(items.iter().map(|s| az(s)).collect())
150
    }
151

            
152
    /// Formats `format` with the given key/value pairs. Because `fmt_string`
153
    /// swallows every `strfmt` failure into the returned `String`, the return
154
    /// value here is EITHER the formatted output OR an error message of the
155
    /// shape `Invalid(..)` / `KeyError(..)` / `TypeError(..)`.
156
    fn run(format: &str, args: &[(&str, FmtValue)]) -> String {
157
        let v: Vec<FmtArg> = args
158
            .iter()
159
            .map(|(k, value)| FmtArg {
160
                key: az(k),
161
                value: value.clone(),
162
            })
163
            .collect();
164
        fmt_string(az(format), FmtArgVec::from_vec(v))
165
    }
166

            
167
    /// True if the output is one of the three `strfmt` error renderings rather
168
    /// than a formatted string.
169
    fn is_err_str(s: &str) -> bool {
170
        s.starts_with("Invalid(") || s.starts_with("KeyError(") || s.starts_with("TypeError(")
171
    }
172

            
173
    /// Every scalar (non-`StrVec`) variant at an interesting boundary.
174
    fn scalar_variants() -> Vec<FmtValue> {
175
        vec![
176
            FmtValue::Bool(true),
177
            FmtValue::Bool(false),
178
            FmtValue::Uchar(0),
179
            FmtValue::Uchar(u8::MAX),
180
            FmtValue::Schar(i8::MIN),
181
            FmtValue::Schar(i8::MAX),
182
            FmtValue::Ushort(0),
183
            FmtValue::Ushort(u16::MAX),
184
            FmtValue::Sshort(i16::MIN),
185
            FmtValue::Sshort(i16::MAX),
186
            FmtValue::Uint(0),
187
            FmtValue::Uint(u32::MAX),
188
            FmtValue::Sint(i32::MIN),
189
            FmtValue::Sint(i32::MAX),
190
            FmtValue::Ulong(0),
191
            FmtValue::Ulong(u64::MAX),
192
            FmtValue::Slong(i64::MIN),
193
            FmtValue::Slong(i64::MAX),
194
            FmtValue::Isize(isize::MIN),
195
            FmtValue::Isize(isize::MAX),
196
            FmtValue::Usize(0),
197
            FmtValue::Usize(usize::MAX),
198
            FmtValue::Float(0.0),
199
            FmtValue::Float(f32::MIN),
200
            FmtValue::Float(f32::MAX),
201
            FmtValue::Float(f32::NAN),
202
            FmtValue::Float(f32::INFINITY),
203
            FmtValue::Float(f32::NEG_INFINITY),
204
            FmtValue::Float(f32::EPSILON),
205
            FmtValue::Double(0.0),
206
            FmtValue::Double(f64::MIN),
207
            FmtValue::Double(f64::MAX),
208
            FmtValue::Double(f64::NAN),
209
            FmtValue::Double(f64::INFINITY),
210
            FmtValue::Double(f64::NEG_INFINITY),
211
            FmtValue::Double(f64::MIN_POSITIVE),
212
            FmtValue::Str(AzString::default()),
213
            FmtValue::Str(az("plain")),
214
        ]
215
    }
216

            
217
    // ------------------------------------------------------------------
218
    // fmt_string: happy path + substitution invariants
219
    // ------------------------------------------------------------------
220

            
221
    #[test]
222
    fn substitutes_a_single_placeholder() {
223
        assert_eq!(
224
            run("Hello {name}!", &[("name", FmtValue::Str(az("World")))]),
225
            "Hello World!"
226
        );
227
    }
228

            
229
    #[test]
230
    fn empty_format_and_empty_args_yield_empty_output() {
231
        assert_eq!(fmt_string(AzString::default(), FmtArgVec::new()), "");
232
        assert_eq!(fmt_string(az("plain text"), FmtArgVec::new()), "plain text");
233
    }
234

            
235
    #[test]
236
    fn args_without_a_matching_placeholder_are_ignored() {
237
        assert_eq!(
238
            run(
239
                "{a}",
240
                &[("a", FmtValue::Sint(1)), ("unused", FmtValue::Sint(2))]
241
            ),
242
            "1"
243
        );
244
    }
245

            
246
    #[test]
247
    fn the_same_key_can_be_substituted_repeatedly() {
248
        assert_eq!(run("{k}-{k}-{k}", &[("k", FmtValue::Uint(7))]), "7-7-7");
249
    }
250

            
251
    #[test]
252
    fn duplicate_keys_resolve_to_the_last_arg() {
253
        // `fmt_string` collects into a `HashMap`, so a later duplicate overwrites
254
        // the earlier one instead of erroring or panicking.
255
        assert_eq!(
256
            run("{k}", &[("k", FmtValue::Sint(1)), ("k", FmtValue::Sint(2))]),
257
            "2"
258
        );
259
    }
260

            
261
    #[test]
262
    fn substituted_values_are_not_re_scanned_for_placeholders() {
263
        // A value that itself looks like a format string must be emitted
264
        // literally — no recursive expansion, no second-order injection.
265
        assert_eq!(
266
            run(
267
                "{a}",
268
                &[
269
                    ("a", FmtValue::Str(az("{b}"))),
270
                    ("b", FmtValue::Str(az("PWNED"))),
271
                ]
272
            ),
273
            "{b}"
274
        );
275
    }
276

            
277
    // ------------------------------------------------------------------
278
    // fmt_string: malformed format strings must return an error, never panic
279
    // ------------------------------------------------------------------
280

            
281
    #[test]
282
    fn missing_key_returns_a_key_error_string() {
283
        let out = run("{missing}", &[]);
284
        assert!(out.contains("Invalid key: missing"), "{out}");
285
        assert!(is_err_str(&out), "{out}");
286
    }
287

            
288
    #[test]
289
    fn unclosed_brace_returns_an_error_string() {
290
        for bad in ["{", "{name", "abc {name"] {
291
            let out = run(bad, &[("name", FmtValue::Sint(1))]);
292
            assert!(out.contains("Expected '}'"), "{bad:?} -> {out}");
293
        }
294
    }
295

            
296
    #[test]
297
    fn lone_closing_brace_returns_an_error_string() {
298
        for bad in ["}", "a}b", "trailing}"] {
299
            let out = run(bad, &[]);
300
            assert!(out.contains("Single '}'"), "{bad:?} -> {out}");
301
        }
302
    }
303

            
304
    #[test]
305
    fn nested_opening_brace_returns_an_error_string() {
306
        let out = run("{a{b}", &[("a", FmtValue::Sint(1))]);
307
        assert!(out.contains("extra {"), "{out}");
308
    }
309

            
310
    #[test]
311
    fn empty_placeholder_is_rejected_even_when_an_empty_key_exists() {
312
        // `{}` has no identifier; the empty-string key in `args` is unreachable.
313
        let out = run("{}", &[("", FmtValue::Sint(1))]);
314
        assert!(out.contains("must specify identifier"), "{out}");
315
    }
316

            
317
    #[test]
318
    fn a_colon_in_a_key_makes_that_key_unaddressable() {
319
        // Everything after the first `:` is parsed as a format spec, so the key
320
        // "a:b" can never be looked up — this must be a KeyError, not a panic.
321
        let out = run("{a:b}", &[("a:b", FmtValue::Sint(1))]);
322
        assert!(out.contains("Invalid key: a"), "{out}");
323
    }
324

            
325
    #[test]
326
    fn escaped_braces_are_emitted_literally() {
327
        assert_eq!(run("{{literal}}", &[]), "{literal}");
328
        assert_eq!(run("{{{{", &[]), "{{");
329
        assert_eq!(
330
            run("{{{k}}}", &[("k", FmtValue::Str(az("v")))]),
331
            "{v}",
332
            "escaped braces around a real placeholder"
333
        );
334
    }
335

            
336
    // ------------------------------------------------------------------
337
    // fmt_string: numeric limits, saturation and non-finite floats
338
    // ------------------------------------------------------------------
339

            
340
    #[test]
341
    fn every_scalar_variant_round_trips_through_its_display_impl() {
342
        // Invariant: for scalars, the strfmt path (`DisplayStr`) and the
343
        // `fmt::Display` path must agree. This also pins NaN/inf/MIN/MAX.
344
        for v in scalar_variants() {
345
            let out = run("{v}", &[("v", v.clone())]);
346
            assert_eq!(out, v.to_string(), "mismatch for {v:?}");
347
            assert!(!is_err_str(&out), "unexpected error for {v:?}: {out}");
348
        }
349
    }
350

            
351
    #[test]
352
    fn integer_limits_match_the_native_rendering() {
353
        assert_eq!(
354
            run("{v}", &[("v", FmtValue::Slong(i64::MIN))]),
355
            i64::MIN.to_string()
356
        );
357
        assert_eq!(
358
            run("{v}", &[("v", FmtValue::Ulong(u64::MAX))]),
359
            u64::MAX.to_string()
360
        );
361
        assert_eq!(
362
            run("{v}", &[("v", FmtValue::Usize(usize::MAX))]),
363
            usize::MAX.to_string()
364
        );
365
        assert_eq!(
366
            run("{v}", &[("v", FmtValue::Isize(isize::MIN))]),
367
            isize::MIN.to_string()
368
        );
369
        assert_eq!(run("{v}", &[("v", FmtValue::Schar(i8::MIN))]), "-128");
370
    }
371

            
372
    #[test]
373
    fn non_finite_floats_render_without_panicking() {
374
        assert_eq!(run("{v}", &[("v", FmtValue::Float(f32::NAN))]), "NaN");
375
        assert_eq!(run("{v}", &[("v", FmtValue::Float(f32::INFINITY))]), "inf");
376
        assert_eq!(
377
            run("{v}", &[("v", FmtValue::Double(f64::NEG_INFINITY))]),
378
            "-inf"
379
        );
380
        // Precision must not turn NaN/inf into a panic or a bogus number.
381
        assert_eq!(run("{v:.2}", &[("v", FmtValue::Double(f64::NAN))]), "NaN");
382
        assert_eq!(
383
            run("{v:.5}", &[("v", FmtValue::Double(f64::INFINITY))]),
384
            "inf"
385
        );
386
    }
387

            
388
    #[test]
389
    fn float_extremes_match_the_native_rendering() {
390
        assert_eq!(
391
            run("{v}", &[("v", FmtValue::Double(f64::MAX))]),
392
            f64::MAX.to_string()
393
        );
394
        assert_eq!(
395
            run("{v}", &[("v", FmtValue::Double(f64::MIN_POSITIVE))]),
396
            f64::MIN_POSITIVE.to_string()
397
        );
398
        assert_eq!(
399
            run("{v}", &[("v", FmtValue::Float(f32::MIN))]),
400
            f32::MIN.to_string()
401
        );
402
    }
403

            
404
    #[test]
405
    fn radix_format_codes_match_the_native_rendering() {
406
        assert_eq!(run("{v:x}", &[("v", FmtValue::Uint(255))]), "ff");
407
        assert_eq!(run("{v:X}", &[("v", FmtValue::Uint(255))]), "FF");
408
        assert_eq!(run("{v:#x}", &[("v", FmtValue::Uint(255))]), "0xff");
409
        assert_eq!(run("{v:b}", &[("v", FmtValue::Uchar(5))]), "101");
410
        assert_eq!(run("{v:o}", &[("v", FmtValue::Uint(8))]), "10");
411
        // Two's-complement rendering of the most negative value must not panic.
412
        assert_eq!(
413
            run("{v:b}", &[("v", FmtValue::Sint(i32::MIN))]),
414
            format!("{:b}", i32::MIN)
415
        );
416
        assert_eq!(
417
            run("{v:x}", &[("v", FmtValue::Usize(usize::MAX))]),
418
            format!("{:x}", usize::MAX)
419
        );
420
    }
421

            
422
    #[test]
423
    fn explicit_sign_is_honoured_for_numbers() {
424
        assert_eq!(run("{v:+}", &[("v", FmtValue::Sint(5))]), "+5");
425
        assert_eq!(run("{v:+}", &[("v", FmtValue::Sint(-5))]), "-5");
426
        assert_eq!(run("{v:+}", &[("v", FmtValue::Sint(0))]), "+0");
427
    }
428

            
429
    #[test]
430
    fn exponent_and_precision_codes_match_the_native_rendering() {
431
        assert_eq!(
432
            run("{v:e}", &[("v", FmtValue::Double(1234.0))]),
433
            format!("{:e}", 1234.0_f64)
434
        );
435
        assert_eq!(
436
            run("{v:.3}", &[("v", FmtValue::Double(1.234_56))]),
437
            format!("{:.3}", 1.234_56_f64)
438
        );
439
    }
440

            
441
    // ------------------------------------------------------------------
442
    // fmt_string: format-spec type errors are reported, not panicked
443
    // ------------------------------------------------------------------
444

            
445
    #[test]
446
    fn precision_on_an_integer_is_a_type_error() {
447
        let out = run("{v:.2}", &[("v", FmtValue::Sint(5))]);
448
        assert!(out.contains("precision not allowed for integers"), "{out}");
449
    }
450

            
451
    #[test]
452
    fn a_string_valued_arg_rejects_numeric_format_codes() {
453
        for spec in ["{v:x}", "{v:b}", "{v:e}", "{v:#}", "{v:+}"] {
454
            let out = run(spec, &[("v", FmtValue::Str(az("hi")))]);
455
            assert!(is_err_str(&out), "{spec} unexpectedly succeeded: {out}");
456
        }
457
    }
458

            
459
    #[test]
460
    fn a_float_valued_arg_rejects_integer_format_codes() {
461
        let out = run("{v:x}", &[("v", FmtValue::Double(1.0))]);
462
        assert!(out.contains("Unknown format code"), "{out}");
463
        let out = run("{v:#}", &[("v", FmtValue::Double(1.0))]);
464
        assert!(out.contains("Alternate form"), "{out}");
465
    }
466

            
467
    #[test]
468
    fn an_unknown_type_specifier_is_reported() {
469
        let out = run("{v:z}", &[("v", FmtValue::Sint(1))]);
470
        assert!(out.contains("Invalid type specifier"), "{out}");
471
    }
472

            
473
    #[test]
474
    fn unsupported_specs_degrade_to_an_error_string() {
475
        // These are documented `strfmt` gaps; assert they surface as errors
476
        // instead of producing wrong output or panicking.
477
        let zero_pad = run("{v:08}", &[("v", FmtValue::Sint(42))]);
478
        assert!(is_err_str(&zero_pad), "{zero_pad}");
479
        let thousands = run("{v:,}", &[("v", FmtValue::Sint(1000))]);
480
        assert!(thousands.contains("not yet supported"), "{thousands}");
481
    }
482

            
483
    #[test]
484
    fn an_out_of_range_width_or_precision_is_rejected_not_overflowed() {
485
        // 20 nines does not fit in the i64 the spec parser uses.
486
        let w = run("{v:>99999999999999999999}", &[("v", FmtValue::Sint(1))]);
487
        assert!(w.contains("overflow error when parsing width"), "{w}");
488
        let p = run(
489
            "{v:.99999999999999999999}",
490
            &[("v", FmtValue::Str(az("abc")))],
491
        );
492
        assert!(p.contains("overflow error when parsing precision"), "{p}");
493
        // A bare `.` with no digits is malformed.
494
        let d = run("{v:.}", &[("v", FmtValue::Str(az("abc")))]);
495
        assert!(d.contains("missing precision"), "{d}");
496
    }
497

            
498
    // ------------------------------------------------------------------
499
    // fmt_string: unicode
500
    // ------------------------------------------------------------------
501

            
502
    #[test]
503
    fn keys_values_and_literals_may_be_non_ascii() {
504
        assert_eq!(
505
            run(
506
                "こんにちは、{名前}!🦀",
507
                &[("名前", FmtValue::Str(az("世界")))]
508
            ),
509
            "こんにちは、世界!🦀"
510
        );
511
    }
512

            
513
    #[test]
514
    fn width_and_precision_count_chars_not_bytes() {
515
        // A byte-oriented implementation would slice mid-codepoint and panic.
516
        assert_eq!(
517
            run("{v:.2}", &[("v", FmtValue::Str(az("日本語")))]),
518
            "日本",
519
            "precision truncates on a char boundary"
520
        );
521
        assert_eq!(
522
            run("{v:>5}", &[("v", FmtValue::Str(az("日本語")))]),
523
            "  日本語",
524
            "width pads by chars, not bytes"
525
        );
526
    }
527

            
528
    #[test]
529
    fn a_multibyte_fill_char_pads_correctly() {
530
        assert_eq!(run("{v:🦀>4}", &[("v", FmtValue::Str(az("ab")))]), "🦀🦀ab");
531
    }
532

            
533
    #[test]
534
    fn control_and_nul_characters_pass_through_untouched() {
535
        let weird = "a\0b\tc\nd\u{7f}e";
536
        assert_eq!(run(weird, &[]), weird);
537
    }
538

            
539
    // ------------------------------------------------------------------
540
    // fmt_string: string alignment / truncation
541
    // ------------------------------------------------------------------
542

            
543
    #[test]
544
    fn string_alignment_and_truncation_behave_as_specified() {
545
        assert_eq!(run("{v:>8}", &[("v", FmtValue::Str(az("ab")))]), "      ab");
546
        assert_eq!(run("{v:<4}|", &[("v", FmtValue::Str(az("ab")))]), "ab  |");
547
        assert_eq!(run("{v:^6}", &[("v", FmtValue::Str(az("ab")))]), "  ab  ");
548
        assert_eq!(run("{v:.3}", &[("v", FmtValue::Str(az("abcdefg")))]), "abc");
549
        assert_eq!(
550
            run("{v:.0}", &[("v", FmtValue::Str(az("abc")))]),
551
            "",
552
            "zero precision erases the value"
553
        );
554
        assert_eq!(
555
            run("{v:.9}", &[("v", FmtValue::Str(az("abc")))]),
556
            "abc",
557
            "precision longer than the value does not overrun"
558
        );
559
        assert_eq!(
560
            run("{v:>2}", &[("v", FmtValue::Str(az("abcdef")))]),
561
            "abcdef",
562
            "width smaller than the value never truncates"
563
        );
564
    }
565

            
566
    // ------------------------------------------------------------------
567
    // fmt_string: StrVec
568
    // ------------------------------------------------------------------
569

            
570
    #[test]
571
    fn strvec_renders_as_a_bracketed_comma_list() {
572
        assert_eq!(run("{v}", &[("v", FmtValue::StrVec(strvec(&[])))]), "[]");
573
        assert_eq!(
574
            run("{v}", &[("v", FmtValue::StrVec(strvec(&["a"])))]),
575
            "[a]"
576
        );
577
        assert_eq!(
578
            run("{v}", &[("v", FmtValue::StrVec(strvec(&["a", "b", "c"])))]),
579
            "[a, b, c]"
580
        );
581
        assert_eq!(
582
            run("{v}", &[("v", FmtValue::StrVec(strvec(&["", ""])))]),
583
            "[, ]",
584
            "empty members still get a separator"
585
        );
586
    }
587

            
588
    #[test]
589
    fn strvec_applies_the_width_spec_to_every_fragment() {
590
        // KNOWN QUIRK, pinned deliberately: `DisplayStr for StrVec` reuses the
591
        // same `Formatter` for "[", each item and "]", so a width spec pads each
592
        // fragment rather than the list as a whole. 3 fragments * width 10 = 30.
593
        let out = run("{v:>10}", &[("v", FmtValue::StrVec(strvec(&["a"])))]);
594
        assert_eq!(out, "         [         a         ]");
595
        assert_eq!(out.chars().count(), 30);
596
    }
597

            
598
    // ------------------------------------------------------------------
599
    // fmt_string: size / stress
600
    // ------------------------------------------------------------------
601

            
602
    #[test]
603
    fn many_placeholders_do_not_blow_up() {
604
        let format: String = "{k}".repeat(500);
605
        let out = run(&format, &[("k", FmtValue::Uchar(9))]);
606
        assert_eq!(out, "9".repeat(500));
607
    }
608

            
609
    #[test]
610
    fn a_very_long_value_is_substituted_whole() {
611
        let big = "x".repeat(50_000);
612
        let out = run("{v}", &[("v", FmtValue::Str(AzString::from(big.clone())))]);
613
        assert_eq!(out.len(), 50_000);
614
        assert_eq!(out, big);
615
    }
616

            
617
    #[test]
618
    fn a_long_literal_format_string_is_returned_verbatim() {
619
        let big = "y".repeat(100_000);
620
        assert_eq!(
621
            fmt_string(AzString::from(big.clone()), FmtArgVec::new()),
622
            big
623
        );
624
    }
625

            
626
    // ------------------------------------------------------------------
627
    // FmtValue::fmt (Display) — the serializer under test
628
    // ------------------------------------------------------------------
629

            
630
    #[test]
631
    fn display_never_panics_on_any_variant_or_edge_value() {
632
        for v in scalar_variants() {
633
            let _ = v.to_string();
634
        }
635
        let _ = FmtValue::StrVec(strvec(&[])).to_string();
636
        let _ = FmtValue::StrVec(strvec(&["a", "", "🦀"])).to_string();
637
    }
638

            
639
    #[test]
640
    fn display_renders_each_variant_as_its_inner_value() {
641
        assert_eq!(FmtValue::Bool(true).to_string(), "true");
642
        assert_eq!(FmtValue::Bool(false).to_string(), "false");
643
        assert_eq!(FmtValue::Uchar(u8::MAX).to_string(), "255");
644
        assert_eq!(FmtValue::Schar(i8::MIN).to_string(), "-128");
645
        assert_eq!(FmtValue::Sshort(i16::MIN).to_string(), "-32768");
646
        assert_eq!(FmtValue::Ulong(u64::MAX).to_string(), u64::MAX.to_string());
647
        assert_eq!(FmtValue::Slong(i64::MIN).to_string(), i64::MIN.to_string());
648
        assert_eq!(
649
            FmtValue::Usize(usize::MAX).to_string(),
650
            usize::MAX.to_string()
651
        );
652
        assert_eq!(
653
            FmtValue::Isize(isize::MIN).to_string(),
654
            isize::MIN.to_string()
655
        );
656
        assert_eq!(FmtValue::Float(f32::NAN).to_string(), "NaN");
657
        assert_eq!(FmtValue::Double(f64::INFINITY).to_string(), "inf");
658
        assert_eq!(FmtValue::Double(f64::NEG_INFINITY).to_string(), "-inf");
659
    }
660

            
661
    #[test]
662
    fn display_of_a_string_is_unquoted_but_a_strvec_is_debug_quoted() {
663
        // The `Str` arm goes through `str::fmt`, the `StrVec` arm through
664
        // `Vec<&str>::fmt` (Debug) — so quoting differs. Pin both.
665
        assert_eq!(FmtValue::Str(az("a\"b")).to_string(), "a\"b");
666
        assert_eq!(FmtValue::Str(AzString::default()).to_string(), "");
667
        assert_eq!(FmtValue::StrVec(strvec(&[])).to_string(), "[]");
668
        assert_eq!(
669
            FmtValue::StrVec(strvec(&["a", "b"])).to_string(),
670
            "[\"a\", \"b\"]"
671
        );
672
    }
673

            
674
    #[test]
675
    fn display_of_a_strvec_diverges_from_the_strfmt_rendering() {
676
        // Documented divergence: `Display` is Debug-quoted, `DisplayStr` is not.
677
        let v = FmtValue::StrVec(strvec(&["a", "b"]));
678
        assert_ne!(run("{v}", &[("v", v.clone())]), v.to_string());
679
        assert_eq!(run("{v}", &[("v", v)]), "[a, b]");
680
    }
681

            
682
    #[test]
683
    fn display_forwards_width_precision_and_fill_flags() {
684
        assert_eq!(format!("{:>6}", FmtValue::Uint(42)), "    42");
685
        assert_eq!(format!("{:<6}|", FmtValue::Uint(42)), "42    |");
686
        assert_eq!(format!("{:0>6}", FmtValue::Uint(42)), "000042");
687
        assert_eq!(format!("{:>6}", FmtValue::Str(az("ab"))), "    ab");
688
        assert_eq!(
689
            format!("{:.2}", FmtValue::Double(2.0 / 3.0)),
690
            format!("{:.2}", 2.0_f64 / 3.0)
691
        );
692
    }
693

            
694
    #[test]
695
    fn debug_is_variant_tagged() {
696
        assert_eq!(format!("{:?}", FmtValue::Uint(1)), "Uint(1)");
697
        assert_eq!(format!("{:?}", FmtValue::Bool(false)), "Bool(false)");
698
    }
699

            
700
    // ------------------------------------------------------------------
701
    // Derived predicates: PartialEq / PartialOrd / Clone
702
    // ------------------------------------------------------------------
703

            
704
    #[test]
705
    fn nan_breaks_reflexive_equality_and_has_no_ordering() {
706
        let nan = FmtValue::Double(f64::NAN);
707
        assert_ne!(nan, nan.clone(), "NaN must not compare equal to itself");
708
        assert_eq!(nan.partial_cmp(&nan.clone()), None);
709
        assert_eq!(
710
            FmtValue::Float(f32::NAN).partial_cmp(&FmtValue::Float(1.0)),
711
            None
712
        );
713
    }
714

            
715
    #[test]
716
    fn equality_and_ordering_discriminate_between_variants() {
717
        assert_eq!(FmtValue::Uint(1), FmtValue::Uint(1));
718
        assert_ne!(
719
            FmtValue::Uint(1),
720
            FmtValue::Sint(1),
721
            "same numeric value, different variant"
722
        );
723
        // Derived PartialOrd compares the discriminant first.
724
        assert!(FmtValue::Bool(true) < FmtValue::Uchar(0));
725
        assert!(FmtValue::Uchar(1) > FmtValue::Uchar(0));
726
        assert!(FmtValue::Double(f64::NEG_INFINITY) < FmtValue::Double(f64::MIN));
727
    }
728

            
729
    #[test]
730
    fn cloning_an_arg_vec_preserves_equality_and_survives_a_double_drop() {
731
        let args = FmtArgVec::from_vec(vec![
732
            FmtArg {
733
                key: az("a"),
734
                value: FmtValue::Str(az("one")),
735
            },
736
            FmtArg {
737
                key: az("b"),
738
                value: FmtValue::StrVec(strvec(&["x", "y"])),
739
            },
740
        ]);
741
        let copy = args.clone();
742
        assert_eq!(args, copy);
743
        assert_eq!(
744
            fmt_string(az("{a}{b}"), args),
745
            fmt_string(az("{a}{b}"), copy.clone()),
746
            "a clone must format identically to its source"
747
        );
748
        drop(copy); // both the original and the clone are dropped: no double free
749
    }
750
}