1
//! CSS Shape data structures for shape-inside, shape-outside, and clip-path
2
//!
3
//! These types are C-compatible (repr(C)) for use across FFI boundaries.
4

            
5
use alloc::string::String;
6

            
7
use crate::corety::{AzString, OptionF32};
8

            
9
/// Compares two f32 values for ordering, treating NaN as equal.
10
413
fn cmp_f32(a: f32, b: f32) -> core::cmp::Ordering {
11
413
    a.partial_cmp(&b).unwrap_or(core::cmp::Ordering::Equal)
12
413
}
13

            
14
/// A 2D point for shape coordinates (using f32 for precision)
15
#[derive(Debug, Copy, Clone, PartialEq)]
16
#[repr(C)]
17
pub struct ShapePoint {
18
    pub x: f32,
19
    pub y: f32,
20
}
21

            
22
impl_option!(
23
    ShapePoint,
24
    OptionShapePoint,
25
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd]
26
);
27

            
28
impl ShapePoint {
29
    #[must_use]
30
111094
    pub const fn new(x: f32, y: f32) -> Self {
31
111094
        Self { x, y }
32
111094
    }
33

            
34
    #[must_use]
35
252
    pub const fn zero() -> Self {
36
252
        Self { x: 0.0, y: 0.0 }
37
252
    }
38
}
39

            
40
impl Eq for ShapePoint {}
41

            
42
// PartialOrd delegates to Ord (NaN-as-equal) so the two stay consistent.
43
impl PartialOrd for ShapePoint {
44
1337
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
45
1337
        Some(self.cmp(other))
46
1337
    }
47
}
48

            
49
impl Ord for ShapePoint {
50
27522
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
51
27522
        match self.x.partial_cmp(&other.x) {
52
22703
            Some(core::cmp::Ordering::Equal) => self
53
22703
                .y
54
22703
                .partial_cmp(&other.y)
55
22703
                .unwrap_or(core::cmp::Ordering::Equal),
56
4819
            other => other.unwrap_or(core::cmp::Ordering::Equal),
57
        }
58
27522
    }
59
}
60

            
61
impl core::hash::Hash for ShapePoint {
62
24
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
63
24
        self.x.to_bits().hash(state);
64
24
        self.y.to_bits().hash(state);
65
24
    }
66
}
67

            
68
impl_vec!(
69
    ShapePoint,
70
    ShapePointVec,
71
    ShapePointVecDestructor,
72
    ShapePointVecDestructorType,
73
    ShapePointVecSlice,
74
    OptionShapePoint
75
);
76
impl_vec_debug!(ShapePoint, ShapePointVec);
77
impl_vec_partialord!(ShapePoint, ShapePointVec);
78
impl_vec_ord!(ShapePoint, ShapePointVec);
79
impl_vec_clone!(ShapePoint, ShapePointVec, ShapePointVecDestructor);
80
impl_vec_partialeq!(ShapePoint, ShapePointVec);
81
impl_vec_eq!(ShapePoint, ShapePointVec);
82
impl_vec_hash!(ShapePoint, ShapePointVec);
83

            
84
/// A circle shape defined by center point and radius
85
#[derive(Debug, Copy, Clone)]
86
#[repr(C)]
87
pub struct ShapeCircle {
88
    pub center: ShapePoint,
89
    pub radius: f32,
90
}
91

            
92
// PartialEq is hand-written to match the to_bits Hash and the NaN-Equal Ord, so
93
// Eq stays reflexive even when a radius is NaN (a preserved, if unusual, length).
94
impl PartialEq for ShapeCircle {
95
    fn eq(&self, other: &Self) -> bool {
96
        self.cmp(other) == core::cmp::Ordering::Equal
97
    }
98
}
99
impl Eq for ShapeCircle {}
100
impl core::hash::Hash for ShapeCircle {
101
11
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
102
11
        self.center.hash(state);
103
11
        self.radius.to_bits().hash(state);
104
11
    }
105
}
106
impl PartialOrd for ShapeCircle {
107
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
108
        Some(self.cmp(other))
109
    }
110
}
111
impl Ord for ShapeCircle {
112
93
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
113
93
        match self.center.cmp(&other.center) {
114
93
            core::cmp::Ordering::Equal => self
115
93
                .radius
116
93
                .partial_cmp(&other.radius)
117
93
                .unwrap_or(core::cmp::Ordering::Equal),
118
            other => other,
119
        }
120
93
    }
121
}
122

            
123
/// An ellipse shape defined by center point and two radii
124
#[derive(Debug, Copy, Clone)]
125
#[repr(C)]
126
pub struct ShapeEllipse {
127
    pub center: ShapePoint,
128
    pub radius_x: f32,
129
    pub radius_y: f32,
130
}
131

            
132
// PartialEq hand-written to match the to_bits Hash / NaN-Equal Ord (reflexive Eq).
133
impl PartialEq for ShapeEllipse {
134
    fn eq(&self, other: &Self) -> bool {
135
        self.cmp(other) == core::cmp::Ordering::Equal
136
    }
137
}
138
impl Eq for ShapeEllipse {}
139
impl core::hash::Hash for ShapeEllipse {
140
1
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
141
1
        self.center.hash(state);
142
1
        self.radius_x.to_bits().hash(state);
143
1
        self.radius_y.to_bits().hash(state);
144
1
    }
145
}
146
impl PartialOrd for ShapeEllipse {
147
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
148
        Some(self.cmp(other))
149
    }
150
}
151
impl Ord for ShapeEllipse {
152
22
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
153
22
        match self.center.cmp(&other.center) {
154
22
            core::cmp::Ordering::Equal => match self.radius_x.partial_cmp(&other.radius_x) {
155
22
                Some(core::cmp::Ordering::Equal) | None => self
156
22
                    .radius_y
157
22
                    .partial_cmp(&other.radius_y)
158
22
                    .unwrap_or(core::cmp::Ordering::Equal),
159
                Some(other) => other,
160
            },
161
            other => other,
162
        }
163
22
    }
164
}
165

            
166
/// A polygon shape defined by a list of points (in clockwise order)
167
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
168
#[repr(C)]
169
pub struct ShapePolygon {
170
    pub points: ShapePointVec,
171
}
172

            
173
/// An inset rectangle with optional border radius
174
/// Defined by insets from the reference box edges
175
#[derive(Debug, Copy, Clone)]
176
#[repr(C)]
177
pub struct ShapeInset {
178
    pub inset_top: f32,
179
    pub inset_right: f32,
180
    pub inset_bottom: f32,
181
    pub inset_left: f32,
182
    pub border_radius: OptionF32,
183
}
184

            
185
// PartialEq hand-written to match the to_bits Hash / NaN-Equal Ord (reflexive Eq).
186
impl PartialEq for ShapeInset {
187
    fn eq(&self, other: &Self) -> bool {
188
        self.cmp(other) == core::cmp::Ordering::Equal
189
    }
190
}
191
impl Eq for ShapeInset {}
192
impl core::hash::Hash for ShapeInset {
193
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
194
        self.inset_top.to_bits().hash(state);
195
        self.inset_right.to_bits().hash(state);
196
        self.inset_bottom.to_bits().hash(state);
197
        self.inset_left.to_bits().hash(state);
198
        self.border_radius.hash(state);
199
    }
200
}
201
impl PartialOrd for ShapeInset {
202
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
203
        Some(self.cmp(other))
204
    }
205
}
206
impl Ord for ShapeInset {
207
37
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
208
37
        cmp_f32(self.inset_top, other.inset_top)
209
37
            .then_with(|| cmp_f32(self.inset_right, other.inset_right))
210
37
            .then_with(|| cmp_f32(self.inset_bottom, other.inset_bottom))
211
37
            .then_with(|| cmp_f32(self.inset_left, other.inset_left))
212
37
            .then_with(|| self.border_radius.cmp(&other.border_radius))
213
37
    }
214
}
215

            
216
/// An SVG-like path for shape definitions.
217
/// TODO: path parsing is not yet implemented — `data` is stored but not interpreted.
218
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
219
#[repr(C)]
220
pub struct ShapePath {
221
    pub data: AzString,
222
}
223

            
224
/// Represents a CSS shape for shape-inside, shape-outside, and clip-path.
225
/// Used for both text layout (shape-inside/outside) and rendering clipping (clip-path).
226
#[derive(Debug, Clone)]
227
#[repr(C, u8)]
228
pub enum CssShape {
229
    Circle(ShapeCircle),
230
    Ellipse(ShapeEllipse),
231
    Polygon(ShapePolygon),
232
    Inset(ShapeInset),
233
    Path(ShapePath),
234
}
235

            
236
// PartialEq hand-written to match the to_bits Hash / NaN-Equal Ord (reflexive Eq
237
// through the float-holding variants).
238
impl PartialEq for CssShape {
239
71
    fn eq(&self, other: &Self) -> bool {
240
71
        self.cmp(other) == core::cmp::Ordering::Equal
241
71
    }
242
}
243
impl Eq for CssShape {}
244

            
245
impl core::hash::Hash for CssShape {
246
14
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
247
14
        core::mem::discriminant(self).hash(state);
248
14
        match self {
249
11
            Self::Circle(c) => c.hash(state),
250
1
            Self::Ellipse(e) => e.hash(state),
251
2
            Self::Polygon(p) => p.hash(state),
252
            Self::Inset(i) => i.hash(state),
253
            Self::Path(p) => p.hash(state),
254
        }
255
14
    }
256
}
257

            
258
impl PartialOrd for CssShape {
259
91
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
260
91
        Some(self.cmp(other))
261
91
    }
262
}
263

            
264
impl Ord for CssShape {
265
    // The tie-break arms `(Self::X(_), _) => Less` / `(_, Self::X(_)) => Greater`
266
    // share bodies but are ORDER-DEPENDENT: they encode the variant ordering, so
267
    // merging them (clippy::match_same_arms) would change the comparison result.
268
    #[allow(clippy::match_same_arms)]
269
542
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
270
542
        match (self, other) {
271
93
            (Self::Circle(a), Self::Circle(b)) => a.cmp(b),
272
21
            (Self::Ellipse(a), Self::Ellipse(b)) => a.cmp(b),
273
39
            (Self::Polygon(a), Self::Polygon(b)) => a.cmp(b),
274
37
            (Self::Inset(a), Self::Inset(b)) => a.cmp(b),
275
46
            (Self::Path(a), Self::Path(b)) => a.cmp(b),
276
            // Different variants: use discriminant ordering
277
68
            (Self::Circle(_), _) => core::cmp::Ordering::Less,
278
64
            (_, Self::Circle(_)) => core::cmp::Ordering::Greater,
279
33
            (Self::Ellipse(_), _) => core::cmp::Ordering::Less,
280
30
            (_, Self::Ellipse(_)) => core::cmp::Ordering::Greater,
281
38
            (Self::Polygon(_), _) => core::cmp::Ordering::Less,
282
36
            (_, Self::Polygon(_)) => core::cmp::Ordering::Greater,
283
19
            (Self::Inset(_), Self::Path(_)) => core::cmp::Ordering::Less,
284
18
            (Self::Path(_), Self::Inset(_)) => core::cmp::Ordering::Greater,
285
        }
286
542
    }
287
}
288

            
289
impl CssShape {
290
    /// Creates a circle shape at the given position with the given radius
291
    #[must_use]
292
408
    pub const fn circle(center: ShapePoint, radius: f32) -> Self {
293
408
        Self::Circle(ShapeCircle { center, radius })
294
408
    }
295

            
296
    /// Creates an ellipse shape
297
    #[must_use]
298
51
    pub const fn ellipse(center: ShapePoint, radius_x: f32, radius_y: f32) -> Self {
299
51
        Self::Ellipse(ShapeEllipse {
300
51
            center,
301
51
            radius_x,
302
51
            radius_y,
303
51
        })
304
51
    }
305

            
306
    /// Creates a polygon from a list of points
307
    #[must_use]
308
82
    pub const fn polygon(points: ShapePointVec) -> Self {
309
82
        Self::Polygon(ShapePolygon { points })
310
82
    }
311

            
312
    /// Creates an inset rectangle
313
    #[must_use]
314
46
    pub const fn inset(top: f32, right: f32, bottom: f32, left: f32) -> Self {
315
46
        Self::Inset(ShapeInset {
316
46
            inset_top: top,
317
46
            inset_right: right,
318
46
            inset_bottom: bottom,
319
46
            inset_left: left,
320
46
            border_radius: OptionF32::None,
321
46
        })
322
46
    }
323

            
324
    /// Creates an inset rectangle with rounded corners
325
    #[must_use]
326
40
    pub const fn inset_rounded(top: f32, right: f32, bottom: f32, left: f32, radius: f32) -> Self {
327
40
        Self::Inset(ShapeInset {
328
40
            inset_top: top,
329
40
            inset_right: right,
330
40
            inset_bottom: bottom,
331
40
            inset_left: left,
332
40
            border_radius: OptionF32::Some(radius),
333
40
        })
334
40
    }
335

            
336
    #[must_use]
337
118
    pub fn print_as_css_value(&self) -> String {
338
        use alloc::format;
339
118
        match self {
340
32
            Self::Circle(ShapeCircle { center, radius }) => {
341
32
                format!("circle({}px at {}px {}px)", radius, center.x, center.y)
342
            }
343
            Self::Ellipse(ShapeEllipse {
344
15
                center,
345
15
                radius_x,
346
15
                radius_y,
347
            }) => {
348
15
                format!(
349
15
                    "ellipse({}px {}px at {}px {}px)",
350
                    radius_x, radius_y, center.x, center.y
351
                )
352
            }
353
21
            Self::Polygon(ShapePolygon { points }) => {
354
21
                let pts: Vec<String> = points
355
21
                    .as_ref()
356
21
                    .iter()
357
7054
                    .map(|p| format!("{}px {}px", p.x, p.y))
358
21
                    .collect();
359
21
                format!("polygon({})", pts.join(", "))
360
            }
361
            Self::Inset(ShapeInset {
362
23
                inset_top,
363
23
                inset_right,
364
23
                inset_bottom,
365
23
                inset_left,
366
23
                border_radius,
367
            }) => {
368
23
                let base =
369
23
                    format!("inset({inset_top}px {inset_right}px {inset_bottom}px {inset_left}px");
370
23
                match border_radius {
371
9
                    OptionF32::Some(r) => format!("{base} round {r}px)"),
372
14
                    OptionF32::None => format!("{base})"),
373
                }
374
            }
375
27
            Self::Path(ShapePath { data }) => {
376
27
                format!("path(\"{}\")", data.as_str())
377
            }
378
        }
379
118
    }
380

            
381
    #[must_use]
382
25
    pub fn format_as_rust_code(&self) -> String {
383
        use alloc::format;
384
25
        match self {
385
3
            Self::Circle(ShapeCircle { center, radius }) => {
386
3
                format!(
387
3
                    "CssShape::Circle(ShapeCircle {{ center: ShapePoint::new({}_f32, {}_f32), \
388
3
                     radius: {}_f32 }})",
389
                    center.x, center.y, radius
390
                )
391
            }
392
            Self::Ellipse(ShapeEllipse {
393
2
                center,
394
2
                radius_x,
395
2
                radius_y,
396
            }) => {
397
2
                format!(
398
2
                    "CssShape::Ellipse(ShapeEllipse {{ center: ShapePoint::new({}_f32, {}_f32), \
399
2
                     radius_x: {}_f32, radius_y: {}_f32 }})",
400
                    center.x, center.y, radius_x, radius_y
401
                )
402
            }
403
3
            Self::Polygon(ShapePolygon { points }) => {
404
3
                let pts: Vec<String> = points
405
3
                    .as_ref()
406
3
                    .iter()
407
3
                    .map(|p| format!("ShapePoint::new({}_f32, {}_f32)", p.x, p.y))
408
3
                    .collect();
409
3
                format!(
410
3
                    "CssShape::Polygon(ShapePolygon {{ points: vec![{}].into() }})",
411
3
                    pts.join(", ")
412
                )
413
            }
414
            Self::Inset(ShapeInset {
415
14
                inset_top,
416
14
                inset_right,
417
14
                inset_bottom,
418
14
                inset_left,
419
14
                border_radius,
420
            }) => {
421
14
                let br = match border_radius {
422
12
                    OptionF32::Some(r) => format!("OptionF32::Some({r}_f32)"),
423
2
                    OptionF32::None => String::from("OptionF32::None"),
424
                };
425
14
                format!(
426
14
                    "CssShape::Inset(ShapeInset {{ inset_top: {inset_top}_f32, inset_right: \
427
14
                     {inset_right}_f32, inset_bottom: {inset_bottom}_f32, inset_left: \
428
14
                     {inset_left}_f32, border_radius: {br} }})"
429
                )
430
            }
431
3
            Self::Path(ShapePath { data }) => {
432
3
                format!(
433
3
                    "CssShape::Path(ShapePath {{ data: AzString::from_const_str(\"{}\") }})",
434
3
                    data.as_str()
435
                )
436
            }
437
        }
438
25
    }
439
}
440

            
441
impl_option!(
442
    CssShape,
443
    OptionCssShape,
444
    copy = false,
445
    [Debug, Clone, PartialEq, Eq]
446
);
447

            
448
#[cfg(test)]
449
mod autotest_generated {
450
    // Float values are compared for exact bit/value identity on purpose: these
451
    // tests check that constructors and (de)serialization are lossless, not that
452
    // the values are approximately right.
453
    #![allow(
454
        clippy::float_cmp,
455
        clippy::unreadable_literal,
456
        clippy::cast_precision_loss
457
    )]
458

            
459
    use core::{
460
        cmp::Ordering,
461
        hash::{Hash, Hasher},
462
    };
463
    use std::collections::hash_map::DefaultHasher;
464

            
465
    use super::*;
466
    use crate::shape_parser::{parse_shape, ShapeParseError};
467

            
468
    /// Every f32 edge value the shape types have to survive.
469
    const EDGE_F32: &[f32] = &[
470
        0.0,
471
        -0.0,
472
        1.0,
473
        -1.0,
474
        f32::MIN,
475
        f32::MAX,
476
        f32::MIN_POSITIVE,
477
        f32::EPSILON,
478
        f32::INFINITY,
479
        f32::NEG_INFINITY,
480
        f32::NAN,
481
    ];
482

            
483
    fn hash_of<T: Hash>(t: &T) -> u64 {
484
        let mut h = DefaultHasher::new();
485
        t.hash(&mut h);
486
        h.finish()
487
    }
488

            
489
    /// Encode a shape to CSS, decode it back. Panics if the shape does not
490
    /// survive its own printer -> the crate's own parser.
491
    fn roundtrip(shape: &CssShape) -> CssShape {
492
        let css = shape.print_as_css_value();
493
        parse_shape(&css).unwrap_or_else(|e| panic!("round-trip failed for {css:?}: {e:?}"))
494
    }
495

            
496
    fn poly(coords: &[(f32, f32)]) -> CssShape {
497
        let pts: Vec<ShapePoint> = coords
498
            .iter()
499
            .map(|(x, y)| ShapePoint::new(*x, *y))
500
            .collect();
501
        CssShape::polygon(ShapePointVec::from_vec(pts))
502
    }
503

            
504
    fn path(data: &str) -> CssShape {
505
        CssShape::Path(ShapePath {
506
            data: AzString::from(data),
507
        })
508
    }
509

            
510
    // ---------------------------------------------------------------------
511
    // cmp_f32 (private, numeric)
512
    // ---------------------------------------------------------------------
513

            
514
    #[test]
515
    fn cmp_f32_orders_ordinary_values() {
516
        assert_eq!(cmp_f32(1.0, 2.0), Ordering::Less);
517
        assert_eq!(cmp_f32(2.0, 1.0), Ordering::Greater);
518
        assert_eq!(cmp_f32(2.0, 2.0), Ordering::Equal);
519
        assert_eq!(cmp_f32(-1.0, 1.0), Ordering::Less);
520
    }
521

            
522
    #[test]
523
    fn cmp_f32_treats_both_zeroes_as_equal() {
524
        assert_eq!(cmp_f32(0.0, -0.0), Ordering::Equal);
525
        assert_eq!(cmp_f32(-0.0, 0.0), Ordering::Equal);
526
    }
527

            
528
    #[test]
529
    fn cmp_f32_nan_is_equal_to_everything_and_never_panics() {
530
        // Documented contract: "treating NaN as equal".
531
        assert_eq!(cmp_f32(f32::NAN, f32::NAN), Ordering::Equal);
532
        for &v in EDGE_F32 {
533
            assert_eq!(cmp_f32(f32::NAN, v), Ordering::Equal);
534
            assert_eq!(cmp_f32(v, f32::NAN), Ordering::Equal);
535
        }
536
    }
537

            
538
    #[test]
539
    fn cmp_f32_handles_infinities_and_limits() {
540
        assert_eq!(cmp_f32(f32::INFINITY, f32::MAX), Ordering::Greater);
541
        assert_eq!(cmp_f32(f32::NEG_INFINITY, f32::MIN), Ordering::Less);
542
        assert_eq!(cmp_f32(f32::INFINITY, f32::INFINITY), Ordering::Equal);
543
        assert_eq!(cmp_f32(f32::NEG_INFINITY, f32::INFINITY), Ordering::Less);
544
        assert_eq!(cmp_f32(f32::MIN_POSITIVE, 0.0), Ordering::Greater);
545
        // Smallest subnormal still sorts above zero.
546
        assert_eq!(cmp_f32(f32::from_bits(1), 0.0), Ordering::Greater);
547
        assert_eq!(cmp_f32(f32::MIN, f32::MAX), Ordering::Less);
548
    }
549

            
550
    #[test]
551
    fn cmp_f32_is_antisymmetric_over_all_edge_values() {
552
        for &a in EDGE_F32 {
553
            for &b in EDGE_F32 {
554
                assert_eq!(
555
                    cmp_f32(a, b),
556
                    cmp_f32(b, a).reverse(),
557
                    "antisymmetry broken for ({a}, {b})"
558
                );
559
            }
560
        }
561
    }
562

            
563
    #[test]
564
    fn cmp_f32_nan_equality_is_not_transitive() {
565
        // Characterization of the known cost of "NaN as equal": NaN == 1.0 and
566
        // NaN == 2.0, yet 1.0 < 2.0. Ord's transitivity therefore does NOT hold
567
        // once a NaN is in the set, so slices holding NaN-bearing shapes must
568
        // not be `sort()`ed (std may panic on a non-total order).
569
        assert_eq!(cmp_f32(f32::NAN, 1.0), Ordering::Equal);
570
        assert_eq!(cmp_f32(f32::NAN, 2.0), Ordering::Equal);
571
        assert_eq!(cmp_f32(1.0, 2.0), Ordering::Less);
572
    }
573

            
574
    // ---------------------------------------------------------------------
575
    // ShapePoint::new / ShapePoint::zero (constructors)
576
    // ---------------------------------------------------------------------
577

            
578
    #[test]
579
    fn shapepoint_new_stores_fields_verbatim() {
580
        let p = ShapePoint::new(3.5, -7.25);
581
        assert_eq!(p.x, 3.5);
582
        assert_eq!(p.y, -7.25);
583
    }
584

            
585
    #[test]
586
    fn shapepoint_new_does_not_normalize_edge_values() {
587
        for &x in EDGE_F32 {
588
            for &y in EDGE_F32 {
589
                let p = ShapePoint::new(x, y);
590
                // Bit-exact: no clamping, no NaN canonicalization, no -0 flush.
591
                assert_eq!(p.x.to_bits(), x.to_bits());
592
                assert_eq!(p.y.to_bits(), y.to_bits());
593
            }
594
        }
595
    }
596

            
597
    #[test]
598
    fn shapepoint_new_preserves_negative_zero_sign() {
599
        let p = ShapePoint::new(-0.0, 0.0);
600
        assert_eq!(p.x.to_bits(), (-0.0f32).to_bits());
601
        assert_eq!(p.y.to_bits(), (0.0f32).to_bits());
602
        assert!(p.x.is_sign_negative());
603
    }
604

            
605
    #[test]
606
    fn shapepoint_zero_is_the_neutral_positive_zero() {
607
        let z = ShapePoint::zero();
608
        assert_eq!(z.x.to_bits(), 0);
609
        assert_eq!(z.y.to_bits(), 0);
610
        assert_eq!(z, ShapePoint::new(0.0, 0.0));
611
        assert_eq!(z.cmp(&ShapePoint::new(0.0, 0.0)), Ordering::Equal);
612
    }
613

            
614
    #[test]
615
    fn shapepoint_constructors_are_usable_in_const_context() {
616
        const P: ShapePoint = ShapePoint::new(1.0, 2.0);
617
        const Z: ShapePoint = ShapePoint::zero();
618
        assert_eq!(P.x, 1.0);
619
        assert_eq!(Z, ShapePoint::zero());
620
        // repr(C) layout guarantee relied on across the FFI boundary.
621
        assert_eq!(size_of::<ShapePoint>(), 8);
622
    }
623

            
624
    // ---------------------------------------------------------------------
625
    // ShapePoint Ord / Eq / Hash invariants
626
    // ---------------------------------------------------------------------
627

            
628
    #[test]
629
    fn shapepoint_ord_sorts_by_x_then_y() {
630
        let mut v = vec![
631
            ShapePoint::new(1.0, 5.0),
632
            ShapePoint::new(-3.0, 0.0),
633
            ShapePoint::new(1.0, -5.0),
634
            ShapePoint::new(0.0, 0.0),
635
        ];
636
        v.sort(); // no NaN involved -> total order holds, sort must not panic
637
        assert_eq!(
638
            v,
639
            vec![
640
                ShapePoint::new(-3.0, 0.0),
641
                ShapePoint::new(0.0, 0.0),
642
                ShapePoint::new(1.0, -5.0),
643
                ShapePoint::new(1.0, 5.0),
644
            ]
645
        );
646
    }
647

            
648
    #[test]
649
    fn shapepoint_cmp_is_antisymmetric_even_with_nan() {
650
        for &ax in EDGE_F32 {
651
            for &ay in EDGE_F32 {
652
                let a = ShapePoint::new(ax, ay);
653
                for &bx in EDGE_F32 {
654
                    let b = ShapePoint::new(bx, 1.0);
655
                    assert_eq!(
656
                        a.cmp(&b),
657
                        b.cmp(&a).reverse(),
658
                        "antisymmetry broken for {a:?} vs {b:?}"
659
                    );
660
                    // PartialOrd must agree with Ord (it delegates).
661
                    assert_eq!(a.partial_cmp(&b), Some(a.cmp(&b)));
662
                }
663
            }
664
        }
665
    }
666

            
667
    #[test]
668
    fn shapepoint_cmp_with_nan_x_ignores_y_entirely() {
669
        // Characterization: when the x comparison is indeterminate, cmp() returns
670
        // Equal WITHOUT looking at y -- unlike ShapeEllipse::cmp, which falls
671
        // through to the next field on None. The two NaN policies in this file
672
        // disagree; see the report.
673
        let a = ShapePoint::new(f32::NAN, 1.0);
674
        let b = ShapePoint::new(f32::NAN, 2.0);
675
        assert_eq!(a.cmp(&b), Ordering::Equal);
676

            
677
        let e1 = ShapeEllipse {
678
            center: ShapePoint::zero(),
679
            radius_x: f32::NAN,
680
            radius_y: 1.0,
681
        };
682
        let e2 = ShapeEllipse {
683
            center: ShapePoint::zero(),
684
            radius_x: f32::NAN,
685
            radius_y: 2.0,
686
        };
687
        assert_eq!(e1.cmp(&e2), Ordering::Less);
688
    }
689

            
690
    #[test]
691
    fn shapepoint_nan_is_ord_equal_but_partialeq_unequal() {
692
        // Eq is implemented for ShapePoint, but PartialEq is derived on f32, so
693
        // reflexivity does not actually hold for NaN while Ord reports Equal.
694
        let a = ShapePoint::new(f32::NAN, 0.0);
695
        let b = ShapePoint::new(f32::NAN, 0.0);
696
        assert_ne!(a, b, "derived PartialEq: NaN != NaN");
697
        assert_eq!(a.cmp(&b), Ordering::Equal, "Ord: NaN treated as equal");
698
    }
699

            
700
    #[test]
701
    fn shapepoint_hash_is_deterministic_and_bitwise() {
702
        let a = ShapePoint::new(1.5, -2.5);
703
        let b = ShapePoint::new(1.5, -2.5);
704
        assert_eq!(hash_of(&a), hash_of(&b));
705
        assert_ne!(hash_of(&a), hash_of(&ShapePoint::new(-2.5, 1.5)));
706
        // NaN hashes by bits, so an identical NaN hashes identically even though
707
        // it does not compare PartialEq-equal to itself.
708
        let n1 = ShapePoint::new(f32::NAN, 0.0);
709
        let n2 = ShapePoint::new(f32::NAN, 0.0);
710
        assert_eq!(hash_of(&n1), hash_of(&n2));
711
    }
712

            
713
    // ---------------------------------------------------------------------
714
    // CssShape constructors (numeric)
715
    // ---------------------------------------------------------------------
716

            
717
    #[test]
718
    fn circle_stores_center_and_radius_including_zero_and_negative() {
719
        match CssShape::circle(ShapePoint::zero(), 0.0) {
720
            CssShape::Circle(c) => {
721
                assert_eq!(c.radius, 0.0);
722
                assert_eq!(c.center, ShapePoint::zero());
723
            }
724
            other => panic!("expected Circle, got {other:?}"),
725
        }
726
        // A negative radius is CSS-invalid but accepted verbatim here (no clamp).
727
        match CssShape::circle(ShapePoint::new(-1.0, -2.0), -50.0) {
728
            CssShape::Circle(c) => assert_eq!(c.radius, -50.0),
729
            other => panic!("expected Circle, got {other:?}"),
730
        }
731
    }
732

            
733
    #[test]
734
    fn circle_accepts_every_f32_edge_value_without_panicking() {
735
        for &r in EDGE_F32 {
736
            for &c in EDGE_F32 {
737
                let shape = CssShape::circle(ShapePoint::new(c, c), r);
738
                match shape {
739
                    CssShape::Circle(circle) => {
740
                        assert_eq!(circle.radius.to_bits(), r.to_bits());
741
                    }
742
                    other => panic!("expected Circle, got {other:?}"),
743
                }
744
            }
745
        }
746
    }
747

            
748
    #[test]
749
    fn ellipse_stores_both_radii_verbatim() {
750
        match CssShape::ellipse(ShapePoint::new(1.0, 2.0), f32::INFINITY, f32::NEG_INFINITY) {
751
            CssShape::Ellipse(e) => {
752
                assert!(e.radius_x.is_infinite() && e.radius_x.is_sign_positive());
753
                assert!(e.radius_y.is_infinite() && e.radius_y.is_sign_negative());
754
                assert_eq!(e.center, ShapePoint::new(1.0, 2.0));
755
            }
756
            other => panic!("expected Ellipse, got {other:?}"),
757
        }
758
        match CssShape::ellipse(ShapePoint::zero(), f32::NAN, f32::MAX) {
759
            CssShape::Ellipse(e) => {
760
                assert!(e.radius_x.is_nan());
761
                assert_eq!(e.radius_y, f32::MAX);
762
            }
763
            other => panic!("expected Ellipse, got {other:?}"),
764
        }
765
    }
766

            
767
    #[test]
768
    fn polygon_accepts_empty_and_huge_point_lists() {
769
        match CssShape::polygon(ShapePointVec::from_vec(Vec::new())) {
770
            CssShape::Polygon(p) => {
771
                assert!(p.points.is_empty());
772
                assert_eq!(p.points.len(), 0);
773
            }
774
            other => panic!("expected Polygon, got {other:?}"),
775
        }
776

            
777
        let big: Vec<ShapePoint> = (0..10_000)
778
            .map(|i| ShapePoint::new(i as f32, -(i as f32)))
779
            .collect();
780
        match CssShape::polygon(ShapePointVec::from_vec(big)) {
781
            CssShape::Polygon(p) => {
782
                assert_eq!(p.points.len(), 10_000);
783
                assert_eq!(p.points.as_ref()[9_999], ShapePoint::new(9999.0, -9999.0));
784
            }
785
            other => panic!("expected Polygon, got {other:?}"),
786
        }
787
    }
788

            
789
    #[test]
790
    fn inset_has_no_border_radius_and_keeps_side_order() {
791
        match CssShape::inset(1.0, 2.0, 3.0, 4.0) {
792
            CssShape::Inset(i) => {
793
                assert_eq!(i.inset_top, 1.0);
794
                assert_eq!(i.inset_right, 2.0);
795
                assert_eq!(i.inset_bottom, 3.0);
796
                assert_eq!(i.inset_left, 4.0);
797
                assert_eq!(i.border_radius, OptionF32::None);
798
                assert_eq!(i.border_radius.into_option(), None);
799
            }
800
            other => panic!("expected Inset, got {other:?}"),
801
        }
802
    }
803

            
804
    #[test]
805
    fn inset_accepts_min_max_and_nan_without_panicking() {
806
        match CssShape::inset(f32::MIN, f32::MAX, f32::NAN, f32::NEG_INFINITY) {
807
            CssShape::Inset(i) => {
808
                assert_eq!(i.inset_top, f32::MIN);
809
                assert_eq!(i.inset_right, f32::MAX);
810
                assert!(i.inset_bottom.is_nan());
811
                assert!(i.inset_left.is_infinite());
812
            }
813
            other => panic!("expected Inset, got {other:?}"),
814
        }
815
    }
816

            
817
    #[test]
818
    fn inset_rounded_keeps_even_a_css_invalid_negative_radius() {
819
        match CssShape::inset_rounded(0.0, 0.0, 0.0, 0.0, -5.0) {
820
            CssShape::Inset(i) => {
821
                assert_eq!(i.border_radius, OptionF32::Some(-5.0));
822
                assert_eq!(i.border_radius.into_option(), Some(-5.0));
823
            }
824
            other => panic!("expected Inset, got {other:?}"),
825
        }
826
        match CssShape::inset_rounded(0.0, 0.0, 0.0, 0.0, f32::NAN) {
827
            CssShape::Inset(i) => match i.border_radius {
828
                OptionF32::Some(r) => assert!(r.is_nan()),
829
                OptionF32::None => panic!("radius was dropped"),
830
            },
831
            other => panic!("expected Inset, got {other:?}"),
832
        }
833
    }
834

            
835
    #[test]
836
    fn css_shape_constructors_are_usable_in_const_context() {
837
        const CIRCLE: CssShape = CssShape::circle(ShapePoint::zero(), 5.0);
838
        const ELLIPSE: CssShape = CssShape::ellipse(ShapePoint::zero(), 1.0, 2.0);
839
        const INSET: CssShape = CssShape::inset(0.0, 0.0, 0.0, 0.0);
840
        const ROUNDED: CssShape = CssShape::inset_rounded(0.0, 0.0, 0.0, 0.0, 1.0);
841
        assert!(matches!(CIRCLE, CssShape::Circle(_)));
842
        assert!(matches!(ELLIPSE, CssShape::Ellipse(_)));
843
        assert!(matches!(INSET, CssShape::Inset(_)));
844
        assert!(matches!(ROUNDED, CssShape::Inset(_)));
845
    }
846

            
847
    // ---------------------------------------------------------------------
848
    // CssShape Ord / Hash invariants
849
    // ---------------------------------------------------------------------
850

            
851
    #[test]
852
    fn css_shape_variant_order_is_circle_ellipse_polygon_inset_path() {
853
        let shapes = vec![
854
            path("M 0 0"),
855
            CssShape::inset(1.0, 1.0, 1.0, 1.0),
856
            poly(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)]),
857
            CssShape::ellipse(ShapePoint::zero(), 1.0, 2.0),
858
            CssShape::circle(ShapePoint::zero(), 1.0),
859
        ];
860
        let mut sorted = shapes;
861
        sorted.sort(); // finite values only -> total order, must not panic
862
        let discriminants: Vec<&str> = sorted
863
            .iter()
864
            .map(|s| match s {
865
                CssShape::Circle(_) => "circle",
866
                CssShape::Ellipse(_) => "ellipse",
867
                CssShape::Polygon(_) => "polygon",
868
                CssShape::Inset(_) => "inset",
869
                CssShape::Path(_) => "path",
870
            })
871
            .collect();
872
        assert_eq!(
873
            discriminants,
874
            vec!["circle", "ellipse", "polygon", "inset", "path"]
875
        );
876
    }
877

            
878
    #[test]
879
    fn css_shape_cmp_is_antisymmetric_across_variants_and_nan() {
880
        let shapes = vec![
881
            CssShape::circle(ShapePoint::zero(), f32::NAN),
882
            CssShape::circle(ShapePoint::new(f32::NAN, 0.0), 1.0),
883
            CssShape::ellipse(ShapePoint::zero(), f32::NAN, f32::INFINITY),
884
            poly(&[]),
885
            poly(&[(f32::NAN, f32::NEG_INFINITY)]),
886
            CssShape::inset(f32::NAN, f32::MAX, f32::MIN, -0.0),
887
            CssShape::inset_rounded(0.0, 0.0, 0.0, 0.0, f32::NAN),
888
            path(""),
889
            path("\u{1F600}"),
890
        ];
891
        for a in &shapes {
892
            for b in &shapes {
893
                assert_eq!(
894
                    a.cmp(b),
895
                    b.cmp(a).reverse(),
896
                    "antisymmetry broken for {a:?} vs {b:?}"
897
                );
898
                assert_eq!(a.partial_cmp(b), Some(a.cmp(b)));
899
            }
900
        }
901
    }
902

            
903
    #[test]
904
    fn css_shape_hash_separates_variants_with_identical_payloads() {
905
        let circle = CssShape::circle(ShapePoint::zero(), 1.0);
906
        let ellipse = CssShape::ellipse(ShapePoint::zero(), 1.0, 1.0);
907
        assert_ne!(hash_of(&circle), hash_of(&ellipse));
908
        assert_eq!(
909
            hash_of(&circle),
910
            hash_of(&CssShape::circle(ShapePoint::zero(), 1.0))
911
        );
912
        // Equal values must hash equally (holds for every non-NaN, non -0.0 case).
913
        let p1 = poly(&[(1.0, 2.0), (3.0, 4.0), (5.0, 6.0)]);
914
        let p2 = poly(&[(1.0, 2.0), (3.0, 4.0), (5.0, 6.0)]);
915
        assert_eq!(p1, p2);
916
        assert_eq!(hash_of(&p1), hash_of(&p2));
917
    }
918

            
919
    // ---------------------------------------------------------------------
920
    // print_as_css_value (getter)
921
    // ---------------------------------------------------------------------
922

            
923
    #[test]
924
    fn print_as_css_value_known_constructions() {
925
        assert_eq!(
926
            CssShape::circle(ShapePoint::new(100.0, 100.0), 50.0).print_as_css_value(),
927
            "circle(50px at 100px 100px)"
928
        );
929
        assert_eq!(
930
            CssShape::ellipse(ShapePoint::new(1.0, 2.0), 3.0, 4.5).print_as_css_value(),
931
            "ellipse(3px 4.5px at 1px 2px)"
932
        );
933
        assert_eq!(
934
            poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)]).print_as_css_value(),
935
            "polygon(0px 0px, 100px 0px, 100px 100px)"
936
        );
937
        assert_eq!(
938
            CssShape::inset(1.0, 2.0, 3.0, 4.0).print_as_css_value(),
939
            "inset(1px 2px 3px 4px)"
940
        );
941
        assert_eq!(
942
            CssShape::inset_rounded(1.0, 2.0, 3.0, 4.0, 5.0).print_as_css_value(),
943
            "inset(1px 2px 3px 4px round 5px)"
944
        );
945
        assert_eq!(
946
            path("M 0 0 L 1 1 Z").print_as_css_value(),
947
            "path(\"M 0 0 L 1 1 Z\")"
948
        );
949
    }
950

            
951
    #[test]
952
    fn print_as_css_value_empty_polygon_emits_empty_parens() {
953
        // Not valid CSS (a polygon needs >= 3 points) but must not panic.
954
        assert_eq!(poly(&[]).print_as_css_value(), "polygon()");
955
    }
956

            
957
    #[test]
958
    fn print_as_css_value_emits_non_css_tokens_for_nan_and_inf() {
959
        // Characterization: `NaNpx` / `infpx` are NOT valid CSS lengths. The
960
        // printer does not guard against non-finite inputs; see the report.
961
        let s = CssShape::circle(ShapePoint::new(f32::INFINITY, f32::NEG_INFINITY), f32::NAN)
962
            .print_as_css_value();
963
        assert_eq!(s, "circle(NaNpx at infpx -infpx)");
964
    }
965

            
966
    #[test]
967
    fn print_as_css_value_handles_extreme_finite_values() {
968
        let s = CssShape::inset(f32::MIN, f32::MAX, f32::MIN_POSITIVE, 0.0).print_as_css_value();
969
        assert!(s.starts_with("inset(-"), "got {s}");
970
        assert!(s.ends_with("px)"), "got {s}");
971
        assert!(!s.contains("inf"), "MIN/MAX must not print as inf: {s}");
972
    }
973

            
974
    #[test]
975
    fn print_as_css_value_survives_a_huge_polygon() {
976
        let coords: Vec<(f32, f32)> = (0..5_000).map(|i| (i as f32, i as f32)).collect();
977
        let s = poly(&coords).print_as_css_value();
978
        assert!(s.starts_with("polygon(0px 0px, "));
979
        assert!(s.ends_with("4999px 4999px)"));
980
        assert_eq!(s.matches(", ").count(), 4_999);
981
    }
982

            
983
    #[test]
984
    fn print_as_css_value_does_not_escape_path_data() {
985
        // Characterization: a quote inside the path data is emitted raw, so the
986
        // printed value is no longer a well-formed CSS string. See the report.
987
        let s = path("a\"b").print_as_css_value();
988
        assert_eq!(s, "path(\"a\"b\")");
989
        // Unicode path data is passed through byte-for-byte.
990
        let uni = path("M 0 0 \u{2192} \u{1F600}").print_as_css_value();
991
        assert!(uni.contains('\u{1F600}'));
992
    }
993

            
994
    // ---------------------------------------------------------------------
995
    // format_as_rust_code (serializer)
996
    // ---------------------------------------------------------------------
997

            
998
    #[test]
999
    fn format_as_rust_code_known_constructions() {
        assert_eq!(
            CssShape::circle(ShapePoint::new(1.0, 2.0), 3.0).format_as_rust_code(),
            "CssShape::Circle(ShapeCircle { center: ShapePoint::new(1_f32, 2_f32), radius: 3_f32 \
             })"
        );
        assert_eq!(
            CssShape::ellipse(ShapePoint::new(1.0, 2.0), 3.0, 4.0).format_as_rust_code(),
            "CssShape::Ellipse(ShapeEllipse { center: ShapePoint::new(1_f32, 2_f32), radius_x: \
             3_f32, radius_y: 4_f32 })"
        );
        assert_eq!(
            CssShape::inset(1.0, 2.0, 3.0, 4.0).format_as_rust_code(),
            "CssShape::Inset(ShapeInset { inset_top: 1_f32, inset_right: 2_f32, inset_bottom: \
             3_f32, inset_left: 4_f32, border_radius: OptionF32::None })"
        );
        assert!(CssShape::inset_rounded(0.0, 0.0, 0.0, 0.0, 5.0)
            .format_as_rust_code()
            .contains("border_radius: OptionF32::Some(5_f32)"));
        assert_eq!(
            path("M 0 0").format_as_rust_code(),
            "CssShape::Path(ShapePath { data: AzString::from_const_str(\"M 0 0\") })"
        );
    }
    #[test]
    fn format_as_rust_code_is_non_empty_for_every_variant() {
        let shapes = vec![
            CssShape::circle(ShapePoint::zero(), 0.0),
            CssShape::ellipse(ShapePoint::zero(), 0.0, 0.0),
            poly(&[]),
            CssShape::inset(0.0, 0.0, 0.0, 0.0),
            path(""),
        ];
        for s in &shapes {
            let code = s.format_as_rust_code();
            assert!(code.starts_with("CssShape::"), "got {code}");
            assert!(code.ends_with(')'), "got {code}");
            assert!(!code.is_empty());
        }
    }
    #[test]
    fn format_as_rust_code_empty_polygon_emits_empty_vec() {
        assert_eq!(
            poly(&[]).format_as_rust_code(),
            "CssShape::Polygon(ShapePolygon { points: vec![].into() })"
        );
        assert_eq!(
            poly(&[(0.0, 0.0), (1.0, 1.0)]).format_as_rust_code(),
            "CssShape::Polygon(ShapePolygon { points: vec![ShapePoint::new(0_f32, 0_f32), \
             ShapePoint::new(1_f32, 1_f32)].into() })"
        );
    }
    #[test]
    fn format_as_rust_code_emits_uncompilable_tokens_for_nan_and_inf() {
        // Characterization of a real codegen defect: `NaN_f32` / `inf_f32` are
        // not valid Rust literals, so generated code containing a non-finite
        // shape does not compile. See the report.
        let code = CssShape::circle(ShapePoint::new(f32::INFINITY, f32::NEG_INFINITY), f32::NAN)
            .format_as_rust_code();
        assert!(code.contains("NaN_f32"), "got {code}");
        assert!(code.contains("inf_f32"), "got {code}");
        assert!(code.contains("-inf_f32"), "got {code}");
    }
    #[test]
    fn format_as_rust_code_does_not_escape_path_data() {
        // Characterization: quotes and backslashes in path data are emitted raw,
        // producing uncompilable Rust. See the report.
        let code = path("a\"b\\c").format_as_rust_code();
        assert!(code.contains("from_const_str(\"a\"b\\c\")"), "got {code}");
    }
    #[test]
    fn format_as_rust_code_survives_extreme_values() {
        for &v in EDGE_F32 {
            let code = CssShape::inset_rounded(v, v, v, v, v).format_as_rust_code();
            assert!(code.starts_with("CssShape::Inset("), "got {code}");
        }
    }
    // ---------------------------------------------------------------------
    // Round-trip: print_as_css_value -> shape_parser::parse_shape
    // ---------------------------------------------------------------------
    #[test]
    fn roundtrip_circle_ellipse_inset_and_path() {
        for shape in [
            CssShape::circle(ShapePoint::new(100.0, -25.5), 50.0),
            CssShape::circle(ShapePoint::zero(), 0.0),
            CssShape::ellipse(ShapePoint::new(-1.0, 2.0), 3.0, 4.5),
            CssShape::inset(1.0, 2.0, 3.0, 4.0),
            CssShape::inset(-1.0, -2.0, -3.0, -4.0),
            CssShape::inset_rounded(1.0, 2.0, 3.0, 4.0, 5.0),
            path("M 0 0 L 100 0 L 100 100 Z"),
            path(""),
        ] {
            assert_eq!(roundtrip(&shape), shape);
        }
    }
    #[test]
    fn roundtrip_polygon_needs_at_least_three_points() {
        let ok = poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
        assert_eq!(roundtrip(&ok), ok);
        // Printer/parser asymmetry: these print fine but the crate's own parser
        // rejects them, so a shape can survive `print` and die on re-parse.
        let two = poly(&[(0.0, 0.0), (1.0, 1.0)]).print_as_css_value();
        assert!(matches!(
            parse_shape(&two),
            Err(ShapeParseError::InvalidSyntax(_))
        ));
        let empty = poly(&[]).print_as_css_value();
        assert!(matches!(
            parse_shape(&empty),
            Err(ShapeParseError::InvalidSyntax(_))
        ));
    }
    #[test]
    fn roundtrip_preserves_extreme_finite_floats_bit_for_bit() {
        for &v in &[
            f32::MIN,
            f32::MAX,
            f32::MIN_POSITIVE,
            f32::EPSILON,
            f32::from_bits(1), // smallest positive subnormal
            1e-7,
            123_456.79,
        ] {
            let shape = CssShape::circle(ShapePoint::new(v, -v), v);
            match roundtrip(&shape) {
                CssShape::Circle(c) => {
                    assert_eq!(c.radius.to_bits(), v.to_bits(), "radius lost for {v:e}");
                    assert_eq!(c.center.x.to_bits(), v.to_bits(), "x lost for {v:e}");
                    assert_eq!(c.center.y.to_bits(), (-v).to_bits(), "y lost for {v:e}");
                }
                other => panic!("expected Circle, got {other:?}"),
            }
        }
    }
    #[test]
    fn roundtrip_of_non_finite_values_survives_but_is_not_valid_css() {
        // Rust's f32 FromStr happens to accept "inf"/"NaN", so azul's own parser
        // reads back what its printer emitted -- but no browser would.
        match roundtrip(&CssShape::circle(ShapePoint::zero(), f32::INFINITY)) {
            CssShape::Circle(c) => assert!(c.radius.is_infinite() && c.radius > 0.0),
            other => panic!("expected Circle, got {other:?}"),
        }
        match roundtrip(&CssShape::circle(ShapePoint::zero(), f32::NAN)) {
            CssShape::Circle(c) => assert!(c.radius.is_nan()),
            other => panic!("expected Circle, got {other:?}"),
        }
        match roundtrip(&CssShape::inset(
            f32::NEG_INFINITY,
            f32::INFINITY,
            f32::NAN,
            0.0,
        )) {
            CssShape::Inset(i) => {
                assert!(i.inset_top.is_infinite() && i.inset_top < 0.0);
                assert!(i.inset_right.is_infinite() && i.inset_right > 0.0);
                assert!(i.inset_bottom.is_nan());
                assert_eq!(i.inset_left, 0.0);
            }
            other => panic!("expected Inset, got {other:?}"),
        }
    }
    #[test]
    fn roundtrip_path_with_hostile_and_unicode_data() {
        // A ')' inside the data is safe (the parser scans with rfind), and so is
        // a bare quote (the outer quotes are stripped positionally).
        for data in [
            "M 0 0)",
            "M 0 0 \u{2192} \u{1F600}",
            "M\n0\t0",
            "a\"b",
            "\u{0}",
        ] {
            let shape = path(data);
            assert_eq!(
                roundtrip(&shape),
                shape,
                "path data {data:?} did not survive"
            );
        }
    }
    #[test]
    fn roundtrip_huge_polygon() {
        let coords: Vec<(f32, f32)> = (0..2_000).map(|i| (i as f32, -(i as f32))).collect();
        let shape = poly(&coords);
        assert_eq!(roundtrip(&shape), shape);
    }
}