1
//! CSS Counter Support
2
//!
3
//! Implements CSS counters for ordered lists and generated content as per CSS spec.
4
//! Counters are cached per-node in the `LayoutCache` and computed during layout traversal.
5
//!
6
//! This module is the single canonical home for numbering-system formatting
7
//! (decimal, roman, alphabetic, greek). The low-level converters
8
//! [`to_roman`], [`to_alphabetic`], and [`to_greek`] back both [`format_counter`]
9
//! (list markers) and `super::pagination::CounterFormat` (paged-media page counters),
10
//! so the same number renders identically in both contexts.
11

            
12
use alloc::string::String;
13

            
14
use azul_css::props::style::lists::StyleListStyleType;
15

            
16
/// Formats a counter value into a string based on the list style type.
17
///
18
/// Implements CSS counter styles for various numbering systems.
19
#[must_use]
20
2244
pub fn format_counter(value: i32, style: StyleListStyleType) -> String {
21
2244
    match style {
22
88
        StyleListStyleType::None => String::new(),
23
593
        StyleListStyleType::Disc => "•".to_string(),
24
80
        StyleListStyleType::Circle => "◦".to_string(),
25
80
        StyleListStyleType::Square => "▪".to_string(),
26
161
        StyleListStyleType::Decimal => value.to_string(),
27
136
        StyleListStyleType::DecimalLeadingZero => format!("{value:02}"),
28
        StyleListStyleType::LowerAlpha => {
29
200
            decimal_fallback(value, with_sign(value, |n| to_alphabetic(n, false)))
30
        }
31
        StyleListStyleType::UpperAlpha => {
32
138
            decimal_fallback(value, with_sign(value, |n| to_alphabetic(n, true)))
33
        }
34
412
        StyleListStyleType::LowerRoman => with_sign(value, |n| to_roman(n, false)),
35
148
        StyleListStyleType::UpperRoman => with_sign(value, |n| to_roman(n, true)),
36
        StyleListStyleType::LowerGreek => {
37
119
            decimal_fallback(value, with_sign(value, |n| to_greek(n, false)))
38
        }
39
        StyleListStyleType::UpperGreek => {
40
89
            decimal_fallback(value, with_sign(value, |n| to_greek(n, true)))
41
        }
42
    }
43
2244
}
44

            
45
/// CSS fallback: when an alphabetic/greek counter style cannot represent a value
46
/// (e.g. `value == 0`, where `to_alphabetic`/`to_greek` yield an empty string), the
47
/// spec falls back to `decimal` so the marker is never blank.
48
567
fn decimal_fallback(value: i32, formatted: String) -> String {
49
567
    if formatted.is_empty() {
50
52
        value.to_string()
51
    } else {
52
515
        formatted
53
    }
54
567
}
55

            
56
// --- Formatting Helpers ---
57

            
58
/// Formats the magnitude of `value`, prefixing `-` for negatives.
59
///
60
/// Avoids the lossy `value as u32` cast: a negative counter such as `-3` in
61
/// `lower-roman` formats as `-iii` instead of wrapping to a huge unsigned value.
62
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // bounded graphics/coord/
63
                                                                   // counter/fixed-point cast
64
1136
fn with_sign<F: Fn(usize) -> String>(value: i32, format: F) -> String {
65
1136
    if value < 0 {
66
190
        let magnitude = i64::from(value).unsigned_abs() as usize;
67
190
        format!("-{}", format(magnitude))
68
    } else {
69
946
        format(value as usize)
70
    }
71
1136
}
72

            
73
/// Converts a number to alphabetic representation (a, b, c, ..., z, aa, ab, ...).
74
///
75
/// This implements the CSS `lower-alpha` and `upper-alpha` counter styles.
76
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/counter/fixed-point cast
77
20394
pub(crate) fn to_alphabetic(mut num: usize, uppercase: bool) -> String {
78
20394
    if num == 0 {
79
25
        return String::new();
80
20369
    }
81

            
82
20369
    let mut result = String::new();
83
20369
    let base = if uppercase { b'A' } else { b'a' };
84

            
85
76035
    while num > 0 {
86
55666
        let remainder = ((num - 1) % 26) as u8;
87
55666
        result.insert(0, (base + remainder) as char);
88
55666
        num = (num - 1) / 26;
89
55666
    }
90

            
91
20369
    result
92
20394
}
93

            
94
/// Converts a number to Roman numeral representation.
95
///
96
/// This implements the CSS `lower-roman` and `upper-roman` counter styles.
97
16608
pub(crate) fn to_roman(mut num: usize, uppercase: bool) -> String {
98
    const MAX_ROMAN: usize = 3999;
99
16608
    if num == 0 {
100
24
        return "0".to_string();
101
16584
    }
102
16584
    if num > MAX_ROMAN {
103
        // Roman numerals traditionally don't go beyond 3999
104
73
        return num.to_string();
105
16511
    }
106

            
107
16511
    let numerals = [
108
16511
        (1000, "m"),
109
16511
        (900, "cm"),
110
16511
        (500, "d"),
111
16511
        (400, "cd"),
112
16511
        (100, "c"),
113
16511
        (90, "xc"),
114
16511
        (50, "l"),
115
16511
        (40, "xl"),
116
16511
        (10, "x"),
117
16511
        (9, "ix"),
118
16511
        (5, "v"),
119
16511
        (4, "iv"),
120
16511
        (1, "i"),
121
16511
    ];
122

            
123
16511
    let mut result = String::new();
124
231154
    for (value, numeral) in &numerals {
125
326130
        while num >= *value {
126
111487
            result.push_str(numeral);
127
111487
            num -= value;
128
111487
        }
129
    }
130

            
131
16511
    if uppercase {
132
8132
        result.to_uppercase()
133
    } else {
134
8379
        result
135
    }
136
16608
}
137

            
138
/// Converts a number to Greek letter representation.
139
///
140
/// This implements the CSS `lower-greek` and `upper-greek` counter styles.
141
/// Supports α, β, γ, ... (24 letters). For numbers > 24, wraps as αα, αβ, etc.
142
14236
pub(crate) fn to_greek(num: usize, uppercase: bool) -> String {
143
    const GREEK_LOWER: &[char] = &[
144
        'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'ο', 'π', 'ρ', 'σ',
145
        'τ', 'υ', 'φ', 'χ', 'ψ', 'ω',
146
    ];
147
    const GREEK_UPPER: &[char] = &[
148
        'Α', 'Β', 'Γ', 'Δ', 'Ε', 'Ζ', 'Η', 'Θ', 'Ι', 'Κ', 'Λ', 'Μ', 'Ν', 'Ξ', 'Ο', 'Π', 'Ρ', 'Σ',
149
        'Τ', 'Υ', 'Φ', 'Χ', 'Ψ', 'Ω',
150
    ];
151

            
152
14236
    if num == 0 {
153
22
        return String::new();
154
14214
    }
155

            
156
14214
    let letters = if uppercase { GREEK_UPPER } else { GREEK_LOWER };
157

            
158
14214
    if num <= letters.len() {
159
219
        return letters[num - 1].to_string();
160
13995
    }
161

            
162
13995
    let mut result = String::new();
163
13995
    let mut remaining = num;
164
53773
    while remaining > 0 {
165
39778
        remaining -= 1;
166
39778
        result.insert(0, letters[remaining % letters.len()]);
167
39778
        remaining /= letters.len();
168
39778
    }
169
13995
    result
170
14236
}
171

            
172
#[cfg(test)]
173
#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
174
mod autotest_generated {
175
    use super::*;
176

            
177
    // ------------------------------------------------------------------
178
    // Fixtures / helpers
179
    // ------------------------------------------------------------------
180

            
181
    /// Every variant of the enum under test — used for "no panic on any style"
182
    /// sweeps.
183
    const ALL_STYLES: [StyleListStyleType; 12] = [
184
        StyleListStyleType::None,
185
        StyleListStyleType::Disc,
186
        StyleListStyleType::Circle,
187
        StyleListStyleType::Square,
188
        StyleListStyleType::Decimal,
189
        StyleListStyleType::DecimalLeadingZero,
190
        StyleListStyleType::LowerRoman,
191
        StyleListStyleType::UpperRoman,
192
        StyleListStyleType::LowerGreek,
193
        StyleListStyleType::UpperGreek,
194
        StyleListStyleType::LowerAlpha,
195
        StyleListStyleType::UpperAlpha,
196
    ];
197

            
198
    /// Adversarial `i32` inputs: the saturation points, the sign boundary, and
199
    /// the roman-numeral cliff at 3999/4000.
200
    const EDGE_VALUES: [i32; 12] = [
201
        i32::MIN,
202
        i32::MIN + 1,
203
        -4000,
204
        -3999,
205
        -27,
206
        -1,
207
        0,
208
        1,
209
        26,
210
        3999,
211
        4000,
212
        i32::MAX,
213
    ];
214

            
215
    const GREEK_LOWER_LETTERS: [char; 24] = [
216
        'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'ο', 'π', 'ρ', 'σ',
217
        'τ', 'υ', 'φ', 'χ', 'ψ', 'ω',
218
    ];
219
    const GREEK_UPPER_LETTERS: [char; 24] = [
220
        'Α', 'Β', 'Γ', 'Δ', 'Ε', 'Ζ', 'Η', 'Θ', 'Ι', 'Κ', 'Λ', 'Μ', 'Ν', 'Ξ', 'Ο', 'Π', 'Ρ', 'Σ',
221
        'Τ', 'Υ', 'Φ', 'Χ', 'Ψ', 'Ω',
222
    ];
223

            
224
    /// Independent decoder for the bijective base-26 alphabetic system.
225
    /// Returns `None` if `s` contains a character outside the expected case.
226
    fn decode_alphabetic(s: &str, uppercase: bool) -> Option<u128> {
227
        if s.is_empty() {
228
            return None;
229
        }
230
        let base = if uppercase { b'A' } else { b'a' };
231
        let mut acc: u128 = 0;
232
        for b in s.bytes() {
233
            if b < base || b >= base + 26 {
234
                return None;
235
            }
236
            acc = acc * 26 + u128::from(b - base + 1);
237
        }
238
        Some(acc)
239
    }
240

            
241
    /// Independent decoder for the bijective base-24 greek system.
242
    fn decode_greek(s: &str, uppercase: bool) -> Option<u128> {
243
        let letters = if uppercase {
244
            &GREEK_UPPER_LETTERS
245
        } else {
246
            &GREEK_LOWER_LETTERS
247
        };
248
        if s.is_empty() {
249
            return None;
250
        }
251
        let mut acc: u128 = 0;
252
        for c in s.chars() {
253
            let idx = letters.iter().position(|l| *l == c)?;
254
            acc = acc * 24 + (idx as u128 + 1);
255
        }
256
        Some(acc)
257
    }
258

            
259
    /// Independent subtractive-notation roman decoder.
260
    fn decode_roman(s: &str) -> Option<u32> {
261
        fn digit(c: char) -> Option<i64> {
262
            match c {
263
                'i' => Some(1),
264
                'v' => Some(5),
265
                'x' => Some(10),
266
                'l' => Some(50),
267
                'c' => Some(100),
268
                'd' => Some(500),
269
                'm' => Some(1000),
270
                _ => None,
271
            }
272
        }
273
        if s.is_empty() {
274
            return None;
275
        }
276
        let digits: Option<Vec<i64>> = s.chars().map(digit).collect();
277
        let digits = digits?;
278
        // Accumulate signed: subtractive pairs go negative before the following
279
        // larger numeral is added, so an unsigned accumulator would underflow.
280
        let mut total: i64 = 0;
281
        for (i, d) in digits.iter().enumerate() {
282
            // A smaller numeral placed before a larger one is subtractive.
283
            if digits[i + 1..].iter().any(|next| next > d) {
284
                total -= *d;
285
            } else {
286
                total += *d;
287
            }
288
        }
289
        u32::try_from(total).ok()
290
    }
291

            
292
    // ------------------------------------------------------------------
293
    // to_alphabetic — numeric: zero / min_max / overflow / round-trip
294
    // ------------------------------------------------------------------
295

            
296
    #[test]
297
    fn to_alphabetic_zero_is_empty_not_a_panic() {
298
        // 0 is not representable in a bijective base — the function signals this
299
        // with an empty string (the caller is expected to `decimal_fallback`).
300
        assert_eq!(to_alphabetic(0, false), "");
301
        assert_eq!(to_alphabetic(0, true), "");
302
    }
303

            
304
    #[test]
305
    fn to_alphabetic_known_values() {
306
        assert_eq!(to_alphabetic(1, false), "a");
307
        assert_eq!(to_alphabetic(26, false), "z");
308
        // The carry boundary: 27 must roll over to two letters, not wrap to "a".
309
        assert_eq!(to_alphabetic(27, false), "aa");
310
        assert_eq!(to_alphabetic(28, false), "ab");
311
        assert_eq!(to_alphabetic(52, false), "az");
312
        assert_eq!(to_alphabetic(53, false), "ba");
313
        assert_eq!(to_alphabetic(702, false), "zz");
314
        assert_eq!(to_alphabetic(703, false), "aaa");
315
    }
316

            
317
    #[test]
318
    fn to_alphabetic_uppercase_only_shifts_case() {
319
        for n in 1..=1000usize {
320
            let lower = to_alphabetic(n, false);
321
            let upper = to_alphabetic(n, true);
322
            assert_eq!(upper, lower.to_uppercase(), "case mismatch at {n}");
323
            assert!(
324
                upper.bytes().all(|b| b.is_ascii_uppercase()),
325
                "non-uppercase byte at {n}: {upper}"
326
            );
327
            assert!(
328
                lower.bytes().all(|b| b.is_ascii_lowercase()),
329
                "non-lowercase byte at {n}: {lower}"
330
            );
331
        }
332
    }
333

            
334
    #[test]
335
    fn to_alphabetic_round_trips_through_an_independent_decoder() {
336
        for n in 1..=5000u128 {
337
            for uppercase in [false, true] {
338
                let encoded = to_alphabetic(n as usize, uppercase);
339
                assert_eq!(
340
                    decode_alphabetic(&encoded, uppercase),
341
                    Some(n),
342
                    "round-trip failed for {n} (uppercase={uppercase}) -> {encoded}"
343
                );
344
            }
345
        }
346
    }
347

            
348
    /// Asserts that no two inputs in `markers` produced the same string.
349
    fn assert_all_distinct(markers: &[String], what: &str) {
350
        let mut sorted: Vec<&String> = markers.iter().collect();
351
        sorted.sort();
352
        for pair in sorted.windows(2) {
353
            assert_ne!(pair[0], pair[1], "duplicate {what} marker: {}", pair[0]);
354
        }
355
    }
356

            
357
    #[test]
358
    fn to_alphabetic_is_injective() {
359
        // Two different counters must never render the same marker.
360
        let markers: Vec<String> = (1..=2000usize).map(|n| to_alphabetic(n, false)).collect();
361
        assert_all_distinct(&markers, "alphabetic");
362
    }
363

            
364
    #[test]
365
    fn to_alphabetic_usize_max_terminates_and_stays_ascii() {
366
        // `num = (num - 1) / 26` strictly decreases, so this must terminate;
367
        // the `base + remainder` byte add must not overflow past 'z'/'Z'.
368
        let lower = to_alphabetic(usize::MAX, false);
369
        let upper = to_alphabetic(usize::MAX, true);
370
        assert!(!lower.is_empty());
371
        assert!(lower.bytes().all(|b: u8| b.is_ascii_lowercase()));
372
        assert!(upper.bytes().all(|b: u8| b.is_ascii_uppercase()));
373
        // The extreme still encodes *exactly* — no digit dropped, no wrap.
374
        assert_eq!(decode_alphabetic(&lower, false), Some(usize::MAX as u128));
375
        assert_eq!(decode_alphabetic(&upper, true), Some(usize::MAX as u128));
376
        assert_eq!(lower.len(), upper.len());
377
    }
378

            
379
    #[test]
380
    fn to_alphabetic_magnitude_of_i32_min_does_not_panic() {
381
        // The magnitude that `with_sign` hands over for i32::MIN.
382
        let magnitude = 2_147_483_648usize;
383
        let s = to_alphabetic(magnitude, false);
384
        assert!(!s.is_empty());
385
        assert_eq!(decode_alphabetic(&s, false), Some(magnitude as u128));
386
    }
387

            
388
    // ------------------------------------------------------------------
389
    // to_roman — numeric: zero / limits / overflow / round-trip
390
    // ------------------------------------------------------------------
391

            
392
    #[test]
393
    fn to_roman_zero_falls_back_to_decimal_zero() {
394
        // Roman has no zero; the impl emits "0" rather than an empty marker.
395
        assert_eq!(to_roman(0, false), "0");
396
        assert_eq!(to_roman(0, true), "0");
397
    }
398

            
399
    #[test]
400
    fn to_roman_known_values() {
401
        assert_eq!(to_roman(1, false), "i");
402
        assert_eq!(to_roman(4, false), "iv");
403
        assert_eq!(to_roman(9, false), "ix");
404
        assert_eq!(to_roman(14, false), "xiv");
405
        assert_eq!(to_roman(40, false), "xl");
406
        assert_eq!(to_roman(90, false), "xc");
407
        assert_eq!(to_roman(400, false), "cd");
408
        assert_eq!(to_roman(900, false), "cm");
409
        assert_eq!(to_roman(1990, false), "mcmxc");
410
        assert_eq!(to_roman(2024, false), "mmxxiv");
411
        assert_eq!(to_roman(3999, false), "mmmcmxcix");
412
        assert_eq!(to_roman(2024, true), "MMXXIV");
413
        assert_eq!(to_roman(3999, true), "MMMCMXCIX");
414
    }
415

            
416
    #[test]
417
    fn to_roman_at_and_past_the_3999_cliff() {
418
        // 3999 is the last representable numeral...
419
        assert_eq!(to_roman(3999, false), "mmmcmxcix");
420
        // ...and 4000 must degrade to decimal instead of emitting "mmmm" or
421
        // looping forever.
422
        assert_eq!(to_roman(4000, false), "4000");
423
        assert_eq!(to_roman(4000, true), "4000");
424
        assert_eq!(to_roman(4001, false), "4001");
425
    }
426

            
427
    #[test]
428
    fn to_roman_usize_max_degrades_to_decimal() {
429
        assert_eq!(to_roman(usize::MAX, false), usize::MAX.to_string());
430
        assert_eq!(to_roman(usize::MAX, true), usize::MAX.to_string());
431
        // The i32::MIN magnitude handed over by `with_sign`.
432
        assert_eq!(to_roman(2_147_483_648, false), "2147483648");
433
    }
434

            
435
    #[test]
436
    fn to_roman_round_trips_over_the_whole_representable_range() {
437
        for n in 1..=3999u32 {
438
            let lower = to_roman(n as usize, false);
439
            let upper = to_roman(n as usize, true);
440
            assert_eq!(
441
                decode_roman(&lower),
442
                Some(n),
443
                "round-trip failed for {n} -> {lower}"
444
            );
445
            assert_eq!(upper, lower.to_uppercase(), "case mismatch at {n}");
446
            // No numeral may repeat more than 3 times in a row (mmm is the max).
447
            assert!(
448
                !lower.contains("iiii")
449
                    && !lower.contains("xxxx")
450
                    && !lower.contains("cccc")
451
                    && !lower.contains("mmmm"),
452
                "malformed numeral at {n}: {lower}"
453
            );
454
            assert!(lower.bytes().all(|b| b"ivxlcdm".contains(&b)));
455
        }
456
    }
457

            
458
    // ------------------------------------------------------------------
459
    // to_greek — numeric + unicode: zero / wrap / round-trip
460
    // ------------------------------------------------------------------
461

            
462
    #[test]
463
    fn to_greek_zero_is_empty_not_a_panic() {
464
        assert_eq!(to_greek(0, false), "");
465
        assert_eq!(to_greek(0, true), "");
466
    }
467

            
468
    #[test]
469
    fn to_greek_known_values_and_wrap_boundary() {
470
        assert_eq!(to_greek(1, false), "α");
471
        assert_eq!(to_greek(2, false), "β");
472
        assert_eq!(to_greek(24, false), "ω");
473
        // 24 letters, then the documented wrap to two letters.
474
        assert_eq!(to_greek(25, false), "αα");
475
        assert_eq!(to_greek(26, false), "αβ");
476
        assert_eq!(to_greek(48, false), "αω");
477
        assert_eq!(to_greek(49, false), "βα");
478
        assert_eq!(to_greek(1, true), "Α");
479
        assert_eq!(to_greek(24, true), "Ω");
480
        assert_eq!(to_greek(25, true), "ΑΑ");
481
    }
482

            
483
    #[test]
484
    fn to_greek_emits_multibyte_chars_without_slicing_bugs() {
485
        // Each greek letter is 2 bytes in UTF-8: byte len must be 2x char count,
486
        // and the string must survive a full char walk (i.e. `insert(0, ..)` never
487
        // split a code point).
488
        let s = to_greek(25, false);
489
        assert_eq!(s.chars().count(), 2);
490
        assert_eq!(s.len(), 4);
491
        assert!(s.chars().all(|c| GREEK_LOWER_LETTERS.contains(&c)));
492
        assert!(s.is_char_boundary(0) && s.is_char_boundary(2) && s.is_char_boundary(4));
493
    }
494

            
495
    #[test]
496
    fn to_greek_round_trips_through_an_independent_decoder() {
497
        for n in 1..=5000u128 {
498
            for uppercase in [false, true] {
499
                let encoded = to_greek(n as usize, uppercase);
500
                assert_eq!(
501
                    decode_greek(&encoded, uppercase),
502
                    Some(n),
503
                    "round-trip failed for {n} (uppercase={uppercase}) -> {encoded}"
504
                );
505
            }
506
        }
507
    }
508

            
509
    #[test]
510
    fn to_greek_is_injective() {
511
        let markers: Vec<String> = (1..=2000usize).map(|n| to_greek(n, true)).collect();
512
        assert_all_distinct(&markers, "greek");
513
    }
514

            
515
    #[test]
516
    fn to_greek_usize_max_terminates_and_stays_in_the_alphabet() {
517
        // `remaining = (remaining - 1) / 24` strictly decreases -> must terminate.
518
        let lower = to_greek(usize::MAX, false);
519
        let upper = to_greek(usize::MAX, true);
520
        assert!(!lower.is_empty());
521
        assert!(lower.chars().all(|c| GREEK_LOWER_LETTERS.contains(&c)));
522
        assert!(upper.chars().all(|c| GREEK_UPPER_LETTERS.contains(&c)));
523
        // The extreme still encodes *exactly* — no letter dropped, no wrap.
524
        assert_eq!(decode_greek(&lower, false), Some(usize::MAX as u128));
525
        assert_eq!(decode_greek(&upper, true), Some(usize::MAX as u128));
526
        assert_eq!(lower.chars().count(), upper.chars().count());
527
    }
528

            
529
    // ------------------------------------------------------------------
530
    // with_sign — numeric: sign handling, no lossy unsigned wrap
531
    // ------------------------------------------------------------------
532

            
533
    #[test]
534
    fn with_sign_passes_the_magnitude_not_a_wrapped_cast() {
535
        // The whole point of `with_sign`: -3 must hand `3` to the formatter,
536
        // NOT `(-3 as u32) == 4294967293`.
537
        assert_eq!(with_sign(-3, |n| n.to_string()), "-3");
538
        assert_eq!(with_sign(-1, |n| n.to_string()), "-1");
539
        assert_eq!(with_sign(0, |n| n.to_string()), "0");
540
        assert_eq!(with_sign(1, |n| n.to_string()), "1");
541
        assert_eq!(with_sign(i32::MAX, |n| n.to_string()), "2147483647");
542
    }
543

            
544
    #[test]
545
    fn with_sign_handles_i32_min_without_overflow() {
546
        // `-i32::MIN` overflows i32 — the impl must widen to i64 first.
547
        assert_eq!(with_sign(i32::MIN, |n| n.to_string()), "-2147483648");
548
        assert_eq!(with_sign(i32::MIN + 1, |n| n.to_string()), "-2147483647");
549
    }
550

            
551
    #[test]
552
    fn with_sign_zero_is_unsigned() {
553
        // 0 is not negative, so no "-0" marker may be produced.
554
        let s = with_sign(0, |n| to_alphabetic(n, false));
555
        assert!(!s.starts_with('-'), "produced a signed zero: {s}");
556
        assert_eq!(s, "");
557
    }
558

            
559
    #[test]
560
    fn with_sign_prefixes_exactly_one_minus() {
561
        for v in [-1, -26, -3999, -4000, i32::MIN] {
562
            let s = with_sign(v, |n| to_roman(n, false));
563
            assert!(s.starts_with('-'), "missing sign for {v}: {s}");
564
            assert_eq!(s.matches('-').count(), 1, "double sign for {v}: {s}");
565
            assert!(s.len() > 1, "sign with no magnitude for {v}");
566
        }
567
    }
568

            
569
    #[test]
570
    fn with_sign_is_transparent_to_the_formatter_output() {
571
        // A formatter returning an empty string yields just the sign — the sign is
572
        // never swallowed (`decimal_fallback` is what rescues the empty case).
573
        assert_eq!(with_sign(-5, |_| String::new()), "-");
574
        assert_eq!(with_sign(5, |_| String::new()), "");
575
        // Unicode from the formatter passes through byte-for-byte.
576
        assert_eq!(with_sign(-5, |_| "αβγ".to_string()), "-αβγ");
577
    }
578

            
579
    #[test]
580
    fn with_sign_negation_is_symmetric_across_the_range() {
581
        for v in [1i32, 2, 26, 27, 3999, 4000, i32::MAX] {
582
            let pos = with_sign(v, |n| to_alphabetic(n, false));
583
            let neg = with_sign(-v, |n| to_alphabetic(n, false));
584
            assert_eq!(neg, format!("-{pos}"), "asymmetric at {v}");
585
        }
586
    }
587

            
588
    // ------------------------------------------------------------------
589
    // decimal_fallback — numeric: the "never blank" invariant
590
    // ------------------------------------------------------------------
591

            
592
    #[test]
593
    fn decimal_fallback_replaces_empty_with_decimal() {
594
        assert_eq!(decimal_fallback(0, String::new()), "0");
595
        assert_eq!(decimal_fallback(-1, String::new()), "-1");
596
        assert_eq!(decimal_fallback(i32::MAX, String::new()), "2147483647");
597
        assert_eq!(decimal_fallback(i32::MIN, String::new()), "-2147483648");
598
    }
599

            
600
    #[test]
601
    fn decimal_fallback_passes_non_empty_through_untouched() {
602
        // Even a "wrong looking" formatted value is preserved: the fallback keys
603
        // off emptiness only, never off the numeric value.
604
        assert_eq!(decimal_fallback(5, "a".to_string()), "a");
605
        assert_eq!(decimal_fallback(0, "z".to_string()), "z");
606
        assert_eq!(decimal_fallback(0, "α".to_string()), "α");
607
        // Whitespace is NOT empty -> not replaced.
608
        assert_eq!(decimal_fallback(7, " ".to_string()), " ");
609
        // A lone NUL byte counts as non-empty too.
610
        assert_eq!(decimal_fallback(7, "\0".to_string()), "\0");
611
    }
612

            
613
    #[test]
614
    fn decimal_fallback_output_is_never_blank_for_any_i32() {
615
        for v in EDGE_VALUES {
616
            assert!(
617
                !decimal_fallback(v, String::new()).is_empty(),
618
                "blank marker for {v}"
619
            );
620
        }
621
    }
622

            
623
    // ------------------------------------------------------------------
624
    // format_counter — serializer: no panic, well-formed, spec-shaped
625
    // ------------------------------------------------------------------
626

            
627
    #[test]
628
    fn format_counter_no_panic_on_edge_values_for_every_style() {
629
        for style in ALL_STYLES {
630
            for v in EDGE_VALUES {
631
                let s = format_counter(v, style);
632
                if style == StyleListStyleType::None {
633
                    assert!(s.is_empty(), "`none` must render nothing, got {s:?}");
634
                } else {
635
                    // The core CSS invariant: a marker is never blank.
636
                    assert!(!s.is_empty(), "blank marker for {v} in {style:?}");
637
                    // ...and never blank-looking either.
638
                    assert!(
639
                        !s.chars().all(char::is_whitespace),
640
                        "whitespace-only marker for {v} in {style:?}"
641
                    );
642
                }
643
            }
644
        }
645
    }
646

            
647
    #[test]
648
    fn format_counter_is_deterministic() {
649
        for style in ALL_STYLES {
650
            for v in EDGE_VALUES {
651
                assert_eq!(format_counter(v, style), format_counter(v, style));
652
            }
653
        }
654
    }
655

            
656
    #[test]
657
    fn format_counter_default_style_is_disc_and_ignores_the_value() {
658
        assert_eq!(format_counter(0, StyleListStyleType::default()), "•");
659
        for v in EDGE_VALUES {
660
            assert_eq!(format_counter(v, StyleListStyleType::default()), "•");
661
        }
662
    }
663

            
664
    #[test]
665
    fn format_counter_bullet_styles_ignore_the_value() {
666
        for (style, expected) in [
667
            (StyleListStyleType::Disc, "•"),
668
            (StyleListStyleType::Circle, "◦"),
669
            (StyleListStyleType::Square, "▪"),
670
        ] {
671
            for v in EDGE_VALUES {
672
                let s = format_counter(v, style);
673
                assert_eq!(s, expected, "bullet changed with value {v}");
674
                assert_eq!(s.chars().count(), 1);
675
            }
676
        }
677
    }
678

            
679
    #[test]
680
    fn format_counter_decimal_matches_i32_display() {
681
        for v in EDGE_VALUES {
682
            assert_eq!(
683
                format_counter(v, StyleListStyleType::Decimal),
684
                v.to_string()
685
            );
686
        }
687
    }
688

            
689
    #[test]
690
    fn format_counter_decimal_leading_zero_pads_single_digits() {
691
        assert_eq!(
692
            format_counter(0, StyleListStyleType::DecimalLeadingZero),
693
            "00"
694
        );
695
        assert_eq!(
696
            format_counter(5, StyleListStyleType::DecimalLeadingZero),
697
            "05"
698
        );
699
        assert_eq!(
700
            format_counter(9, StyleListStyleType::DecimalLeadingZero),
701
            "09"
702
        );
703
        assert_eq!(
704
            format_counter(10, StyleListStyleType::DecimalLeadingZero),
705
            "10"
706
        );
707
        assert_eq!(
708
            format_counter(100, StyleListStyleType::DecimalLeadingZero),
709
            "100"
710
        );
711
        assert_eq!(
712
            format_counter(i32::MAX, StyleListStyleType::DecimalLeadingZero),
713
            "2147483647"
714
        );
715
    }
716

            
717
    #[test]
718
    fn format_counter_decimal_leading_zero_negative_current_behavior() {
719
        // NOTE (reported, not weakened): `format!("{value:02}")` pads the *total*
720
        // width including the sign, so -5 renders as "-5". CSS
721
        // `decimal-leading-zero` pads the digits only, i.e. "-05". This test pins
722
        // the current behavior so the deviation is visible if/when it is fixed.
723
        assert_eq!(
724
            format_counter(-5, StyleListStyleType::DecimalLeadingZero),
725
            "-5"
726
        );
727
        assert_eq!(
728
            format_counter(i32::MIN, StyleListStyleType::DecimalLeadingZero),
729
            "-2147483648"
730
        );
731
    }
732

            
733
    #[test]
734
    fn format_counter_alpha_known_values_and_zero_fallback() {
735
        assert_eq!(format_counter(1, StyleListStyleType::LowerAlpha), "a");
736
        assert_eq!(format_counter(26, StyleListStyleType::LowerAlpha), "z");
737
        assert_eq!(format_counter(27, StyleListStyleType::LowerAlpha), "aa");
738
        assert_eq!(format_counter(1, StyleListStyleType::UpperAlpha), "A");
739
        assert_eq!(format_counter(27, StyleListStyleType::UpperAlpha), "AA");
740
        // 0 has no alphabetic representation -> decimal fallback, not a blank.
741
        assert_eq!(format_counter(0, StyleListStyleType::LowerAlpha), "0");
742
        assert_eq!(format_counter(0, StyleListStyleType::UpperAlpha), "0");
743
        // Negatives keep the sign instead of wrapping to a giant unsigned value.
744
        assert_eq!(format_counter(-1, StyleListStyleType::LowerAlpha), "-a");
745
        assert_eq!(format_counter(-3, StyleListStyleType::UpperAlpha), "-C");
746
    }
747

            
748
    #[test]
749
    fn format_counter_roman_known_values_and_limits() {
750
        assert_eq!(format_counter(1, StyleListStyleType::LowerRoman), "i");
751
        assert_eq!(format_counter(4, StyleListStyleType::LowerRoman), "iv");
752
        assert_eq!(
753
            format_counter(2024, StyleListStyleType::UpperRoman),
754
            "MMXXIV"
755
        );
756
        assert_eq!(
757
            format_counter(3999, StyleListStyleType::LowerRoman),
758
            "mmmcmxcix"
759
        );
760
        // Past the roman range -> decimal, never an unbounded "mmmm..." string.
761
        assert_eq!(format_counter(4000, StyleListStyleType::LowerRoman), "4000");
762
        assert_eq!(format_counter(4000, StyleListStyleType::UpperRoman), "4000");
763
        // No roman zero.
764
        assert_eq!(format_counter(0, StyleListStyleType::LowerRoman), "0");
765
        assert_eq!(format_counter(0, StyleListStyleType::UpperRoman), "0");
766
        assert_eq!(format_counter(-3, StyleListStyleType::LowerRoman), "-iii");
767
        assert_eq!(format_counter(-14, StyleListStyleType::UpperRoman), "-XIV");
768
    }
769

            
770
    #[test]
771
    fn format_counter_roman_at_i32_min_matches_signed_decimal() {
772
        // The magnitude of i32::MIN is far past MAX_ROMAN, so the marker degrades
773
        // to decimal — and must equal the plain decimal rendering, i.e. the
774
        // `unsigned_abs` widening must not have wrapped.
775
        assert_eq!(
776
            format_counter(i32::MIN, StyleListStyleType::LowerRoman),
777
            "-2147483648"
778
        );
779
        assert_eq!(
780
            format_counter(i32::MIN, StyleListStyleType::LowerRoman),
781
            format_counter(i32::MIN, StyleListStyleType::Decimal)
782
        );
783
    }
784

            
785
    #[test]
786
    fn format_counter_greek_known_values_and_zero_fallback() {
787
        assert_eq!(format_counter(1, StyleListStyleType::LowerGreek), "α");
788
        assert_eq!(format_counter(24, StyleListStyleType::LowerGreek), "ω");
789
        assert_eq!(format_counter(25, StyleListStyleType::LowerGreek), "αα");
790
        assert_eq!(format_counter(1, StyleListStyleType::UpperGreek), "Α");
791
        assert_eq!(format_counter(24, StyleListStyleType::UpperGreek), "Ω");
792
        // 0 -> decimal fallback, not a blank marker.
793
        assert_eq!(format_counter(0, StyleListStyleType::LowerGreek), "0");
794
        assert_eq!(format_counter(0, StyleListStyleType::UpperGreek), "0");
795
        assert_eq!(format_counter(-2, StyleListStyleType::LowerGreek), "-β");
796
        assert_eq!(format_counter(-1, StyleListStyleType::UpperGreek), "-Α");
797
    }
798

            
799
    #[test]
800
    fn format_counter_negative_is_positive_with_a_minus_for_letter_styles() {
801
        // Guards the regression the `with_sign` doc calls out: a lossy `as u32`
802
        // cast would make -3 render as a huge unsigned counter, not "-iii"/"-c".
803
        for style in [
804
            StyleListStyleType::LowerAlpha,
805
            StyleListStyleType::UpperAlpha,
806
            StyleListStyleType::LowerRoman,
807
            StyleListStyleType::UpperRoman,
808
            StyleListStyleType::LowerGreek,
809
            StyleListStyleType::UpperGreek,
810
        ] {
811
            for v in [1i32, 2, 3, 24, 25, 26, 27, 3999] {
812
                let pos = format_counter(v, style);
813
                let neg = format_counter(-v, style);
814
                assert_eq!(neg, format!("-{pos}"), "asymmetric at {v} in {style:?}");
815
                assert!(!pos.starts_with('-'), "positive gained a sign at {v}");
816
            }
817
        }
818
    }
819

            
820
    #[test]
821
    fn format_counter_letter_styles_never_leak_huge_unsigned_markers() {
822
        // A wrapped cast would produce a marker for -1 as long as the one for
823
        // 4294967295. Bound the length instead of trusting the exact string.
824
        for style in [
825
            StyleListStyleType::LowerAlpha,
826
            StyleListStyleType::UpperGreek,
827
        ] {
828
            let s = format_counter(-1, style);
829
            assert_eq!(s.chars().count(), 2, "suspiciously long marker: {s}");
830
        }
831
    }
832

            
833
    #[test]
834
    fn format_counter_marker_length_stays_bounded_at_i32_extremes() {
835
        // No style may blow up into a megabyte-long marker at the i32 extremes.
836
        for style in ALL_STYLES {
837
            for v in [i32::MIN, i32::MAX] {
838
                let s = format_counter(v, style);
839
                assert!(
840
                    s.chars().count() <= 32,
841
                    "marker for {v} in {style:?} is {} chars: {s}",
842
                    s.chars().count()
843
                );
844
            }
845
        }
846
    }
847
}