1
//! CSS list styling properties (`list-style-type` and `list-style-position`)
2

            
3
use alloc::string::{String, ToString};
4
use core::fmt;
5

            
6
use crate::{
7
    codegen::format::FormatAsRustCode, corety::AzString, props::formatter::PrintAsCssValue,
8
};
9

            
10
// --- list-style-type ---
11

            
12
/// CSS `list-style-type` property — controls the marker style for list items.
13
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
14
#[repr(C)]
15
#[derive(Default)]
16
pub enum StyleListStyleType {
17
    None,
18
    #[default]
19
    Disc,
20
    Circle,
21
    Square,
22
    Decimal,
23
    DecimalLeadingZero,
24
    LowerRoman,
25
    UpperRoman,
26
    LowerGreek,
27
    UpperGreek,
28
    LowerAlpha,
29
    UpperAlpha,
30
}
31

            
32
impl PrintAsCssValue for StyleListStyleType {
33
75
    fn print_as_css_value(&self) -> String {
34
        use StyleListStyleType::{
35
            Circle, Decimal, DecimalLeadingZero, Disc, LowerAlpha, LowerGreek, LowerRoman, None,
36
            Square, UpperAlpha, UpperGreek, UpperRoman,
37
        };
38
75
        String::from(match self {
39
6
            None => "none",
40
7
            Disc => "disc",
41
6
            Circle => "circle",
42
6
            Square => "square",
43
6
            Decimal => "decimal",
44
6
            DecimalLeadingZero => "decimal-leading-zero",
45
6
            LowerRoman => "lower-roman",
46
6
            UpperRoman => "upper-roman",
47
6
            LowerGreek => "lower-greek",
48
6
            UpperGreek => "upper-greek",
49
7
            LowerAlpha => "lower-alpha",
50
7
            UpperAlpha => "upper-alpha",
51
        })
52
75
    }
53
}
54

            
55
impl FormatAsRustCode for StyleListStyleType {
56
24
    fn format_as_rust_code(&self, _tabs: usize) -> String {
57
        use StyleListStyleType::{
58
            Circle, Decimal, DecimalLeadingZero, Disc, LowerAlpha, LowerGreek, LowerRoman, None,
59
            Square, UpperAlpha, UpperGreek, UpperRoman,
60
        };
61
24
        format!(
62
24
            "StyleListStyleType::{}",
63
24
            match self {
64
2
                None => "None",
65
2
                Disc => "Disc",
66
2
                Circle => "Circle",
67
2
                Square => "Square",
68
2
                Decimal => "Decimal",
69
2
                DecimalLeadingZero => "DecimalLeadingZero",
70
2
                LowerRoman => "LowerRoman",
71
2
                UpperRoman => "UpperRoman",
72
2
                LowerGreek => "LowerGreek",
73
2
                UpperGreek => "UpperGreek",
74
2
                LowerAlpha => "LowerAlpha",
75
2
                UpperAlpha => "UpperAlpha",
76
            }
77
        )
78
24
    }
79
}
80

            
81
impl fmt::Display for StyleListStyleType {
82
13
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83
13
        write!(f, "{}", self.print_as_css_value())
84
13
    }
85
}
86

            
87
// --- list-style-position ---
88

            
89
/// CSS `list-style-position` property — controls whether the marker is inside or outside the list
90
/// item box.
91
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
92
#[repr(C)]
93
#[derive(Default)]
94
pub enum StyleListStylePosition {
95
    Inside,
96
    #[default]
97
    Outside,
98
}
99

            
100
impl PrintAsCssValue for StyleListStylePosition {
101
11
    fn print_as_css_value(&self) -> String {
102
        use StyleListStylePosition::{Inside, Outside};
103
11
        String::from(match self {
104
5
            Inside => "inside",
105
6
            Outside => "outside",
106
        })
107
11
    }
108
}
109

            
110
impl FormatAsRustCode for StyleListStylePosition {
111
4
    fn format_as_rust_code(&self, _tabs: usize) -> String {
112
        use StyleListStylePosition::{Inside, Outside};
113
4
        format!(
114
4
            "StyleListStylePosition::{}",
115
4
            match self {
116
2
                Inside => "Inside",
117
2
                Outside => "Outside",
118
            }
119
        )
120
4
    }
121
}
122

            
123
impl fmt::Display for StyleListStylePosition {
124
3
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125
3
        write!(f, "{}", self.print_as_css_value())
126
3
    }
127
}
128

            
129
// --- Parsing Logic ---
130

            
131
#[cfg(feature = "parser")]
132
#[derive(Clone, PartialEq, Eq)]
133
pub enum StyleListStyleTypeParseError<'a> {
134
    InvalidValue(&'a str),
135
}
136

            
137
#[cfg(feature = "parser")]
138
impl_debug_as_display!(StyleListStyleTypeParseError<'a>);
139

            
140
#[cfg(feature = "parser")]
141
impl_display! { StyleListStyleTypeParseError<'a>, {
142
    InvalidValue(val) => format!("Invalid list-style-type value: \"{}\"", val),
143
}}
144

            
145
#[cfg(feature = "parser")]
146
#[derive(Debug, Clone, PartialEq, Eq)]
147
#[repr(C, u8)]
148
pub enum StyleListStyleTypeParseErrorOwned {
149
    InvalidValue(AzString),
150
}
151

            
152
#[cfg(feature = "parser")]
153
impl StyleListStyleTypeParseError<'_> {
154
    #[must_use]
155
8
    pub fn to_contained(&self) -> StyleListStyleTypeParseErrorOwned {
156
8
        match self {
157
8
            Self::InvalidValue(s) => {
158
8
                StyleListStyleTypeParseErrorOwned::InvalidValue((*s).to_string().into())
159
            }
160
        }
161
8
    }
162
}
163

            
164
#[cfg(feature = "parser")]
165
impl StyleListStyleTypeParseErrorOwned {
166
    #[must_use]
167
9
    pub fn to_shared(&self) -> StyleListStyleTypeParseError<'_> {
168
9
        match self {
169
9
            Self::InvalidValue(s) => StyleListStyleTypeParseError::InvalidValue(s.as_str()),
170
        }
171
9
    }
172
}
173

            
174
/// Parses a CSS `list-style-type` value from a string.
175
#[cfg(feature = "parser")]
176
/// # Errors
177
///
178
/// Returns an error if `input` is not a valid CSS `list-style-type` value.
179
127
pub fn parse_style_list_style_type(
180
127
    input: &str,
181
127
) -> Result<StyleListStyleType, StyleListStyleTypeParseError<'_>> {
182
127
    let input = input.trim();
183
127
    match input {
184
127
        "none" => Ok(StyleListStyleType::None),
185
123
        "disc" => Ok(StyleListStyleType::Disc),
186
111
        "circle" => Ok(StyleListStyleType::Circle),
187
107
        "square" => Ok(StyleListStyleType::Square),
188
103
        "decimal" => Ok(StyleListStyleType::Decimal),
189
99
        "decimal-leading-zero" => Ok(StyleListStyleType::DecimalLeadingZero),
190
95
        "lower-roman" => Ok(StyleListStyleType::LowerRoman),
191
91
        "upper-roman" => Ok(StyleListStyleType::UpperRoman),
192
87
        "lower-greek" => Ok(StyleListStyleType::LowerGreek),
193
83
        "upper-greek" => Ok(StyleListStyleType::UpperGreek),
194
79
        "lower-alpha" | "lower-latin" => Ok(StyleListStyleType::LowerAlpha),
195
72
        "upper-alpha" | "upper-latin" => Ok(StyleListStyleType::UpperAlpha),
196
65
        _ => Err(StyleListStyleTypeParseError::InvalidValue(input)),
197
    }
198
127
}
199

            
200
#[cfg(feature = "parser")]
201
#[derive(Clone, PartialEq, Eq)]
202
pub enum StyleListStylePositionParseError<'a> {
203
    InvalidValue(&'a str),
204
}
205

            
206
#[cfg(feature = "parser")]
207
impl_debug_as_display!(StyleListStylePositionParseError<'a>);
208

            
209
#[cfg(feature = "parser")]
210
impl_display! { StyleListStylePositionParseError<'a>, {
211
    InvalidValue(val) => format!("Invalid list-style-position value: \"{}\"", val),
212
}}
213

            
214
#[cfg(feature = "parser")]
215
#[derive(Debug, Clone, PartialEq, Eq)]
216
#[repr(C, u8)]
217
pub enum StyleListStylePositionParseErrorOwned {
218
    InvalidValue(AzString),
219
}
220

            
221
#[cfg(feature = "parser")]
222
impl StyleListStylePositionParseError<'_> {
223
    #[must_use]
224
7
    pub fn to_contained(&self) -> StyleListStylePositionParseErrorOwned {
225
7
        match self {
226
7
            Self::InvalidValue(s) => {
227
7
                StyleListStylePositionParseErrorOwned::InvalidValue((*s).to_string().into())
228
            }
229
        }
230
7
    }
231
}
232

            
233
#[cfg(feature = "parser")]
234
impl StyleListStylePositionParseErrorOwned {
235
    #[must_use]
236
6
    pub fn to_shared(&self) -> StyleListStylePositionParseError<'_> {
237
6
        match self {
238
6
            Self::InvalidValue(s) => StyleListStylePositionParseError::InvalidValue(s.as_str()),
239
        }
240
6
    }
241
}
242

            
243
/// Parses a CSS `list-style-position` value from a string.
244
#[cfg(feature = "parser")]
245
/// # Errors
246
///
247
/// Returns an error if `input` is not a valid CSS `list-style-position` value.
248
60
pub fn parse_style_list_style_position(
249
60
    input: &str,
250
60
) -> Result<StyleListStylePosition, StyleListStylePositionParseError<'_>> {
251
60
    let input = input.trim();
252
60
    match input {
253
60
        "inside" => Ok(StyleListStylePosition::Inside),
254
58
        "outside" => Ok(StyleListStylePosition::Outside),
255
55
        _ => Err(StyleListStylePositionParseError::InvalidValue(input)),
256
    }
257
60
}
258

            
259
#[cfg(test)]
260
mod autotest_generated {
261
    //! Adversarial tests for the two list-style keyword enums: serializer
262
    //! well-formedness, `print_as_css_value` -> `parse_*` round-trips over every
263
    //! variant, parser abuse (empty / whitespace / garbage / megabyte-sized /
264
    //! unicode / deeply nested input) and the `to_contained` / `to_shared` error
265
    //! conversion invariants.
266
    //!
267
    //! Both parsers are pure keyword matchers over a trimmed `&str`, so the
268
    //! interesting failure modes are (a) panicking or hanging on hostile input,
269
    //! (b) losing or corrupting the borrowed error payload, and (c) a variant
270
    //! whose serialized form does not parse back to itself.
271

            
272
    use std::collections::BTreeSet;
273

            
274
    use super::*;
275

            
276
    const ALL_TYPES: [StyleListStyleType; 12] = [
277
        StyleListStyleType::None,
278
        StyleListStyleType::Disc,
279
        StyleListStyleType::Circle,
280
        StyleListStyleType::Square,
281
        StyleListStyleType::Decimal,
282
        StyleListStyleType::DecimalLeadingZero,
283
        StyleListStyleType::LowerRoman,
284
        StyleListStyleType::UpperRoman,
285
        StyleListStyleType::LowerGreek,
286
        StyleListStyleType::UpperGreek,
287
        StyleListStyleType::LowerAlpha,
288
        StyleListStyleType::UpperAlpha,
289
    ];
290

            
291
    const ALL_POSITIONS: [StyleListStylePosition; 2] = [
292
        StyleListStylePosition::Inside,
293
        StyleListStylePosition::Outside,
294
    ];
295

            
296
    /// Hostile inputs that must never be accepted, never panic and never hang.
297
    #[cfg(feature = "parser")]
298
    fn hostile_inputs() -> Vec<String> {
299
        let mut v = vec![
300
            String::new(),
301
            " ".to_string(),
302
            "   \t\n\r".to_string(),
303
            "\u{0c}\u{0b}".to_string(),
304
            "\0".to_string(),
305
            "disc\0".to_string(),
306
            "\0disc".to_string(),
307
            "-".to_string(),
308
            "--".to_string(),
309
            ";".to_string(),
310
            "{}".to_string(),
311
            "/* disc */".to_string(),
312
            "disc;garbage".to_string(),
313
            "disc disc".to_string(),
314
            "disc,circle".to_string(),
315
            "disc!important".to_string(),
316
            "inside;".to_string(),
317
            "list-style-type: disc".to_string(),
318
            "lower_roman".to_string(),
319
            "lower - roman".to_string(),
320
            "lowerroman".to_string(),
321
            // boundary numerics
322
            "0".to_string(),
323
            "-0".to_string(),
324
            "NaN".to_string(),
325
            "nan".to_string(),
326
            "inf".to_string(),
327
            "-inf".to_string(),
328
            "infinity".to_string(),
329
            i64::MAX.to_string(),
330
            i64::MIN.to_string(),
331
            u64::MAX.to_string(),
332
            f64::MAX.to_string(),
333
            f64::MIN_POSITIVE.to_string(),
334
            "1e308".to_string(),
335
            "-1e-308".to_string(),
336
            // unicode
337
            "\u{1F600}".to_string(),
338
            "disc\u{301}".to_string(),
339
            "\u{301}".to_string(),
340
            "\u{202E}disc".to_string(),
341
            "di\u{200B}sc".to_string(),
342
            "DISС".to_string(),  // trailing char is Cyrillic U+0421, not ASCII C
343
            "disc".to_string(), // fullwidth s
344
            "круг".to_string(),
345
            "\u{FFFD}".to_string(),
346
        ];
347
        // Deeply nested / recursive-looking input must not blow the stack: these
348
        // parsers are non-recursive, so this is a regression guard.
349
        v.push("(".repeat(10_000));
350
        v.push("[".repeat(10_000));
351
        v.push("disc(".repeat(10_000));
352
        v.push(format!("{}disc{}", "(".repeat(10_000), ")".repeat(10_000)));
353
        v
354
    }
355

            
356
    // --- serializers -------------------------------------------------------
357

            
358
    #[test]
359
    fn css_values_are_well_formed_for_every_type() {
360
        for v in ALL_TYPES {
361
            let s = v.print_as_css_value();
362
            assert!(!s.is_empty(), "{v:?} serialized to an empty CSS value");
363
            assert!(
364
                s.chars().all(|c| c.is_ascii_lowercase() || c == '-'),
365
                "{v:?} serialized to {s:?}, which is not a bare lowercase CSS keyword"
366
            );
367
            assert!(!s.starts_with('-') && !s.ends_with('-'), "{v:?} -> {s:?}");
368
        }
369
    }
370

            
371
    #[test]
372
    fn css_values_are_well_formed_for_every_position() {
373
        for v in ALL_POSITIONS {
374
            let s = v.print_as_css_value();
375
            assert!(!s.is_empty(), "{v:?} serialized to an empty CSS value");
376
            assert!(s.chars().all(|c| c.is_ascii_lowercase()), "{v:?} -> {s:?}");
377
        }
378
    }
379

            
380
    #[test]
381
    fn css_values_are_unique() {
382
        let types: BTreeSet<String> = ALL_TYPES
383
            .iter()
384
            .map(PrintAsCssValue::print_as_css_value)
385
            .collect();
386
        assert_eq!(
387
            types.len(),
388
            ALL_TYPES.len(),
389
            "two list-style-type variants share a CSS keyword"
390
        );
391

            
392
        let positions: BTreeSet<String> = ALL_POSITIONS
393
            .iter()
394
            .map(PrintAsCssValue::print_as_css_value)
395
            .collect();
396
        assert_eq!(positions.len(), ALL_POSITIONS.len());
397
    }
398

            
399
    #[test]
400
    fn display_agrees_with_print_as_css_value() {
401
        for v in ALL_TYPES {
402
            assert_eq!(
403
                v.to_string(),
404
                v.print_as_css_value(),
405
                "Display diverged for {v:?}"
406
            );
407
        }
408
        for v in ALL_POSITIONS {
409
            assert_eq!(
410
                v.to_string(),
411
                v.print_as_css_value(),
412
                "Display diverged for {v:?}"
413
            );
414
        }
415
    }
416

            
417
    #[test]
418
    fn display_of_default_is_the_css_initial_value() {
419
        // CSS initial values: list-style-type: disc, list-style-position: outside.
420
        assert_eq!(StyleListStyleType::default(), StyleListStyleType::Disc);
421
        assert_eq!(StyleListStyleType::default().to_string(), "disc");
422
        assert_eq!(
423
            StyleListStylePosition::default(),
424
            StyleListStylePosition::Outside
425
        );
426
        assert_eq!(StyleListStylePosition::default().to_string(), "outside");
427
    }
428

            
429
    #[test]
430
    fn rust_code_names_the_variant_and_ignores_the_tab_argument() {
431
        for v in ALL_TYPES {
432
            // Debug is derived, so it yields the bare variant name.
433
            let expected = format!("StyleListStyleType::{v:?}");
434
            assert_eq!(v.format_as_rust_code(0), expected);
435
            // `_tabs` is unused: no indentation must leak in, at any depth.
436
            assert_eq!(v.format_as_rust_code(usize::MAX), expected);
437
        }
438
        for v in ALL_POSITIONS {
439
            let expected = format!("StyleListStylePosition::{v:?}");
440
            assert_eq!(v.format_as_rust_code(0), expected);
441
            assert_eq!(v.format_as_rust_code(usize::MAX), expected);
442
        }
443
    }
444

            
445
    // --- round-trips -------------------------------------------------------
446

            
447
    #[test]
448
    #[cfg(feature = "parser")]
449
    fn every_type_round_trips_through_its_css_value() {
450
        for v in ALL_TYPES {
451
            let printed = v.print_as_css_value();
452
            assert_eq!(
453
                parse_style_list_style_type(&printed),
454
                Ok(v),
455
                "{v:?} serialized to {printed:?}, which does not parse back"
456
            );
457
        }
458
    }
459

            
460
    #[test]
461
    #[cfg(feature = "parser")]
462
    fn every_position_round_trips_through_its_css_value() {
463
        for v in ALL_POSITIONS {
464
            let printed = v.print_as_css_value();
465
            assert_eq!(
466
                parse_style_list_style_position(&printed),
467
                Ok(v),
468
                "{v:?} -> {printed:?}"
469
            );
470
        }
471
    }
472

            
473
    #[test]
474
    #[cfg(feature = "parser")]
475
    fn parsing_is_idempotent_through_reserialization() {
476
        // parse -> print -> parse must reach a fixed point, including for the
477
        // alias spellings that normalize onto a different keyword.
478
        for input in [
479
            "disc",
480
            "none",
481
            "circle",
482
            "square",
483
            "decimal",
484
            "decimal-leading-zero",
485
            "lower-roman",
486
            "upper-roman",
487
            "lower-greek",
488
            "upper-greek",
489
            "lower-alpha",
490
            "upper-alpha",
491
            "lower-latin",
492
            "upper-latin",
493
        ] {
494
            let first = parse_style_list_style_type(input).expect("known-good keyword");
495
            let printed = first.print_as_css_value();
496
            let second =
497
                parse_style_list_style_type(&printed).expect("reserialized value must reparse");
498
            assert_eq!(
499
                first, second,
500
                "{input:?} was not idempotent (printed {printed:?})"
501
            );
502
        }
503
    }
504

            
505
    // --- parser: positive controls ----------------------------------------
506

            
507
    #[test]
508
    #[cfg(feature = "parser")]
509
    fn valid_keywords_map_to_the_expected_variants() {
510
        let table = [
511
            ("none", StyleListStyleType::None),
512
            ("disc", StyleListStyleType::Disc),
513
            ("circle", StyleListStyleType::Circle),
514
            ("square", StyleListStyleType::Square),
515
            ("decimal", StyleListStyleType::Decimal),
516
            (
517
                "decimal-leading-zero",
518
                StyleListStyleType::DecimalLeadingZero,
519
            ),
520
            ("lower-roman", StyleListStyleType::LowerRoman),
521
            ("upper-roman", StyleListStyleType::UpperRoman),
522
            ("lower-greek", StyleListStyleType::LowerGreek),
523
            ("upper-greek", StyleListStyleType::UpperGreek),
524
            ("lower-alpha", StyleListStyleType::LowerAlpha),
525
            ("upper-alpha", StyleListStyleType::UpperAlpha),
526
            // documented aliases
527
            ("lower-latin", StyleListStyleType::LowerAlpha),
528
            ("upper-latin", StyleListStyleType::UpperAlpha),
529
        ];
530
        for (input, expected) in table {
531
            assert_eq!(
532
                parse_style_list_style_type(input),
533
                Ok(expected),
534
                "input {input:?}"
535
            );
536
        }
537

            
538
        assert_eq!(
539
            parse_style_list_style_position("inside"),
540
            Ok(StyleListStylePosition::Inside)
541
        );
542
        assert_eq!(
543
            parse_style_list_style_position("outside"),
544
            Ok(StyleListStylePosition::Outside)
545
        );
546
    }
547

            
548
    #[test]
549
    #[cfg(feature = "parser")]
550
    fn ascii_whitespace_padding_is_trimmed() {
551
        for padded in ["  disc", "disc\n", "\t disc \r\n", "\u{0c}disc\u{0c}"] {
552
            assert_eq!(
553
                parse_style_list_style_type(padded),
554
                Ok(StyleListStyleType::Disc),
555
                "padding was not trimmed from {padded:?}"
556
            );
557
        }
558
        assert_eq!(
559
            parse_style_list_style_position("\n\t outside \t\n"),
560
            Ok(StyleListStylePosition::Outside)
561
        );
562
    }
563

            
564
    #[test]
565
    #[cfg(feature = "parser")]
566
    fn parsers_agree_with_str_trim_on_unicode_whitespace() {
567
        // `str::trim` strips *Unicode* whitespace (U+00A0 NBSP, U+2003 EM SPACE,
568
        // U+3000 IDEOGRAPHIC SPACE), which CSS does not consider whitespace. The
569
        // parsers trim first, so whatever `trim` decides, they must stay
570
        // consistent with it rather than accepting a keyword `trim` left dirty.
571
        for pad in ["\u{a0}", "\u{2003}", "\u{3000}"] {
572
            let padded = format!("{pad}disc{pad}");
573
            assert_eq!(
574
                parse_style_list_style_type(&padded).is_ok(),
575
                padded.trim() == "disc",
576
                "parser and str::trim disagree on {padded:?}"
577
            );
578
        }
579
    }
580

            
581
    // --- parser: hostile input --------------------------------------------
582

            
583
    #[test]
584
    #[cfg(feature = "parser")]
585
    fn hostile_input_is_rejected_without_panicking() {
586
        for input in hostile_inputs() {
587
            let ty = parse_style_list_style_type(&input);
588
            assert!(
589
                ty.is_err(),
590
                "list-style-type accepted hostile input {input:?} as {ty:?}"
591
            );
592

            
593
            let pos = parse_style_list_style_position(&input);
594
            assert!(
595
                pos.is_err(),
596
                "list-style-position accepted hostile input {input:?} as {pos:?}"
597
            );
598
        }
599
    }
600

            
601
    #[test]
602
    #[cfg(feature = "parser")]
603
    fn keyword_matching_is_case_sensitive() {
604
        // NOTE: CSS keyword values are ASCII case-insensitive, so `DISC` /
605
        // `Inside` *should* parse per spec. These parsers are exact-match only;
606
        // the assertions below pin the current (stricter than spec) behavior.
607
        for input in [
608
            "Disc",
609
            "DISC",
610
            "dIsC",
611
            "LOWER-ROMAN",
612
            "Decimal-Leading-Zero",
613
            "NONE",
614
        ] {
615
            assert!(
616
                parse_style_list_style_type(input).is_err(),
617
                "unexpectedly case-insensitive for {input:?}"
618
            );
619
        }
620
        for input in ["Inside", "OUTSIDE", "OuTsIdE"] {
621
            assert!(
622
                parse_style_list_style_position(input).is_err(),
623
                "unexpectedly case-insensitive for {input:?}"
624
            );
625
        }
626
    }
627

            
628
    #[test]
629
    #[cfg(feature = "parser")]
630
    fn megabyte_sized_input_terminates_and_is_rejected() {
631
        let long = "a".repeat(1_000_000);
632
        assert!(parse_style_list_style_type(&long).is_err());
633
        assert!(parse_style_list_style_position(&long).is_err());
634

            
635
        // A valid keyword repeated a quarter-million times is still not a keyword.
636
        let repeated = "disc".repeat(250_000);
637
        assert!(parse_style_list_style_type(&repeated).is_err());
638

            
639
        // Megabytes of padding around a valid keyword must still trim down to it.
640
        let padded = format!("{}disc{}", " ".repeat(1_000_000), "\n".repeat(1_000_000));
641
        assert_eq!(
642
            parse_style_list_style_type(&padded),
643
            Ok(StyleListStyleType::Disc)
644
        );
645
    }
646

            
647
    #[test]
648
    #[cfg(feature = "parser")]
649
    fn multibyte_input_is_rejected_without_slicing_panics() {
650
        // Trimming a string whose bytes straddle char boundaries must not panic
651
        // and must not truncate the error payload mid-codepoint.
652
        for input in [
653
            "🙂",
654
            " 🙂 ",
655
            "日本語",
656
            "e\u{301}",
657
            "\u{1F600}\u{1F600}\u{1F600}",
658
        ] {
659
            match parse_style_list_style_type(input) {
660
                Ok(v) => panic!("multibyte input {input:?} parsed as {v:?}"),
661
                Err(StyleListStyleTypeParseError::InvalidValue(s)) => {
662
                    assert_eq!(s, input.trim(), "error payload was mangled for {input:?}");
663
                }
664
            }
665
        }
666
    }
667

            
668
    // --- parser: error payloads -------------------------------------------
669

            
670
    #[test]
671
    #[cfg(feature = "parser")]
672
    fn error_payload_is_the_trimmed_input() {
673
        match parse_style_list_style_type("  bogus-keyword  ") {
674
            Err(StyleListStyleTypeParseError::InvalidValue(s)) => assert_eq!(s, "bogus-keyword"),
675
            other => panic!("expected InvalidValue, got {other:?}"),
676
        }
677
        match parse_style_list_style_position("\t bogus \n") {
678
            Err(StyleListStylePositionParseError::InvalidValue(s)) => assert_eq!(s, "bogus"),
679
            other => panic!("expected InvalidValue, got {other:?}"),
680
        }
681
        // Whitespace-only input trims to the empty string, not to a `None`-ish value.
682
        match parse_style_list_style_type("   \t\n") {
683
            Err(StyleListStyleTypeParseError::InvalidValue(s)) => assert!(s.is_empty()),
684
            other => panic!("expected InvalidValue(\"\"), got {other:?}"),
685
        }
686
    }
687

            
688
    #[test]
689
    #[cfg(feature = "parser")]
690
    fn error_display_quotes_the_offending_value() {
691
        let err = parse_style_list_style_type("🙂").unwrap_err();
692
        let msg = err.to_string();
693
        assert!(msg.contains("list-style-type"), "{msg:?}");
694
        assert!(
695
            msg.contains('🙂'),
696
            "error message dropped the offending value: {msg:?}"
697
        );
698

            
699
        let err = parse_style_list_style_position("").unwrap_err();
700
        let msg = err.to_string();
701
        assert!(msg.contains("list-style-position"), "{msg:?}");
702
        assert!(!msg.is_empty());
703
    }
704

            
705
    // --- error conversions: to_contained / to_shared ------------------------
706

            
707
    #[test]
708
    #[cfg(feature = "parser")]
709
    fn type_error_survives_a_contained_shared_round_trip() {
710
        let payloads = [
711
            "",
712
            " ",
713
            "bogus",
714
            "🙂 combining\u{301}",
715
            "\0embedded nul\0",
716
            "line\nbreak\r\n",
717
            "-",
718
        ];
719
        for payload in payloads {
720
            let shared = StyleListStyleTypeParseError::InvalidValue(payload);
721
            let owned = shared.to_contained();
722
            match &owned {
723
                StyleListStyleTypeParseErrorOwned::InvalidValue(s) => {
724
                    assert_eq!(s.as_str(), payload, "to_contained mangled {payload:?}");
725
                }
726
            }
727
            assert_eq!(
728
                owned.to_shared(),
729
                shared,
730
                "round-trip lost data for {payload:?}"
731
            );
732
        }
733
    }
734

            
735
    #[test]
736
    #[cfg(feature = "parser")]
737
    fn position_error_survives_a_contained_shared_round_trip() {
738
        for payload in ["", "bogus", "🙂", "\0", "  interior  spaces  "] {
739
            let shared = StyleListStylePositionParseError::InvalidValue(payload);
740
            let owned = shared.to_contained();
741
            match &owned {
742
                StyleListStylePositionParseErrorOwned::InvalidValue(s) => {
743
                    assert_eq!(s.as_str(), payload);
744
                }
745
            }
746
            assert_eq!(
747
                owned.to_shared(),
748
                shared,
749
                "round-trip lost data for {payload:?}"
750
            );
751
        }
752
    }
753

            
754
    #[test]
755
    #[cfg(feature = "parser")]
756
    fn owned_errors_constructed_directly_convert_back_to_shared() {
757
        let owned = StyleListStyleTypeParseErrorOwned::InvalidValue(String::new().into());
758
        match owned.to_shared() {
759
            StyleListStyleTypeParseError::InvalidValue(s) => assert_eq!(s, ""),
760
        }
761

            
762
        let owned = StyleListStylePositionParseErrorOwned::InvalidValue(String::from("x").into());
763
        match owned.to_shared() {
764
            StyleListStylePositionParseError::InvalidValue(s) => assert_eq!(s, "x"),
765
        }
766
    }
767

            
768
    #[test]
769
    #[cfg(feature = "parser")]
770
    fn huge_error_payload_is_carried_without_truncation() {
771
        let huge = "z".repeat(100_000);
772
        let err = parse_style_list_style_type(&huge).unwrap_err();
773
        let owned = err.to_contained();
774
        match &owned {
775
            StyleListStyleTypeParseErrorOwned::InvalidValue(s) => {
776
                assert_eq!(s.as_str().len(), 100_000, "payload was truncated");
777
            }
778
        }
779
        assert_eq!(
780
            owned.to_shared(),
781
            StyleListStyleTypeParseError::InvalidValue(&huge)
782
        );
783
    }
784

            
785
    #[test]
786
    #[cfg(feature = "parser")]
787
    fn to_contained_is_repeatable_and_does_not_consume_the_error() {
788
        let err = parse_style_list_style_position("nope").unwrap_err();
789
        let a = err.to_contained();
790
        let b = err.to_contained();
791
        assert_eq!(a, b);
792
        assert_eq!(err, StyleListStylePositionParseError::InvalidValue("nope"));
793
    }
794
}