1
//! CSS properties for border radius (`border-top-left-radius`,
2
//! `border-top-right-radius`, `border-bottom-left-radius`,
3
//! `border-bottom-right-radius`) and the `border-radius` shorthand parser.
4

            
5
use alloc::string::{String, ToString};
6

            
7
use crate::{
8
    corety::AzString,
9
    props::{
10
        basic::pixel::{
11
            parse_pixel_value, CssPixelValueParseError, CssPixelValueParseErrorOwned, PixelValue,
12
        },
13
        macros::PixelValueTaker,
14
    },
15
};
16

            
17
// --- Property Struct Definitions ---
18

            
19
macro_rules! define_border_radius_property {
20
    ($struct_name:ident) => {
21
        #[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
22
        #[repr(C)]
23
        pub struct $struct_name {
24
            pub inner: PixelValue,
25
        }
26

            
27
        impl ::core::fmt::Debug for $struct_name {
28
2
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
29
2
                write!(f, "{}", self.inner)
30
2
            }
31
        }
32

            
33
        impl PixelValueTaker for $struct_name {
34
1
            fn from_pixel_value(inner: PixelValue) -> Self {
35
1
                Self { inner }
36
1
            }
37
        }
38

            
39
        impl_pixel_value!($struct_name);
40
    };
41
}
42

            
43
/// CSS `border-top-left-radius` property value.
44
define_border_radius_property!(StyleBorderTopLeftRadius);
45
/// CSS `border-top-right-radius` property value.
46
define_border_radius_property!(StyleBorderTopRightRadius);
47
/// CSS `border-bottom-left-radius` property value.
48
define_border_radius_property!(StyleBorderBottomLeftRadius);
49
/// CSS `border-bottom-right-radius` property value.
50
define_border_radius_property!(StyleBorderBottomRightRadius);
51

            
52
// --- Parser-only Struct ---
53

            
54
/// A temporary struct used only during the parsing of the `border-radius` shorthand property.
55
#[cfg(feature = "parser")]
56
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
57
pub struct StyleBorderRadius {
58
    pub top_left: PixelValue,
59
    pub top_right: PixelValue,
60
    pub bottom_left: PixelValue,
61
    pub bottom_right: PixelValue,
62
}
63

            
64
// --- Error Types ---
65

            
66
/// Error for the shorthand `border-radius` property.
67
#[derive(Clone, PartialEq, Eq)]
68
pub enum CssBorderRadiusParseError<'a> {
69
    /// Too many values were provided (max is 4).
70
    TooManyValues(&'a str),
71
    /// An underlying pixel value could not be parsed.
72
    PixelValue(CssPixelValueParseError<'a>),
73
}
74

            
75
impl_debug_as_display!(CssBorderRadiusParseError<'a>);
76
impl_display! { CssBorderRadiusParseError<'a>, {
77
    TooManyValues(val) => format!("Too many values for border-radius: \"{}\"", val),
78
    PixelValue(e) => format!("{}", e),
79
}}
80
impl_from!(
81
    CssPixelValueParseError<'a>,
82
    CssBorderRadiusParseError::PixelValue
83
);
84

            
85
/// Owned version of `CssBorderRadiusParseError`.
86
#[derive(Debug, Clone, PartialEq, Eq)]
87
#[repr(C, u8)]
88
pub enum CssBorderRadiusParseErrorOwned {
89
    TooManyValues(AzString),
90
    PixelValue(CssPixelValueParseErrorOwned),
91
}
92

            
93
/// Newtype wrapper around `CssBorderRadiusParseErrorOwned` for the `border-radius` shorthand.
94
#[derive(Debug, Clone, PartialEq, Eq)]
95
#[repr(C)]
96
pub struct CssStyleBorderRadiusParseErrorOwned {
97
    pub inner: CssBorderRadiusParseErrorOwned,
98
}
99

            
100
impl From<CssBorderRadiusParseErrorOwned> for CssStyleBorderRadiusParseErrorOwned {
101
1
    fn from(v: CssBorderRadiusParseErrorOwned) -> Self {
102
1
        Self { inner: v }
103
1
    }
104
}
105

            
106
impl CssBorderRadiusParseError<'_> {
107
    #[must_use]
108
17
    pub fn to_contained(&self) -> CssBorderRadiusParseErrorOwned {
109
17
        match self {
110
10
            CssBorderRadiusParseError::TooManyValues(s) => {
111
10
                CssBorderRadiusParseErrorOwned::TooManyValues((*s).to_string().into())
112
            }
113
7
            CssBorderRadiusParseError::PixelValue(e) => {
114
7
                CssBorderRadiusParseErrorOwned::PixelValue(e.to_contained())
115
            }
116
        }
117
17
    }
118
}
119

            
120
impl CssBorderRadiusParseErrorOwned {
121
    #[must_use]
122
21
    pub fn to_shared(&self) -> CssBorderRadiusParseError<'_> {
123
21
        match self {
124
10
            Self::TooManyValues(s) => CssBorderRadiusParseError::TooManyValues(s),
125
11
            Self::PixelValue(e) => CssBorderRadiusParseError::PixelValue(e.to_shared()),
126
        }
127
21
    }
128
}
129

            
130
/// Macro to generate error types for individual radius properties.
131
macro_rules! define_border_radius_parse_error {
132
    ($error_name:ident, $error_name_owned:ident) => {
133
        #[derive(Clone, PartialEq, Eq)]
134
        pub enum $error_name<'a> {
135
            PixelValue(CssPixelValueParseError<'a>),
136
        }
137

            
138
        impl_debug_as_display!($error_name<'a>);
139
        impl_display! { $error_name<'a>, {
140
            PixelValue(e) => format!("{}", e),
141
        }}
142

            
143
        impl_from!(CssPixelValueParseError<'a>, $error_name::PixelValue);
144

            
145
        #[derive(Debug, Clone, PartialEq, Eq)]
146
        #[repr(C, u8)]
147
        pub enum $error_name_owned {
148
            PixelValue(CssPixelValueParseErrorOwned),
149
        }
150

            
151
        impl $error_name<'_> {
152
            #[must_use]
153
5
            pub fn to_contained(&self) -> $error_name_owned {
154
5
                match self {
155
5
                    $error_name::PixelValue(e) => $error_name_owned::PixelValue(e.to_contained()),
156
                }
157
5
            }
158
        }
159

            
160
        impl $error_name_owned {
161
            #[must_use]
162
4
            pub fn to_shared(&self) -> $error_name<'_> {
163
4
                match self {
164
4
                    $error_name_owned::PixelValue(e) => $error_name::PixelValue(e.to_shared()),
165
                }
166
4
            }
167
        }
168
    };
169
}
170

            
171
define_border_radius_parse_error!(
172
    StyleBorderTopLeftRadiusParseError,
173
    StyleBorderTopLeftRadiusParseErrorOwned
174
);
175
define_border_radius_parse_error!(
176
    StyleBorderTopRightRadiusParseError,
177
    StyleBorderTopRightRadiusParseErrorOwned
178
);
179
define_border_radius_parse_error!(
180
    StyleBorderBottomLeftRadiusParseError,
181
    StyleBorderBottomLeftRadiusParseErrorOwned
182
);
183
define_border_radius_parse_error!(
184
    StyleBorderBottomRightRadiusParseError,
185
    StyleBorderBottomRightRadiusParseErrorOwned
186
);
187

            
188
// --- Parsing Functions ---
189

            
190
/// Parse the CSS `border-radius` shorthand into individual corner values.
191
#[cfg(feature = "parser")]
192
/// # Errors
193
///
194
/// Returns an error if `input` is not a valid CSS `border-radius` value.
195
16854
pub fn parse_style_border_radius(
196
16854
    input: &str,
197
16854
) -> Result<StyleBorderRadius, CssBorderRadiusParseError<'_>> {
198
16854
    let components: Vec<_> = input.split_whitespace().collect();
199
16854
    let mut values = Vec::with_capacity(components.len());
200
133708
    for comp in &components {
201
116889
        values.push(parse_pixel_value(comp)?);
202
    }
203

            
204
16819
    match values.len() {
205
16791
        1 => Ok(StyleBorderRadius {
206
16791
            top_left: values[0],
207
16791
            top_right: values[0],
208
16791
            bottom_right: values[0],
209
16791
            bottom_left: values[0],
210
16791
        }),
211
5
        2 => Ok(StyleBorderRadius {
212
5
            top_left: values[0],
213
5
            top_right: values[1],
214
5
            bottom_right: values[0],
215
5
            bottom_left: values[1],
216
5
        }),
217
2
        3 => Ok(StyleBorderRadius {
218
2
            top_left: values[0],
219
2
            top_right: values[1],
220
2
            bottom_right: values[2],
221
2
            bottom_left: values[1],
222
2
        }),
223
5
        4 => Ok(StyleBorderRadius {
224
5
            top_left: values[0],
225
5
            top_right: values[1],
226
5
            bottom_right: values[2],
227
5
            bottom_left: values[3],
228
5
        }),
229
16
        _ => Err(CssBorderRadiusParseError::TooManyValues(input)),
230
    }
231
16854
}
232

            
233
/// Parse the CSS `border-top-left-radius` longhand property.
234
#[cfg(feature = "parser")]
235
/// # Errors
236
///
237
/// Returns an error if `input` is not a valid CSS `border-top-left-radius` value.
238
125
pub fn parse_style_border_top_left_radius(
239
125
    input: &str,
240
125
) -> Result<StyleBorderTopLeftRadius, StyleBorderTopLeftRadiusParseError<'_>> {
241
125
    let pixel_value = parse_pixel_value(input)?;
242
99
    Ok(StyleBorderTopLeftRadius { inner: pixel_value })
243
125
}
244

            
245
/// Parse the CSS `border-top-right-radius` longhand property.
246
#[cfg(feature = "parser")]
247
/// # Errors
248
///
249
/// Returns an error if `input` is not a valid CSS `border-top-right-radius` value.
250
123
pub fn parse_style_border_top_right_radius(
251
123
    input: &str,
252
123
) -> Result<StyleBorderTopRightRadius, StyleBorderTopRightRadiusParseError<'_>> {
253
123
    let pixel_value = parse_pixel_value(input)?;
254
97
    Ok(StyleBorderTopRightRadius { inner: pixel_value })
255
123
}
256

            
257
/// Parse the CSS `border-bottom-left-radius` longhand property.
258
#[cfg(feature = "parser")]
259
/// # Errors
260
///
261
/// Returns an error if `input` is not a valid CSS `border-bottom-left-radius` value.
262
123
pub fn parse_style_border_bottom_left_radius(
263
123
    input: &str,
264
123
) -> Result<StyleBorderBottomLeftRadius, StyleBorderBottomLeftRadiusParseError<'_>> {
265
123
    let pixel_value = parse_pixel_value(input)?;
266
97
    Ok(StyleBorderBottomLeftRadius { inner: pixel_value })
267
123
}
268

            
269
/// Parse the CSS `border-bottom-right-radius` longhand property.
270
#[cfg(feature = "parser")]
271
/// # Errors
272
///
273
/// Returns an error if `input` is not a valid CSS `border-bottom-right-radius` value.
274
123
pub fn parse_style_border_bottom_right_radius(
275
123
    input: &str,
276
123
) -> Result<StyleBorderBottomRightRadius, StyleBorderBottomRightRadiusParseError<'_>> {
277
123
    let pixel_value = parse_pixel_value(input)?;
278
97
    Ok(StyleBorderBottomRightRadius { inner: pixel_value })
279
123
}
280

            
281
#[cfg(all(test, feature = "parser"))]
282
mod tests {
283
    use super::*;
284

            
285
    #[test]
286
1
    fn test_parse_border_radius_shorthand() {
287
        // One value
288
1
        let result = parse_style_border_radius("10px").unwrap();
289
1
        assert_eq!(result.top_left, PixelValue::px(10.0));
290
1
        assert_eq!(result.top_right, PixelValue::px(10.0));
291
1
        assert_eq!(result.bottom_right, PixelValue::px(10.0));
292
1
        assert_eq!(result.bottom_left, PixelValue::px(10.0));
293

            
294
        // Two values
295
1
        let result = parse_style_border_radius("10px 5%").unwrap();
296
1
        assert_eq!(result.top_left, PixelValue::px(10.0));
297
1
        assert_eq!(result.top_right, PixelValue::percent(5.0));
298
1
        assert_eq!(result.bottom_right, PixelValue::px(10.0));
299
1
        assert_eq!(result.bottom_left, PixelValue::percent(5.0));
300

            
301
        // Three values
302
1
        let result = parse_style_border_radius("2px 4px 8px").unwrap();
303
1
        assert_eq!(result.top_left, PixelValue::px(2.0));
304
1
        assert_eq!(result.top_right, PixelValue::px(4.0));
305
1
        assert_eq!(result.bottom_right, PixelValue::px(8.0));
306
1
        assert_eq!(result.bottom_left, PixelValue::px(4.0));
307

            
308
        // Four values
309
1
        let result = parse_style_border_radius("1px 0 3px 4px").unwrap();
310
1
        assert_eq!(result.top_left, PixelValue::px(1.0));
311
1
        assert_eq!(result.top_right, PixelValue::px(0.0));
312
1
        assert_eq!(result.bottom_right, PixelValue::px(3.0));
313
1
        assert_eq!(result.bottom_left, PixelValue::px(4.0));
314

            
315
        // Weird whitespace
316
1
        let result = parse_style_border_radius("  1em   2em  ").unwrap();
317
1
        assert_eq!(result.top_left, PixelValue::em(1.0));
318
1
        assert_eq!(result.top_right, PixelValue::em(2.0));
319
1
    }
320

            
321
    #[test]
322
1
    fn test_parse_border_radius_shorthand_errors() {
323
1
        assert!(parse_style_border_radius("").is_err());
324
1
        assert!(parse_style_border_radius("1px 2px 3px 4px 5px").is_err());
325
1
        assert!(parse_style_border_radius("1px bad 3px").is_err());
326
1
    }
327

            
328
    #[test]
329
1
    fn test_parse_longhand_radius() {
330
1
        let result = parse_style_border_top_left_radius("25%").unwrap();
331
1
        assert_eq!(result.inner, PixelValue::percent(25.0));
332
1
    }
333
}
334

            
335
#[cfg(all(test, feature = "parser"))]
336
#[allow(
337
    clippy::float_cmp,
338
    clippy::unreadable_literal,
339
    clippy::too_many_lines,
340
    clippy::cast_precision_loss
341
)]
342
mod autotest_generated {
343
    use super::*;
344
    use crate::{css::PrintAsCssValue, props::basic::length::SizeMetric};
345

            
346
    /// Every metric that `parse_pixel_value` has a suffix for. `Vmin` is
347
    /// deliberately absent — see `vmin_radius_should_parse_but_is_shadowed_by_in`.
348
    const ROUNDTRIPPABLE_METRICS: [SizeMetric; 11] = [
349
        SizeMetric::Px,
350
        SizeMetric::Pt,
351
        SizeMetric::Em,
352
        SizeMetric::Rem,
353
        SizeMetric::In,
354
        SizeMetric::Cm,
355
        SizeMetric::Mm,
356
        SizeMetric::Percent,
357
        SizeMetric::Vw,
358
        SizeMetric::Vh,
359
        SizeMetric::Vmax,
360
    ];
361

            
362
    /// Values that survive the 1/1000 fixed-point quantization of `FloatValue`
363
    /// exactly, so a failed round-trip means a real parser/printer bug and not
364
    /// a rounding artifact.
365
    const EXACT_VALUES: [f32; 6] = [0.0, 1.0, 12.5, -3.25, 0.125, 1000.5];
366

            
367
    /// Inputs that are not valid CSS lengths in any position.
368
    const GARBAGE: [&str; 14] = [
369
        "bad",
370
        "px",
371
        "%",
372
        "em",
373
        "-",
374
        "+",
375
        ".",
376
        "e",
377
        "1..2px",
378
        "1,2px",
379
        "10px;",
380
        "10px!important",
381
        "\0",
382
        "\u{7f}\u{1}",
383
    ];
384

            
385
    fn all_longhands(input: &str) -> [Result<PixelValue, ()>; 4] {
386
        [
387
            parse_style_border_top_left_radius(input)
388
                .map(|v| v.inner)
389
                .map_err(|_| ()),
390
            parse_style_border_top_right_radius(input)
391
                .map(|v| v.inner)
392
                .map_err(|_| ()),
393
            parse_style_border_bottom_left_radius(input)
394
                .map(|v| v.inner)
395
                .map_err(|_| ()),
396
            parse_style_border_bottom_right_radius(input)
397
                .map(|v| v.inner)
398
                .map_err(|_| ()),
399
        ]
400
    }
401

            
402
    // ================================================= shorthand: malformed ===
403

            
404
    #[test]
405
    fn shorthand_rejects_empty_and_whitespace_only() {
406
        // `split_whitespace` yields zero components, which falls into the `_`
407
        // arm — so a *missing* value is reported as TooManyValues. That variant
408
        // is a misnomer for this input (see report), but it is still an Err.
409
        for input in ["", " ", "   ", "\t\n", "\r\n\t ", "\u{a0}"] {
410
            let err = parse_style_border_radius(input)
411
                .expect_err("whitespace-only border-radius must not parse");
412
            assert!(
413
                matches!(err, CssBorderRadiusParseError::TooManyValues(_)),
414
                "unexpected error for {input:?}: {err}"
415
            );
416
        }
417
    }
418

            
419
    #[test]
420
    fn shorthand_rejects_garbage_without_panicking() {
421
        for input in GARBAGE {
422
            assert!(
423
                parse_style_border_radius(input).is_err(),
424
                "garbage {input:?} was accepted"
425
            );
426
        }
427
    }
428

            
429
    #[test]
430
    fn shorthand_rejects_more_than_four_values() {
431
        let input = "1px 2px 3px 4px 5px";
432
        let err = parse_style_border_radius(input).unwrap_err();
433
        assert_eq!(err, CssBorderRadiusParseError::TooManyValues(input));
434
        // The error carries the *whole* input back, not just the extra value.
435
        assert!(format!("{err}").contains(input));
436
    }
437

            
438
    #[test]
439
    fn shorthand_reports_the_bad_component_before_counting_values() {
440
        // Values are parsed eagerly, so a malformed component wins over the
441
        // arity check even when the arity is also wrong.
442
        let err = parse_style_border_radius("1px 2px 3px 4px 5px bad").unwrap_err();
443
        assert_eq!(
444
            err,
445
            CssBorderRadiusParseError::PixelValue(CssPixelValueParseError::InvalidPixelValue(
446
                "bad"
447
            ))
448
        );
449
    }
450

            
451
    #[test]
452
    fn shorthand_rejects_elliptical_slash_syntax() {
453
        // `border-radius: 10px / 20px` is valid CSS but unsupported here; the
454
        // important part is that it is *rejected* rather than silently
455
        // mis-parsed into the wrong corners.
456
        assert!(parse_style_border_radius("10px / 20px").is_err());
457
        assert!(parse_style_border_radius("10px/20px").is_err());
458
        assert!(parse_style_border_radius("1px 2px / 3px 4px").is_err());
459
    }
460

            
461
    #[test]
462
    fn shorthand_rejects_split_number_and_unit() {
463
        // "10 px" is two components: "10" (a bare number => px) and "px"
464
        // (a unit with no value) — the latter fails.
465
        let err = parse_style_border_radius("10 px").unwrap_err();
466
        assert_eq!(
467
            err,
468
            CssBorderRadiusParseError::PixelValue(CssPixelValueParseError::NoValueGiven(
469
                "px",
470
                SizeMetric::Px
471
            ))
472
        );
473
    }
474

            
475
    // ================================================== shorthand: numerics ===
476

            
477
    #[test]
478
    fn shorthand_boundary_numbers_never_produce_nan_or_infinity() {
479
        // Whatever these do, the stored FloatValue must stay finite: it is an
480
        // isize under the hood and a NaN/inf leak would poison layout.
481
        let inputs = [
482
            "0",
483
            "-0",
484
            "+0",
485
            "0px",
486
            "-0px",
487
            "0.0001px",
488
            "1e-30px",
489
            "1e30px",
490
            "-1e30px",
491
            "3.4028235e38px",
492
            "-3.4028235e38px",
493
            "9223372036854775807px",
494
            "-9223372036854775808px",
495
            "340282350000000000000000000000000000000%",
496
        ];
497
        for input in inputs {
498
            let Ok(radius) = parse_style_border_radius(input) else {
499
                continue; // rejection is an equally safe outcome
500
            };
501
            for corner in [
502
                radius.top_left,
503
                radius.top_right,
504
                radius.bottom_left,
505
                radius.bottom_right,
506
            ] {
507
                let n = corner.number.get();
508
                assert!(n.is_finite(), "{input:?} produced non-finite {n}");
509
            }
510
        }
511
    }
512

            
513
    #[test]
514
    fn shorthand_nan_input_is_flattened_to_zero() {
515
        // f32::from_str accepts "NaN"; FloatValue::new then casts NaN*1000 to
516
        // isize, and `as` maps NaN to 0. So `border-radius: NaNpx` is silently
517
        // accepted as 0px rather than rejected — assert it at least cannot
518
        // smuggle a NaN into the layout engine.
519
        for input in ["NaN", "nan", "NaNpx", "-nan%"] {
520
            let radius = parse_style_border_radius(input)
521
                .unwrap_or_else(|e| panic!("{input:?} unexpectedly rejected: {e}"));
522
            let n = radius.top_left.number.get();
523
            assert!(!n.is_nan(), "{input:?} leaked a NaN");
524
            assert_eq!(n, 0.0, "{input:?} should quantize to 0");
525
        }
526
    }
527

            
528
    #[test]
529
    fn shorthand_infinite_input_saturates_instead_of_overflowing() {
530
        let pos = parse_style_border_radius("infpx").unwrap().top_left;
531
        let neg = parse_style_border_radius("-infpx").unwrap().top_left;
532
        assert!(pos.number.get().is_finite());
533
        assert!(neg.number.get().is_finite());
534
        assert!(pos.number.get() > 0.0);
535
        assert!(neg.number.get() < 0.0);
536
        // Saturation, not wraparound: +inf must not come back out negative.
537
        assert_eq!(pos.number.number(), isize::MAX);
538
        assert_eq!(neg.number.number(), isize::MIN);
539
    }
540

            
541
    #[test]
542
    fn shorthand_sub_quantum_values_truncate_to_zero() {
543
        // FloatValue keeps 1/1000 of a unit; anything smaller becomes 0.
544
        // A 0.0001px radius is therefore indistinguishable from no radius.
545
        let radius = parse_style_border_radius("0.0001px").unwrap();
546
        assert_eq!(radius.top_left, PixelValue::px(0.0));
547
        assert_eq!(radius.top_left.number.number(), 0);
548
    }
549

            
550
    #[test]
551
    fn shorthand_negative_zero_equals_positive_zero() {
552
        let neg = parse_style_border_radius("-0px").unwrap();
553
        let pos = parse_style_border_radius("0px").unwrap();
554
        assert_eq!(neg, pos);
555
        assert_eq!(neg.top_left.number.number(), 0);
556
    }
557

            
558
    // ==================================== shorthand: long / unicode / nested ===
559

            
560
    #[test]
561
    fn shorthand_extremely_long_input_terminates() {
562
        // 100k components: must reject on arity, not hang or blow the stack.
563
        let many = "1px ".repeat(100_000);
564
        assert!(matches!(
565
            parse_style_border_radius(&many),
566
            Err(CssBorderRadiusParseError::TooManyValues(_))
567
        ));
568

            
569
        // A single 100k-digit number: f32 parsing overflows to inf, which the
570
        // fixed-point cast saturates.
571
        let huge = format!("{}px", "1".repeat(100_000));
572
        let radius = parse_style_border_radius(&huge).unwrap();
573
        assert!(radius.top_left.number.get().is_finite());
574

            
575
        // 100k chars of pure junk in one token.
576
        let junk = "z".repeat(100_000);
577
        assert!(parse_style_border_radius(&junk).is_err());
578
    }
579

            
580
    #[test]
581
    fn shorthand_deeply_nested_brackets_do_not_stack_overflow() {
582
        let nested = format!("{}{}", "(".repeat(10_000), ")".repeat(10_000));
583
        assert!(parse_style_border_radius(&nested).is_err());
584

            
585
        let calls = format!("{}1px{}", "calc(".repeat(10_000), ")".repeat(10_000));
586
        assert!(parse_style_border_radius(&calls).is_err());
587
    }
588

            
589
    #[test]
590
    fn shorthand_unicode_input_is_rejected_without_panicking() {
591
        // Multibyte input must not be byte-sliced anywhere in the parser.
592
        for input in [
593
            "\u{1F600}",
594
            "10px\u{1F600}",
595
            "\u{1F600}px",
596
            "\u{661}\u{660}px", // arabic-indic digits
597
            "10\u{301}px",      // combining acute
598
            "10px\u{200b}",     // zero-width space (not a separator)
599
            "10px",           // fullwidth digits
600
            "10\u{202e}px",     // right-to-left override
601
        ] {
602
            assert!(
603
                parse_style_border_radius(input).is_err(),
604
                "unicode {input:?} was accepted"
605
            );
606
        }
607
    }
608

            
609
    #[test]
610
    fn shorthand_treats_non_breaking_space_as_a_value_separator() {
611
        // `str::split_whitespace` uses the Unicode White_Space property, so
612
        // U+00A0 separates values here even though CSS tokenization does not
613
        // treat it as whitespace (browsers reject this). Pinning current
614
        // behaviour — see report.
615
        let radius = parse_style_border_radius("1px\u{a0}2px").unwrap();
616
        assert_eq!(radius.top_left, PixelValue::px(1.0));
617
        assert_eq!(radius.top_right, PixelValue::px(2.0));
618
    }
619

            
620
    // ==================================== shorthand: corner-expansion invariants
621

            
622
    #[test]
623
    fn shorthand_one_value_fills_every_corner() {
624
        let radius = parse_style_border_radius("7px").unwrap();
625
        assert_eq!(radius.top_left, PixelValue::px(7.0));
626
        assert_eq!(radius.top_right, PixelValue::px(7.0));
627
        assert_eq!(radius.bottom_left, PixelValue::px(7.0));
628
        assert_eq!(radius.bottom_right, PixelValue::px(7.0));
629
    }
630

            
631
    #[test]
632
    fn shorthand_two_and_three_values_expand_along_the_diagonals() {
633
        // CSS Backgrounds 3 §5.1: 2 values => TL/BR = 1st, TR/BL = 2nd.
634
        let two = parse_style_border_radius("1px 2px").unwrap();
635
        assert_eq!(two.top_left, two.bottom_right);
636
        assert_eq!(two.top_right, two.bottom_left);
637
        assert_eq!(two.top_left, PixelValue::px(1.0));
638
        assert_eq!(two.top_right, PixelValue::px(2.0));
639

            
640
        // 3 values => TL = 1st, TR/BL = 2nd, BR = 3rd.
641
        let three = parse_style_border_radius("1px 2px 3px").unwrap();
642
        assert_eq!(three.top_left, PixelValue::px(1.0));
643
        assert_eq!(three.top_right, PixelValue::px(2.0));
644
        assert_eq!(three.bottom_left, PixelValue::px(2.0));
645
        assert_eq!(three.bottom_right, PixelValue::px(3.0));
646
    }
647

            
648
    #[test]
649
    fn shorthand_four_values_map_clockwise_from_top_left() {
650
        let four = parse_style_border_radius("1px 2px 3px 4px").unwrap();
651
        assert_eq!(four.top_left, PixelValue::px(1.0));
652
        assert_eq!(four.top_right, PixelValue::px(2.0));
653
        assert_eq!(four.bottom_right, PixelValue::px(3.0));
654
        assert_eq!(four.bottom_left, PixelValue::px(4.0));
655
        // No two corners aliased: a copy-paste slip in the match arm would
656
        // duplicate one of these.
657
        assert_ne!(four.top_left, four.top_right);
658
        assert_ne!(four.bottom_right, four.bottom_left);
659
    }
660

            
661
    #[test]
662
    fn shorthand_preserves_per_corner_units() {
663
        let radius = parse_style_border_radius("1px 2em 3% 4rem").unwrap();
664
        assert_eq!(radius.top_left, PixelValue::px(1.0));
665
        assert_eq!(radius.top_right, PixelValue::em(2.0));
666
        assert_eq!(radius.bottom_right, PixelValue::percent(3.0));
667
        assert_eq!(radius.bottom_left, PixelValue::rem(4.0));
668
    }
669

            
670
    #[test]
671
    fn shorthand_valid_minimal_input() {
672
        let radius = parse_style_border_radius("0").unwrap();
673
        assert_eq!(radius.top_left, PixelValue::px(0.0));
674
    }
675

            
676
    #[test]
677
    fn shorthand_tolerates_arbitrary_ascii_whitespace_runs() {
678
        let radius = parse_style_border_radius("\n\t 1px \t 2px\r\n").unwrap();
679
        assert_eq!(radius.top_left, PixelValue::px(1.0));
680
        assert_eq!(radius.top_right, PixelValue::px(2.0));
681
    }
682

            
683
    // ====================================================== longhand parsers ===
684

            
685
    #[test]
686
    fn longhands_reject_empty_whitespace_and_garbage() {
687
        for input in ["", " ", "\t\n"] {
688
            for result in all_longhands(input) {
689
                assert_eq!(result, Err(()), "{input:?} was accepted by a longhand");
690
            }
691
        }
692
        for input in GARBAGE {
693
            for result in all_longhands(input) {
694
                assert_eq!(result, Err(()), "{input:?} was accepted by a longhand");
695
            }
696
        }
697
    }
698

            
699
    #[test]
700
    fn longhands_reject_multiple_values() {
701
        // A longhand takes exactly one length; the shorthand list must not leak
702
        // through (e.g. by silently using the first value).
703
        for input in ["1px 2px", "1px 2px 3px 4px", "1px,2px"] {
704
            for result in all_longhands(input) {
705
                assert_eq!(result, Err(()), "{input:?} was accepted by a longhand");
706
            }
707
        }
708
    }
709

            
710
    #[test]
711
    fn all_four_longhands_agree_on_every_input() {
712
        // The four parsers are macro-free copies of each other; a copy-paste
713
        // bug (wrong metric, wrong field) would show up as a disagreement.
714
        let inputs = [
715
            "0",
716
            "10px",
717
            "-3.25em",
718
            "50%",
719
            "1.5rem",
720
            "2pt",
721
            "1in",
722
            "2.54cm",
723
            "10mm",
724
            "5vw",
725
            "5vh",
726
            "5vmax",
727
            "bad",
728
            "",
729
            "   ",
730
            "\u{1F600}",
731
            "1e30px",
732
            "NaNpx",
733
        ];
734
        for input in inputs {
735
            let [tl, tr, bl, br] = all_longhands(input);
736
            assert_eq!(tl, tr, "top-left vs top-right disagree on {input:?}");
737
            assert_eq!(tl, bl, "top-left vs bottom-left disagree on {input:?}");
738
            assert_eq!(tl, br, "top-left vs bottom-right disagree on {input:?}");
739
        }
740
    }
741

            
742
    #[test]
743
    fn longhands_agree_with_the_shorthand_on_single_values() {
744
        for input in ["0", "10px", "-3.25em", "50%", "1.5rem", "2pt"] {
745
            let shorthand = parse_style_border_radius(input).unwrap();
746
            let [tl, tr, bl, br] = all_longhands(input);
747
            assert_eq!(tl, Ok(shorthand.top_left), "{input:?}");
748
            assert_eq!(tr, Ok(shorthand.top_right), "{input:?}");
749
            assert_eq!(bl, Ok(shorthand.bottom_left), "{input:?}");
750
            assert_eq!(br, Ok(shorthand.bottom_right), "{input:?}");
751
        }
752
    }
753

            
754
    #[test]
755
    fn longhands_accept_a_gap_between_number_and_unit_but_the_shorthand_does_not() {
756
        // `parse_pixel_value` trims the value before parsing, so "10 px" is a
757
        // valid longhand — while the shorthand splits it into two components
758
        // and fails. Divergent, but deterministic; pinning both sides.
759
        for result in all_longhands("10 px") {
760
            assert_eq!(result, Ok(PixelValue::px(10.0)));
761
        }
762
        assert!(parse_style_border_radius("10 px").is_err());
763
    }
764

            
765
    #[test]
766
    fn longhands_survive_extremely_long_and_nested_input() {
767
        let long = format!("{}px", "9".repeat(100_000));
768
        for result in all_longhands(&long) {
769
            assert!(result.unwrap().number.get().is_finite());
770
        }
771
        let nested = format!("{}1px{}", "(".repeat(10_000), ")".repeat(10_000));
772
        for result in all_longhands(&nested) {
773
            assert_eq!(result, Err(()));
774
        }
775
    }
776

            
777
    #[test]
778
    fn longhands_boundary_numbers_stay_finite() {
779
        for input in [
780
            "0",
781
            "-0",
782
            "1e-30px",
783
            "1e30px",
784
            "-1e30px",
785
            "9223372036854775807px",
786
            "NaNpx",
787
            "infpx",
788
            "-infpx",
789
        ] {
790
            for result in all_longhands(input) {
791
                let value = result.unwrap_or_else(|()| panic!("{input:?} rejected"));
792
                let n = value.number.get();
793
                assert!(n.is_finite() && !n.is_nan(), "{input:?} produced {n}");
794
            }
795
        }
796
    }
797

            
798
    // =========================================================== round-trips ===
799

            
800
    #[test]
801
    fn print_as_css_value_round_trips_through_every_longhand_parser() {
802
        for metric in ROUNDTRIPPABLE_METRICS {
803
            for value in EXACT_VALUES {
804
                let pixel = PixelValue::from_metric(metric, value);
805

            
806
                let tl = StyleBorderTopLeftRadius { inner: pixel };
807
                let reparsed = parse_style_border_top_left_radius(&tl.print_as_css_value())
808
                    .unwrap_or_else(|e| {
809
                        panic!("{:?} did not re-parse: {e}", tl.print_as_css_value())
810
                    });
811
                assert_eq!(reparsed, tl);
812

            
813
                let tr = StyleBorderTopRightRadius { inner: pixel };
814
                assert_eq!(
815
                    parse_style_border_top_right_radius(&tr.print_as_css_value()).unwrap(),
816
                    tr
817
                );
818

            
819
                let bl = StyleBorderBottomLeftRadius { inner: pixel };
820
                assert_eq!(
821
                    parse_style_border_bottom_left_radius(&bl.print_as_css_value()).unwrap(),
822
                    bl
823
                );
824

            
825
                let br = StyleBorderBottomRightRadius { inner: pixel };
826
                assert_eq!(
827
                    parse_style_border_bottom_right_radius(&br.print_as_css_value()).unwrap(),
828
                    br
829
                );
830
            }
831
        }
832
    }
833

            
834
    #[test]
835
    fn shorthand_round_trips_through_the_printed_corner_values() {
836
        let original = parse_style_border_radius("1px 2em 3% 4rem").unwrap();
837
        let printed = format!(
838
            "{} {} {} {}",
839
            StyleBorderTopLeftRadius {
840
                inner: original.top_left
841
            }
842
            .print_as_css_value(),
843
            StyleBorderTopRightRadius {
844
                inner: original.top_right
845
            }
846
            .print_as_css_value(),
847
            StyleBorderBottomRightRadius {
848
                inner: original.bottom_right
849
            }
850
            .print_as_css_value(),
851
            StyleBorderBottomLeftRadius {
852
                inner: original.bottom_left
853
            }
854
            .print_as_css_value(),
855
        );
856
        assert_eq!(parse_style_border_radius(&printed).unwrap(), original);
857
    }
858

            
859
    #[test]
860
    fn debug_output_matches_the_printed_css_value() {
861
        // The Debug impl is hand-written to delegate to `inner`; if it ever
862
        // reverts to the derived one, printed CSS and logs would diverge.
863
        let pixel = PixelValue::em(1.5);
864
        let tl = StyleBorderTopLeftRadius { inner: pixel };
865
        assert_eq!(format!("{tl:?}"), "1.5em");
866
        assert_eq!(format!("{tl:?}"), tl.print_as_css_value());
867
    }
868

            
869
    #[test]
870
    fn vmin_radius_parses() {
871
        // `border-radius: 3vmin` is valid CSS. parse_pixel_value used to check the
872
        // "in" suffix before "vmin", so "3vmin" stripped to "3vm" and failed to
873
        // parse as f32. The suffix table now orders "vmin"/"vmax" before "in"
874
        // (css/src/props/basic/pixel.rs), so this round-trips like every other metric.
875
        let printed = StyleBorderTopLeftRadius {
876
            inner: PixelValue::from_metric(SizeMetric::Vmin, 3.0),
877
        }
878
        .print_as_css_value();
879
        assert_eq!(printed, "3vmin");
880
        assert_eq!(
881
            parse_style_border_top_left_radius(&printed).unwrap().inner,
882
            PixelValue::from_metric(SizeMetric::Vmin, 3.0)
883
        );
884
    }
885

            
886
    // ================================================ constructors / getters ===
887

            
888
    #[test]
889
    fn default_and_zero_agree_for_every_corner_type() {
890
        assert_eq!(
891
            StyleBorderTopLeftRadius::default(),
892
            StyleBorderTopLeftRadius::zero()
893
        );
894
        assert_eq!(
895
            StyleBorderTopRightRadius::default(),
896
            StyleBorderTopRightRadius::zero()
897
        );
898
        assert_eq!(
899
            StyleBorderBottomLeftRadius::default(),
900
            StyleBorderBottomLeftRadius::zero()
901
        );
902
        assert_eq!(
903
            StyleBorderBottomRightRadius::default(),
904
            StyleBorderBottomRightRadius::zero()
905
        );
906
        assert_eq!(
907
            StyleBorderTopLeftRadius::default().inner,
908
            PixelValue::px(0.0)
909
        );
910
    }
911

            
912
    #[test]
913
    fn const_constructors_agree_with_the_float_constructors() {
914
        assert_eq!(
915
            StyleBorderTopLeftRadius::const_px(10),
916
            StyleBorderTopLeftRadius::px(10.0)
917
        );
918
        assert_eq!(
919
            StyleBorderTopLeftRadius::const_em(2),
920
            StyleBorderTopLeftRadius::em(2.0)
921
        );
922
        assert_eq!(
923
            StyleBorderTopLeftRadius::const_percent(50),
924
            StyleBorderTopLeftRadius::percent(50.0)
925
        );
926
        assert_eq!(
927
            StyleBorderTopLeftRadius::const_pt(-3),
928
            StyleBorderTopLeftRadius::pt(-3.0)
929
        );
930
        assert_eq!(
931
            StyleBorderTopLeftRadius::from_pixel_value(PixelValue::px(4.0)),
932
            StyleBorderTopLeftRadius::px(4.0)
933
        );
934
    }
935

            
936
    #[test]
937
    fn interpolate_returns_the_endpoints_for_matching_metrics() {
938
        let a = StyleBorderTopLeftRadius::px(0.0);
939
        let b = StyleBorderTopLeftRadius::px(10.0);
940
        assert_eq!(a.interpolate(&b, 0.0), a);
941
        assert_eq!(a.interpolate(&b, 1.0), b);
942
        assert_eq!(a.interpolate(&b, 0.5), StyleBorderTopLeftRadius::px(5.0));
943
    }
944

            
945
    #[test]
946
    fn interpolate_stays_finite_for_hostile_t_values() {
947
        let a = StyleBorderTopLeftRadius::px(0.0);
948
        let b = StyleBorderTopLeftRadius::px(10.0);
949
        for t in [
950
            -1.0,
951
            2.0,
952
            1e30,
953
            -1e30,
954
            f32::INFINITY,
955
            f32::NEG_INFINITY,
956
            f32::NAN,
957
        ] {
958
            let n = a.interpolate(&b, t).inner.number.get();
959
            assert!(n.is_finite(), "t={t} produced {n}");
960
            assert!(!n.is_nan(), "t={t} produced NaN");
961
        }
962
        // NaN t collapses to 0 rather than poisoning the value.
963
        assert_eq!(a.interpolate(&b, f32::NAN).inner.number.get(), 0.0);
964
    }
965

            
966
    #[test]
967
    fn interpolate_across_metrics_converts_to_px() {
968
        // Mixed metrics fall back to px using the default 16px font size,
969
        // so 1em (=16px) -> 10px at t=0.5 is 13px.
970
        let em = StyleBorderTopLeftRadius::em(1.0);
971
        let px = StyleBorderTopLeftRadius::px(10.0);
972
        let mid = em.interpolate(&px, 0.5);
973
        assert_eq!(mid.inner.metric, SizeMetric::Px);
974
        assert_eq!(mid.inner.number.get(), 13.0);
975
        // Note: unlike the same-metric case, t=0 does NOT return `em` itself.
976
        assert_eq!(em.interpolate(&px, 0.0), StyleBorderTopLeftRadius::px(16.0));
977
    }
978

            
979
    // ========================================================= error getters ===
980

            
981
    #[test]
982
    fn shorthand_error_to_contained_round_trips_for_every_variant() {
983
        let float_err = "x".parse::<f32>().unwrap_err();
984
        let variants = [
985
            CssBorderRadiusParseError::TooManyValues("1px 2px 3px 4px 5px"),
986
            CssBorderRadiusParseError::PixelValue(CssPixelValueParseError::EmptyString),
987
            CssBorderRadiusParseError::PixelValue(CssPixelValueParseError::NoValueGiven(
988
                "px",
989
                SizeMetric::Px,
990
            )),
991
            CssBorderRadiusParseError::PixelValue(CssPixelValueParseError::ValueParseErr(
992
                float_err, "bad",
993
            )),
994
            CssBorderRadiusParseError::PixelValue(CssPixelValueParseError::InvalidPixelValue(
995
                "nope",
996
            )),
997
        ];
998
        for variant in variants {
999
            let owned = variant.to_contained();
            assert_eq!(owned.to_shared(), variant);
            // Display must survive the round-trip too.
            assert_eq!(format!("{}", owned.to_shared()), format!("{variant}"));
        }
    }
    #[test]
    fn shorthand_error_to_contained_handles_empty_unicode_and_huge_inputs() {
        let huge = "1px ".repeat(50_000);
        for input in ["", " ", "\u{1F600}\u{301}", "\0", huge.as_str()] {
            let err = CssBorderRadiusParseError::TooManyValues(input);
            let owned = err.to_contained();
            assert_eq!(owned.to_shared(), err);
            match owned {
                CssBorderRadiusParseErrorOwned::TooManyValues(s) => {
                    assert_eq!(s.as_str(), input);
                }
                CssBorderRadiusParseErrorOwned::PixelValue(_) => panic!("wrong variant"),
            }
        }
    }
    #[test]
    fn shorthand_errors_from_the_parser_round_trip() {
        // Same as above, but with errors the parser actually produces rather
        // than hand-built ones.
        for input in ["", "1px 2px 3px 4px 5px", "1px bad 3px", "px", "\u{1F600}"] {
            let err = parse_style_border_radius(input).unwrap_err();
            let owned = err.to_contained();
            assert_eq!(owned.to_shared(), err);
        }
    }
    #[test]
    fn error_debug_delegates_to_display() {
        let err = CssBorderRadiusParseError::TooManyValues("a b c d e");
        assert_eq!(format!("{err:?}"), format!("{err}"));
        assert!(format!("{err}").contains("a b c d e"));
        let inner = CssBorderRadiusParseError::PixelValue(CssPixelValueParseError::EmptyString);
        assert_eq!(
            format!("{inner}"),
            format!("{}", CssPixelValueParseError::EmptyString)
        );
    }
    #[test]
    fn longhand_error_types_round_trip() {
        // Each of the four longhand error enums has its own generated
        // to_contained/to_shared pair.
        let tl = parse_style_border_top_left_radius("bad").unwrap_err();
        assert_eq!(tl.to_contained().to_shared(), tl);
        let tr = parse_style_border_top_right_radius("").unwrap_err();
        assert_eq!(tr.to_contained().to_shared(), tr);
        let bl = parse_style_border_bottom_left_radius("px").unwrap_err();
        assert_eq!(bl.to_contained().to_shared(), bl);
        let br = parse_style_border_bottom_right_radius("\u{1F600}").unwrap_err();
        assert_eq!(br.to_contained().to_shared(), br);
        // ... and each keeps the underlying pixel error intact.
        assert_eq!(
            tl.to_contained(),
            StyleBorderTopLeftRadiusParseErrorOwned::PixelValue(
                CssPixelValueParseError::InvalidPixelValue("bad").to_contained()
            )
        );
    }
    #[test]
    fn owned_error_newtype_wrapper_preserves_the_inner_error() {
        let owned = CssBorderRadiusParseError::TooManyValues("1 2 3 4 5").to_contained();
        let wrapped = CssStyleBorderRadiusParseErrorOwned::from(owned.clone());
        assert_eq!(wrapped.inner, owned);
        assert_eq!(wrapped.inner.to_shared().to_contained(), owned);
    }
}