1
//! CSS properties for multi-column layout.
2
//!
3
//! Covers `column-count`, `column-width`, `column-span`, `column-fill`,
4
//! `column-rule-width`, `column-rule-style`, and `column-rule-color`.
5
//! Types are consumed via the `CssProperty` enum in the CSS property system.
6

            
7
use alloc::string::{String, ToString};
8
use core::num::ParseIntError;
9

            
10
use crate::props::{
11
    basic::{
12
        color::{parse_css_color, ColorU, CssColorParseError, CssColorParseErrorOwned},
13
        pixel::{
14
            parse_pixel_value, CssPixelValueParseError, CssPixelValueParseErrorOwned, PixelValue,
15
        },
16
    },
17
    formatter::PrintAsCssValue,
18
    style::border::{
19
        parse_border_style, BorderStyle, CssBorderStyleParseError, CssBorderStyleParseErrorOwned,
20
    },
21
};
22

            
23
// --- column-count ---
24

            
25
/// CSS `column-count` property: specifies the number of columns in a multi-column layout.
26
///
27
/// Values: `auto` or a positive integer.
28
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
29
#[repr(C, u8)]
30
#[derive(Default)]
31
pub enum ColumnCount {
32
    #[default]
33
    Auto,
34
    Integer(u32),
35
}
36

            
37
impl PrintAsCssValue for ColumnCount {
38
5
    fn print_as_css_value(&self) -> String {
39
5
        match self {
40
2
            Self::Auto => "auto".to_string(),
41
3
            Self::Integer(i) => i.to_string(),
42
        }
43
5
    }
44
}
45

            
46
// --- column-width ---
47
#[allow(variant_size_differences)]
48
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
49
// disparity accepted
50
/// CSS `column-width` property: specifies the optimal width of columns.
51
///
52
/// Values: `auto` or a length value (e.g. `200px`, `15em`).
53
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
54
#[repr(C, u8)]
55
#[derive(Default)]
56
pub enum ColumnWidth {
57
    #[default]
58
    Auto,
59
    Length(PixelValue),
60
}
61

            
62
impl PrintAsCssValue for ColumnWidth {
63
15
    fn print_as_css_value(&self) -> String {
64
15
        match self {
65
2
            Self::Auto => "auto".to_string(),
66
13
            Self::Length(px) => px.print_as_css_value(),
67
        }
68
15
    }
69
}
70

            
71
// --- column-span ---
72

            
73
/// CSS `column-span` property: whether an element spans across all columns.
74
///
75
/// Values: `none` (default) or `all`.
76
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
77
#[repr(C)]
78
#[derive(Default)]
79
pub enum ColumnSpan {
80
    #[default]
81
    None,
82
    All,
83
}
84

            
85
impl PrintAsCssValue for ColumnSpan {
86
1
    fn print_as_css_value(&self) -> String {
87
1
        String::from(match self {
88
1
            Self::None => "none",
89
            Self::All => "all",
90
        })
91
1
    }
92
}
93

            
94
// --- column-fill ---
95

            
96
/// CSS `column-fill` property: how content is distributed across columns.
97
///
98
/// Values: `balance` (default) or `auto`.
99
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
100
#[repr(C)]
101
#[derive(Default)]
102
pub enum ColumnFill {
103
    Auto,
104
    #[default]
105
    Balance,
106
}
107

            
108
impl PrintAsCssValue for ColumnFill {
109
1
    fn print_as_css_value(&self) -> String {
110
1
        String::from(match self {
111
            Self::Auto => "auto",
112
1
            Self::Balance => "balance",
113
        })
114
1
    }
115
}
116

            
117
// --- column-rule ---
118

            
119
/// CSS `column-rule-width` property: the width of the rule between columns.
120
///
121
/// Defaults to `medium` (3px).
122
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
123
#[repr(C)]
124
pub struct ColumnRuleWidth {
125
    pub inner: PixelValue,
126
}
127

            
128
impl Default for ColumnRuleWidth {
129
4
    fn default() -> Self {
130
4
        Self {
131
4
            inner: PixelValue::const_px(3),
132
4
        }
133
4
    }
134
}
135

            
136
impl PrintAsCssValue for ColumnRuleWidth {
137
6
    fn print_as_css_value(&self) -> String {
138
6
        self.inner.print_as_css_value()
139
6
    }
140
}
141

            
142
/// CSS `column-rule-style` property: the style of the rule between columns.
143
///
144
/// Uses `BorderStyle` values (e.g. `none`, `solid`, `dotted`).
145
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
146
#[repr(C)]
147
pub struct ColumnRuleStyle {
148
    pub inner: BorderStyle,
149
}
150

            
151
impl Default for ColumnRuleStyle {
152
3
    fn default() -> Self {
153
3
        Self {
154
3
            inner: BorderStyle::None,
155
3
        }
156
3
    }
157
}
158

            
159
impl PrintAsCssValue for ColumnRuleStyle {
160
11
    fn print_as_css_value(&self) -> String {
161
11
        self.inner.print_as_css_value()
162
11
    }
163
}
164

            
165
/// CSS `column-rule-color` property: the color of the rule between columns.
166
///
167
/// Per the CSS spec this should default to `currentcolor`, but currently
168
/// defaults to black as `currentcolor` requires a resolved-value pass at
169
/// layout time.
170
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
171
#[repr(C)]
172
pub struct ColumnRuleColor {
173
    pub inner: ColorU,
174
}
175

            
176
impl Default for ColumnRuleColor {
177
3
    fn default() -> Self {
178
        // NOTE: should be `currentcolor` per CSS spec, see doc comment on type
179
3
        Self {
180
3
            inner: ColorU::BLACK,
181
3
        }
182
3
    }
183
}
184

            
185
impl PrintAsCssValue for ColumnRuleColor {
186
9
    fn print_as_css_value(&self) -> String {
187
9
        self.inner.to_hash()
188
9
    }
189
}
190

            
191
// Formatting to Rust code
192
impl crate::codegen::format::FormatAsRustCode for ColumnCount {
193
2
    fn format_as_rust_code(&self, _tabs: usize) -> String {
194
2
        match self {
195
1
            Self::Auto => String::from("ColumnCount::Auto"),
196
1
            Self::Integer(i) => format!("ColumnCount::Integer({i})"),
197
        }
198
2
    }
199
}
200

            
201
impl crate::codegen::format::FormatAsRustCode for ColumnWidth {
202
2
    fn format_as_rust_code(&self, _tabs: usize) -> String {
203
2
        match self {
204
1
            Self::Auto => String::from("ColumnWidth::Auto"),
205
1
            Self::Length(px) => format!(
206
1
                "ColumnWidth::Length({})",
207
1
                crate::codegen::format::format_pixel_value(px)
208
            ),
209
        }
210
2
    }
211
}
212

            
213
impl crate::codegen::format::FormatAsRustCode for ColumnSpan {
214
2
    fn format_as_rust_code(&self, _tabs: usize) -> String {
215
2
        match self {
216
1
            Self::None => String::from("ColumnSpan::None"),
217
1
            Self::All => String::from("ColumnSpan::All"),
218
        }
219
2
    }
220
}
221

            
222
impl crate::codegen::format::FormatAsRustCode for ColumnFill {
223
2
    fn format_as_rust_code(&self, _tabs: usize) -> String {
224
2
        match self {
225
1
            Self::Auto => String::from("ColumnFill::Auto"),
226
1
            Self::Balance => String::from("ColumnFill::Balance"),
227
        }
228
2
    }
229
}
230

            
231
impl crate::codegen::format::FormatAsRustCode for ColumnRuleWidth {
232
1
    fn format_as_rust_code(&self, _tabs: usize) -> String {
233
1
        format!(
234
1
            "ColumnRuleWidth {{ inner: {} }}",
235
1
            crate::codegen::format::format_pixel_value(&self.inner)
236
        )
237
1
    }
238
}
239

            
240
impl crate::codegen::format::FormatAsRustCode for ColumnRuleStyle {
241
1
    fn format_as_rust_code(&self, tabs: usize) -> String {
242
1
        format!(
243
1
            "ColumnRuleStyle {{ inner: {} }}",
244
1
            self.inner.format_as_rust_code(tabs)
245
        )
246
1
    }
247
}
248

            
249
impl crate::codegen::format::FormatAsRustCode for ColumnRuleColor {
250
1
    fn format_as_rust_code(&self, _tabs: usize) -> String {
251
1
        format!(
252
1
            "ColumnRuleColor {{ inner: {} }}",
253
1
            crate::codegen::format::format_color_value(&self.inner)
254
        )
255
1
    }
256
}
257

            
258
// --- PARSERS ---
259

            
260
#[cfg(feature = "parser")]
261
pub mod parser {
262
    #[allow(clippy::wildcard_imports)]
263
    // parser submodule reuses the parent module's value types
264
    use super::*;
265
    use crate::corety::AzString;
266

            
267
    // -- ColumnCount parser
268

            
269
    #[derive(Clone, PartialEq, Eq)]
270
    pub enum ColumnCountParseError<'a> {
271
        InvalidValue(&'a str),
272
        ParseInt(ParseIntError),
273
    }
274

            
275
    impl_debug_as_display!(ColumnCountParseError<'a>);
276
    impl_display! { ColumnCountParseError<'a>, {
277
        InvalidValue(v) => format!("Invalid column-count value: \"{}\"", v),
278
        ParseInt(e) => format!("Invalid integer for column-count: {}", e),
279
    }}
280

            
281
    #[derive(Debug, Clone, PartialEq, Eq)]
282
    #[repr(C, u8)]
283
    pub enum ColumnCountParseErrorOwned {
284
        InvalidValue(AzString),
285
        ParseInt(AzString),
286
    }
287

            
288
    impl ColumnCountParseError<'_> {
289
        #[must_use]
290
6
        pub fn to_contained(&self) -> ColumnCountParseErrorOwned {
291
6
            match self {
292
4
                Self::InvalidValue(s) => {
293
4
                    ColumnCountParseErrorOwned::InvalidValue((*s).to_string().into())
294
                }
295
2
                Self::ParseInt(e) => ColumnCountParseErrorOwned::ParseInt(e.to_string().into()),
296
            }
297
6
        }
298
    }
299

            
300
    impl ColumnCountParseErrorOwned {
301
        #[must_use]
302
5
        pub fn to_shared(&self) -> ColumnCountParseError<'_> {
303
5
            match self {
304
4
                Self::InvalidValue(s) => ColumnCountParseError::InvalidValue(s),
305
                // ParseIntError cannot be reconstructed from its Display string,
306
                // so we fall back to a generic message. The original error text
307
                // is preserved in the owned `AzString` but not round-trippable.
308
1
                Self::ParseInt(_) => ColumnCountParseError::InvalidValue("invalid integer"),
309
            }
310
5
        }
311
    }
312

            
313
    /// # Errors
314
    ///
315
    /// Returns an error if `input` is not a valid CSS `column-count` value.
316
61
    pub fn parse_column_count(input: &str) -> Result<ColumnCount, ColumnCountParseError<'_>> {
317
61
        let trimmed = input.trim();
318
61
        if trimmed == "auto" {
319
5
            return Ok(ColumnCount::Auto);
320
56
        }
321
56
        let val: u32 = trimmed.parse().map_err(ColumnCountParseError::ParseInt)?;
322
11
        Ok(ColumnCount::Integer(val))
323
61
    }
324

            
325
    // -- ColumnWidth parser
326

            
327
    #[derive(Clone, PartialEq, Eq)]
328
    pub enum ColumnWidthParseError<'a> {
329
        InvalidValue(&'a str),
330
        PixelValue(CssPixelValueParseError<'a>),
331
    }
332

            
333
    impl_debug_as_display!(ColumnWidthParseError<'a>);
334
    impl_display! { ColumnWidthParseError<'a>, {
335
        InvalidValue(v) => format!("Invalid column-width value: \"{}\"", v),
336
        PixelValue(e) => format!("{}", e),
337
    }}
338
    impl_from! { CssPixelValueParseError<'a>, ColumnWidthParseError::PixelValue }
339

            
340
    #[derive(Debug, Clone, PartialEq, Eq)]
341
    #[repr(C, u8)]
342
    pub enum ColumnWidthParseErrorOwned {
343
        InvalidValue(AzString),
344
        PixelValue(CssPixelValueParseErrorOwned),
345
    }
346

            
347
    impl ColumnWidthParseError<'_> {
348
        #[must_use]
349
7
        pub fn to_contained(&self) -> ColumnWidthParseErrorOwned {
350
7
            match self {
351
3
                Self::InvalidValue(s) => {
352
3
                    ColumnWidthParseErrorOwned::InvalidValue((*s).to_string().into())
353
                }
354
4
                Self::PixelValue(e) => ColumnWidthParseErrorOwned::PixelValue(e.to_contained()),
355
            }
356
7
        }
357
    }
358

            
359
    impl ColumnWidthParseErrorOwned {
360
        #[must_use]
361
7
        pub fn to_shared(&self) -> ColumnWidthParseError<'_> {
362
7
            match self {
363
3
                Self::InvalidValue(s) => ColumnWidthParseError::InvalidValue(s),
364
4
                Self::PixelValue(e) => ColumnWidthParseError::PixelValue(e.to_shared()),
365
            }
366
7
        }
367
    }
368

            
369
    /// # Errors
370
    ///
371
    /// Returns an error if `input` is not a valid CSS `column-width` value.
372
58
    pub fn parse_column_width(input: &str) -> Result<ColumnWidth, ColumnWidthParseError<'_>> {
373
58
        let trimmed = input.trim();
374
58
        if trimmed == "auto" {
375
5
            return Ok(ColumnWidth::Auto);
376
53
        }
377
53
        Ok(ColumnWidth::Length(parse_pixel_value(trimmed)?))
378
58
    }
379

            
380
    // -- Other column parsers...
381
    macro_rules! define_simple_column_parser {
382
        (
383
            $fn_name:ident,
384
            $struct_name:ident,
385
            $error_name:ident,
386
            $error_owned_name:ident,
387
            $prop_name:expr,
388
            $($val:expr => $variant:path),+
389
        ) => {
390
            #[derive(Clone, PartialEq, Eq)]
391
            pub enum $error_name<'a> {
392
                InvalidValue(&'a str),
393
            }
394

            
395
            impl_debug_as_display!($error_name<'a>);
396
            impl_display! { $error_name<'a>, {
397
                InvalidValue(v) => format!("Invalid {} value: \"{}\"", $prop_name, v),
398
            }}
399

            
400
            #[derive(Debug, Clone, PartialEq, Eq)]
401
            #[repr(C, u8)]
402
            pub enum $error_owned_name {
403
                InvalidValue(AzString),
404
            }
405

            
406
            impl $error_name<'_> {
407
2
                #[must_use] pub fn to_contained(&self) -> $error_owned_name {
408
2
                    match self {
409
2
                        Self::InvalidValue(s) => $error_owned_name::InvalidValue(s.to_string().into()),
410
                    }
411
2
                }
412
            }
413

            
414
            impl $error_owned_name {
415
2
                #[must_use] pub fn to_shared(&self) -> $error_name<'_> {
416
2
                    match self {
417
2
                        Self::InvalidValue(s) => $error_name::InvalidValue(s.as_str()),
418
                    }
419
2
                }
420
            }
421

            
422
            /// # Errors
423
            ///
424
            /// Returns an error if `input` is not a valid CSS value for this property.
425
37
            pub fn $fn_name(input: &str) -> Result<$struct_name, $error_name<'_>> {
426
37
                match input.trim() {
427
32
                    $( $val => Ok($variant), )+
428
27
                    _ => Err($error_name::InvalidValue(input)),
429
                }
430
37
            }
431
        };
432
    }
433

            
434
    define_simple_column_parser!(
435
        parse_column_span,
436
        ColumnSpan,
437
        ColumnSpanParseError,
438
        ColumnSpanParseErrorOwned,
439
        "column-span",
440
        "none" => ColumnSpan::None,
441
        "all" => ColumnSpan::All
442
    );
443

            
444
    define_simple_column_parser!(
445
        parse_column_fill,
446
        ColumnFill,
447
        ColumnFillParseError,
448
        ColumnFillParseErrorOwned,
449
        "column-fill",
450
        "auto" => ColumnFill::Auto,
451
        "balance" => ColumnFill::Balance
452
    );
453

            
454
    // Parsers for column-rule-*
455

            
456
    #[derive(Clone, PartialEq, Eq)]
457
    pub enum ColumnRuleWidthParseError<'a> {
458
        Pixel(CssPixelValueParseError<'a>),
459
    }
460
    impl_debug_as_display!(ColumnRuleWidthParseError<'a>);
461
    impl_display! { ColumnRuleWidthParseError<'a>, { Pixel(e) => format!("{}", e) }}
462
    impl_from! { CssPixelValueParseError<'a>, ColumnRuleWidthParseError::Pixel }
463
    #[derive(Debug, Clone, PartialEq, Eq)]
464
    #[repr(C, u8)]
465
    pub enum ColumnRuleWidthParseErrorOwned {
466
        Pixel(CssPixelValueParseErrorOwned),
467
    }
468
    impl ColumnRuleWidthParseError<'_> {
469
        #[must_use]
470
3
        pub fn to_contained(&self) -> ColumnRuleWidthParseErrorOwned {
471
3
            match self {
472
3
                ColumnRuleWidthParseError::Pixel(e) => {
473
3
                    ColumnRuleWidthParseErrorOwned::Pixel(e.to_contained())
474
                }
475
            }
476
3
        }
477
    }
478
    impl ColumnRuleWidthParseErrorOwned {
479
        #[must_use]
480
3
        pub fn to_shared(&self) -> ColumnRuleWidthParseError<'_> {
481
3
            match self {
482
3
                Self::Pixel(e) => ColumnRuleWidthParseError::Pixel(e.to_shared()),
483
            }
484
3
        }
485
    }
486
    /// # Errors
487
    ///
488
    /// Returns an error if `input` is not a valid CSS `column-rule-width` value.
489
28
    pub fn parse_column_rule_width(
490
28
        input: &str,
491
28
    ) -> Result<ColumnRuleWidth, ColumnRuleWidthParseError<'_>> {
492
        Ok(ColumnRuleWidth {
493
28
            inner: parse_pixel_value(input)?,
494
        })
495
28
    }
496

            
497
    #[derive(Clone, PartialEq, Eq)]
498
    pub enum ColumnRuleStyleParseError<'a> {
499
        Style(CssBorderStyleParseError<'a>),
500
    }
501
    impl_debug_as_display!(ColumnRuleStyleParseError<'a>);
502
    impl_display! { ColumnRuleStyleParseError<'a>, { Style(e) => format!("{}", e) }}
503
    impl_from! { CssBorderStyleParseError<'a>, ColumnRuleStyleParseError::Style }
504
    #[derive(Debug, Clone, PartialEq, Eq)]
505
    #[repr(C, u8)]
506
    pub enum ColumnRuleStyleParseErrorOwned {
507
        Style(CssBorderStyleParseErrorOwned),
508
    }
509
    impl ColumnRuleStyleParseError<'_> {
510
        #[must_use]
511
2
        pub fn to_contained(&self) -> ColumnRuleStyleParseErrorOwned {
512
2
            match self {
513
2
                ColumnRuleStyleParseError::Style(e) => {
514
2
                    ColumnRuleStyleParseErrorOwned::Style(e.to_contained())
515
                }
516
            }
517
2
        }
518
    }
519
    impl ColumnRuleStyleParseErrorOwned {
520
        #[must_use]
521
2
        pub fn to_shared(&self) -> ColumnRuleStyleParseError<'_> {
522
2
            match self {
523
2
                Self::Style(e) => ColumnRuleStyleParseError::Style(e.to_shared()),
524
            }
525
2
        }
526
    }
527
    /// # Errors
528
    ///
529
    /// Returns an error if `input` is not a valid CSS `column-rule-style` value.
530
26
    pub fn parse_column_rule_style(
531
26
        input: &str,
532
26
    ) -> Result<ColumnRuleStyle, ColumnRuleStyleParseError<'_>> {
533
        Ok(ColumnRuleStyle {
534
26
            inner: parse_border_style(input)?,
535
        })
536
26
    }
537

            
538
    #[derive(Clone, PartialEq)]
539
    pub enum ColumnRuleColorParseError<'a> {
540
        Color(CssColorParseError<'a>),
541
    }
542
    impl_debug_as_display!(ColumnRuleColorParseError<'a>);
543
    impl_display! { ColumnRuleColorParseError<'a>, { Color(e) => format!("{}", e) }}
544
    impl_from! { CssColorParseError<'a>, ColumnRuleColorParseError::Color }
545
    #[derive(Debug, Clone, PartialEq)]
546
    #[repr(C, u8)]
547
    pub enum ColumnRuleColorParseErrorOwned {
548
        Color(CssColorParseErrorOwned),
549
    }
550
    impl ColumnRuleColorParseError<'_> {
551
        #[must_use]
552
4
        pub fn to_contained(&self) -> ColumnRuleColorParseErrorOwned {
553
4
            match self {
554
4
                ColumnRuleColorParseError::Color(e) => {
555
4
                    ColumnRuleColorParseErrorOwned::Color(e.to_contained())
556
                }
557
            }
558
4
        }
559
    }
560
    impl ColumnRuleColorParseErrorOwned {
561
        #[must_use]
562
4
        pub fn to_shared(&self) -> ColumnRuleColorParseError<'_> {
563
4
            match self {
564
4
                Self::Color(e) => ColumnRuleColorParseError::Color(e.to_shared()),
565
            }
566
4
        }
567
    }
568
    /// # Errors
569
    ///
570
    /// Returns an error if `input` is not a valid CSS `column-rule-color` value.
571
41
    pub fn parse_column_rule_color(
572
41
        input: &str,
573
41
    ) -> Result<ColumnRuleColor, ColumnRuleColorParseError<'_>> {
574
        Ok(ColumnRuleColor {
575
41
            inner: parse_css_color(input)?,
576
        })
577
41
    }
578
}
579

            
580
#[cfg(feature = "parser")]
581
pub use parser::*;
582

            
583
#[cfg(all(test, feature = "parser"))]
584
mod tests {
585
    use super::*;
586

            
587
    #[test]
588
1
    fn test_parse_column_count() {
589
1
        assert_eq!(parse_column_count("auto").unwrap(), ColumnCount::Auto);
590
1
        assert_eq!(parse_column_count("3").unwrap(), ColumnCount::Integer(3));
591
1
        assert!(parse_column_count("none").is_err());
592
1
        assert!(parse_column_count("2.5").is_err());
593
1
    }
594

            
595
    #[test]
596
1
    fn test_parse_column_width() {
597
1
        assert_eq!(parse_column_width("auto").unwrap(), ColumnWidth::Auto);
598
1
        assert_eq!(
599
1
            parse_column_width("200px").unwrap(),
600
1
            ColumnWidth::Length(PixelValue::px(200.0))
601
        );
602
1
        assert_eq!(
603
1
            parse_column_width("15em").unwrap(),
604
1
            ColumnWidth::Length(PixelValue::em(15.0))
605
        );
606
1
        assert!(parse_column_width("50%").is_ok()); // Percentage is valid for column-width
607
1
    }
608

            
609
    #[test]
610
1
    fn test_parse_column_span() {
611
1
        assert_eq!(parse_column_span("none").unwrap(), ColumnSpan::None);
612
1
        assert_eq!(parse_column_span("all").unwrap(), ColumnSpan::All);
613
1
        assert!(parse_column_span("2").is_err());
614
1
    }
615

            
616
    #[test]
617
1
    fn test_parse_column_fill() {
618
1
        assert_eq!(parse_column_fill("auto").unwrap(), ColumnFill::Auto);
619
1
        assert_eq!(parse_column_fill("balance").unwrap(), ColumnFill::Balance);
620
1
        assert!(parse_column_fill("none").is_err());
621
1
    }
622

            
623
    #[test]
624
1
    fn test_parse_column_rule() {
625
1
        assert_eq!(
626
1
            parse_column_rule_width("5px").unwrap().inner,
627
1
            PixelValue::px(5.0)
628
        );
629
1
        assert_eq!(
630
1
            parse_column_rule_style("dotted").unwrap().inner,
631
            BorderStyle::Dotted
632
        );
633
1
        assert_eq!(parse_column_rule_color("blue").unwrap().inner, ColorU::BLUE);
634
1
    }
635
}
636

            
637
#[cfg(all(test, feature = "parser"))]
638
#[allow(clippy::float_cmp)] // parsed values are compared against the exact source literals
639
mod autotest_generated {
640
    use super::*;
641
    use crate::{codegen::format::FormatAsRustCode, corety::AzString, props::basic::SizeMetric};
642

            
643
    // A long-but-not-pathological input size for the "does not hang" cases.
644
    const LONG: usize = 1_000_000;
645

            
646
    // -----------------------------------------------------------------
647
    // parse_column_count
648
    // -----------------------------------------------------------------
649

            
650
    #[test]
651
    fn column_count_valid_minimal_and_trimming() {
652
        assert_eq!(parse_column_count("auto").unwrap(), ColumnCount::Auto);
653
        assert_eq!(parse_column_count("1").unwrap(), ColumnCount::Integer(1));
654
        // The parser trims, so surrounding whitespace must not change the value.
655
        assert_eq!(parse_column_count("  auto\t\n").unwrap(), ColumnCount::Auto);
656
        assert_eq!(
657
            parse_column_count(" \n 12 \t").unwrap(),
658
            ColumnCount::Integer(12)
659
        );
660
    }
661

            
662
    #[test]
663
    fn column_count_rejects_empty_and_whitespace_only() {
664
        assert!(parse_column_count("").is_err());
665
        assert!(parse_column_count("   ").is_err());
666
        assert!(parse_column_count("\t\n\r ").is_err());
667
    }
668

            
669
    #[test]
670
    fn column_count_rejects_garbage_without_panicking() {
671
        for bad in [
672
            "none",
673
            "auto auto",
674
            "3px",
675
            "3;garbage",
676
            "3 4",
677
            "2.5",
678
            "0x10",
679
            "1_000",
680
            "--3",
681
            "+-3",
682
            "\0",
683
            "3\0",
684
            "١٢٣",
685
            "Ù£",
686
            "3",
687
            "NaN",
688
            "inf",
689
            "-inf",
690
            "e5",
691
            "1e3",
692
        ] {
693
            assert!(
694
                parse_column_count(bad).is_err(),
695
                "column-count accepted garbage: {bad:?}"
696
            );
697
        }
698
    }
699

            
700
    #[test]
701
    fn column_count_case_sensitivity_is_exact() {
702
        // NOTE: CSS keywords are ASCII-case-insensitive; this parser is not.
703
        // Documented here as the *current* contract - it must at least not panic.
704
        assert!(parse_column_count("AUTO").is_err());
705
        assert!(parse_column_count("Auto").is_err());
706
    }
707

            
708
    #[test]
709
    fn column_count_u32_boundaries_saturate_into_err_not_wrap() {
710
        // Lower bound: 0 is accepted even though CSS requires a positive integer.
711
        assert_eq!(parse_column_count("0").unwrap(), ColumnCount::Integer(0));
712
        // `u32::from_str` accepts a leading '+'.
713
        assert_eq!(parse_column_count("+7").unwrap(), ColumnCount::Integer(7));
714
        // Exact u32 ceiling parses; one above must be a clean Err, never a wrap to 0.
715
        assert_eq!(
716
            parse_column_count("4294967295").unwrap(),
717
            ColumnCount::Integer(u32::MAX)
718
        );
719
        assert!(parse_column_count("4294967296").is_err());
720
        // i64::MAX / u64::MAX / a 40-digit number all overflow u32 -> Err, no wraparound.
721
        assert!(parse_column_count("9223372036854775807").is_err());
722
        assert!(parse_column_count("18446744073709551615").is_err());
723
        assert!(parse_column_count("9999999999999999999999999999999999999999").is_err());
724
        // Negatives (including -0) are not representable in u32.
725
        assert!(parse_column_count("-1").is_err());
726
        assert!(parse_column_count("-0").is_err());
727
    }
728

            
729
    #[test]
730
    fn column_count_extremely_long_input_terminates() {
731
        let huge = "9".repeat(LONG);
732
        assert!(parse_column_count(&huge).is_err());
733
        let huge_keyword = "auto".repeat(LONG / 4);
734
        assert!(parse_column_count(&huge_keyword).is_err());
735
        // Whitespace-padded huge input: trimming must not be quadratic or panic.
736
        let padded = format!("{}{}{}", " ".repeat(10_000), "7", " ".repeat(10_000));
737
        assert_eq!(
738
            parse_column_count(&padded).unwrap(),
739
            ColumnCount::Integer(7)
740
        );
741
    }
742

            
743
    #[test]
744
    fn column_count_deeply_nested_input_does_not_stack_overflow() {
745
        let nested = "(".repeat(10_000);
746
        assert!(parse_column_count(&nested).is_err());
747
        let balanced = format!("{}{}", "(".repeat(10_000), ")".repeat(10_000));
748
        assert!(parse_column_count(&balanced).is_err());
749
    }
750

            
751
    #[test]
752
    fn column_count_unicode_input_does_not_panic() {
753
        for bad in [
754
            "\u{1F600}",
755
            "auto\u{1F600}",
756
            "e\u{301}",     // combining acute accent
757
            "\u{202E}3",    // RTL override
758
            "\u{FEFF}auto", // BOM (not whitespace -> not trimmed)
759
            "au\u{0000}to",
760
        ] {
761
            assert!(
762
                parse_column_count(bad).is_err(),
763
                "column-count accepted unicode junk: {bad:?}"
764
            );
765
        }
766
    }
767

            
768
    #[test]
769
    fn column_count_roundtrips_through_print_as_css_value() {
770
        for value in [
771
            ColumnCount::Auto,
772
            ColumnCount::Integer(0),
773
            ColumnCount::Integer(1),
774
            ColumnCount::Integer(u32::MAX),
775
        ] {
776
            let printed = value.print_as_css_value();
777
            assert_eq!(
778
                parse_column_count(&printed).unwrap(),
779
                value,
780
                "round-trip failed for {value:?} (printed as {printed:?})"
781
            );
782
        }
783
    }
784

            
785
    // -----------------------------------------------------------------
786
    // ColumnCountParseError::to_contained / ColumnCountParseErrorOwned::to_shared
787
    // -----------------------------------------------------------------
788

            
789
    #[test]
790
    fn column_count_error_invalid_value_roundtrips_losslessly() {
791
        for s in ["", "x", "  padded  ", "\u{1F600}"] {
792
            let shared = ColumnCountParseError::InvalidValue(s);
793
            let owned = shared.to_contained();
794
            assert_eq!(
795
                owned,
796
                ColumnCountParseErrorOwned::InvalidValue(AzString::from(s))
797
            );
798
            assert_eq!(owned.to_shared(), shared);
799
        }
800
    }
801

            
802
    #[test]
803
    fn column_count_error_parse_int_roundtrip_is_lossy_but_safe() {
804
        let err = parse_column_count("abc").unwrap_err();
805
        assert_eq!(
806
            err,
807
            ColumnCountParseError::ParseInt("abc".parse::<u32>().unwrap_err())
808
        );
809

            
810
        let owned = err.to_contained();
811
        match &owned {
812
            ColumnCountParseErrorOwned::ParseInt(msg) => {
813
                assert!(!msg.as_str().is_empty(), "ParseInt message was dropped");
814
            }
815
            other => panic!("expected ParseInt, got {other:?}"),
816
        }
817

            
818
        // Documented lossy path: a ParseIntError cannot be rebuilt from its Display
819
        // string, so to_shared() degrades to a generic InvalidValue instead of panicking.
820
        assert_eq!(
821
            owned.to_shared(),
822
            ColumnCountParseError::InvalidValue("invalid integer")
823
        );
824
    }
825

            
826
    #[test]
827
    fn column_count_error_debug_equals_display_and_keeps_input() {
828
        let err = ColumnCountParseError::InvalidValue("weird\u{1F600}input");
829
        assert_eq!(format!("{err:?}"), format!("{err}"));
830
        assert!(format!("{err}").contains("weird\u{1F600}input"));
831

            
832
        // Overflow errors must render without panicking on an empty/huge instance.
833
        let overflow = parse_column_count("4294967296").unwrap_err();
834
        assert!(!format!("{overflow}").is_empty());
835
        assert!(!format!("{:?}", overflow.to_contained()).is_empty());
836
    }
837

            
838
    // -----------------------------------------------------------------
839
    // parse_column_width
840
    // -----------------------------------------------------------------
841

            
842
    #[test]
843
    fn column_width_valid_minimal_and_trimming() {
844
        assert_eq!(parse_column_width("auto").unwrap(), ColumnWidth::Auto);
845
        assert_eq!(parse_column_width("  auto  ").unwrap(), ColumnWidth::Auto);
846
        assert_eq!(
847
            parse_column_width("\t1px\n").unwrap(),
848
            ColumnWidth::Length(PixelValue::px(1.0))
849
        );
850
    }
851

            
852
    #[test]
853
    fn column_width_rejects_empty_whitespace_and_garbage() {
854
        assert!(parse_column_width("").is_err());
855
        assert!(parse_column_width("   ").is_err());
856
        assert!(parse_column_width("\t\n").is_err());
857
        for bad in [
858
            "px",
859
            "em",
860
            "%",
861
            "ten-px",
862
            "200px;garbage",
863
            "200 px extra",
864
            "#200px",
865
            "\u{1F600}",
866
            "20\u{301}px",
867
            "AUTO",
868
        ] {
869
            assert!(
870
                parse_column_width(bad).is_err(),
871
                "column-width accepted garbage: {bad:?}"
872
            );
873
        }
874
    }
875

            
876
    #[test]
877
    fn column_width_non_finite_numbers_are_stored_finite() {
878
        // f32::from_str accepts "NaN"/"inf", so these reach FloatValue::new().
879
        // The isize-backed FloatValue must clamp them - a NaN/inf leaking into
880
        // layout would poison every downstream computation.
881
        let nan = parse_column_width("NaN").unwrap();
882
        assert_eq!(nan, ColumnWidth::Length(PixelValue::px(0.0)));
883

            
884
        for input in ["inf", "Infinity", "-inf", "-Infinity", "1e40px", "-1e40px"] {
885
            let parsed = parse_column_width(input).unwrap();
886
            match parsed {
887
                ColumnWidth::Length(px) => assert!(
888
                    px.number.get().is_finite(),
889
                    "{input:?} produced a non-finite PixelValue"
890
                ),
891
                ColumnWidth::Auto => panic!("{input:?} unexpectedly parsed as auto"),
892
            }
893
        }
894
    }
895

            
896
    #[test]
897
    fn column_width_zero_and_subnormal_boundaries() {
898
        assert_eq!(
899
            parse_column_width("0").unwrap(),
900
            ColumnWidth::Length(PixelValue::px(0.0))
901
        );
902
        // -0.0 must normalize to the same stored value as +0.0 (FloatValue is an isize).
903
        assert_eq!(
904
            parse_column_width("-0").unwrap(),
905
            parse_column_width("0").unwrap()
906
        );
907
        assert_eq!(
908
            parse_column_width("-0px").unwrap(),
909
            ColumnWidth::Length(PixelValue::px(0.0))
910
        );
911
        // Subnormal f32: 1e-45 * 1000 truncates to 0 rather than panicking.
912
        assert_eq!(
913
            parse_column_width("1e-45px").unwrap(),
914
            ColumnWidth::Length(PixelValue::px(0.0))
915
        );
916
        // Negative lengths are (currently) accepted by the parser; must not wrap sign.
917
        match parse_column_width("-10px").unwrap() {
918
            ColumnWidth::Length(px) => assert!(px.number.get() < 0.0),
919
            ColumnWidth::Auto => panic!("-10px parsed as auto"),
920
        }
921
    }
922

            
923
    #[test]
924
    fn column_width_extremely_long_input_terminates() {
925
        let huge_digits = format!("{}px", "9".repeat(LONG));
926
        let parsed = parse_column_width(&huge_digits).unwrap();
927
        match parsed {
928
            ColumnWidth::Length(px) => assert!(px.number.get().is_finite()),
929
            ColumnWidth::Auto => panic!("digit soup parsed as auto"),
930
        }
931
        assert!(parse_column_width(&"a".repeat(LONG)).is_err());
932
        assert!(parse_column_width(&"auto".repeat(LONG / 4)).is_err());
933
    }
934

            
935
    #[test]
936
    fn column_width_deeply_nested_input_does_not_stack_overflow() {
937
        assert!(parse_column_width(&"(".repeat(10_000)).is_err());
938
        let balanced = format!("calc{}{}", "(".repeat(10_000), ")".repeat(10_000));
939
        assert!(parse_column_width(&balanced).is_err());
940
    }
941

            
942
    #[test]
943
    fn column_width_roundtrips_through_print_as_css_value() {
944
        // Only exactly-representable numbers: FloatValue truncates to 1/1000ths,
945
        // so e.g. 2.54cm is *not* expected to survive a print/parse cycle.
946
        let values = [
947
            ColumnWidth::Auto,
948
            ColumnWidth::Length(PixelValue::px(0.0)),
949
            ColumnWidth::Length(PixelValue::px(200.0)),
950
            ColumnWidth::Length(PixelValue::px(-12.5)),
951
            ColumnWidth::Length(PixelValue::em(1.5)),
952
            ColumnWidth::Length(PixelValue::rem(2.0)),
953
            ColumnWidth::Length(PixelValue::pt(-20.0)),
954
            ColumnWidth::Length(PixelValue::percent(50.0)),
955
            ColumnWidth::Length(PixelValue::inch(1.0)),
956
            ColumnWidth::Length(PixelValue::cm(3.0)),
957
            ColumnWidth::Length(PixelValue::mm(10.0)),
958
            ColumnWidth::Length(PixelValue::from_metric(SizeMetric::Vw, 10.0)),
959
            ColumnWidth::Length(PixelValue::from_metric(SizeMetric::Vh, 10.0)),
960
            ColumnWidth::Length(PixelValue::from_metric(SizeMetric::Vmax, 10.0)),
961
        ];
962
        for value in values {
963
            let printed = value.print_as_css_value();
964
            assert_eq!(
965
                parse_column_width(&printed).unwrap(),
966
                value,
967
                "round-trip failed for {value:?} (printed as {printed:?})"
968
            );
969
        }
970
    }
971

            
972
    // -----------------------------------------------------------------
973
    // ColumnWidthParseError::to_contained / ColumnWidthParseErrorOwned::to_shared
974
    // -----------------------------------------------------------------
975

            
976
    #[test]
977
    fn column_width_error_roundtrips_through_owned() {
978
        // InvalidValue is only reachable by hand - the parser always delegates to
979
        // the pixel parser - but the conversion still has to be lossless.
980
        for s in ["", "bogus", "\u{1F600}"] {
981
            let shared = ColumnWidthParseError::InvalidValue(s);
982
            let owned = shared.to_contained();
983
            assert_eq!(
984
                owned,
985
                ColumnWidthParseErrorOwned::InvalidValue(AzString::from(s))
986
            );
987
            assert_eq!(owned.to_shared(), shared);
988
        }
989

            
990
        // The variants the parser actually produces.
991
        for bad in ["", "ten-px", "px", "%"] {
992
            let err = parse_column_width(bad).unwrap_err();
993
            assert!(
994
                matches!(err, ColumnWidthParseError::PixelValue(_)),
995
                "{bad:?} produced an unexpected error variant: {err:?}"
996
            );
997
            let owned = err.to_contained();
998
            assert_eq!(owned.to_shared(), err, "lossy round-trip for {bad:?}");
999
            assert_eq!(format!("{err:?}"), format!("{err}"));
        }
    }
    // -----------------------------------------------------------------
    // parse_column_span / parse_column_fill
    // -----------------------------------------------------------------
    #[test]
    fn column_span_and_fill_accept_only_their_keywords() {
        assert_eq!(parse_column_span("none").unwrap(), ColumnSpan::None);
        assert_eq!(parse_column_span(" all \t").unwrap(), ColumnSpan::All);
        assert_eq!(parse_column_fill("auto").unwrap(), ColumnFill::Auto);
        assert_eq!(
            parse_column_fill("\n balance ").unwrap(),
            ColumnFill::Balance
        );
        for bad in [
            "",
            "   ",
            "2",
            "ALL",
            "None",
            "all all",
            "all;",
            "\u{1F600}",
            "nonee",
            "\0",
        ] {
            assert!(
                parse_column_span(bad).is_err(),
                "column-span accepted {bad:?}"
            );
        }
        for bad in [
            "",
            "   ",
            "none",
            "AUTO",
            "balanced",
            "auto balance",
            "\u{1F600}",
        ] {
            assert!(
                parse_column_fill(bad).is_err(),
                "column-fill accepted {bad:?}"
            );
        }
        // The two properties must not accept each other's keywords.
        assert!(parse_column_span("balance").is_err());
        assert!(parse_column_fill("all").is_err());
    }
    #[test]
    fn column_span_and_fill_survive_long_and_nested_input() {
        let huge = "all".repeat(LONG / 3);
        assert!(parse_column_span(&huge).is_err());
        assert!(parse_column_fill(&huge).is_err());
        let nested = "(".repeat(10_000);
        assert!(parse_column_span(&nested).is_err());
        assert!(parse_column_fill(&nested).is_err());
    }
    #[test]
    fn column_span_error_reports_the_untrimmed_input() {
        // The macro-generated parser matches on the trimmed input but reports the
        // *original* one - that asymmetry is load-bearing for error messages.
        let err = parse_column_span("  bogus  ").unwrap_err();
        match err {
            ColumnSpanParseError::InvalidValue(s) => assert_eq!(s, "  bogus  "),
        }
        assert_eq!(format!("{err:?}"), format!("{err}"));
        assert!(format!("{err}").contains("column-span"));
        let owned = err.to_contained();
        assert_eq!(
            owned,
            ColumnSpanParseErrorOwned::InvalidValue(AzString::from("  bogus  "))
        );
        assert_eq!(owned.to_shared(), err);
        let fill_err = parse_column_fill("\u{1F600}").unwrap_err();
        let fill_owned = fill_err.to_contained();
        assert_eq!(fill_owned.to_shared(), fill_err);
        assert!(format!("{fill_err}").contains("column-fill"));
    }
    // -----------------------------------------------------------------
    // parse_column_rule_width
    // -----------------------------------------------------------------
    #[test]
    fn column_rule_width_valid_and_invalid() {
        assert_eq!(
            parse_column_rule_width("5px").unwrap().inner,
            PixelValue::px(5.0)
        );
        assert_eq!(
            parse_column_rule_width("  0  ").unwrap().inner,
            PixelValue::px(0.0)
        );
        for bad in [
            "",
            "   ",
            "auto",
            "solid",
            "px",
            "\u{1F600}",
            "5px;5px",
            "5 px extra",
        ] {
            assert!(
                parse_column_rule_width(bad).is_err(),
                "column-rule-width accepted {bad:?}"
            );
        }
    }
    #[test]
    fn column_rule_width_extremes_stay_finite() {
        for input in ["NaN", "inf", "-inf", "1e40px", "-1e40px", "1e-45px"] {
            let w = parse_column_rule_width(input).unwrap();
            assert!(
                w.inner.number.get().is_finite(),
                "{input:?} produced a non-finite column-rule-width"
            );
        }
        assert!(parse_column_rule_width(&"9".repeat(LONG))
            .unwrap()
            .inner
            .number
            .get()
            .is_finite());
        assert!(parse_column_rule_width(&"(".repeat(10_000)).is_err());
    }
    #[test]
    fn column_rule_width_default_is_medium_and_roundtrips() {
        let default = ColumnRuleWidth::default();
        assert_eq!(default.inner, PixelValue::const_px(3));
        assert_eq!(default.print_as_css_value(), "3px");
        assert_eq!(parse_column_rule_width("3px").unwrap(), default);
        for value in [
            ColumnRuleWidth::default(),
            ColumnRuleWidth {
                inner: PixelValue::px(0.0),
            },
            ColumnRuleWidth {
                inner: PixelValue::em(2.5),
            },
            ColumnRuleWidth {
                inner: PixelValue::percent(-25.0),
            },
        ] {
            let printed = value.print_as_css_value();
            assert_eq!(parse_column_rule_width(&printed).unwrap(), value);
        }
    }
    #[test]
    fn column_rule_width_error_roundtrips_through_owned() {
        for bad in ["", "auto", "px"] {
            let err = parse_column_rule_width(bad).unwrap_err();
            let owned = err.to_contained();
            assert_eq!(owned.to_shared(), err, "lossy round-trip for {bad:?}");
            assert_eq!(format!("{err:?}"), format!("{err}"));
            assert!(!format!("{err}").is_empty());
        }
    }
    // -----------------------------------------------------------------
    // parse_column_rule_style
    // -----------------------------------------------------------------
    #[test]
    fn column_rule_style_accepts_every_border_style_and_roundtrips() {
        for style in [
            BorderStyle::None,
            BorderStyle::Solid,
            BorderStyle::Double,
            BorderStyle::Dotted,
            BorderStyle::Dashed,
            BorderStyle::Hidden,
            BorderStyle::Groove,
            BorderStyle::Ridge,
            BorderStyle::Inset,
            BorderStyle::Outset,
        ] {
            let value = ColumnRuleStyle { inner: style };
            let printed = value.print_as_css_value();
            assert_eq!(
                parse_column_rule_style(&printed).unwrap(),
                value,
                "round-trip failed for {style:?} (printed as {printed:?})"
            );
        }
    }
    #[test]
    fn column_rule_style_rejects_garbage_without_panicking() {
        for bad in [
            "",
            "   ",
            "SOLID",
            "solidd",
            "solid solid",
            "3px",
            "\u{1F600}",
            "\0",
            "soli\u{0301}d",
        ] {
            assert!(
                parse_column_rule_style(bad).is_err(),
                "column-rule-style accepted {bad:?}"
            );
        }
        assert!(parse_column_rule_style(&"solid".repeat(LONG / 5)).is_err());
        assert!(parse_column_rule_style(&"(".repeat(10_000)).is_err());
        // Leading/trailing whitespace *is* trimmed.
        assert_eq!(
            parse_column_rule_style("  dotted \n").unwrap().inner,
            BorderStyle::Dotted
        );
    }
    #[test]
    fn column_rule_style_error_roundtrips_through_owned() {
        let err = parse_column_rule_style("bogus").unwrap_err();
        let owned = err.to_contained();
        assert_eq!(owned.to_shared(), err);
        assert_eq!(format!("{err:?}"), format!("{err}"));
        assert!(format!("{err}").contains("bogus"));
        let unicode_err = parse_column_rule_style("\u{1F600}").unwrap_err();
        let unicode_owned = unicode_err.to_contained();
        assert_eq!(unicode_owned.to_shared(), unicode_err);
    }
    // -----------------------------------------------------------------
    // parse_column_rule_color
    // -----------------------------------------------------------------
    #[test]
    fn column_rule_color_accepts_names_hex_and_functions() {
        assert_eq!(parse_column_rule_color("blue").unwrap().inner, ColorU::BLUE);
        // Named colors *are* case-insensitive here (unlike column-span/fill/count).
        assert_eq!(
            parse_column_rule_color("  BLUE \t").unwrap().inner,
            ColorU::BLUE
        );
        assert_eq!(
            parse_column_rule_color("#000f").unwrap().inner,
            ColorU::BLACK
        );
        assert_eq!(
            parse_column_rule_color("#ff000080").unwrap().inner,
            ColorU::rgba(255, 0, 0, 128)
        );
        assert_eq!(parse_column_rule_color("transparent").unwrap().inner.a, 0);
        assert_eq!(
            parse_column_rule_color("rgba(255, 0, 0, 1.0)")
                .unwrap()
                .inner,
            ColorU::RED
        );
    }
    #[test]
    fn column_rule_color_rejects_garbage_without_panicking() {
        for bad in [
            "",
            "   ",
            "#",
            "#f",
            "#ff",
            "#fffff",
            "#zzzzzz",
            "notacolor",
            "rgb(",
            "rgb(1,2",
            "rgb()",
            "rgb(300)",
            "hsl(",
            "\u{1F600}",
            "#\u{1F600}",
            "\u{130}", // dotted capital I: to_lowercase() expands to 2 chars
        ] {
            assert!(
                parse_column_rule_color(bad).is_err(),
                "column-rule-color accepted {bad:?}"
            );
        }
    }
    #[test]
    fn column_rule_color_survives_long_and_nested_input() {
        assert!(parse_column_rule_color(&"a".repeat(100_000)).is_err());
        assert!(parse_column_rule_color(&"#".repeat(100_000)).is_err());
        // Unbalanced and deeply nested parens must not recurse or hang.
        assert!(parse_column_rule_color(&"(".repeat(10_000)).is_err());
        assert!(parse_column_rule_color(&format!("rgb{}", "(".repeat(10_000))).is_err());
        let nested = format!("rgb{}{}", "(".repeat(10_000), ")".repeat(10_000));
        assert!(parse_column_rule_color(&nested).is_err());
    }
    #[test]
    fn column_rule_color_roundtrips_through_to_hash() {
        for color in [
            ColorU::BLACK,
            ColorU::WHITE,
            ColorU::RED,
            ColorU::BLUE,
            ColorU::TRANSPARENT,
            ColorU::rgba(1, 2, 3, 4),
            ColorU::rgba(255, 255, 255, 0),
            ColorU::rgba(0, 0, 0, 255),
        ] {
            let value = ColumnRuleColor { inner: color };
            let printed = value.print_as_css_value(); // "#rrggbbaa"
            assert_eq!(printed.len(), 9, "unexpected hash form: {printed:?}");
            assert_eq!(
                parse_column_rule_color(&printed).unwrap(),
                value,
                "round-trip failed for {color:?} (printed as {printed:?})"
            );
        }
    }
    #[test]
    fn column_rule_color_error_roundtrips_through_owned() {
        for bad in ["", "notacolor", "rgb(", "#zzzzzz"] {
            let err = parse_column_rule_color(bad).unwrap_err();
            let owned = err.to_contained();
            assert_eq!(owned.to_shared(), err, "lossy round-trip for {bad:?}");
            assert_eq!(format!("{err:?}"), format!("{err}"));
            assert!(!format!("{err}").is_empty());
        }
    }
    // -----------------------------------------------------------------
    // Type invariants: defaults, ordering, hashing, codegen
    // -----------------------------------------------------------------
    #[test]
    fn defaults_match_the_documented_css_initial_values() {
        assert_eq!(ColumnCount::default(), ColumnCount::Auto);
        assert_eq!(ColumnWidth::default(), ColumnWidth::Auto);
        assert_eq!(ColumnSpan::default(), ColumnSpan::None);
        assert_eq!(ColumnFill::default(), ColumnFill::Balance);
        assert_eq!(ColumnRuleStyle::default().inner, BorderStyle::None);
        // NOTE: per CSS this should be `currentcolor`; the type doc records the deviation.
        assert_eq!(ColumnRuleColor::default().inner, ColorU::BLACK);
        // Every default must print to something its own parser accepts.
        assert_eq!(
            parse_column_count(&ColumnCount::default().print_as_css_value()).unwrap(),
            ColumnCount::default()
        );
        assert_eq!(
            parse_column_width(&ColumnWidth::default().print_as_css_value()).unwrap(),
            ColumnWidth::default()
        );
        assert_eq!(
            parse_column_span(&ColumnSpan::default().print_as_css_value()).unwrap(),
            ColumnSpan::default()
        );
        assert_eq!(
            parse_column_fill(&ColumnFill::default().print_as_css_value()).unwrap(),
            ColumnFill::default()
        );
        assert_eq!(
            parse_column_rule_width(&ColumnRuleWidth::default().print_as_css_value()).unwrap(),
            ColumnRuleWidth::default()
        );
        assert_eq!(
            parse_column_rule_style(&ColumnRuleStyle::default().print_as_css_value()).unwrap(),
            ColumnRuleStyle::default()
        );
        assert_eq!(
            parse_column_rule_color(&ColumnRuleColor::default().print_as_css_value()).unwrap(),
            ColumnRuleColor::default()
        );
    }
    #[test]
    fn ord_and_hash_agree_with_eq() {
        use std::{
            collections::hash_map::DefaultHasher,
            hash::{Hash, Hasher},
        };
        fn hash_of<T: Hash>(t: &T) -> u64 {
            let mut h = DefaultHasher::new();
            t.hash(&mut h);
            h.finish()
        }
        // Keyword variants sort before their value-carrying counterparts.
        assert!(ColumnCount::Auto < ColumnCount::Integer(0));
        assert!(ColumnCount::Integer(1) < ColumnCount::Integer(u32::MAX));
        assert!(ColumnWidth::Auto < ColumnWidth::Length(PixelValue::px(0.0)));
        assert!(ColumnSpan::None < ColumnSpan::All);
        assert!(ColumnFill::Auto < ColumnFill::Balance);
        // Eq implies equal hashes (these types are used as prop-cache keys).
        assert_eq!(
            hash_of(&ColumnCount::Integer(7)),
            hash_of(&parse_column_count("7").unwrap())
        );
        assert_eq!(
            hash_of(&ColumnWidth::Length(PixelValue::px(0.0))),
            hash_of(&parse_column_width("-0px").unwrap())
        );
        assert_ne!(hash_of(&ColumnFill::Auto), hash_of(&ColumnFill::Balance));
    }
    #[test]
    fn format_as_rust_code_emits_constructible_snippets() {
        assert_eq!(
            ColumnCount::Auto.format_as_rust_code(0),
            "ColumnCount::Auto"
        );
        assert_eq!(
            ColumnCount::Integer(u32::MAX).format_as_rust_code(0),
            "ColumnCount::Integer(4294967295)"
        );
        assert_eq!(
            ColumnWidth::Auto.format_as_rust_code(0),
            "ColumnWidth::Auto"
        );
        assert_eq!(ColumnSpan::All.format_as_rust_code(0), "ColumnSpan::All");
        assert_eq!(ColumnSpan::None.format_as_rust_code(0), "ColumnSpan::None");
        assert_eq!(ColumnFill::Auto.format_as_rust_code(0), "ColumnFill::Auto");
        assert_eq!(
            ColumnFill::Balance.format_as_rust_code(0),
            "ColumnFill::Balance"
        );
        // Extreme instances must format without panicking.
        let wide = ColumnWidth::Length(PixelValue::px(f32::MAX));
        assert!(wide
            .format_as_rust_code(0)
            .starts_with("ColumnWidth::Length("));
        let rule = ColumnRuleWidth {
            inner: PixelValue::px(-0.5),
        };
        assert!(rule.format_as_rust_code(0).starts_with("ColumnRuleWidth {"));
        let style = ColumnRuleStyle {
            inner: BorderStyle::Dotted,
        };
        assert!(style.format_as_rust_code(0).contains("Dotted"));
        let color = ColumnRuleColor {
            inner: ColorU::TRANSPARENT,
        };
        assert!(color
            .format_as_rust_code(0)
            .starts_with("ColumnRuleColor {"));
    }
}