1
//! CSS properties for border style, width, and color.
2

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

            
6
#[cfg(feature = "parser")]
7
use crate::props::basic::{color::parse_css_color, pixel::parse_pixel_value};
8
use crate::{
9
    corety::AzString,
10
    css::PrintAsCssValue,
11
    props::{
12
        basic::{
13
            color::{ColorU, CssColorParseError, CssColorParseErrorOwned},
14
            pixel::{
15
                CssPixelValueParseError, CssPixelValueParseErrorOwned, PixelValue,
16
                MEDIUM_BORDER_THICKNESS, THICK_BORDER_THICKNESS, THIN_BORDER_THICKNESS,
17
            },
18
        },
19
        macros::PixelValueTaker,
20
    },
21
};
22

            
23
/// Style of a `border`: solid, double, dash, ridge, etc.
24
#[derive(Debug, Copy, Clone, PartialEq, Ord, PartialOrd, Eq, Hash)]
25
#[repr(C)]
26
// +spec:box-model:28fad6 - Border style variants including groove/ridge/inset/outset for
27
// separated/collapsing border models
28
#[derive(Default)]
29
pub enum BorderStyle {
30
    #[default]
31
    None,
32
    Solid,
33
    Double,
34
    Dotted,
35
    Dashed,
36
    Hidden,
37
    Groove,
38
    Ridge,
39
    Inset,
40
    Outset,
41
}
42

            
43
impl fmt::Display for BorderStyle {
44
918
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45
918
        write!(
46
918
            f,
47
918
            "{}",
48
918
            match self {
49
12
                Self::None => "none",
50
737
                Self::Solid => "solid",
51
60
                Self::Double => "double",
52
60
                Self::Dotted => "dotted",
53
8
                Self::Dashed => "dashed",
54
8
                Self::Hidden => "hidden",
55
9
                Self::Groove => "groove",
56
8
                Self::Ridge => "ridge",
57
8
                Self::Inset => "inset",
58
8
                Self::Outset => "outset",
59
            }
60
        )
61
918
    }
62
}
63

            
64
impl PrintAsCssValue for BorderStyle {
65
31
    fn print_as_css_value(&self) -> String {
66
31
        self.to_string()
67
31
    }
68
}
69

            
70
/// Internal macro to reduce boilerplate for defining border-top, -right, -bottom, -left properties.
71
macro_rules! define_border_side_property {
72
    // For types that have a simple inner value and can be formatted with Display
73
    ($struct_name:ident, $inner_type:ty, $default:expr) => {
74
        #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
75
        #[repr(C)]
76
        pub struct $struct_name {
77
            pub inner: $inner_type,
78
        }
79
        impl ::core::fmt::Debug for $struct_name {
80
1719
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
81
1719
                write!(f, "{}", self.inner)
82
1719
            }
83
        }
84
        impl Default for $struct_name {
85
334
            fn default() -> Self {
86
334
                Self { inner: $default }
87
334
            }
88
        }
89
    };
90
    // Specialization for ColorU
91
    ($struct_name:ident,ColorU) => {
92
        #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
93
        #[repr(C)]
94
        pub struct $struct_name {
95
            pub inner: ColorU,
96
        }
97
        impl ::core::fmt::Debug for $struct_name {
98
833
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
99
833
                write!(f, "{}", self.inner.to_hash())
100
833
            }
101
        }
102
        // The default border color is 'currentcolor', but for simplicity we default to BLACK.
103
        // The style property resolver should handle the 'currentcolor' logic.
104
        impl Default for $struct_name {
105
5
            fn default() -> Self {
106
5
                Self {
107
5
                    inner: ColorU::BLACK,
108
5
                }
109
5
            }
110
        }
111
        impl $struct_name {
112
            #[must_use]
113
15
            pub fn interpolate(&self, other: &Self, t: f32) -> Self {
114
15
                Self {
115
15
                    inner: self.inner.interpolate(&other.inner, t),
116
15
                }
117
15
            }
118
        }
119
    }; /* NOTE: no separate `PixelValue` specialization arm — the generic
120
        * `($struct_name, $inner_type:ty, $default)` arm above already matches
121
        * `define_border_side_property!(.., PixelValue, ..)` (PixelValue is a `:ty`),
122
        * so a 3-arg PixelValue arm here would be unreachable (unused_macro_rules). */
123
}
124

            
125
// --- Individual Property Structs ---
126

            
127
// +spec:box-model:8c49fe - Border style properties (none, solid, double, dashed, etc.) and border
128
// color defaulting to element's color Border Style (border-*-style)
129
/// CSS `border-top-style` property (e.g. `solid`, `dashed`, `none`).
130
define_border_side_property!(StyleBorderTopStyle, BorderStyle, BorderStyle::None);
131
/// CSS `border-right-style` property (e.g. `solid`, `dashed`, `none`).
132
define_border_side_property!(StyleBorderRightStyle, BorderStyle, BorderStyle::None);
133
/// CSS `border-bottom-style` property (e.g. `solid`, `dashed`, `none`).
134
define_border_side_property!(StyleBorderBottomStyle, BorderStyle, BorderStyle::None);
135
/// CSS `border-left-style` property (e.g. `solid`, `dashed`, `none`).
136
define_border_side_property!(StyleBorderLeftStyle, BorderStyle, BorderStyle::None);
137

            
138
// Formatting implementations for border side style values
139
impl crate::codegen::format::FormatAsRustCode for StyleBorderTopStyle {
140
    fn format_as_rust_code(&self, tabs: usize) -> String {
141
        format!(
142
            "StyleBorderTopStyle {{ inner: {} }}",
143
            &self.inner.format_as_rust_code(tabs)
144
        )
145
    }
146
}
147

            
148
impl crate::codegen::format::FormatAsRustCode for StyleBorderRightStyle {
149
    fn format_as_rust_code(&self, tabs: usize) -> String {
150
        format!(
151
            "StyleBorderRightStyle {{ inner: {} }}",
152
            &self.inner.format_as_rust_code(tabs)
153
        )
154
    }
155
}
156

            
157
impl crate::codegen::format::FormatAsRustCode for StyleBorderLeftStyle {
158
    fn format_as_rust_code(&self, tabs: usize) -> String {
159
        format!(
160
            "StyleBorderLeftStyle {{ inner: {} }}",
161
            &self.inner.format_as_rust_code(tabs)
162
        )
163
    }
164
}
165

            
166
impl crate::codegen::format::FormatAsRustCode for StyleBorderBottomStyle {
167
    fn format_as_rust_code(&self, tabs: usize) -> String {
168
        format!(
169
            "StyleBorderBottomStyle {{ inner: {} }}",
170
            &self.inner.format_as_rust_code(tabs)
171
        )
172
    }
173
}
174

            
175
// Border Color (border-*-color)
176
/// CSS `border-top-color` property. Defaults to `ColorU::BLACK`.
177
define_border_side_property!(StyleBorderTopColor, ColorU);
178
/// CSS `border-right-color` property. Defaults to `ColorU::BLACK`.
179
define_border_side_property!(StyleBorderRightColor, ColorU);
180
/// CSS `border-bottom-color` property. Defaults to `ColorU::BLACK`.
181
define_border_side_property!(StyleBorderBottomColor, ColorU);
182
/// CSS `border-left-color` property. Defaults to `ColorU::BLACK`.
183
define_border_side_property!(StyleBorderLeftColor, ColorU);
184

            
185
// Border Width (border-*-width)
186
// The default width is 'medium', which corresponds to 3px.
187
// Import from pixel.rs for consistency.
188
/// CSS `border-top-width` property. Defaults to `MEDIUM_BORDER_THICKNESS` (3px).
189
define_border_side_property!(LayoutBorderTopWidth, PixelValue, MEDIUM_BORDER_THICKNESS);
190
/// CSS `border-right-width` property. Defaults to `MEDIUM_BORDER_THICKNESS` (3px).
191
define_border_side_property!(LayoutBorderRightWidth, PixelValue, MEDIUM_BORDER_THICKNESS);
192
/// CSS `border-bottom-width` property. Defaults to `MEDIUM_BORDER_THICKNESS` (3px).
193
define_border_side_property!(LayoutBorderBottomWidth, PixelValue, MEDIUM_BORDER_THICKNESS);
194
/// CSS `border-left-width` property. Defaults to `MEDIUM_BORDER_THICKNESS` (3px).
195
define_border_side_property!(LayoutBorderLeftWidth, PixelValue, MEDIUM_BORDER_THICKNESS);
196

            
197
macro_rules! impl_border_width_helpers {
198
    ($($t:ty),+) => { $(
199
        impl $t {
200
39
            #[must_use] pub fn interpolate(&self, other: &Self, t: f32) -> Self {
201
39
                Self { inner: self.inner.interpolate(&other.inner, t) }
202
39
            }
203
522500
            #[must_use] pub const fn const_px(value: isize) -> Self {
204
522500
                Self { inner: PixelValue::const_px(value) }
205
522500
            }
206
        }
207
    )+ };
208
}
209

            
210
impl_border_width_helpers!(
211
    LayoutBorderTopWidth,
212
    LayoutBorderRightWidth,
213
    LayoutBorderBottomWidth,
214
    LayoutBorderLeftWidth
215
);
216

            
217
/// Represents the three components of a border shorthand property, used as an intermediate
218
/// representation during parsing.
219
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
220
pub struct StyleBorderSide {
221
    pub border_width: PixelValue,
222
    pub border_style: BorderStyle,
223
    pub border_color: ColorU,
224
}
225

            
226
// --- PARSERS ---
227

            
228
// -- BorderStyle Parser --
229

            
230
#[cfg(feature = "parser")]
231
#[derive(Clone, PartialEq, Eq)]
232
pub enum CssBorderStyleParseError<'a> {
233
    InvalidStyle(&'a str),
234
}
235

            
236
#[cfg(feature = "parser")]
237
impl_debug_as_display!(CssBorderStyleParseError<'a>);
238
#[cfg(feature = "parser")]
239
impl_display! { CssBorderStyleParseError<'a>, {
240
    InvalidStyle(val) => format!("Invalid border style: \"{}\"", val),
241
}}
242

            
243
#[cfg(feature = "parser")]
244
#[derive(Debug, Clone, PartialEq, Eq)]
245
#[repr(C, u8)]
246
pub enum CssBorderStyleParseErrorOwned {
247
    InvalidStyle(AzString),
248
}
249

            
250
#[cfg(feature = "parser")]
251
impl CssBorderStyleParseError<'_> {
252
    #[must_use]
253
12
    pub fn to_contained(&self) -> CssBorderStyleParseErrorOwned {
254
12
        match self {
255
12
            CssBorderStyleParseError::InvalidStyle(s) => {
256
12
                CssBorderStyleParseErrorOwned::InvalidStyle((*s).to_string().into())
257
            }
258
        }
259
12
    }
260
}
261

            
262
#[cfg(feature = "parser")]
263
impl CssBorderStyleParseErrorOwned {
264
    #[must_use]
265
12
    pub fn to_shared(&self) -> CssBorderStyleParseError<'_> {
266
12
        match self {
267
12
            Self::InvalidStyle(s) => CssBorderStyleParseError::InvalidStyle(s.as_str()),
268
        }
269
12
    }
270
}
271

            
272
#[cfg(feature = "parser")]
273
/// # Errors
274
///
275
/// Returns an error if `input` is not a valid CSS `border-style` value.
276
18126
pub fn parse_border_style(input: &str) -> Result<BorderStyle, CssBorderStyleParseError<'_>> {
277
18126
    match input.trim() {
278
18126
        "none" => Ok(BorderStyle::None),
279
18114
        "solid" => Ok(BorderStyle::Solid),
280
261
        "double" => Ok(BorderStyle::Double),
281
235
        "dotted" => Ok(BorderStyle::Dotted),
282
207
        "dashed" => Ok(BorderStyle::Dashed),
283
173
        "hidden" => Ok(BorderStyle::Hidden),
284
151
        "groove" => Ok(BorderStyle::Groove),
285
141
        "ridge" => Ok(BorderStyle::Ridge),
286
131
        "inset" => Ok(BorderStyle::Inset),
287
118
        "outset" => Ok(BorderStyle::Outset),
288
109
        _ => Err(CssBorderStyleParseError::InvalidStyle(input)),
289
    }
290
18126
}
291

            
292
// -- Shorthand Parser (for `border`, `border-top`, etc.) --
293

            
294
#[cfg(feature = "parser")]
295
#[derive(Clone, PartialEq)]
296
pub enum CssBorderSideParseError<'a> {
297
    InvalidDeclaration(&'a str),
298
    Width(CssPixelValueParseError<'a>),
299
    Style(CssBorderStyleParseError<'a>),
300
    Color(CssColorParseError<'a>),
301
}
302

            
303
#[cfg(feature = "parser")]
304
impl_debug_as_display!(CssBorderSideParseError<'a>);
305
#[cfg(feature = "parser")]
306
impl_display! { CssBorderSideParseError<'a>, {
307
    InvalidDeclaration(e) => format!("Invalid border declaration: \"{}\"", e),
308
    Width(e) => format!("Invalid border-width component: {}", e),
309
    Style(e) => format!("Invalid border-style component: {}", e),
310
    Color(e) => format!("Invalid border-color component: {}", e),
311
}}
312

            
313
#[cfg(feature = "parser")]
314
impl_from!(CssPixelValueParseError<'a>, CssBorderSideParseError::Width);
315
#[cfg(feature = "parser")]
316
impl_from!(CssBorderStyleParseError<'a>, CssBorderSideParseError::Style);
317
#[cfg(feature = "parser")]
318
impl_from!(CssColorParseError<'a>, CssBorderSideParseError::Color);
319

            
320
#[cfg(feature = "parser")]
321
#[derive(Debug, Clone, PartialEq)]
322
#[repr(C, u8)]
323
pub enum CssBorderSideParseErrorOwned {
324
    InvalidDeclaration(AzString),
325
    Width(CssPixelValueParseErrorOwned),
326
    Style(CssBorderStyleParseErrorOwned),
327
    Color(CssColorParseErrorOwned),
328
}
329

            
330
#[cfg(feature = "parser")]
331
impl CssBorderSideParseError<'_> {
332
    #[must_use]
333
12
    pub fn to_contained(&self) -> CssBorderSideParseErrorOwned {
334
12
        match self {
335
5
            CssBorderSideParseError::InvalidDeclaration(s) => {
336
5
                CssBorderSideParseErrorOwned::InvalidDeclaration((*s).to_string().into())
337
            }
338
2
            CssBorderSideParseError::Width(e) => {
339
2
                CssBorderSideParseErrorOwned::Width(e.to_contained())
340
            }
341
2
            CssBorderSideParseError::Style(e) => {
342
2
                CssBorderSideParseErrorOwned::Style(e.to_contained())
343
            }
344
3
            CssBorderSideParseError::Color(e) => {
345
3
                CssBorderSideParseErrorOwned::Color(e.to_contained())
346
            }
347
        }
348
12
    }
349
}
350

            
351
#[cfg(feature = "parser")]
352
impl CssBorderSideParseErrorOwned {
353
    #[must_use]
354
11
    pub fn to_shared(&self) -> CssBorderSideParseError<'_> {
355
11
        match self {
356
4
            Self::InvalidDeclaration(s) => CssBorderSideParseError::InvalidDeclaration(s.as_str()),
357
2
            Self::Width(e) => CssBorderSideParseError::Width(e.to_shared()),
358
2
            Self::Style(e) => CssBorderSideParseError::Style(e.to_shared()),
359
3
            Self::Color(e) => CssBorderSideParseError::Color(e.to_shared()),
360
        }
361
11
    }
362
}
363

            
364
// Type alias for compatibility with old code
365
#[cfg(feature = "parser")]
366
pub type CssBorderParseError<'a> = CssBorderSideParseError<'a>;
367

            
368
/// Newtype wrapper around `CssBorderSideParseErrorOwned` for the `border` shorthand.
369
#[cfg(feature = "parser")]
370
#[derive(Debug, Clone, PartialEq)]
371
#[repr(C)]
372
pub struct CssBorderParseErrorOwned {
373
    pub inner: CssBorderSideParseErrorOwned,
374
}
375

            
376
#[cfg(feature = "parser")]
377
impl From<CssBorderSideParseErrorOwned> for CssBorderParseErrorOwned {
378
1
    fn from(v: CssBorderSideParseErrorOwned) -> Self {
379
1
        Self { inner: v }
380
1
    }
381
}
382

            
383
/// Parses a border shorthand property such as "1px solid red".
384
/// Handles any order of components and applies defaults for missing values.
385
#[cfg(feature = "parser")]
386
17911
fn parse_border_side(input: &str) -> Result<StyleBorderSide, CssBorderSideParseError<'_>> {
387
17911
    let mut width = None;
388
17911
    let mut style = None;
389
17911
    let mut color = None;
390

            
391
17911
    if input.trim().is_empty() {
392
9
        return Err(CssBorderSideParseError::InvalidDeclaration(input));
393
17902
    }
394

            
395
53630
    for part in input.split_whitespace() {
396
        // Try to parse as a width.
397
53630
        if width.is_none() {
398
17942
            if let Ok(w) = parse_border_width_value(part) {
399
17862
                width = Some(w);
400
17862
                continue;
401
80
            }
402
35688
        }
403

            
404
        // Try to parse as a style.
405
35768
        if style.is_none() {
406
17906
            if let Ok(s) = parse_border_style(part) {
407
17882
                style = Some(s);
408
17882
                continue;
409
24
            }
410
17862
        }
411

            
412
        // Try to parse as a color.
413
17886
        if color.is_none() {
414
17880
            if let Ok(c) = parse_css_color(part) {
415
17831
                color = Some(c);
416
17831
                continue;
417
49
            }
418
6
        }
419

            
420
        // If we get here, the part didn't match anything, or a value was specified twice.
421
55
        return Err(CssBorderSideParseError::InvalidDeclaration(input));
422
    }
423

            
424
17847
    Ok(StyleBorderSide {
425
17847
        border_width: width.unwrap_or(MEDIUM_BORDER_THICKNESS),
426
17847
        border_style: style.unwrap_or(BorderStyle::None),
427
17847
        border_color: color.unwrap_or(ColorU::BLACK),
428
17847
    })
429
17911
}
430

            
431
// --- Individual Property Parsers ---
432

            
433
#[cfg(feature = "parser")]
434
18071
fn parse_border_width_value(input: &str) -> Result<PixelValue, CssPixelValueParseError<'_>> {
435
18071
    match input.trim() {
436
18071
        "thin" => Ok(THIN_BORDER_THICKNESS),
437
18063
        "medium" => Ok(MEDIUM_BORDER_THICKNESS),
438
18057
        "thick" => Ok(THICK_BORDER_THICKNESS),
439
18047
        _ => parse_pixel_value(input),
440
    }
441
18071
}
442

            
443
#[cfg(feature = "parser")]
444
/// # Errors
445
///
446
/// Returns an error if `input` is not a valid CSS `border-top-width` value.
447
34
pub fn parse_border_top_width(
448
34
    input: &str,
449
34
) -> Result<LayoutBorderTopWidth, CssPixelValueParseError<'_>> {
450
34
    parse_border_width_value(input).map(|inner| LayoutBorderTopWidth { inner })
451
34
}
452

            
453
#[cfg(feature = "parser")]
454
/// # Errors
455
///
456
/// Returns an error if `input` is not a valid CSS `border-right-width` value.
457
14
pub fn parse_border_right_width(
458
14
    input: &str,
459
14
) -> Result<LayoutBorderRightWidth, CssPixelValueParseError<'_>> {
460
14
    parse_border_width_value(input).map(|inner| LayoutBorderRightWidth { inner })
461
14
}
462

            
463
#[cfg(feature = "parser")]
464
/// # Errors
465
///
466
/// Returns an error if `input` is not a valid CSS `border-bottom-width` value.
467
14
pub fn parse_border_bottom_width(
468
14
    input: &str,
469
14
) -> Result<LayoutBorderBottomWidth, CssPixelValueParseError<'_>> {
470
14
    parse_border_width_value(input).map(|inner| LayoutBorderBottomWidth { inner })
471
14
}
472

            
473
#[cfg(feature = "parser")]
474
/// # Errors
475
///
476
/// Returns an error if `input` is not a valid CSS `border-left-width` value.
477
15
pub fn parse_border_left_width(
478
15
    input: &str,
479
15
) -> Result<LayoutBorderLeftWidth, CssPixelValueParseError<'_>> {
480
15
    parse_border_width_value(input).map(|inner| LayoutBorderLeftWidth { inner })
481
15
}
482

            
483
#[cfg(feature = "parser")]
484
/// # Errors
485
///
486
/// Returns an error if `input` is not a valid CSS `border-top-style` value.
487
17
pub fn parse_border_top_style(
488
17
    input: &str,
489
17
) -> Result<StyleBorderTopStyle, CssBorderStyleParseError<'_>> {
490
17
    parse_border_style(input).map(|inner| StyleBorderTopStyle { inner })
491
17
}
492
#[cfg(feature = "parser")]
493
/// # Errors
494
///
495
/// Returns an error if `input` is not a valid CSS `border-right-style` value.
496
17
pub fn parse_border_right_style(
497
17
    input: &str,
498
17
) -> Result<StyleBorderRightStyle, CssBorderStyleParseError<'_>> {
499
17
    parse_border_style(input).map(|inner| StyleBorderRightStyle { inner })
500
17
}
501
#[cfg(feature = "parser")]
502
/// # Errors
503
///
504
/// Returns an error if `input` is not a valid CSS `border-bottom-style` value.
505
17
pub fn parse_border_bottom_style(
506
17
    input: &str,
507
17
) -> Result<StyleBorderBottomStyle, CssBorderStyleParseError<'_>> {
508
17
    parse_border_style(input).map(|inner| StyleBorderBottomStyle { inner })
509
17
}
510
#[cfg(feature = "parser")]
511
/// # Errors
512
///
513
/// Returns an error if `input` is not a valid CSS `border-left-style` value.
514
18
pub fn parse_border_left_style(
515
18
    input: &str,
516
18
) -> Result<StyleBorderLeftStyle, CssBorderStyleParseError<'_>> {
517
18
    parse_border_style(input).map(|inner| StyleBorderLeftStyle { inner })
518
18
}
519

            
520
#[cfg(feature = "parser")]
521
/// # Errors
522
///
523
/// Returns an error if `input` is not a valid CSS `border-top-color` value.
524
41
pub fn parse_border_top_color(input: &str) -> Result<StyleBorderTopColor, CssColorParseError<'_>> {
525
41
    parse_css_color(input).map(|inner| StyleBorderTopColor { inner })
526
41
}
527
#[cfg(feature = "parser")]
528
/// # Errors
529
///
530
/// Returns an error if `input` is not a valid CSS `border-right-color` value.
531
27
pub fn parse_border_right_color(
532
27
    input: &str,
533
27
) -> Result<StyleBorderRightColor, CssColorParseError<'_>> {
534
27
    parse_css_color(input).map(|inner| StyleBorderRightColor { inner })
535
27
}
536
#[cfg(feature = "parser")]
537
/// # Errors
538
///
539
/// Returns an error if `input` is not a valid CSS `border-bottom-color` value.
540
26
pub fn parse_border_bottom_color(
541
26
    input: &str,
542
26
) -> Result<StyleBorderBottomColor, CssColorParseError<'_>> {
543
26
    parse_css_color(input).map(|inner| StyleBorderBottomColor { inner })
544
26
}
545
#[cfg(feature = "parser")]
546
/// # Errors
547
///
548
/// Returns an error if `input` is not a valid CSS `border-left-color` value.
549
34
pub fn parse_border_left_color(
550
34
    input: &str,
551
34
) -> Result<StyleBorderLeftColor, CssColorParseError<'_>> {
552
34
    parse_css_color(input).map(|inner| StyleBorderLeftColor { inner })
553
34
}
554

            
555
// --- Border Color Shorthand ---
556

            
557
/// Parsed result of `border-color` shorthand (1-4 color values)
558
#[cfg(feature = "parser")]
559
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
560
pub struct StyleBorderColors {
561
    pub top: ColorU,
562
    pub right: ColorU,
563
    pub bottom: ColorU,
564
    pub left: ColorU,
565
}
566

            
567
/// Parses `border-color` shorthand: 1-4 color values
568
/// - 1 value: all sides
569
/// - 2 values: top/bottom, left/right
570
/// - 3 values: top, left/right, bottom
571
/// - 4 values: top, right, bottom, left
572
#[cfg(feature = "parser")]
573
/// # Errors
574
///
575
/// Returns an error if `input` is not a valid CSS `border-color` value.
576
34
pub fn parse_style_border_color(input: &str) -> Result<StyleBorderColors, CssColorParseError<'_>> {
577
34
    let input = input.trim();
578
34
    let parts: Vec<&str> = input.split_whitespace().collect();
579

            
580
34
    match parts.len() {
581
        1 => {
582
16
            let color = parse_css_color(parts[0])?;
583
14
            Ok(StyleBorderColors {
584
14
                top: color,
585
14
                right: color,
586
14
                bottom: color,
587
14
                left: color,
588
14
            })
589
        }
590
        2 => {
591
3
            let top_bottom = parse_css_color(parts[0])?;
592
3
            let left_right = parse_css_color(parts[1])?;
593
1
            Ok(StyleBorderColors {
594
1
                top: top_bottom,
595
1
                right: left_right,
596
1
                bottom: top_bottom,
597
1
                left: left_right,
598
1
            })
599
        }
600
        3 => {
601
6
            let top = parse_css_color(parts[0])?;
602
6
            let left_right = parse_css_color(parts[1])?;
603
6
            let bottom = parse_css_color(parts[2])?;
604
5
            Ok(StyleBorderColors {
605
5
                top,
606
5
                right: left_right,
607
5
                bottom,
608
5
                left: left_right,
609
5
            })
610
        }
611
        4 => {
612
3
            let top = parse_css_color(parts[0])?;
613
3
            let right = parse_css_color(parts[1])?;
614
3
            let bottom = parse_css_color(parts[2])?;
615
3
            let left = parse_css_color(parts[3])?;
616
2
            Ok(StyleBorderColors {
617
2
                top,
618
2
                right,
619
2
                bottom,
620
2
                left,
621
2
            })
622
        }
623
6
        _ => Err(CssColorParseError::InvalidColor(input)),
624
    }
625
34
}
626

            
627
// --- Border Style Shorthand ---
628

            
629
/// Parsed result of `border-style` shorthand (1-4 style values)
630
#[cfg(feature = "parser")]
631
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
632
pub struct StyleBorderStyles {
633
    pub top: BorderStyle,
634
    pub right: BorderStyle,
635
    pub bottom: BorderStyle,
636
    pub left: BorderStyle,
637
}
638

            
639
/// Parses `border-style` shorthand: 1-4 style values
640
#[cfg(feature = "parser")]
641
/// # Errors
642
///
643
/// Returns an error if `input` is not a valid CSS `border-style` value.
644
31
pub fn parse_style_border_style(
645
31
    input: &str,
646
31
) -> Result<StyleBorderStyles, CssBorderStyleParseError<'_>> {
647
31
    let input = input.trim();
648
31
    let parts: Vec<&str> = input.split_whitespace().collect();
649

            
650
31
    match parts.len() {
651
        1 => {
652
16
            let style = parse_border_style(parts[0])?;
653
14
            Ok(StyleBorderStyles {
654
14
                top: style,
655
14
                right: style,
656
14
                bottom: style,
657
14
                left: style,
658
14
            })
659
        }
660
        2 => {
661
3
            let top_bottom = parse_border_style(parts[0])?;
662
3
            let left_right = parse_border_style(parts[1])?;
663
1
            Ok(StyleBorderStyles {
664
1
                top: top_bottom,
665
1
                right: left_right,
666
1
                bottom: top_bottom,
667
1
                left: left_right,
668
1
            })
669
        }
670
        3 => {
671
2
            let top = parse_border_style(parts[0])?;
672
2
            let left_right = parse_border_style(parts[1])?;
673
2
            let bottom = parse_border_style(parts[2])?;
674
1
            Ok(StyleBorderStyles {
675
1
                top,
676
1
                right: left_right,
677
1
                bottom,
678
1
                left: left_right,
679
1
            })
680
        }
681
        4 => {
682
5
            let top = parse_border_style(parts[0])?;
683
5
            let right = parse_border_style(parts[1])?;
684
5
            let bottom = parse_border_style(parts[2])?;
685
5
            let left = parse_border_style(parts[3])?;
686
4
            Ok(StyleBorderStyles {
687
4
                top,
688
4
                right,
689
4
                bottom,
690
4
                left,
691
4
            })
692
        }
693
5
        _ => Err(CssBorderStyleParseError::InvalidStyle(input)),
694
    }
695
31
}
696

            
697
// --- Border Width Shorthand ---
698

            
699
/// Parsed result of `border-width` shorthand (1-4 width values)
700
#[cfg(feature = "parser")]
701
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
702
pub struct StyleBorderWidths {
703
    pub top: PixelValue,
704
    pub right: PixelValue,
705
    pub bottom: PixelValue,
706
    pub left: PixelValue,
707
}
708

            
709
/// Parses `border-width` shorthand: 1-4 width values
710
#[cfg(feature = "parser")]
711
/// # Errors
712
///
713
/// Returns an error if `input` is not a valid CSS `border-width` value.
714
60
pub fn parse_style_border_width(
715
60
    input: &str,
716
60
) -> Result<StyleBorderWidths, CssPixelValueParseError<'_>> {
717
60
    let input = input.trim();
718
60
    let parts: Vec<&str> = input.split_whitespace().collect();
719

            
720
60
    match parts.len() {
721
        1 => {
722
45
            let width = parse_pixel_value(parts[0])?;
723
40
            Ok(StyleBorderWidths {
724
40
                top: width,
725
40
                right: width,
726
40
                bottom: width,
727
40
                left: width,
728
40
            })
729
        }
730
        2 => {
731
4
            let top_bottom = parse_pixel_value(parts[0])?;
732
3
            let left_right = parse_pixel_value(parts[1])?;
733
1
            Ok(StyleBorderWidths {
734
1
                top: top_bottom,
735
1
                right: left_right,
736
1
                bottom: top_bottom,
737
1
                left: left_right,
738
1
            })
739
        }
740
        3 => {
741
2
            let top = parse_pixel_value(parts[0])?;
742
2
            let left_right = parse_pixel_value(parts[1])?;
743
2
            let bottom = parse_pixel_value(parts[2])?;
744
1
            Ok(StyleBorderWidths {
745
1
                top,
746
1
                right: left_right,
747
1
                bottom,
748
1
                left: left_right,
749
1
            })
750
        }
751
        4 => {
752
4
            let top = parse_pixel_value(parts[0])?;
753
4
            let right = parse_pixel_value(parts[1])?;
754
4
            let bottom = parse_pixel_value(parts[2])?;
755
4
            let left = parse_pixel_value(parts[3])?;
756
3
            Ok(StyleBorderWidths {
757
3
                top,
758
3
                right,
759
3
                bottom,
760
3
                left,
761
3
            })
762
        }
763
5
        _ => Err(CssPixelValueParseError::InvalidPixelValue(input)),
764
    }
765
60
}
766

            
767
// Compatibility alias
768
#[cfg(feature = "parser")]
769
/// # Errors
770
///
771
/// Returns an error if `input` is not a valid CSS `border` value.
772
17852
pub fn parse_style_border(input: &str) -> Result<StyleBorderSide, CssBorderParseError<'_>> {
773
17852
    parse_border_side(input)
774
17852
}
775

            
776
#[cfg(all(test, feature = "parser"))]
777
mod tests {
778
    use super::*;
779

            
780
    #[test]
781
1
    fn test_parse_border_style() {
782
1
        assert_eq!(parse_border_style("solid").unwrap(), BorderStyle::Solid);
783
1
        assert_eq!(parse_border_style("dotted").unwrap(), BorderStyle::Dotted);
784
1
        assert_eq!(parse_border_style("none").unwrap(), BorderStyle::None);
785
1
        assert_eq!(
786
1
            parse_border_style("  dashed  ").unwrap(),
787
            BorderStyle::Dashed
788
        );
789
1
        assert!(parse_border_style("solidd").is_err());
790
1
    }
791

            
792
    #[test]
793
1
    fn test_parse_border_side_shorthand() {
794
        // Full
795
1
        let result = parse_border_side("2px dotted #ff0000").unwrap();
796
1
        assert_eq!(result.border_width, PixelValue::px(2.0));
797
1
        assert_eq!(result.border_style, BorderStyle::Dotted);
798
1
        assert_eq!(result.border_color, ColorU::new_rgb(255, 0, 0));
799

            
800
        // Different order
801
1
        let result = parse_border_side("solid green 1em").unwrap();
802
1
        assert_eq!(result.border_width, PixelValue::em(1.0));
803
1
        assert_eq!(result.border_style, BorderStyle::Solid);
804
1
        assert_eq!(result.border_color, ColorU::new_rgb(0, 128, 0));
805

            
806
        // Missing width
807
1
        let result = parse_border_side("ridge #f0f").unwrap();
808
1
        assert_eq!(result.border_width, MEDIUM_BORDER_THICKNESS); // default
809
1
        assert_eq!(result.border_style, BorderStyle::Ridge);
810
1
        assert_eq!(result.border_color, ColorU::new_rgb(255, 0, 255));
811

            
812
        // Missing style
813
1
        let result = parse_border_side("5pt blue").unwrap();
814
1
        assert_eq!(result.border_width, PixelValue::pt(5.0));
815
1
        assert_eq!(result.border_style, BorderStyle::None); // default
816
1
        assert_eq!(result.border_color, ColorU::BLUE);
817

            
818
        // Missing color
819
1
        let result = parse_border_side("thick double").unwrap();
820
1
        assert_eq!(result.border_width, PixelValue::px(5.0));
821
1
        assert_eq!(result.border_style, BorderStyle::Double);
822
1
        assert_eq!(result.border_color, ColorU::BLACK); // default
823

            
824
        // Only one value
825
1
        let result = parse_border_side("inset").unwrap();
826
1
        assert_eq!(result.border_width, MEDIUM_BORDER_THICKNESS);
827
1
        assert_eq!(result.border_style, BorderStyle::Inset);
828
1
        assert_eq!(result.border_color, ColorU::BLACK);
829
1
    }
830

            
831
    #[test]
832
1
    fn test_parse_border_side_invalid() {
833
        // Two widths
834
1
        assert!(parse_border_side("1px 2px solid red").is_err());
835
        // Two styles
836
1
        assert!(parse_border_side("solid dashed red").is_err());
837
        // Two colors
838
1
        assert!(parse_border_side("red blue solid").is_err());
839
        // Empty
840
1
        assert!(parse_border_side("").is_err());
841
        // Unknown keyword
842
1
        assert!(parse_border_side("1px unknown red").is_err());
843
1
    }
844

            
845
    #[test]
846
1
    fn test_parse_longhand_border() {
847
1
        assert_eq!(
848
1
            parse_border_top_width("1.5em").unwrap().inner,
849
1
            PixelValue::em(1.5)
850
        );
851
1
        assert_eq!(
852
1
            parse_border_left_style("groove").unwrap().inner,
853
            BorderStyle::Groove
854
        );
855
1
        assert_eq!(
856
1
            parse_border_right_color("rgba(10, 20, 30, 0.5)")
857
1
                .unwrap()
858
                .inner,
859
1
            ColorU::new(10, 20, 30, 128)
860
        );
861
1
    }
862
}
863

            
864
#[cfg(test)]
865
mod autotest_generated {
866
    use super::*;
867

            
868
    const ALL_STYLES: [BorderStyle; 10] = [
869
        BorderStyle::None,
870
        BorderStyle::Solid,
871
        BorderStyle::Double,
872
        BorderStyle::Dotted,
873
        BorderStyle::Dashed,
874
        BorderStyle::Hidden,
875
        BorderStyle::Groove,
876
        BorderStyle::Ridge,
877
        BorderStyle::Inset,
878
        BorderStyle::Outset,
879
    ];
880

            
881
    // =====================================================================
882
    // BorderStyle: Display / PrintAsCssValue / Default
883
    // =====================================================================
884

            
885
    #[test]
886
    fn border_style_display_is_a_unique_lowercase_keyword_for_every_variant() {
887
        let mut seen: Vec<String> = Vec::new();
888
        for style in ALL_STYLES {
889
            let s = style.to_string();
890
            assert!(!s.is_empty(), "{style:?} renders as the empty string");
891
            assert!(
892
                s.chars().all(|c| c.is_ascii_lowercase()),
893
                "{style:?} renders as {s:?}, which is not a lowercase ASCII keyword"
894
            );
895
            assert!(
896
                !seen.contains(&s),
897
                "two BorderStyle variants both render as {s:?} (copy-paste in Display)"
898
            );
899
            seen.push(s);
900
        }
901
        assert_eq!(seen.len(), ALL_STYLES.len());
902
    }
903

            
904
    #[test]
905
    fn border_style_print_as_css_value_matches_display() {
906
        for style in ALL_STYLES {
907
            assert_eq!(style.print_as_css_value(), style.to_string());
908
        }
909
    }
910

            
911
    #[test]
912
    fn border_style_default_is_none_and_formats_as_none() {
913
        assert_eq!(BorderStyle::default(), BorderStyle::None);
914
        assert_eq!(BorderStyle::default().to_string(), "none");
915
    }
916

            
917
    // =====================================================================
918
    // Side-property structs: Default / Debug / const_px / interpolate
919
    // =====================================================================
920

            
921
    #[test]
922
    fn border_side_property_defaults_match_the_css_initial_values() {
923
        // border-*-style initial value is `none`
924
        assert_eq!(StyleBorderTopStyle::default().inner, BorderStyle::None);
925
        assert_eq!(StyleBorderRightStyle::default().inner, BorderStyle::None);
926
        assert_eq!(StyleBorderBottomStyle::default().inner, BorderStyle::None);
927
        assert_eq!(StyleBorderLeftStyle::default().inner, BorderStyle::None);
928

            
929
        // border-*-color has no `currentcolor` here; the documented stand-in is BLACK
930
        assert_eq!(StyleBorderTopColor::default().inner, ColorU::BLACK);
931
        assert_eq!(StyleBorderRightColor::default().inner, ColorU::BLACK);
932
        assert_eq!(StyleBorderBottomColor::default().inner, ColorU::BLACK);
933
        assert_eq!(StyleBorderLeftColor::default().inner, ColorU::BLACK);
934

            
935
        // border-*-width initial value is `medium` (3px)
936
        assert_eq!(
937
            LayoutBorderTopWidth::default().inner,
938
            MEDIUM_BORDER_THICKNESS
939
        );
940
        assert_eq!(
941
            LayoutBorderRightWidth::default().inner,
942
            MEDIUM_BORDER_THICKNESS
943
        );
944
        assert_eq!(
945
            LayoutBorderBottomWidth::default().inner,
946
            MEDIUM_BORDER_THICKNESS
947
        );
948
        assert_eq!(
949
            LayoutBorderLeftWidth::default().inner,
950
            MEDIUM_BORDER_THICKNESS
951
        );
952
        assert_eq!(MEDIUM_BORDER_THICKNESS, PixelValue::px(3.0));
953
    }
954

            
955
    #[test]
956
    fn border_side_property_debug_impls_are_the_documented_shapes() {
957
        // The macro deliberately overrides Debug: styles print the keyword,
958
        // colors print the 8-digit hash, widths print the pixel value.
959
        assert_eq!(format!("{:?}", StyleBorderTopStyle::default()), "none");
960
        assert_eq!(
961
            format!(
962
                "{:?}",
963
                StyleBorderLeftStyle {
964
                    inner: BorderStyle::Groove
965
                }
966
            ),
967
            "groove"
968
        );
969
        assert_eq!(format!("{:?}", StyleBorderTopColor::default()), "#000000ff");
970
        assert_eq!(format!("{:?}", LayoutBorderTopWidth::default()), "3px");
971
    }
972

            
973
    #[test]
974
    fn layout_border_width_const_px_matches_the_runtime_constructor() {
975
        assert_eq!(LayoutBorderTopWidth::const_px(5).inner, PixelValue::px(5.0));
976
        assert_eq!(
977
            LayoutBorderRightWidth::const_px(0).inner,
978
            PixelValue::zero()
979
        );
980
        assert_eq!(
981
            LayoutBorderBottomWidth::const_px(-2).inner,
982
            PixelValue::px(-2.0)
983
        );
984
        // The largest magnitude `const_px` can scale by FP_PRECISION_MULTIPLIER
985
        // (1000) without overflowing the isize multiply. Anything beyond this
986
        // overflows — see the FloatValue::const_new tests in length.rs.
987
        let max_safe = isize::MAX / 1000;
988
        assert!(LayoutBorderLeftWidth::const_px(max_safe)
989
            .inner
990
            .number
991
            .get()
992
            .is_finite());
993
    }
994

            
995
    #[test]
996
    fn layout_border_width_interpolate_endpoints_are_exact() {
997
        let a = LayoutBorderTopWidth::const_px(0);
998
        let b = LayoutBorderTopWidth::const_px(10);
999
        assert_eq!(a.interpolate(&b, 0.0), a);
        assert_eq!(a.interpolate(&b, 1.0), b);
        assert_eq!(a.interpolate(&b, 0.5).inner, PixelValue::px(5.0));
    }
    #[test]
    fn layout_border_width_interpolate_stays_finite_for_hostile_t() {
        let a = LayoutBorderTopWidth::const_px(0);
        let b = LayoutBorderTopWidth::const_px(10);
        for t in [
            0.0,
            1.0,
            -1.0,
            2.0,
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::MAX,
            f32::MIN,
        ] {
            // A NaN/inf must never leak out of the animation path: FloatValue
            // stores an isize, so the cast saturates instead of propagating.
            assert!(
                a.interpolate(&b, t).inner.number.get().is_finite(),
                "interpolate(t = {t}) produced a non-finite width"
            );
            assert!(b.interpolate(&a, t).inner.number.get().is_finite());
        }
    }
    #[test]
    fn layout_border_width_interpolate_across_metrics_stays_finite() {
        let px = LayoutBorderRightWidth {
            inner: PixelValue::px(4.0),
        };
        let em = LayoutBorderRightWidth {
            inner: PixelValue::em(2.0),
        };
        let percent = LayoutBorderRightWidth {
            inner: PixelValue::percent(100.0),
        };
        for t in [0.0, 0.5, 1.0, -3.0, f32::NAN, f32::INFINITY] {
            assert!(px.interpolate(&em, t).inner.number.get().is_finite());
            assert!(em.interpolate(&percent, t).inner.number.get().is_finite());
            assert!(percent.interpolate(&px, t).inner.number.get().is_finite());
        }
    }
    #[test]
    fn style_border_color_interpolate_endpoints_are_exact() {
        let black = StyleBorderTopColor {
            inner: ColorU::BLACK,
        };
        let white = StyleBorderTopColor {
            inner: ColorU::WHITE,
        };
        assert_eq!(black.interpolate(&white, 0.0).inner, ColorU::BLACK);
        assert_eq!(black.interpolate(&white, 1.0).inner, ColorU::WHITE);
        let mid = black.interpolate(&white, 0.5).inner;
        assert_eq!((mid.r, mid.g, mid.b), (128, 128, 128));
    }
    #[test]
    fn style_border_color_interpolate_hostile_t_does_not_panic() {
        let a = StyleBorderLeftColor {
            inner: ColorU::new(10, 20, 30, 40),
        };
        let b = StyleBorderLeftColor {
            inner: ColorU::new(200, 210, 220, 230),
        };
        for t in [
            -1000.0,
            1000.0,
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::MAX,
        ] {
            // u8 channels saturate; the only requirement is that this returns.
            let _ = a.interpolate(&b, t);
            let _ = b.interpolate(&a, t);
        }
    }
    // =====================================================================
    // parse_border_style
    // =====================================================================
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_style_accepts_every_keyword() {
        assert_eq!(parse_border_style("none").unwrap(), BorderStyle::None);
        assert_eq!(parse_border_style("solid").unwrap(), BorderStyle::Solid);
        assert_eq!(parse_border_style("double").unwrap(), BorderStyle::Double);
        assert_eq!(parse_border_style("dotted").unwrap(), BorderStyle::Dotted);
        assert_eq!(parse_border_style("dashed").unwrap(), BorderStyle::Dashed);
        assert_eq!(parse_border_style("hidden").unwrap(), BorderStyle::Hidden);
        assert_eq!(parse_border_style("groove").unwrap(), BorderStyle::Groove);
        assert_eq!(parse_border_style("ridge").unwrap(), BorderStyle::Ridge);
        assert_eq!(parse_border_style("inset").unwrap(), BorderStyle::Inset);
        assert_eq!(parse_border_style("outset").unwrap(), BorderStyle::Outset);
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_style_round_trips_through_display() {
        for style in ALL_STYLES {
            let encoded = style.to_string();
            assert_eq!(
                parse_border_style(&encoded).unwrap(),
                style,
                "{encoded} did not round-trip"
            );
            // and through the PrintAsCssValue path, which must agree
            assert_eq!(
                parse_border_style(&style.print_as_css_value()).unwrap(),
                style
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_style_trims_surrounding_whitespace() {
        for input in [" solid", "solid ", "\t\nsolid\r\n ", "   solid   "] {
            assert_eq!(
                parse_border_style(input).unwrap(),
                BorderStyle::Solid,
                "{input:?} should trim to `solid`"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_style_empty_and_whitespace_only_are_errors() {
        for input in ["", " ", "   ", "\t", "\n", "\r\n\t "] {
            assert!(
                parse_border_style(input).is_err(),
                "{input:?} must not parse as a border style"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_style_error_carries_the_untrimmed_input() {
        // The Ok path trims, but the Err path hands back the *raw* input.
        let input = "  bogus  ";
        let err = parse_border_style(input).unwrap_err();
        assert!(
            matches!(err, CssBorderStyleParseError::InvalidStyle(s) if s == input),
            "unexpected error payload: {err:?}"
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_style_rejects_uppercase_keywords() {
        // NOTE: CSS keywords are ASCII case-insensitive, so a spec-conformant
        // parser would accept these. This parser does not — asserted here so
        // the divergence is visible rather than silent.
        for input in ["SOLID", "Solid", "sOlId", "NONE", "Dashed"] {
            assert!(
                parse_border_style(input).is_err(),
                "{input:?} unexpectedly parsed (case-insensitivity was added?)"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_style_rejects_garbage_unicode_and_numbers() {
        for input in [
            "solidd",
            "soli",
            "solid solid",
            "solid;garbage",
            "solid!important",
            "0",
            "-0",
            "1px",
            "9223372036854775807",
            "NaN",
            "inf",
            "-inf",
            "\u{1F600}",
            "s\u{0301}olid",
            "sölid",
            "\u{0}",
            "\u{202e}solid",
            "sol\tid",
            "()",
            "solid()",
        ] {
            assert!(
                parse_border_style(input).is_err(),
                "{input:?} unexpectedly parsed as a border style"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_style_handles_huge_and_nested_input_without_panicking() {
        let huge = "a".repeat(100_000);
        assert!(parse_border_style(&huge).is_err());
        let repeated = "solid ".repeat(50_000);
        assert!(parse_border_style(&repeated).is_err());
        let nested = format!("{}{}", "(".repeat(10_000), ")".repeat(10_000));
        assert!(parse_border_style(&nested).is_err());
        let padded = format!("{}solid{}", " ".repeat(100_000), " ".repeat(100_000));
        assert_eq!(parse_border_style(&padded).unwrap(), BorderStyle::Solid);
    }
    // =====================================================================
    // border-*-style longhands
    // =====================================================================
    #[cfg(feature = "parser")]
    #[test]
    fn border_style_longhands_agree_with_parse_border_style() {
        for style in ALL_STYLES {
            let input = style.to_string();
            assert_eq!(parse_border_top_style(&input).unwrap().inner, style);
            assert_eq!(parse_border_right_style(&input).unwrap().inner, style);
            assert_eq!(parse_border_bottom_style(&input).unwrap().inner, style);
            assert_eq!(parse_border_left_style(&input).unwrap().inner, style);
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn border_style_longhands_reject_everything_parse_border_style_rejects() {
        for input in [
            "",
            "   ",
            "SOLID",
            "solidd",
            "\u{1F600}",
            "1px",
            "solid red",
        ] {
            assert!(parse_border_top_style(input).is_err(), "top: {input:?}");
            assert!(parse_border_right_style(input).is_err(), "right: {input:?}");
            assert!(
                parse_border_bottom_style(input).is_err(),
                "bottom: {input:?}"
            );
            assert!(parse_border_left_style(input).is_err(), "left: {input:?}");
        }
    }
    // =====================================================================
    // parse_border_width_value (private)
    // =====================================================================
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_width_value_accepts_the_three_keywords() {
        assert_eq!(
            parse_border_width_value("thin").unwrap(),
            THIN_BORDER_THICKNESS
        );
        assert_eq!(
            parse_border_width_value("medium").unwrap(),
            MEDIUM_BORDER_THICKNESS
        );
        assert_eq!(
            parse_border_width_value("thick").unwrap(),
            THICK_BORDER_THICKNESS
        );
        // keywords are trimmed like everything else
        assert_eq!(
            parse_border_width_value("  \tthick\n ").unwrap(),
            THICK_BORDER_THICKNESS
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_width_value_rejects_uppercase_keywords() {
        // Same case-sensitivity divergence as parse_border_style.
        for input in ["THIN", "Medium", "THICK"] {
            assert!(
                parse_border_width_value(input).is_err(),
                "{input:?} unexpectedly parsed"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_width_value_empty_and_whitespace_only_are_errors() {
        for input in ["", " ", "\t\n", "    "] {
            let err = parse_border_width_value(input).unwrap_err();
            assert!(
                matches!(err, CssPixelValueParseError::EmptyString),
                "{input:?} -> {err:?}"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_width_value_bare_number_is_interpreted_as_px() {
        assert_eq!(parse_border_width_value("0").unwrap(), PixelValue::px(0.0));
        assert_eq!(
            parse_border_width_value("42").unwrap(),
            PixelValue::px(42.0)
        );
        assert_eq!(
            parse_border_width_value("1.5").unwrap(),
            PixelValue::px(1.5)
        );
        // -0 collapses to +0 once quantized into the isize-backed FloatValue
        assert_eq!(parse_border_width_value("-0").unwrap(), PixelValue::px(0.0));
        // negative widths are *accepted* (CSS would reject them) — pinned so a
        // future validity check is a deliberate change, not an accident.
        assert_eq!(
            parse_border_width_value("-5px").unwrap(),
            PixelValue::px(-5.0)
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_width_value_nan_saturates_to_zero() {
        // "NaN" is a valid f32 literal for Rust's FromStr, so this reaches
        // FloatValue::new(NaN) — which saturates to 0 rather than storing NaN.
        let parsed = parse_border_width_value("NaN").unwrap();
        assert!(parsed.number.get().is_finite());
        assert_eq!(parsed, PixelValue::px(0.0));
        let parsed = parse_border_width_value("NaNpx").unwrap();
        assert_eq!(parsed, PixelValue::px(0.0));
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_width_value_infinities_and_overflow_saturate_finite() {
        for input in [
            "inf",
            "-inf",
            "infpx",
            "1e999",
            "-1e999",
            "1e40px",
            "340282350000000000000000000000000000000px", // ~f32::MAX
            "9223372036854775807",                       // i64::MAX
            "-9223372036854775808",                      // i64::MIN
        ] {
            let parsed = parse_border_width_value(input)
                .unwrap_or_else(|e| panic!("{input:?} failed to parse: {e:?}"));
            assert!(
                parsed.number.get().is_finite(),
                "{input:?} produced a non-finite width: {parsed:?}"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_width_value_rejects_garbage_and_unicode() {
        for input in [
            "px",
            "em",
            "abc",
            "1px 2px",
            "1px;",
            "--1px",
            "1PX",
            "\u{1F600}",
            "1\u{1F600}px",
            "Ù¡px", // arabic-indic digit one
            "()",
            "calc(1px + 2px)",
        ] {
            assert!(
                parse_border_width_value(input).is_err(),
                "{input:?} unexpectedly parsed as a border width"
            );
        }
        // ...but note the suffix strip trims what's left of the number, so a
        // space between value and unit is silently accepted:
        assert_eq!(
            parse_border_width_value("1 px").unwrap(),
            PixelValue::px(1.0)
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_width_value_bare_unit_reports_no_value_given() {
        let err = parse_border_width_value("px").unwrap_err();
        assert!(
            matches!(err, CssPixelValueParseError::NoValueGiven(..)),
            "expected NoValueGiven, got {err:?}"
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_width_value_huge_input_does_not_hang() {
        let huge_digits = format!("{}px", "9".repeat(1_000));
        let parsed = parse_border_width_value(&huge_digits).unwrap();
        assert!(parsed.number.get().is_finite());
        let huge_garbage = "z".repeat(100_000);
        assert!(parse_border_width_value(&huge_garbage).is_err());
        let padded = format!("{}1px{}", " ".repeat(50_000), " ".repeat(50_000));
        assert_eq!(
            parse_border_width_value(&padded).unwrap(),
            PixelValue::px(1.0)
        );
    }
    // =====================================================================
    // border-*-width longhands
    // =====================================================================
    #[cfg(feature = "parser")]
    #[test]
    fn border_width_longhands_agree_with_each_other() {
        for input in [
            "thin", "medium", "thick", "0", "1.5em", "3px", "50%", "-2pt",
        ] {
            let expected = parse_border_width_value(input).unwrap();
            assert_eq!(parse_border_top_width(input).unwrap().inner, expected);
            assert_eq!(parse_border_right_width(input).unwrap().inner, expected);
            assert_eq!(parse_border_bottom_width(input).unwrap().inner, expected);
            assert_eq!(parse_border_left_width(input).unwrap().inner, expected);
        }
        for input in ["", "   ", "px", "abc", "\u{1F600}", "1px 2px"] {
            assert!(parse_border_top_width(input).is_err(), "top: {input:?}");
            assert!(parse_border_right_width(input).is_err(), "right: {input:?}");
            assert!(
                parse_border_bottom_width(input).is_err(),
                "bottom: {input:?}"
            );
            assert!(parse_border_left_width(input).is_err(), "left: {input:?}");
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn border_width_longhands_round_trip_through_display() {
        for value in [
            PixelValue::px(0.0),
            PixelValue::px(1.0),
            PixelValue::px(1.5),
            PixelValue::px(-3.25),
            PixelValue::em(2.0),
            PixelValue::rem(0.5),
            PixelValue::pt(12.0),
            PixelValue::inch(1.0),
            PixelValue::cm(2.5),
            PixelValue::mm(10.0),
            PixelValue::percent(50.0),
            THIN_BORDER_THICKNESS,
            MEDIUM_BORDER_THICKNESS,
            THICK_BORDER_THICKNESS,
        ] {
            let encoded = value.to_string();
            let decoded = parse_border_top_width(&encoded)
                .unwrap_or_else(|e| panic!("{encoded} failed to re-parse: {e:?}"))
                .inner;
            assert_eq!(decoded, value, "{encoded} did not round-trip");
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn border_width_longhands_inherit_the_vmin_suffix_shadowing_bug() {
        // FIXED (this pin flipped, as intended): the suffix table used to test "in"
        // before "vmin", so "5vmin" stripped "in" and failed to parse "5vm" — every
        // `border-width: 5vmin` was rejected. The table now orders "vmin" ahead of "in".
        assert_eq!(
            parse_border_top_width("5vmin").unwrap().inner,
            PixelValue::from_metric(crate::props::basic::SizeMetric::Vmin, 5.0)
        );
        assert_eq!(
            parse_border_left_width("5vmin").unwrap().inner,
            PixelValue::from_metric(crate::props::basic::SizeMetric::Vmin, 5.0)
        );
        assert_eq!(
            parse_border_top_width("5vmax").unwrap().inner,
            PixelValue::from_metric(crate::props::basic::SizeMetric::Vmax, 5.0)
        );
        assert_eq!(
            parse_border_top_width("5vw").unwrap().inner,
            PixelValue::from_metric(crate::props::basic::SizeMetric::Vw, 5.0)
        );
    }
    // =====================================================================
    // border-*-color longhands
    // =====================================================================
    #[cfg(feature = "parser")]
    #[test]
    fn border_color_longhands_agree_with_each_other() {
        for input in [
            "#ff0000",
            "#f0f",
            "#11223344",
            "red",
            "transparent",
            "rgb(1, 2, 3)",
            "rgba(10, 20, 30, 0.5)",
            "hsl(0, 100%, 50%)",
        ] {
            let expected = parse_css_color(input)
                .unwrap_or_else(|e| panic!("{input:?} failed to parse: {e:?}"));
            assert_eq!(parse_border_top_color(input).unwrap().inner, expected);
            assert_eq!(parse_border_right_color(input).unwrap().inner, expected);
            assert_eq!(parse_border_bottom_color(input).unwrap().inner, expected);
            assert_eq!(parse_border_left_color(input).unwrap().inner, expected);
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn border_color_longhands_round_trip_through_to_hash() {
        for color in [
            ColorU::BLACK,
            ColorU::WHITE,
            ColorU::RED,
            ColorU::BLUE,
            ColorU::TRANSPARENT,
            ColorU::new(1, 2, 3, 4),
            ColorU::new(255, 254, 253, 252),
            ColorU::new(0, 128, 0, 255),
        ] {
            let encoded = color.to_hash();
            assert_eq!(
                parse_border_left_color(&encoded)
                    .unwrap_or_else(|e| panic!("{encoded} failed to re-parse: {e:?}"))
                    .inner,
                color,
                "{encoded} did not round-trip"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn border_color_longhands_empty_input_is_an_error() {
        for input in ["", " ", "\t\n  "] {
            let err = parse_border_top_color(input).unwrap_err();
            assert!(
                matches!(err, CssColorParseError::EmptyInput),
                "{input:?} -> {err:?}"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn border_color_longhands_reject_garbage_and_unicode() {
        for input in [
            "#",
            "#z",
            "#ff",
            "#fffff",
            "#\u{1F600}",
            "notacolor",
            "rgb(1, 2)",
            "rgb(1, 2, 3, 4, 5)",
            "\u{1F600}",
            "red;",
            "red blue",
            "0",
        ] {
            assert!(
                parse_border_top_color(input).is_err(),
                "{input:?} unexpectedly parsed as a color"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn border_color_longhands_never_panic_on_hostile_input() {
        let long = "f".repeat(100_000);
        let nested = format!("rgb{}1,2,3{}", "(".repeat(10_000), ")".repeat(10_000));
        let deep_parens = format!("{}{}", "(".repeat(10_000), ")".repeat(10_000));
        let hostile: [&str; 18] = [
            "#",
            "##ff0000",
            "rgb(",
            "rgb()",
            "rgba(0,0,0,NaN)",
            "rgba(0,0,0,inf)",
            "rgb(-1,-2,-3)",
            "rgb(999,999,999)",
            "rgb(NaN, NaN, NaN)",
            "hsl(inf, 0%, 0%)",
            "hsla(NaN, NaN%, NaN%, NaN)",
            "\u{0}",
            "\u{202e}",
            "s\u{0301}",
            ")))",
            &long,
            &nested,
            &deep_parens,
        ];
        for input in hostile {
            // The contract is only "returns, never panics / never overflows the stack".
            let _ = parse_border_top_color(input);
            let _ = parse_border_right_color(input);
            let _ = parse_border_bottom_color(input);
            let _ = parse_border_left_color(input);
        }
    }
    // =====================================================================
    // parse_border_side / parse_style_border
    // =====================================================================
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_side_positive_control() {
        let side = parse_border_side("1px solid red").unwrap();
        assert_eq!(side.border_width, PixelValue::px(1.0));
        assert_eq!(side.border_style, BorderStyle::Solid);
        assert_eq!(side.border_color, ColorU::RED);
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_side_is_component_order_independent() {
        let expected = StyleBorderSide {
            border_width: PixelValue::px(2.0),
            border_style: BorderStyle::Dashed,
            border_color: ColorU::new_rgb(0, 255, 0),
        };
        for input in [
            "2px dashed #00ff00",
            "2px #00ff00 dashed",
            "dashed 2px #00ff00",
            "dashed #00ff00 2px",
            "#00ff00 2px dashed",
            "#00ff00 dashed 2px",
            "  2px   dashed   #00ff00  ",
            "\t2px\ndashed\r#00ff00\t",
        ] {
            assert_eq!(
                parse_border_side(input).unwrap(),
                expected,
                "{input:?} parsed differently"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_side_applies_defaults_for_missing_components() {
        // Missing components fall back to medium / none / black.
        let only_style = parse_border_side("inset").unwrap();
        assert_eq!(only_style.border_width, MEDIUM_BORDER_THICKNESS);
        assert_eq!(only_style.border_style, BorderStyle::Inset);
        assert_eq!(only_style.border_color, ColorU::BLACK);
        let only_width = parse_border_side("7px").unwrap();
        assert_eq!(only_width.border_width, PixelValue::px(7.0));
        assert_eq!(only_width.border_style, BorderStyle::None);
        assert_eq!(only_width.border_color, ColorU::BLACK);
        let only_color = parse_border_side("blue").unwrap();
        assert_eq!(only_color.border_width, MEDIUM_BORDER_THICKNESS);
        assert_eq!(only_color.border_style, BorderStyle::None);
        assert_eq!(only_color.border_color, ColorU::BLUE);
        // keyword widths work in the shorthand too
        let keyword = parse_border_side("thin solid").unwrap();
        assert_eq!(keyword.border_width, THIN_BORDER_THICKNESS);
        assert_eq!(keyword.border_style, BorderStyle::Solid);
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_side_rejects_duplicate_components() {
        for input in [
            "1px 2px solid red",
            "solid dashed red",
            "red blue solid",
            "1px solid red 2px",
            "1px solid red solid",
            "1px solid red red",
        ] {
            let err = parse_border_side(input).unwrap_err();
            assert!(
                matches!(err, CssBorderSideParseError::InvalidDeclaration(s) if s == input),
                "{input:?} -> {err:?}"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_side_empty_and_whitespace_only_are_errors() {
        for input in ["", " ", "\t\n", "      "] {
            let err = parse_border_side(input).unwrap_err();
            // The raw (untrimmed) input is echoed back in the error.
            assert!(
                matches!(err, CssBorderSideParseError::InvalidDeclaration(s) if s == input),
                "{input:?} -> {err:?}"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_side_rejects_unknown_tokens() {
        for input in [
            "1px unknown red",
            "1px solid red !important",
            "1px solid red;",
            "\u{1F600}",
            "1px solid \u{1F600}",
            "solid \u{0}",
            "1px, solid, red",
        ] {
            assert!(
                parse_border_side(input).is_err(),
                "{input:?} unexpectedly parsed as a border shorthand"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_side_hostile_numbers_stay_finite() {
        // "NaN" / "inf" are valid f32 literals, so they *do* parse as widths —
        // but the isize-backed FloatValue saturates them to a finite value.
        for input in ["NaN solid red", "inf solid red", "1e999 solid red"] {
            let side = parse_border_side(input)
                .unwrap_or_else(|e| panic!("{input:?} failed to parse: {e:?}"));
            assert!(
                side.border_width.number.get().is_finite(),
                "{input:?} produced a non-finite width: {:?}",
                side.border_width
            );
            assert_eq!(side.border_style, BorderStyle::Solid);
            assert_eq!(side.border_color, ColorU::RED);
        }
        assert_eq!(
            parse_border_side("NaN solid red").unwrap().border_width,
            PixelValue::px(0.0)
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_border_side_long_and_nested_input_does_not_hang() {
        // Repeated tokens: the 2nd `solid` cannot be re-assigned, so this must
        // bail out immediately rather than scanning all 50k tokens.
        let repeated = "solid ".repeat(50_000);
        assert!(parse_border_side(&repeated).is_err());
        let repeated_px = "1px ".repeat(50_000);
        assert!(parse_border_side(&repeated_px).is_err());
        let huge_token = "z".repeat(100_000);
        assert!(parse_border_side(&huge_token).is_err());
        let nested = format!("{}{}", "(".repeat(10_000), ")".repeat(10_000));
        assert!(parse_border_side(&nested).is_err());
        let padded = format!("{}1px solid red{}", " ".repeat(50_000), " ".repeat(50_000));
        assert_eq!(
            parse_border_side(&padded).unwrap().border_style,
            BorderStyle::Solid
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_is_an_alias_of_parse_border_side() {
        for input in [
            "1px solid red",
            "thick double",
            "inset",
            "",
            "   ",
            "1px 2px solid red",
            "\u{1F600}",
            "solid green 1em",
        ] {
            match (parse_style_border(input), parse_border_side(input)) {
                (Ok(a), Ok(b)) => assert_eq!(a, b, "{input:?}"),
                (Err(a), Err(b)) => assert_eq!(a, b, "{input:?}"),
                (a, b) => panic!("{input:?}: alias disagrees: {a:?} vs {b:?}"),
            }
        }
    }
    // =====================================================================
    // border-color shorthand
    // =====================================================================
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_color_expands_one_to_four_values() {
        let red = ColorU::RED;
        let blue = ColorU::BLUE;
        let green = ColorU::new_rgb(0, 128, 0);
        let white = ColorU::WHITE;
        let one = parse_style_border_color("red").unwrap();
        assert_eq!(
            one,
            StyleBorderColors {
                top: red,
                right: red,
                bottom: red,
                left: red
            }
        );
        // 2 values: top/bottom, left/right
        let two = parse_style_border_color("red blue").unwrap();
        assert_eq!(
            two,
            StyleBorderColors {
                top: red,
                right: blue,
                bottom: red,
                left: blue
            }
        );
        // 3 values: top, left/right, bottom
        let three = parse_style_border_color("red blue green").unwrap();
        assert_eq!(
            three,
            StyleBorderColors {
                top: red,
                right: blue,
                bottom: green,
                left: blue
            }
        );
        // 4 values: top, right, bottom, left
        let four = parse_style_border_color("red blue green white").unwrap();
        assert_eq!(
            four,
            StyleBorderColors {
                top: red,
                right: blue,
                bottom: green,
                left: white
            }
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_color_normalizes_whitespace() {
        let expected = parse_style_border_color("red blue green").unwrap();
        for input in [
            "  red blue green  ",
            "red\tblue\ngreen",
            "red   blue \r\n green",
        ] {
            assert_eq!(
                parse_style_border_color(input).unwrap(),
                expected,
                "{input:?}"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_color_rejects_zero_and_more_than_four_values() {
        for input in ["", "   ", "\t\n"] {
            let err = parse_style_border_color(input).unwrap_err();
            assert!(
                matches!(err, CssColorParseError::InvalidColor(_)),
                "{input:?} -> {err:?}"
            );
        }
        let too_many = "red ".repeat(1_000);
        let inputs: [&str; 3] = [
            "red red red red red",
            "red blue green white black yellow",
            &too_many,
        ];
        for input in inputs {
            assert!(
                parse_style_border_color(input).is_err(),
                "{input:?} unexpectedly parsed"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_color_propagates_component_errors() {
        for input in [
            "notacolor",
            "red notacolor",
            "red blue notacolor",
            "red blue green notacolor",
            "red \u{1F600}",
            "#zzz",
        ] {
            assert!(
                parse_style_border_color(input).is_err(),
                "{input:?} unexpectedly parsed"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_color_round_trips_through_to_hash() {
        let colors = StyleBorderColors {
            top: ColorU::new(1, 2, 3, 4),
            right: ColorU::new(255, 0, 0, 255),
            bottom: ColorU::TRANSPARENT,
            left: ColorU::new(9, 8, 7, 6),
        };
        let encoded = format!(
            "{} {} {} {}",
            colors.top.to_hash(),
            colors.right.to_hash(),
            colors.bottom.to_hash(),
            colors.left.to_hash()
        );
        assert_eq!(parse_style_border_color(&encoded).unwrap(), colors);
    }
    // =====================================================================
    // border-style shorthand
    // =====================================================================
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_style_expands_one_to_four_values() {
        assert_eq!(
            parse_style_border_style("solid").unwrap(),
            StyleBorderStyles {
                top: BorderStyle::Solid,
                right: BorderStyle::Solid,
                bottom: BorderStyle::Solid,
                left: BorderStyle::Solid,
            }
        );
        assert_eq!(
            parse_style_border_style("solid dashed").unwrap(),
            StyleBorderStyles {
                top: BorderStyle::Solid,
                right: BorderStyle::Dashed,
                bottom: BorderStyle::Solid,
                left: BorderStyle::Dashed,
            }
        );
        assert_eq!(
            parse_style_border_style("solid dashed dotted").unwrap(),
            StyleBorderStyles {
                top: BorderStyle::Solid,
                right: BorderStyle::Dashed,
                bottom: BorderStyle::Dotted,
                left: BorderStyle::Dashed,
            }
        );
        assert_eq!(
            parse_style_border_style("solid dashed dotted double").unwrap(),
            StyleBorderStyles {
                top: BorderStyle::Solid,
                right: BorderStyle::Dashed,
                bottom: BorderStyle::Dotted,
                left: BorderStyle::Double,
            }
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_style_rejects_zero_and_more_than_four_values() {
        for input in ["", "   ", "\t\n"] {
            let err = parse_style_border_style(input).unwrap_err();
            // NOTE: the error payload here is the *trimmed* input, unlike
            // parse_border_style, which echoes the raw input back.
            assert!(
                matches!(err, CssBorderStyleParseError::InvalidStyle(s) if s == input.trim()),
                "{input:?} -> {err:?}"
            );
        }
        let too_many = "dotted ".repeat(1_000);
        let inputs: [&str; 2] = ["solid solid solid solid solid", &too_many];
        for input in inputs {
            assert!(
                parse_style_border_style(input).is_err(),
                "{input:?} unexpectedly parsed"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_style_propagates_component_errors() {
        for input in [
            "bogus",
            "solid bogus",
            "solid solid bogus",
            "solid solid solid bogus",
            "solid \u{1F600}",
            "SOLID",
        ] {
            assert!(
                parse_style_border_style(input).is_err(),
                "{input:?} unexpectedly parsed"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_style_round_trips_through_display() {
        for (t, r, b, l) in [
            (
                BorderStyle::Solid,
                BorderStyle::Dashed,
                BorderStyle::Dotted,
                BorderStyle::Double,
            ),
            (
                BorderStyle::None,
                BorderStyle::Hidden,
                BorderStyle::Groove,
                BorderStyle::Ridge,
            ),
            (
                BorderStyle::Inset,
                BorderStyle::Outset,
                BorderStyle::None,
                BorderStyle::Solid,
            ),
        ] {
            let expected = StyleBorderStyles {
                top: t,
                right: r,
                bottom: b,
                left: l,
            };
            let encoded = format!("{t} {r} {b} {l}");
            assert_eq!(
                parse_style_border_style(&encoded).unwrap(),
                expected,
                "{encoded} did not round-trip"
            );
        }
    }
    // =====================================================================
    // border-width shorthand
    // =====================================================================
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_width_expands_one_to_four_values() {
        assert_eq!(
            parse_style_border_width("1px").unwrap(),
            StyleBorderWidths {
                top: PixelValue::px(1.0),
                right: PixelValue::px(1.0),
                bottom: PixelValue::px(1.0),
                left: PixelValue::px(1.0),
            }
        );
        assert_eq!(
            parse_style_border_width("1px 2px").unwrap(),
            StyleBorderWidths {
                top: PixelValue::px(1.0),
                right: PixelValue::px(2.0),
                bottom: PixelValue::px(1.0),
                left: PixelValue::px(2.0),
            }
        );
        assert_eq!(
            parse_style_border_width("1px 2px 3px").unwrap(),
            StyleBorderWidths {
                top: PixelValue::px(1.0),
                right: PixelValue::px(2.0),
                bottom: PixelValue::px(3.0),
                left: PixelValue::px(2.0),
            }
        );
        assert_eq!(
            parse_style_border_width("1px 2em 3pt 4%").unwrap(),
            StyleBorderWidths {
                top: PixelValue::px(1.0),
                right: PixelValue::em(2.0),
                bottom: PixelValue::pt(3.0),
                left: PixelValue::percent(4.0),
            }
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_width_rejects_zero_and_more_than_four_values() {
        for input in ["", "   ", "\t\n"] {
            let err = parse_style_border_width(input).unwrap_err();
            assert!(
                matches!(err, CssPixelValueParseError::InvalidPixelValue(s) if s == input.trim()),
                "{input:?} -> {err:?}"
            );
        }
        let too_many = "1px ".repeat(1_000);
        let inputs: [&str; 2] = ["1px 1px 1px 1px 1px", &too_many];
        for input in inputs {
            assert!(
                parse_style_border_width(input).is_err(),
                "{input:?} unexpectedly parsed"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_width_rejects_the_thin_medium_thick_keywords() {
        // KNOWN DIVERGENCE: the longhands (parse_border_top_width) go through
        // parse_border_width_value and DO accept thin/medium/thick, but this
        // shorthand calls parse_pixel_value directly, so `border-width: thin`
        // is rejected. Worse, "thin" ends with the "in" (inch) suffix, so it is
        // reported as a broken *inches* value rather than an unknown keyword.
        let err = parse_style_border_width("thin").unwrap_err();
        assert!(
            matches!(err, CssPixelValueParseError::ValueParseErr(_, s) if s == "th"),
            "expected `thin` to be misread as inches, got {err:?}"
        );
        assert!(parse_style_border_width("medium").is_err());
        assert!(parse_style_border_width("thick").is_err());
        assert!(parse_style_border_width("thin thick").is_err());
        // ...while the longhand happily accepts all three:
        assert_eq!(
            parse_border_top_width("thin").unwrap().inner,
            THIN_BORDER_THICKNESS
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_width_propagates_component_errors() {
        for input in [
            "abc",
            "1px abc",
            "1px 2px abc",
            "1px 2px 3px abc",
            "1px \u{1F600}",
            "1PX",
        ] {
            assert!(
                parse_style_border_width(input).is_err(),
                "{input:?} unexpectedly parsed"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_width_hostile_numbers_stay_finite() {
        let widths = parse_style_border_width("NaN inf -inf 1e999").unwrap();
        for w in [widths.top, widths.right, widths.bottom, widths.left] {
            assert!(
                w.number.get().is_finite(),
                "hostile width did not saturate: {w:?}"
            );
        }
        assert_eq!(widths.top, PixelValue::px(0.0)); // NaN -> 0
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_style_border_width_round_trips_through_display() {
        let widths = StyleBorderWidths {
            top: PixelValue::px(1.5),
            right: PixelValue::em(2.0),
            bottom: PixelValue::pt(3.25),
            left: PixelValue::percent(50.0),
        };
        let encoded = format!(
            "{} {} {} {}",
            widths.top, widths.right, widths.bottom, widths.left
        );
        assert_eq!(parse_style_border_width(&encoded).unwrap(), widths);
    }
    // =====================================================================
    // Error types: to_contained / to_shared / From / Display
    // =====================================================================
    #[cfg(feature = "parser")]
    #[test]
    fn css_border_style_parse_error_round_trips_owned_and_shared() {
        let huge = "x".repeat(10_000);
        let payloads: [&str; 7] = ["", " ", "bogus", "\u{1F600}", "s\u{0301}", "\u{0}", &huge];
        for payload in payloads {
            let shared = CssBorderStyleParseError::InvalidStyle(payload);
            let owned = shared.to_contained();
            assert_eq!(owned.to_shared(), shared, "{payload:?} did not round-trip");
            assert!(
                matches!(&owned, CssBorderStyleParseErrorOwned::InvalidStyle(s) if s.as_str() == payload)
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn css_border_style_parse_error_from_a_real_parse_failure_round_trips() {
        let err = parse_border_style("\u{1F600}bogus").unwrap_err();
        let owned = err.to_contained();
        assert_eq!(owned.to_shared(), err);
        // Debug is routed through Display, so both must mention the input.
        assert!(format!("{err}").contains("bogus"));
        assert!(format!("{err:?}").contains("bogus"));
        assert!(!format!("{owned:?}").is_empty());
    }
    #[cfg(feature = "parser")]
    #[test]
    fn css_border_side_parse_error_round_trips_for_every_variant() {
        let variants = [
            CssBorderSideParseError::InvalidDeclaration(""),
            CssBorderSideParseError::InvalidDeclaration("1px 2px solid"),
            CssBorderSideParseError::InvalidDeclaration("\u{1F600}"),
            CssBorderSideParseError::Width(CssPixelValueParseError::EmptyString),
            CssBorderSideParseError::Width(CssPixelValueParseError::InvalidPixelValue("zz")),
            CssBorderSideParseError::Style(CssBorderStyleParseError::InvalidStyle("zz")),
            CssBorderSideParseError::Style(CssBorderStyleParseError::InvalidStyle("")),
            CssBorderSideParseError::Color(CssColorParseError::InvalidColor("zz")),
            CssBorderSideParseError::Color(CssColorParseError::EmptyInput),
            CssBorderSideParseError::Color(CssColorParseError::InvalidColorComponent(u8::MAX)),
        ];
        for shared in variants {
            let owned = shared.to_contained();
            assert_eq!(owned.to_shared(), shared, "{shared:?} did not round-trip");
            assert!(!format!("{shared}").is_empty());
            assert!(!format!("{owned:?}").is_empty());
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn css_border_side_parse_error_from_conversions_pick_the_right_variant() {
        let width: CssBorderSideParseError<'_> =
            CssPixelValueParseError::InvalidPixelValue("zz").into();
        assert!(matches!(width, CssBorderSideParseError::Width(_)));
        let style: CssBorderSideParseError<'_> =
            CssBorderStyleParseError::InvalidStyle("zz").into();
        assert!(matches!(style, CssBorderSideParseError::Style(_)));
        let color: CssBorderSideParseError<'_> = CssColorParseError::InvalidColor("zz").into();
        assert!(matches!(color, CssBorderSideParseError::Color(_)));
    }
    #[cfg(feature = "parser")]
    #[test]
    fn css_border_parse_error_owned_newtype_wraps_the_side_error() {
        let owned = CssBorderSideParseError::InvalidDeclaration("bogus").to_contained();
        let wrapped = CssBorderParseErrorOwned::from(owned.clone());
        assert_eq!(wrapped.inner, owned);
        assert_eq!(wrapped.inner.to_shared().to_contained(), owned);
    }
    #[cfg(feature = "parser")]
    #[test]
    fn error_display_mentions_the_offending_input() {
        let err = parse_border_side("1px bogus red").unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("1px bogus red"), "unhelpful message: {msg}");
        let err = parse_border_style("bogus").unwrap_err();
        assert!(format!("{err}").contains("bogus"));
        let err = parse_border_top_width("bogus").unwrap_err();
        assert!(format!("{err}").contains("bogus"));
    }
}