1
//! CSS properties for positioning elements: `position`, `top`, `right`,
2
//! `bottom`, `left`, and `z-index`. Types defined here are consumed by the
3
//! layout solver to resolve positioned elements.
4

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

            
7
#[cfg(feature = "parser")]
8
use crate::props::basic::pixel::parse_pixel_value;
9
use crate::{
10
    corety::AzString,
11
    props::{
12
        basic::pixel::{CssPixelValueParseError, CssPixelValueParseErrorOwned, PixelValue},
13
        formatter::PrintAsCssValue,
14
        macros::PixelValueTaker,
15
    },
16
};
17

            
18
// --- LayoutPosition ---
19

            
20
/// Represents a `position` attribute - default: `Static`
21
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
22
#[repr(C)]
23
#[derive(Default)]
24
pub enum LayoutPosition {
25
    #[default]
26
    Static,
27
    Relative,
28
    Absolute,
29
    Fixed,
30
    Sticky,
31
}
32

            
33
impl LayoutPosition {
34
    #[must_use]
35
7931
    pub fn is_positioned(&self) -> bool {
36
7931
        *self != Self::Static
37
7931
    }
38
}
39

            
40
impl PrintAsCssValue for LayoutPosition {
41
10
    fn print_as_css_value(&self) -> String {
42
10
        String::from(match self {
43
2
            Self::Static => "static",
44
2
            Self::Relative => "relative",
45
2
            Self::Absolute => "absolute",
46
2
            Self::Fixed => "fixed",
47
2
            Self::Sticky => "sticky",
48
        })
49
10
    }
50
}
51

            
52
impl_enum_fmt!(LayoutPosition, Static, Fixed, Absolute, Relative, Sticky);
53

            
54
// -- Parser for LayoutPosition
55

            
56
#[derive(Clone, PartialEq, Eq)]
57
pub enum LayoutPositionParseError<'a> {
58
    InvalidValue(&'a str),
59
}
60

            
61
impl_debug_as_display!(LayoutPositionParseError<'a>);
62
impl_display! { LayoutPositionParseError<'a>, {
63
    InvalidValue(val) => format!("Invalid position value: \"{}\"", val),
64
}}
65

            
66
#[derive(Debug, Clone, PartialEq, Eq)]
67
#[repr(C, u8)]
68
pub enum LayoutPositionParseErrorOwned {
69
    InvalidValue(AzString),
70
}
71

            
72
impl LayoutPositionParseError<'_> {
73
    #[must_use]
74
13
    pub fn to_contained(&self) -> LayoutPositionParseErrorOwned {
75
13
        match self {
76
13
            LayoutPositionParseError::InvalidValue(s) => {
77
13
                LayoutPositionParseErrorOwned::InvalidValue((*s).to_string().into())
78
            }
79
        }
80
13
    }
81
}
82

            
83
impl LayoutPositionParseErrorOwned {
84
    #[must_use]
85
13
    pub fn to_shared(&self) -> LayoutPositionParseError<'_> {
86
13
        match self {
87
13
            Self::InvalidValue(s) => LayoutPositionParseError::InvalidValue(s.as_str()),
88
        }
89
13
    }
90
}
91

            
92
#[cfg(feature = "parser")]
93
/// # Errors
94
///
95
/// Returns an error if `input` is not a valid CSS `position` value.
96
37847
pub fn parse_layout_position(input: &str) -> Result<LayoutPosition, LayoutPositionParseError<'_>> {
97
37847
    let input = input.trim();
98
37847
    match input {
99
37847
        "static" => Ok(LayoutPosition::Static),
100
37791
        "relative" => Ok(LayoutPosition::Relative),
101
30590
        "absolute" => Ok(LayoutPosition::Absolute),
102
443
        "fixed" => Ok(LayoutPosition::Fixed),
103
301
        "sticky" => Ok(LayoutPosition::Sticky),
104
50
        _ => Err(LayoutPositionParseError::InvalidValue(input)),
105
    }
106
37847
}
107

            
108
// --- Offset Properties (top, right, bottom, left) ---
109

            
110
macro_rules! define_position_property {
111
    ($struct_name:ident) => {
112
        #[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
113
        #[repr(C)]
114
        pub struct $struct_name {
115
            pub inner: PixelValue,
116
        }
117

            
118
        impl ::core::fmt::Debug for $struct_name {
119
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
120
                write!(f, "{}", self.inner)
121
            }
122
        }
123

            
124
        impl PixelValueTaker for $struct_name {
125
            fn from_pixel_value(inner: PixelValue) -> Self {
126
                Self { inner }
127
            }
128
        }
129

            
130
        impl_pixel_value!($struct_name);
131

            
132
        impl PrintAsCssValue for $struct_name {
133
66
            fn print_as_css_value(&self) -> String {
134
66
                format!("{}", self.inner)
135
66
            }
136
        }
137
    };
138
}
139

            
140
/// Represents the CSS `top` offset property for positioned elements.
141
define_position_property!(LayoutTop);
142
/// Represents the CSS `right` offset property for positioned elements.
143
define_position_property!(LayoutRight);
144
/// Represents the CSS `bottom` offset property for positioned elements.
145
define_position_property!(LayoutInsetBottom);
146
/// Represents the CSS `left` offset property for positioned elements.
147
define_position_property!(LayoutLeft);
148

            
149
// -- Parse error types and parsers for offset properties (top, right, bottom, left)
150

            
151
macro_rules! define_offset_parse_error {
152
    ($struct_name:ident, $error_name:ident, $error_owned_name:ident, $parse_fn:ident) => {
153
        #[derive(Clone, PartialEq, Eq)]
154
        pub enum $error_name<'a> {
155
            PixelValue(CssPixelValueParseError<'a>),
156
        }
157
        impl_debug_as_display!($error_name<'a>);
158
        impl_display! { $error_name<'a>, { PixelValue(e) => format!("{}", e), }}
159
        impl_from!(CssPixelValueParseError<'a>, $error_name::PixelValue);
160

            
161
        #[derive(Debug, Clone, PartialEq, Eq)]
162
        #[repr(C, u8)]
163
        pub enum $error_owned_name {
164
            PixelValue(CssPixelValueParseErrorOwned),
165
        }
166
        impl $error_name<'_> {
167
            #[must_use]
168
8
            pub fn to_contained(&self) -> $error_owned_name {
169
8
                match self {
170
8
                    $error_name::PixelValue(e) => $error_owned_name::PixelValue(e.to_contained()),
171
                }
172
8
            }
173
        }
174
        impl $error_owned_name {
175
            #[must_use]
176
8
            pub fn to_shared(&self) -> $error_name<'_> {
177
8
                match self {
178
8
                    $error_owned_name::PixelValue(e) => $error_name::PixelValue(e.to_shared()),
179
                }
180
8
            }
181
        }
182

            
183
        #[cfg(feature = "parser")]
184
        /// # Errors
185
        ///
186
        /// Returns an error if `input` is not a valid CSS value for this property.
187
61919
        pub fn $parse_fn(input: &str) -> Result<$struct_name, $error_name<'_>> {
188
61919
            parse_pixel_value(input)
189
61919
                .map(|v| $struct_name { inner: v })
190
61919
                .map_err(Into::into)
191
61919
        }
192
    };
193
}
194

            
195
define_offset_parse_error!(
196
    LayoutTop,
197
    LayoutTopParseError,
198
    LayoutTopParseErrorOwned,
199
    parse_layout_top
200
);
201
define_offset_parse_error!(
202
    LayoutRight,
203
    LayoutRightParseError,
204
    LayoutRightParseErrorOwned,
205
    parse_layout_right
206
);
207
define_offset_parse_error!(
208
    LayoutInsetBottom,
209
    LayoutInsetBottomParseError,
210
    LayoutInsetBottomParseErrorOwned,
211
    parse_layout_bottom
212
);
213
define_offset_parse_error!(
214
    LayoutLeft,
215
    LayoutLeftParseError,
216
    LayoutLeftParseErrorOwned,
217
    parse_layout_left
218
);
219

            
220
// --- LayoutZIndex ---
221

            
222
/// Represents a `z-index` attribute - controls stacking order of positioned elements
223
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
224
#[repr(C, u8)]
225
#[derive(Default)]
226
pub enum LayoutZIndex {
227
    #[default]
228
    Auto,
229
    Integer(i32),
230
}
231

            
232
// Formatting to Rust code
233
impl crate::codegen::format::FormatAsRustCode for LayoutZIndex {
234
2
    fn format_as_rust_code(&self, _tabs: usize) -> String {
235
2
        match self {
236
1
            Self::Auto => String::from("LayoutZIndex::Auto"),
237
1
            Self::Integer(val) => {
238
1
                format!("LayoutZIndex::Integer({val})")
239
            }
240
        }
241
2
    }
242
}
243

            
244
impl PrintAsCssValue for LayoutZIndex {
245
9
    fn print_as_css_value(&self) -> String {
246
9
        match self {
247
2
            Self::Auto => String::from("auto"),
248
7
            Self::Integer(val) => val.to_string(),
249
        }
250
9
    }
251
}
252

            
253
// -- Parser for LayoutZIndex
254

            
255
#[derive(Clone, PartialEq, Eq)]
256
pub enum LayoutZIndexParseError<'a> {
257
    InvalidValue(&'a str),
258
    ParseInt(::core::num::ParseIntError, &'a str),
259
}
260
impl_debug_as_display!(LayoutZIndexParseError<'a>);
261
impl_display! { LayoutZIndexParseError<'a>, {
262
    InvalidValue(val) => format!("Invalid z-index value: \"{}\"", val),
263
    ParseInt(e, s) => format!("Invalid z-index integer \"{}\": {}", s, e),
264
}}
265

            
266
/// Wrapper for `ParseIntError` that stores the error message and original
267
/// input as owned strings for FFI compatibility.
268
#[derive(Debug, Clone, PartialEq, Eq)]
269
#[repr(C)]
270
pub struct ParseIntErrorWithInput {
271
    /// The stringified parse error (e.g. "invalid digit found in string").
272
    pub error: AzString,
273
    /// The original input string that failed to parse.
274
    pub input: AzString,
275
}
276

            
277
#[derive(Debug, Clone, PartialEq, Eq)]
278
#[repr(C, u8)]
279
pub enum LayoutZIndexParseErrorOwned {
280
    InvalidValue(AzString),
281
    ParseInt(ParseIntErrorWithInput),
282
}
283

            
284
impl LayoutZIndexParseError<'_> {
285
    #[must_use]
286
10
    pub fn to_contained(&self) -> LayoutZIndexParseErrorOwned {
287
10
        match self {
288
6
            LayoutZIndexParseError::InvalidValue(s) => {
289
6
                LayoutZIndexParseErrorOwned::InvalidValue((*s).to_string().into())
290
            }
291
4
            LayoutZIndexParseError::ParseInt(e, s) => {
292
4
                LayoutZIndexParseErrorOwned::ParseInt(ParseIntErrorWithInput {
293
4
                    error: e.to_string().into(),
294
4
                    input: (*s).to_string().into(),
295
4
                })
296
            }
297
        }
298
10
    }
299
}
300

            
301
impl LayoutZIndexParseErrorOwned {
302
    /// Converts back to the borrowed error type.
303
    ///
304
    /// **Note:** This conversion is lossy for `ParseInt` — the original
305
    /// `core::num::ParseIntError` cannot be reconstructed from its string
306
    /// representation, so `ParseInt` is mapped to `InvalidValue` instead.
307
    #[must_use]
308
6
    pub fn to_shared(&self) -> LayoutZIndexParseError<'_> {
309
6
        match self {
310
4
            Self::InvalidValue(s) => LayoutZIndexParseError::InvalidValue(s.as_str()),
311
2
            Self::ParseInt(e) => {
312
                // We can't reconstruct ParseIntError, so use InvalidValue
313
2
                LayoutZIndexParseError::InvalidValue(e.input.as_str())
314
            }
315
        }
316
6
    }
317
}
318

            
319
#[cfg(feature = "parser")]
320
/// # Errors
321
///
322
/// Returns an error if `input` is not a valid CSS `z-index` value.
323
194
pub fn parse_layout_z_index(input: &str) -> Result<LayoutZIndex, LayoutZIndexParseError<'_>> {
324
194
    let input = input.trim();
325
194
    if input == "auto" {
326
3
        return Ok(LayoutZIndex::Auto);
327
191
    }
328

            
329
191
    match input.parse::<i32>() {
330
145
        Ok(val) => Ok(LayoutZIndex::Integer(val)),
331
46
        Err(e) => Err(LayoutZIndexParseError::ParseInt(e, input)),
332
    }
333
194
}
334

            
335
#[cfg(all(test, feature = "parser"))]
336
mod tests {
337
    use super::*;
338

            
339
    #[test]
340
1
    fn test_parse_layout_position() {
341
1
        assert_eq!(
342
1
            parse_layout_position("static").unwrap(),
343
            LayoutPosition::Static
344
        );
345
1
        assert_eq!(
346
1
            parse_layout_position("relative").unwrap(),
347
            LayoutPosition::Relative
348
        );
349
1
        assert_eq!(
350
1
            parse_layout_position("absolute").unwrap(),
351
            LayoutPosition::Absolute
352
        );
353
1
        assert_eq!(
354
1
            parse_layout_position("fixed").unwrap(),
355
            LayoutPosition::Fixed
356
        );
357
1
        assert_eq!(
358
1
            parse_layout_position("sticky").unwrap(),
359
            LayoutPosition::Sticky
360
        );
361
1
    }
362

            
363
    #[test]
364
1
    fn test_parse_layout_position_whitespace() {
365
1
        assert_eq!(
366
1
            parse_layout_position("  absolute  ").unwrap(),
367
            LayoutPosition::Absolute
368
        );
369
1
    }
370

            
371
    #[test]
372
1
    fn test_parse_layout_position_invalid() {
373
1
        assert!(parse_layout_position("").is_err());
374
1
        assert!(parse_layout_position("absolutely").is_err());
375
1
    }
376

            
377
    #[test]
378
1
    fn test_parse_layout_z_index() {
379
1
        assert_eq!(parse_layout_z_index("auto").unwrap(), LayoutZIndex::Auto);
380
1
        assert_eq!(
381
1
            parse_layout_z_index("10").unwrap(),
382
            LayoutZIndex::Integer(10)
383
        );
384
1
        assert_eq!(parse_layout_z_index("0").unwrap(), LayoutZIndex::Integer(0));
385
1
        assert_eq!(
386
1
            parse_layout_z_index("-5").unwrap(),
387
            LayoutZIndex::Integer(-5)
388
        );
389
1
        assert_eq!(
390
1
            parse_layout_z_index("  999  ").unwrap(),
391
            LayoutZIndex::Integer(999)
392
        );
393
1
    }
394

            
395
    #[test]
396
1
    fn test_parse_layout_z_index_invalid() {
397
1
        assert!(parse_layout_z_index("10px").is_err());
398
1
        assert!(parse_layout_z_index("1.5").is_err());
399
1
        assert!(parse_layout_z_index("none").is_err());
400
1
        assert!(parse_layout_z_index("").is_err());
401
1
    }
402

            
403
    #[test]
404
1
    fn test_parse_offsets() {
405
1
        assert_eq!(
406
1
            parse_layout_top("10px").unwrap(),
407
1
            LayoutTop {
408
1
                inner: PixelValue::px(10.0)
409
1
            }
410
        );
411
1
        assert_eq!(
412
1
            parse_layout_right("5%").unwrap(),
413
1
            LayoutRight {
414
1
                inner: PixelValue::percent(5.0)
415
1
            }
416
        );
417
1
        assert_eq!(
418
1
            parse_layout_bottom("2.5em").unwrap(),
419
1
            LayoutInsetBottom {
420
1
                inner: PixelValue::em(2.5)
421
1
            }
422
        );
423
1
        assert_eq!(
424
1
            parse_layout_left("0").unwrap(),
425
1
            LayoutLeft {
426
1
                inner: PixelValue::px(0.0)
427
1
            }
428
        );
429
1
    }
430

            
431
    #[test]
432
1
    fn test_parse_offsets_invalid() {
433
        // The simple `parse_pixel_value` does not handle `auto`.
434
1
        assert!(parse_layout_top("auto").is_err());
435
1
        assert!(parse_layout_right("").is_err());
436
        // Liberal parsing accepts whitespace between number and unit
437
1
        assert!(parse_layout_bottom("10 px").is_ok());
438
1
        assert!(parse_layout_left("ten pixels").is_err());
439
1
    }
440
}
441

            
442
#[cfg(test)]
443
mod autotest_generated {
444
    use alloc::{string::String, vec::Vec};
445

            
446
    use super::*;
447
    use crate::{codegen::format::FormatAsRustCode, props::basic::length::SizeMetric};
448

            
449
    /// Every `LayoutPosition` variant, so tests stay exhaustive if one is added.
450
    const ALL_POSITIONS: [LayoutPosition; 5] = [
451
        LayoutPosition::Static,
452
        LayoutPosition::Relative,
453
        LayoutPosition::Absolute,
454
        LayoutPosition::Fixed,
455
        LayoutPosition::Sticky,
456
    ];
457

            
458
    /// Every `SizeMetric` variant *except* `Vmin`, which cannot survive a
459
    /// `parse_pixel_value` round-trip — see `vmin_suffix_is_shadowed_by_in_bug`.
460
    const ROUNDTRIPPABLE_METRICS: [SizeMetric; 11] = [
461
        SizeMetric::Px,
462
        SizeMetric::Pt,
463
        SizeMetric::Em,
464
        SizeMetric::Rem,
465
        SizeMetric::In,
466
        SizeMetric::Cm,
467
        SizeMetric::Mm,
468
        SizeMetric::Percent,
469
        SizeMetric::Vw,
470
        SizeMetric::Vh,
471
        SizeMetric::Vmax,
472
    ];
473

            
474
    // ---------------------------------------------------------------------
475
    // LayoutPosition::is_positioned (predicate)
476
    // ---------------------------------------------------------------------
477

            
478
    #[test]
479
    fn is_positioned_basic_true_false() {
480
        assert!(!LayoutPosition::Static.is_positioned());
481
        assert!(LayoutPosition::Absolute.is_positioned());
482
    }
483

            
484
    #[test]
485
    fn is_positioned_holds_for_every_variant() {
486
        // The invariant the layout solver relies on: positioned <=> not static.
487
        for p in ALL_POSITIONS {
488
            assert_eq!(p.is_positioned(), p != LayoutPosition::Static, "{p:?}");
489
        }
490
    }
491

            
492
    #[test]
493
    fn is_positioned_default_is_static_and_unpositioned() {
494
        assert_eq!(LayoutPosition::default(), LayoutPosition::Static);
495
        assert!(!LayoutPosition::default().is_positioned());
496
    }
497

            
498
    #[test]
499
    fn is_positioned_is_pure() {
500
        // Takes &self; repeated calls must not mutate or drift.
501
        let p = LayoutPosition::Sticky;
502
        assert_eq!(p.is_positioned(), p.is_positioned());
503
        assert!(p.is_positioned());
504
    }
505

            
506
    // ---------------------------------------------------------------------
507
    // parse_layout_position (parser)
508
    // ---------------------------------------------------------------------
509

            
510
    #[cfg(feature = "parser")]
511
    #[test]
512
    fn parse_position_valid_minimal() {
513
        assert_eq!(parse_layout_position("static"), Ok(LayoutPosition::Static));
514
        assert_eq!(
515
            parse_layout_position("relative"),
516
            Ok(LayoutPosition::Relative)
517
        );
518
        assert_eq!(
519
            parse_layout_position("absolute"),
520
            Ok(LayoutPosition::Absolute)
521
        );
522
        assert_eq!(parse_layout_position("fixed"), Ok(LayoutPosition::Fixed));
523
        assert_eq!(parse_layout_position("sticky"), Ok(LayoutPosition::Sticky));
524
    }
525

            
526
    #[cfg(feature = "parser")]
527
    #[test]
528
    fn parse_position_empty_and_whitespace_only() {
529
        // Empty and whitespace-only both trim down to "" and must report "".
530
        for input in ["", "   ", "\t\n", "\r\n\t  \x0c", " \u{0b} "] {
531
            let err =
532
                parse_layout_position(input).expect_err("whitespace-only input must not parse");
533
            assert_eq!(err, LayoutPositionParseError::InvalidValue(""));
534
        }
535
    }
536

            
537
    #[cfg(feature = "parser")]
538
    #[test]
539
    fn parse_position_garbage_never_panics() {
540
        for input in [
541
            "absolutely",
542
            "STATIC",
543
            "position: absolute",
544
            "!@#$%^&*()",
545
            "\0\0\0",
546
            "-1",
547
            "0",
548
            "null",
549
            "static;",
550
            "static static",
551
            "\u{7f}\u{1}",
552
        ] {
553
            assert!(
554
                parse_layout_position(input).is_err(),
555
                "expected Err for {input:?}"
556
            );
557
        }
558
    }
559

            
560
    #[cfg(feature = "parser")]
561
    #[test]
562
    fn parse_position_is_ascii_case_sensitive() {
563
        // NOTE: pins *current* behaviour. Per CSS Syntax, keywords are ASCII
564
        // case-insensitive, so these arguably ought to be Ok(..) — see report.
565
        for input in ["Static", "STATIC", "sTaTiC", "Absolute", "FIXED"] {
566
            assert!(
567
                parse_layout_position(input).is_err(),
568
                "expected Err for {input:?}"
569
            );
570
        }
571
    }
572

            
573
    #[cfg(feature = "parser")]
574
    #[test]
575
    fn parse_position_trims_but_rejects_inner_junk() {
576
        // Surrounding whitespace is trimmed...
577
        assert_eq!(
578
            parse_layout_position("  \t absolute \n "),
579
            Ok(LayoutPosition::Absolute)
580
        );
581
        // ...but anything else attached to the keyword is rejected.
582
        for input in ["absolute;", "absolute garbage", ";absolute", "absolute,"] {
583
            assert!(
584
                parse_layout_position(input).is_err(),
585
                "expected Err for {input:?}"
586
            );
587
        }
588
    }
589

            
590
    #[cfg(feature = "parser")]
591
    #[test]
592
    fn parse_position_error_borrows_the_trimmed_input() {
593
        let err = parse_layout_position("   bogus   ").unwrap_err();
594
        assert_eq!(err, LayoutPositionParseError::InvalidValue("bogus"));
595
        // Display must show the trimmed slice, not the padded original.
596
        assert_eq!(err.to_string(), "Invalid position value: \"bogus\"");
597
    }
598

            
599
    #[cfg(feature = "parser")]
600
    #[test]
601
    fn parse_position_unicode_never_panics() {
602
        for input in [
603
            "\u{1F600}",
604
            "static\u{0301}", // combining acute accent
605
            "\u{202E}static", // RTL override
606
            "абсолютный",
607
            "\u{FEFF}static", // BOM is not ASCII whitespace -> must not parse
608
            "𝔰𝔱𝔞𝔱𝔦𝔠",
609
        ] {
610
            assert!(
611
                parse_layout_position(input).is_err(),
612
                "expected Err for {input:?}"
613
            );
614
        }
615
    }
616

            
617
    #[cfg(feature = "parser")]
618
    #[test]
619
    fn parse_position_extremely_long_input() {
620
        let huge = "static".repeat(200_000); // ~1.2M bytes
621
        assert!(parse_layout_position(&huge).is_err());
622

            
623
        let huge_ws = String::from(" ").repeat(1_000_000);
624
        assert_eq!(
625
            parse_layout_position(&huge_ws),
626
            Err(LayoutPositionParseError::InvalidValue(""))
627
        );
628
    }
629

            
630
    #[cfg(feature = "parser")]
631
    #[test]
632
    fn parse_position_deeply_nested_does_not_stack_overflow() {
633
        let nested = "[".repeat(10_000);
634
        assert!(parse_layout_position(&nested).is_err());
635
    }
636

            
637
    #[cfg(feature = "parser")]
638
    #[test]
639
    fn parse_position_round_trip_encode_decode() {
640
        for p in ALL_POSITIONS {
641
            let css = p.print_as_css_value();
642
            assert_eq!(parse_layout_position(&css), Ok(p), "round-trip of {p:?}");
643
        }
644
    }
645

            
646
    #[cfg(feature = "parser")]
647
    #[test]
648
    fn parse_position_round_trip_decode_encode() {
649
        for css in ["static", "relative", "absolute", "fixed", "sticky"] {
650
            let parsed = parse_layout_position(css).unwrap();
651
            assert_eq!(parsed.print_as_css_value(), css);
652
        }
653
    }
654

            
655
    #[test]
656
    fn position_format_as_rust_code_names_the_variant() {
657
        assert_eq!(
658
            LayoutPosition::Static.format_as_rust_code(0),
659
            "LayoutPosition::Static"
660
        );
661
        assert_eq!(
662
            LayoutPosition::Sticky.format_as_rust_code(usize::MAX),
663
            "LayoutPosition::Sticky"
664
        );
665
    }
666

            
667
    // ---------------------------------------------------------------------
668
    // LayoutPositionParseError <-> Owned (getters)
669
    // ---------------------------------------------------------------------
670

            
671
    #[test]
672
    fn position_error_to_contained_basic_access() {
673
        let shared = LayoutPositionParseError::InvalidValue("bogus");
674
        assert_eq!(
675
            shared.to_contained(),
676
            LayoutPositionParseErrorOwned::InvalidValue("bogus".to_string().into())
677
        );
678
    }
679

            
680
    #[test]
681
    fn position_error_owned_to_shared_basic_access() {
682
        let owned = LayoutPositionParseErrorOwned::InvalidValue("bogus".to_string().into());
683
        assert_eq!(
684
            owned.to_shared(),
685
            LayoutPositionParseError::InvalidValue("bogus")
686
        );
687
    }
688

            
689
    #[test]
690
    fn position_error_round_trip_is_lossless_on_edge_payloads() {
691
        // Empty, unicode, NUL and a 100k-byte payload must all survive intact.
692
        let long = "x".repeat(100_000);
693
        for payload in [
694
            "",
695
            " ",
696
            "\0",
697
            "\u{1F600}\u{0301}",
698
            "quote\"and\\backslash",
699
            long.as_str(),
700
        ] {
701
            let shared = LayoutPositionParseError::InvalidValue(payload);
702
            let owned = shared.to_contained();
703
            assert_eq!(owned.to_shared(), shared, "payload {payload:?} was mangled");
704
            // ...and the owned form is a fixed point of the two conversions.
705
            assert_eq!(owned.to_shared().to_contained(), owned);
706
        }
707
    }
708

            
709
    // ---------------------------------------------------------------------
710
    // parse_layout_z_index (parser)
711
    // ---------------------------------------------------------------------
712

            
713
    #[cfg(feature = "parser")]
714
    #[test]
715
    fn parse_z_index_valid_minimal() {
716
        assert_eq!(parse_layout_z_index("auto"), Ok(LayoutZIndex::Auto));
717
        assert_eq!(parse_layout_z_index("1"), Ok(LayoutZIndex::Integer(1)));
718
    }
719

            
720
    #[cfg(feature = "parser")]
721
    #[test]
722
    fn parse_z_index_i32_boundaries_saturate_into_err_not_wraparound() {
723
        // Exactly at the i32 limits: must parse.
724
        assert_eq!(
725
            parse_layout_z_index("2147483647"),
726
            Ok(LayoutZIndex::Integer(i32::MAX))
727
        );
728
        assert_eq!(
729
            parse_layout_z_index("-2147483648"),
730
            Ok(LayoutZIndex::Integer(i32::MIN))
731
        );
732

            
733
        // One past the limits: must be a clean Err, never a wrapped value.
734
        for overflowing in [
735
            "2147483648",
736
            "-2147483649",
737
            "9223372036854775807",  // i64::MAX
738
            "-9223372036854775808", // i64::MIN
739
            "340282366920938463463374607431768211456",
740
        ] {
741
            let err =
742
                parse_layout_z_index(overflowing).expect_err("out-of-range integer must not parse");
743
            assert!(
744
                matches!(err, LayoutZIndexParseError::ParseInt(_, s) if s == overflowing),
745
                "expected ParseInt({overflowing:?}), got {err:?}"
746
            );
747
        }
748
    }
749

            
750
    #[cfg(feature = "parser")]
751
    #[test]
752
    fn parse_z_index_zero_sign_and_padding_forms() {
753
        assert_eq!(parse_layout_z_index("0"), Ok(LayoutZIndex::Integer(0)));
754
        assert_eq!(parse_layout_z_index("-0"), Ok(LayoutZIndex::Integer(0)));
755
        assert_eq!(parse_layout_z_index("+0"), Ok(LayoutZIndex::Integer(0)));
756
        assert_eq!(parse_layout_z_index("+7"), Ok(LayoutZIndex::Integer(7)));
757
        assert_eq!(parse_layout_z_index("007"), Ok(LayoutZIndex::Integer(7)));
758
        assert_eq!(
759
            parse_layout_z_index("  \t -42 \n "),
760
            Ok(LayoutZIndex::Integer(-42))
761
        );
762
    }
763

            
764
    #[cfg(feature = "parser")]
765
    #[test]
766
    fn parse_z_index_rejects_floats_and_float_literals() {
767
        // z-index is an <integer>; nothing float-shaped may sneak through.
768
        for input in [
769
            "1.5", "1.0", "0.0", "-0.0", "1e3", "1E3", "1e-3", "NaN", "nan", "inf", "-inf",
770
            "infinity",
771
        ] {
772
            assert!(
773
                parse_layout_z_index(input).is_err(),
774
                "expected Err for {input:?}"
775
            );
776
        }
777
    }
778

            
779
    #[cfg(feature = "parser")]
780
    #[test]
781
    fn parse_z_index_garbage_never_panics() {
782
        for input in [
783
            "",
784
            "   ",
785
            "\t\n",
786
            "auto auto",
787
            "AUTO",
788
            "Auto",
789
            "none",
790
            "10px",
791
            "1_000",
792
            "1,000",
793
            "- 5",
794
            "5-",
795
            "--5",
796
            "++5",
797
            "0x1F",
798
            "0b1",
799
            "١٢٣",    // Arabic-Indic digits
800
            "123", // fullwidth digits
801
            "\u{1F600}",
802
            "\0",
803
            "5\0",
804
        ] {
805
            assert!(
806
                parse_layout_z_index(input).is_err(),
807
                "expected Err for {input:?}"
808
            );
809
        }
810
    }
811

            
812
    #[cfg(feature = "parser")]
813
    #[test]
814
    fn parse_z_index_extremely_long_input_terminates() {
815
        let huge = "9".repeat(1_000_000);
816
        assert!(parse_layout_z_index(&huge).is_err());
817

            
818
        let nested = "[".repeat(10_000);
819
        assert!(parse_layout_z_index(&nested).is_err());
820
    }
821

            
822
    #[cfg(feature = "parser")]
823
    #[test]
824
    fn parse_z_index_error_borrows_the_trimmed_input() {
825
        let err = parse_layout_z_index("  abc  ").unwrap_err();
826
        assert!(
827
            matches!(&err, LayoutZIndexParseError::ParseInt(_, s) if *s == "abc"),
828
            "got {err:?}"
829
        );
830
        assert!(err
831
            .to_string()
832
            .starts_with("Invalid z-index integer \"abc\""));
833
    }
834

            
835
    #[cfg(feature = "parser")]
836
    #[test]
837
    fn parse_z_index_round_trip_encode_decode() {
838
        let values = [
839
            LayoutZIndex::Auto,
840
            LayoutZIndex::Integer(0),
841
            LayoutZIndex::Integer(1),
842
            LayoutZIndex::Integer(-1),
843
            LayoutZIndex::Integer(12_345),
844
            LayoutZIndex::Integer(-99_999),
845
            LayoutZIndex::Integer(i32::MAX),
846
            LayoutZIndex::Integer(i32::MIN),
847
        ];
848
        for z in values {
849
            let css = z.print_as_css_value();
850
            assert_eq!(parse_layout_z_index(&css), Ok(z), "round-trip of {z:?}");
851
        }
852
    }
853

            
854
    #[test]
855
    fn z_index_default_is_auto() {
856
        assert_eq!(LayoutZIndex::default(), LayoutZIndex::Auto);
857
        assert_eq!(LayoutZIndex::default().print_as_css_value(), "auto");
858
    }
859

            
860
    #[test]
861
    fn z_index_format_as_rust_code_survives_i32_min() {
862
        assert_eq!(
863
            LayoutZIndex::Auto.format_as_rust_code(0),
864
            "LayoutZIndex::Auto"
865
        );
866
        assert_eq!(
867
            LayoutZIndex::Integer(i32::MIN).format_as_rust_code(0),
868
            "LayoutZIndex::Integer(-2147483648)"
869
        );
870
    }
871

            
872
    // ---------------------------------------------------------------------
873
    // LayoutZIndexParseError <-> Owned (getters)
874
    // ---------------------------------------------------------------------
875

            
876
    #[test]
877
    fn z_index_error_invalid_value_round_trips_losslessly() {
878
        for payload in ["", "auto ", "\u{1F600}", "\0"] {
879
            let shared = LayoutZIndexParseError::InvalidValue(payload);
880
            let owned = shared.to_contained();
881
            assert_eq!(
882
                owned,
883
                LayoutZIndexParseErrorOwned::InvalidValue(payload.to_string().into())
884
            );
885
            assert_eq!(owned.to_shared(), shared);
886
        }
887
    }
888

            
889
    #[test]
890
    fn z_index_error_to_contained_captures_parse_int_message_and_input() {
891
        let int_err = "abc".parse::<i32>().unwrap_err();
892
        let shared = LayoutZIndexParseError::ParseInt(int_err.clone(), "abc");
893

            
894
        match shared.to_contained() {
895
            LayoutZIndexParseErrorOwned::ParseInt(e) => {
896
                assert_eq!(e.input.as_str(), "abc");
897
                assert!(!e.error.as_str().is_empty());
898
                assert_eq!(e.error.as_str(), int_err.to_string());
899
            }
900
            other => panic!("expected ParseInt, got {other:?}"),
901
        }
902
    }
903

            
904
    #[test]
905
    fn z_index_error_overflow_and_invalid_digit_are_distinct_before_to_shared() {
906
        let invalid_digit = "abc".parse::<i32>().unwrap_err();
907
        let overflow = "2147483648".parse::<i32>().unwrap_err();
908

            
909
        let a = LayoutZIndexParseError::ParseInt(invalid_digit, "abc").to_contained();
910
        let b = LayoutZIndexParseError::ParseInt(overflow, "2147483648").to_contained();
911
        assert_ne!(a, b, "the two ParseIntError kinds must not collapse");
912
    }
913

            
914
    #[test]
915
    fn z_index_error_to_shared_is_lossy_for_parse_int_as_documented() {
916
        let int_err = "abc".parse::<i32>().unwrap_err();
917
        let owned = LayoutZIndexParseError::ParseInt(int_err, "abc").to_contained();
918

            
919
        // Documented: ParseIntError cannot be rebuilt, so ParseInt -> InvalidValue.
920
        let shared = owned.to_shared();
921
        assert_eq!(shared, LayoutZIndexParseError::InvalidValue("abc"));
922

            
923
        // ...which means the owned form is NOT a fixed point of the two
924
        // conversions. This asserts the lossiness is exactly as documented,
925
        // and will fail loudly if someone silently changes the mapping.
926
        assert_ne!(shared.to_contained(), owned);
927
        assert_eq!(
928
            shared.to_contained(),
929
            LayoutZIndexParseErrorOwned::InvalidValue("abc".to_string().into())
930
        );
931
    }
932

            
933
    #[test]
934
    fn z_index_error_to_shared_on_empty_parse_int_payload_does_not_panic() {
935
        let owned = LayoutZIndexParseErrorOwned::ParseInt(ParseIntErrorWithInput {
936
            error: String::new().into(),
937
            input: String::new().into(),
938
        });
939
        assert_eq!(owned.to_shared(), LayoutZIndexParseError::InvalidValue(""));
940
    }
941

            
942
    // ---------------------------------------------------------------------
943
    // Offset properties: top / right / bottom / left
944
    // ---------------------------------------------------------------------
945

            
946
    #[cfg(feature = "parser")]
947
    #[test]
948
    fn offsets_nan_input_saturates_to_zero_instead_of_propagating_nan() {
949
        // f32::from_str accepts "NaN"; PixelValue stores fixed-point isize, and
950
        // `NaN as isize` == 0. Assert the NaN is absorbed, not carried into layout.
951
        for input in ["NaN", "nan", "-NaN", "NaNpx", "nan%"] {
952
            let v = parse_layout_top(input)
953
                .unwrap_or_else(|e| panic!("{input:?} should parse, got {e:?}"));
954
            let n = v.inner.number.get();
955
            assert!(!n.is_nan(), "{input:?} leaked a NaN into PixelValue");
956
            assert_eq!(n, 0.0, "{input:?} should saturate to 0");
957
        }
958
    }
959

            
960
    #[cfg(feature = "parser")]
961
    #[test]
962
    fn offsets_infinite_input_saturates_to_finite_bounds() {
963
        // f32::from_str maps overflow to +/-inf; the fixed-point cast then
964
        // saturates at isize::MIN/MAX. Nothing infinite may reach the solver.
965
        for (input, positive) in [
966
            ("inf", true),
967
            ("infinity", true),
968
            ("-inf", false),
969
            ("1e40px", true),
970
            ("-1e40px", false),
971
            ("99999999999999999999999999999999999999999999px", true),
972
        ] {
973
            let v = parse_layout_right(input)
974
                .unwrap_or_else(|e| panic!("{input:?} should parse, got {e:?}"));
975
            let n = v.inner.number.get();
976
            assert!(n.is_finite(), "{input:?} leaked a non-finite PixelValue");
977
            assert_eq!(n > 0.0, positive, "{input:?} lost its sign");
978
        }
979
    }
980

            
981
    #[cfg(feature = "parser")]
982
    #[test]
983
    fn offsets_subnormal_input_flushes_to_zero() {
984
        // Below the 1/1000 fixed-point resolution everything truncates to 0.
985
        for input in ["1e-40px", "-1e-40px", "0.0001px", "0.0009px"] {
986
            let v = parse_layout_bottom(input)
987
                .unwrap_or_else(|e| panic!("{input:?} should parse, got {e:?}"));
988
            assert_eq!(v.inner.number.get(), 0.0, "{input:?} should truncate to 0");
989
        }
990
    }
991

            
992
    #[cfg(feature = "parser")]
993
    #[test]
994
    fn offsets_reject_empty_garbage_and_unicode() {
995
        for input in [
996
            "",
997
            "   ",
998
            "auto",
999
            "px",
            "%",
            "10 20px",
            "ten pixels",
            "10pxx",
            "10 px extra",
            "\u{1F600}",
            "١٠px", // Arabic-Indic digits
            "10\u{00B5}m",
        ] {
            assert!(
                parse_layout_left(input).is_err(),
                "expected Err for {input:?}"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn offsets_extremely_long_input_terminates() {
        let huge = "9".repeat(1_000_000);
        // Parses to a saturated-but-finite value; must not hang or panic.
        let v = parse_layout_top(&huge).expect("a million 9s is a valid f32 literal");
        assert!(v.inner.number.get().is_finite());
        let junk = "z".repeat(1_000_000);
        assert!(parse_layout_top(&junk).is_err());
        let nested = "[".repeat(10_000);
        assert!(parse_layout_top(&nested).is_err());
    }
    #[cfg(feature = "parser")]
    #[test]
    fn offsets_round_trip_encode_decode_across_metrics() {
        // Values chosen to be exact at the 1/1000 fixed-point resolution.
        for metric in ROUNDTRIPPABLE_METRICS {
            for raw in [0.0_f32, 1.0, -1.0, 10.5, -7.25, 1024.0] {
                let expected = LayoutTop {
                    inner: PixelValue::from_metric(metric, raw),
                };
                let css = expected.print_as_css_value();
                let parsed = parse_layout_top(&css)
                    .unwrap_or_else(|e| panic!("{css:?} failed to re-parse: {e:?}"));
                assert_eq!(parsed, expected, "round-trip of {css:?}");
            }
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn offsets_all_four_sides_agree_on_the_same_input() {
        // The four parsers are macro-generated; they must not diverge.
        let t = parse_layout_top("12.5%").unwrap();
        let r = parse_layout_right("12.5%").unwrap();
        let b = parse_layout_bottom("12.5%").unwrap();
        let l = parse_layout_left("12.5%").unwrap();
        assert_eq!(t.inner, r.inner);
        assert_eq!(r.inner, b.inner);
        assert_eq!(b.inner, l.inner);
        assert_eq!(t.inner, PixelValue::percent(12.5));
    }
    #[cfg(feature = "parser")]
    #[test]
    fn offsets_zero_is_bare_number_defaulting_to_px() {
        assert_eq!(parse_layout_left("0").unwrap(), LayoutLeft::zero());
        assert_eq!(LayoutTop::zero().inner, PixelValue::px(0.0));
        assert_eq!(LayoutTop::default().inner, PixelValue::zero());
    }
    #[cfg(feature = "parser")]
    #[test]
    fn offset_error_round_trip_is_lossless_for_every_variant() {
        // Drive each CssPixelValueParseError variant through the real parser,
        // then assert to_contained/to_shared preserves it.
        let inputs = ["", "px", "abcpx", "not-a-length"];
        let mut seen: Vec<String> = Vec::new();
        for input in inputs {
            let err = parse_layout_top(input).unwrap_err();
            let owned = err.to_contained();
            assert_eq!(owned.to_shared(), err, "error for {input:?} was mangled");
            assert_eq!(owned.to_shared().to_contained(), owned);
            seen.push(err.to_string());
        }
        // The four inputs must exercise four *distinct* error messages,
        // otherwise this test is silently only covering one variant.
        seen.sort();
        seen.dedup();
        assert_eq!(seen.len(), 4, "expected 4 distinct pixel-value errors");
    }
    /// KNOWN BUG (pinned, not endorsed): `vmin` lengths are unparseable.
    ///
    /// `parse_pixel_value`'s suffix table tries `("in", In)` *before*
    /// `("vmin", Vmin)`, so `"10vmin"` hits `strip_suffix("in")` first, leaving
    /// `"10vm"` to be parsed as an f32 — which fails. Every `vmin` length in a
    /// stylesheet is therefore silently dropped, on `top`/`right`/`bottom`/
    /// `left` and on every other property that goes through `parse_pixel_value`.
    ///
    /// This test asserts the *current* (broken) behaviour so the suite stays
    /// honest; flip it to `is_ok()` / an equality assert once the suffix table
    /// in `css/src/props/basic/pixel.rs` is reordered.
    #[cfg(feature = "parser")]
    #[test]
    fn vmin_suffix_is_shadowed_by_in_bug() {
        // FIXED (was a characterization of the bug): "vmin" used to be shadowed by an
        // earlier "in" suffix and rejected. It now parses on every longhand.
        assert!(parse_layout_top("10vmin").is_ok());
        assert!(parse_layout_right("0vmin").is_ok());
        assert!(parse_layout_bottom("2.5vmin").is_ok());
        assert!(parse_layout_left("100vmin").is_ok());
        // The neighbouring viewport units keep working too.
        assert!(parse_layout_top("10vmax").is_ok());
        assert!(parse_layout_top("10vw").is_ok());
        assert!(parse_layout_top("10vh").is_ok());
    }
}