1
//! CSS properties for flexbox layout.
2

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

            
6
use crate::{
7
    codegen::format::FormatAsRustCode,
8
    corety::AzString,
9
    props::{
10
        basic::{
11
            error::ParseFloatErrorWithInput,
12
            length::{parse_float_value, FloatValue},
13
        },
14
        formatter::PrintAsCssValue,
15
    },
16
};
17

            
18
// --- flex-grow ---
19

            
20
/// Represents a `flex-grow` attribute, which dictates what proportion of the
21
/// remaining space in the flex container should be assigned to the item.
22
/// Default: 0
23
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
24
#[repr(C)]
25
pub struct LayoutFlexGrow {
26
    pub inner: FloatValue,
27
}
28

            
29
impl core::fmt::Debug for LayoutFlexGrow {
30
26
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
31
26
        write!(f, "{}", self.inner.get())
32
26
    }
33
}
34

            
35
impl Default for LayoutFlexGrow {
36
1
    fn default() -> Self {
37
1
        Self {
38
1
            inner: FloatValue::const_new(0),
39
1
        }
40
1
    }
41
}
42

            
43
impl PrintAsCssValue for LayoutFlexGrow {
44
7
    fn print_as_css_value(&self) -> String {
45
7
        format!("{}", self.inner)
46
7
    }
47
}
48

            
49
impl LayoutFlexGrow {
50
    #[must_use]
51
23
    pub fn new(value: isize) -> Self {
52
23
        Self {
53
23
            inner: FloatValue::new(crate::cast::isize_to_f32(value)),
54
23
        }
55
23
    }
56

            
57
    #[must_use]
58
473909
    pub const fn const_new(value: isize) -> Self {
59
473909
        Self {
60
473909
            inner: FloatValue::const_new(value),
61
473909
        }
62
473909
    }
63

            
64
    #[must_use]
65
20
    pub fn interpolate(&self, other: &Self, t: f32) -> Self {
66
20
        Self {
67
20
            inner: self.inner.interpolate(&other.inner, t),
68
20
        }
69
20
    }
70
}
71

            
72
#[cfg(feature = "parser")]
73
#[derive(Clone, PartialEq, Eq)]
74
pub enum FlexGrowParseError<'a> {
75
    ParseFloat(ParseFloatError, &'a str),
76
    NegativeValue(&'a str),
77
}
78

            
79
#[cfg(feature = "parser")]
80
impl_debug_as_display!(FlexGrowParseError<'a>);
81
#[cfg(feature = "parser")]
82
impl_display! { FlexGrowParseError<'a>, {
83
    ParseFloat(e, s) => format!("Invalid flex-grow value: \"{}\". Reason: {}", s, e),
84
    NegativeValue(s) => format!("Invalid flex-grow value: \"{}\". Flex-grow cannot be negative", s),
85
}}
86

            
87
#[cfg(feature = "parser")]
88
#[derive(Debug, Clone, PartialEq, Eq)]
89
#[repr(C, u8)]
90
pub enum FlexGrowParseErrorOwned {
91
    ParseFloat(ParseFloatErrorWithInput),
92
    NegativeValue(AzString),
93
}
94

            
95
#[cfg(feature = "parser")]
96
impl FlexGrowParseError<'_> {
97
    #[must_use]
98
16
    pub fn to_contained(&self) -> FlexGrowParseErrorOwned {
99
16
        match self {
100
11
            FlexGrowParseError::ParseFloat(e, s) => {
101
11
                FlexGrowParseErrorOwned::ParseFloat(ParseFloatErrorWithInput {
102
11
                    error: e.clone().into(),
103
11
                    input: (*s).to_string().into(),
104
11
                })
105
            }
106
5
            FlexGrowParseError::NegativeValue(s) => {
107
5
                FlexGrowParseErrorOwned::NegativeValue((*s).to_string().into())
108
            }
109
        }
110
16
    }
111
}
112

            
113
#[cfg(feature = "parser")]
114
impl FlexGrowParseErrorOwned {
115
    #[must_use]
116
17
    pub fn to_shared(&self) -> FlexGrowParseError<'_> {
117
17
        match self {
118
11
            Self::ParseFloat(e) => {
119
11
                FlexGrowParseError::ParseFloat(e.error.to_std(), e.input.as_str())
120
            }
121
6
            Self::NegativeValue(s) => FlexGrowParseError::NegativeValue(s.as_str()),
122
        }
123
17
    }
124
}
125

            
126
#[cfg(feature = "parser")]
127
/// # Errors
128
///
129
/// Returns an error if `input` is not a valid CSS `flex-grow` value.
130
4144
pub fn parse_layout_flex_grow(input: &str) -> Result<LayoutFlexGrow, FlexGrowParseError<'_>> {
131
4144
    match parse_float_value(input) {
132
4108
        Ok(o) => {
133
4108
            if o.get() < 0.0 {
134
5
                Err(FlexGrowParseError::NegativeValue(input))
135
            } else {
136
4103
                Ok(LayoutFlexGrow { inner: o })
137
            }
138
        }
139
36
        Err(e) => Err(FlexGrowParseError::ParseFloat(e, input)),
140
    }
141
4144
}
142

            
143
// --- flex-shrink ---
144

            
145
/// Represents a `flex-shrink` attribute, which dictates what proportion of
146
/// the negative space in the flex container should be removed from the item.
147
/// Default: 1
148
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
149
#[repr(C)]
150
pub struct LayoutFlexShrink {
151
    pub inner: FloatValue,
152
}
153

            
154
impl core::fmt::Debug for LayoutFlexShrink {
155
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
156
        write!(f, "{}", self.inner.get())
157
    }
158
}
159

            
160
impl Default for LayoutFlexShrink {
161
1
    fn default() -> Self {
162
1
        Self {
163
1
            inner: FloatValue::const_new(1),
164
1
        }
165
1
    }
166
}
167

            
168
impl PrintAsCssValue for LayoutFlexShrink {
169
7
    fn print_as_css_value(&self) -> String {
170
7
        format!("{}", self.inner)
171
7
    }
172
}
173

            
174
impl LayoutFlexShrink {
175
    #[must_use]
176
9
    pub fn interpolate(&self, other: &Self, t: f32) -> Self {
177
9
        Self {
178
9
            inner: self.inner.interpolate(&other.inner, t),
179
9
        }
180
9
    }
181
}
182

            
183
#[cfg(feature = "parser")]
184
#[derive(Clone, PartialEq, Eq)]
185
pub enum FlexShrinkParseError<'a> {
186
    ParseFloat(ParseFloatError, &'a str),
187
    NegativeValue(&'a str),
188
}
189

            
190
#[cfg(feature = "parser")]
191
impl_debug_as_display!(FlexShrinkParseError<'a>);
192
#[cfg(feature = "parser")]
193
impl_display! { FlexShrinkParseError<'a>, {
194
    ParseFloat(e, s) => format!("Invalid flex-shrink value: \"{}\". Reason: {}", s, e),
195
    NegativeValue(s) => format!("Invalid flex-shrink value: \"{}\". Flex-shrink cannot be negative", s),
196
}}
197

            
198
#[cfg(feature = "parser")]
199
#[derive(Debug, Clone, PartialEq, Eq)]
200
#[repr(C, u8)]
201
pub enum FlexShrinkParseErrorOwned {
202
    ParseFloat(ParseFloatErrorWithInput),
203
    NegativeValue(AzString),
204
}
205

            
206
#[cfg(feature = "parser")]
207
impl FlexShrinkParseError<'_> {
208
    #[must_use]
209
11
    pub fn to_contained(&self) -> FlexShrinkParseErrorOwned {
210
11
        match self {
211
5
            FlexShrinkParseError::ParseFloat(e, s) => {
212
5
                FlexShrinkParseErrorOwned::ParseFloat(ParseFloatErrorWithInput {
213
5
                    error: e.clone().into(),
214
5
                    input: (*s).to_string().into(),
215
5
                })
216
            }
217
6
            FlexShrinkParseError::NegativeValue(s) => {
218
6
                FlexShrinkParseErrorOwned::NegativeValue((*s).to_string().into())
219
            }
220
        }
221
11
    }
222
}
223

            
224
#[cfg(feature = "parser")]
225
impl FlexShrinkParseErrorOwned {
226
    #[must_use]
227
12
    pub fn to_shared(&self) -> FlexShrinkParseError<'_> {
228
12
        match self {
229
5
            Self::ParseFloat(e) => {
230
5
                FlexShrinkParseError::ParseFloat(e.error.to_std(), e.input.as_str())
231
            }
232
7
            Self::NegativeValue(s) => FlexShrinkParseError::NegativeValue(s.as_str()),
233
        }
234
12
    }
235
}
236

            
237
#[cfg(feature = "parser")]
238
/// # Errors
239
///
240
/// Returns an error if `input` is not a valid CSS `flex-shrink` value.
241
1754
pub fn parse_layout_flex_shrink(input: &str) -> Result<LayoutFlexShrink, FlexShrinkParseError<'_>> {
242
1754
    match parse_float_value(input) {
243
1719
        Ok(o) => {
244
1719
            if o.get() < 0.0 {
245
5
                Err(FlexShrinkParseError::NegativeValue(input))
246
            } else {
247
1714
                Ok(LayoutFlexShrink { inner: o })
248
            }
249
        }
250
35
        Err(e) => Err(FlexShrinkParseError::ParseFloat(e, input)),
251
    }
252
1754
}
253

            
254
// --- flex-direction ---
255

            
256
/// Represents a `flex-direction` attribute, which establishes the main-axis,
257
/// thus defining the direction flex items are placed in the flex container.
258
/// Default: `Row`
259
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
260
#[repr(C)]
261
#[derive(Default)]
262
pub enum LayoutFlexDirection {
263
    #[default]
264
    Row,
265
    RowReverse,
266
    Column,
267
    ColumnReverse,
268
}
269

            
270
/// Represents the main or cross axis of a flex container.
271
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
272
#[repr(C)]
273
pub enum LayoutAxis {
274
    Horizontal,
275
    Vertical,
276
}
277

            
278
impl LayoutFlexDirection {
279
    #[must_use]
280
17
    pub const fn get_axis(&self) -> LayoutAxis {
281
17
        match self {
282
9
            Self::Row | Self::RowReverse => LayoutAxis::Horizontal,
283
8
            Self::Column | Self::ColumnReverse => LayoutAxis::Vertical,
284
        }
285
17
    }
286

            
287
    #[must_use]
288
13
    pub const fn is_reverse(&self) -> bool {
289
13
        matches!(self, Self::RowReverse | Self::ColumnReverse)
290
13
    }
291
}
292

            
293
impl PrintAsCssValue for LayoutFlexDirection {
294
134
    fn print_as_css_value(&self) -> String {
295
134
        String::from(match self {
296
1
            Self::Row => "row",
297
1
            Self::RowReverse => "row-reverse",
298
131
            Self::Column => "column",
299
1
            Self::ColumnReverse => "column-reverse",
300
        })
301
134
    }
302
}
303

            
304
#[cfg(feature = "parser")]
305
#[derive(Clone, PartialEq, Eq)]
306
pub enum FlexDirectionParseError<'a> {
307
    InvalidValue(&'a str),
308
}
309

            
310
#[cfg(feature = "parser")]
311
impl_debug_as_display!(FlexDirectionParseError<'a>);
312
#[cfg(feature = "parser")]
313
impl_display! { FlexDirectionParseError<'a>, {
314
    InvalidValue(s) => format!("Invalid flex-direction value: \"{}\"", s),
315
}}
316

            
317
#[cfg(feature = "parser")]
318
#[derive(Debug, Clone, PartialEq, Eq)]
319
#[repr(C, u8)]
320
pub enum FlexDirectionParseErrorOwned {
321
    InvalidValue(AzString),
322
}
323

            
324
#[cfg(feature = "parser")]
325
impl FlexDirectionParseError<'_> {
326
    #[must_use]
327
6
    pub fn to_contained(&self) -> FlexDirectionParseErrorOwned {
328
6
        match self {
329
6
            Self::InvalidValue(s) => {
330
6
                FlexDirectionParseErrorOwned::InvalidValue((*s).to_string().into())
331
            }
332
        }
333
6
    }
334
}
335

            
336
#[cfg(feature = "parser")]
337
impl FlexDirectionParseErrorOwned {
338
    #[must_use]
339
7
    pub fn to_shared(&self) -> FlexDirectionParseError<'_> {
340
7
        match self {
341
7
            Self::InvalidValue(s) => FlexDirectionParseError::InvalidValue(s.as_str()),
342
        }
343
7
    }
344
}
345

            
346
#[cfg(feature = "parser")]
347
/// # Errors
348
///
349
/// Returns an error if `input` is not a valid CSS `flex-direction` value.
350
46715
pub fn parse_layout_flex_direction(
351
46715
    input: &str,
352
46715
) -> Result<LayoutFlexDirection, FlexDirectionParseError<'_>> {
353
46715
    match input.trim() {
354
46715
        "row" => Ok(LayoutFlexDirection::Row),
355
7245
        "row-reverse" => Ok(LayoutFlexDirection::RowReverse),
356
7243
        "column" => Ok(LayoutFlexDirection::Column),
357
24
        "column-reverse" => Ok(LayoutFlexDirection::ColumnReverse),
358
22
        _ => Err(FlexDirectionParseError::InvalidValue(input)),
359
    }
360
46715
}
361

            
362
// --- flex-wrap ---
363

            
364
/// Represents a `flex-wrap` attribute, which determines whether flex items
365
/// are forced onto one line or can wrap onto multiple lines.
366
/// Default: `NoWrap`
367
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
368
#[repr(C)]
369
#[derive(Default)]
370
pub enum LayoutFlexWrap {
371
    Wrap,
372
    #[default]
373
    NoWrap,
374
    WrapReverse,
375
}
376

            
377
impl PrintAsCssValue for LayoutFlexWrap {
378
3
    fn print_as_css_value(&self) -> String {
379
3
        String::from(match self {
380
1
            Self::Wrap => "wrap",
381
1
            Self::NoWrap => "nowrap",
382
1
            Self::WrapReverse => "wrap-reverse",
383
        })
384
3
    }
385
}
386

            
387
#[cfg(feature = "parser")]
388
#[derive(Clone, PartialEq, Eq)]
389
pub enum FlexWrapParseError<'a> {
390
    InvalidValue(&'a str),
391
}
392

            
393
#[cfg(feature = "parser")]
394
impl_debug_as_display!(FlexWrapParseError<'a>);
395
#[cfg(feature = "parser")]
396
impl_display! { FlexWrapParseError<'a>, {
397
    InvalidValue(s) => format!("Invalid flex-wrap value: \"{}\"", s),
398
}}
399

            
400
#[cfg(feature = "parser")]
401
#[derive(Debug, Clone, PartialEq, Eq)]
402
#[repr(C, u8)]
403
pub enum FlexWrapParseErrorOwned {
404
    InvalidValue(AzString),
405
}
406

            
407
#[cfg(feature = "parser")]
408
impl FlexWrapParseError<'_> {
409
    #[must_use]
410
6
    pub fn to_contained(&self) -> FlexWrapParseErrorOwned {
411
6
        match self {
412
6
            Self::InvalidValue(s) => FlexWrapParseErrorOwned::InvalidValue((*s).to_string().into()),
413
        }
414
6
    }
415
}
416

            
417
#[cfg(feature = "parser")]
418
impl FlexWrapParseErrorOwned {
419
    #[must_use]
420
7
    pub fn to_shared(&self) -> FlexWrapParseError<'_> {
421
7
        match self {
422
7
            Self::InvalidValue(s) => FlexWrapParseError::InvalidValue(s.as_str()),
423
        }
424
7
    }
425
}
426

            
427
#[cfg(feature = "parser")]
428
/// # Errors
429
///
430
/// Returns an error if `input` is not a valid CSS `flex-wrap` value.
431
62
pub fn parse_layout_flex_wrap(input: &str) -> Result<LayoutFlexWrap, FlexWrapParseError<'_>> {
432
62
    match input.trim() {
433
62
        "wrap" => Ok(LayoutFlexWrap::Wrap),
434
25
        "nowrap" => Ok(LayoutFlexWrap::NoWrap),
435
23
        "wrap-reverse" => Ok(LayoutFlexWrap::WrapReverse),
436
21
        _ => Err(FlexWrapParseError::InvalidValue(input)),
437
    }
438
62
}
439

            
440
// --- justify-content ---
441

            
442
/// Represents a `justify-content` attribute, which defines the alignment
443
/// along the main axis.
444
/// Default: `Start` (flex-start)
445
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
446
#[repr(C)]
447
#[derive(Default)]
448
pub enum LayoutJustifyContent {
449
    FlexStart,
450
    FlexEnd,
451
    #[default]
452
    Start,
453
    End,
454
    Center,
455
    SpaceBetween,
456
    SpaceAround,
457
    SpaceEvenly,
458
}
459

            
460
impl PrintAsCssValue for LayoutJustifyContent {
461
8
    fn print_as_css_value(&self) -> String {
462
8
        String::from(match self {
463
1
            Self::Start => "start",
464
1
            Self::End => "end",
465
1
            Self::FlexStart => "flex-start",
466
1
            Self::FlexEnd => "flex-end",
467
1
            Self::Center => "center",
468
1
            Self::SpaceBetween => "space-between",
469
1
            Self::SpaceAround => "space-around",
470
1
            Self::SpaceEvenly => "space-evenly",
471
        })
472
8
    }
473
}
474

            
475
#[cfg(feature = "parser")]
476
#[derive(Clone, PartialEq, Eq)]
477
pub enum JustifyContentParseError<'a> {
478
    InvalidValue(&'a str),
479
}
480

            
481
#[cfg(feature = "parser")]
482
impl_debug_as_display!(JustifyContentParseError<'a>);
483
#[cfg(feature = "parser")]
484
impl_display! { JustifyContentParseError<'a>, {
485
    InvalidValue(s) => format!("Invalid justify-content value: \"{}\"", s),
486
}}
487

            
488
#[cfg(feature = "parser")]
489
#[derive(Debug, Clone, PartialEq, Eq)]
490
#[repr(C, u8)]
491
pub enum JustifyContentParseErrorOwned {
492
    InvalidValue(AzString),
493
}
494

            
495
#[cfg(feature = "parser")]
496
impl JustifyContentParseError<'_> {
497
    #[must_use]
498
6
    pub fn to_contained(&self) -> JustifyContentParseErrorOwned {
499
6
        match self {
500
6
            Self::InvalidValue(s) => {
501
6
                JustifyContentParseErrorOwned::InvalidValue((*s).to_string().into())
502
            }
503
        }
504
6
    }
505
}
506

            
507
#[cfg(feature = "parser")]
508
impl JustifyContentParseErrorOwned {
509
    #[must_use]
510
7
    pub fn to_shared(&self) -> JustifyContentParseError<'_> {
511
7
        match self {
512
7
            Self::InvalidValue(s) => JustifyContentParseError::InvalidValue(s.as_str()),
513
        }
514
7
    }
515
}
516

            
517
#[cfg(feature = "parser")]
518
/// # Errors
519
///
520
/// Returns an error if `input` is not a valid CSS `justify-content` value.
521
3248
pub fn parse_layout_justify_content(
522
3248
    input: &str,
523
3248
) -> Result<LayoutJustifyContent, JustifyContentParseError<'_>> {
524
3248
    match input.trim() {
525
3248
        "flex-start" => Ok(LayoutJustifyContent::FlexStart),
526
3245
        "flex-end" => Ok(LayoutJustifyContent::FlexEnd),
527
3243
        "start" => Ok(LayoutJustifyContent::Start),
528
3240
        "end" => Ok(LayoutJustifyContent::End),
529
3238
        "center" => Ok(LayoutJustifyContent::Center),
530
159
        "space-between" => Ok(LayoutJustifyContent::SpaceBetween),
531
25
        "space-around" => Ok(LayoutJustifyContent::SpaceAround),
532
23
        "space-evenly" => Ok(LayoutJustifyContent::SpaceEvenly),
533
20
        _ => Err(JustifyContentParseError::InvalidValue(input)),
534
    }
535
3248
}
536

            
537
// --- align-items ---
538

            
539
/// Represents an `align-items` attribute, which defines the default behavior for
540
/// how flex items are laid out along the cross axis on the current line.
541
/// Default: `Stretch`
542
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
543
#[repr(C)]
544
#[derive(Default)]
545
pub enum LayoutAlignItems {
546
    #[default]
547
    Stretch,
548
    Center,
549
    Start,
550
    End,
551
    Baseline,
552
}
553

            
554
impl PrintAsCssValue for LayoutAlignItems {
555
5
    fn print_as_css_value(&self) -> String {
556
5
        String::from(match self {
557
1
            Self::Stretch => "stretch",
558
1
            Self::Center => "center",
559
1
            Self::Start => "flex-start",
560
1
            Self::End => "flex-end",
561
1
            Self::Baseline => "baseline",
562
        })
563
5
    }
564
}
565

            
566
#[cfg(feature = "parser")]
567
#[derive(Clone, PartialEq, Eq)]
568
pub enum AlignItemsParseError<'a> {
569
    InvalidValue(&'a str),
570
}
571

            
572
#[cfg(feature = "parser")]
573
impl_debug_as_display!(AlignItemsParseError<'a>);
574
#[cfg(feature = "parser")]
575
impl_display! { AlignItemsParseError<'a>, {
576
    InvalidValue(s) => format!("Invalid align-items value: \"{}\"", s),
577
}}
578

            
579
#[cfg(feature = "parser")]
580
#[derive(Debug, Clone, PartialEq, Eq)]
581
#[repr(C, u8)]
582
pub enum AlignItemsParseErrorOwned {
583
    InvalidValue(AzString),
584
}
585

            
586
#[cfg(feature = "parser")]
587
impl AlignItemsParseError<'_> {
588
    #[must_use]
589
6
    pub fn to_contained(&self) -> AlignItemsParseErrorOwned {
590
6
        match self {
591
6
            Self::InvalidValue(s) => {
592
6
                AlignItemsParseErrorOwned::InvalidValue((*s).to_string().into())
593
            }
594
        }
595
6
    }
596
}
597

            
598
#[cfg(feature = "parser")]
599
impl AlignItemsParseErrorOwned {
600
    #[must_use]
601
7
    pub fn to_shared(&self) -> AlignItemsParseError<'_> {
602
7
        match self {
603
7
            Self::InvalidValue(s) => AlignItemsParseError::InvalidValue(s.as_str()),
604
        }
605
7
    }
606
}
607

            
608
#[cfg(feature = "parser")]
609
/// # Errors
610
///
611
/// Returns an error if `input` is not a valid CSS `align-items` value.
612
30557
pub fn parse_layout_align_items(input: &str) -> Result<LayoutAlignItems, AlignItemsParseError<'_>> {
613
30557
    match input.trim() {
614
30557
        "stretch" => Ok(LayoutAlignItems::Stretch),
615
29970
        "center" => Ok(LayoutAlignItems::Center),
616
45
        "start" | "flex-start" => Ok(LayoutAlignItems::Start),
617
27
        "end" | "flex-end" => Ok(LayoutAlignItems::End),
618
24
        "baseline" => Ok(LayoutAlignItems::Baseline),
619
22
        _ => Err(AlignItemsParseError::InvalidValue(input)),
620
    }
621
30557
}
622

            
623
// --- align-content ---
624

            
625
/// Represents an `align-content` attribute, which aligns a flex container's lines
626
/// within it when there is extra space in the cross-axis.
627
/// Default: `Stretch`
628
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
629
#[repr(C)]
630
#[derive(Default)]
631
pub enum LayoutAlignContent {
632
    #[default]
633
    Stretch,
634
    Center,
635
    Start,
636
    End,
637
    SpaceBetween,
638
    SpaceAround,
639
}
640

            
641
impl PrintAsCssValue for LayoutAlignContent {
642
6
    fn print_as_css_value(&self) -> String {
643
6
        String::from(match self {
644
1
            Self::Stretch => "stretch",
645
1
            Self::Center => "center",
646
1
            Self::Start => "flex-start",
647
1
            Self::End => "flex-end",
648
1
            Self::SpaceBetween => "space-between",
649
1
            Self::SpaceAround => "space-around",
650
        })
651
6
    }
652
}
653

            
654
#[cfg(feature = "parser")]
655
#[derive(Clone, PartialEq, Eq)]
656
pub enum AlignContentParseError<'a> {
657
    InvalidValue(&'a str),
658
}
659

            
660
#[cfg(feature = "parser")]
661
impl_debug_as_display!(AlignContentParseError<'a>);
662
#[cfg(feature = "parser")]
663
impl_display! { AlignContentParseError<'a>, {
664
    InvalidValue(s) => format!("Invalid align-content value: \"{}\"", s),
665
}}
666

            
667
#[cfg(feature = "parser")]
668
#[derive(Debug, Clone, PartialEq, Eq)]
669
#[repr(C, u8)]
670
pub enum AlignContentParseErrorOwned {
671
    InvalidValue(AzString),
672
}
673

            
674
#[cfg(feature = "parser")]
675
impl AlignContentParseError<'_> {
676
    #[must_use]
677
6
    pub fn to_contained(&self) -> AlignContentParseErrorOwned {
678
6
        match self {
679
6
            Self::InvalidValue(s) => {
680
6
                AlignContentParseErrorOwned::InvalidValue((*s).to_string().into())
681
            }
682
        }
683
6
    }
684
}
685

            
686
#[cfg(feature = "parser")]
687
impl AlignContentParseErrorOwned {
688
    #[must_use]
689
7
    pub fn to_shared(&self) -> AlignContentParseError<'_> {
690
7
        match self {
691
7
            Self::InvalidValue(s) => AlignContentParseError::InvalidValue(s.as_str()),
692
        }
693
7
    }
694
}
695

            
696
#[cfg(feature = "parser")]
697
/// # Errors
698
///
699
/// Returns an error if `input` is not a valid CSS `align-content` value.
700
36
pub fn parse_layout_align_content(
701
36
    input: &str,
702
36
) -> Result<LayoutAlignContent, AlignContentParseError<'_>> {
703
36
    match input.trim() {
704
36
        "stretch" => Ok(LayoutAlignContent::Stretch),
705
34
        "center" => Ok(LayoutAlignContent::Center),
706
32
        "start" | "flex-start" => Ok(LayoutAlignContent::Start),
707
30
        "end" | "flex-end" => Ok(LayoutAlignContent::End),
708
26
        "space-between" => Ok(LayoutAlignContent::SpaceBetween),
709
24
        "space-around" => Ok(LayoutAlignContent::SpaceAround),
710
22
        _ => Err(AlignContentParseError::InvalidValue(input)),
711
    }
712
36
}
713

            
714
// --- align-self ---
715

            
716
/// Represents an `align-self` attribute, which allows the default alignment
717
/// (or the one specified by align-items) to be overridden for individual flex items.
718
/// Default: `Auto`
719
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
720
#[repr(C)]
721
#[derive(Default)]
722
pub enum LayoutAlignSelf {
723
    #[default]
724
    Auto,
725
    Stretch,
726
    Center,
727
    Start,
728
    End,
729
    Baseline,
730
}
731

            
732
impl PrintAsCssValue for LayoutAlignSelf {
733
6
    fn print_as_css_value(&self) -> String {
734
6
        String::from(match self {
735
1
            Self::Auto => "auto",
736
1
            Self::Stretch => "stretch",
737
1
            Self::Center => "center",
738
1
            Self::Start => "flex-start",
739
1
            Self::End => "flex-end",
740
1
            Self::Baseline => "baseline",
741
        })
742
6
    }
743
}
744

            
745
impl FormatAsRustCode for LayoutAlignSelf {
746
    fn format_as_rust_code(&self, _tabs: usize) -> String {
747
        format!(
748
            "LayoutAlignSelf::{}",
749
            match self {
750
                Self::Auto => "Auto",
751
                Self::Stretch => "Stretch",
752
                Self::Center => "Center",
753
                Self::Start => "Start",
754
                Self::End => "End",
755
                Self::Baseline => "Baseline",
756
            }
757
        )
758
    }
759
}
760

            
761
#[cfg(feature = "parser")]
762
#[derive(Clone, PartialEq, Eq)]
763
pub enum AlignSelfParseError<'a> {
764
    InvalidValue(&'a str),
765
}
766

            
767
#[cfg(feature = "parser")]
768
impl_debug_as_display!(AlignSelfParseError<'a>);
769
#[cfg(feature = "parser")]
770
impl_display! { AlignSelfParseError<'a>, {
771
    InvalidValue(s) => format!("Invalid align-self value: \"{}\"", s),
772
}}
773

            
774
#[cfg(feature = "parser")]
775
#[derive(Debug, Clone, PartialEq, Eq)]
776
#[repr(C, u8)]
777
pub enum AlignSelfParseErrorOwned {
778
    InvalidValue(AzString),
779
}
780

            
781
#[cfg(feature = "parser")]
782
impl AlignSelfParseError<'_> {
783
    #[must_use]
784
6
    pub fn to_contained(&self) -> AlignSelfParseErrorOwned {
785
6
        match self {
786
6
            Self::InvalidValue(s) => {
787
6
                AlignSelfParseErrorOwned::InvalidValue((*s).to_string().into())
788
            }
789
        }
790
6
    }
791
}
792

            
793
#[cfg(feature = "parser")]
794
impl AlignSelfParseErrorOwned {
795
    #[must_use]
796
7
    pub fn to_shared(&self) -> AlignSelfParseError<'_> {
797
7
        match self {
798
7
            Self::InvalidValue(s) => AlignSelfParseError::InvalidValue(s.as_str()),
799
        }
800
7
    }
801
}
802

            
803
#[cfg(feature = "parser")]
804
/// # Errors
805
///
806
/// Returns an error if `input` is not a valid CSS `align-self` value.
807
56
pub fn parse_layout_align_self(input: &str) -> Result<LayoutAlignSelf, AlignSelfParseError<'_>> {
808
56
    match input.trim() {
809
56
        "auto" => Ok(LayoutAlignSelf::Auto),
810
53
        "stretch" => Ok(LayoutAlignSelf::Stretch),
811
39
        "center" => Ok(LayoutAlignSelf::Center),
812
38
        "start" | "flex-start" => Ok(LayoutAlignSelf::Start),
813
35
        "end" | "flex-end" => Ok(LayoutAlignSelf::End),
814
21
        "baseline" => Ok(LayoutAlignSelf::Baseline),
815
20
        _ => Err(AlignSelfParseError::InvalidValue(input)),
816
    }
817
56
}
818

            
819
// --- flex-basis ---
820
#[allow(variant_size_differences)]
821
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
822
// disparity accepted
823
/// Represents a `flex-basis` attribute
824
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
825
#[repr(C, u8)]
826
#[derive(Default)]
827
pub enum LayoutFlexBasis {
828
    /// auto
829
    #[default]
830
    Auto,
831
    /// Fixed size
832
    Exact(crate::props::basic::pixel::PixelValue),
833
}
834

            
835
impl core::fmt::Debug for LayoutFlexBasis {
836
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
837
        write!(f, "{}", self.print_as_css_value())
838
    }
839
}
840

            
841
impl PrintAsCssValue for LayoutFlexBasis {
842
8
    fn print_as_css_value(&self) -> String {
843
8
        match self {
844
1
            Self::Auto => "auto".to_string(),
845
7
            Self::Exact(px) => px.print_as_css_value(),
846
        }
847
8
    }
848
}
849

            
850
impl FormatAsRustCode for LayoutFlexBasis {
851
    fn format_as_rust_code(&self, _tabs: usize) -> String {
852
        match self {
853
            Self::Auto => String::from("LayoutFlexBasis::Auto"),
854
            Self::Exact(px) => {
855
                format!(
856
                    "LayoutFlexBasis::Exact({})",
857
                    crate::codegen::format::format_pixel_value(px)
858
                )
859
            }
860
        }
861
    }
862
}
863

            
864
#[cfg(feature = "parser")]
865
#[derive(Clone, PartialEq, Eq)]
866
pub enum FlexBasisParseError<'a> {
867
    InvalidValue(&'a str),
868
}
869

            
870
#[cfg(feature = "parser")]
871
impl_debug_as_display!(FlexBasisParseError<'a>);
872
#[cfg(feature = "parser")]
873
impl_display! { FlexBasisParseError<'a>, {
874
    InvalidValue(e) => format!("Invalid flex-basis value: \"{}\"", e),
875
}}
876

            
877
#[cfg(feature = "parser")]
878
#[derive(Debug, Clone, PartialEq, Eq)]
879
#[repr(C, u8)]
880
pub enum FlexBasisParseErrorOwned {
881
    InvalidValue(AzString),
882
}
883

            
884
#[cfg(feature = "parser")]
885
impl FlexBasisParseError<'_> {
886
    #[must_use]
887
6
    pub fn to_contained(&self) -> FlexBasisParseErrorOwned {
888
6
        match self {
889
6
            FlexBasisParseError::InvalidValue(s) => {
890
6
                FlexBasisParseErrorOwned::InvalidValue((*s).to_string().into())
891
            }
892
        }
893
6
    }
894
}
895

            
896
#[cfg(feature = "parser")]
897
impl FlexBasisParseErrorOwned {
898
    #[must_use]
899
7
    pub fn to_shared(&self) -> FlexBasisParseError<'_> {
900
7
        match self {
901
7
            Self::InvalidValue(s) => FlexBasisParseError::InvalidValue(s.as_str()),
902
        }
903
7
    }
904
}
905

            
906
#[cfg(feature = "parser")]
907
/// # Errors
908
///
909
/// Returns an error if `input` is not a valid CSS `flex-basis` value.
910
76
pub fn parse_layout_flex_basis(input: &str) -> Result<LayoutFlexBasis, FlexBasisParseError<'_>> {
911
    use crate::props::basic::pixel::parse_pixel_value;
912

            
913
76
    match input.trim() {
914
76
        "auto" => Ok(LayoutFlexBasis::Auto),
915
60
        s => parse_pixel_value(s)
916
60
            .map(LayoutFlexBasis::Exact)
917
60
            .map_err(|_| FlexBasisParseError::InvalidValue(input)),
918
    }
919
76
}
920

            
921
#[cfg(all(test, feature = "parser"))]
922
mod tests {
923
    // Tests assert that parsed values equal the exact source literals.
924
    #![allow(clippy::float_cmp)]
925
    use super::*;
926
    use crate::props::basic::pixel::PixelValue;
927

            
928
    #[test]
929
1
    fn test_parse_layout_flex_grow() {
930
1
        assert_eq!(parse_layout_flex_grow("0").unwrap().inner.get(), 0.0);
931
1
        assert_eq!(parse_layout_flex_grow("1").unwrap().inner.get(), 1.0);
932
1
        assert_eq!(parse_layout_flex_grow("2.5").unwrap().inner.get(), 2.5);
933
1
        assert_eq!(parse_layout_flex_grow("  0.5  ").unwrap().inner.get(), 0.5);
934
1
        assert!(parse_layout_flex_grow("none").is_err());
935
1
        assert!(parse_layout_flex_grow("-1").is_err()); // Negative values are invalid
936
1
    }
937

            
938
    #[test]
939
1
    fn test_parse_layout_flex_shrink() {
940
1
        assert_eq!(parse_layout_flex_shrink("0").unwrap().inner.get(), 0.0);
941
1
        assert_eq!(parse_layout_flex_shrink("1").unwrap().inner.get(), 1.0);
942
1
        assert_eq!(parse_layout_flex_shrink("3.0").unwrap().inner.get(), 3.0);
943
1
        assert_eq!(parse_layout_flex_shrink(" 0.2 ").unwrap().inner.get(), 0.2);
944
1
        assert!(parse_layout_flex_shrink("auto").is_err());
945
1
        assert!(parse_layout_flex_shrink("-1").is_err()); // Negative values are invalid
946
1
    }
947

            
948
    #[test]
949
1
    fn test_parse_layout_flex_direction() {
950
1
        assert_eq!(
951
1
            parse_layout_flex_direction("row").unwrap(),
952
            LayoutFlexDirection::Row
953
        );
954
1
        assert_eq!(
955
1
            parse_layout_flex_direction("row-reverse").unwrap(),
956
            LayoutFlexDirection::RowReverse
957
        );
958
1
        assert_eq!(
959
1
            parse_layout_flex_direction("column").unwrap(),
960
            LayoutFlexDirection::Column
961
        );
962
1
        assert_eq!(
963
1
            parse_layout_flex_direction("column-reverse").unwrap(),
964
            LayoutFlexDirection::ColumnReverse
965
        );
966
1
        assert_eq!(
967
1
            parse_layout_flex_direction("  row  ").unwrap(),
968
            LayoutFlexDirection::Row
969
        );
970
1
        assert!(parse_layout_flex_direction("reversed-row").is_err());
971
1
    }
972

            
973
    #[test]
974
1
    fn test_parse_layout_flex_wrap() {
975
1
        assert_eq!(
976
1
            parse_layout_flex_wrap("nowrap").unwrap(),
977
            LayoutFlexWrap::NoWrap
978
        );
979
1
        assert_eq!(
980
1
            parse_layout_flex_wrap("wrap").unwrap(),
981
            LayoutFlexWrap::Wrap
982
        );
983
1
        assert_eq!(
984
1
            parse_layout_flex_wrap("wrap-reverse").unwrap(),
985
            LayoutFlexWrap::WrapReverse
986
        );
987
1
        assert_eq!(
988
1
            parse_layout_flex_wrap("  wrap  ").unwrap(),
989
            LayoutFlexWrap::Wrap
990
        );
991
1
        assert!(parse_layout_flex_wrap("wrap reverse").is_err());
992
1
    }
993

            
994
    #[test]
995
1
    fn test_parse_layout_justify_content() {
996
1
        assert_eq!(
997
1
            parse_layout_justify_content("flex-start").unwrap(),
998
            LayoutJustifyContent::FlexStart
999
        );
1
        assert_eq!(
1
            parse_layout_justify_content("flex-end").unwrap(),
            LayoutJustifyContent::FlexEnd
        );
1
        assert_eq!(
1
            parse_layout_justify_content("start").unwrap(),
            LayoutJustifyContent::Start
        );
1
        assert_eq!(
1
            parse_layout_justify_content("end").unwrap(),
            LayoutJustifyContent::End
        );
1
        assert_eq!(
1
            parse_layout_justify_content("center").unwrap(),
            LayoutJustifyContent::Center
        );
1
        assert_eq!(
1
            parse_layout_justify_content("space-between").unwrap(),
            LayoutJustifyContent::SpaceBetween
        );
1
        assert_eq!(
1
            parse_layout_justify_content("space-around").unwrap(),
            LayoutJustifyContent::SpaceAround
        );
1
        assert_eq!(
1
            parse_layout_justify_content("space-evenly").unwrap(),
            LayoutJustifyContent::SpaceEvenly
        );
1
        assert_eq!(
1
            parse_layout_justify_content("  center  ").unwrap(),
            LayoutJustifyContent::Center
        );
1
    }
    #[test]
1
    fn test_parse_layout_align_items() {
1
        assert_eq!(
1
            parse_layout_align_items("stretch").unwrap(),
            LayoutAlignItems::Stretch
        );
1
        assert_eq!(
1
            parse_layout_align_items("flex-start").unwrap(),
            LayoutAlignItems::Start
        );
1
        assert_eq!(
1
            parse_layout_align_items("flex-end").unwrap(),
            LayoutAlignItems::End
        );
1
        assert_eq!(
1
            parse_layout_align_items("start").unwrap(),
            LayoutAlignItems::Start
        );
1
        assert_eq!(
1
            parse_layout_align_items("end").unwrap(),
            LayoutAlignItems::End
        );
1
        assert_eq!(
1
            parse_layout_align_items("center").unwrap(),
            LayoutAlignItems::Center
        );
1
        assert_eq!(
1
            parse_layout_align_items("baseline").unwrap(),
            LayoutAlignItems::Baseline
        );
1
        assert!(parse_layout_align_items("invalid").is_err());
1
    }
    #[test]
1
    fn test_parse_layout_align_content() {
1
        assert_eq!(
1
            parse_layout_align_content("stretch").unwrap(),
            LayoutAlignContent::Stretch
        );
1
        assert_eq!(
1
            parse_layout_align_content("flex-start").unwrap(),
            LayoutAlignContent::Start
        );
1
        assert_eq!(
1
            parse_layout_align_content("flex-end").unwrap(),
            LayoutAlignContent::End
        );
1
        assert_eq!(
1
            parse_layout_align_content("center").unwrap(),
            LayoutAlignContent::Center
        );
1
        assert_eq!(
1
            parse_layout_align_content("space-between").unwrap(),
            LayoutAlignContent::SpaceBetween
        );
1
        assert_eq!(
1
            parse_layout_align_content("space-around").unwrap(),
            LayoutAlignContent::SpaceAround
        );
1
        assert!(parse_layout_align_content("space-evenly").is_err()); // Not valid for align-content
1
    }
    #[test]
1
    fn test_parse_layout_flex_basis() {
1
        assert_eq!(
1
            parse_layout_flex_basis("auto").unwrap(),
            LayoutFlexBasis::Auto
        );
1
        assert_eq!(
1
            parse_layout_flex_basis("200px").unwrap(),
1
            LayoutFlexBasis::Exact(PixelValue::px(200.0))
        );
1
        assert_eq!(
1
            parse_layout_flex_basis("50%").unwrap(),
1
            LayoutFlexBasis::Exact(PixelValue::percent(50.0))
        );
1
        assert_eq!(
1
            parse_layout_flex_basis("  10em  ").unwrap(),
1
            LayoutFlexBasis::Exact(PixelValue::em(10.0))
        );
1
        assert!(parse_layout_flex_basis("none").is_err());
        // Liberal parsing accepts unitless numbers (treated as px)
1
        assert_eq!(
1
            parse_layout_flex_basis("200").unwrap(),
1
            LayoutFlexBasis::Exact(PixelValue::px(200.0))
        );
1
        assert_eq!(
1
            parse_layout_flex_basis("0").unwrap(),
1
            LayoutFlexBasis::Exact(PixelValue::px(0.0))
        );
1
    }
}
#[cfg(test)]
#[allow(clippy::float_cmp)] // fixed-point (1/1000) values are exactly representable in f32
mod autotest_generated {
    use super::*;
    use crate::props::basic::{length::FloatValue, pixel::PixelValue};
    // ---------------------------------------------------------------------
    // LayoutFlexGrow::new / const_new  (constructor + numeric)
    // ---------------------------------------------------------------------
    /// `new()` goes through f32 (`isize -> f32 -> *1000 -> isize`) while
    /// `const_new()` uses pure integer math (`value * 1000`). For magnitudes
    /// where both encodings are exact they must agree bit-for-bit.
    #[test]
    fn flex_grow_new_agrees_with_const_new_for_exact_ints() {
        for v in [-10_000_isize, -1000, -7, -1, 0, 1, 7, 1000, 10_000] {
            assert_eq!(
                LayoutFlexGrow::new(v).inner.number(),
                LayoutFlexGrow::const_new(v).inner.number(),
                "new()/const_new() disagree for {v}"
            );
            assert_eq!(LayoutFlexGrow::new(v).inner.get(), v as f32);
        }
    }
    /// `new()` runs the value through `f32 as isize`, which saturates rather
    /// than wrapping or panicking: MIN/MAX must survive without UB or overflow.
    #[test]
    fn flex_grow_new_saturates_at_isize_extremes() {
        let max = LayoutFlexGrow::new(isize::MAX);
        let min = LayoutFlexGrow::new(isize::MIN);
        assert_eq!(
            max.inner.number(),
            isize::MAX,
            "MAX must saturate, not wrap"
        );
        assert_eq!(
            min.inner.number(),
            isize::MIN,
            "MIN must saturate, not wrap"
        );
        assert!(max.inner.get().is_finite());
        assert!(min.inner.get().is_finite());
        assert!(max.inner.get() > 0.0);
        assert!(min.inner.get() < 0.0);
    }
    /// `const_new()` stores `value * 1000` in an `isize`, so the largest safe
    /// input is `isize::MAX / 1000`. Anything above that overflows the
    /// multiplication (debug-panic / release-wrap) — this pins the documented
    /// safe boundary. See the report note on `const_new` overflow.
    #[test]
    fn flex_grow_const_new_at_safe_encoding_boundary() {
        let hi = isize::MAX / 1000;
        let lo = isize::MIN / 1000;
        assert_eq!(LayoutFlexGrow::const_new(hi).inner.number(), hi * 1000);
        assert_eq!(LayoutFlexGrow::const_new(lo).inner.number(), lo * 1000);
        assert!(LayoutFlexGrow::const_new(hi).inner.get().is_finite());
        assert!(LayoutFlexGrow::const_new(lo).inner.get().is_finite());
    }
    /// Zero / negative inputs are stored verbatim: the constructors perform no
    /// CSS validation (`flex-grow` may not be negative), only the parser does.
    #[test]
    fn flex_grow_const_new_zero_and_negative_are_not_clamped() {
        const ZERO: LayoutFlexGrow = LayoutFlexGrow::const_new(0);
        const NEG: LayoutFlexGrow = LayoutFlexGrow::const_new(-3);
        assert_eq!(ZERO.inner.get(), 0.0);
        assert_eq!(ZERO.inner.number(), 0);
        assert_eq!(NEG.inner.get(), -3.0);
        assert_eq!(LayoutFlexGrow::new(-3).inner.get(), -3.0);
    }
    #[test]
    fn flex_grow_and_shrink_defaults_match_css_initial_values() {
        assert_eq!(LayoutFlexGrow::default().inner.get(), 0.0);
        assert_eq!(LayoutFlexShrink::default().inner.get(), 1.0);
        // Ord is derived over the fixed-point isize, so it must track the float.
        assert!(LayoutFlexGrow::const_new(1) < LayoutFlexGrow::const_new(2));
        assert!(LayoutFlexGrow::const_new(-1) < LayoutFlexGrow::const_new(0));
    }
    // ---------------------------------------------------------------------
    // interpolate()  (numeric: zero / limits / NaN / inf / overflow)
    // ---------------------------------------------------------------------
    fn grow(v: f32) -> LayoutFlexGrow {
        LayoutFlexGrow {
            inner: FloatValue::new(v),
        }
    }
    fn shrink(v: f32) -> LayoutFlexShrink {
        LayoutFlexShrink {
            inner: FloatValue::new(v),
        }
    }
    #[test]
    fn flex_grow_interpolate_endpoints_midpoint_and_extrapolation() {
        let a = grow(0.0);
        let b = grow(10.0);
        assert_eq!(a.interpolate(&b, 0.0).inner.get(), 0.0);
        assert_eq!(a.interpolate(&b, 1.0).inner.get(), 10.0);
        assert_eq!(a.interpolate(&b, 0.5).inner.get(), 5.0);
        // t is not clamped: extrapolation past the endpoints is well-defined.
        assert_eq!(a.interpolate(&b, 2.0).inner.get(), 20.0);
        assert_eq!(a.interpolate(&b, -1.0).inner.get(), -10.0);
    }
    /// A NaN `t` produces NaN internally; the `f32 as isize` cast maps NaN to 0,
    /// so the result is a defined 0.0 rather than a NaN or a panic.
    #[test]
    fn flex_grow_interpolate_nan_t_collapses_to_zero() {
        let a = grow(2.0);
        let b = grow(8.0);
        let out = a.interpolate(&b, f32::NAN);
        assert!(
            out.inner.get().is_finite(),
            "NaN must not leak into the value"
        );
        assert_eq!(out.inner.get(), 0.0);
        assert_eq!(out.inner.number(), 0);
    }
    /// Infinite `t` overflows the lerp; the saturating cast must keep the result
    /// finite and correctly signed instead of panicking.
    #[test]
    fn flex_grow_interpolate_infinite_t_saturates_finite() {
        let a = grow(0.0);
        let b = grow(10.0);
        let pos = a.interpolate(&b, f32::INFINITY);
        assert!(pos.inner.get().is_finite());
        assert!(pos.inner.get() > 0.0);
        assert_eq!(pos.inner.number(), isize::MAX);
        let neg = a.interpolate(&b, f32::NEG_INFINITY);
        assert!(neg.inner.get().is_finite());
        assert!(neg.inner.get() < 0.0);
        assert_eq!(neg.inner.number(), isize::MIN);
        // Degenerate case: equal endpoints => (b - a) * inf == NaN => 0.0.
        let same = grow(4.0).interpolate(&grow(4.0), f32::INFINITY);
        assert!(same.inner.get().is_finite());
        assert_eq!(same.inner.get(), 0.0);
    }
    /// Interpolating between the saturated extremes must never panic and must
    /// always yield a finite, decodable value.
    #[test]
    fn flex_grow_interpolate_extreme_endpoints_stay_finite() {
        let a = LayoutFlexGrow::new(isize::MAX);
        let b = LayoutFlexGrow::new(isize::MIN);
        for t in [
            0.0_f32,
            0.5,
            1.0,
            -1.0,
            1e30,
            -1e30,
            f32::MIN_POSITIVE,
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
        ] {
            let out = a.interpolate(&b, t);
            assert!(
                out.inner.get().is_finite(),
                "interpolate(MAX, MIN, {t}) produced a non-finite value"
            );
        }
        // t = 0 must return `self` even at the saturation boundary.
        assert_eq!(a.interpolate(&b, 0.0).inner.get(), a.inner.get());
    }
    #[test]
    fn flex_shrink_interpolate_endpoints_nan_and_inf() {
        let a = shrink(1.0);
        let b = shrink(3.0);
        assert_eq!(a.interpolate(&b, 0.0).inner.get(), 1.0);
        assert_eq!(a.interpolate(&b, 1.0).inner.get(), 3.0);
        assert_eq!(a.interpolate(&b, 0.5).inner.get(), 2.0);
        assert_eq!(a.interpolate(&b, -2.0).inner.get(), -3.0);
        assert_eq!(a.interpolate(&b, f32::NAN).inner.get(), 0.0);
        assert!(a.interpolate(&b, f32::INFINITY).inner.get().is_finite());
        assert!(a.interpolate(&b, f32::NEG_INFINITY).inner.get().is_finite());
        let extreme = LayoutFlexShrink {
            inner: FloatValue::new(f32::MAX),
        };
        assert!(extreme.interpolate(&a, 0.5).inner.get().is_finite());
        assert!(extreme.interpolate(&a, f32::NAN).inner.get().is_finite());
    }
    // ---------------------------------------------------------------------
    // LayoutFlexDirection::get_axis / is_reverse  (getter + predicate)
    // ---------------------------------------------------------------------
    const ALL_DIRECTIONS: [LayoutFlexDirection; 4] = [
        LayoutFlexDirection::Row,
        LayoutFlexDirection::RowReverse,
        LayoutFlexDirection::Column,
        LayoutFlexDirection::ColumnReverse,
    ];
    #[test]
    fn flex_direction_get_axis_is_exhaustive_and_reverse_invariant() {
        assert_eq!(LayoutFlexDirection::Row.get_axis(), LayoutAxis::Horizontal);
        assert_eq!(
            LayoutFlexDirection::RowReverse.get_axis(),
            LayoutAxis::Horizontal
        );
        assert_eq!(LayoutFlexDirection::Column.get_axis(), LayoutAxis::Vertical);
        assert_eq!(
            LayoutFlexDirection::ColumnReverse.get_axis(),
            LayoutAxis::Vertical
        );
        // Invariant: reversing a direction never changes its axis.
        assert_eq!(
            LayoutFlexDirection::Row.get_axis(),
            LayoutFlexDirection::RowReverse.get_axis()
        );
        assert_eq!(
            LayoutFlexDirection::Column.get_axis(),
            LayoutFlexDirection::ColumnReverse.get_axis()
        );
        // Default (`row`) must be the horizontal, non-reversed axis.
        assert_eq!(
            LayoutFlexDirection::default().get_axis(),
            LayoutAxis::Horizontal
        );
        assert!(!LayoutFlexDirection::default().is_reverse());
    }
    #[test]
    fn flex_direction_is_reverse_exhaustive() {
        assert!(!LayoutFlexDirection::Row.is_reverse());
        assert!(LayoutFlexDirection::RowReverse.is_reverse());
        assert!(!LayoutFlexDirection::Column.is_reverse());
        assert!(LayoutFlexDirection::ColumnReverse.is_reverse());
        // Every variant answers deterministically, and exactly half are reverse.
        let reversed = ALL_DIRECTIONS.iter().filter(|d| d.is_reverse()).count();
        assert_eq!(reversed, 2);
        // get_axis()/is_reverse() are orthogonal: both axes have a reverse form.
        for axis in [LayoutAxis::Horizontal, LayoutAxis::Vertical] {
            assert_eq!(
                ALL_DIRECTIONS
                    .iter()
                    .filter(|d| d.get_axis() == axis && d.is_reverse())
                    .count(),
                1
            );
        }
    }
    // =====================================================================
    // Parser-gated tests
    // =====================================================================
    // --- flex-grow / flex-shrink (numeric parsers) -----------------------
    #[cfg(feature = "parser")]
    #[test]
    fn flex_grow_parse_empty_and_whitespace_only_are_err() {
        for input in ["", " ", "   ", "\t", "\n", "\r\n", "\t \n "] {
            assert!(
                parse_layout_flex_grow(input).is_err(),
                "empty/whitespace input {input:?} must not parse"
            );
            assert!(parse_layout_flex_shrink(input).is_err());
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn flex_grow_parse_garbage_and_unicode_never_panics() {
        let deep_nesting = "(".repeat(10_000) + &")".repeat(10_000);
        let long_junk = "x".repeat(1_000_000);
        let long_digits = "9".repeat(100_000);
        let garbage = [
            "none",
            "auto",
            "null",
            "1/2",
            "0x10",
            "1,0",
            "--1",
            "1-",
            "+-1",
            "1e",
            "e1",
            "\u{1F600}",        // emoji
            "1\u{1F600}",       // digit + emoji
            "e\u{0301}",        // combining acute accent
            "\u{0661}\u{0662}", // arabic-indic digits
            "1",               // fullwidth digit
            "1\u{0}",           // embedded NUL
            "\u{200B}1",        // zero-width space
            deep_nesting.as_str(),
            long_junk.as_str(),
        ];
        for input in garbage {
            assert!(
                parse_layout_flex_grow(input).is_err(),
                "garbage input {:?} must be rejected",
                input.chars().take(8).collect::<String>()
            );
            assert!(parse_layout_flex_shrink(input).is_err());
        }
        // 100k digits overflows f32 to +inf; it must saturate, not hang or panic.
        let huge = parse_layout_flex_grow(&long_digits).expect("huge finite-overflow input");
        assert!(huge.inner.get().is_finite());
        assert!(huge.inner.get() >= 0.0);
    }
    #[cfg(feature = "parser")]
    #[test]
    fn flex_grow_parse_boundary_numbers() {
        // Positive controls.
        assert_eq!(parse_layout_flex_grow("0").unwrap().inner.get(), 0.0);
        assert_eq!(parse_layout_flex_grow("1").unwrap().inner.get(), 1.0);
        assert_eq!(parse_layout_flex_grow("+2.5").unwrap().inner.get(), 2.5);
        assert_eq!(parse_layout_flex_grow(".5").unwrap().inner.get(), 0.5);
        // Signed zero is accepted and normalised to +0.
        let neg_zero = parse_layout_flex_grow("-0").unwrap();
        assert_eq!(neg_zero.inner.get(), 0.0);
        assert_eq!(neg_zero.inner.number(), 0);
        // Genuinely negative values are rejected.
        assert!(matches!(
            parse_layout_flex_grow("-1"),
            Err(FlexGrowParseError::NegativeValue("-1"))
        ));
        assert!(parse_layout_flex_grow("-0.01").is_err());
        assert!(parse_layout_flex_grow("-1e10").is_err());
        // -inf underflows the fixed point to isize::MIN => still caught as negative.
        assert!(matches!(
            parse_layout_flex_grow("-inf"),
            Err(FlexGrowParseError::NegativeValue(_))
        ));
        // Sub-quantum negatives (|v| < 0.001) truncate to 0 and are ACCEPTED —
        // the negative check runs after the fixed-point quantisation.
        let tiny_neg = parse_layout_flex_grow("-0.0001").unwrap();
        assert_eq!(tiny_neg.inner.get(), 0.0);
        assert_eq!(parse_layout_flex_grow("-1e-30").unwrap().inner.get(), 0.0);
        // Values beyond f32 range become +inf, then saturate to a finite maximum.
        for input in ["inf", "1e40", "9223372036854775807", "3.5e38"] {
            let parsed = parse_layout_flex_grow(input)
                .unwrap_or_else(|e| panic!("{input:?} unexpectedly rejected: {e}"));
            assert!(
                parsed.inner.get().is_finite(),
                "{input:?} decoded to a non-finite value"
            );
            assert!(parsed.inner.get() >= 0.0);
        }
        // Denormal-scale positives quantise to 0 rather than erroring.
        assert_eq!(parse_layout_flex_grow("1e-40").unwrap().inner.get(), 0.0);
        // "NaN" is a valid Rust float literal, so it reaches the fixed-point
        // cast, which maps NaN -> 0. It is accepted as flex-grow: 0.
        let nan = parse_layout_flex_grow("NaN").unwrap();
        assert!(nan.inner.get().is_finite());
        assert_eq!(nan.inner.get(), 0.0);
    }
    #[cfg(feature = "parser")]
    #[test]
    fn flex_shrink_parse_boundary_numbers() {
        assert_eq!(parse_layout_flex_shrink("0").unwrap().inner.get(), 0.0);
        assert_eq!(parse_layout_flex_shrink("1").unwrap().inner.get(), 1.0);
        assert_eq!(parse_layout_flex_shrink("-0").unwrap().inner.get(), 0.0);
        assert!(matches!(
            parse_layout_flex_shrink("-1"),
            Err(FlexShrinkParseError::NegativeValue("-1"))
        ));
        assert!(parse_layout_flex_shrink("-inf").is_err());
        let huge = parse_layout_flex_shrink("1e40").unwrap();
        assert!(huge.inner.get().is_finite() && huge.inner.get() > 0.0);
        assert_eq!(parse_layout_flex_shrink("NaN").unwrap().inner.get(), 0.0);
    }
    #[cfg(feature = "parser")]
    #[test]
    fn flex_grow_parse_leading_trailing_junk() {
        // Surrounding whitespace is trimmed.
        assert_eq!(parse_layout_flex_grow("  0.5  ").unwrap().inner.get(), 0.5);
        assert_eq!(parse_layout_flex_grow("\t2\n").unwrap().inner.get(), 2.0);
        // Trailing junk / units / extra tokens are rejected.
        for input in ["1;", "1 2", "1px", "1%", "valid;garbage", "1 1 1"] {
            assert!(
                parse_layout_flex_grow(input).is_err(),
                "{input:?} must be rejected"
            );
        }
    }
    /// The error must carry the *original* (untrimmed) input, not the trimmed
    /// slice — callers rely on it to point back into the source CSS.
    #[cfg(feature = "parser")]
    #[test]
    fn flex_grow_error_preserves_untrimmed_input() {
        match parse_layout_flex_grow("  bogus  ") {
            Err(FlexGrowParseError::ParseFloat(_, s)) => assert_eq!(s, "  bogus  "),
            other => panic!("expected ParseFloat error, got {other:?}"),
        }
        match parse_layout_flex_shrink(" -2 ") {
            Err(FlexShrinkParseError::NegativeValue(s)) => assert_eq!(s, " -2 "),
            other => panic!("expected NegativeValue error, got {other:?}"),
        }
    }
    /// Round-trip: print -> parse must reproduce the value for anything that is
    /// exactly representable in the 1/1000 fixed point.
    #[cfg(feature = "parser")]
    #[test]
    fn flex_grow_shrink_print_parse_round_trip() {
        for v in [0.0_f32, 1.0, 2.5, 0.25, 0.125, 100.0, 12.5] {
            let g = grow(v);
            let printed = g.print_as_css_value();
            assert_eq!(
                parse_layout_flex_grow(&printed).unwrap().inner.number(),
                g.inner.number(),
                "flex-grow round-trip failed for {printed}"
            );
            let s = shrink(v);
            let printed = s.print_as_css_value();
            assert_eq!(
                parse_layout_flex_shrink(&printed).unwrap().inner.number(),
                s.inner.number(),
                "flex-shrink round-trip failed for {printed}"
            );
        }
    }
    // --- keyword parsers -------------------------------------------------
    /// Every enum variant must survive `print_as_css_value() -> parse()`.
    #[cfg(feature = "parser")]
    #[test]
    fn keyword_enums_print_parse_round_trip() {
        for d in ALL_DIRECTIONS {
            assert_eq!(
                parse_layout_flex_direction(&d.print_as_css_value()).unwrap(),
                d
            );
        }
        for w in [
            LayoutFlexWrap::Wrap,
            LayoutFlexWrap::NoWrap,
            LayoutFlexWrap::WrapReverse,
        ] {
            assert_eq!(parse_layout_flex_wrap(&w.print_as_css_value()).unwrap(), w);
        }
        for j in [
            LayoutJustifyContent::FlexStart,
            LayoutJustifyContent::FlexEnd,
            LayoutJustifyContent::Start,
            LayoutJustifyContent::End,
            LayoutJustifyContent::Center,
            LayoutJustifyContent::SpaceBetween,
            LayoutJustifyContent::SpaceAround,
            LayoutJustifyContent::SpaceEvenly,
        ] {
            assert_eq!(
                parse_layout_justify_content(&j.print_as_css_value()).unwrap(),
                j
            );
        }
        for a in [
            LayoutAlignItems::Stretch,
            LayoutAlignItems::Center,
            LayoutAlignItems::Start,
            LayoutAlignItems::End,
            LayoutAlignItems::Baseline,
        ] {
            assert_eq!(
                parse_layout_align_items(&a.print_as_css_value()).unwrap(),
                a
            );
        }
        for a in [
            LayoutAlignContent::Stretch,
            LayoutAlignContent::Center,
            LayoutAlignContent::Start,
            LayoutAlignContent::End,
            LayoutAlignContent::SpaceBetween,
            LayoutAlignContent::SpaceAround,
        ] {
            assert_eq!(
                parse_layout_align_content(&a.print_as_css_value()).unwrap(),
                a
            );
        }
        for a in [
            LayoutAlignSelf::Auto,
            LayoutAlignSelf::Stretch,
            LayoutAlignSelf::Center,
            LayoutAlignSelf::Start,
            LayoutAlignSelf::End,
            LayoutAlignSelf::Baseline,
        ] {
            assert_eq!(parse_layout_align_self(&a.print_as_css_value()).unwrap(), a);
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn keyword_parsers_reject_empty_whitespace_and_garbage() {
        let deep_nesting = "[".repeat(10_000) + &"]".repeat(10_000);
        let long_junk = "row".repeat(300_000); // ~900k chars, no hang
        let bad = [
            "",
            " ",
            "\t\n",
            "0",
            "-1",
            "NaN",
            "inf",
            "9223372036854775807",
            "\u{1F600}",
            "row\u{200B}", // zero-width space is NOT css whitespace
            "row\u{0}",    // embedded NUL
            "row row",
            "row;",
            ";row",
            "row/**/",
            deep_nesting.as_str(),
            long_junk.as_str(),
        ];
        for input in bad {
            assert!(parse_layout_flex_direction(input).is_err());
            assert!(parse_layout_flex_wrap(input).is_err());
            assert!(parse_layout_justify_content(input).is_err());
            assert!(parse_layout_align_items(input).is_err());
            assert!(parse_layout_align_content(input).is_err());
            assert!(parse_layout_align_self(input).is_err());
        }
    }
    /// CSS keywords are ASCII case-insensitive, but these parsers match
    /// case-sensitively. Pinned as current behaviour (see report).
    #[cfg(feature = "parser")]
    #[test]
    fn keyword_parsers_are_case_sensitive() {
        assert!(parse_layout_flex_direction("ROW").is_err());
        assert!(parse_layout_flex_direction("Row").is_err());
        assert!(parse_layout_flex_wrap("NoWrap").is_err());
        assert!(parse_layout_justify_content("Center").is_err());
        assert!(parse_layout_align_items("STRETCH").is_err());
        assert!(parse_layout_align_content("Stretch").is_err());
        assert!(parse_layout_align_self("AUTO").is_err());
        // lowercase positive controls still work
        assert_eq!(
            parse_layout_flex_direction("row").unwrap(),
            LayoutFlexDirection::Row
        );
        assert_eq!(
            parse_layout_align_self("auto").unwrap(),
            LayoutAlignSelf::Auto
        );
    }
    /// Keyword errors must echo the original, untrimmed input.
    #[cfg(feature = "parser")]
    #[test]
    fn keyword_errors_preserve_untrimmed_input() {
        assert_eq!(
            parse_layout_flex_direction("  bogus  ").unwrap_err(),
            FlexDirectionParseError::InvalidValue("  bogus  ")
        );
        assert_eq!(
            parse_layout_flex_wrap("\twrap!\n").unwrap_err(),
            FlexWrapParseError::InvalidValue("\twrap!\n")
        );
        assert_eq!(
            parse_layout_justify_content("").unwrap_err(),
            JustifyContentParseError::InvalidValue("")
        );
        assert_eq!(
            parse_layout_align_items(" nope ").unwrap_err(),
            AlignItemsParseError::InvalidValue(" nope ")
        );
        assert_eq!(
            parse_layout_align_content(" nope ").unwrap_err(),
            AlignContentParseError::InvalidValue(" nope ")
        );
        assert_eq!(
            parse_layout_align_self(" nope ").unwrap_err(),
            AlignSelfParseError::InvalidValue(" nope ")
        );
    }
    /// Aliases: `start`/`flex-start` and `end`/`flex-end` collapse to the same
    /// variant for align-*, while justify-content keeps them distinct.
    #[cfg(feature = "parser")]
    #[test]
    fn align_aliases_collapse_but_justify_keeps_them_distinct() {
        assert_eq!(
            parse_layout_align_items("start").unwrap(),
            parse_layout_align_items("flex-start").unwrap()
        );
        assert_eq!(
            parse_layout_align_content("end").unwrap(),
            parse_layout_align_content("flex-end").unwrap()
        );
        assert_eq!(
            parse_layout_align_self("start").unwrap(),
            parse_layout_align_self("flex-start").unwrap()
        );
        assert_ne!(
            parse_layout_justify_content("start").unwrap(),
            parse_layout_justify_content("flex-start").unwrap()
        );
        // space-evenly exists for justify-content but not for align-content.
        assert!(parse_layout_justify_content("space-evenly").is_ok());
        assert!(parse_layout_align_content("space-evenly").is_err());
        // align-self has `auto`; align-items does not.
        assert!(parse_layout_align_self("auto").is_ok());
        assert!(parse_layout_align_items("auto").is_err());
    }
    // --- flex-basis ------------------------------------------------------
    #[cfg(feature = "parser")]
    #[test]
    fn flex_basis_print_parse_round_trip() {
        for basis in [
            LayoutFlexBasis::Auto,
            LayoutFlexBasis::Exact(PixelValue::px(0.0)),
            LayoutFlexBasis::Exact(PixelValue::px(200.0)),
            LayoutFlexBasis::Exact(PixelValue::px(-5.0)),
            LayoutFlexBasis::Exact(PixelValue::percent(50.0)),
            LayoutFlexBasis::Exact(PixelValue::em(10.5)),
            LayoutFlexBasis::Exact(PixelValue::rem(1.25)),
            LayoutFlexBasis::Exact(PixelValue::pt(12.0)),
        ] {
            let printed = basis.print_as_css_value();
            assert_eq!(
                parse_layout_flex_basis(&printed).unwrap(),
                basis,
                "flex-basis round-trip failed for {printed}"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn flex_basis_rejects_empty_units_only_and_garbage() {
        let deep_nesting = "(".repeat(10_000) + &")".repeat(10_000);
        let long_junk = "z".repeat(1_000_000);
        for input in [
            "",
            "   ",
            "\t\n",
            "px", // unit with no value
            "%",
            "em",
            " px ",
            "none",
            "auto auto",
            "200px;",
            "200 px extra",
            "AUTO", // case-sensitive
            "5PX",
            "\u{1F600}",
            "50px", // fullwidth digits
            "200\u{200B}px",
            deep_nesting.as_str(),
            long_junk.as_str(),
        ] {
            assert!(
                parse_layout_flex_basis(input).is_err(),
                "flex-basis {:?} must be rejected",
                input.chars().take(10).collect::<String>()
            );
        }
        // The error echoes the original, untrimmed input.
        assert_eq!(
            parse_layout_flex_basis("  none  ").unwrap_err(),
            FlexBasisParseError::InvalidValue("  none  ")
        );
    }
    /// Adversarial numeric flex-basis inputs: NaN/inf reach the fixed-point cast
    /// through the unit suffix and must saturate to a finite, defined value.
    #[cfg(feature = "parser")]
    #[test]
    fn flex_basis_nan_and_inf_units_saturate() {
        // "NaN" is a valid float literal => NaNpx decodes to 0px, not an error.
        assert_eq!(
            parse_layout_flex_basis("NaNpx").unwrap(),
            LayoutFlexBasis::Exact(PixelValue::px(0.0))
        );
        // Overflowing magnitudes saturate rather than panicking.
        assert_eq!(
            parse_layout_flex_basis("infpx").unwrap(),
            LayoutFlexBasis::Exact(PixelValue::px(f32::INFINITY))
        );
        assert_eq!(
            parse_layout_flex_basis("1e40px").unwrap(),
            LayoutFlexBasis::Exact(PixelValue::px(f32::INFINITY))
        );
        assert_eq!(
            parse_layout_flex_basis(&"9".repeat(100_000)).unwrap(),
            LayoutFlexBasis::Exact(PixelValue::px(f32::INFINITY))
        );
        // Unitless numbers are accepted and treated as px (liberal parsing).
        assert_eq!(
            parse_layout_flex_basis("-0").unwrap(),
            LayoutFlexBasis::Exact(PixelValue::px(0.0))
        );
        // Negative lengths are accepted even though CSS forbids them (see report).
        assert_eq!(
            parse_layout_flex_basis("-5px").unwrap(),
            LayoutFlexBasis::Exact(PixelValue::px(-5.0))
        );
        // Whitespace *inside* the token is tolerated (see report).
        assert_eq!(
            parse_layout_flex_basis("5 px").unwrap(),
            LayoutFlexBasis::Exact(PixelValue::px(5.0))
        );
    }
    // ---------------------------------------------------------------------
    // Error to_contained() / to_shared()  (getters, borrow <-> owned)
    // ---------------------------------------------------------------------
    /// `to_contained()` then `to_shared()` must be the identity for every error
    /// variant, including empty / unicode / long payloads.
    #[cfg(feature = "parser")]
    #[test]
    fn flex_grow_shrink_error_owned_round_trip() {
        let invalid = "x".parse::<f32>().unwrap_err();
        let empty = "".parse::<f32>().unwrap_err();
        let long = "q".repeat(10_000);
        for payload in ["", "abc", "\u{1F600}\u{0301}", "  spaced  ", long.as_str()] {
            for err in [
                FlexGrowParseError::ParseFloat(invalid.clone(), payload),
                FlexGrowParseError::ParseFloat(empty.clone(), payload),
                FlexGrowParseError::NegativeValue(payload),
            ] {
                assert_eq!(err.to_contained().to_shared(), err);
            }
            for err in [
                FlexShrinkParseError::ParseFloat(invalid.clone(), payload),
                FlexShrinkParseError::NegativeValue(payload),
            ] {
                assert_eq!(err.to_contained().to_shared(), err);
            }
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn keyword_error_owned_round_trip() {
        let long = "k".repeat(10_000);
        for payload in ["", " ", "\u{1F600}", "bogus", long.as_str()] {
            let d = FlexDirectionParseError::InvalidValue(payload);
            assert_eq!(d.to_contained().to_shared(), d);
            let w = FlexWrapParseError::InvalidValue(payload);
            assert_eq!(w.to_contained().to_shared(), w);
            let j = JustifyContentParseError::InvalidValue(payload);
            assert_eq!(j.to_contained().to_shared(), j);
            let ai = AlignItemsParseError::InvalidValue(payload);
            assert_eq!(ai.to_contained().to_shared(), ai);
            let ac = AlignContentParseError::InvalidValue(payload);
            assert_eq!(ac.to_contained().to_shared(), ac);
            let asf = AlignSelfParseError::InvalidValue(payload);
            assert_eq!(asf.to_contained().to_shared(), asf);
            let b = FlexBasisParseError::InvalidValue(payload);
            assert_eq!(b.to_contained().to_shared(), b);
        }
    }
    /// `to_shared()` must not panic on a directly-constructed owned error with a
    /// degenerate (empty) payload, and must hand back the exact same string.
    #[cfg(feature = "parser")]
    #[test]
    fn owned_errors_to_shared_on_degenerate_payloads() {
        let empty: AzString = String::new().into();
        assert_eq!(
            FlexDirectionParseErrorOwned::InvalidValue(empty.clone()).to_shared(),
            FlexDirectionParseError::InvalidValue("")
        );
        assert_eq!(
            FlexWrapParseErrorOwned::InvalidValue(empty.clone()).to_shared(),
            FlexWrapParseError::InvalidValue("")
        );
        assert_eq!(
            JustifyContentParseErrorOwned::InvalidValue(empty.clone()).to_shared(),
            JustifyContentParseError::InvalidValue("")
        );
        assert_eq!(
            AlignItemsParseErrorOwned::InvalidValue(empty.clone()).to_shared(),
            AlignItemsParseError::InvalidValue("")
        );
        assert_eq!(
            AlignContentParseErrorOwned::InvalidValue(empty.clone()).to_shared(),
            AlignContentParseError::InvalidValue("")
        );
        assert_eq!(
            AlignSelfParseErrorOwned::InvalidValue(empty.clone()).to_shared(),
            AlignSelfParseError::InvalidValue("")
        );
        assert_eq!(
            FlexBasisParseErrorOwned::InvalidValue(empty.clone()).to_shared(),
            FlexBasisParseError::InvalidValue("")
        );
        assert_eq!(
            FlexGrowParseErrorOwned::NegativeValue(empty.clone()).to_shared(),
            FlexGrowParseError::NegativeValue("")
        );
        assert_eq!(
            FlexShrinkParseErrorOwned::NegativeValue(empty).to_shared(),
            FlexShrinkParseError::NegativeValue("")
        );
    }
    /// Errors surfaced by the real parsers must convert to owned form and
    /// render a non-empty message that names the offending property.
    #[cfg(feature = "parser")]
    #[test]
    fn parser_errors_to_contained_and_display() {
        let e = parse_layout_flex_grow("bogus").unwrap_err();
        assert_eq!(e.to_contained().to_shared(), e);
        assert!(format!("{e}").contains("flex-grow"));
        let e = parse_layout_flex_shrink("-1").unwrap_err();
        assert_eq!(e.to_contained().to_shared(), e);
        assert!(format!("{e}").contains("flex-shrink"));
        let e = parse_layout_flex_direction("\u{1F600}").unwrap_err();
        assert_eq!(e.to_contained().to_shared(), e);
        assert!(format!("{e}").contains("flex-direction"));
        let e = parse_layout_flex_wrap("").unwrap_err();
        assert_eq!(e.to_contained().to_shared(), e);
        assert!(format!("{e}").contains("flex-wrap"));
        let e = parse_layout_justify_content("nope").unwrap_err();
        assert_eq!(e.to_contained().to_shared(), e);
        assert!(format!("{e}").contains("justify-content"));
        let e = parse_layout_align_items("nope").unwrap_err();
        assert_eq!(e.to_contained().to_shared(), e);
        assert!(format!("{e}").contains("align-items"));
        let e = parse_layout_align_content("nope").unwrap_err();
        assert_eq!(e.to_contained().to_shared(), e);
        assert!(format!("{e}").contains("align-content"));
        let e = parse_layout_align_self("nope").unwrap_err();
        assert_eq!(e.to_contained().to_shared(), e);
        assert!(format!("{e}").contains("align-self"));
        let e = parse_layout_flex_basis("none").unwrap_err();
        assert_eq!(e.to_contained().to_shared(), e);
        assert!(format!("{e}").contains("flex-basis"));
    }
}