1
//! CSS properties for `margin`, `padding`, and `gap` (column-gap / row-gap).
2
//!
3
//! Shorthand parsers (`parse_layout_padding`, `parse_layout_margin`) and
4
//! longhand per-side parsers are gated behind `#[cfg(feature = "parser")]`.
5

            
6
use alloc::{
7
    string::{String, ToString},
8
    vec::Vec,
9
};
10

            
11
#[cfg(feature = "parser")]
12
use crate::props::basic::pixel::{parse_pixel_value_with_auto, PixelValueWithAuto};
13
use crate::{
14
    css::PrintAsCssValue,
15
    props::{
16
        basic::pixel::{CssPixelValueParseError, CssPixelValueParseErrorOwned, PixelValue},
17
        macros::PixelValueTaker,
18
    },
19
};
20

            
21
// --- TYPE DEFINITIONS ---
22

            
23
// Spacing properties - wrapper structs around PixelValue for type safety
24

            
25
macro_rules! impl_spacing_type_impls {
26
    ($name:ident) => {
27
        impl ::core::fmt::Debug for $name {
28
809
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
29
809
                write!(f, "{}", self.inner)
30
809
            }
31
        }
32

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

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

            
43
/// Layout padding top value
44
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
45
#[repr(C)]
46
pub struct LayoutPaddingTop {
47
    pub inner: PixelValue,
48
}
49
impl_spacing_type_impls!(LayoutPaddingTop);
50

            
51
/// Layout padding right value
52
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
53
#[repr(C)]
54
pub struct LayoutPaddingRight {
55
    pub inner: PixelValue,
56
}
57
impl_spacing_type_impls!(LayoutPaddingRight);
58

            
59
/// Layout padding bottom value
60
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
61
#[repr(C)]
62
pub struct LayoutPaddingBottom {
63
    pub inner: PixelValue,
64
}
65
impl_spacing_type_impls!(LayoutPaddingBottom);
66

            
67
/// Layout padding left value
68
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
69
#[repr(C)]
70
pub struct LayoutPaddingLeft {
71
    pub inner: PixelValue,
72
}
73
impl_spacing_type_impls!(LayoutPaddingLeft);
74

            
75
/// Layout padding inline start value (for RTL/LTR support)
76
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
77
#[repr(C)]
78
pub struct LayoutPaddingInlineStart {
79
    pub inner: PixelValue,
80
}
81
impl_spacing_type_impls!(LayoutPaddingInlineStart);
82

            
83
/// Layout padding inline end value (for RTL/LTR support)
84
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
85
#[repr(C)]
86
pub struct LayoutPaddingInlineEnd {
87
    pub inner: PixelValue,
88
}
89
impl_spacing_type_impls!(LayoutPaddingInlineEnd);
90

            
91
/// Layout margin top value
92
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
93
#[repr(C)]
94
pub struct LayoutMarginTop {
95
    pub inner: PixelValue,
96
}
97
impl_spacing_type_impls!(LayoutMarginTop);
98

            
99
/// Layout margin right value
100
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
101
#[repr(C)]
102
pub struct LayoutMarginRight {
103
    pub inner: PixelValue,
104
}
105
impl_spacing_type_impls!(LayoutMarginRight);
106

            
107
/// Layout margin bottom value
108
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
109
#[repr(C)]
110
pub struct LayoutMarginBottom {
111
    pub inner: PixelValue,
112
}
113
impl_spacing_type_impls!(LayoutMarginBottom);
114

            
115
/// Layout margin left value
116
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
117
#[repr(C)]
118
pub struct LayoutMarginLeft {
119
    pub inner: PixelValue,
120
}
121
impl_spacing_type_impls!(LayoutMarginLeft);
122

            
123
/// Layout column gap value (for flexbox/grid)
124
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
125
#[repr(C)]
126
pub struct LayoutColumnGap {
127
    pub inner: PixelValue,
128
}
129
impl_spacing_type_impls!(LayoutColumnGap);
130

            
131
/// Layout row gap value (for flexbox/grid)
132
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
133
#[repr(C)]
134
pub struct LayoutRowGap {
135
    pub inner: PixelValue,
136
}
137
impl_spacing_type_impls!(LayoutRowGap);
138

            
139
// --- PARSERS ---
140

            
141
#[cfg(feature = "parser")]
142
macro_rules! impl_spacing_parse_error {
143
    ($borrowed:ident, $owned:ident, $property_name:expr) => {
144
        #[cfg(feature = "parser")]
145
        impl_debug_as_display!($borrowed<'a>);
146

            
147
        #[cfg(feature = "parser")]
148
        impl_display! { $borrowed<'a>, {
149
            PixelValueParseError(e) => format!("Could not parse pixel value: {}", e),
150
            TooManyValues => concat!("Too many values: ", $property_name, " property accepts at most 4 values."),
151
            TooFewValues => concat!("Too few values: ", $property_name, " property requires at least 1 value."),
152
        }}
153

            
154
        #[cfg(feature = "parser")]
155
        impl_from!(
156
            CssPixelValueParseError<'a>,
157
            $borrowed::PixelValueParseError
158
        );
159

            
160
        #[cfg(feature = "parser")]
161
        impl $borrowed<'_> {
162
4
            #[must_use] pub fn to_contained(&self) -> $owned {
163
4
                match self {
164
2
                    $borrowed::PixelValueParseError(e) => {
165
2
                        $owned::PixelValueParseError(e.to_contained())
166
                    }
167
1
                    $borrowed::TooManyValues => $owned::TooManyValues,
168
1
                    $borrowed::TooFewValues => $owned::TooFewValues,
169
                }
170
4
            }
171
        }
172

            
173
        #[cfg(feature = "parser")]
174
        impl $owned {
175
4
            #[must_use] pub fn to_shared(&self) -> $borrowed<'_> {
176
4
                match self {
177
2
                    $owned::PixelValueParseError(e) => {
178
2
                        $borrowed::PixelValueParseError(e.to_shared())
179
                    }
180
1
                    $owned::TooManyValues => $borrowed::TooManyValues,
181
1
                    $owned::TooFewValues => $borrowed::TooFewValues,
182
                }
183
4
            }
184
        }
185
    };
186
}
187

            
188
// -- Padding Shorthand Parser --
189

            
190
/// Error from parsing a CSS `padding` shorthand value.
191
#[cfg(feature = "parser")]
192
#[derive(Clone, PartialEq, Eq)]
193
pub enum LayoutPaddingParseError<'a> {
194
    PixelValueParseError(CssPixelValueParseError<'a>),
195
    TooManyValues,
196
    TooFewValues,
197
}
198
#[allow(variant_size_differences)]
199
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
200
// disparity accepted
201
/// Owned variant of [`LayoutPaddingParseError`].
202
#[cfg(feature = "parser")]
203
#[derive(Debug, Clone, PartialEq, Eq)]
204
#[repr(C, u8)]
205
pub enum LayoutPaddingParseErrorOwned {
206
    PixelValueParseError(CssPixelValueParseErrorOwned),
207
    TooManyValues,
208
    TooFewValues,
209
}
210

            
211
#[cfg(feature = "parser")]
212
impl_spacing_parse_error!(
213
    LayoutPaddingParseError,
214
    LayoutPaddingParseErrorOwned,
215
    "padding"
216
);
217

            
218
/// Result of parsing the CSS `padding` shorthand property (1–4 values).
219
#[cfg(feature = "parser")]
220
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
221
pub struct LayoutPadding {
222
    pub top: PixelValueWithAuto,
223
    pub bottom: PixelValueWithAuto,
224
    pub left: PixelValueWithAuto,
225
    pub right: PixelValueWithAuto,
226
}
227

            
228
#[cfg(feature = "parser")]
229
/// # Errors
230
///
231
/// Returns an error if `input` is not a valid CSS `padding` value.
232
24533
pub fn parse_layout_padding(input: &str) -> Result<LayoutPadding, LayoutPaddingParseError<'_>> {
233
24533
    let values: Vec<_> = input.split_whitespace().collect();
234

            
235
24533
    let parsed_values: Vec<PixelValueWithAuto> = values
236
24533
        .iter()
237
445468
        .map(|s| parse_pixel_value_with_auto(s))
238
24533
        .collect::<Result<_, _>>()?;
239

            
240
24461
    match parsed_values.len() {
241
        1 => {
242
            // top, right, bottom, left
243
23565
            let all = parsed_values[0];
244
23565
            Ok(LayoutPadding {
245
23565
                top: all,
246
23565
                right: all,
247
23565
                bottom: all,
248
23565
                left: all,
249
23565
            })
250
        }
251
        2 => {
252
            // top/bottom, left/right
253
820
            let vertical = parsed_values[0];
254
820
            let horizontal = parsed_values[1];
255
820
            Ok(LayoutPadding {
256
820
                top: vertical,
257
820
                right: horizontal,
258
820
                bottom: vertical,
259
820
                left: horizontal,
260
820
            })
261
        }
262
        3 => {
263
            // top, left/right, bottom
264
18
            let top = parsed_values[0];
265
18
            let horizontal = parsed_values[1];
266
18
            let bottom = parsed_values[2];
267
18
            Ok(LayoutPadding {
268
18
                top,
269
18
                right: horizontal,
270
18
                bottom,
271
18
                left: horizontal,
272
18
            })
273
        }
274
        4 => {
275
            // top, right, bottom, left
276
21
            Ok(LayoutPadding {
277
21
                top: parsed_values[0],
278
21
                right: parsed_values[1],
279
21
                bottom: parsed_values[2],
280
21
                left: parsed_values[3],
281
21
            })
282
        }
283
26
        0 => Err(LayoutPaddingParseError::TooFewValues),
284
11
        _ => Err(LayoutPaddingParseError::TooManyValues),
285
    }
286
24533
}
287

            
288
// -- Margin Shorthand Parser --
289

            
290
/// Error from parsing a CSS `margin` shorthand value.
291
#[cfg(feature = "parser")]
292
#[derive(Clone, PartialEq, Eq)]
293
pub enum LayoutMarginParseError<'a> {
294
    PixelValueParseError(CssPixelValueParseError<'a>),
295
    TooManyValues,
296
    TooFewValues,
297
}
298
#[allow(variant_size_differences)]
299
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
300
// disparity accepted
301
/// Owned variant of [`LayoutMarginParseError`].
302
#[cfg(feature = "parser")]
303
#[derive(Debug, Clone, PartialEq, Eq)]
304
#[repr(C, u8)]
305
pub enum LayoutMarginParseErrorOwned {
306
    PixelValueParseError(CssPixelValueParseErrorOwned),
307
    TooManyValues,
308
    TooFewValues,
309
}
310

            
311
#[cfg(feature = "parser")]
312
impl_spacing_parse_error!(
313
    LayoutMarginParseError,
314
    LayoutMarginParseErrorOwned,
315
    "margin"
316
);
317

            
318
/// Result of parsing the CSS `margin` shorthand property (1–4 values).
319
#[cfg(feature = "parser")]
320
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
321
pub struct LayoutMargin {
322
    pub top: PixelValueWithAuto,
323
    pub bottom: PixelValueWithAuto,
324
    pub left: PixelValueWithAuto,
325
    pub right: PixelValueWithAuto,
326
}
327

            
328
#[cfg(feature = "parser")]
329
/// # Errors
330
///
331
/// Returns an error if `input` is not a valid CSS `margin` value.
332
10833
pub fn parse_layout_margin(input: &str) -> Result<LayoutMargin, LayoutMarginParseError<'_>> {
333
    // Margin parsing logic is identical to padding, so we can reuse the padding parser
334
    // and just map the Ok and Err variants to the margin-specific types.
335
10833
    match parse_layout_padding(input) {
336
10770
        Ok(padding) => Ok(LayoutMargin {
337
10770
            top: padding.top,
338
10770
            left: padding.left,
339
10770
            right: padding.right,
340
10770
            bottom: padding.bottom,
341
10770
        }),
342
63
        Err(e) => match e {
343
41
            LayoutPaddingParseError::PixelValueParseError(err) => {
344
41
                Err(LayoutMarginParseError::PixelValueParseError(err))
345
            }
346
7
            LayoutPaddingParseError::TooManyValues => Err(LayoutMarginParseError::TooManyValues),
347
15
            LayoutPaddingParseError::TooFewValues => Err(LayoutMarginParseError::TooFewValues),
348
        },
349
    }
350
10833
}
351

            
352
// -- Longhand Property Parsers --
353

            
354
macro_rules! typed_pixel_value_parser {
355
    (
356
        $fn:ident, $fn_str:expr, $return:ident, $return_str:expr, $import_str:expr, $test_str:expr
357
    ) => {
358
        ///Parses a `
359
        #[doc = $return_str]
360
        ///` attribute from a `&str`
361
        ///
362
        ///# Example
363
        ///
364
        ///```rust
365
        #[doc = $import_str]
366
        #[doc = $test_str]
367
        ///```
368
        /// # Errors
369
        ///
370
        /// Returns an error if `input` is not a valid CSS value for this property.
371
51589
        pub fn $fn(input: &str) -> Result<$return, CssPixelValueParseError<'_>> {
372
51589
            crate::props::basic::parse_pixel_value(input).map(|e| $return { inner: e })
373
51589
        }
374

            
375
        impl crate::props::formatter::FormatAsCssValue for $return {
376
180
            fn format_as_css_value(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
377
180
                self.inner.format_as_css_value(f)
378
180
            }
379
        }
380
    };
381
    ($fn:ident, $return:ident) => {
382
        typed_pixel_value_parser!(
383
            $fn,
384
            stringify!($fn),
385
            $return,
386
            stringify!($return),
387
            concat!(
388
                "# extern crate azul_css;",
389
                "\r\n",
390
                "# use azul_css::props::layout::spacing::",
391
                stringify!($fn),
392
                ";",
393
                "\r\n",
394
                "# use azul_css::props::basic::pixel::PixelValue;\r\n",
395
                "# use azul_css::props::layout::spacing::",
396
                stringify!($return),
397
                ";\r\n"
398
            ),
399
            concat!(
400
                "assert_eq!(",
401
                stringify!($fn),
402
                "(\"5px\"), Ok(",
403
                stringify!($return),
404
                " { inner: PixelValue::px(5.0) }));"
405
            )
406
        );
407
    };
408
}
409

            
410
#[cfg(feature = "parser")]
411
typed_pixel_value_parser!(parse_layout_padding_top, LayoutPaddingTop);
412
#[cfg(feature = "parser")]
413
typed_pixel_value_parser!(parse_layout_padding_right, LayoutPaddingRight);
414
#[cfg(feature = "parser")]
415
typed_pixel_value_parser!(parse_layout_padding_bottom, LayoutPaddingBottom);
416
#[cfg(feature = "parser")]
417
typed_pixel_value_parser!(parse_layout_padding_left, LayoutPaddingLeft);
418
#[cfg(feature = "parser")]
419
typed_pixel_value_parser!(parse_layout_padding_inline_start, LayoutPaddingInlineStart);
420
#[cfg(feature = "parser")]
421
typed_pixel_value_parser!(parse_layout_padding_inline_end, LayoutPaddingInlineEnd);
422

            
423
#[cfg(feature = "parser")]
424
typed_pixel_value_parser!(parse_layout_margin_top, LayoutMarginTop);
425
#[cfg(feature = "parser")]
426
typed_pixel_value_parser!(parse_layout_margin_right, LayoutMarginRight);
427
#[cfg(feature = "parser")]
428
typed_pixel_value_parser!(parse_layout_margin_bottom, LayoutMarginBottom);
429
#[cfg(feature = "parser")]
430
typed_pixel_value_parser!(parse_layout_margin_left, LayoutMarginLeft);
431

            
432
#[cfg(feature = "parser")]
433
typed_pixel_value_parser!(parse_layout_column_gap, LayoutColumnGap);
434
#[cfg(feature = "parser")]
435
typed_pixel_value_parser!(parse_layout_row_gap, LayoutRowGap);
436

            
437
#[cfg(all(test, feature = "parser"))]
438
mod tests {
439
    use super::*;
440
    use crate::props::basic::pixel::{PixelValue, PixelValueWithAuto};
441

            
442
    #[test]
443
1
    fn test_parse_layout_padding_shorthand() {
444
        // 1 value
445
1
        let result = parse_layout_padding("10px").unwrap();
446
1
        assert_eq!(result.top, PixelValueWithAuto::Exact(PixelValue::px(10.0)));
447
1
        assert_eq!(
448
            result.right,
449
1
            PixelValueWithAuto::Exact(PixelValue::px(10.0))
450
        );
451
1
        assert_eq!(
452
            result.bottom,
453
1
            PixelValueWithAuto::Exact(PixelValue::px(10.0))
454
        );
455
1
        assert_eq!(result.left, PixelValueWithAuto::Exact(PixelValue::px(10.0)));
456

            
457
        // 2 values
458
1
        let result = parse_layout_padding("5% 2em").unwrap();
459
1
        assert_eq!(
460
            result.top,
461
1
            PixelValueWithAuto::Exact(PixelValue::percent(5.0))
462
        );
463
1
        assert_eq!(result.right, PixelValueWithAuto::Exact(PixelValue::em(2.0)));
464
1
        assert_eq!(
465
            result.bottom,
466
1
            PixelValueWithAuto::Exact(PixelValue::percent(5.0))
467
        );
468
1
        assert_eq!(result.left, PixelValueWithAuto::Exact(PixelValue::em(2.0)));
469

            
470
        // 3 values
471
1
        let result = parse_layout_padding("1px 2px 3px").unwrap();
472
1
        assert_eq!(result.top, PixelValueWithAuto::Exact(PixelValue::px(1.0)));
473
1
        assert_eq!(result.right, PixelValueWithAuto::Exact(PixelValue::px(2.0)));
474
1
        assert_eq!(
475
            result.bottom,
476
1
            PixelValueWithAuto::Exact(PixelValue::px(3.0))
477
        );
478
1
        assert_eq!(result.left, PixelValueWithAuto::Exact(PixelValue::px(2.0)));
479

            
480
        // 4 values
481
1
        let result = parse_layout_padding("1px 2px 3px 4px").unwrap();
482
1
        assert_eq!(result.top, PixelValueWithAuto::Exact(PixelValue::px(1.0)));
483
1
        assert_eq!(result.right, PixelValueWithAuto::Exact(PixelValue::px(2.0)));
484
1
        assert_eq!(
485
            result.bottom,
486
1
            PixelValueWithAuto::Exact(PixelValue::px(3.0))
487
        );
488
1
        assert_eq!(result.left, PixelValueWithAuto::Exact(PixelValue::px(4.0)));
489

            
490
        // Whitespace
491
1
        let result = parse_layout_padding("  1px   2px  ").unwrap();
492
1
        assert_eq!(result.top, PixelValueWithAuto::Exact(PixelValue::px(1.0)));
493
1
        assert_eq!(result.right, PixelValueWithAuto::Exact(PixelValue::px(2.0)));
494
1
    }
495

            
496
    #[test]
497
1
    fn test_parse_layout_padding_errors() {
498
1
        assert!(matches!(
499
1
            parse_layout_padding("").err().unwrap(),
500
            LayoutPaddingParseError::TooFewValues
501
        ));
502
1
        assert!(matches!(
503
1
            parse_layout_padding("1px 2px 3px 4px 5px").err().unwrap(),
504
            LayoutPaddingParseError::TooManyValues
505
        ));
506
1
        assert!(matches!(
507
1
            parse_layout_padding("1px oops 3px").err().unwrap(),
508
            LayoutPaddingParseError::PixelValueParseError(_)
509
        ));
510
1
    }
511

            
512
    #[test]
513
1
    fn test_parse_layout_margin_shorthand() {
514
        // 1 value with auto
515
1
        let result = parse_layout_margin("auto").unwrap();
516
1
        assert_eq!(result.top, PixelValueWithAuto::Auto);
517
1
        assert_eq!(result.right, PixelValueWithAuto::Auto);
518
1
        assert_eq!(result.bottom, PixelValueWithAuto::Auto);
519
1
        assert_eq!(result.left, PixelValueWithAuto::Auto);
520

            
521
        // 2 values
522
1
        let result = parse_layout_margin("10px auto").unwrap();
523
1
        assert_eq!(result.top, PixelValueWithAuto::Exact(PixelValue::px(10.0)));
524
1
        assert_eq!(result.right, PixelValueWithAuto::Auto);
525
1
        assert_eq!(
526
            result.bottom,
527
1
            PixelValueWithAuto::Exact(PixelValue::px(10.0))
528
        );
529
1
        assert_eq!(result.left, PixelValueWithAuto::Auto);
530
1
    }
531

            
532
    #[test]
533
1
    fn test_parse_layout_margin_errors() {
534
1
        assert!(matches!(
535
1
            parse_layout_margin("").err().unwrap(),
536
            LayoutMarginParseError::TooFewValues
537
        ));
538
1
        assert!(matches!(
539
1
            parse_layout_margin("1px 2px 3px 4px 5px").err().unwrap(),
540
            LayoutMarginParseError::TooManyValues
541
        ));
542
1
        assert!(matches!(
543
1
            parse_layout_margin("1px invalid").err().unwrap(),
544
            LayoutMarginParseError::PixelValueParseError(_)
545
        ));
546
1
    }
547

            
548
    #[test]
549
1
    fn test_parse_longhand_spacing() {
550
1
        assert_eq!(
551
1
            parse_layout_padding_left("2em").unwrap(),
552
1
            LayoutPaddingLeft {
553
1
                inner: PixelValue::em(2.0)
554
1
            }
555
        );
556
1
        assert!(parse_layout_margin_top("auto").is_err()); // Longhands don't parse "auto"
557
1
        assert_eq!(
558
1
            parse_layout_column_gap("20px").unwrap(),
559
1
            LayoutColumnGap {
560
1
                inner: PixelValue::px(20.0)
561
1
            }
562
        );
563
1
    }
564
}
565

            
566
#[cfg(all(test, feature = "parser"))]
567
mod autotest_generated {
568
    #![allow(clippy::float_cmp)] // fixed-point quantisation makes exact f32 compares meaningful
569
                                 // here
570

            
571
    use alloc::format;
572
    use core::{
573
        fmt,
574
        hash::{Hash, Hasher},
575
    };
576
    use std::collections::hash_map::DefaultHasher;
577

            
578
    #[allow(clippy::wildcard_imports)]
579
    use super::*;
580
    use crate::props::{
581
        basic::{
582
            length::SizeMetric,
583
            pixel::{CssPixelValueParseError, PixelValue, PixelValueWithAuto},
584
        },
585
        formatter::FormatAsCssValue,
586
    };
587

            
588
    /// Renders a value through `FormatAsCssValue` so it can be compared against the
589
    /// `String`-returning `PrintAsCssValue` path.
590
    #[allow(missing_debug_implementations)]
591
    struct AsCss<'a, T: FormatAsCssValue>(&'a T);
592

            
593
    impl<T: FormatAsCssValue> fmt::Display for AsCss<'_, T> {
594
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
595
            self.0.format_as_css_value(f)
596
        }
597
    }
598

            
599
    fn hash_of<T: Hash>(value: &T) -> u64 {
600
        let mut hasher = DefaultHasher::new();
601
        value.hash(&mut hasher);
602
        hasher.finish()
603
    }
604

            
605
    fn exact_px(value: f32) -> PixelValueWithAuto {
606
        PixelValueWithAuto::Exact(PixelValue::px(value))
607
    }
608

            
609
    /// `parse(print(parse(s))) == parse(s)` — the encode/decode fixed point. Also
610
    /// checks the two formatting traits agree, since they are separate impls.
611
    macro_rules! assert_css_roundtrip {
612
        ($parse:ident, $input:expr) => {{
613
            let parsed = $parse($input).expect("positive control must parse");
614
            let printed = parsed.print_as_css_value();
615
            let reparsed = $parse(printed.as_str()).expect("printed value must re-parse");
616
            assert_eq!(
617
                parsed,
618
                reparsed,
619
                "{} did not survive {:?} -> {:?}",
620
                stringify!($parse),
621
                $input,
622
                printed
623
            );
624
            assert_eq!(
625
                printed,
626
                format!("{}", AsCss(&parsed)),
627
                "FormatAsCssValue and PrintAsCssValue disagree for {:?}",
628
                $input
629
            );
630
        }};
631
    }
632

            
633
    macro_rules! assert_all_longhands_err {
634
        ($input:expr) => {{
635
            assert!(
636
                parse_layout_padding_top($input).is_err(),
637
                "padding-top accepted {:?}",
638
                $input
639
            );
640
            assert!(
641
                parse_layout_padding_right($input).is_err(),
642
                "padding-right accepted {:?}",
643
                $input
644
            );
645
            assert!(
646
                parse_layout_padding_bottom($input).is_err(),
647
                "padding-bottom accepted {:?}",
648
                $input
649
            );
650
            assert!(
651
                parse_layout_padding_left($input).is_err(),
652
                "padding-left accepted {:?}",
653
                $input
654
            );
655
            assert!(
656
                parse_layout_padding_inline_start($input).is_err(),
657
                "padding-inline-start accepted {:?}",
658
                $input
659
            );
660
            assert!(
661
                parse_layout_padding_inline_end($input).is_err(),
662
                "padding-inline-end accepted {:?}",
663
                $input
664
            );
665
            assert!(
666
                parse_layout_margin_top($input).is_err(),
667
                "margin-top accepted {:?}",
668
                $input
669
            );
670
            assert!(
671
                parse_layout_margin_right($input).is_err(),
672
                "margin-right accepted {:?}",
673
                $input
674
            );
675
            assert!(
676
                parse_layout_margin_bottom($input).is_err(),
677
                "margin-bottom accepted {:?}",
678
                $input
679
            );
680
            assert!(
681
                parse_layout_margin_left($input).is_err(),
682
                "margin-left accepted {:?}",
683
                $input
684
            );
685
            assert!(
686
                parse_layout_column_gap($input).is_err(),
687
                "column-gap accepted {:?}",
688
                $input
689
            );
690
            assert!(
691
                parse_layout_row_gap($input).is_err(),
692
                "row-gap accepted {:?}",
693
                $input
694
            );
695
        }};
696
    }
697

            
698
    // --- parsers: positive controls -----------------------------------------
699

            
700
    #[test]
701
    fn minimal_valid_inputs_parse_to_the_documented_values() {
702
        assert_eq!(
703
            parse_layout_padding("0").unwrap(),
704
            LayoutPadding {
705
                top: exact_px(0.0),
706
                right: exact_px(0.0),
707
                bottom: exact_px(0.0),
708
                left: exact_px(0.0),
709
            }
710
        );
711
        assert_eq!(
712
            parse_layout_margin("1px").unwrap(),
713
            LayoutMargin {
714
                top: exact_px(1.0),
715
                right: exact_px(1.0),
716
                bottom: exact_px(1.0),
717
                left: exact_px(1.0),
718
            }
719
        );
720
    }
721

            
722
    #[test]
723
    fn shorthand_expansion_follows_the_css_1_to_4_value_rules() {
724
        let one = parse_layout_padding("7px").unwrap();
725
        assert_eq!(one.top, exact_px(7.0));
726
        assert_eq!(one.right, one.top);
727
        assert_eq!(one.bottom, one.top);
728
        assert_eq!(one.left, one.top);
729

            
730
        let two = parse_layout_padding("1px 2px").unwrap();
731
        assert_eq!((two.top, two.bottom), (exact_px(1.0), exact_px(1.0)));
732
        assert_eq!((two.right, two.left), (exact_px(2.0), exact_px(2.0)));
733

            
734
        // The third value is the *bottom*, and left mirrors right. Getting this
735
        // expansion backwards is the classic shorthand bug, so pin all four sides.
736
        let three = parse_layout_padding("1px 2px 3px").unwrap();
737
        assert_eq!(three.top, exact_px(1.0));
738
        assert_eq!(three.right, exact_px(2.0));
739
        assert_eq!(three.bottom, exact_px(3.0));
740
        assert_eq!(three.left, exact_px(2.0));
741

            
742
        // Four values run clockwise: top, right, bottom, left.
743
        let four = parse_layout_padding("1px 2px 3px 4px").unwrap();
744
        assert_eq!(four.top, exact_px(1.0));
745
        assert_eq!(four.right, exact_px(2.0));
746
        assert_eq!(four.bottom, exact_px(3.0));
747
        assert_eq!(four.left, exact_px(4.0));
748
    }
749

            
750
    #[test]
751
    fn margin_is_a_faithful_mirror_of_padding() {
752
        for input in [
753
            "0",
754
            "10px",
755
            "5% 2em",
756
            "1px 2px 3px",
757
            "1px 2px 3px 4px",
758
            "auto",
759
            "10px auto",
760
            "auto 0 inherit 2em",
761
        ] {
762
            let p = parse_layout_padding(input).unwrap();
763
            let m = parse_layout_margin(input).unwrap();
764
            assert_eq!(m.top, p.top, "top differs for {input:?}");
765
            assert_eq!(m.right, p.right, "right differs for {input:?}");
766
            assert_eq!(m.bottom, p.bottom, "bottom differs for {input:?}");
767
            assert_eq!(m.left, p.left, "left differs for {input:?}");
768
        }
769

            
770
        // ...and every error variant maps 1:1 through the delegation.
771
        assert!(matches!(
772
            parse_layout_margin(""),
773
            Err(LayoutMarginParseError::TooFewValues)
774
        ));
775
        assert!(matches!(
776
            parse_layout_margin("1 2 3 4 5"),
777
            Err(LayoutMarginParseError::TooManyValues)
778
        ));
779
        assert!(matches!(
780
            parse_layout_margin("nope"),
781
            Err(LayoutMarginParseError::PixelValueParseError(_))
782
        ));
783
    }
784

            
785
    // --- parsers: malformed / boundary / unicode ----------------------------
786

            
787
    #[test]
788
    fn empty_and_whitespace_only_input_is_too_few_values() {
789
        for input in [
790
            "", " ", "   ", "\t", "\n", "\r\n", "\x0b", "\x0c", " \t\r\n ",
791
        ] {
792
            assert!(
793
                matches!(
794
                    parse_layout_padding(input),
795
                    Err(LayoutPaddingParseError::TooFewValues)
796
                ),
797
                "padding {input:?}"
798
            );
799
            assert!(
800
                matches!(
801
                    parse_layout_margin(input),
802
                    Err(LayoutMarginParseError::TooFewValues)
803
                ),
804
                "margin {input:?}"
805
            );
806
        }
807
    }
808

            
809
    #[test]
810
    fn garbage_is_rejected_without_panicking() {
811
        for input in [
812
            "oops",
813
            "px",
814
            "%",
815
            "-",
816
            "+",
817
            ".",
818
            "e",
819
            "--",
820
            "10px;",
821
            "10px,20px",
822
            "10px, 20px",
823
            "10px!important",
824
            "calc(1px + 2px)",
825
            "1px/2px",
826
            "#10px",
827
            "0x10px",
828
            "1_000px",
829
            "auto auto auto auto auto",
830
        ] {
831
            assert!(
832
                parse_layout_padding(input).is_err(),
833
                "padding accepted {input:?}"
834
            );
835
            assert!(
836
                parse_layout_margin(input).is_err(),
837
                "margin accepted {input:?}"
838
            );
839
        }
840
    }
841

            
842
    #[test]
843
    fn shorthand_rejects_a_unit_split_from_its_number() {
844
        // `parse_pixel_value` trims *inside* a token, so "10 px" is a valid longhand.
845
        // The shorthand splits on whitespace first, so the same text is two values
846
        // and the bare unit is what fails -- a divergence worth pinning.
847
        let err = parse_layout_padding("10 px").unwrap_err();
848
        assert!(
849
            matches!(
850
                err,
851
                LayoutPaddingParseError::PixelValueParseError(
852
                    CssPixelValueParseError::NoValueGiven("px", SizeMetric::Px)
853
                )
854
            ),
855
            "expected NoValueGiven(\"px\", Px), got {err:?}"
856
        );
857
        assert_eq!(
858
            parse_layout_padding_top("10 px").unwrap(),
859
            LayoutPaddingTop::px(10.0)
860
        );
861
    }
862

            
863
    #[test]
864
    fn value_errors_are_reported_before_arity_errors() {
865
        // Every token is parsed before the count is checked, so a malformed value in
866
        // an over-long list surfaces as a value error, not TooManyValues.
867
        assert!(matches!(
868
            parse_layout_padding("1px 2px 3px 4px 5px"),
869
            Err(LayoutPaddingParseError::TooManyValues)
870
        ));
871
        assert!(matches!(
872
            parse_layout_padding("1px 2px 3px 4px bogus"),
873
            Err(LayoutPaddingParseError::PixelValueParseError(_))
874
        ));
875
        assert!(matches!(
876
            parse_layout_margin("1px 2px 3px 4px bogus"),
877
            Err(LayoutMarginParseError::PixelValueParseError(_))
878
        ));
879
    }
880

            
881
    #[test]
882
    fn boundary_numbers_saturate_instead_of_overflowing() {
883
        // Signed zero collapses onto one encoding.
884
        let zero = parse_layout_padding("0").unwrap();
885
        assert_eq!(parse_layout_padding("-0").unwrap(), zero);
886
        assert_eq!(zero.top, PixelValueWithAuto::Exact(PixelValue::zero()));
887

            
888
        // Overflowing literals become +/-inf in `f32::from_str` and must then saturate
889
        // to the isize bounds: nothing infinite may escape into layout arithmetic.
890
        for input in [
891
            "1e39px",
892
            "-1e39px",
893
            "inf",
894
            "-inf",
895
            "infinity",
896
            "9223372036854775807",
897
            "-9223372036854775808",
898
            "340282350000000000000000000000000000000px",
899
        ] {
900
            let parsed =
901
                parse_layout_padding(input).unwrap_or_else(|e| panic!("{input:?} failed: {e}"));
902
            let PixelValueWithAuto::Exact(value) = parsed.top else {
903
                panic!("{input:?} did not parse to an exact length");
904
            };
905
            let raw = value.number.get();
906
            assert!(
907
                raw.is_finite(),
908
                "{input:?} produced a non-finite length: {raw}"
909
            );
910
        }
911

            
912
        // SPEC DIVERGENCE (pinned, not endorsed): CSS has no `NaN` value, but Rust's
913
        // `f32::from_str` accepts it, so `padding: NaN` parses. The saturating cast at
914
        // least keeps it safe -- it quantises to exactly 0px rather than poisoning
915
        // layout with a NaN.
916
        let nan = parse_layout_padding("NaN").unwrap();
917
        assert_eq!(nan.top, PixelValueWithAuto::Exact(PixelValue::zero()));
918
        assert_eq!(nan.right, nan.top);
919
        assert_eq!(nan.bottom, nan.top);
920
        assert_eq!(nan.left, nan.top);
921
    }
922

            
923
    #[test]
924
    fn sub_milli_unit_values_truncate_toward_zero() {
925
        // Lengths are stored as thousandths in an isize, and the cast truncates.
926
        assert_eq!(
927
            parse_layout_padding_top("0.0004px").unwrap(),
928
            LayoutPaddingTop::zero()
929
        );
930
        assert_eq!(
931
            parse_layout_padding_top("-0.0009px").unwrap(),
932
            LayoutPaddingTop::zero()
933
        );
934
        assert_eq!(
935
            parse_layout_padding_top("1e-40px").unwrap(),
936
            LayoutPaddingTop::zero()
937
        );
938
        // Truncation, not rounding: 1.9999px stays below 2px.
939
        assert_eq!(
940
            parse_layout_padding_top("1.9999px")
941
                .unwrap()
942
                .inner
943
                .number
944
                .get(),
945
            1.999
946
        );
947
    }
948

            
949
    #[test]
950
    fn unicode_junk_is_rejected_without_panicking() {
951
        for input in [
952
            "\u{1F600}",                        // emoji alone
953
            "10px\u{1F600}",                    // emoji glued to a valid value
954
            "\u{FF11}\u{FF10}\u{FF50}\u{FF58}", // fullwidth "10px"
955
            "10px\u{0301}",                     // combining acute on the unit
956
            "10\u{200b}px",                     // zero-width space inside the number
957
            "\u{661}\u{660}px",                 // arabic-indic digits
958
            "\u{202E}10px",                     // RTL-override prefix
959
        ] {
960
            assert!(
961
                parse_layout_padding(input).is_err(),
962
                "padding accepted {input:?}"
963
            );
964
            assert!(
965
                parse_layout_margin(input).is_err(),
966
                "margin accepted {input:?}"
967
            );
968
        }
969
    }
970

            
971
    #[test]
972
    fn unicode_whitespace_separates_values_even_though_css_only_splits_on_ascii() {
973
        // `split_whitespace()` follows the Unicode White_Space property, so U+00A0
974
        // (NO-BREAK SPACE) and U+2003 (EM SPACE) split a declaration into two values,
975
        // where CSS would treat the whole thing as one malformed token. Stated as an
976
        // invariant against `split_whitespace()` itself, so the test pins the parser's
977
        // contract instead of restating a Unicode table.
978
        for sep in [" ", "\u{a0}", "\u{2003}"] {
979
            let input = format!("10px{sep}20px");
980
            let tokens = input.split_whitespace().count();
981
            let parsed = parse_layout_padding(&input);
982
            assert_eq!(
983
                parsed.is_ok(),
984
                tokens == 2,
985
                "{input:?} split into {tokens} token(s)"
986
            );
987
            if let Ok(p) = parsed {
988
                assert_eq!(p.top, exact_px(10.0));
989
                assert_eq!(p.right, exact_px(20.0));
990
                assert_eq!(p.bottom, p.top);
991
                assert_eq!(p.left, p.right);
992
            }
993
        }
994
    }
995

            
996
    #[test]
997
    fn extremely_long_inputs_terminate_without_panicking() {
998
        // 200_000 well-formed values: an ordinary arity error, not a hang.
999
        let many = "1px ".repeat(200_000);
        assert!(matches!(
            parse_layout_padding(&many),
            Err(LayoutPaddingParseError::TooManyValues)
        ));
        assert!(matches!(
            parse_layout_margin(&many),
            Err(LayoutMarginParseError::TooManyValues)
        ));
        // A single 100_000-digit number overflows f32 to +inf, then saturates.
        let huge = format!("{}px", "9".repeat(100_000));
        let parsed = parse_layout_padding(&huge).unwrap();
        let PixelValueWithAuto::Exact(value) = parsed.top else {
            panic!("a huge number did not parse to an exact length");
        };
        assert!(value.number.get().is_finite());
        assert!(value.number.get() > 0.0);
        // A 1_000_000-char garbage token is rejected, not scanned forever.
        let junk = "z".repeat(1_000_000);
        assert!(parse_layout_padding(&junk).is_err());
        assert!(parse_layout_margin(&junk).is_err());
    }
    #[test]
    fn deeply_nested_brackets_do_not_stack_overflow() {
        // The grammar is flat, so nesting must be rejected by the float parser rather
        // than recursed into.
        let nested = format!("{}1px{}", "(".repeat(10_000), ")".repeat(10_000));
        assert!(
            matches!(
                parse_layout_padding(&nested),
                Err(LayoutPaddingParseError::PixelValueParseError(
                    CssPixelValueParseError::InvalidPixelValue(_)
                ))
            ),
            "deeply nested input was not rejected as an invalid pixel value"
        );
        let spread = format!("{n} {n} {n} {n}", n = "(".repeat(1_000));
        assert!(parse_layout_padding(&spread).is_err());
        assert!(parse_layout_margin(&spread).is_err());
    }
    #[test]
    fn shorthands_accept_css_wide_keywords_per_side() {
        // SPEC DIVERGENCE (pinned, not endorsed): the shorthands run every side through
        // `parse_pixel_value_with_auto`, so `padding: auto` parses (CSS has no such
        // value) and `initial`/`inherit` are accepted per side rather than only as a
        // whole declaration. Pinned so that tightening this is a visible change.
        assert_eq!(
            parse_layout_padding("auto").unwrap().top,
            PixelValueWithAuto::Auto
        );
        assert_eq!(
            parse_layout_padding("none").unwrap().top,
            PixelValueWithAuto::None
        );
        let mixed = parse_layout_padding("initial 10px inherit auto").unwrap();
        assert_eq!(mixed.top, PixelValueWithAuto::Initial);
        assert_eq!(mixed.right, exact_px(10.0));
        assert_eq!(mixed.bottom, PixelValueWithAuto::Inherit);
        assert_eq!(mixed.left, PixelValueWithAuto::Auto);
    }
    // --- errors -------------------------------------------------------------
    #[test]
    fn arity_error_messages_name_the_right_property() {
        // `parse_layout_margin` delegates to the padding parser and re-wraps the error;
        // a mis-mapped variant would be invisible to callers but wrong for users.
        let pad_many = format!("{}", LayoutPaddingParseError::TooManyValues);
        let pad_few = format!("{}", LayoutPaddingParseError::TooFewValues);
        assert!(
            pad_many.contains("padding") && pad_many.contains("at most 4"),
            "{pad_many}"
        );
        assert!(pad_few.contains("padding"), "{pad_few}");
        let margin_many = format!("{}", LayoutMarginParseError::TooManyValues);
        let margin_few = format!("{}", LayoutMarginParseError::TooFewValues);
        assert!(
            margin_many.contains("margin") && !margin_many.contains("padding"),
            "{margin_many}"
        );
        assert!(
            margin_few.contains("margin") && !margin_few.contains("padding"),
            "{margin_few}"
        );
        // The live parser surfaces those same messages.
        assert_eq!(
            format!("{}", parse_layout_margin("1 2 3 4 5").unwrap_err()),
            margin_many
        );
        assert_eq!(
            format!("{}", parse_layout_padding("").unwrap_err()),
            pad_few
        );
    }
    #[test]
    fn owned_and_shared_error_forms_round_trip() {
        assert_eq!(
            LayoutPaddingParseError::TooManyValues.to_contained(),
            LayoutPaddingParseErrorOwned::TooManyValues
        );
        assert_eq!(
            LayoutPaddingParseErrorOwned::TooFewValues.to_shared(),
            LayoutPaddingParseError::TooFewValues
        );
        assert_eq!(
            LayoutMarginParseError::TooFewValues.to_contained(),
            LayoutMarginParseErrorOwned::TooFewValues
        );
        assert_eq!(
            LayoutMarginParseErrorOwned::TooManyValues.to_shared(),
            LayoutMarginParseError::TooManyValues
        );
        // The borrowed payload must survive the owned round-trip as the same variant,
        // even though it holds a `&str` into the (now dropped) input.
        let owned = parse_layout_padding("1px oops").unwrap_err().to_contained();
        assert!(matches!(
            &owned,
            LayoutPaddingParseErrorOwned::PixelValueParseError(_)
        ));
        assert!(matches!(
            owned.to_shared(),
            LayoutPaddingParseError::PixelValueParseError(_)
        ));
        let owned_margin = parse_layout_margin("1px oops").unwrap_err().to_contained();
        assert!(matches!(
            owned_margin.to_shared(),
            LayoutMarginParseError::PixelValueParseError(_)
        ));
    }
    // --- longhands: parse + round-trip --------------------------------------
    #[test]
    fn longhand_parsers_reject_keywords_and_empty_input() {
        // The longhands go through `parse_pixel_value`, which -- unlike the shorthands
        // -- has no keyword table.
        for input in [
            "",
            "   ",
            "auto",
            "none",
            "initial",
            "inherit",
            "oops",
            "10px 20px",
        ] {
            assert_all_longhands_err!(input);
        }
    }
    #[test]
    fn every_longhand_spacing_parser_accepts_a_minimal_value() {
        assert_eq!(
            parse_layout_padding_top("0").unwrap(),
            LayoutPaddingTop::px(0.0)
        );
        assert_eq!(
            parse_layout_padding_right("1px").unwrap(),
            LayoutPaddingRight::px(1.0)
        );
        assert_eq!(
            parse_layout_padding_bottom("2pt").unwrap(),
            LayoutPaddingBottom::pt(2.0)
        );
        assert_eq!(
            parse_layout_padding_left("2em").unwrap(),
            LayoutPaddingLeft::em(2.0)
        );
        assert_eq!(
            parse_layout_padding_inline_start("3px").unwrap(),
            LayoutPaddingInlineStart::px(3.0)
        );
        assert_eq!(
            parse_layout_padding_inline_end("4px").unwrap(),
            LayoutPaddingInlineEnd::px(4.0)
        );
        assert_eq!(
            parse_layout_margin_top("-5px").unwrap(),
            LayoutMarginTop::px(-5.0)
        );
        assert_eq!(
            parse_layout_margin_right("6%").unwrap(),
            LayoutMarginRight::percent(6.0)
        );
        assert_eq!(
            parse_layout_margin_bottom("7px").unwrap(),
            LayoutMarginBottom::px(7.0)
        );
        assert_eq!(
            parse_layout_margin_left("8px").unwrap(),
            LayoutMarginLeft::px(8.0)
        );
        assert_eq!(
            parse_layout_column_gap("20px").unwrap(),
            LayoutColumnGap::px(20.0)
        );
        assert_eq!(
            parse_layout_row_gap("1.5em").unwrap(),
            LayoutRowGap::em(1.5)
        );
    }
    #[test]
    fn every_longhand_spacing_parser_round_trips_through_its_printed_form() {
        // Only exactly-representable values here: the point is the encode/decode fixed
        // point, not the quantisation (covered by `sub_milli_unit_values_*`).
        for input in [
            "0", "1px", "10.5px", "1.5em", "2rem", "-20pt", "50%", "0.125px", "3.25in", "12.75mm",
            "2.54cm", "0.5vmin", "4vmax", "8vw", "100vh",
        ] {
            assert_css_roundtrip!(parse_layout_padding_top, input);
            assert_css_roundtrip!(parse_layout_padding_right, input);
            assert_css_roundtrip!(parse_layout_padding_bottom, input);
            assert_css_roundtrip!(parse_layout_padding_left, input);
            assert_css_roundtrip!(parse_layout_padding_inline_start, input);
            assert_css_roundtrip!(parse_layout_padding_inline_end, input);
            assert_css_roundtrip!(parse_layout_margin_top, input);
            assert_css_roundtrip!(parse_layout_margin_right, input);
            assert_css_roundtrip!(parse_layout_margin_bottom, input);
            assert_css_roundtrip!(parse_layout_margin_left, input);
            assert_css_roundtrip!(parse_layout_column_gap, input);
            assert_css_roundtrip!(parse_layout_row_gap, input);
        }
    }
    #[test]
    fn printed_css_matches_the_source_text_for_representable_values() {
        assert_eq!(
            parse_layout_padding_top("10px")
                .unwrap()
                .print_as_css_value(),
            "10px"
        );
        assert_eq!(
            parse_layout_column_gap("50%").unwrap().print_as_css_value(),
            "50%"
        );
        assert_eq!(
            parse_layout_margin_left("-2.5em")
                .unwrap()
                .print_as_css_value(),
            "-2.5em"
        );
        assert_eq!(LayoutRowGap::zero().print_as_css_value(), "0px");
        // A unitless number is a px length, and prints back *with* the unit.
        assert_eq!(
            parse_layout_padding_bottom("3")
                .unwrap()
                .print_as_css_value(),
            "3px"
        );
    }
    // --- constructors, ordering, hashing, interpolation ----------------------
    #[test]
    fn const_and_runtime_constructors_agree() {
        assert_eq!(LayoutPaddingLeft::const_px(5), LayoutPaddingLeft::px(5.0));
        assert_eq!(LayoutPaddingLeft::const_em(2), LayoutPaddingLeft::em(2.0));
        assert_eq!(LayoutPaddingLeft::const_pt(-3), LayoutPaddingLeft::pt(-3.0));
        assert_eq!(
            LayoutPaddingLeft::const_percent(50),
            LayoutPaddingLeft::percent(50.0)
        );
        assert_eq!(
            LayoutColumnGap::const_from_metric(SizeMetric::Vh, 7),
            LayoutColumnGap::from_metric(SizeMetric::Vh, 7.0)
        );
        assert_eq!(
            LayoutColumnGap::const_in(1),
            LayoutColumnGap::from_metric(SizeMetric::In, 1.0)
        );
        assert_eq!(
            LayoutColumnGap::const_cm(2),
            LayoutColumnGap::from_metric(SizeMetric::Cm, 2.0)
        );
        assert_eq!(
            LayoutColumnGap::const_mm(3),
            LayoutColumnGap::from_metric(SizeMetric::Mm, 3.0)
        );
        // `PixelValueTaker` is what the shorthand macros build these types through.
        assert_eq!(
            LayoutRowGap::from_pixel_value(PixelValue::em(2.0)).inner,
            PixelValue::em(2.0)
        );
        assert_eq!(LayoutPaddingBottom::zero(), LayoutPaddingBottom::default());
        assert_eq!(
            LayoutPaddingBottom::default().inner.metric,
            SizeMetric::Px,
            "the default spacing metric is px"
        );
    }
    #[test]
    fn ordering_is_metric_major_not_physical_length() {
        // `Ord` is derived over (metric, number), so 1000px sorts *below* 0pt. Anything
        // ranking spacing by real size has to resolve to px first -- this is a trap, and
        // the test exists to state it.
        assert!(LayoutPaddingTop::px(1000.0) < LayoutPaddingTop::pt(0.0));
        assert!(LayoutPaddingTop::pt(0.0) < LayoutPaddingTop::em(0.0));
        // Within one metric the ordering is numeric, as expected.
        assert!(LayoutPaddingTop::px(1.0) < LayoutPaddingTop::px(2.0));
        assert!(LayoutMarginLeft::const_px(-5) < LayoutMarginLeft::zero());
    }
    #[test]
    fn equal_values_hash_equal_across_signed_zero_and_quantisation() {
        let pos = LayoutMarginTop::px(0.0);
        let neg = LayoutMarginTop::px(-0.0);
        assert_eq!(pos, neg, "signed zero must have one canonical encoding");
        assert_eq!(hash_of(&pos), hash_of(&neg));
        assert_eq!(pos, LayoutMarginTop::zero());
        // Two values that quantise to the same thousandth are Eq, so they must hash
        // alike -- otherwise they would behave inconsistently as HashMap keys.
        let a = LayoutMarginTop::px(1.0001);
        let b = LayoutMarginTop::px(1.0009);
        assert_eq!(a, b);
        assert_eq!(hash_of(&a), hash_of(&b));
        // Same number, different metric: not equal.
        assert_ne!(LayoutMarginTop::px(1.0), LayoutMarginTop::em(1.0));
    }
    #[test]
    fn debug_renders_the_value_as_css() {
        assert_eq!(format!("{:?}", LayoutPaddingTop::px(10.0)), "10px");
        assert_eq!(format!("{:?}", LayoutColumnGap::percent(50.0)), "50%");
        assert_eq!(format!("{:?}", LayoutRowGap::zero()), "0px");
    }
    #[test]
    fn interpolate_hits_its_endpoints_and_survives_nan_and_huge_t() {
        let a = LayoutRowGap::px(0.0);
        let b = LayoutRowGap::px(10.0);
        assert_eq!(a.interpolate(&b, 0.0), a);
        assert_eq!(a.interpolate(&b, 1.0), b);
        assert_eq!(a.interpolate(&b, 0.5), LayoutRowGap::px(5.0));
        // A NaN `t` (a degenerate zero-length animation, say) must not leak a NaN length
        // into layout: the saturating cast maps it to 0.
        let nan = a.interpolate(&b, f32::NAN);
        assert_eq!(nan.inner.metric, SizeMetric::Px);
        assert_eq!(nan.inner.number.get(), 0.0);
        // Out-of-range `t` saturates rather than wrapping the fixed-point encoding.
        for t in [1e30_f32, -1e30_f32, f32::INFINITY, f32::NEG_INFINITY] {
            let out = a.interpolate(&b, t);
            assert!(
                out.inner.number.get().is_finite(),
                "t = {t} produced a non-finite length"
            );
        }
        // Mismatched metrics fall back to px instead of silently keeping the left metric.
        let mixed = LayoutRowGap::px(0.0).interpolate(&LayoutRowGap::em(1.0), 1.0);
        assert_eq!(mixed.inner.metric, SizeMetric::Px);
        assert!(mixed.inner.number.get().is_finite());
    }
}