1
//! CSS properties for visual effects (opacity, blending, cursor), box sizing
2
//! (object-fit, object-position, aspect-ratio), and text orientation.
3

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

            
7
#[cfg(feature = "parser")]
8
use crate::props::basic::{
9
    error::{InvalidValueErr, InvalidValueErrOwned},
10
    length::parse_percentage_value,
11
};
12
use crate::props::{
13
    basic::length::{PercentageParseError, PercentageValue},
14
    formatter::PrintAsCssValue,
15
};
16

            
17
// -- Opacity --
18

            
19
/// Represents an `opacity` attribute, a value from 0.0 to 1.0.
20
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
21
#[repr(C)]
22
pub struct StyleOpacity {
23
    pub inner: PercentageValue,
24
}
25

            
26
impl Default for StyleOpacity {
27
1
    fn default() -> Self {
28
1
        Self {
29
1
            inner: PercentageValue::const_new(100),
30
1
        }
31
1
    }
32
}
33

            
34
impl PrintAsCssValue for StyleOpacity {
35
7
    fn print_as_css_value(&self) -> String {
36
7
        format!("{}", self.inner.normalized())
37
7
    }
38
}
39

            
40
#[cfg(feature = "parser")]
41
impl_percentage_value!(StyleOpacity);
42

            
43
// -- Visibility --
44

            
45
/// Represents a `visibility` attribute, controlling element visibility.
46
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
47
#[repr(C)]
48
#[derive(Default)]
49
pub enum StyleVisibility {
50
    #[default]
51
    Visible,
52
    Hidden,
53
    Collapse,
54
}
55

            
56
impl PrintAsCssValue for StyleVisibility {
57
3
    fn print_as_css_value(&self) -> String {
58
3
        String::from(match self {
59
1
            Self::Visible => "visible",
60
1
            Self::Hidden => "hidden",
61
1
            Self::Collapse => "collapse",
62
        })
63
3
    }
64
}
65

            
66
// -- Mix Blend Mode --
67

            
68
/// Represents a `mix-blend-mode` attribute, which determines how an element's
69
/// content should blend with the content of the element's parent.
70
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
71
#[repr(C)]
72
#[derive(Default)]
73
pub enum StyleMixBlendMode {
74
    #[default]
75
    Normal,
76
    Multiply,
77
    Screen,
78
    Overlay,
79
    Darken,
80
    Lighten,
81
    ColorDodge,
82
    ColorBurn,
83
    HardLight,
84
    SoftLight,
85
    Difference,
86
    Exclusion,
87
    Hue,
88
    Saturation,
89
    Color,
90
    Luminosity,
91
}
92

            
93
impl fmt::Display for StyleMixBlendMode {
94
55
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95
55
        write!(
96
55
            f,
97
55
            "{}",
98
55
            match self {
99
5
                Self::Normal => "normal",
100
6
                Self::Multiply => "multiply",
101
3
                Self::Screen => "screen",
102
3
                Self::Overlay => "overlay",
103
3
                Self::Darken => "darken",
104
3
                Self::Lighten => "lighten",
105
5
                Self::ColorDodge => "color-dodge",
106
3
                Self::ColorBurn => "color-burn",
107
3
                Self::HardLight => "hard-light",
108
3
                Self::SoftLight => "soft-light",
109
3
                Self::Difference => "difference",
110
3
                Self::Exclusion => "exclusion",
111
3
                Self::Hue => "hue",
112
3
                Self::Saturation => "saturation",
113
3
                Self::Color => "color",
114
3
                Self::Luminosity => "luminosity",
115
            }
116
        )
117
55
    }
118
}
119

            
120
impl PrintAsCssValue for StyleMixBlendMode {
121
35
    fn print_as_css_value(&self) -> String {
122
35
        self.to_string()
123
35
    }
124
}
125

            
126
// -- Cursor --
127

            
128
/// Represents a `cursor` attribute, defining the mouse cursor to be displayed
129
/// when pointing over an element.
130
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
131
#[repr(C)]
132
#[derive(Default)]
133
pub enum StyleCursor {
134
    Alias,
135
    AllScroll,
136
    Cell,
137
    ColResize,
138
    ContextMenu,
139
    Copy,
140
    Crosshair,
141
    #[default]
142
    Default,
143
    EResize,
144
    EwResize,
145
    Grab,
146
    Grabbing,
147
    Help,
148
    Move,
149
    NResize,
150
    NsResize,
151
    NeswResize,
152
    NwseResize,
153
    Pointer,
154
    Progress,
155
    RowResize,
156
    SResize,
157
    SeResize,
158
    Text,
159
    Unset,
160
    VerticalText,
161
    WResize,
162
    Wait,
163
    ZoomIn,
164
    ZoomOut,
165
}
166

            
167
impl PrintAsCssValue for StyleCursor {
168
905
    fn print_as_css_value(&self) -> String {
169
905
        String::from(match self {
170
2
            Self::Alias => "alias",
171
2
            Self::AllScroll => "all-scroll",
172
2
            Self::Cell => "cell",
173
2
            Self::ColResize => "col-resize",
174
2
            Self::ContextMenu => "context-menu",
175
2
            Self::Copy => "copy",
176
2
            Self::Crosshair => "crosshair",
177
2
            Self::Default => "default",
178
2
            Self::EResize => "e-resize",
179
2
            Self::EwResize => "ew-resize",
180
2
            Self::Grab => "grab",
181
2
            Self::Grabbing => "grabbing",
182
2
            Self::Help => "help",
183
2
            Self::Move => "move",
184
2
            Self::NResize => "n-resize",
185
2
            Self::NsResize => "ns-resize",
186
2
            Self::NeswResize => "nesw-resize",
187
2
            Self::NwseResize => "nwse-resize",
188
2
            Self::Pointer => "pointer",
189
2
            Self::Progress => "progress",
190
2
            Self::RowResize => "row-resize",
191
2
            Self::SResize => "s-resize",
192
2
            Self::SeResize => "se-resize",
193
847
            Self::Text => "text",
194
2
            Self::Unset => "unset",
195
2
            Self::VerticalText => "vertical-text",
196
2
            Self::WResize => "w-resize",
197
2
            Self::Wait => "wait",
198
2
            Self::ZoomIn => "zoom-in",
199
2
            Self::ZoomOut => "zoom-out",
200
        })
201
905
    }
202
}
203

            
204
// --- PARSERS ---
205

            
206
#[cfg(feature = "parser")]
207
pub mod parsers {
208
    #[allow(clippy::wildcard_imports)]
209
    // parser submodule reuses the parent module's value types
210
    use super::*;
211
    use crate::{
212
        corety::AzString,
213
        props::basic::error::{InvalidValueErr, InvalidValueErrOwned},
214
    };
215

            
216
    // -- Opacity Parser --
217

            
218
    #[derive(Clone, PartialEq, Eq)]
219
    pub enum OpacityParseError<'a> {
220
        ParsePercentage(PercentageParseError, &'a str),
221
        OutOfRange(&'a str),
222
    }
223
    impl_debug_as_display!(OpacityParseError<'a>);
224
    impl_display! { OpacityParseError<'a>, {
225
        ParsePercentage(e, s) => format!("Invalid opacity value \"{}\": {}", s, e),
226
        OutOfRange(s) => format!("Invalid opacity value \"{}\": must be between 0 and 1", s),
227
    }}
228

            
229
    /// Wrapper for `PercentageParseError` with input string.
230
    #[derive(Debug, Clone, PartialEq, Eq)]
231
    #[repr(C)]
232
    pub struct PercentageParseErrorWithInput {
233
        pub error: PercentageParseError,
234
        pub input: AzString,
235
    }
236

            
237
    #[derive(Debug, Clone, PartialEq, Eq)]
238
    #[repr(C, u8)]
239
    pub enum OpacityParseErrorOwned {
240
        ParsePercentage(PercentageParseErrorWithInput),
241
        OutOfRange(AzString),
242
    }
243

            
244
    impl OpacityParseError<'_> {
245
        #[must_use]
246
16
        pub fn to_contained(&self) -> OpacityParseErrorOwned {
247
16
            match self {
248
9
                Self::ParsePercentage(err, s) => {
249
9
                    OpacityParseErrorOwned::ParsePercentage(PercentageParseErrorWithInput {
250
9
                        error: err.clone(),
251
9
                        input: (*s).to_string().into(),
252
9
                    })
253
                }
254
7
                Self::OutOfRange(s) => OpacityParseErrorOwned::OutOfRange((*s).to_string().into()),
255
            }
256
16
        }
257
    }
258

            
259
    impl OpacityParseErrorOwned {
260
        #[must_use]
261
16
        pub fn to_shared(&self) -> OpacityParseError<'_> {
262
16
            match self {
263
9
                Self::ParsePercentage(e) => {
264
9
                    OpacityParseError::ParsePercentage(e.error.clone(), e.input.as_str())
265
                }
266
7
                Self::OutOfRange(s) => OpacityParseError::OutOfRange(s.as_str()),
267
            }
268
16
        }
269
    }
270

            
271
    /// # Errors
272
    ///
273
    /// Returns an error if `input` is not a valid CSS `opacity` value.
274
638
    pub fn parse_style_opacity(input: &str) -> Result<StyleOpacity, OpacityParseError<'_>> {
275
638
        let val = parse_percentage_value(input)
276
638
            .map_err(|e| OpacityParseError::ParsePercentage(e, input))?;
277

            
278
551
        let normalized = val.normalized();
279
551
        if !(0.0..=1.0).contains(&normalized) {
280
121
            return Err(OpacityParseError::OutOfRange(input));
281
430
        }
282

            
283
430
        Ok(StyleOpacity { inner: val })
284
638
    }
285

            
286
    // -- Visibility Parser --
287

            
288
    #[derive(Clone, PartialEq, Eq)]
289
    pub enum StyleVisibilityParseError<'a> {
290
        InvalidValue(InvalidValueErr<'a>),
291
    }
292
    impl_debug_as_display!(StyleVisibilityParseError<'a>);
293
    impl_display! { StyleVisibilityParseError<'a>, {
294
        InvalidValue(e) => format!("Invalid visibility value: \"{}\"", e.0),
295
    }}
296
    impl_from!(InvalidValueErr<'a>, StyleVisibilityParseError::InvalidValue);
297

            
298
    #[derive(Debug, Clone, PartialEq, Eq)]
299
    #[repr(C, u8)]
300
    pub enum StyleVisibilityParseErrorOwned {
301
        InvalidValue(InvalidValueErrOwned),
302
    }
303

            
304
    impl StyleVisibilityParseError<'_> {
305
        #[must_use]
306
6
        pub fn to_contained(&self) -> StyleVisibilityParseErrorOwned {
307
6
            match self {
308
6
                Self::InvalidValue(e) => {
309
6
                    StyleVisibilityParseErrorOwned::InvalidValue(e.to_contained())
310
                }
311
            }
312
6
        }
313
    }
314

            
315
    impl StyleVisibilityParseErrorOwned {
316
        #[must_use]
317
6
        pub fn to_shared(&self) -> StyleVisibilityParseError<'_> {
318
6
            match self {
319
6
                Self::InvalidValue(e) => StyleVisibilityParseError::InvalidValue(e.to_shared()),
320
            }
321
6
        }
322
    }
323

            
324
    /// # Errors
325
    ///
326
    /// Returns an error if `input` is not a valid CSS `visibility` value.
327
61
    pub fn parse_style_visibility(
328
61
        input: &str,
329
61
    ) -> Result<StyleVisibility, StyleVisibilityParseError<'_>> {
330
61
        let input = input.trim();
331
61
        match input {
332
61
            "visible" => Ok(StyleVisibility::Visible),
333
55
            "hidden" => Ok(StyleVisibility::Hidden),
334
30
            "collapse" => Ok(StyleVisibility::Collapse),
335
26
            _ => Err(InvalidValueErr(input).into()),
336
        }
337
61
    }
338

            
339
    // -- Mix Blend Mode Parser --
340

            
341
    #[derive(Clone, PartialEq, Eq)]
342
    pub enum MixBlendModeParseError<'a> {
343
        InvalidValue(InvalidValueErr<'a>),
344
    }
345
    impl_debug_as_display!(MixBlendModeParseError<'a>);
346
    impl_display! { MixBlendModeParseError<'a>, {
347
        InvalidValue(e) => format!("Invalid mix-blend-mode value: \"{}\"", e.0),
348
    }}
349
    impl_from!(InvalidValueErr<'a>, MixBlendModeParseError::InvalidValue);
350

            
351
    #[derive(Debug, Clone, PartialEq, Eq)]
352
    #[repr(C, u8)]
353
    pub enum MixBlendModeParseErrorOwned {
354
        InvalidValue(InvalidValueErrOwned),
355
    }
356

            
357
    impl MixBlendModeParseError<'_> {
358
        #[must_use]
359
6
        pub fn to_contained(&self) -> MixBlendModeParseErrorOwned {
360
6
            match self {
361
6
                Self::InvalidValue(e) => {
362
6
                    MixBlendModeParseErrorOwned::InvalidValue(e.to_contained())
363
                }
364
            }
365
6
        }
366
    }
367

            
368
    impl MixBlendModeParseErrorOwned {
369
        #[must_use]
370
6
        pub fn to_shared(&self) -> MixBlendModeParseError<'_> {
371
6
            match self {
372
6
                Self::InvalidValue(e) => MixBlendModeParseError::InvalidValue(e.to_shared()),
373
            }
374
6
        }
375
    }
376

            
377
    /// # Errors
378
    ///
379
    /// Returns an error if `input` is not a valid CSS `mix-blend-mode` value.
380
67
    pub fn parse_style_mix_blend_mode(
381
67
        input: &str,
382
67
    ) -> Result<StyleMixBlendMode, MixBlendModeParseError<'_>> {
383
67
        let input = input.trim();
384
67
        match input {
385
67
            "normal" => Ok(StyleMixBlendMode::Normal),
386
64
            "multiply" => Ok(StyleMixBlendMode::Multiply),
387
59
            "screen" => Ok(StyleMixBlendMode::Screen),
388
56
            "overlay" => Ok(StyleMixBlendMode::Overlay),
389
54
            "darken" => Ok(StyleMixBlendMode::Darken),
390
52
            "lighten" => Ok(StyleMixBlendMode::Lighten),
391
50
            "color-dodge" => Ok(StyleMixBlendMode::ColorDodge),
392
45
            "color-burn" => Ok(StyleMixBlendMode::ColorBurn),
393
43
            "hard-light" => Ok(StyleMixBlendMode::HardLight),
394
41
            "soft-light" => Ok(StyleMixBlendMode::SoftLight),
395
39
            "difference" => Ok(StyleMixBlendMode::Difference),
396
37
            "exclusion" => Ok(StyleMixBlendMode::Exclusion),
397
35
            "hue" => Ok(StyleMixBlendMode::Hue),
398
33
            "saturation" => Ok(StyleMixBlendMode::Saturation),
399
31
            "color" => Ok(StyleMixBlendMode::Color),
400
29
            "luminosity" => Ok(StyleMixBlendMode::Luminosity),
401
27
            _ => Err(InvalidValueErr(input).into()),
402
        }
403
67
    }
404

            
405
    // -- Cursor Parser --
406

            
407
    #[derive(Clone, PartialEq, Eq)]
408
    pub enum CursorParseError<'a> {
409
        InvalidValue(InvalidValueErr<'a>),
410
    }
411
    impl_debug_as_display!(CursorParseError<'a>);
412
    impl_display! { CursorParseError<'a>, {
413
        InvalidValue(e) => format!("Invalid cursor value: \"{}\"", e.0),
414
    }}
415
    impl_from!(InvalidValueErr<'a>, CursorParseError::InvalidValue);
416

            
417
    #[derive(Debug, Clone, PartialEq, Eq)]
418
    #[repr(C, u8)]
419
    pub enum CursorParseErrorOwned {
420
        InvalidValue(InvalidValueErrOwned),
421
    }
422

            
423
    impl CursorParseError<'_> {
424
        #[must_use]
425
6
        pub fn to_contained(&self) -> CursorParseErrorOwned {
426
6
            match self {
427
6
                Self::InvalidValue(e) => CursorParseErrorOwned::InvalidValue(e.to_contained()),
428
            }
429
6
        }
430
    }
431

            
432
    impl CursorParseErrorOwned {
433
        #[must_use]
434
6
        pub fn to_shared(&self) -> CursorParseError<'_> {
435
6
            match self {
436
6
                Self::InvalidValue(e) => CursorParseError::InvalidValue(e.to_shared()),
437
            }
438
6
        }
439
    }
440

            
441
    /// # Errors
442
    ///
443
    /// Returns an error if `input` is not a valid CSS `cursor` value.
444
25899
    pub fn parse_style_cursor(input: &str) -> Result<StyleCursor, CursorParseError<'_>> {
445
25899
        let input = input.trim();
446
25899
        match input {
447
25899
            "alias" => Ok(StyleCursor::Alias),
448
25897
            "all-scroll" => Ok(StyleCursor::AllScroll),
449
25895
            "cell" => Ok(StyleCursor::Cell),
450
25893
            "col-resize" => Ok(StyleCursor::ColResize),
451
25890
            "context-menu" => Ok(StyleCursor::ContextMenu),
452
25888
            "copy" => Ok(StyleCursor::Copy),
453
25886
            "crosshair" => Ok(StyleCursor::Crosshair),
454
24181
            "default" => Ok(StyleCursor::Default),
455
23841
            "e-resize" => Ok(StyleCursor::EResize),
456
23839
            "ew-resize" => Ok(StyleCursor::EwResize),
457
23837
            "grab" => Ok(StyleCursor::Grab),
458
22442
            "grabbing" => Ok(StyleCursor::Grabbing),
459
22440
            "help" => Ok(StyleCursor::Help),
460
22438
            "move" => Ok(StyleCursor::Move),
461
22436
            "n-resize" => Ok(StyleCursor::NResize),
462
22434
            "ns-resize" => Ok(StyleCursor::NsResize),
463
22432
            "nesw-resize" => Ok(StyleCursor::NeswResize),
464
22430
            "nwse-resize" => Ok(StyleCursor::NwseResize),
465
22428
            "pointer" => Ok(StyleCursor::Pointer),
466
50
            "progress" => Ok(StyleCursor::Progress),
467
48
            "row-resize" => Ok(StyleCursor::RowResize),
468
46
            "s-resize" => Ok(StyleCursor::SResize),
469
44
            "se-resize" => Ok(StyleCursor::SeResize),
470
42
            "text" => Ok(StyleCursor::Text),
471
39
            "unset" => Ok(StyleCursor::Unset),
472
37
            "vertical-text" => Ok(StyleCursor::VerticalText),
473
35
            "w-resize" => Ok(StyleCursor::WResize),
474
33
            "wait" => Ok(StyleCursor::Wait),
475
30
            "zoom-in" => Ok(StyleCursor::ZoomIn),
476
28
            "zoom-out" => Ok(StyleCursor::ZoomOut),
477
26
            _ => Err(InvalidValueErr(input).into()),
478
        }
479
25899
    }
480
}
481

            
482
#[cfg(feature = "parser")]
483
pub use self::parsers::*;
484

            
485
#[cfg(all(test, feature = "parser"))]
486
mod tests {
487
    // Tests assert that parsed values equal the exact source literals.
488
    #![allow(clippy::float_cmp)]
489
    use super::*;
490

            
491
    #[test]
492
1
    fn test_parse_opacity() {
493
1
        assert_eq!(parse_style_opacity("0.5").unwrap().inner.normalized(), 0.5);
494
1
        assert_eq!(parse_style_opacity("1").unwrap().inner.normalized(), 1.0);
495
1
        assert_eq!(parse_style_opacity("50%").unwrap().inner.normalized(), 0.5);
496
1
        assert_eq!(parse_style_opacity("0").unwrap().inner.normalized(), 0.0);
497
1
        assert_eq!(
498
1
            parse_style_opacity("  75%  ").unwrap().inner.normalized(),
499
            0.75
500
        );
501
1
        assert!(parse_style_opacity("1.1").is_err());
502
1
        assert!(parse_style_opacity("-0.1").is_err());
503
1
        assert!(parse_style_opacity("auto").is_err());
504
1
    }
505

            
506
    #[test]
507
1
    fn test_parse_mix_blend_mode() {
508
1
        assert_eq!(
509
1
            parse_style_mix_blend_mode("multiply").unwrap(),
510
            StyleMixBlendMode::Multiply
511
        );
512
1
        assert_eq!(
513
1
            parse_style_mix_blend_mode("screen").unwrap(),
514
            StyleMixBlendMode::Screen
515
        );
516
1
        assert_eq!(
517
1
            parse_style_mix_blend_mode("color-dodge").unwrap(),
518
            StyleMixBlendMode::ColorDodge
519
        );
520
1
        assert!(parse_style_mix_blend_mode("mix").is_err());
521
1
    }
522

            
523
    #[test]
524
1
    fn test_parse_visibility() {
525
1
        assert_eq!(
526
1
            parse_style_visibility("visible").unwrap(),
527
            StyleVisibility::Visible
528
        );
529
1
        assert_eq!(
530
1
            parse_style_visibility("hidden").unwrap(),
531
            StyleVisibility::Hidden
532
        );
533
1
        assert_eq!(
534
1
            parse_style_visibility("collapse").unwrap(),
535
            StyleVisibility::Collapse
536
        );
537
1
        assert_eq!(
538
1
            parse_style_visibility("  visible  ").unwrap(),
539
            StyleVisibility::Visible
540
        );
541
1
        assert!(parse_style_visibility("none").is_err());
542
1
        assert!(parse_style_visibility("show").is_err());
543
1
    }
544

            
545
    #[test]
546
1
    fn test_parse_cursor() {
547
1
        assert_eq!(parse_style_cursor("pointer").unwrap(), StyleCursor::Pointer);
548
1
        assert_eq!(parse_style_cursor("wait").unwrap(), StyleCursor::Wait);
549
1
        assert_eq!(
550
1
            parse_style_cursor("col-resize").unwrap(),
551
            StyleCursor::ColResize
552
        );
553
1
        assert_eq!(parse_style_cursor("  text  ").unwrap(), StyleCursor::Text);
554
1
        assert!(parse_style_cursor("hand").is_err()); // "hand" is a legacy IE value
555
1
    }
556

            
557
    #[test]
558
1
    fn test_parse_object_fit() {
559
1
        assert_eq!(
560
1
            parse_style_object_fit("fill").unwrap(),
561
            StyleObjectFit::Fill
562
        );
563
1
        assert_eq!(
564
1
            parse_style_object_fit("contain").unwrap(),
565
            StyleObjectFit::Contain
566
        );
567
1
        assert_eq!(
568
1
            parse_style_object_fit("cover").unwrap(),
569
            StyleObjectFit::Cover
570
        );
571
1
        assert_eq!(
572
1
            parse_style_object_fit("none").unwrap(),
573
            StyleObjectFit::None
574
        );
575
1
        assert_eq!(
576
1
            parse_style_object_fit("scale-down").unwrap(),
577
            StyleObjectFit::ScaleDown
578
        );
579
1
        assert_eq!(
580
1
            parse_style_object_fit("  cover  ").unwrap(),
581
            StyleObjectFit::Cover
582
        );
583
1
        assert!(parse_style_object_fit("stretch").is_err());
584
1
        assert!(parse_style_object_fit("").is_err());
585
1
    }
586

            
587
    #[test]
588
1
    fn test_parse_text_orientation() {
589
1
        assert_eq!(
590
1
            parse_style_text_orientation("mixed").unwrap(),
591
            StyleTextOrientation::Mixed
592
        );
593
1
        assert_eq!(
594
1
            parse_style_text_orientation("upright").unwrap(),
595
            StyleTextOrientation::Upright
596
        );
597
1
        assert_eq!(
598
1
            parse_style_text_orientation("sideways").unwrap(),
599
            StyleTextOrientation::Sideways
600
        );
601
1
        assert_eq!(
602
1
            parse_style_text_orientation("  mixed  ").unwrap(),
603
            StyleTextOrientation::Mixed
604
        );
605
1
        assert!(parse_style_text_orientation("vertical").is_err());
606
1
    }
607

            
608
    #[test]
609
1
    fn test_parse_object_position() {
610
        use crate::props::style::background::{
611
            BackgroundPositionHorizontal, BackgroundPositionVertical,
612
        };
613
1
        let centered = parse_style_object_position("center").unwrap();
614
1
        assert_eq!(
615
            centered,
616
1
            parse_style_object_position("center center").unwrap()
617
        );
618

            
619
1
        let lt = parse_style_object_position("left top").unwrap();
620
1
        assert_eq!(lt.horizontal, BackgroundPositionHorizontal::Left);
621
1
        assert_eq!(lt.vertical, BackgroundPositionVertical::Top);
622

            
623
1
        let rb = parse_style_object_position("right bottom").unwrap();
624
1
        assert_eq!(rb.horizontal, BackgroundPositionHorizontal::Right);
625
1
        assert_eq!(rb.vertical, BackgroundPositionVertical::Bottom);
626

            
627
1
        assert!(parse_style_object_position("left top center").is_err());
628
1
        assert!(parse_style_object_position("invalid").is_err());
629
1
    }
630

            
631
    #[test]
632
1
    fn test_parse_aspect_ratio() {
633
1
        assert_eq!(
634
1
            parse_style_aspect_ratio("auto").unwrap(),
635
            StyleAspectRatio::Auto
636
        );
637
1
        assert_eq!(
638
1
            parse_style_aspect_ratio("16 / 9").unwrap(),
639
            StyleAspectRatio::Ratio(AspectRatioValue {
640
                width: 16000,
641
                height: 9000
642
            })
643
        );
644
1
        assert_eq!(
645
1
            parse_style_aspect_ratio("16/9").unwrap(),
646
            StyleAspectRatio::Ratio(AspectRatioValue {
647
                width: 16000,
648
                height: 9000
649
            })
650
        );
651
1
        assert_eq!(
652
1
            parse_style_aspect_ratio("1.5").unwrap(),
653
            StyleAspectRatio::Ratio(AspectRatioValue {
654
                width: 1500,
655
                height: 1000
656
            })
657
        );
658
1
        assert_eq!(
659
1
            parse_style_aspect_ratio("  4 / 3  ").unwrap(),
660
            StyleAspectRatio::Ratio(AspectRatioValue {
661
                width: 4000,
662
                height: 3000
663
            })
664
        );
665
1
        assert!(parse_style_aspect_ratio("0 / 1").is_err());
666
1
        assert!(parse_style_aspect_ratio("1 / 0").is_err());
667
1
        assert!(parse_style_aspect_ratio("-1 / 1").is_err());
668
1
        assert!(parse_style_aspect_ratio("abc").is_err());
669
1
    }
670
}
671

            
672
// -- StyleObjectFit --
673

            
674
/// CSS object-fit property: how replaced element content is fitted to its box.
675
/// CSS Images Level 3 §5.5
676
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
677
#[repr(C)]
678
#[derive(Default)]
679
pub enum StyleObjectFit {
680
    #[default]
681
    Fill,
682
    Contain,
683
    Cover,
684
    None,
685
    ScaleDown,
686
}
687

            
688
crate::impl_option!(
689
    StyleObjectFit,
690
    OptionStyleObjectFit,
691
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
692
);
693

            
694
impl PrintAsCssValue for StyleObjectFit {
695
5
    fn print_as_css_value(&self) -> String {
696
5
        String::from(match self {
697
1
            Self::Fill => "fill",
698
1
            Self::Contain => "contain",
699
1
            Self::Cover => "cover",
700
1
            Self::None => "none",
701
1
            Self::ScaleDown => "scale-down",
702
        })
703
5
    }
704
}
705

            
706
#[cfg(feature = "parser")]
707
#[derive(Clone, PartialEq, Eq)]
708
pub enum StyleObjectFitParseError<'a> {
709
    InvalidValue(&'a str),
710
}
711

            
712
#[cfg(feature = "parser")]
713
crate::impl_debug_as_display!(StyleObjectFitParseError<'a>);
714

            
715
#[cfg(feature = "parser")]
716
crate::impl_display! { StyleObjectFitParseError<'a>, {
717
    InvalidValue(val) => format!("Invalid object-fit value: \"{}\"", val),
718
}}
719

            
720
#[cfg(feature = "parser")]
721
#[derive(Debug, Clone, PartialEq, Eq)]
722
#[repr(C, u8)]
723
pub enum StyleObjectFitParseErrorOwned {
724
    InvalidValue(crate::AzString),
725
}
726

            
727
#[cfg(feature = "parser")]
728
impl StyleObjectFitParseError<'_> {
729
    #[must_use]
730
7
    pub fn to_contained(&self) -> StyleObjectFitParseErrorOwned {
731
7
        match self {
732
7
            Self::InvalidValue(s) => {
733
7
                StyleObjectFitParseErrorOwned::InvalidValue((*s).to_string().into())
734
            }
735
        }
736
7
    }
737
}
738

            
739
#[cfg(feature = "parser")]
740
impl StyleObjectFitParseErrorOwned {
741
    #[must_use]
742
7
    pub fn to_shared(&self) -> StyleObjectFitParseError<'_> {
743
7
        match self {
744
7
            Self::InvalidValue(s) => StyleObjectFitParseError::InvalidValue(s.as_str()),
745
        }
746
7
    }
747
}
748

            
749
#[cfg(feature = "parser")]
750
/// # Errors
751
///
752
/// Returns an error if `input` is not a valid CSS `object-fit` value.
753
42
pub fn parse_style_object_fit(input: &str) -> Result<StyleObjectFit, StyleObjectFitParseError<'_>> {
754
42
    let input = input.trim();
755
42
    match input {
756
42
        "fill" => Ok(StyleObjectFit::Fill),
757
39
        "contain" => Ok(StyleObjectFit::Contain),
758
36
        "cover" => Ok(StyleObjectFit::Cover),
759
32
        "none" => Ok(StyleObjectFit::None),
760
29
        "scale-down" => Ok(StyleObjectFit::ScaleDown),
761
26
        _ => Err(StyleObjectFitParseError::InvalidValue(input)),
762
    }
763
42
}
764

            
765
// -- StyleTextOrientation --
766

            
767
/// CSS text-orientation property for vertical writing modes.
768
/// CSS Writing Modes Level 4 §5.1
769
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
770
#[repr(C)]
771
#[derive(Default)]
772
pub enum StyleTextOrientation {
773
    #[default]
774
    Mixed,
775
    Upright,
776
    Sideways,
777
}
778

            
779
crate::impl_option!(
780
    StyleTextOrientation,
781
    OptionStyleTextOrientation,
782
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
783
);
784

            
785
impl PrintAsCssValue for StyleTextOrientation {
786
3
    fn print_as_css_value(&self) -> String {
787
3
        String::from(match self {
788
1
            Self::Mixed => "mixed",
789
1
            Self::Upright => "upright",
790
1
            Self::Sideways => "sideways",
791
        })
792
3
    }
793
}
794

            
795
#[cfg(feature = "parser")]
796
#[derive(Clone, PartialEq, Eq)]
797
pub enum StyleTextOrientationParseError<'a> {
798
    InvalidValue(&'a str),
799
}
800

            
801
#[cfg(feature = "parser")]
802
crate::impl_debug_as_display!(StyleTextOrientationParseError<'a>);
803

            
804
#[cfg(feature = "parser")]
805
crate::impl_display! { StyleTextOrientationParseError<'a>, {
806
    InvalidValue(val) => format!("Invalid text-orientation value: \"{}\"", val),
807
}}
808

            
809
#[cfg(feature = "parser")]
810
#[derive(Debug, Clone, PartialEq, Eq)]
811
#[repr(C, u8)]
812
pub enum StyleTextOrientationParseErrorOwned {
813
    InvalidValue(crate::AzString),
814
}
815

            
816
#[cfg(feature = "parser")]
817
impl StyleTextOrientationParseError<'_> {
818
    #[must_use]
819
6
    pub fn to_contained(&self) -> StyleTextOrientationParseErrorOwned {
820
6
        match self {
821
6
            Self::InvalidValue(s) => {
822
6
                StyleTextOrientationParseErrorOwned::InvalidValue((*s).to_string().into())
823
            }
824
        }
825
6
    }
826
}
827

            
828
#[cfg(feature = "parser")]
829
impl StyleTextOrientationParseErrorOwned {
830
    #[must_use]
831
6
    pub fn to_shared(&self) -> StyleTextOrientationParseError<'_> {
832
6
        match self {
833
6
            Self::InvalidValue(s) => StyleTextOrientationParseError::InvalidValue(s.as_str()),
834
        }
835
6
    }
836
}
837

            
838
#[cfg(feature = "parser")]
839
/// # Errors
840
///
841
/// Returns an error if `input` is not a valid CSS `text-orientation` value.
842
32
pub fn parse_style_text_orientation(
843
32
    input: &str,
844
32
) -> Result<StyleTextOrientation, StyleTextOrientationParseError<'_>> {
845
32
    let input = input.trim();
846
32
    match input {
847
32
        "mixed" => Ok(StyleTextOrientation::Mixed),
848
28
        "upright" => Ok(StyleTextOrientation::Upright),
849
25
        "sideways" => Ok(StyleTextOrientation::Sideways),
850
22
        _ => Err(StyleTextOrientationParseError::InvalidValue(input)),
851
    }
852
32
}
853

            
854
// -- StyleObjectPosition --
855

            
856
/// CSS object-position property: position of replaced element content within its box.
857
/// CSS Images Level 3 §5.6 — default: `50% 50%` (centered)
858
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
859
#[repr(C)]
860
pub struct StyleObjectPosition {
861
    pub horizontal: crate::props::style::background::BackgroundPositionHorizontal,
862
    pub vertical: crate::props::style::background::BackgroundPositionVertical,
863
}
864

            
865
impl Default for StyleObjectPosition {
866
1
    fn default() -> Self {
867
        use crate::props::basic::pixel::PixelValue;
868
1
        Self {
869
1
            horizontal: crate::props::style::background::BackgroundPositionHorizontal::Exact(
870
1
                PixelValue::percent(50.0),
871
1
            ),
872
1
            vertical: crate::props::style::background::BackgroundPositionVertical::Exact(
873
1
                PixelValue::percent(50.0),
874
1
            ),
875
1
        }
876
1
    }
877
}
878

            
879
crate::impl_option!(
880
    StyleObjectPosition,
881
    OptionStyleObjectPosition,
882
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
883
);
884

            
885
impl PrintAsCssValue for StyleObjectPosition {
886
18
    fn print_as_css_value(&self) -> String {
887
18
        format!(
888
18
            "{} {}",
889
18
            self.horizontal.print_as_css_value(),
890
18
            self.vertical.print_as_css_value()
891
        )
892
18
    }
893
}
894

            
895
#[cfg(feature = "parser")]
896
#[derive(Clone, PartialEq, Eq)]
897
pub enum StyleObjectPositionParseError<'a> {
898
    InvalidValue(&'a str),
899
}
900

            
901
#[cfg(feature = "parser")]
902
crate::impl_debug_as_display!(StyleObjectPositionParseError<'a>);
903

            
904
#[cfg(feature = "parser")]
905
crate::impl_display! { StyleObjectPositionParseError<'a>, {
906
    InvalidValue(val) => format!("Invalid object-position value: \"{}\"", val),
907
}}
908

            
909
#[cfg(feature = "parser")]
910
#[derive(Debug, Clone, PartialEq, Eq)]
911
#[repr(C, u8)]
912
pub enum StyleObjectPositionParseErrorOwned {
913
    InvalidValue(crate::AzString),
914
}
915

            
916
#[cfg(feature = "parser")]
917
impl StyleObjectPositionParseError<'_> {
918
    #[must_use]
919
6
    pub fn to_contained(&self) -> StyleObjectPositionParseErrorOwned {
920
6
        match self {
921
6
            Self::InvalidValue(s) => {
922
6
                StyleObjectPositionParseErrorOwned::InvalidValue((*s).to_string().into())
923
            }
924
        }
925
6
    }
926
}
927

            
928
#[cfg(feature = "parser")]
929
impl StyleObjectPositionParseErrorOwned {
930
    #[must_use]
931
6
    pub fn to_shared(&self) -> StyleObjectPositionParseError<'_> {
932
6
        match self {
933
6
            Self::InvalidValue(s) => StyleObjectPositionParseError::InvalidValue(s.as_str()),
934
        }
935
6
    }
936
}
937

            
938
/// Parse object-position: accepts keyword pairs or percentage/length values.
939
/// Examples: "center", "left top", "50% 50%", "10px 20px"
940
#[cfg(feature = "parser")]
941
/// # Errors
942
///
943
/// Returns an error if `input` is not a valid CSS `object-position` value.
944
65
pub fn parse_style_object_position(
945
65
    input: &str,
946
65
) -> Result<StyleObjectPosition, StyleObjectPositionParseError<'_>> {
947
    use crate::props::{
948
        basic::pixel::parse_pixel_value,
949
        style::background::{BackgroundPositionHorizontal, BackgroundPositionVertical},
950
    };
951

            
952
65
    let input = input.trim();
953
65
    let parts: Vec<&str> = input.split_whitespace().collect();
954

            
955
65
    let (h, v) = match parts.len() {
956
        1 => {
957
20
            let val = parts[0];
958
20
            match val {
959
20
                "center" => (
960
3
                    BackgroundPositionHorizontal::Center,
961
3
                    BackgroundPositionVertical::Center,
962
3
                ),
963
17
                "left" => (
964
1
                    BackgroundPositionHorizontal::Left,
965
1
                    BackgroundPositionVertical::Center,
966
1
                ),
967
16
                "right" => (
968
1
                    BackgroundPositionHorizontal::Right,
969
1
                    BackgroundPositionVertical::Center,
970
1
                ),
971
15
                "top" => (
972
1
                    BackgroundPositionHorizontal::Center,
973
1
                    BackgroundPositionVertical::Top,
974
1
                ),
975
14
                "bottom" => (
976
1
                    BackgroundPositionHorizontal::Center,
977
1
                    BackgroundPositionVertical::Bottom,
978
1
                ),
979
                _ => {
980
13
                    let px = parse_pixel_value(val)
981
13
                        .map_err(|_| StyleObjectPositionParseError::InvalidValue(input))?;
982
6
                    (
983
6
                        BackgroundPositionHorizontal::Exact(px),
984
6
                        BackgroundPositionVertical::Exact(px),
985
6
                    )
986
                }
987
            }
988
        }
989
        2 => {
990
            // <position>: [left|center|right|<len>] || [top|center|bottom|<len>].
991
            // The `||` combinator lets two *keywords* appear in either order, so
992
            // canonicalize to (horizontal, vertical) first. A length in either
993
            // slot forces positional order (first = horizontal, second = vertical).
994
38
            let (a, b) = (parts[0], parts[1]);
995
38
            let both_keywords = matches!(a, "left" | "center" | "right" | "top" | "bottom")
996
27
                && matches!(b, "left" | "center" | "right" | "top" | "bottom");
997
38
            let reversed =
998
38
                both_keywords && (matches!(a, "top" | "bottom") || matches!(b, "left" | "right"));
999
38
            let (h_str, v_str) = if reversed { (b, a) } else { (a, b) };
38
            let h = match h_str {
38
                "left" => BackgroundPositionHorizontal::Left,
24
                "center" => BackgroundPositionHorizontal::Center,
19
                "right" => BackgroundPositionHorizontal::Right,
12
                other => {
12
                    let px = parse_pixel_value(other)
12
                        .map_err(|_| StyleObjectPositionParseError::InvalidValue(input))?;
10
                    BackgroundPositionHorizontal::Exact(px)
                }
            };
36
            let v = match v_str {
36
                "top" => BackgroundPositionVertical::Top,
23
                "center" => BackgroundPositionVertical::Center,
18
                "bottom" => BackgroundPositionVertical::Bottom,
11
                other => {
11
                    let px = parse_pixel_value(other)
11
                        .map_err(|_| StyleObjectPositionParseError::InvalidValue(input))?;
10
                    BackgroundPositionVertical::Exact(px)
                }
            };
35
            (h, v)
        }
7
        _ => return Err(StyleObjectPositionParseError::InvalidValue(input)),
    };
48
    Ok(StyleObjectPosition {
48
        horizontal: h,
48
        vertical: v,
48
    })
65
}
// -- StyleAspectRatio --
/// Width/height ratio stored as fixed-point (value * 1000).
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct AspectRatioValue {
    pub width: u32,
    pub height: u32,
}
impl AspectRatioValue {
    /// Format one fixed-point component (`value * 1000`) back to its CSS number,
    /// dropping the scale and any trailing fractional zeros: 16000 -> "16",
    /// 1500 -> "1.5". Used by `PrintAsCssValue` so a printed ratio re-parses to
    /// the same value (integer math, no lossy f32 cast).
2
    fn fmt_component(v: u32) -> String {
2
        let int = v / 1000;
2
        let frac = v % 1000;
2
        if frac == 0 {
2
            int.to_string()
        } else {
            let frac_str = format!("{frac:03}");
            format!("{int}.{}", frac_str.trim_end_matches('0'))
        }
2
    }
}
#[allow(variant_size_differences)]
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
// disparity accepted
/// CSS aspect-ratio property: preferred aspect ratio for the box.
/// CSS Box Sizing Level 4 §6 — values: `auto | <ratio>` (initial: `auto`)
///
/// Stored as width/height ratio. Auto means no preferred ratio.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C, u8)]
#[derive(Default)]
pub enum StyleAspectRatio {
    /// No preferred aspect ratio
    #[default]
    Auto,
    /// Fixed ratio (width / height), stored as fixed-point (value * 1000)
    Ratio(AspectRatioValue),
}
crate::impl_option!(
    StyleAspectRatio,
    OptionStyleAspectRatio,
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl PrintAsCssValue for StyleAspectRatio {
2
    fn print_as_css_value(&self) -> String {
2
        match self {
1
            Self::Auto => String::from("auto"),
1
            Self::Ratio(r) => format!(
1
                "{} / {}",
1
                AspectRatioValue::fmt_component(r.width),
1
                AspectRatioValue::fmt_component(r.height)
            ),
        }
2
    }
}
#[cfg(feature = "parser")]
#[derive(Clone, PartialEq, Eq)]
pub enum StyleAspectRatioParseError<'a> {
    InvalidValue(&'a str),
}
#[cfg(feature = "parser")]
crate::impl_debug_as_display!(StyleAspectRatioParseError<'a>);
#[cfg(feature = "parser")]
crate::impl_display! { StyleAspectRatioParseError<'a>, {
    InvalidValue(val) => format!("Invalid aspect-ratio value: \"{}\"", val),
}}
#[cfg(feature = "parser")]
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C, u8)]
pub enum StyleAspectRatioParseErrorOwned {
    InvalidValue(crate::AzString),
}
#[cfg(feature = "parser")]
impl StyleAspectRatioParseError<'_> {
    #[must_use]
6
    pub fn to_contained(&self) -> StyleAspectRatioParseErrorOwned {
6
        match self {
6
            Self::InvalidValue(s) => {
6
                StyleAspectRatioParseErrorOwned::InvalidValue((*s).to_string().into())
            }
        }
6
    }
}
#[cfg(feature = "parser")]
impl StyleAspectRatioParseErrorOwned {
    #[must_use]
6
    pub fn to_shared(&self) -> StyleAspectRatioParseError<'_> {
6
        match self {
6
            Self::InvalidValue(s) => StyleAspectRatioParseError::InvalidValue(s.as_str()),
        }
6
    }
}
/// Truncating `f32` → `u32` for aspect-ratio values (callers validate the input
/// is positive and bounded, so the value always fits). Rust's `as u32` saturates
/// out-of-range floats; this isolates the one unavoidable float→int cast.
#[cfg(feature = "parser")]
#[inline]
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
106
const fn aspect_f32_to_u32(v: f32) -> u32 {
106
    v as u32
106
}
/// Validate two ratio components and encode them into the fixed-point
/// [`AspectRatioValue`]. The positive-range checks are written as
/// `!(x > 0.0 && x <= MAX)` so NaN — which is false for every ordered
/// comparison — is rejected instead of sailing through the guards. A component
/// whose fixed-point encoding rounds to 0 (magnitude below ~0.0005) is a
/// degenerate divide-by-zero ratio and is rejected as well.
#[cfg(feature = "parser")]
75
fn ratio_from_components(
75
    w: f32,
75
    h: f32,
75
    input: &str,
75
) -> Result<StyleAspectRatio, StyleAspectRatioParseError<'_>> {
75
    if !(w > 0.0 && w <= 100_000.0 && h > 0.0 && h <= 100_000.0) {
31
        return Err(StyleAspectRatioParseError::InvalidValue(input));
44
    }
44
    let width = aspect_f32_to_u32((w * 1000.0).round());
44
    let height = aspect_f32_to_u32((h * 1000.0).round());
44
    if width == 0 || height == 0 {
4
        return Err(StyleAspectRatioParseError::InvalidValue(input));
40
    }
40
    Ok(StyleAspectRatio::Ratio(AspectRatioValue { width, height }))
75
}
/// Parse aspect-ratio: "auto", "16 / 9", "1.5", "4/3"
#[cfg(feature = "parser")]
/// # Errors
///
/// Returns an error if `input` is not a valid CSS `aspect-ratio` value.
99
pub fn parse_style_aspect_ratio(
99
    input: &str,
99
) -> Result<StyleAspectRatio, StyleAspectRatioParseError<'_>> {
99
    let input = input.trim();
99
    if input == "auto" {
3
        return Ok(StyleAspectRatio::Auto);
96
    }
    // Try "w / h" or "w/h" format
96
    if let Some(slash_pos) = input.find('/') {
40
        let w_str = input[..slash_pos].trim();
40
        let h_str = input[slash_pos + 1..].trim();
40
        let w: f32 = w_str
40
            .parse()
40
            .map_err(|_| StyleAspectRatioParseError::InvalidValue(input))?;
34
        let h: f32 = h_str
34
            .parse()
34
            .map_err(|_| StyleAspectRatioParseError::InvalidValue(input))?;
31
        return ratio_from_components(w, h, input);
56
    }
    // A single number is the "<w> / 1" ratio.
56
    let w: f32 = input
56
        .parse()
56
        .map_err(|_| StyleAspectRatioParseError::InvalidValue(input))?;
44
    ratio_from_components(w, 1.0, input)
99
}
#[cfg(all(test, feature = "parser"))]
#[allow(
    clippy::float_cmp,
    clippy::unreadable_literal,
    clippy::too_many_lines,
    clippy::cast_precision_loss
)]
mod autotest_generated {
    use super::*;
    use crate::props::{
        basic::{error::ParseFloatError as CssParseFloatError, pixel::PixelValue},
        formatter::PrintAsCssValue,
        style::background::{BackgroundPositionHorizontal, BackgroundPositionVertical},
    };
    const ALL_VISIBILITY: [StyleVisibility; 3] = [
        StyleVisibility::Visible,
        StyleVisibility::Hidden,
        StyleVisibility::Collapse,
    ];
    const ALL_BLEND_MODES: [StyleMixBlendMode; 16] = [
        StyleMixBlendMode::Normal,
        StyleMixBlendMode::Multiply,
        StyleMixBlendMode::Screen,
        StyleMixBlendMode::Overlay,
        StyleMixBlendMode::Darken,
        StyleMixBlendMode::Lighten,
        StyleMixBlendMode::ColorDodge,
        StyleMixBlendMode::ColorBurn,
        StyleMixBlendMode::HardLight,
        StyleMixBlendMode::SoftLight,
        StyleMixBlendMode::Difference,
        StyleMixBlendMode::Exclusion,
        StyleMixBlendMode::Hue,
        StyleMixBlendMode::Saturation,
        StyleMixBlendMode::Color,
        StyleMixBlendMode::Luminosity,
    ];
    const ALL_CURSORS: [StyleCursor; 30] = [
        StyleCursor::Alias,
        StyleCursor::AllScroll,
        StyleCursor::Cell,
        StyleCursor::ColResize,
        StyleCursor::ContextMenu,
        StyleCursor::Copy,
        StyleCursor::Crosshair,
        StyleCursor::Default,
        StyleCursor::EResize,
        StyleCursor::EwResize,
        StyleCursor::Grab,
        StyleCursor::Grabbing,
        StyleCursor::Help,
        StyleCursor::Move,
        StyleCursor::NResize,
        StyleCursor::NsResize,
        StyleCursor::NeswResize,
        StyleCursor::NwseResize,
        StyleCursor::Pointer,
        StyleCursor::Progress,
        StyleCursor::RowResize,
        StyleCursor::SResize,
        StyleCursor::SeResize,
        StyleCursor::Text,
        StyleCursor::Unset,
        StyleCursor::VerticalText,
        StyleCursor::WResize,
        StyleCursor::Wait,
        StyleCursor::ZoomIn,
        StyleCursor::ZoomOut,
    ];
    const ALL_OBJECT_FIT: [StyleObjectFit; 5] = [
        StyleObjectFit::Fill,
        StyleObjectFit::Contain,
        StyleObjectFit::Cover,
        StyleObjectFit::None,
        StyleObjectFit::ScaleDown,
    ];
    const ALL_TEXT_ORIENTATION: [StyleTextOrientation; 3] = [
        StyleTextOrientation::Mixed,
        StyleTextOrientation::Upright,
        StyleTextOrientation::Sideways,
    ];
    /// Inputs no keyword parser may ever accept, and none may panic on.
    /// Deliberately mixes empty / whitespace / punctuation / multibyte input.
    const HOSTILE_KEYWORDS: [&str; 14] = [
        "",
        " ",
        "\t\n\r",
        "\u{a0}", // NBSP — `str::trim` treats it as whitespace
        ";",
        "{}",
        "/*",
        "0",
        "-1",
        "NaN",
        "inf",
        "\u{1F600}", // emoji
        "e\u{0301}", // combining acute accent
        "\u{0665}",  // ARABIC-INDIC DIGIT FIVE (multibyte, `is_numeric`)
    ];
    // ------------------------------------------------ StyleMixBlendMode::fmt ---
    #[test]
    fn blend_mode_display_is_well_formed_for_every_variant() {
        for mode in ALL_BLEND_MODES {
            let shown = mode.to_string();
            assert!(!shown.is_empty(), "{mode:?} renders as an empty string");
            assert!(
                shown.chars().all(|c| c.is_ascii_lowercase() || c == '-'),
                "{mode:?} renders as {shown:?}, which is not a CSS ident"
            );
            // `PrintAsCssValue` delegates to `Display`; pin them together so a
            // future divergence has to be deliberate.
            assert_eq!(shown, mode.print_as_css_value());
        }
    }
    #[test]
    fn blend_mode_display_of_default_is_normal() {
        assert_eq!(StyleMixBlendMode::default().to_string(), "normal");
        assert_eq!(StyleMixBlendMode::default(), StyleMixBlendMode::Normal);
    }
    #[test]
    fn blend_mode_display_survives_width_and_precision_flags() {
        // The impl forwards through `write!(f, "{}", ..)` instead of `f.pad(..)`,
        // so the caller's width/precision/fill flags are dropped rather than
        // applied. Not a panic, but pin it: `{:>10}` does NOT pad.
        assert_eq!(format!("{:>10}", StyleMixBlendMode::Normal), "normal");
        assert_eq!(format!("{:.2}", StyleMixBlendMode::Multiply), "multiply");
        assert_eq!(
            format!("{:*^30}", StyleMixBlendMode::ColorDodge),
            "color-dodge"
        );
    }
    // ----------------------------------------------------- parse_style_opacity ---
    #[test]
    fn opacity_rejects_empty_and_whitespace_only_input() {
        for input in ["", " ", "   ", "\t\n", "\r\n\t ", "\u{a0}"] {
            assert!(
                parse_style_opacity(input).is_err(),
                "{input:?} must not parse as an opacity"
            );
        }
    }
    #[test]
    fn opacity_rejects_garbage() {
        for input in [
            "auto",
            "abc",
            "%",
            ";;;",
            "50%%",
            "#0.5",
            "0.5;garbage",
            "1 2",
            "rgb(0,0,0)",
            "0,5",
            "--",
            "..",
            "-",
            ".",
        ] {
            assert!(
                parse_style_opacity(input).is_err(),
                "{input:?} must not parse as an opacity"
            );
        }
    }
    #[test]
    fn opacity_boundary_numbers() {
        // In range.
        assert_eq!(parse_style_opacity("0").unwrap().inner.normalized(), 0.0);
        assert_eq!(parse_style_opacity("1").unwrap().inner.normalized(), 1.0);
        assert_eq!(parse_style_opacity("0%").unwrap().inner.normalized(), 0.0);
        assert_eq!(parse_style_opacity("100%").unwrap().inner.normalized(), 1.0);
        // `-0.0 == 0.0` under IEEE-754, so the `0.0..=1.0` guard accepts it.
        assert_eq!(parse_style_opacity("-0").unwrap().inner.normalized(), 0.0);
        assert_eq!(parse_style_opacity("-0%").unwrap().inner.normalized(), 0.0);
        // Below the fixed-point resolution: quantized to 0, still in range.
        assert!(parse_style_opacity("0.0000001").is_ok());
        // Out of range.
        for input in ["1.001", "1.1", "2", "101%", "-0.001", "-1", "-100%"] {
            assert!(
                matches!(
                    parse_style_opacity(input),
                    Err(OpacityParseError::OutOfRange(_))
                ),
                "{input:?} should be rejected as out-of-range"
            );
        }
        // Float extremes: `str::parse::<f32>` maps 1e39 to +inf, which must not
        // panic through the fixed-point cast and must land out of range.
        for input in ["1e39", "3.5e38", "9223372036854775807", "1e30"] {
            assert!(
                parse_style_opacity(input).is_err(),
                "{input:?} should be rejected as out-of-range"
            );
        }
        // `NaN` / `inf` contain no numeric char, so the scanner bails out first.
        for input in ["NaN", "nan", "inf", "infinity", "-inf", "-NaN"] {
            assert!(
                parse_style_opacity(input).is_err(),
                "{input:?} should be rejected"
            );
        }
    }
    #[test]
    fn opacity_trims_but_rejects_trailing_junk() {
        assert_eq!(
            parse_style_opacity("  0.5  ").unwrap().inner.normalized(),
            0.5
        );
        assert_eq!(
            parse_style_opacity("\t50%\n").unwrap().inner.normalized(),
            0.5
        );
        for input in ["0.5;", "0.5 !important", "0.5px", "0.5 0.5"] {
            assert!(
                parse_style_opacity(input).is_err(),
                "{input:?} must not parse as an opacity"
            );
        }
        // Lax, pinned: the unit is trimmed *after* being split off the number, so
        // an internal space between value and unit is accepted even though CSS
        // forbids it.
        assert_eq!(parse_style_opacity("50 %").unwrap().inner.normalized(), 0.5);
    }
    #[test]
    fn opacity_non_numeric_unicode_does_not_panic() {
        // Multibyte input whose *last* numeric char is ASCII (or which has no
        // numeric char at all) must be rejected without slicing mid-codepoint.
        // See `known_bug_opacity_multibyte_numeric_char_panics` for the case
        // that does not hold.
        for input in [
            "\u{1F600}",        // emoji only
            "\u{1F600}0.5",     // emoji then ASCII digits
            "0.5\u{0301}",      // digits then a combining acute accent
            "\u{2603}%",        // snowman + percent sign
            "\u{4F60}\u{597D}", // CJK
            "\u{202E}0.5",      // RTL override
        ] {
            assert!(
                parse_style_opacity(input).is_err(),
                "{input:?} must not parse as an opacity"
            );
        }
    }
    #[test]
    fn opacity_extremely_long_input_terminates() {
        // 100k digits overflow f32 to +inf => out of range, but must not hang.
        let huge = "1".repeat(100_000);
        assert!(parse_style_opacity(&huge).is_err());
        // 100k *leading* fraction zeros exercise the slow float path and stay
        // in range.
        let tiny = format!("0.{}5", "0".repeat(100_000));
        assert_eq!(parse_style_opacity(&tiny).unwrap().inner.normalized(), 0.0);
        // A long trailing unit is rejected, not truncated.
        let long_unit = format!("0.5{}", "z".repeat(100_000));
        assert!(parse_style_opacity(&long_unit).is_err());
    }
    #[test]
    fn opacity_deeply_nested_brackets_do_not_stack_overflow() {
        let nested = "(".repeat(10_000);
        assert!(parse_style_opacity(&nested).is_err());
        let wrapped = format!("{}0.5{}", "(".repeat(10_000), ")".repeat(10_000));
        assert!(parse_style_opacity(&wrapped).is_err());
    }
    #[test]
    fn opacity_valid_minimal_positive_control() {
        assert!(parse_style_opacity("1").unwrap() == StyleOpacity::default());
        assert!(parse_style_opacity("50%").unwrap() == StyleOpacity::new(50.0));
        assert!(parse_style_opacity("0.5").unwrap() == StyleOpacity::new(50.0));
        // `0.5` (fraction) and `50%` are the same value.
        assert!(parse_style_opacity("0.5").unwrap() == parse_style_opacity("50%").unwrap());
    }
    #[test]
    fn opacity_round_trips_through_print_as_css_value_and_display() {
        for pct in [0.0f32, 12.5, 25.0, 50.0, 75.0, 99.9, 100.0] {
            let opacity = StyleOpacity::new(pct);
            // `PrintAsCssValue` emits the normalized 0..=1 fraction.
            let printed = opacity.print_as_css_value();
            let reparsed = parse_style_opacity(&printed)
                .unwrap_or_else(|e| panic!("{printed:?} (from {pct}%) failed to re-parse: {e}"));
            assert_eq!(
                reparsed.inner.normalized(),
                opacity.inner.normalized(),
                "{pct}% printed as {printed:?} but re-parsed differently"
            );
            // `Display` emits the percentage form; that must re-parse too.
            let displayed = opacity.to_string();
            let reparsed = parse_style_opacity(&displayed)
                .unwrap_or_else(|e| panic!("{displayed:?} (from {pct}%) failed to re-parse: {e}"));
            assert_eq!(reparsed.inner.normalized(), opacity.inner.normalized());
        }
    }
    // ------------------------------------------------- parse_style_visibility ---
    #[test]
    fn visibility_parses_every_keyword_and_round_trips() {
        assert_eq!(
            parse_style_visibility("visible").unwrap(),
            StyleVisibility::Visible
        );
        assert_eq!(
            parse_style_visibility("hidden").unwrap(),
            StyleVisibility::Hidden
        );
        assert_eq!(
            parse_style_visibility("collapse").unwrap(),
            StyleVisibility::Collapse
        );
        assert_eq!(StyleVisibility::default(), StyleVisibility::Visible);
        for v in ALL_VISIBILITY {
            let printed = v.print_as_css_value();
            assert!(!printed.is_empty());
            assert_eq!(parse_style_visibility(&printed).unwrap(), v);
            // Surrounding whitespace is trimmed, not rejected.
            assert_eq!(
                parse_style_visibility(&format!("  {printed}\t")).unwrap(),
                v
            );
        }
    }
    #[test]
    fn visibility_rejects_hostile_input() {
        for input in HOSTILE_KEYWORDS {
            assert!(
                parse_style_visibility(input).is_err(),
                "{input:?} must not parse as a visibility"
            );
        }
        for input in [
            "none",
            "show",
            "visible hidden",
            "visible;",
            "vis",
            "visibleX",
        ] {
            assert!(
                parse_style_visibility(input).is_err(),
                "{input:?} must not parse as a visibility"
            );
        }
    }
    // -------------------------------------------- parse_style_mix_blend_mode ---
    #[test]
    fn blend_mode_parses_every_keyword_and_round_trips() {
        for mode in ALL_BLEND_MODES {
            let printed = mode.print_as_css_value();
            assert_eq!(
                parse_style_mix_blend_mode(&printed).unwrap(),
                mode,
                "{printed:?} did not round-trip"
            );
            assert_eq!(
                parse_style_mix_blend_mode(&format!(" {printed} ")).unwrap(),
                mode
            );
        }
        assert_eq!(StyleMixBlendMode::default(), StyleMixBlendMode::Normal);
    }
    #[test]
    fn blend_mode_rejects_hostile_input() {
        for input in HOSTILE_KEYWORDS {
            assert!(
                parse_style_mix_blend_mode(input).is_err(),
                "{input:?} must not parse as a mix-blend-mode"
            );
        }
        // Near-misses: separator swaps, plain-CSS-adjacent words, partial idents.
        for input in [
            "mix",
            "color dodge",
            "color_dodge",
            "colordodge",
            "normal normal",
            "plus-lighter",
            "multiply;",
            "screen!",
        ] {
            assert!(
                parse_style_mix_blend_mode(input).is_err(),
                "{input:?} must not parse as a mix-blend-mode"
            );
        }
    }
    // ------------------------------------------------------ parse_style_cursor ---
    #[test]
    fn cursor_parses_every_keyword_and_round_trips() {
        for cursor in ALL_CURSORS {
            let printed = cursor.print_as_css_value();
            assert_eq!(
                parse_style_cursor(&printed).unwrap(),
                cursor,
                "{printed:?} did not round-trip"
            );
            assert_eq!(
                parse_style_cursor(&format!("\n{printed}  ")).unwrap(),
                cursor
            );
        }
        assert_eq!(StyleCursor::default(), StyleCursor::Default);
    }
    #[test]
    fn cursor_keyword_printing_is_injective() {
        // Two variants mapping to the same CSS ident would silently collapse on
        // re-parse; the round-trip test above cannot catch that on its own.
        let mut printed: Vec<String> = ALL_CURSORS
            .iter()
            .map(PrintAsCssValue::print_as_css_value)
            .collect();
        printed.sort();
        let count = printed.len();
        printed.dedup();
        assert_eq!(
            printed.len(),
            count,
            "two StyleCursor variants print the same ident"
        );
    }
    #[test]
    fn cursor_rejects_hostile_input() {
        for input in HOSTILE_KEYWORDS {
            assert!(
                parse_style_cursor(input).is_err(),
                "{input:?} must not parse as a cursor"
            );
        }
        for input in [
            "hand",       // legacy IE alias, deliberately unsupported
            "col resize", // space instead of hyphen
            "e_resize",
            "pointer pointer",
            "url(cursor.png)",
            "auto", // valid CSS, but not in the enum
        ] {
            assert!(
                parse_style_cursor(input).is_err(),
                "{input:?} must not parse as a cursor"
            );
        }
    }
    // -------------------------------------------------- parse_style_object_fit ---
    #[test]
    fn object_fit_parses_every_keyword_and_round_trips() {
        for fit in ALL_OBJECT_FIT {
            let printed = fit.print_as_css_value();
            assert_eq!(parse_style_object_fit(&printed).unwrap(), fit);
            assert_eq!(
                parse_style_object_fit(&format!("  {printed} ")).unwrap(),
                fit
            );
        }
        assert_eq!(StyleObjectFit::default(), StyleObjectFit::Fill);
    }
    #[test]
    fn object_fit_rejects_hostile_input() {
        for input in HOSTILE_KEYWORDS {
            assert!(
                parse_style_object_fit(input).is_err(),
                "{input:?} must not parse as an object-fit"
            );
        }
        for input in [
            "stretch",
            "scale_down",
            "scale down",
            "cover cover",
            "fill;",
        ] {
            assert!(
                parse_style_object_fit(input).is_err(),
                "{input:?} must not parse as an object-fit"
            );
        }
    }
    // -------------------------------------------- parse_style_text_orientation ---
    #[test]
    fn text_orientation_parses_every_keyword_and_round_trips() {
        for orientation in ALL_TEXT_ORIENTATION {
            let printed = orientation.print_as_css_value();
            assert_eq!(parse_style_text_orientation(&printed).unwrap(), orientation);
            assert_eq!(
                parse_style_text_orientation(&format!("\t{printed}\n")).unwrap(),
                orientation
            );
        }
        assert_eq!(StyleTextOrientation::default(), StyleTextOrientation::Mixed);
    }
    #[test]
    fn text_orientation_rejects_hostile_input() {
        for input in HOSTILE_KEYWORDS {
            assert!(
                parse_style_text_orientation(input).is_err(),
                "{input:?} must not parse as a text-orientation"
            );
        }
        for input in ["vertical", "sideways-right", "upright mixed", "mixed;"] {
            assert!(
                parse_style_text_orientation(input).is_err(),
                "{input:?} must not parse as a text-orientation"
            );
        }
    }
    // ----------------------------------------- keyword parsers, shared invariant ---
    #[test]
    fn keyword_parsers_are_case_sensitive() {
        // CSS idents are ASCII case-insensitive per spec, but every keyword
        // parser in this crate matches the lowercase form only. Pinned so that
        // adding case-folding is a deliberate, crate-wide change rather than an
        // accident in one parser.
        assert!(parse_style_visibility("VISIBLE").is_err());
        assert!(parse_style_mix_blend_mode("Multiply").is_err());
        assert!(parse_style_cursor("Pointer").is_err());
        assert!(parse_style_object_fit("COVER").is_err());
        assert!(parse_style_text_orientation("Upright").is_err());
        assert!(parse_style_aspect_ratio("AUTO").is_err());
    }
    #[test]
    fn keyword_parsers_do_not_hang_on_extremely_long_input() {
        let long = "a".repeat(500_000);
        assert!(parse_style_visibility(&long).is_err());
        assert!(parse_style_mix_blend_mode(&long).is_err());
        assert!(parse_style_cursor(&long).is_err());
        assert!(parse_style_object_fit(&long).is_err());
        assert!(parse_style_text_orientation(&long).is_err());
        // A valid keyword buried in 500k of padding is still just whitespace-
        // trimmed, so it parses; the padding must not be quadratic.
        let padded = format!("{}visible{}", " ".repeat(250_000), " ".repeat(250_000));
        assert_eq!(
            parse_style_visibility(&padded).unwrap(),
            StyleVisibility::Visible
        );
    }
    #[test]
    fn keyword_parsers_do_not_stack_overflow_on_nested_input() {
        let nested = format!("{}center{}", "(".repeat(10_000), ")".repeat(10_000));
        assert!(parse_style_visibility(&nested).is_err());
        assert!(parse_style_cursor(&nested).is_err());
        assert!(parse_style_object_fit(&nested).is_err());
        assert!(parse_style_object_position(&nested).is_err());
        assert!(parse_style_aspect_ratio(&nested).is_err());
    }
    // --------------------------------------------- parse_style_object_position ---
    #[test]
    fn object_position_parses_single_keywords() {
        use BackgroundPositionHorizontal as H;
        use BackgroundPositionVertical as V;
        for (input, h, v) in [
            ("center", H::Center, V::Center),
            ("left", H::Left, V::Center),
            ("right", H::Right, V::Center),
            ("top", H::Center, V::Top),
            ("bottom", H::Center, V::Bottom),
        ] {
            let parsed = parse_style_object_position(input).unwrap();
            assert_eq!(parsed.horizontal, h, "{input:?} horizontal");
            assert_eq!(parsed.vertical, v, "{input:?} vertical");
        }
    }
    #[test]
    fn object_position_parses_lengths_and_percentages() {
        let px = parse_style_object_position("10px 20px").unwrap();
        assert_eq!(
            px.horizontal,
            BackgroundPositionHorizontal::Exact(PixelValue::px(10.0))
        );
        assert_eq!(
            px.vertical,
            BackgroundPositionVertical::Exact(PixelValue::px(20.0))
        );
        let pct = parse_style_object_position("50% 50%").unwrap();
        assert_eq!(
            pct.horizontal,
            BackgroundPositionHorizontal::Exact(PixelValue::percent(50.0))
        );
        assert_eq!(
            pct.vertical,
            BackgroundPositionVertical::Exact(PixelValue::percent(50.0))
        );
        // A single length applies to *both* axes.
        let single = parse_style_object_position("25%").unwrap();
        assert_eq!(
            single.horizontal,
            BackgroundPositionHorizontal::Exact(PixelValue::percent(25.0))
        );
        assert_eq!(
            single.vertical,
            BackgroundPositionVertical::Exact(PixelValue::percent(25.0))
        );
        // Mixed keyword + length, both orders.
        assert_eq!(
            parse_style_object_position("left 25%").unwrap(),
            StyleObjectPosition {
                horizontal: BackgroundPositionHorizontal::Left,
                vertical: BackgroundPositionVertical::Exact(PixelValue::percent(25.0)),
            }
        );
        assert_eq!(
            parse_style_object_position("25% top").unwrap(),
            StyleObjectPosition {
                horizontal: BackgroundPositionHorizontal::Exact(PixelValue::percent(25.0)),
                vertical: BackgroundPositionVertical::Top,
            }
        );
    }
    #[test]
    fn object_position_collapses_internal_whitespace() {
        // `split_whitespace` means any run of blanks separates the components.
        let expected = parse_style_object_position("left top").unwrap();
        for input in ["left  top", "left\ttop", "  left \n top  ", "left\r\ntop"] {
            assert_eq!(
                parse_style_object_position(input).unwrap(),
                expected,
                "{input:?} should be equivalent to \"left top\""
            );
        }
    }
    #[test]
    fn object_position_rejects_wrong_component_counts_and_garbage() {
        for input in [
            "",
            "   ",
            "\t\n",
            "left top center",
            "10px 20px 30px",
            "center center center center",
            "invalid",
            "left left", // second component must be a vertical keyword or a length
            "top top",   // first component must be a horizontal keyword or a length
            "left,top",  // comma is not a component separator
            ";",
            "\u{1F600}",
            "\u{1F600} \u{1F600}",
        ] {
            assert!(
                parse_style_object_position(input).is_err(),
                "{input:?} must not parse as an object-position"
            );
        }
    }
    #[test]
    fn object_position_extreme_lengths_do_not_panic() {
        // `parse_pixel_value` accepts bare floats (incl. NaN/inf) and saturates
        // them in the fixed-point cast — characterized in pixel.rs. All that is
        // asserted here is that object-position does not panic on them.
        for input in [
            "NaN NaN",
            "inf inf",
            "-inf",
            "1e39px",
            "-1e39px",
            "340282350000000000000000000000000000000px",
        ] {
            let _ = parse_style_object_position(input);
        }
        let long = format!("{}px", "9".repeat(100_000));
        let _ = parse_style_object_position(&long);
    }
    #[test]
    fn object_position_round_trips_through_print_as_css_value() {
        use BackgroundPositionHorizontal as H;
        use BackgroundPositionVertical as V;
        let horizontals = [
            H::Left,
            H::Center,
            H::Right,
            H::Exact(PixelValue::percent(25.0)),
        ];
        let verticals = [V::Top, V::Center, V::Bottom, V::Exact(PixelValue::px(30.0))];
        for horizontal in horizontals {
            for vertical in verticals {
                let position = StyleObjectPosition {
                    horizontal,
                    vertical,
                };
                let printed = position.print_as_css_value();
                let reparsed = parse_style_object_position(&printed).unwrap_or_else(|e| {
                    panic!("{position:?} printed as {printed:?}, which failed to re-parse: {e}")
                });
                assert_eq!(reparsed, position, "{printed:?} did not round-trip");
            }
        }
        // The documented initial value is `50% 50%`.
        let default = StyleObjectPosition::default();
        assert_eq!(default.print_as_css_value(), "50% 50%");
        assert_eq!(parse_style_object_position("50% 50%").unwrap(), default);
        assert_eq!(
            parse_style_object_position("center")
                .unwrap()
                .print_as_css_value(),
            "center center"
        );
    }
    // ------------------------------------------------------ aspect_f32_to_u32 ---
    #[test]
    fn aspect_f32_to_u32_saturates_instead_of_panicking() {
        // Zero / truncation.
        assert_eq!(aspect_f32_to_u32(0.0), 0);
        assert_eq!(aspect_f32_to_u32(-0.0), 0);
        assert_eq!(aspect_f32_to_u32(0.9), 0);
        assert_eq!(aspect_f32_to_u32(1.0), 1);
        assert_eq!(aspect_f32_to_u32(1.9), 1);
        assert_eq!(aspect_f32_to_u32(f32::MIN_POSITIVE), 0);
        // Negatives saturate to 0 (`as` is a saturating cast since Rust 1.45).
        assert_eq!(aspect_f32_to_u32(-1.0), 0);
        assert_eq!(aspect_f32_to_u32(-0.5), 0);
        assert_eq!(aspect_f32_to_u32(-1e30), 0);
        assert_eq!(aspect_f32_to_u32(f32::MIN), 0);
        assert_eq!(aspect_f32_to_u32(f32::NEG_INFINITY), 0);
        // Above u32::MAX saturates to u32::MAX.
        assert_eq!(aspect_f32_to_u32(f32::MAX), u32::MAX);
        assert_eq!(aspect_f32_to_u32(f32::INFINITY), u32::MAX);
        assert_eq!(aspect_f32_to_u32(1e30), u32::MAX);
        // `u32::MAX as f32` rounds *up* to 2^32, so it saturates back down.
        assert_eq!(aspect_f32_to_u32(u32::MAX as f32), u32::MAX);
        // NaN is defined to be 0, not UB and not a panic.
        assert_eq!(aspect_f32_to_u32(f32::NAN), 0);
        assert_eq!(aspect_f32_to_u32(-f32::NAN), 0);
        // The largest value the parser can hand it (100_000 * 1000) fits exactly.
        assert_eq!(aspect_f32_to_u32(100_000.0 * 1000.0), 100_000_000);
    }
    #[test]
    fn aspect_f32_to_u32_is_usable_in_const_context() {
        const TRUNCATED: u32 = aspect_f32_to_u32(1.999);
        const SATURATED: u32 = aspect_f32_to_u32(f32::INFINITY);
        const NEGATIVE: u32 = aspect_f32_to_u32(-5.0);
        const NOT_A_NUMBER: u32 = aspect_f32_to_u32(f32::NAN);
        assert_eq!(
            (TRUNCATED, SATURATED, NEGATIVE, NOT_A_NUMBER),
            (1, u32::MAX, 0, 0)
        );
    }
    // ------------------------------------------------ parse_style_aspect_ratio ---
    #[test]
    fn aspect_ratio_parses_valid_forms() {
        assert_eq!(
            parse_style_aspect_ratio("auto").unwrap(),
            StyleAspectRatio::Auto
        );
        assert_eq!(StyleAspectRatio::default(), StyleAspectRatio::Auto);
        for input in ["16 / 9", "16/9", "16 /9", "16/ 9", "  16  /  9  "] {
            assert_eq!(
                parse_style_aspect_ratio(input).unwrap(),
                StyleAspectRatio::Ratio(AspectRatioValue {
                    width: 16000,
                    height: 9000
                }),
                "{input:?} should parse as 16/9"
            );
        }
        // A bare number is `<number> / 1`, stored as fixed-point * 1000.
        assert_eq!(
            parse_style_aspect_ratio("1").unwrap(),
            StyleAspectRatio::Ratio(AspectRatioValue {
                width: 1000,
                height: 1000
            })
        );
        assert_eq!(
            parse_style_aspect_ratio("1.5").unwrap(),
            StyleAspectRatio::Ratio(AspectRatioValue {
                width: 1500,
                height: 1000
            })
        );
        // Boundary of the documented range: 100_000 is accepted, just above is not.
        assert_eq!(
            parse_style_aspect_ratio("100000").unwrap(),
            StyleAspectRatio::Ratio(AspectRatioValue {
                width: 100_000_000,
                height: 1000
            })
        );
        assert!(parse_style_aspect_ratio("100001").is_err());
        assert!(parse_style_aspect_ratio("100000.1 / 1").is_err());
        assert!(parse_style_aspect_ratio("1 / 100001").is_err());
    }
    #[test]
    fn aspect_ratio_rejects_non_positive_and_malformed_input() {
        for input in [
            "",
            "   ",
            "\t\n",
            "abc",
            "auto / auto",
            "16 / 9 / 4",
            "1/2/3",
            "/",
            "//",
            "/9",
            "16/",
            "16 9",
            ";",
            "16,9",
            "\u{1F600}",
            "\u{1F600}/\u{1F600}",
        ] {
            assert!(
                parse_style_aspect_ratio(input).is_err(),
                "{input:?} must not parse as an aspect-ratio"
            );
        }
        // Zero and negative components are explicitly rejected.
        for input in [
            "0", "0 / 1", "1 / 0", "0/0", "-0", "-0 / 1", "1 / -0", "-1 / 1", "-1", "-1.5",
        ] {
            assert!(
                parse_style_aspect_ratio(input).is_err(),
                "{input:?} must not parse as an aspect-ratio"
            );
        }
        // Infinities exceed the 100_000 bound (or are non-positive).
        for input in [
            "inf", "inf / 1", "1 / inf", "-inf", "-inf / 1", "1e39", "1e39 / 1",
        ] {
            assert!(
                parse_style_aspect_ratio(input).is_err(),
                "{input:?} should be rejected: out of the [0, 100_000] range"
            );
        }
    }
    #[test]
    fn aspect_ratio_extremely_long_input_terminates() {
        let long = "9".repeat(100_000);
        assert!(parse_style_aspect_ratio(&long).is_err());
        assert!(parse_style_aspect_ratio(&format!("{long}/{long}")).is_err());
        // 100k slashes: `find('/')` hits the first one, both sides fail to parse.
        let slashes = "/".repeat(100_000);
        assert!(parse_style_aspect_ratio(&slashes).is_err());
    }
    #[test]
    fn aspect_ratio_auto_round_trips() {
        let printed = StyleAspectRatio::Auto.print_as_css_value();
        assert_eq!(printed, "auto");
        assert_eq!(
            parse_style_aspect_ratio(&printed).unwrap(),
            StyleAspectRatio::Auto
        );
    }
    // ------------------------------------------- error types: to_contained/to_shared ---
    #[test]
    fn opacity_parse_error_round_trips_through_the_owned_form() {
        let errors = [
            OpacityParseError::ParsePercentage(
                PercentageParseError::ValueParseErr(CssParseFloatError::Empty),
                "",
            ),
            OpacityParseError::ParsePercentage(
                PercentageParseError::ValueParseErr(CssParseFloatError::Invalid),
                "abc",
            ),
            OpacityParseError::ParsePercentage(PercentageParseError::NoPercentSign, "0.5"),
            OpacityParseError::ParsePercentage(
                PercentageParseError::InvalidUnit(String::from("px").into()),
                "5px",
            ),
            OpacityParseError::OutOfRange("1.5"),
            OpacityParseError::OutOfRange(""),
            OpacityParseError::OutOfRange("\u{1F600}"),
        ];
        for error in errors {
            let owned = error.to_contained();
            assert_eq!(owned.to_shared(), error, "{error:?} did not round-trip");
            assert_eq!(owned.to_shared().to_contained(), owned);
            let shown = error.to_string();
            assert!(!shown.is_empty(), "{error:?} renders as an empty message");
            // `impl_debug_as_display` forwards Debug to Display.
            assert_eq!(format!("{error:?}"), shown);
        }
    }
    #[test]
    fn opacity_parse_error_to_contained_copies_the_borrowed_input() {
        // The owned form must not alias the (possibly temporary) input slice.
        let owned = {
            let input = String::from("1.5");
            parse_style_opacity(&input).unwrap_err().to_contained()
        };
        assert_eq!(
            owned,
            OpacityParseErrorOwned::OutOfRange(String::from("1.5").into())
        );
        assert!(owned.to_shared().to_string().contains("1.5"));
    }
    #[test]
    fn keyword_parse_errors_round_trip_through_the_owned_form() {
        // All four `InvalidValueErr`-backed error types, over hostile payloads.
        for payload in ["", "junk", "  ", "\u{1F600}", "a\0b", "\u{0665}"] {
            let visibility = StyleVisibilityParseError::InvalidValue(InvalidValueErr(payload));
            assert_eq!(visibility.to_contained().to_shared(), visibility);
            assert!(!visibility.to_string().is_empty());
            assert_eq!(format!("{visibility:?}"), visibility.to_string());
            let blend = MixBlendModeParseError::InvalidValue(InvalidValueErr(payload));
            assert_eq!(blend.to_contained().to_shared(), blend);
            assert!(!blend.to_string().is_empty());
            let cursor = CursorParseError::InvalidValue(InvalidValueErr(payload));
            assert_eq!(cursor.to_contained().to_shared(), cursor);
            assert!(!cursor.to_string().is_empty());
            // The `&str`-backed error types.
            let object_fit = StyleObjectFitParseError::InvalidValue(payload);
            assert_eq!(object_fit.to_contained().to_shared(), object_fit);
            assert!(!object_fit.to_string().is_empty());
            let orientation = StyleTextOrientationParseError::InvalidValue(payload);
            assert_eq!(orientation.to_contained().to_shared(), orientation);
            assert!(!orientation.to_string().is_empty());
            let position = StyleObjectPositionParseError::InvalidValue(payload);
            assert_eq!(position.to_contained().to_shared(), position);
            assert!(!position.to_string().is_empty());
            let ratio = StyleAspectRatioParseError::InvalidValue(payload);
            assert_eq!(ratio.to_contained().to_shared(), ratio);
            assert!(!ratio.to_string().is_empty());
        }
    }
    #[test]
    fn parse_errors_quote_the_offending_input() {
        // The rejected value has to survive into the message, or authors cannot
        // find the bad declaration.
        assert!(parse_style_visibility("show")
            .unwrap_err()
            .to_string()
            .contains("show"));
        assert!(parse_style_mix_blend_mode("mix")
            .unwrap_err()
            .to_string()
            .contains("mix"));
        assert!(parse_style_cursor("hand")
            .unwrap_err()
            .to_string()
            .contains("hand"));
        assert!(parse_style_object_fit("stretch")
            .unwrap_err()
            .to_string()
            .contains("stretch"));
        assert!(parse_style_text_orientation("vertical")
            .unwrap_err()
            .to_string()
            .contains("vertical"));
        assert!(parse_style_object_position("nope")
            .unwrap_err()
            .to_string()
            .contains("nope"));
        assert!(parse_style_aspect_ratio("nope")
            .unwrap_err()
            .to_string()
            .contains("nope"));
        assert!(parse_style_opacity("1.5")
            .unwrap_err()
            .to_string()
            .contains("1.5"));
    }
    #[test]
    fn parse_errors_report_the_trimmed_input_not_the_raw_slice() {
        // Every keyword parser trims *before* constructing the error, so the
        // message never contains the caller's padding.
        let shown = parse_style_cursor("  hand  ").unwrap_err().to_string();
        assert!(
            shown.contains("\"hand\""),
            "expected the trimmed value, got {shown:?}"
        );
        // ...except `parse_style_opacity`, which passes the *untrimmed* input to
        // the error. Pinned so the inconsistency is visible.
        let shown = parse_style_opacity("  1.5  ").unwrap_err().to_string();
        assert!(
            shown.contains("\"  1.5  \""),
            "expected the raw value, got {shown:?}"
        );
    }
    #[test]
    fn owned_error_forms_are_independent_of_the_source_buffer() {
        // `to_contained` must deep-copy: the owned error has to outlive the
        // String it was parsed from.
        let owned = {
            let input = String::from("stretch");
            parse_style_object_fit(&input).unwrap_err().to_contained()
        };
        assert_eq!(
            owned,
            StyleObjectFitParseErrorOwned::InvalidValue(String::from("stretch").into())
        );
        assert!(owned.to_shared().to_string().contains("stretch"));
    }
    // ------------------------------------------------------------ known bugs ---
    //
    // The tests below assert the behaviour these functions must have; they are
    // regression guards for bugs that have since been fixed.
    #[test]
    fn known_bug_opacity_multibyte_numeric_char_panics() {
        // `char::is_numeric()` is true for Nd/Nl/No, including multi-byte chars
        // like '½' (U+00BD) and '٥' (U+0665). `parse_percentage_value` records
        // the *start* byte index of the last such char and then slices at
        // `split_pos + 1`, which lands inside the codepoint => the slice panics.
        //
        // `opacity: ½` in any author stylesheet therefore panics the CSS parser.
        // See `known_bug_percentage_multibyte_numeric_char_panics` in length.rs.
        for input in ["\u{00BD}", "\u{00BD}%", "0.5\u{0665}", "\u{FF15}%"] {
            assert!(
                parse_style_opacity(input).is_err(),
                "{input:?} should be rejected, not panic"
            );
        }
    }
    #[test]
    fn known_bug_aspect_ratio_nan_bypasses_the_range_guards() {
        // Every guard in `parse_style_aspect_ratio` is a float comparison
        // (`h <= 0.0 || w <= 0.0 || w > 100_000.0 || h > 100_000.0`), and every
        // comparison against NaN is false — so a NaN component sails through and
        // `aspect_f32_to_u32(NaN)` turns it into 0. The parser explicitly rejects
        // "0 / 1", but happily returns `Ratio { width: 0, height: 1000 }` for
        // "NaN", which is a division by zero waiting to happen in layout.
        for input in ["NaN", "nan", "NaN / 1", "1 / NaN", "nan/nan", "-NaN"] {
            assert!(
                parse_style_aspect_ratio(input).is_err(),
                "{input:?} should be rejected, but parsed as {:?}",
                parse_style_aspect_ratio(input)
            );
        }
    }
    #[test]
    fn known_bug_aspect_ratio_tiny_positive_values_round_down_to_zero() {
        // `w > 0.0` passes, but `(w * 1000.0).round()` is 0 for anything below
        // 0.0005 — so a positive ratio silently becomes the degenerate 0 that the
        // guard exists to prevent.
        for input in ["0.0001", "0.0004 / 1", "1 / 0.0001", "1e-10"] {
            let Ok(StyleAspectRatio::Ratio(ratio)) = parse_style_aspect_ratio(input) else {
                continue; // rejected outright — that is the fix
            };
            assert!(
                ratio.width > 0 && ratio.height > 0,
                "{input:?} produced the degenerate ratio {ratio:?}"
            );
        }
    }
    #[test]
    fn known_bug_aspect_ratio_does_not_survive_a_print_reparse_cycle() {
        // `Ratio { width: 16000, height: 9000 }` (i.e. 16/9) prints as
        // "16000 / 9000", so every print/parse cycle multiplies both components
        // by 1000. One cycle changes the stored value; two cycles exceed the
        // 100_000 bound and fail to parse at all.
        let ratio = parse_style_aspect_ratio("16 / 9").unwrap();
        let printed = ratio.print_as_css_value();
        assert_eq!(
            printed, "16 / 9",
            "printed the fixed-point form: {printed:?}"
        );
        assert_eq!(parse_style_aspect_ratio(&printed).unwrap(), ratio);
    }
    #[test]
    fn known_bug_object_position_rejects_reversed_keyword_pairs() {
        // `<position>` is `[left|center|right] || [top|center|bottom]` — the `||`
        // means either order is valid, so `object-position: top left` is legal
        // CSS. The parser only ever reads parts[0] as the horizontal component,
        // so it hands "top" to `parse_pixel_value` and fails.
        assert_eq!(
            parse_style_object_position("top left").unwrap(),
            parse_style_object_position("left top").unwrap()
        );
        assert_eq!(
            parse_style_object_position("bottom right").unwrap(),
            parse_style_object_position("right bottom").unwrap()
        );
    }
}