1
//! CSS properties for table layout and styling.
2
//!
3
//! This module contains properties specific to CSS table formatting:
4
//! - `table-layout`: Controls the algorithm used to layout table cells, rows, and columns
5
//! - `border-collapse`: Specifies whether cell borders are collapsed into a single border or
6
//!   separated
7
//! - `border-spacing`: Sets the distance between borders of adjacent cells (separate borders only)
8
//! - `caption-side`: Specifies the placement of a table caption
9
//! - `empty-cells`: Specifies whether or not to display borders on empty cells in a table
10

            
11
use alloc::string::{String, ToString};
12

            
13
use crate::{
14
    codegen::format::FormatAsRustCode,
15
    props::{
16
        basic::pixel::{CssPixelValueParseError, PixelValue},
17
        formatter::PrintAsCssValue,
18
    },
19
};
20

            
21
// table-layout
22

            
23
/// Controls the algorithm used to lay out table cells, rows, and columns.
24
///
25
/// The `table-layout` property determines whether the browser should use:
26
/// - **auto**: Column widths are determined by the content (slower but flexible)
27
/// - **fixed**: Column widths are determined by the first row (faster and predictable)
28
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
29
#[repr(C)]
30
#[derive(Default)]
31
pub enum LayoutTableLayout {
32
    /// Use automatic table layout algorithm (content-based, default).
33
    /// Column width is set by the widest unbreakable content in the cells.
34
    #[default]
35
    Auto,
36
    /// Use fixed table layout algorithm (first-row-based).
37
    /// Column width is set by the width property of the column or first-row cell.
38
    /// Renders faster than auto.
39
    Fixed,
40
}
41

            
42
impl PrintAsCssValue for LayoutTableLayout {
43
5
    fn print_as_css_value(&self) -> String {
44
5
        match self {
45
3
            Self::Auto => "auto".to_string(),
46
2
            Self::Fixed => "fixed".to_string(),
47
        }
48
5
    }
49
}
50

            
51
impl FormatAsRustCode for LayoutTableLayout {
52
3
    fn format_as_rust_code(&self, _tabs: usize) -> String {
53
3
        match self {
54
2
            Self::Auto => "LayoutTableLayout::Auto".to_string(),
55
1
            Self::Fixed => "LayoutTableLayout::Fixed".to_string(),
56
        }
57
3
    }
58
}
59

            
60
// border-collapse
61

            
62
/// Specifies whether cell borders are collapsed into a single border or separated.
63
///
64
/// The `border-collapse` property determines the border rendering model:
65
/// - **separate**: Each cell has its own border (default, uses border-spacing)
66
/// - **collapse**: Adjacent cells share borders (ignores border-spacing)
67
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
68
#[repr(C)]
69
#[derive(Default)]
70
pub enum StyleBorderCollapse {
71
    /// Borders are separated (default). Each cell has its own border.
72
    /// The `border-spacing` property defines the distance between borders.
73
    #[default]
74
    Separate,
75
    /// Borders are collapsed. Adjacent cells share a single border.
76
    /// Border conflict resolution rules apply when borders differ.
77
    Collapse,
78
}
79

            
80
impl PrintAsCssValue for StyleBorderCollapse {
81
4
    fn print_as_css_value(&self) -> String {
82
4
        match self {
83
2
            Self::Separate => "separate".to_string(),
84
2
            Self::Collapse => "collapse".to_string(),
85
        }
86
4
    }
87
}
88

            
89
impl FormatAsRustCode for StyleBorderCollapse {
90
1
    fn format_as_rust_code(&self, _tabs: usize) -> String {
91
1
        match self {
92
            Self::Separate => "StyleBorderCollapse::Separate".to_string(),
93
1
            Self::Collapse => "StyleBorderCollapse::Collapse".to_string(),
94
        }
95
1
    }
96
}
97

            
98
// border-spacing
99

            
100
/// Sets the distance between the borders of adjacent cells.
101
///
102
/// The `border-spacing` property is only applicable when `border-collapse` is set to `separate`.
103
/// It can have one or two values:
104
/// - One value: Sets both horizontal and vertical spacing
105
/// - Two values: First is horizontal, second is vertical
106
///
107
/// This struct represents a single spacing value (either horizontal or vertical).
108
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
109
#[repr(C)]
110
pub struct LayoutBorderSpacing {
111
    /// Horizontal spacing between cell borders
112
    pub horizontal: PixelValue,
113
    /// Vertical spacing between cell borders
114
    pub vertical: PixelValue,
115
}
116

            
117
impl Default for LayoutBorderSpacing {
118
497
    fn default() -> Self {
119
        // Default border-spacing is 0 (no spacing)
120
497
        Self {
121
497
            horizontal: PixelValue::const_px(0),
122
497
            vertical: PixelValue::const_px(0),
123
497
        }
124
497
    }
125
}
126

            
127
impl LayoutBorderSpacing {
128
    /// Creates a new border spacing with the same value for horizontal and vertical
129
    #[must_use]
130
117
    pub const fn new(spacing: PixelValue) -> Self {
131
117
        Self {
132
117
            horizontal: spacing,
133
117
            vertical: spacing,
134
117
        }
135
117
    }
136

            
137
    /// Creates a new border spacing with different horizontal and vertical values
138
    #[must_use]
139
859
    pub const fn new_separate(horizontal: PixelValue, vertical: PixelValue) -> Self {
140
859
        Self {
141
859
            horizontal,
142
859
            vertical,
143
859
        }
144
859
    }
145
}
146

            
147
impl PrintAsCssValue for LayoutBorderSpacing {
148
128
    fn print_as_css_value(&self) -> String {
149
128
        if self.horizontal == self.vertical {
150
            // Single value: same for both dimensions
151
36
            self.horizontal.to_string()
152
        } else {
153
            // Two values: horizontal vertical
154
92
            format!("{} {}", self.horizontal, self.vertical)
155
        }
156
128
    }
157
}
158

            
159
impl FormatAsRustCode for LayoutBorderSpacing {
160
7
    fn format_as_rust_code(&self, _tabs: usize) -> String {
161
        use crate::codegen::format::format_pixel_value;
162
7
        format!(
163
7
            "LayoutBorderSpacing {{ horizontal: {}, vertical: {} }}",
164
7
            format_pixel_value(&self.horizontal),
165
7
            format_pixel_value(&self.vertical)
166
        )
167
7
    }
168
}
169

            
170
// caption-side
171

            
172
/// Specifies the placement of a table caption.
173
///
174
/// The `caption-side` property positions the caption either above or below the table.
175
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
176
#[repr(C)]
177
#[derive(Default)]
178
pub enum StyleCaptionSide {
179
    /// Caption is placed above the table (default)
180
    #[default]
181
    Top,
182
    /// Caption is placed below the table
183
    Bottom,
184
}
185

            
186
impl PrintAsCssValue for StyleCaptionSide {
187
4
    fn print_as_css_value(&self) -> String {
188
4
        match self {
189
2
            Self::Top => "top".to_string(),
190
2
            Self::Bottom => "bottom".to_string(),
191
        }
192
4
    }
193
}
194

            
195
impl FormatAsRustCode for StyleCaptionSide {
196
1
    fn format_as_rust_code(&self, _tabs: usize) -> String {
197
1
        match self {
198
            Self::Top => "StyleCaptionSide::Top".to_string(),
199
1
            Self::Bottom => "StyleCaptionSide::Bottom".to_string(),
200
        }
201
1
    }
202
}
203

            
204
// empty-cells
205

            
206
/// Specifies whether or not to display borders and background on empty cells.
207
///
208
/// The `empty-cells` property only applies when `border-collapse` is set to `separate`.
209
/// A cell is considered empty if it contains no visible content.
210
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
211
#[repr(C)]
212
#[derive(Default)]
213
pub enum StyleEmptyCells {
214
    /// Show borders and background on empty cells (default)
215
    #[default]
216
    Show,
217
    /// Hide borders and background on empty cells
218
    Hide,
219
}
220

            
221
impl PrintAsCssValue for StyleEmptyCells {
222
4
    fn print_as_css_value(&self) -> String {
223
4
        match self {
224
2
            Self::Show => "show".to_string(),
225
2
            Self::Hide => "hide".to_string(),
226
        }
227
4
    }
228
}
229

            
230
impl FormatAsRustCode for StyleEmptyCells {
231
1
    fn format_as_rust_code(&self, _tabs: usize) -> String {
232
1
        match self {
233
            Self::Show => "StyleEmptyCells::Show".to_string(),
234
1
            Self::Hide => "StyleEmptyCells::Hide".to_string(),
235
        }
236
1
    }
237
}
238

            
239
// Parsing Functions
240

            
241
/// Parse errors for table-layout property
242
#[derive(Debug, Clone, PartialEq)]
243
pub(crate) enum LayoutTableLayoutParseError<'a> {
244
    InvalidKeyword(&'a str),
245
}
246

            
247
/// Parse a table-layout value from a string
248
89
pub(crate) fn parse_table_layout(
249
89
    input: &str,
250
89
) -> Result<LayoutTableLayout, LayoutTableLayoutParseError<'_>> {
251
89
    match input.trim() {
252
89
        "auto" => Ok(LayoutTableLayout::Auto),
253
81
        "fixed" => Ok(LayoutTableLayout::Fixed),
254
77
        other => Err(LayoutTableLayoutParseError::InvalidKeyword(other)),
255
    }
256
89
}
257

            
258
/// Parse errors for border-collapse property
259
#[derive(Debug, Clone, PartialEq)]
260
pub(crate) enum StyleBorderCollapseParseError<'a> {
261
    InvalidKeyword(&'a str),
262
}
263

            
264
/// Parse a border-collapse value from a string
265
134
pub(crate) fn parse_border_collapse(
266
134
    input: &str,
267
134
) -> Result<StyleBorderCollapse, StyleBorderCollapseParseError<'_>> {
268
134
    match input.trim() {
269
134
        "separate" => Ok(StyleBorderCollapse::Separate),
270
131
        "collapse" => Ok(StyleBorderCollapse::Collapse),
271
74
        other => Err(StyleBorderCollapseParseError::InvalidKeyword(other)),
272
    }
273
134
}
274

            
275
/// Parse errors for border-spacing property
276
#[derive(Debug, Clone, PartialEq)]
277
pub(crate) enum LayoutBorderSpacingParseError<'a> {
278
    PixelValue(CssPixelValueParseError<'a>),
279
    InvalidFormat,
280
}
281

            
282
/// Parse a border-spacing value from a string
283
/// Accepts: "5px" or "5px 10px"
284
199
pub(crate) fn parse_border_spacing(
285
199
    input: &str,
286
199
) -> Result<LayoutBorderSpacing, LayoutBorderSpacingParseError<'_>> {
287
    use crate::props::basic::parse_pixel_value;
288

            
289
199
    let parts: Vec<&str> = input.split_whitespace().collect();
290

            
291
199
    match parts.len() {
292
        1 => {
293
            // Single value: use for both horizontal and vertical
294
70
            let value =
295
82
                parse_pixel_value(parts[0]).map_err(LayoutBorderSpacingParseError::PixelValue)?;
296
70
            Ok(LayoutBorderSpacing::new(value))
297
        }
298
        2 => {
299
            // Two values: horizontal vertical
300
106
            let horizontal =
301
106
                parse_pixel_value(parts[0]).map_err(LayoutBorderSpacingParseError::PixelValue)?;
302
103
            let vertical =
303
106
                parse_pixel_value(parts[1]).map_err(LayoutBorderSpacingParseError::PixelValue)?;
304
103
            Ok(LayoutBorderSpacing::new_separate(horizontal, vertical))
305
        }
306
11
        _ => Err(LayoutBorderSpacingParseError::InvalidFormat),
307
    }
308
199
}
309

            
310
/// Parse errors for caption-side property
311
#[derive(Debug, Clone, PartialEq)]
312
pub(crate) enum StyleCaptionSideParseError<'a> {
313
    InvalidKeyword(&'a str),
314
}
315

            
316
/// Parse a caption-side value from a string
317
82
pub(crate) fn parse_caption_side(
318
82
    input: &str,
319
82
) -> Result<StyleCaptionSide, StyleCaptionSideParseError<'_>> {
320
82
    match input.trim() {
321
82
        "top" => Ok(StyleCaptionSide::Top),
322
78
        "bottom" => Ok(StyleCaptionSide::Bottom),
323
74
        other => Err(StyleCaptionSideParseError::InvalidKeyword(other)),
324
    }
325
82
}
326

            
327
/// Parse errors for empty-cells property
328
#[derive(Debug, Clone, PartialEq)]
329
pub(crate) enum StyleEmptyCellsParseError<'a> {
330
    InvalidKeyword(&'a str),
331
}
332

            
333
/// Parse an empty-cells value from a string
334
83
pub(crate) fn parse_empty_cells(
335
83
    input: &str,
336
83
) -> Result<StyleEmptyCells, StyleEmptyCellsParseError<'_>> {
337
83
    match input.trim() {
338
83
        "show" => Ok(StyleEmptyCells::Show),
339
79
        "hide" => Ok(StyleEmptyCells::Hide),
340
74
        other => Err(StyleEmptyCellsParseError::InvalidKeyword(other)),
341
    }
342
83
}
343

            
344
#[cfg(test)]
345
mod tests {
346
    use super::*;
347

            
348
    #[test]
349
1
    fn test_parse_table_layout() {
350
1
        assert_eq!(parse_table_layout("auto").unwrap(), LayoutTableLayout::Auto);
351
1
        assert_eq!(
352
1
            parse_table_layout("fixed").unwrap(),
353
            LayoutTableLayout::Fixed
354
        );
355
1
        assert!(parse_table_layout("invalid").is_err());
356
1
    }
357

            
358
    #[test]
359
1
    fn test_parse_border_collapse() {
360
1
        assert_eq!(
361
1
            parse_border_collapse("separate").unwrap(),
362
            StyleBorderCollapse::Separate
363
        );
364
1
        assert_eq!(
365
1
            parse_border_collapse("collapse").unwrap(),
366
            StyleBorderCollapse::Collapse
367
        );
368
1
        assert!(parse_border_collapse("invalid").is_err());
369
1
    }
370

            
371
    #[test]
372
1
    fn test_parse_border_spacing() {
373
1
        let spacing1 = parse_border_spacing("5px").unwrap();
374
1
        assert_eq!(spacing1.horizontal, PixelValue::const_px(5));
375
1
        assert_eq!(spacing1.vertical, PixelValue::const_px(5));
376

            
377
1
        let spacing2 = parse_border_spacing("5px 10px").unwrap();
378
1
        assert_eq!(spacing2.horizontal, PixelValue::const_px(5));
379
1
        assert_eq!(spacing2.vertical, PixelValue::const_px(10));
380
1
    }
381

            
382
    #[test]
383
1
    fn test_parse_caption_side() {
384
1
        assert_eq!(parse_caption_side("top").unwrap(), StyleCaptionSide::Top);
385
1
        assert_eq!(
386
1
            parse_caption_side("bottom").unwrap(),
387
            StyleCaptionSide::Bottom
388
        );
389
1
        assert!(parse_caption_side("invalid").is_err());
390
1
    }
391

            
392
    #[test]
393
1
    fn test_parse_empty_cells() {
394
1
        assert_eq!(parse_empty_cells("show").unwrap(), StyleEmptyCells::Show);
395
1
        assert_eq!(parse_empty_cells("hide").unwrap(), StyleEmptyCells::Hide);
396
1
        assert!(parse_empty_cells("invalid").is_err());
397
1
    }
398
}
399

            
400
#[cfg(test)]
401
#[allow(clippy::float_cmp)] // exact comparisons are the point: FloatValue is fixed-point
402
mod autotest_generated {
403
    use super::*;
404
    use crate::props::basic::SizeMetric;
405

            
406
    // `FloatValue` stores millipixels in an `isize` (value * 1000, truncated via
407
    // `as`). `.number.number()` is that raw integer -- asserting on it keeps the
408
    // numeric tests exact instead of comparing floats.
409
    fn raw(p: PixelValue) -> isize {
410
        p.number.number()
411
    }
412

            
413
    fn table_layout_ok(s: &str) -> bool {
414
        parse_table_layout(s).is_ok()
415
    }
416
    fn border_collapse_ok(s: &str) -> bool {
417
        parse_border_collapse(s).is_ok()
418
    }
419
    fn caption_side_ok(s: &str) -> bool {
420
        parse_caption_side(s).is_ok()
421
    }
422
    fn empty_cells_ok(s: &str) -> bool {
423
        parse_empty_cells(s).is_ok()
424
    }
425

            
426
    /// Every keyword parser, type-erased to `&str -> bool` (is it accepted?), so
427
    /// the malformed-input cases can be asserted against all four at once.
428
    type KeywordParser = (&'static str, fn(&str) -> bool);
429
    const KEYWORD_PARSERS: &[KeywordParser] = &[
430
        ("table-layout", table_layout_ok),
431
        ("border-collapse", border_collapse_ok),
432
        ("caption-side", caption_side_ok),
433
        ("empty-cells", empty_cells_ok),
434
    ];
435

            
436
    fn assert_all_keyword_parsers_reject(input: &str, why: &str) {
437
        for (prop, parse) in KEYWORD_PARSERS {
438
            assert!(
439
                !parse(input),
440
                "{prop}: expected {input:?} to be rejected ({why}), but it parsed"
441
            );
442
        }
443
    }
444

            
445
    // ------------------------------------------------------------------------
446
    // constructors
447
    // ------------------------------------------------------------------------
448

            
449
    #[test]
450
    fn new_applies_the_same_spacing_to_both_axes() {
451
        let s = LayoutBorderSpacing::new(PixelValue::const_px(7));
452
        assert_eq!(s.horizontal, PixelValue::const_px(7));
453
        assert_eq!(s.vertical, PixelValue::const_px(7));
454
        assert_eq!(s.horizontal, s.vertical);
455
    }
456

            
457
    #[test]
458
    fn new_separate_preserves_argument_order() {
459
        // Asymmetric on purpose: a swapped assignment would still pass if both
460
        // axes shared a metric *and* a value.
461
        let s =
462
            LayoutBorderSpacing::new_separate(PixelValue::const_px(3), PixelValue::percent(50.0));
463
        assert_eq!(s.horizontal, PixelValue::const_px(3));
464
        assert_eq!(s.vertical, PixelValue::percent(50.0));
465
        assert_ne!(s.horizontal, s.vertical);
466
    }
467

            
468
    #[test]
469
    fn constructors_do_not_panic_on_extreme_floats() {
470
        let extremes = [
471
            0.0f32,
472
            -0.0,
473
            1.0,
474
            -1.0,
475
            f32::EPSILON,
476
            f32::MIN_POSITIVE,
477
            -f32::MIN_POSITIVE,
478
            f32::MAX,
479
            f32::MIN,
480
            f32::INFINITY,
481
            f32::NEG_INFINITY,
482
            f32::NAN,
483
        ];
484

            
485
        for v in extremes {
486
            let same = LayoutBorderSpacing::new(PixelValue::px(v));
487
            assert_eq!(same.horizontal, same.vertical, "new({v}) must be symmetric");
488

            
489
            for w in extremes {
490
                let sep = LayoutBorderSpacing::new_separate(PixelValue::px(v), PixelValue::em(w));
491
                assert_eq!(sep.horizontal.metric, SizeMetric::Px);
492
                assert_eq!(sep.vertical.metric, SizeMetric::Em);
493
                // Whatever the input float was, the stored value is a plain isize,
494
                // so it can never be NaN/inf once it lands in the struct.
495
                assert!(sep.horizontal.number.get().is_finite());
496
                assert!(sep.vertical.number.get().is_finite());
497
            }
498
        }
499
    }
500

            
501
    #[test]
502
    fn nan_spacing_is_flattened_to_zero_and_stays_comparable() {
503
        // `FloatValue::new` does `NaN * 1000.0 as isize`, and an `as` cast maps NaN
504
        // to 0. So a NaN spacing silently becomes 0px rather than poisoning Eq/Ord
505
        // (which are derived over the isize, not the float).
506
        let nan = LayoutBorderSpacing::new(PixelValue::px(f32::NAN));
507
        assert_eq!(raw(nan.horizontal), 0);
508
        assert_eq!(raw(nan.vertical), 0);
509

            
510
        // Reflexivity would fail here if equality were float-based.
511
        assert_eq!(nan, nan);
512
        assert_eq!(nan, LayoutBorderSpacing::new(PixelValue::px(f32::NAN)));
513
        assert_eq!(nan, LayoutBorderSpacing::new(PixelValue::px(0.0)));
514
        assert_eq!(nan, LayoutBorderSpacing::default());
515
    }
516

            
517
    #[test]
518
    fn infinite_spacing_saturates_instead_of_wrapping() {
519
        // `inf * 1000.0 as isize` saturates at the isize bounds; ditto any finite
520
        // f32 whose *1000 scaling overflows (f32::MAX).
521
        for input in [f32::INFINITY, f32::MAX, 1e38] {
522
            let s = LayoutBorderSpacing::new(PixelValue::px(input));
523
            assert_eq!(raw(s.horizontal), isize::MAX, "{input} must saturate high");
524
            assert!(s.horizontal.number.get().is_finite());
525
        }
526
        for input in [f32::NEG_INFINITY, f32::MIN, -1e38] {
527
            let s = LayoutBorderSpacing::new(PixelValue::px(input));
528
            assert_eq!(raw(s.horizontal), isize::MIN, "{input} must saturate low");
529
            assert!(s.horizontal.number.get().is_finite());
530
        }
531
    }
532

            
533
    #[test]
534
    fn equal_border_spacings_hash_equal() {
535
        use std::{
536
            collections::hash_map::DefaultHasher,
537
            hash::{Hash, Hasher},
538
        };
539

            
540
        fn hash(s: LayoutBorderSpacing) -> u64 {
541
            let mut h = DefaultHasher::new();
542
            s.hash(&mut h);
543
            h.finish()
544
        }
545

            
546
        // NaN and 0.0 collapse to the same stored value, so the Hash/Eq contract
547
        // must hold across them too.
548
        assert_eq!(
549
            hash(LayoutBorderSpacing::new(PixelValue::px(f32::NAN))),
550
            hash(LayoutBorderSpacing::default())
551
        );
552
        assert_eq!(
553
            hash(LayoutBorderSpacing::new(PixelValue::const_px(4))),
554
            hash(LayoutBorderSpacing::new_separate(
555
                PixelValue::const_px(4),
556
                PixelValue::const_px(4)
557
            ))
558
        );
559
    }
560

            
561
    #[test]
562
    fn defaults_are_the_css_initial_values() {
563
        assert_eq!(LayoutTableLayout::default(), LayoutTableLayout::Auto);
564
        assert_eq!(
565
            StyleBorderCollapse::default(),
566
            StyleBorderCollapse::Separate
567
        );
568
        assert_eq!(StyleCaptionSide::default(), StyleCaptionSide::Top);
569
        assert_eq!(StyleEmptyCells::default(), StyleEmptyCells::Show);
570

            
571
        let d = LayoutBorderSpacing::default();
572
        assert_eq!(d, LayoutBorderSpacing::new(PixelValue::const_px(0)));
573
        assert_eq!(raw(d.horizontal), 0);
574
        assert_eq!(raw(d.vertical), 0);
575
        assert_eq!(d.horizontal.metric, SizeMetric::Px);
576
    }
577

            
578
    // ------------------------------------------------------------------------
579
    // keyword parsers: table-layout / border-collapse / caption-side / empty-cells
580
    // ------------------------------------------------------------------------
581

            
582
    #[test]
583
    fn keyword_parsers_accept_every_variant() {
584
        // Positive controls -- exhaustive over the variants of each enum.
585
        assert_eq!(parse_table_layout("auto").unwrap(), LayoutTableLayout::Auto);
586
        assert_eq!(
587
            parse_table_layout("fixed").unwrap(),
588
            LayoutTableLayout::Fixed
589
        );
590
        assert_eq!(
591
            parse_border_collapse("separate").unwrap(),
592
            StyleBorderCollapse::Separate
593
        );
594
        assert_eq!(
595
            parse_border_collapse("collapse").unwrap(),
596
            StyleBorderCollapse::Collapse
597
        );
598
        assert_eq!(parse_caption_side("top").unwrap(), StyleCaptionSide::Top);
599
        assert_eq!(
600
            parse_caption_side("bottom").unwrap(),
601
            StyleCaptionSide::Bottom
602
        );
603
        assert_eq!(parse_empty_cells("show").unwrap(), StyleEmptyCells::Show);
604
        assert_eq!(parse_empty_cells("hide").unwrap(), StyleEmptyCells::Hide);
605
    }
606

            
607
    #[test]
608
    fn keyword_parsers_reject_empty_input() {
609
        assert_all_keyword_parsers_reject("", "empty input");
610
        assert_eq!(
611
            parse_table_layout(""),
612
            Err(LayoutTableLayoutParseError::InvalidKeyword(""))
613
        );
614
        assert_eq!(
615
            parse_border_collapse(""),
616
            Err(StyleBorderCollapseParseError::InvalidKeyword(""))
617
        );
618
        assert_eq!(
619
            parse_caption_side(""),
620
            Err(StyleCaptionSideParseError::InvalidKeyword(""))
621
        );
622
        assert_eq!(
623
            parse_empty_cells(""),
624
            Err(StyleEmptyCellsParseError::InvalidKeyword(""))
625
        );
626
    }
627

            
628
    #[test]
629
    fn keyword_parsers_reject_whitespace_only_input() {
630
        for input in ["   ", "\t", "\n", "\r\n", "\t\n \x0c", "\u{a0}", "\u{2028}"] {
631
            assert_all_keyword_parsers_reject(input, "whitespace only");
632
        }
633
        // The trim happens before the match, so the error payload is the *trimmed*
634
        // input -- i.e. the empty string, not the original blanks.
635
        assert_eq!(
636
            parse_table_layout("  \t\n "),
637
            Err(LayoutTableLayoutParseError::InvalidKeyword(""))
638
        );
639
    }
640

            
641
    #[test]
642
    fn keyword_parsers_trim_surrounding_whitespace() {
643
        assert_eq!(
644
            parse_table_layout("   auto\t\n").unwrap(),
645
            LayoutTableLayout::Auto
646
        );
647
        assert_eq!(
648
            parse_border_collapse("\r\n collapse  ").unwrap(),
649
            StyleBorderCollapse::Collapse
650
        );
651
        assert_eq!(
652
            parse_caption_side("\t bottom \t").unwrap(),
653
            StyleCaptionSide::Bottom
654
        );
655
        assert_eq!(
656
            parse_empty_cells("\n hide \n").unwrap(),
657
            StyleEmptyCells::Hide
658
        );
659
    }
660

            
661
    #[test]
662
    fn keyword_parsers_also_trim_non_css_unicode_whitespace() {
663
        // Characterized leniency: `str::trim` strips everything with the Unicode
664
        // White_Space property, but CSS whitespace is only space/tab/LF/CR/FF. So
665
        // NBSP- and LINE-SEPARATOR-padded keywords are accepted here even though a
666
        // conformant tokenizer would reject them.
667
        assert_eq!(
668
            parse_table_layout("\u{a0}auto\u{a0}").unwrap(),
669
            LayoutTableLayout::Auto
670
        );
671
        assert_eq!(
672
            parse_empty_cells("\u{2028}show\u{2029}").unwrap(),
673
            StyleEmptyCells::Show
674
        );
675
    }
676

            
677
    #[test]
678
    fn keyword_parse_errors_carry_the_trimmed_input() {
679
        // The error borrows from `input` (lifetime-tied) and reports the trimmed
680
        // slice, not the raw one.
681
        assert_eq!(
682
            parse_table_layout("  bogus  "),
683
            Err(LayoutTableLayoutParseError::InvalidKeyword("bogus"))
684
        );
685
        assert_eq!(
686
            parse_border_collapse(" separate collapse "),
687
            Err(StyleBorderCollapseParseError::InvalidKeyword(
688
                "separate collapse"
689
            ))
690
        );
691
        assert_eq!(
692
            parse_caption_side("\ttop;\t"),
693
            Err(StyleCaptionSideParseError::InvalidKeyword("top;"))
694
        );
695
        assert_eq!(
696
            parse_empty_cells(" show hide "),
697
            Err(StyleEmptyCellsParseError::InvalidKeyword("show hide"))
698
        );
699
    }
700

            
701
    #[test]
702
    fn keyword_parsers_are_case_sensitive() {
703
        // Conformance gap (characterized, matching `parse_pixel_value`): CSS
704
        // keywords are ASCII case-insensitive, so `table-layout: AUTO` is valid CSS
705
        // -- but the match arms only cover the lowercase spelling.
706
        for input in [
707
            "AUTO", "Auto", "aUtO", "FIXED", "SEPARATE", "Collapse", "TOP", "Bottom", "SHOW",
708
            "Hide",
709
        ] {
710
            assert_all_keyword_parsers_reject(input, "keyword matching is case-sensitive");
711
        }
712
    }
713

            
714
    #[test]
715
    fn keyword_parsers_reject_garbage() {
716
        for input in [
717
            "invalid",
718
            "auto fixed",
719
            "auto;",
720
            "auto;garbage",
721
            "auto/*c*/",
722
            "/*auto*/",
723
            "au to",
724
            "a\0uto",
725
            "\0",
726
            "\u{7f}",
727
            "-->",
728
            "<!--",
729
            "!important",
730
            "\\61 uto",
731
            "'auto'",
732
            "\"auto\"",
733
            "auto()",
734
            "url(auto)",
735
        ] {
736
            assert_all_keyword_parsers_reject(input, "garbage");
737
        }
738
    }
739

            
740
    #[test]
741
    fn keyword_parsers_reject_boundary_numeric_strings() {
742
        // None of these properties take a number; the numeric boundary cases must
743
        // not be coerced into a keyword.
744
        for input in [
745
            "0",
746
            "-0",
747
            "0.0",
748
            "1",
749
            "-1",
750
            "9223372036854775807",  // i64::MAX
751
            "-9223372036854775808", // i64::MIN
752
            "18446744073709551616", // u64::MAX + 1
753
            "1e400",
754
            "-1e400",
755
            "3.4028235e38",
756
            "1.17549435e-38",
757
            "NaN",
758
            "nan",
759
            "inf",
760
            "-inf",
761
            "infinity",
762
        ] {
763
            assert_all_keyword_parsers_reject(input, "numeric input for a keyword property");
764
        }
765
    }
766

            
767
    #[test]
768
    fn keyword_parsers_reject_leading_and_trailing_junk() {
769
        assert_all_keyword_parsers_reject("xauto", "leading junk");
770
        assert_all_keyword_parsers_reject("autox", "trailing junk");
771
        assert_all_keyword_parsers_reject("auto!", "trailing junk");
772
        assert_all_keyword_parsers_reject("(fixed)", "wrapped in parens");
773
        assert_all_keyword_parsers_reject("collapse,", "trailing comma");
774
        // Trailing/leading *whitespace* is the one thing that is trimmed away.
775
        assert_eq!(
776
            parse_table_layout("auto ").unwrap(),
777
            LayoutTableLayout::Auto
778
        );
779
    }
780

            
781
    #[test]
782
    fn keyword_parsers_survive_unicode_input() {
783
        for input in [
784
            "\u{1F600}",                        // emoji
785
            "auto\u{0301}",                     // combining acute on the final char
786
            "\u{FF41}\u{FF55}\u{FF54}\u{FF4F}", // fullwidth "auto"
787
            "\u{202E}auto",                     // RTL override prefix
788
            "\u{FEFF}auto",                     // BOM prefix (not Unicode whitespace)
789
            "аuto",                             // leading CYRILLIC A homoglyph
790
            "🇩🇪",                               // regional indicator pair
791
            "e\u{0301}\u{0301}\u{0301}",
792
            "\u{10FFFF}", // highest scalar value
793
        ] {
794
            assert_all_keyword_parsers_reject(input, "non-ASCII input");
795
        }
796
        // Slicing must stay on char boundaries: the error payload borrows the input.
797
        assert_eq!(
798
            parse_table_layout("  \u{1F600}  "),
799
            Err(LayoutTableLayoutParseError::InvalidKeyword("\u{1F600}"))
800
        );
801
    }
802

            
803
    #[test]
804
    fn keyword_parsers_survive_extremely_long_input() {
805
        let long = "a".repeat(1_000_000);
806
        assert_all_keyword_parsers_reject(&long, "1M-char input");
807
        assert_eq!(
808
            parse_table_layout(&long),
809
            Err(LayoutTableLayoutParseError::InvalidKeyword(long.as_str()))
810
        );
811

            
812
        // A million repetitions of a *valid* token is still not the token.
813
        let repeated = "auto".repeat(250_000);
814
        assert_all_keyword_parsers_reject(&repeated, "repeated valid token");
815

            
816
        // Padding a valid keyword with a megabyte of whitespace still parses.
817
        let padded = format!("{}auto{}", " ".repeat(500_000), "\n".repeat(500_000));
818
        assert_eq!(
819
            parse_table_layout(&padded).unwrap(),
820
            LayoutTableLayout::Auto
821
        );
822
    }
823

            
824
    #[test]
825
    fn keyword_parsers_survive_deeply_nested_input() {
826
        // These parsers are non-recursive, so 10k nesting levels must not blow the
827
        // stack -- assert that explicitly so a future recursive-descent rewrite of
828
        // the value parser trips here.
829
        let nested = format!("{}auto{}", "(".repeat(10_000), ")".repeat(10_000));
830
        assert_all_keyword_parsers_reject(&nested, "10k nested brackets");
831

            
832
        let braces = "{".repeat(50_000);
833
        assert_all_keyword_parsers_reject(&braces, "50k open braces");
834
    }
835

            
836
    // ------------------------------------------------------------------------
837
    // border-spacing
838
    // ------------------------------------------------------------------------
839

            
840
    #[test]
841
    fn border_spacing_single_value_applies_to_both_axes() {
842
        let s = parse_border_spacing("5px").unwrap();
843
        assert_eq!(s.horizontal, PixelValue::const_px(5));
844
        assert_eq!(s.vertical, PixelValue::const_px(5));
845
        assert_eq!(s, LayoutBorderSpacing::new(PixelValue::const_px(5)));
846
    }
847

            
848
    #[test]
849
    fn border_spacing_two_values_are_horizontal_then_vertical() {
850
        let s = parse_border_spacing("5px 10px").unwrap();
851
        assert_eq!(s.horizontal, PixelValue::const_px(5));
852
        assert_eq!(s.vertical, PixelValue::const_px(10));
853
        // Order matters: the reversed input must not compare equal.
854
        assert_ne!(s, parse_border_spacing("10px 5px").unwrap());
855
    }
856

            
857
    #[test]
858
    fn border_spacing_accepts_mixed_metrics_per_axis() {
859
        let s = parse_border_spacing("1em 50%").unwrap();
860
        assert_eq!(s.horizontal.metric, SizeMetric::Em);
861
        assert_eq!(raw(s.horizontal), 1000);
862
        assert_eq!(s.vertical.metric, SizeMetric::Percent);
863
        assert_eq!(raw(s.vertical), 50_000);
864

            
865
        // "rem" must win over "em" in the suffix table.
866
        assert_eq!(
867
            parse_border_spacing("2rem").unwrap().horizontal.metric,
868
            SizeMetric::Rem
869
        );
870
        // ...and "vmax"/"vmin" over "vw"/"vh".
871
        assert_eq!(
872
            parse_border_spacing("2vmax 3vmin")
873
                .unwrap()
874
                .horizontal
875
                .metric,
876
            SizeMetric::Vmax
877
        );
878
    }
879

            
880
    #[test]
881
    fn border_spacing_rejects_empty_and_whitespace_only_input() {
882
        // `split_whitespace` yields zero parts, which falls through to the `_` arm.
883
        for input in ["", "   ", "\t\n", "\r\n\x0c ", "\u{a0}", "\u{2028}\u{2029}"] {
884
            assert_eq!(
885
                parse_border_spacing(input),
886
                Err(LayoutBorderSpacingParseError::InvalidFormat),
887
                "expected InvalidFormat for {input:?}"
888
            );
889
        }
890
    }
891

            
892
    #[test]
893
    fn border_spacing_rejects_more_than_two_components() {
894
        for input in ["5px 10px 15px", "1px 2px 3px 4px", "0 0 0"] {
895
            assert_eq!(
896
                parse_border_spacing(input),
897
                Err(LayoutBorderSpacingParseError::InvalidFormat),
898
                "expected InvalidFormat for {input:?}"
899
            );
900
        }
901
    }
902

            
903
    #[test]
904
    fn border_spacing_collapses_arbitrary_internal_whitespace() {
905
        let expected =
906
            LayoutBorderSpacing::new_separate(PixelValue::const_px(5), PixelValue::const_px(10));
907
        for input in [
908
            "5px 10px",
909
            "  5px   10px  ",
910
            "\t5px\n10px\r\n",
911
            "5px\x0c10px",
912
        ] {
913
            assert_eq!(parse_border_spacing(input).unwrap(), expected, "{input:?}");
914
        }
915
    }
916

            
917
    #[test]
918
    fn border_spacing_splits_on_non_css_unicode_whitespace() {
919
        // Characterized leniency (same root cause as the keyword trim):
920
        // `split_whitespace` uses the Unicode White_Space property, so a
921
        // non-breaking space separates the two components even though CSS would
922
        // tokenize `5px\u{a0}10px` as a single (invalid) dimension token.
923
        let s = parse_border_spacing("5px\u{a0}10px").unwrap();
924
        assert_eq!(s.horizontal, PixelValue::const_px(5));
925
        assert_eq!(s.vertical, PixelValue::const_px(10));
926
    }
927

            
928
    #[test]
929
    fn border_spacing_propagates_pixel_value_errors() {
930
        // Unit with no number.
931
        assert!(matches!(
932
            parse_border_spacing("px"),
933
            Err(LayoutBorderSpacingParseError::PixelValue(
934
                CssPixelValueParseError::NoValueGiven("px", SizeMetric::Px)
935
            ))
936
        ));
937
        // Garbage, unknown unit, trailing junk.
938
        for input in ["abc", "5foo", "5px;", "#5px", "5 .. px"] {
939
            assert!(
940
                parse_border_spacing(input).is_err(),
941
                "expected {input:?} to be rejected"
942
            );
943
        }
944
        // A separated unit makes the *second* component the failing one.
945
        assert!(matches!(
946
            parse_border_spacing("5 px"),
947
            Err(LayoutBorderSpacingParseError::PixelValue(
948
                CssPixelValueParseError::NoValueGiven("px", SizeMetric::Px)
949
            ))
950
        ));
951
        // The error payload borrows the offending slice, not the whole input.
952
        assert!(matches!(
953
            parse_border_spacing("5px zzz"),
954
            Err(LayoutBorderSpacingParseError::PixelValue(
955
                CssPixelValueParseError::InvalidPixelValue("zzz")
956
            ))
957
        ));
958
    }
959

            
960
    #[test]
961
    fn border_spacing_accepts_unitless_numbers() {
962
        // Characterized gap: `parse_pixel_value` falls back to a bare f32 and
963
        // assumes px, so `border-spacing: 5` is accepted as 5px. Per CSS, only a
964
        // unitless *zero* is legal for a <length>.
965
        assert_eq!(
966
            parse_border_spacing("0").unwrap(),
967
            LayoutBorderSpacing::new(PixelValue::const_px(0))
968
        );
969
        assert_eq!(
970
            parse_border_spacing("5").unwrap(),
971
            LayoutBorderSpacing::new(PixelValue::const_px(5))
972
        );
973
        // -0 must land on the same stored value as +0 (no signed-zero surprises).
974
        assert_eq!(raw(parse_border_spacing("-0").unwrap().horizontal), 0);
975
        assert_eq!(
976
            parse_border_spacing("-0").unwrap(),
977
            parse_border_spacing("0").unwrap()
978
        );
979
    }
980

            
981
    #[test]
982
    fn border_spacing_accepts_negative_values() {
983
        // Characterized gap: `border-spacing` is a non-negative <length> in CSS,
984
        // but nothing here clamps -- the negative value is stored as-is.
985
        let s = parse_border_spacing("-5px -10px").unwrap();
986
        assert_eq!(raw(s.horizontal), -5000);
987
        assert_eq!(raw(s.vertical), -10_000);
988
    }
989

            
990
    #[test]
991
    fn border_spacing_flattens_nan_to_zero() {
992
        // "NaN" is a valid f32 literal, so this reaches `FloatValue::new(NaN)`,
993
        // where `NaN * 1000.0 as isize` yields 0. The parse succeeds with 0px --
994
        // it does not panic, and it does not store a NaN.
995
        let s = parse_border_spacing("NaNpx").unwrap();
996
        assert_eq!(raw(s.horizontal), 0);
997
        assert_eq!(raw(s.vertical), 0);
998
        assert!(s.horizontal.number.get().is_finite());
999
        assert_eq!(s, LayoutBorderSpacing::default());
        let mixed = parse_border_spacing("NaNpx 4px").unwrap();
        assert_eq!(raw(mixed.horizontal), 0);
        assert_eq!(raw(mixed.vertical), 4000);
    }
    #[test]
    fn border_spacing_saturates_infinite_and_overflowing_values() {
        // Both an explicit infinity and a finite-but-overflowing literal (whose
        // *1000 scaling overflows isize) must saturate rather than wrap.
        for input in ["infpx", "infinitypx", "1e40px", "3.5e38px"] {
            let s = parse_border_spacing(input).unwrap();
            assert_eq!(raw(s.horizontal), isize::MAX, "{input} must saturate high");
            assert!(
                s.horizontal.number.get().is_finite(),
                "{input} must be finite"
            );
        }
        for input in ["-infpx", "-1e40px", "-3.5e38px"] {
            let s = parse_border_spacing(input).unwrap();
            assert_eq!(raw(s.horizontal), isize::MIN, "{input} must saturate low");
            assert!(
                s.horizontal.number.get().is_finite(),
                "{input} must be finite"
            );
        }
        // Saturation is per-axis, and the high/low bounds do not collapse together.
        let s = parse_border_spacing("infpx -infpx").unwrap();
        assert_eq!(raw(s.horizontal), isize::MAX);
        assert_eq!(raw(s.vertical), isize::MIN);
        assert_ne!(s.horizontal, s.vertical);
    }
    #[test]
    fn border_spacing_truncates_below_milli_precision() {
        // FloatValue is fixed-point with 3 decimals and truncates (does not round)
        // toward zero, so sub-millipixel input silently becomes 0.
        assert_eq!(raw(parse_border_spacing("0.0005px").unwrap().horizontal), 0);
        assert_eq!(
            raw(parse_border_spacing("0.9999px").unwrap().horizontal),
            999
        );
        assert_eq!(
            raw(parse_border_spacing("1.9999px").unwrap().horizontal),
            1999
        );
        // Denormal input must not panic or produce a non-finite stored value.
        let denormal = parse_border_spacing("1.17549435e-38px").unwrap();
        assert_eq!(raw(denormal.horizontal), 0);
    }
    #[test]
    fn border_spacing_survives_extremely_long_input() {
        // One 1M-char token: rejected by the pixel parser, and the error borrows
        // the whole slice back out.
        let long_token = "z".repeat(1_000_000);
        assert!(parse_border_spacing(&long_token).is_err());
        // 200k components: hits the `_ => InvalidFormat` arm without hanging.
        let many = "5px ".repeat(200_000);
        assert_eq!(
            parse_border_spacing(&many),
            Err(LayoutBorderSpacingParseError::InvalidFormat)
        );
        // A megabyte of padding around a valid single value still parses.
        let padded = format!("{}5px{}", " ".repeat(500_000), " ".repeat(500_000));
        assert_eq!(
            parse_border_spacing(&padded).unwrap(),
            LayoutBorderSpacing::new(PixelValue::const_px(5))
        );
    }
    #[test]
    fn border_spacing_survives_deeply_nested_input() {
        let nested = format!("{}5px{}", "(".repeat(10_000), ")".repeat(10_000));
        assert!(
            parse_border_spacing(&nested).is_err(),
            "10k nested brackets must be rejected, not stack-overflow"
        );
    }
    #[test]
    fn border_spacing_unicode_input_does_not_panic() {
        for input in [
            "\u{1F600}",
            "5\u{1F600}px",
            "5px \u{1F600}",
            "5px",        // fullwidth digit
            "5\u{0301}px", // combining mark between number and unit
            "\u{FEFF}5px", // BOM prefix (not whitespace -> part of the token)
        ] {
            assert!(
                parse_border_spacing(input).is_err(),
                "expected {input:?} to be rejected"
            );
        }
    }
    // ------------------------------------------------------------------------
    // round-trips: print_as_css_value -> parse_* must be the identity
    // ------------------------------------------------------------------------
    #[test]
    fn keyword_enums_roundtrip_through_css() {
        for v in [LayoutTableLayout::Auto, LayoutTableLayout::Fixed] {
            assert_eq!(parse_table_layout(&v.print_as_css_value()).unwrap(), v);
        }
        for v in [StyleBorderCollapse::Separate, StyleBorderCollapse::Collapse] {
            assert_eq!(parse_border_collapse(&v.print_as_css_value()).unwrap(), v);
        }
        for v in [StyleCaptionSide::Top, StyleCaptionSide::Bottom] {
            assert_eq!(parse_caption_side(&v.print_as_css_value()).unwrap(), v);
        }
        for v in [StyleEmptyCells::Show, StyleEmptyCells::Hide] {
            assert_eq!(parse_empty_cells(&v.print_as_css_value()).unwrap(), v);
        }
        // Defaults round-trip too.
        assert_eq!(
            parse_table_layout(&LayoutTableLayout::default().print_as_css_value()).unwrap(),
            LayoutTableLayout::default()
        );
    }
    #[test]
    fn keyword_enum_css_spellings_are_distinct() {
        // A copy-paste in `print_as_css_value` would make two variants print the
        // same string, which the round-trip above would silently accept for one of
        // them.
        assert_ne!(
            LayoutTableLayout::Auto.print_as_css_value(),
            LayoutTableLayout::Fixed.print_as_css_value()
        );
        assert_ne!(
            StyleBorderCollapse::Separate.print_as_css_value(),
            StyleBorderCollapse::Collapse.print_as_css_value()
        );
        assert_ne!(
            StyleCaptionSide::Top.print_as_css_value(),
            StyleCaptionSide::Bottom.print_as_css_value()
        );
        assert_ne!(
            StyleEmptyCells::Show.print_as_css_value(),
            StyleEmptyCells::Hide.print_as_css_value()
        );
    }
    #[test]
    fn border_spacing_roundtrips_through_css() {
        let values = [
            PixelValue::const_px(0),
            PixelValue::const_px(5),
            PixelValue::const_px(-5),
            PixelValue::px(1.5),
            PixelValue::px(-0.125),
            PixelValue::em(2.0),
            PixelValue::rem(0.5),
            PixelValue::percent(50.0),
            PixelValue::from_metric(SizeMetric::Pt, 12.0),
            PixelValue::from_metric(SizeMetric::Vmin, 3.25),
        ];
        for h in values {
            // Single-value form (horizontal == vertical).
            let same = LayoutBorderSpacing::new(h);
            assert_eq!(
                parse_border_spacing(&same.print_as_css_value()).unwrap(),
                same,
                "single-value round-trip failed for {h:?}"
            );
            // Two-value form.
            for v in values {
                let sep = LayoutBorderSpacing::new_separate(h, v);
                assert_eq!(
                    parse_border_spacing(&sep.print_as_css_value()).unwrap(),
                    sep,
                    "two-value round-trip failed for {h:?} / {v:?}"
                );
            }
        }
    }
    #[test]
    fn border_spacing_prints_one_value_only_when_both_axes_match() {
        assert_eq!(
            LayoutBorderSpacing::new(PixelValue::const_px(5)).print_as_css_value(),
            "5px"
        );
        assert_eq!(
            LayoutBorderSpacing::new_separate(PixelValue::const_px(5), PixelValue::const_px(10))
                .print_as_css_value(),
            "5px 10px"
        );
        // Same number, different unit -> still two values (the metric is part of Eq).
        assert_eq!(
            LayoutBorderSpacing::new_separate(PixelValue::const_px(0), PixelValue::percent(0.0))
                .print_as_css_value(),
            "0px 0%"
        );
        assert_eq!(
            LayoutBorderSpacing::default().print_as_css_value(),
            "0px",
            "the default must not print as a two-value form"
        );
    }
    #[test]
    fn border_spacing_saturated_value_roundtrips_stably() {
        // The saturated bound prints as a lossy f32 (9223372000000000px), but
        // re-parsing it saturates right back to the same stored bound, so the
        // round-trip is still a fixed point.
        let saturated = parse_border_spacing("infpx").unwrap();
        let printed = saturated.print_as_css_value();
        assert_eq!(parse_border_spacing(&printed).unwrap(), saturated);
        let low = parse_border_spacing("-infpx").unwrap();
        assert_eq!(
            parse_border_spacing(&low.print_as_css_value()).unwrap(),
            low
        );
    }
    #[test]
    fn border_spacing_parse_print_is_idempotent_after_quantization() {
        // Inputs whose precision the fixed-point representation cannot hold must
        // reach a fixed point after a single round-trip, not drift on every pass.
        for input in ["0.0005px", "0.9999px", "0.1px", "1e40px", "NaNpx", "-0"] {
            let once = parse_border_spacing(input).unwrap();
            let printed = once.print_as_css_value();
            let twice = parse_border_spacing(&printed).unwrap();
            assert_eq!(once, twice, "not idempotent for {input:?}");
            assert_eq!(
                printed,
                twice.print_as_css_value(),
                "not stable for {input:?}"
            );
        }
    }
    // ------------------------------------------------------------------------
    // FormatAsRustCode
    // ------------------------------------------------------------------------
    #[test]
    fn format_as_rust_code_emits_the_variant_paths() {
        assert_eq!(
            LayoutTableLayout::Fixed.format_as_rust_code(0),
            "LayoutTableLayout::Fixed"
        );
        assert_eq!(
            StyleBorderCollapse::Collapse.format_as_rust_code(0),
            "StyleBorderCollapse::Collapse"
        );
        assert_eq!(
            StyleCaptionSide::Bottom.format_as_rust_code(0),
            "StyleCaptionSide::Bottom"
        );
        assert_eq!(
            StyleEmptyCells::Hide.format_as_rust_code(0),
            "StyleEmptyCells::Hide"
        );
        // The indent argument is ignored -- it must not change the output.
        assert_eq!(
            LayoutTableLayout::Auto.format_as_rust_code(0),
            LayoutTableLayout::Auto.format_as_rust_code(usize::MAX)
        );
    }
    #[test]
    fn format_as_rust_code_for_border_spacing_is_total() {
        assert_eq!(
            LayoutBorderSpacing::new(PixelValue::const_px(5)).format_as_rust_code(0),
            "LayoutBorderSpacing { horizontal: \
             PixelValue::const_from_metric_fractional(SizeMetric::Px, 5, 0), vertical: \
             PixelValue::const_from_metric_fractional(SizeMetric::Px, 5, 0) }"
        );
        // Extreme / degenerate values must still format without panicking.
        for v in [
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::MAX,
            f32::MIN,
            -2.5,
        ] {
            let code = LayoutBorderSpacing::new(PixelValue::px(v)).format_as_rust_code(0);
            assert!(code.starts_with("LayoutBorderSpacing {"), "{v}: {code}");
            assert!(code.ends_with('}'), "{v}: {code}");
        }
    }
}