1
//! CSS properties for flowing content around shapes (CSS Shapes Module).
2
//!
3
//! Defines [`ShapeOutside`], [`ShapeInside`], [`ClipPath`], [`ShapeMargin`],
4
//! and [`ShapeImageThreshold`]. Note: `ClipPath` belongs to CSS Masking but
5
//! is co-located here for convenience.
6

            
7
use alloc::string::{String, ToString};
8

            
9
use crate::{
10
    props::{
11
        basic::{
12
            length::{parse_float_value, FloatValue},
13
            pixel::{parse_pixel_value, CssPixelValueParseError, PixelValue},
14
        },
15
        formatter::PrintAsCssValue,
16
    },
17
    shape::CssShape,
18
};
19
#[allow(variant_size_differences)]
20
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
21
// disparity accepted
22
/// CSS shape-outside property for wrapping text around shapes
23
#[derive(Debug, Clone, PartialEq)]
24
#[repr(C, u8)]
25
#[derive(Default)]
26
pub enum ShapeOutside {
27
    #[default]
28
    None,
29
    Shape(CssShape),
30
}
31

            
32
impl Eq for ShapeOutside {}
33
impl core::hash::Hash for ShapeOutside {
34
2
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
35
2
        core::mem::discriminant(self).hash(state);
36
2
        if let Self::Shape(s) = self {
37
1
            s.hash(state);
38
1
        }
39
2
    }
40
}
41
impl PartialOrd for ShapeOutside {
42
1
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
43
1
        Some(self.cmp(other))
44
1
    }
45
}
46
impl Ord for ShapeOutside {
47
2
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
48
2
        match (self, other) {
49
            (Self::None, Self::None) => core::cmp::Ordering::Equal,
50
2
            (Self::None, Self::Shape(_)) => core::cmp::Ordering::Less,
51
            (Self::Shape(_), Self::None) => core::cmp::Ordering::Greater,
52
            (Self::Shape(a), Self::Shape(b)) => a.cmp(b),
53
        }
54
2
    }
55
}
56

            
57
impl PrintAsCssValue for ShapeOutside {
58
23
    fn print_as_css_value(&self) -> String {
59
23
        match self {
60
3
            Self::None => "none".to_string(),
61
20
            Self::Shape(shape) => shape.print_as_css_value(),
62
        }
63
23
    }
64
}
65
#[allow(variant_size_differences)]
66
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
67
// disparity accepted
68
/// CSS shape-inside property for flowing text within shapes
69
#[derive(Debug, Clone, PartialEq)]
70
#[repr(C, u8)]
71
#[derive(Default)]
72
pub enum ShapeInside {
73
    #[default]
74
    None,
75
    Shape(CssShape),
76
}
77

            
78
impl Eq for ShapeInside {}
79
impl core::hash::Hash for ShapeInside {
80
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
81
        core::mem::discriminant(self).hash(state);
82
        if let Self::Shape(s) = self {
83
            s.hash(state);
84
        }
85
    }
86
}
87
impl PartialOrd for ShapeInside {
88
1
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
89
1
        Some(self.cmp(other))
90
1
    }
91
}
92
impl Ord for ShapeInside {
93
2
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
94
2
        match (self, other) {
95
            (Self::None, Self::None) => core::cmp::Ordering::Equal,
96
2
            (Self::None, Self::Shape(_)) => core::cmp::Ordering::Less,
97
            (Self::Shape(_), Self::None) => core::cmp::Ordering::Greater,
98
            (Self::Shape(a), Self::Shape(b)) => a.cmp(b),
99
        }
100
2
    }
101
}
102

            
103
impl PrintAsCssValue for ShapeInside {
104
12
    fn print_as_css_value(&self) -> String {
105
12
        match self {
106
2
            Self::None => "none".to_string(),
107
10
            Self::Shape(shape) => shape.print_as_css_value(),
108
        }
109
12
    }
110
}
111
#[allow(variant_size_differences)]
112
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
113
// disparity accepted
114
/// CSS clip-path property for clipping element rendering
115
#[derive(Debug, Clone, PartialEq)]
116
#[repr(C, u8)]
117
#[derive(Default)]
118
pub enum ClipPath {
119
    #[default]
120
    None,
121
    Shape(CssShape),
122
}
123

            
124
impl Eq for ClipPath {}
125
impl core::hash::Hash for ClipPath {
126
10
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
127
10
        core::mem::discriminant(self).hash(state);
128
10
        if let Self::Shape(s) = self {
129
7
            s.hash(state);
130
7
        }
131
10
    }
132
}
133
impl PartialOrd for ClipPath {
134
2
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
135
2
        Some(self.cmp(other))
136
2
    }
137
}
138
impl Ord for ClipPath {
139
62
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
140
62
        match (self, other) {
141
1
            (Self::None, Self::None) => core::cmp::Ordering::Equal,
142
3
            (Self::None, Self::Shape(_)) => core::cmp::Ordering::Less,
143
1
            (Self::Shape(_), Self::None) => core::cmp::Ordering::Greater,
144
57
            (Self::Shape(a), Self::Shape(b)) => a.cmp(b),
145
        }
146
62
    }
147
}
148

            
149
impl PrintAsCssValue for ClipPath {
150
12
    fn print_as_css_value(&self) -> String {
151
12
        match self {
152
2
            Self::None => "none".to_string(),
153
10
            Self::Shape(shape) => shape.print_as_css_value(),
154
        }
155
12
    }
156
}
157

            
158
/// CSS `shape-margin` property — adds margin to the shape-outside exclusion area.
159
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
160
#[repr(C)]
161
pub struct ShapeMargin {
162
    pub inner: PixelValue,
163
}
164

            
165
impl Default for ShapeMargin {
166
3
    fn default() -> Self {
167
3
        Self {
168
3
            inner: PixelValue::zero(),
169
3
        }
170
3
    }
171
}
172

            
173
impl PrintAsCssValue for ShapeMargin {
174
8
    fn print_as_css_value(&self) -> String {
175
8
        self.inner.print_as_css_value()
176
8
    }
177
}
178

            
179
/// CSS `shape-image-threshold` property — alpha threshold for image-based shapes.
180
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
181
#[repr(C)]
182
pub struct ShapeImageThreshold {
183
    pub inner: FloatValue,
184
}
185

            
186
impl Default for ShapeImageThreshold {
187
2
    fn default() -> Self {
188
2
        Self {
189
2
            inner: FloatValue::const_new(0),
190
2
        }
191
2
    }
192
}
193

            
194
impl PrintAsCssValue for ShapeImageThreshold {
195
5
    fn print_as_css_value(&self) -> String {
196
5
        self.inner.to_string()
197
5
    }
198
}
199

            
200
// Formatting to Rust code
201
impl crate::codegen::format::FormatAsRustCode for ShapeOutside {
202
    fn format_as_rust_code(&self, _tabs: usize) -> String {
203
        match self {
204
            Self::None => String::from("ShapeOutside::None"),
205
            Self::Shape(s) => {
206
                let mut r = String::from("ShapeOutside::Shape(");
207
                r.push_str(&s.format_as_rust_code());
208
                r.push(')');
209
                r
210
            }
211
        }
212
    }
213
}
214

            
215
impl crate::codegen::format::FormatAsRustCode for ShapeInside {
216
    fn format_as_rust_code(&self, _tabs: usize) -> String {
217
        match self {
218
            Self::None => String::from("ShapeInside::None"),
219
            Self::Shape(s) => {
220
                let mut r = String::from("ShapeInside::Shape(");
221
                r.push_str(&s.format_as_rust_code());
222
                r.push(')');
223
                r
224
            }
225
        }
226
    }
227
}
228

            
229
impl crate::codegen::format::FormatAsRustCode for ClipPath {
230
    fn format_as_rust_code(&self, _tabs: usize) -> String {
231
        match self {
232
            Self::None => String::from("ClipPath::None"),
233
            Self::Shape(s) => {
234
                let mut r = String::from("ClipPath::Shape(");
235
                r.push_str(&s.format_as_rust_code());
236
                r.push(')');
237
                r
238
            }
239
        }
240
    }
241
}
242

            
243
impl crate::codegen::format::FormatAsRustCode for ShapeMargin {
244
    fn format_as_rust_code(&self, _tabs: usize) -> String {
245
        format!(
246
            "ShapeMargin {{ inner: {} }}",
247
            crate::codegen::format::format_pixel_value(&self.inner)
248
        )
249
    }
250
}
251

            
252
impl crate::codegen::format::FormatAsRustCode for ShapeImageThreshold {
253
    fn format_as_rust_code(&self, _tabs: usize) -> String {
254
        format!(
255
            "ShapeImageThreshold {{ inner: {} }}",
256
            crate::codegen::format::format_float_value(&self.inner)
257
        )
258
    }
259
}
260

            
261
// --- PARSERS ---
262
#[cfg(feature = "parser")]
263
pub mod parser {
264
    use core::num::ParseFloatError;
265

            
266
    #[allow(clippy::wildcard_imports)]
267
    // parser submodule reuses the parent module's value types
268
    use super::*;
269
    use crate::shape_parser::{parse_shape, ShapeParseError};
270

            
271
    /// Parser for shape-outside property
272
    /// # Errors
273
    ///
274
    /// Returns an error if `input` is not a valid CSS `shape-outside` value.
275
297
    pub fn parse_shape_outside(input: &str) -> Result<ShapeOutside, ShapeParseError> {
276
297
        let trimmed = input.trim();
277
297
        if trimmed == "none" {
278
12
            Ok(ShapeOutside::None)
279
        } else {
280
285
            let shape = parse_shape(trimmed)?;
281
113
            Ok(ShapeOutside::Shape(shape))
282
        }
283
297
    }
284

            
285
    /// Parser for shape-inside property
286
    /// # Errors
287
    ///
288
    /// Returns an error if `input` is not a valid CSS `shape-inside` value.
289
285
    pub fn parse_shape_inside(input: &str) -> Result<ShapeInside, ShapeParseError> {
290
285
        let trimmed = input.trim();
291
285
        if trimmed == "none" {
292
11
            Ok(ShapeInside::None)
293
        } else {
294
274
            let shape = parse_shape(trimmed)?;
295
102
            Ok(ShapeInside::Shape(shape))
296
        }
297
285
    }
298

            
299
    /// Parser for clip-path property
300
    /// # Errors
301
    ///
302
    /// Returns an error if `input` is not a valid CSS `clip-path` value.
303
387
    pub fn parse_clip_path(input: &str) -> Result<ClipPath, ShapeParseError> {
304
387
        let trimmed = input.trim();
305
387
        if trimmed == "none" {
306
12
            Ok(ClipPath::None)
307
        } else {
308
375
            let shape = parse_shape(trimmed)?;
309
148
            Ok(ClipPath::Shape(shape))
310
        }
311
387
    }
312

            
313
    /// Parser for shape-margin property
314
    /// # Errors
315
    ///
316
    /// Returns an error if `input` is not a valid CSS `shape-margin` value.
317
211
    pub fn parse_shape_margin(input: &str) -> Result<ShapeMargin, CssPixelValueParseError<'_>> {
318
        Ok(ShapeMargin {
319
211
            inner: parse_pixel_value(input)?,
320
        })
321
211
    }
322

            
323
    /// Parser for shape-image-threshold property
324
    /// # Errors
325
    ///
326
    /// Returns an error if `input` is not a valid CSS `shape-image-threshold` value.
327
191
    pub fn parse_shape_image_threshold(
328
191
        input: &str,
329
191
    ) -> Result<ShapeImageThreshold, ParseFloatError> {
330
191
        let val = parse_float_value(input)?;
331
        // value should be clamped between 0.0 and 1.0
332
55
        let clamped = val.get().clamp(0.0, 1.0);
333
55
        Ok(ShapeImageThreshold {
334
55
            inner: FloatValue::new(clamped),
335
55
        })
336
191
    }
337
}
338

            
339
#[cfg(feature = "parser")]
340
pub use parser::*;
341

            
342
#[cfg(all(test, feature = "parser"))]
343
mod tests {
344
    // Tests assert that parsed values equal the exact source literals.
345
    #![allow(clippy::float_cmp)]
346
    use super::*;
347

            
348
    #[test]
349
1
    fn test_parse_shape_properties() {
350
        // Test shape-outside
351
1
        assert!(matches!(
352
1
            parse_shape_outside("none").unwrap(),
353
            ShapeOutside::None
354
        ));
355
1
        assert!(matches!(
356
1
            parse_shape_outside("circle(50px)").unwrap(),
357
            ShapeOutside::Shape(_)
358
        ));
359

            
360
        // Test shape-inside
361
1
        assert!(matches!(
362
1
            parse_shape_inside("none").unwrap(),
363
            ShapeInside::None
364
        ));
365
1
        assert!(matches!(
366
1
            parse_shape_inside("circle(100px at 50px 50px)").unwrap(),
367
            ShapeInside::Shape(_)
368
        ));
369

            
370
        // Test clip-path
371
1
        assert!(matches!(parse_clip_path("none").unwrap(), ClipPath::None));
372
1
        assert!(matches!(
373
1
            parse_clip_path("polygon(0 0, 100px 0, 100px 100px, 0 100px)").unwrap(),
374
            ClipPath::Shape(_)
375
        ));
376

            
377
        // Test existing properties
378
1
        assert_eq!(
379
1
            parse_shape_margin("10px").unwrap().inner,
380
1
            PixelValue::px(10.0)
381
        );
382
1
        assert_eq!(parse_shape_image_threshold("0.5").unwrap().inner.get(), 0.5);
383
1
    }
384
}
385

            
386
#[cfg(all(test, feature = "parser"))]
387
mod autotest_generated {
388
    //! Adversarial tests for the five `shape.rs` parsers.
389
    //!
390
    //! Three of these tests are *characterization* tests: they pin down current
391
    //! behaviour that is a genuine defect in code this module calls into
392
    //! (`shape_parser` / `props::basic::pixel`). Each is marked `KNOWN BUG`, and
393
    //! each is written so that it FAILS THE DAY THE BUG IS FIXED, with a message
394
    //! saying what to replace it with. They are tripwires, not endorsements.
395

            
396
    // float_cmp: parsed values are compared against the exact literals they were
397
    // built from. eq_op: several tests compare a value with itself on purpose —
398
    // reflexivity of PartialEq is precisely what is under test.
399
    #![allow(clippy::float_cmp, clippy::eq_op)]
400

            
401
    use core::{cmp::Ordering, hash::Hash};
402

            
403
    use super::*;
404
    use crate::{
405
        corety::OptionF32,
406
        props::basic::length::SizeMetric,
407
        shape::{ShapeCircle, ShapeEllipse, ShapeInset, ShapePath, ShapePolygon},
408
        shape_parser::ShapeParseError,
409
    };
410

            
411
    /// Inputs that USED to make `shape_parser::parse_path` panic (a lone `"` argument
412
    /// satisfies both `starts_with('"')` and `ends_with('"')`, so the parser sliced
413
    /// `[1..0]`). Now fixed — these return `Err`. Kept as a corpus of formerly-panicking
414
    /// inputs; `path_lone_quote_returns_err_not_panic` asserts the graceful rejection,
415
    /// and the fuzz guards below tolerate them for free.
416
    const KNOWN_PANIC_INPUTS: &[&str] = &["path(\")", "path( \" )"];
417

            
418
    fn is_known_panic(input: &str) -> bool {
419
        KNOWN_PANIC_INPUTS.contains(&input)
420
    }
421

            
422
    /// Every input the shape-function parsers must survive: malformed, huge,
423
    /// boundary-numeric and non-ASCII. Includes the known-panic family above so
424
    /// the corpus stays honest; callers filter it explicitly.
425
    fn nasty_corpus() -> Vec<String> {
426
        let mut corpus: Vec<String> = [
427
            // empty / whitespace (incl. U+00A0, which `str::trim` also strips)
428
            "",
429
            " ",
430
            "      ",
431
            "\t",
432
            "\n",
433
            "\r\n",
434
            "\t \n ",
435
            "\u{a0}",
436
            // keyword handling
437
            "none",
438
            " none ",
439
            "NONE",
440
            "None",
441
            "nonee",
442
            "none none",
443
            "none;",
444
            // bare punctuation / unbalanced parens
445
            "(",
446
            ")",
447
            "()",
448
            ")(",
449
            "((",
450
            "))",
451
            "(()",
452
            "())",
453
            "!@#$%^&*",
454
            ";;;;",
455
            ",,,,",
456
            "\0",
457
            "\0\0(\0)\0",
458
            "\u{7f}",
459
            // structurally broken function calls
460
            "circle",
461
            "circle(",
462
            "circle)",
463
            "circle()",
464
            "circle( )",
465
            "circle(50px",
466
            "circle 50px)",
467
            "circle(50px))",
468
            "((circle(50px)))",
469
            "unknown(50px)",
470
            "square(1px)",
471
            "(50px)",
472
            " (50px) ",
473
            "circle(;)",
474
            "circle(,)",
475
            // leading / trailing junk
476
            "circle(50px);garbage",
477
            "circle(50px)garbage",
478
            "junk circle(50px)",
479
            "circle(50px) circle(50px)",
480
            // boundary numbers
481
            "circle(0)",
482
            "circle(-0)",
483
            "circle(0px)",
484
            "circle(-0px)",
485
            "circle(-50px)",
486
            "circle(50)",
487
            "circle(50%)",
488
            "circle(NaN)",
489
            "circle(nan)",
490
            "circle(inf)",
491
            "circle(-inf)",
492
            "circle(infpx)",
493
            "circle(NaNpx)",
494
            "circle(1e400px)",
495
            "circle(-1e400)",
496
            "circle(9223372036854775807px)",
497
            "circle(-9223372036854775808)",
498
            "circle(0x10px)",
499
            "circle(1_000px)",
500
            "circle(+5px)",
501
            "circle(.5px)",
502
            "circle(5.px)",
503
            // arity edges
504
            "circle(50px at)",
505
            "circle(50px at 1px)",
506
            "circle(50px at 1px 2px 3px)",
507
            "circle(50px AT 1px 2px)",
508
            "ellipse()",
509
            "ellipse(1px)",
510
            "ellipse(1px 2px)",
511
            "ellipse(1px 2px at 3px 4px)",
512
            "ellipse(a b)",
513
            "polygon()",
514
            "polygon(,)",
515
            "polygon(0 0)",
516
            "polygon(0 0, 1 1)",
517
            "polygon(0 0, 1 1, 2 2)",
518
            "polygon(0 0, 1 1, 2 2,)",
519
            "polygon(nonzero,)",
520
            "polygon(nonzero, 0 0, 1 1, 2 2)",
521
            "polygon(evenodd,0 0,1 1,2 2)",
522
            "polygon(nonzero 0 0, 1 1, 2 2)",
523
            "polygon(0, 1, 2)",
524
            "polygon(x y, x y, x y)",
525
            "inset()",
526
            "inset( )",
527
            "inset(10px)",
528
            "inset(1px 2px 3px 4px 5px)",
529
            "inset(round)",
530
            "inset(round 5px)",
531
            "inset(10px round)",
532
            "inset(10px round 5px)",
533
            "inset(10px round 5px 6px)",
534
            "inset(roundround)",
535
            "path()",
536
            "path(abc)",
537
            "path(\"\")",
538
            "path(\"M 0 0 Z\")",
539
            "path(\"\"\")",
540
            "path(\"🙂\")",
541
            // non-ASCII: `parse_function` slices on the byte offsets of '(' and
542
            // ')', so every multibyte input here is a char-boundary probe.
543
            "🙂",
544
            "🙂(1px)",
545
            "circle(🙂)",
546
            "circle(🙂px)",
547
            "circle(1px at 🙂 🙂)",
548
            "cïrcle(1px)",
549
            "e\u{0301}(1px)",
550
            "\u{202e}circle(1px)",
551
            "circle(١٢٣px)",
552
            "\u{1f600}\u{1f600}(\u{1f600})",
553
        ]
554
        .iter()
555
        .map(|s| (*s).to_string())
556
        .collect();
557

            
558
        for panicking in KNOWN_PANIC_INPUTS {
559
            corpus.push((*panicking).to_string());
560
        }
561

            
562
        // Pathological sizes: must terminate, must not overflow the stack.
563
        corpus.push("a".repeat(1_000_000));
564
        corpus.push("(".repeat(100_000));
565
        corpus.push(format!("circle({}px)", "9".repeat(10_000)));
566
        corpus.push("circle(".repeat(10_000) + &")".repeat(10_000));
567
        corpus.push(format!("polygon({}1px 1px)", "1px 1px, ".repeat(10_000)));
568
        corpus.push(format!("path(\"{}\")", "M 0 0 ".repeat(10_000)));
569

            
570
        corpus
571
    }
572

            
573
    fn hash_of<T: Hash>(value: &T) -> u64 {
574
        use core::hash::Hasher;
575
        use std::collections::hash_map::DefaultHasher;
576

            
577
        let mut hasher = DefaultHasher::new();
578
        value.hash(&mut hasher);
579
        hasher.finish()
580
    }
581

            
582
    fn clip_shape(input: &str) -> CssShape {
583
        match parse_clip_path(input) {
584
            Ok(ClipPath::Shape(shape)) => shape,
585
            other => panic!("expected a shape for {input:?}, got {other:?}"),
586
        }
587
    }
588

            
589
    // ---------------------------------------------------------------------
590
    // KNOWN BUGS — characterization tests (see module docs)
591
    // ---------------------------------------------------------------------
592

            
593
    /// KNOWN BUG (`shape_parser::parse_path`): a lone `"` as the argument passes
594
    /// *both* the `starts_with('"')` and `ends_with('"')` guards, so
595
    /// `&args[1..args.len() - 1]` slices `[1..0]` and panics with
596
    /// "slice index starts at 1 but ends at 0".
597
    ///
598
    /// It is reachable from all three public shape parsers, from untrusted CSS:
599
    /// `clip-path: path(")`. The correct result is
600
    /// `Err(ShapeParseError::InvalidSyntax(_))`.
601
    ///
602
    /// FIXED: `parse_path` now requires `args.len() >= 2` before slicing, so a lone
603
    /// `"` argument returns `Err(InvalidSyntax)` instead of panicking on the reversed
604
    /// `[1..0]` slice. These inputs are reachable from untrusted CSS (`clip-path:
605
    /// path(")`), so the graceful-rejection guarantee matters.
606
    #[test]
607
    fn path_lone_quote_returns_err_not_panic() {
608
        for input in KNOWN_PANIC_INPUTS {
609
            let outcome =
610
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| parse_clip_path(input)));
611
            match outcome {
612
                Ok(res) => assert!(res.is_err(), "{input:?} must be rejected, got {res:?}"),
613
                Err(_) => {
614
                    panic!("parse_clip_path({input:?}) still panics — the slice bug regressed")
615
                }
616
            }
617
        }
618
    }
619

            
620
    /// KNOWN BUG (`props::basic::pixel::parse_pixel_value`): the metric table is
621
    /// scanned in order and tries `("in", In)` *before* `("vmin", Vmin)`. Since
622
    /// "vmin" ends with "in", `10vmin` strips to `10vm`, which fails to parse as
623
    /// an f32 — so the valid CSS unit `vmin` is rejected outright. `vmax`, `vw`
624
    /// and `vh` are unaffected (no earlier metric is a suffix of them).
625
    ///
626
    /// This is not shape-specific: every property that routes through
627
    /// `parse_pixel_value` (width, margin, padding, …) rejects `vmin` too.
628
    ///
629
    /// WHEN pixel.rs IS FIXED (match longest metric first, or move vmax/vmin
630
    /// ahead of "in"), this test fails — replace it with:
631
    ///     `assert_eq!(parse_shape_margin("10vmin").unwrap().inner.metric`, `SizeMetric::Vmin`);
632
    #[test]
633
    fn known_bug_vmin_unit_is_rejected_by_metric_table_order() {
634
        // FIXED (as this pin's own message instructed): "10vmin" now parses to Vmin.
635
        assert_eq!(
636
            parse_shape_margin("10vmin").unwrap().inner.metric,
637
            SizeMetric::Vmin
638
        );
639

            
640
        // The sibling viewport units do work, which is what makes the bug easy
641
        // to miss: only the unit that *ends in an earlier metric* is broken.
642
        assert_eq!(
643
            parse_shape_margin("10vmax").unwrap().inner.metric,
644
            SizeMetric::Vmax
645
        );
646
        assert_eq!(
647
            parse_shape_margin("10vw").unwrap().inner.metric,
648
            SizeMetric::Vw
649
        );
650
        assert_eq!(
651
            parse_shape_margin("10vh").unwrap().inner.metric,
652
            SizeMetric::Vh
653
        );
654
    }
655

            
656
    /// A NaN f32 in a shape used to break the `Eq`/`Ord` contracts: the property
657
    /// enums derived `PartialEq` (raw compare, NaN != NaN) while hand-writing
658
    /// `Ord`/`Hash` as NaN-Equal (`to_bits`), so `a == a` was false yet `cmp` said
659
    /// `Equal`. Fixed: `PartialEq` is now hand-written to match `Ord`, so a
660
    /// preserved NaN length stays reflexive and consistent with Hash/Ord.
661
    #[test]
662
    fn nan_shape_is_reflexive_and_consistent_across_eq_ord_hash() {
663
        let a = parse_clip_path("circle(NaN)").expect("NaN is a preserved length");
664
        let b = parse_clip_path("circle(NaN)").expect("NaN is a preserved length");
665
        assert_eq!(a, a, "Eq must be reflexive for a NaN shape");
666
        assert_eq!(a, b);
667
        assert_eq!(a.cmp(&b), Ordering::Equal);
668
        assert_eq!(a.partial_cmp(&b), Some(Ordering::Equal));
669
        assert_eq!(hash_of(&a), hash_of(&b));
670
    }
671

            
672
    /// Contrast with the bug above: `ShapeMargin` / `ShapeImageThreshold` store
673
    /// their numbers as `FloatValue` (an isize-encoded fixed-point), and the
674
    /// f32 -> isize cast maps NaN to 0. So no NaN can survive into these two
675
    /// types and their derived `Eq` really is reflexive.
676
    #[test]
677
    fn floatvalue_encoding_makes_margin_and_threshold_nan_free() {
678
        let threshold = parse_shape_image_threshold("NaN").expect("f32 parses NaN");
679
        assert!(threshold.inner.get().is_finite());
680
        assert_eq!(threshold.inner.get(), 0.0);
681
        assert_eq!(threshold, threshold);
682
        assert_eq!(hash_of(&threshold), hash_of(&threshold));
683

            
684
        // "NaNpx" is *accepted* (leniency worth tightening) but cannot produce a
685
        // NaN PixelValue. Written to also pass once the parser rejects it.
686
        if let Ok(margin) = parse_shape_margin("NaNpx") {
687
            assert!(
688
                margin.inner.number.get().is_finite(),
689
                "NaN leaked into a PixelValue"
690
            );
691
            assert_eq!(margin.inner.number.get(), 0.0);
692
            assert_eq!(margin, margin);
693
        } else { /* rejecting "NaNpx" outright would be more correct */
694
        }
695
    }
696

            
697
    // ---------------------------------------------------------------------
698
    // Panic / hang safety across the whole corpus
699
    // ---------------------------------------------------------------------
700

            
701
    /// The headline invariant: no input may panic any shape-function parser.
702
    ///
703
    /// Written as "the set of panicking inputs is a subset of the known-bug set",
704
    /// so it keeps passing (and keeps guarding) after `parse_path` is fixed.
705
    #[test]
706
    fn shape_parsers_never_panic_on_hostile_input() {
707
        let mut unexpected: Vec<String> = Vec::new();
708

            
709
        for input in nasty_corpus() {
710
            let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
711
                let _ = parse_shape_outside(&input);
712
                let _ = parse_shape_inside(&input);
713
                let _ = parse_clip_path(&input);
714
            }));
715

            
716
            if outcome.is_err() && !is_known_panic(&input) {
717
                let preview: String = input.chars().take(48).collect();
718
                unexpected.push(preview);
719
            }
720
        }
721

            
722
        assert!(
723
            unexpected.is_empty(),
724
            "shape parsers panicked on input(s) outside the known-bug set: {unexpected:?}"
725
        );
726
    }
727

            
728
    /// Same invariant for the two numeric parsers — these have no known panics,
729
    /// so the bar is absolute.
730
    #[test]
731
    fn numeric_parsers_never_panic_on_hostile_input() {
732
        for input in nasty_corpus() {
733
            let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
734
                let _ = parse_shape_margin(&input);
735
                let _ = parse_shape_image_threshold(&input);
736
            }));
737
            assert!(
738
                outcome.is_ok(),
739
                "numeric parser panicked on {:?}",
740
                input.chars().take(48).collect::<String>()
741
            );
742
        }
743
    }
744

            
745
    /// All three properties delegate to the same `parse_shape`, so they must
746
    /// accept exactly the same language and produce the same shape. Compared via
747
    /// `Ord` rather than `==` because NaN shapes are not self-equal (see
748
    /// `known_bug_nan_shape_breaks_eq_ord_consistency`).
749
    #[test]
750
    fn the_three_shape_properties_agree_on_every_input() {
751
        for input in nasty_corpus() {
752
            if is_known_panic(&input) {
753
                continue;
754
            }
755

            
756
            let outside = parse_shape_outside(&input);
757
            let inside = parse_shape_inside(&input);
758
            let clip = parse_clip_path(&input);
759

            
760
            assert_eq!(
761
                outside.is_ok(),
762
                inside.is_ok(),
763
                "shape-outside and shape-inside disagree on {input:?}"
764
            );
765
            assert_eq!(
766
                outside.is_ok(),
767
                clip.is_ok(),
768
                "shape-outside and clip-path disagree on {input:?}"
769
            );
770

            
771
            if let (Ok(ShapeOutside::Shape(a)), Ok(ShapeInside::Shape(b)), Ok(ClipPath::Shape(c))) =
772
                (&outside, &inside, &clip)
773
            {
774
                assert_eq!(a.cmp(b), Ordering::Equal, "different shape for {input:?}");
775
                assert_eq!(a.cmp(c), Ordering::Equal, "different shape for {input:?}");
776
            }
777
        }
778
    }
779

            
780
    /// A million-character input, a 10 000-deep paren nest and a 10 000-point
781
    /// polygon must all terminate. `parse_shape` is iterative, so nesting must
782
    /// not grow the stack; if this ever hangs or overflows, the test never
783
    /// returns and the suite times out rather than passing silently.
784
    #[test]
785
    fn pathological_sizes_terminate_without_stack_overflow() {
786
        let million = "a".repeat(1_000_000);
787
        assert!(matches!(
788
            parse_clip_path(&million),
789
            Err(ShapeParseError::InvalidSyntax(_))
790
        ));
791

            
792
        let nested = "circle(".repeat(10_000) + &")".repeat(10_000);
793
        assert!(parse_clip_path(&nested).is_err());
794

            
795
        let unclosed = "(".repeat(100_000);
796
        assert!(matches!(
797
            parse_clip_path(&unclosed),
798
            Err(ShapeParseError::InvalidSyntax(_))
799
        ));
800

            
801
        let big_polygon = format!("polygon({}1px 1px)", "1px 1px, ".repeat(10_000));
802
        match clip_shape(&big_polygon) {
803
            CssShape::Polygon(ShapePolygon { points }) => {
804
                assert_eq!(points.as_ref().len(), 10_001);
805
            }
806
            other => panic!("expected Polygon, got {other:?}"),
807
        }
808

            
809
        // 10 000 digits overflow f32 to infinity rather than erroring — the
810
        // shape keeps a raw f32, so this is where a non-finite radius gets in.
811
        let huge_radius = format!("circle({}px)", "9".repeat(10_000));
812
        match clip_shape(&huge_radius) {
813
            CssShape::Circle(ShapeCircle { radius, .. }) => {
814
                assert!(radius.is_infinite() && radius.is_sign_positive());
815
            }
816
            other => panic!("expected Circle, got {other:?}"),
817
        }
818
    }
819

            
820
    // ---------------------------------------------------------------------
821
    // parse_shape_outside / parse_shape_inside / parse_clip_path
822
    // ---------------------------------------------------------------------
823

            
824
    #[test]
825
    fn empty_and_whitespace_only_input_is_empty_input_error() {
826
        for input in ["", " ", "      ", "\t", "\n", "\r\n", "\t \n ", "\u{a0}"] {
827
            assert_eq!(
828
                parse_shape_outside(input),
829
                Err(ShapeParseError::EmptyInput),
830
                "shape-outside {input:?}"
831
            );
832
            assert_eq!(
833
                parse_shape_inside(input),
834
                Err(ShapeParseError::EmptyInput),
835
                "shape-inside {input:?}"
836
            );
837
            assert_eq!(
838
                parse_clip_path(input),
839
                Err(ShapeParseError::EmptyInput),
840
                "clip-path {input:?}"
841
            );
842
        }
843
    }
844

            
845
    /// Positive control, plus the one piece of trimming the parsers do promise.
846
    #[test]
847
    fn none_keyword_parses_and_is_trimmed() {
848
        for input in ["none", " none ", "\tnone\n", "  none\r\n"] {
849
            assert_eq!(parse_shape_outside(input), Ok(ShapeOutside::None));
850
            assert_eq!(parse_shape_inside(input), Ok(ShapeInside::None));
851
            assert_eq!(parse_clip_path(input), Ok(ClipPath::None));
852
        }
853
    }
854

            
855
    /// `none` is matched case-sensitively, which is not CSS-conformant (CSS
856
    /// keywords are ASCII case-insensitive). Asserted as an invariant that holds
857
    /// either way — uppercase must never silently become a *shape*.
858
    #[test]
859
    fn uppercase_none_never_yields_a_shape() {
860
        for input in ["NONE", "None", "nOnE"] {
861
            match parse_clip_path(input) {
862
                Ok(ClipPath::None) | Err(_) => {}
863
                Ok(other) => panic!("{input:?} parsed as a shape: {other:?}"),
864
            }
865
        }
866
        // Current behaviour: rejected as an unparseable function.
867
        assert!(parse_clip_path("NONE").is_err());
868
    }
869

            
870
    #[test]
871
    fn garbage_and_broken_parens_are_rejected() {
872
        // No '(' at all.
873
        for input in ["!@#$%^&*", ";;;;", ",,,,", "circle", "\u{7f}", "🙂"] {
874
            assert!(
875
                matches!(
876
                    parse_clip_path(input),
877
                    Err(ShapeParseError::InvalidSyntax(_))
878
                ),
879
                "expected InvalidSyntax for {input:?}"
880
            );
881
        }
882

            
883
        // '(' but no ')'.
884
        assert!(matches!(
885
            parse_clip_path("circle(50px"),
886
            Err(ShapeParseError::InvalidSyntax(_))
887
        ));
888
        // ')' before '('.
889
        assert!(matches!(
890
            parse_clip_path(")("),
891
            Err(ShapeParseError::InvalidSyntax(_))
892
        ));
893
        // Empty function name.
894
        assert!(matches!(
895
            parse_clip_path("()"),
896
            Err(ShapeParseError::UnknownFunction(_))
897
        ));
898
        // Unknown function names carry the offending name.
899
        assert_eq!(
900
            parse_clip_path("square(1px)"),
901
            Err(ShapeParseError::UnknownFunction("square".to_string()))
902
        );
903
        assert_eq!(
904
            parse_clip_path("junk circle(50px)"),
905
            Err(ShapeParseError::UnknownFunction("junk circle".to_string()))
906
        );
907
    }
908

            
909
    /// Trailing junk after the closing paren is currently *ignored*:
910
    /// `parse_function` takes `rfind(')')` and never checks that the input ends
911
    /// there, so `circle(50px);garbage` parses as a plain circle. That is a
912
    /// leniency bug (a declaration with trailing garbage should be dropped), but
913
    /// it is not a memory-safety issue.
914
    ///
915
    /// Asserted as the invariant that must hold either way: the parser may
916
    /// reject the input, but it must never return a *different* shape than the
917
    /// prefix describes.
918
    #[test]
919
    fn trailing_junk_is_ignored_but_never_changes_the_shape() {
920
        for input in [
921
            "circle(50px);garbage",
922
            "circle(50px)garbage",
923
            "circle(50px)🙂",
924
        ] {
925
            match parse_clip_path(input) {
926
                Ok(ClipPath::Shape(CssShape::Circle(ShapeCircle { center, radius }))) => {
927
                    assert_eq!(radius, 50.0, "{input:?}");
928
                    assert_eq!(center.x, 0.0);
929
                    assert_eq!(center.y, 0.0);
930
                }
931
                Err(_) => { /* rejecting trailing junk would be more correct */ }
932
                other => panic!("{input:?} produced an unexpected value: {other:?}"),
933
            }
934
        }
935
    }
936

            
937
    /// `parse_function` slices `input` at the *byte* offsets of '(' and ')'.
938
    /// Those are ASCII, so they can never land inside a multibyte sequence — but
939
    /// only if nothing else slices. These probe that.
940
    #[test]
941
    fn multibyte_input_does_not_panic_and_is_rejected() {
942
        for input in [
943
            "🙂(1px)",
944
            "circle(🙂)",
945
            "circle(🙂px)",
946
            "circle(1px at 🙂 🙂)",
947
            "cïrcle(1px)",
948
            "e\u{0301}(1px)",
949
            "\u{202e}circle(1px)",
950
            "circle(١٢٣px)",
951
            "\u{1f600}\u{1f600}(\u{1f600})",
952
        ] {
953
            assert!(
954
                parse_clip_path(input).is_err(),
955
                "expected Err for {input:?}"
956
            );
957
        }
958

            
959
        // Multibyte *inside* a quoted path is data, and is preserved verbatim.
960
        match clip_shape("path(\"🙂\")") {
961
            CssShape::Path(ShapePath { data }) => assert_eq!(data.as_str(), "🙂"),
962
            other => panic!("expected Path, got {other:?}"),
963
        }
964
    }
965

            
966
    #[test]
967
    fn circle_boundary_numbers() {
968
        // Unitless and `%` are both accepted; `%` is silently treated as a raw
969
        // number (parse_length has a TODO — it needs the container size).
970
        for input in ["circle(50px)", "circle(50)", "circle(50%)"] {
971
            match clip_shape(input) {
972
                CssShape::Circle(ShapeCircle { radius, .. }) => assert_eq!(radius, 50.0),
973
                other => panic!("expected Circle, got {other:?}"),
974
            }
975
        }
976

            
977
        // Zero, signed zero, and negative radii are all accepted. A negative
978
        // radius is invalid per CSS Shapes; it is stored as-is.
979
        for (input, expected) in [
980
            ("circle(0px)", 0.0_f32),
981
            ("circle(-0px)", -0.0_f32),
982
            ("circle(-50px)", -50.0_f32),
983
            ("circle(+5px)", 5.0_f32),
984
            ("circle(.5px)", 0.5_f32),
985
            ("circle(5.px)", 5.0_f32),
986
        ] {
987
            match clip_shape(input) {
988
                CssShape::Circle(ShapeCircle { radius, .. }) => {
989
                    assert_eq!(radius, expected, "{input:?}");
990
                }
991
                other => panic!("expected Circle, got {other:?}"),
992
            }
993
        }
994

            
995
        // f32 overflow saturates to infinity instead of erroring.
996
        for input in ["circle(1e400px)", "circle(inf)", "circle(infpx)"] {
997
            match clip_shape(input) {
998
                CssShape::Circle(ShapeCircle { radius, .. }) => {
999
                    assert!(radius.is_infinite(), "{input:?} -> {radius}");
                }
                other => panic!("expected Circle, got {other:?}"),
            }
        }
        // i64::MAX survives as an f32 approximation, no overflow panic.
        match clip_shape("circle(9223372036854775807px)") {
            CssShape::Circle(ShapeCircle { radius, .. }) => {
                assert!(radius.is_finite() && radius > 9.0e18);
            }
            other => panic!("expected Circle, got {other:?}"),
        }
        // Rust-only / C-only numeric literals are NOT valid CSS numbers.
        for input in ["circle(0x10px)", "circle(1_000px)"] {
            assert!(
                matches!(
                    parse_clip_path(input),
                    Err(ShapeParseError::InvalidNumber(_))
                ),
                "expected InvalidNumber for {input:?}"
            );
        }
    }
    /// `circle()` needs 4 parts *and* `parts[1] == "at"` before it reads a
    /// center; anything else silently falls back to the origin rather than
    /// erroring. Pin that down — a partial `at` clause is not a parse error.
    #[test]
    fn circle_at_clause_arity_falls_back_to_origin() {
        for input in [
            "circle(50px at)",
            "circle(50px at 1px)",
            "circle(50px AT 1px 2px)",
        ] {
            match clip_shape(input) {
                CssShape::Circle(ShapeCircle { center, radius }) => {
                    assert_eq!(radius, 50.0);
                    assert_eq!((center.x, center.y), (0.0, 0.0), "{input:?}");
                }
                other => panic!("expected Circle, got {other:?}"),
            }
        }
        // A complete `at` clause is honoured; extra trailing parts are ignored.
        for input in ["circle(50px at 1px 2px)", "circle(50px at 1px 2px 3px)"] {
            match clip_shape(input) {
                CssShape::Circle(ShapeCircle { center, radius }) => {
                    assert_eq!(radius, 50.0);
                    assert_eq!((center.x, center.y), (1.0, 2.0), "{input:?}");
                }
                other => panic!("expected Circle, got {other:?}"),
            }
        }
        assert!(matches!(
            parse_clip_path("circle()"),
            Err(ShapeParseError::MissingParameter(_))
        ));
    }
    #[test]
    fn ellipse_requires_two_radii() {
        for input in ["ellipse()", "ellipse(1px)"] {
            assert!(
                matches!(
                    parse_clip_path(input),
                    Err(ShapeParseError::MissingParameter(_))
                ),
                "expected MissingParameter for {input:?}"
            );
        }
        match clip_shape("ellipse(1px 2px)") {
            CssShape::Ellipse(ShapeEllipse {
                center,
                radius_x,
                radius_y,
            }) => {
                assert_eq!((radius_x, radius_y), (1.0, 2.0));
                assert_eq!((center.x, center.y), (0.0, 0.0));
            }
            other => panic!("expected Ellipse, got {other:?}"),
        }
        match clip_shape("ellipse(1px 2px at 3px 4px)") {
            CssShape::Ellipse(ShapeEllipse {
                center,
                radius_x,
                radius_y,
            }) => {
                assert_eq!((radius_x, radius_y), (1.0, 2.0));
                assert_eq!((center.x, center.y), (3.0, 4.0));
            }
            other => panic!("expected Ellipse, got {other:?}"),
        }
        assert!(matches!(
            parse_clip_path("ellipse(a b)"),
            Err(ShapeParseError::InvalidNumber(_))
        ));
    }
    #[test]
    fn polygon_needs_three_complete_points() {
        // Fewer than 3 points, empty args, and a trailing comma all fail.
        for input in [
            "polygon()",
            "polygon(,)",
            "polygon(0 0)",
            "polygon(0 0, 1 1)",
            "polygon(0 0, 1 1, 2 2,)",
            "polygon(0, 1, 2)",
            "polygon(nonzero,)",
        ] {
            assert!(
                parse_clip_path(input).is_err(),
                "expected Err for {input:?}"
            );
        }
        match clip_shape("polygon(0 0, 1 1, 2 2)") {
            CssShape::Polygon(ShapePolygon { points }) => {
                assert_eq!(points.as_ref().len(), 3);
                assert_eq!((points.as_ref()[2].x, points.as_ref()[2].y), (2.0, 2.0));
            }
            other => panic!("expected Polygon, got {other:?}"),
        }
        // The optional fill-rule prefix is accepted (and ignored) only when it
        // is immediately followed by a comma.
        for input in [
            "polygon(nonzero, 0 0, 1 1, 2 2)",
            "polygon(evenodd,0 0,1 1,2 2)",
        ] {
            match clip_shape(input) {
                CssShape::Polygon(ShapePolygon { points }) => {
                    assert_eq!(points.as_ref().len(), 3, "{input:?}");
                }
                other => panic!("expected Polygon, got {other:?}"),
            }
        }
        assert!(matches!(
            parse_clip_path("polygon(nonzero 0 0, 1 1, 2 2)"),
            Err(ShapeParseError::InvalidNumber(_))
        ));
        assert!(matches!(
            parse_clip_path("polygon(x y, x y, x y)"),
            Err(ShapeParseError::InvalidNumber(_))
        ));
    }
    #[test]
    fn inset_shorthand_and_round_keyword() {
        // 1/2/3/4-value shorthand, same rules as margin/padding.
        let cases: [(&str, [f32; 4]); 4] = [
            ("inset(10px)", [10.0, 10.0, 10.0, 10.0]),
            ("inset(1px 2px)", [1.0, 2.0, 1.0, 2.0]),
            ("inset(1px 2px 3px)", [1.0, 2.0, 3.0, 2.0]),
            ("inset(1px 2px 3px 4px)", [1.0, 2.0, 3.0, 4.0]),
        ];
        for (input, [top, right, bottom, left]) in cases {
            match clip_shape(input) {
                CssShape::Inset(ShapeInset {
                    inset_top,
                    inset_right,
                    inset_bottom,
                    inset_left,
                    border_radius,
                }) => {
                    assert_eq!(
                        [inset_top, inset_right, inset_bottom, inset_left],
                        [top, right, bottom, left],
                        "{input:?}"
                    );
                    assert!(matches!(border_radius, OptionF32::None));
                }
                other => panic!("expected Inset, got {other:?}"),
            }
        }
        // 5 values is rejected; no values is rejected.
        assert!(matches!(
            parse_clip_path("inset(1px 2px 3px 4px 5px)"),
            Err(ShapeParseError::InvalidSyntax(_))
        ));
        assert!(matches!(
            parse_clip_path("inset()"),
            Err(ShapeParseError::MissingParameter(_))
        ));
        assert!(matches!(
            parse_clip_path("inset( )"),
            Err(ShapeParseError::MissingParameter(_))
        ));
        // `round` with a missing / unparseable radius errors rather than
        // panicking on the `args[round_pos + 5..]` slice.
        for input in [
            "inset(round)",
            "inset(10px round)",
            "inset(roundround)",
            "inset(10px round 5px 6px)",
        ] {
            assert!(
                matches!(
                    parse_clip_path(input),
                    Err(ShapeParseError::InvalidNumber(_))
                ),
                "expected InvalidNumber for {input:?}"
            );
        }
        match clip_shape("inset(10px round 5px)") {
            CssShape::Inset(ShapeInset { border_radius, .. }) => {
                assert!(matches!(border_radius, OptionF32::Some(r) if r == 5.0));
            }
            other => panic!("expected Inset, got {other:?}"),
        }
    }
    #[test]
    fn path_data_must_be_quoted_and_is_stored_verbatim() {
        // Unquoted / half-quoted path data is rejected.
        for input in ["path()", "path(abc)", "path(\"abc)", "path(abc\")"] {
            assert!(
                matches!(
                    parse_clip_path(input),
                    Err(ShapeParseError::InvalidSyntax(_))
                ),
                "expected InvalidSyntax for {input:?}"
            );
        }
        // An empty quoted path is valid and yields empty data (this is the
        // len == 2 neighbour of the len == 1 panic in the known-bug test).
        match clip_shape("path(\"\")") {
            CssShape::Path(ShapePath { data }) => assert_eq!(data.as_str(), ""),
            other => panic!("expected Path, got {other:?}"),
        }
        // Path data is never interpreted, so it can contain anything — including
        // the parens that `parse_function` scans for, thanks to rfind(')').
        match clip_shape("path(\"M 0 0 (L) 1 1 Z\")") {
            CssShape::Path(ShapePath { data }) => {
                assert_eq!(data.as_str(), "M 0 0 (L) 1 1 Z");
            }
            other => panic!("expected Path, got {other:?}"),
        }
    }
    // ---------------------------------------------------------------------
    // Round-trip: print_as_css_value -> parse -> identical value
    // ---------------------------------------------------------------------
    #[test]
    fn shape_properties_round_trip_through_their_css_representation() {
        let inputs = [
            "none",
            "circle(50px)",
            "circle(50px at 10px 20px)",
            "circle(-1px at -2px -3px)",
            "ellipse(1px 2px)",
            "ellipse(1px 2px at 3px 4px)",
            "polygon(0px 0px, 100px 0px, 100px 100px)",
            "polygon(0px 0px, 1px 1px, 2px 2px, 3px 3px, 4px 4px)",
            "inset(1px 2px 3px 4px)",
            "inset(10px round 5px)",
            "path(\"M 0 0 L 1 1 Z\")",
        ];
        for input in inputs {
            let outside = parse_shape_outside(input).expect(input);
            let printed = outside.print_as_css_value();
            assert_eq!(
                parse_shape_outside(&printed).as_ref(),
                Ok(&outside),
                "shape-outside round-trip changed the value: {input:?} -> {printed:?}"
            );
            // Printing must also be idempotent, not just re-parseable.
            assert_eq!(
                parse_shape_outside(&printed)
                    .expect(input)
                    .print_as_css_value(),
                printed
            );
            let inside = parse_shape_inside(input).expect(input);
            let printed = inside.print_as_css_value();
            assert_eq!(
                parse_shape_inside(&printed).as_ref(),
                Ok(&inside),
                "{input:?}"
            );
            let clip = parse_clip_path(input).expect(input);
            let printed = clip.print_as_css_value();
            assert_eq!(parse_clip_path(&printed).as_ref(), Ok(&clip), "{input:?}");
        }
    }
    #[test]
    fn none_prints_as_the_none_keyword() {
        assert_eq!(ShapeOutside::None.print_as_css_value(), "none");
        assert_eq!(ShapeInside::None.print_as_css_value(), "none");
        assert_eq!(ClipPath::None.print_as_css_value(), "none");
    }
    #[test]
    fn margin_and_threshold_round_trip() {
        for input in ["0px", "10px", "-5px", "1.5em", "50%", "2rem", "12pt", "1in"] {
            let margin = parse_shape_margin(input).expect(input);
            let printed = margin.print_as_css_value();
            assert_eq!(
                parse_shape_margin(&printed).expect(&printed),
                margin,
                "shape-margin round-trip changed the value: {input:?} -> {printed:?}"
            );
        }
        for input in ["0", "0.5", "1", "0.001", "0.999"] {
            let threshold = parse_shape_image_threshold(input).expect(input);
            let printed = threshold.print_as_css_value();
            assert_eq!(
                parse_shape_image_threshold(&printed).expect(&printed),
                threshold,
                "shape-image-threshold round-trip changed the value: {input:?} -> {printed:?}"
            );
        }
    }
    // ---------------------------------------------------------------------
    // parse_shape_margin
    // ---------------------------------------------------------------------
    #[test]
    fn margin_empty_and_whitespace_only_is_empty_string_error() {
        for input in ["", " ", "     ", "\t", "\n", "\r\n", "\u{a0}"] {
            assert!(
                matches!(
                    parse_shape_margin(input),
                    Err(CssPixelValueParseError::EmptyString)
                ),
                "expected EmptyString for {input:?}"
            );
        }
    }
    #[test]
    fn margin_valid_units_map_to_the_right_metric() {
        // NOTE: `vmin` is missing here on purpose — it is broken. See
        // `known_bug_vmin_unit_is_rejected_by_metric_table_order`.
        let cases = [
            ("10px", SizeMetric::Px),
            ("10em", SizeMetric::Em),
            ("10rem", SizeMetric::Rem),
            ("10pt", SizeMetric::Pt),
            ("10in", SizeMetric::In),
            ("10cm", SizeMetric::Cm),
            ("10mm", SizeMetric::Mm),
            ("10%", SizeMetric::Percent),
            ("10vw", SizeMetric::Vw),
            ("10vh", SizeMetric::Vh),
            ("10vmax", SizeMetric::Vmax),
            // Unitless numbers are accepted and default to px.
            ("10", SizeMetric::Px),
        ];
        for (input, metric) in cases {
            let margin = parse_shape_margin(input).expect(input);
            assert_eq!(margin.inner.metric, metric, "{input:?}");
            assert_eq!(margin.inner.number.get(), 10.0, "{input:?}");
        }
        // Whitespace around the value and between number and unit is tolerated.
        assert_eq!(
            parse_shape_margin("  10px  ").expect("padded").inner,
            PixelValue::px(10.0)
        );
        assert_eq!(
            parse_shape_margin("10 px").expect("inner space").inner,
            PixelValue::px(10.0)
        );
    }
    #[test]
    fn margin_rejects_malformed_and_junk_suffixed_values() {
        // A unit with no number.
        assert!(matches!(
            parse_shape_margin("px"),
            Err(CssPixelValueParseError::NoValueGiven(_, SizeMetric::Px))
        ));
        // A number with a bad number part in front of a known unit.
        assert!(matches!(
            parse_shape_margin("abcpx"),
            Err(CssPixelValueParseError::ValueParseErr(_, "abc"))
        ));
        // Neither a known unit nor a bare number.
        for input in [
            "10px;garbage",
            "garbage",
            "10 20px",
            "10px 20px",
            "10PX",
            "10Px",
            "10px🙂",
            "🙂px",
            "!@#$",
        ] {
            assert!(
                parse_shape_margin(input).is_err(),
                "expected Err for {input:?}"
            );
        }
    }
    /// Unit matching is ASCII-case-sensitive, which is not CSS-conformant.
    /// Asserted so it holds either way: uppercase must never yield a *wrong*
    /// value, only the right one or an error.
    #[test]
    fn margin_uppercase_units_never_yield_a_wrong_value() {
        for input in ["10PX", "10Px", "10EM", "10%"] {
            if let Ok(margin) = parse_shape_margin(input) {
                assert_eq!(margin.inner.number.get(), 10.0, "{input:?}")
            } else { /* current behaviour for the uppercase forms */
            }
        }
    }
    /// The `FloatValue` isize encoding is the only thing standing between a
    /// hostile stylesheet and a non-finite length in layout. Nothing that parses
    /// may produce a NaN or infinite `PixelValue`.
    #[test]
    fn margin_never_produces_a_non_finite_value() {
        let extremes = [
            "0px",
            "-0px",
            "0",
            "-0",
            "NaNpx",
            "nanpx",
            "infpx",
            "-infpx",
            "inf",
            "-inf",
            "1e400px",
            "-1e400px",
            "1e38px",
            "-1e38px",
            "9223372036854775807px",
            "-9223372036854775808px",
            "340282350000000000000000000000000000000px",
            "0.0000000000000000001px",
        ];
        for input in extremes {
            if let Ok(margin) = parse_shape_margin(input) {
                let value = margin.inner.number.get();
                assert!(
                    value.is_finite(),
                    "{input:?} produced a non-finite PixelValue: {value}"
                );
            }
        }
        // Saturation, specifically: `1e400` parses to f32::INFINITY (Rust's f32
        // FromStr does not error on overflow), and the `f32 as isize` cast in
        // FloatValue::new then saturates at the isize bound — which is exactly
        // what keeps the infinity from reaching layout.
        let saturated = parse_shape_margin("1e400px").expect("f32 overflow parses as inf");
        assert_eq!(saturated.inner.number.number(), isize::MAX);
        assert!(saturated.inner.number.get().is_finite());
        let saturated_neg = parse_shape_margin("-1e400px").expect("parses as -inf");
        assert_eq!(saturated_neg.inner.number.number(), isize::MIN);
        assert!(saturated_neg.inner.number.get().is_finite());
        // NaN saturates to 0 rather than to a bound.
        assert_eq!(
            parse_shape_margin("NaNpx")
                .expect("NaN currently parses")
                .inner
                .number
                .number(),
            0
        );
    }
    /// `FloatValue` keeps 3 decimal places and *truncates* toward zero — sizes
    /// below 0.001 collapse to exactly 0. Worth pinning: it silently changes
    /// authored values.
    #[test]
    fn margin_quantizes_to_three_decimals_by_truncation() {
        assert_eq!(
            parse_shape_margin("0.001px")
                .expect("0.001")
                .inner
                .number
                .get(),
            0.001
        );
        // 0.0005 does NOT round up to 0.001 — it truncates to 0.
        assert_eq!(
            parse_shape_margin("0.0005px")
                .expect("0.0005")
                .inner
                .number
                .get(),
            0.0
        );
        assert_eq!(
            parse_shape_margin("0.0009px")
                .expect("0.0009")
                .inner
                .number
                .get(),
            0.0
        );
        let truncated = parse_shape_margin("1.9999px")
            .expect("1.9999")
            .inner
            .number
            .get();
        assert!(
            (truncated - 1.999).abs() < 1.0e-6,
            "expected truncation to 1.999, got {truncated}"
        );
    }
    // ---------------------------------------------------------------------
    // parse_shape_image_threshold
    // ---------------------------------------------------------------------
    #[test]
    fn threshold_empty_whitespace_and_garbage_are_errors() {
        for input in [
            "", " ", "   ", "\t\n", "abc", "0.5px", "50%", "1,0", "0.5.5", "🙂", "--1",
        ] {
            assert!(
                parse_shape_image_threshold(input).is_err(),
                "expected Err for {input:?}"
            );
        }
    }
    #[test]
    fn threshold_parses_and_trims_valid_values() {
        assert_eq!(
            parse_shape_image_threshold("0").expect("0").inner.get(),
            0.0
        );
        assert_eq!(
            parse_shape_image_threshold("1").expect("1").inner.get(),
            1.0
        );
        assert_eq!(
            parse_shape_image_threshold("0.5").expect("0.5").inner.get(),
            0.5
        );
        assert_eq!(
            parse_shape_image_threshold("  0.5  ")
                .expect("padded")
                .inner
                .get(),
            0.5
        );
        // f32 accepts these spellings; CSS numbers do too.
        assert_eq!(
            parse_shape_image_threshold("+0.5")
                .expect("+0.5")
                .inner
                .get(),
            0.5
        );
        assert_eq!(
            parse_shape_image_threshold("5e-1")
                .expect("5e-1")
                .inner
                .get(),
            0.5
        );
        assert_eq!(
            parse_shape_image_threshold(".5").expect(".5").inner.get(),
            0.5
        );
    }
    /// The documented contract: the result is clamped to `0.0 ..= 1.0`. Assert it
    /// as a hard invariant over every input that parses at all — including the
    /// ones that reach `clamp` as infinities.
    #[test]
    fn threshold_is_always_clamped_to_zero_one_and_finite() {
        let extremes = [
            "0",
            "-0",
            "1",
            "-1",
            "2",
            "1.0001",
            "-0.0001",
            "100",
            "1e10",
            "-1e10",
            "1e38",
            "1e400",
            "-1e400",
            "inf",
            "-inf",
            "infinity",
            "-infinity",
            "NaN",
            "nan",
            "-NaN",
            "9223372036854775807",
            "-9223372036854775808",
            "1e-45",
            "-1e-45",
            "0.0000001",
        ];
        for input in extremes {
            let Ok(threshold) = parse_shape_image_threshold(input) else {
                continue;
            };
            let value = threshold.inner.get();
            assert!(
                value.is_finite(),
                "{input:?} produced a non-finite threshold: {value}"
            );
            assert!(
                (0.0..=1.0).contains(&value),
                "{input:?} escaped the [0, 1] clamp: {value}"
            );
        }
        // Direction of the clamp, specifically.
        assert_eq!(
            parse_shape_image_threshold("2").expect("2").inner.get(),
            1.0
        );
        assert_eq!(
            parse_shape_image_threshold("-1").expect("-1").inner.get(),
            0.0
        );
        assert_eq!(
            parse_shape_image_threshold("inf").expect("inf").inner.get(),
            1.0
        );
        assert_eq!(
            parse_shape_image_threshold("-inf")
                .expect("-inf")
                .inner
                .get(),
            0.0
        );
        // NaN is neutralised by the isize encoding *before* it reaches clamp
        // (`f32 as isize` maps NaN to 0), so it lands on 0.0 rather than
        // propagating or panicking.
        assert_eq!(
            parse_shape_image_threshold("NaN").expect("NaN").inner.get(),
            0.0
        );
    }
    /// Same 0.001 truncation as `ShapeMargin`: a threshold below 0.001 becomes a
    /// fully transparent 0.
    #[test]
    fn threshold_quantizes_to_three_decimals() {
        assert_eq!(
            parse_shape_image_threshold("0.001")
                .expect("0.001")
                .inner
                .get(),
            0.001
        );
        assert_eq!(
            parse_shape_image_threshold("0.0005")
                .expect("0.0005")
                .inner
                .get(),
            0.0
        );
        let truncated = parse_shape_image_threshold("0.9999")
            .expect("0.9999")
            .inner
            .get();
        assert!(
            (truncated - 0.999).abs() < 1.0e-6,
            "expected truncation to 0.999, got {truncated}"
        );
    }
    #[test]
    fn threshold_survives_a_ten_thousand_digit_number() {
        let huge = "9".repeat(10_000);
        assert_eq!(
            parse_shape_image_threshold(&huge)
                .expect("overflows to inf, clamps to 1")
                .inner
                .get(),
            1.0
        );
        let tiny = format!("0.{}1", "0".repeat(10_000));
        assert_eq!(
            parse_shape_image_threshold(&tiny)
                .expect("underflows to 0")
                .inner
                .get(),
            0.0
        );
    }
    // ---------------------------------------------------------------------
    // Type invariants: Default, Ord/PartialOrd agreement, Hash
    // ---------------------------------------------------------------------
    #[test]
    fn defaults_are_none_and_zero() {
        assert_eq!(ShapeOutside::default(), ShapeOutside::None);
        assert_eq!(ShapeInside::default(), ShapeInside::None);
        assert_eq!(ClipPath::default(), ClipPath::None);
        assert_eq!(ShapeMargin::default().inner, PixelValue::zero());
        assert_eq!(ShapeMargin::default().inner.number.get(), 0.0);
        assert_eq!(ShapeImageThreshold::default().inner.get(), 0.0);
        // The defaults are exactly what the minimal CSS text parses to.
        assert_eq!(parse_clip_path("none").expect("none"), ClipPath::default());
        assert_eq!(
            parse_shape_margin("0px").expect("0px"),
            ShapeMargin::default()
        );
        assert_eq!(
            parse_shape_image_threshold("0").expect("0"),
            ShapeImageThreshold::default()
        );
    }
    /// `None` sorts before any shape, and the hand-written `Ord` must agree with
    /// the `PartialOrd` that delegates to it.
    #[test]
    fn none_sorts_before_shape_and_ord_agrees_with_partial_ord() {
        let shape_clip = parse_clip_path("circle(1px)").expect("circle");
        let shape_out = parse_shape_outside("circle(1px)").expect("circle");
        let shape_in = parse_shape_inside("circle(1px)").expect("circle");
        assert_eq!(ClipPath::None.cmp(&shape_clip), Ordering::Less);
        assert_eq!(shape_clip.cmp(&ClipPath::None), Ordering::Greater);
        assert_eq!(ClipPath::None.cmp(&ClipPath::None), Ordering::Equal);
        assert_eq!(
            ClipPath::None.partial_cmp(&shape_clip),
            Some(ClipPath::None.cmp(&shape_clip))
        );
        assert_eq!(ShapeOutside::None.cmp(&shape_out), Ordering::Less);
        assert_eq!(
            ShapeOutside::None.partial_cmp(&shape_out),
            Some(Ordering::Less)
        );
        assert_eq!(ShapeInside::None.cmp(&shape_in), Ordering::Less);
        assert_eq!(
            ShapeInside::None.partial_cmp(&shape_in),
            Some(Ordering::Less)
        );
    }
    /// `CssShape`'s `Ord` is hand-written with explicit cross-variant arms whose
    /// ORDER encodes the variant ranking. Check it is a strict, antisymmetric
    /// total order across all five variants — a merged/reordered arm would show
    /// up here as two variants comparing Less in both directions.
    #[test]
    fn css_shape_variant_ordering_is_antisymmetric() {
        let shapes = [
            parse_clip_path("circle(1px)").expect("circle"),
            parse_clip_path("ellipse(1px 2px)").expect("ellipse"),
            parse_clip_path("polygon(0 0, 1 1, 2 2)").expect("polygon"),
            parse_clip_path("inset(1px)").expect("inset"),
            parse_clip_path("path(\"Z\")").expect("path"),
        ];
        for (i, a) in shapes.iter().enumerate() {
            assert_eq!(a.cmp(a), Ordering::Equal, "variant {i} is not self-equal");
            for (j, b) in shapes.iter().enumerate() {
                let forward = a.cmp(b);
                let backward = b.cmp(a);
                assert_eq!(
                    forward,
                    backward.reverse(),
                    "cmp is not antisymmetric for variants {i} and {j}"
                );
                if i < j {
                    assert_eq!(
                        forward,
                        Ordering::Less,
                        "variant {i} should sort before variant {j}"
                    );
                }
            }
        }
    }
    /// Hash must agree with equality for the values that *are* self-equal (i.e.
    /// everything except the NaN shapes covered by the known-bug test), and the
    /// discriminant must take part so `None` and a shape don't collide.
    #[test]
    fn hash_agrees_with_equality() {
        let a = parse_clip_path("circle(50px at 1px 2px)").expect("circle");
        let b = parse_clip_path("circle(50px at 1px 2px)").expect("circle");
        assert_eq!(a, b);
        assert_eq!(hash_of(&a), hash_of(&b));
        let different = parse_clip_path("circle(51px at 1px 2px)").expect("circle");
        assert_ne!(a, different);
        assert_ne!(hash_of(&a), hash_of(&different));
        // The discriminant takes part in the hash, so None and a shape do not
        // collide (the manual Hash impls would be easy to write without it).
        assert_ne!(hash_of(&ClipPath::None), hash_of(&a));
        assert_eq!(hash_of(&ClipPath::None), hash_of(&ClipPath::None));
        let outside = parse_shape_outside("circle(50px at 1px 2px)").expect("circle");
        assert_ne!(hash_of(&ShapeOutside::None), hash_of(&outside));
        let margin = parse_shape_margin("10px").expect("10px");
        assert_eq!(
            hash_of(&margin),
            hash_of(&ShapeMargin {
                inner: PixelValue::px(10.0)
            })
        );
        assert_ne!(
            hash_of(&margin),
            hash_of(&parse_shape_margin("10em").expect("10em"))
        );
    }
}