1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
#[allow(clippy::float_cmp)] // exact float equality is the point: the parser propagates values
5
                            // bit-for-bit
6
mod autotest_generated {
7
    use alloc::format;
8

            
9
    use proptest::{prelude::*, proptest};
10

            
11
    use super::*;
12

            
13
    // ---------------------------------------------------------------- helpers
14

            
15
    fn approx(a: f32, b: f32) -> bool {
16
        (a - b).abs() < 1e-4
17
    }
18

            
19
    /// Every point produced by a path, in element order.
20
    fn all_points(path: &SvgPath) -> Vec<SvgPoint> {
21
        let mut out = Vec::new();
22
        for e in path.items.as_ref() {
23
            match e {
24
                SvgPathElement::Line(l) => {
25
                    out.push(l.start);
26
                    out.push(l.end);
27
                }
28
                SvgPathElement::QuadraticCurve(q) => {
29
                    out.push(q.start);
30
                    out.push(q.ctrl);
31
                    out.push(q.end);
32
                }
33
                SvgPathElement::CubicCurve(c) => {
34
                    out.push(c.start);
35
                    out.push(c.ctrl_1);
36
                    out.push(c.ctrl_2);
37
                    out.push(c.end);
38
                }
39
            }
40
        }
41
        out
42
    }
43

            
44
    /// Each element's end must be the next element's start (the parser threads
45
    /// `self.current` through every handler, so this holds bit-for-bit).
46
    fn assert_contiguous(items: &[SvgPathElement], what: &str) {
47
        for w in items.windows(2) {
48
            assert_eq!(
49
                w[0].get_end(),
50
                w[1].get_start(),
51
                "{what}: element chain is not contiguous"
52
            );
53
        }
54
    }
55

            
56
    // ======================================================= char_at (numeric)
57

            
58
    #[test]
59
    fn char_at_zero_and_ascii() {
60
        // "M0 0" is ['M', '0', ' ', '0'] -- the space is at index 2, not 3.
61
        assert_eq!(char_at(b"M0 0", 0), 'M');
62
        assert_eq!(char_at(b"M0 0", 2), ' ');
63
        assert_eq!(char_at(b"M0 0", 3), '0');
64
    }
65

            
66
    #[test]
67
    fn char_at_empty_input_is_replacement() {
68
        assert_eq!(char_at(b"", 0), char::REPLACEMENT_CHARACTER);
69
    }
70

            
71
    #[test]
72
    fn char_at_past_end_is_replacement_not_panic() {
73
        assert_eq!(char_at(b"abc", 3), char::REPLACEMENT_CHARACTER);
74
        assert_eq!(char_at(b"abc", 4), char::REPLACEMENT_CHARACTER);
75
    }
76

            
77
    /// `pos = usize::MAX` must be a `get(pos..)` miss, not an arithmetic panic.
78
    #[test]
79
    fn char_at_usize_max_is_replacement() {
80
        assert_eq!(char_at(b"abc", usize::MAX), char::REPLACEMENT_CHARACTER);
81
        assert_eq!(char_at(b"", usize::MAX), char::REPLACEMENT_CHARACTER);
82
    }
83

            
84
    /// The whole point of `char_at`: report the real char, not one UTF-8 byte.
85
    #[test]
86
    fn char_at_decodes_multibyte_not_latin1() {
87
        assert_eq!(char_at("ü".as_bytes(), 0), 'ü');
88
        assert_eq!(char_at("€".as_bytes(), 0), '€');
89
        assert_eq!(char_at("\u{1F600}".as_bytes(), 0), '\u{1F600}');
90
    }
91

            
92
    /// A corrupt (mid-codepoint) offset falls back rather than panicking.
93
    #[test]
94
    fn char_at_mid_codepoint_offset_is_replacement() {
95
        let bytes = "😀".as_bytes(); // 4 bytes
96
        for pos in 1..bytes.len() {
97
            assert_eq!(
98
                char_at(bytes, pos),
99
                char::REPLACEMENT_CHARACTER,
100
                "mid-codepoint offset {pos} must not panic"
101
            );
102
        }
103
    }
104

            
105
    /// Trailing garbage after a valid char makes the *whole rest* invalid UTF-8,
106
    /// so even a valid leading char decodes to the replacement char. Pinned as
107
    /// deterministic (never a panic).
108
    #[test]
109
    fn char_at_invalid_utf8_tail_is_replacement() {
110
        assert_eq!(char_at(&[b'A', 0xFF], 0), char::REPLACEMENT_CHARACTER);
111
        assert_eq!(char_at(&[0xFF], 0), char::REPLACEMENT_CHARACTER);
112
        // ...but a clean tail after the char still decodes.
113
        assert_eq!(char_at(b"AB", 0), 'A');
114
    }
115

            
116
    // ============================================ SvgPathParseError (serializer)
117

            
118
    #[test]
119
    fn error_display_is_non_empty_for_every_variant() {
120
        let variants = [
121
            SvgPathParseError::EmptyPath,
122
            SvgPathParseError::UnexpectedChar { pos: 0, ch: 'x' },
123
            SvgPathParseError::ExpectedNumber { pos: 0 },
124
            SvgPathParseError::InvalidArcFlag { pos: 0 },
125
        ];
126
        for v in variants {
127
            let s = format!("{v}");
128
            assert!(!s.is_empty(), "Display for {v:?} must not be empty");
129
            assert!(!format!("{v:?}").is_empty(), "Debug must not be empty");
130
        }
131
    }
132

            
133
    #[test]
134
    fn error_display_edge_values_do_not_panic() {
135
        let s = format!(
136
            "{}",
137
            SvgPathParseError::UnexpectedChar {
138
                pos: usize::MAX,
139
                ch: char::REPLACEMENT_CHARACTER,
140
            }
141
        );
142
        assert!(s.contains(&format!("{}", usize::MAX)));
143
        assert!(s.contains(char::REPLACEMENT_CHARACTER));
144

            
145
        // NUL, an emoji and a combining mark all format without panicking.
146
        for ch in ['\0', '\u{1F600}', '\u{0301}'] {
147
            let s = format!("{}", SvgPathParseError::UnexpectedChar { pos: 0, ch });
148
            assert!(!s.is_empty());
149
        }
150
        assert!(!format!("{}", SvgPathParseError::ExpectedNumber { pos: usize::MAX }).is_empty());
151
        assert!(!format!("{}", SvgPathParseError::InvalidArcFlag { pos: usize::MAX }).is_empty());
152
    }
153

            
154
    // ================================================= PathParser::new / getters
155

            
156
    #[test]
157
    fn parser_new_invariants_hold() {
158
        let p = PathParser::new(b"M0 0");
159
        assert_eq!(p.pos, 0);
160
        assert_eq!(p.current, SvgPoint { x: 0.0, y: 0.0 });
161
        assert_eq!(p.subpath_start, SvgPoint { x: 0.0, y: 0.0 });
162
        assert!(p.last_control.is_none());
163
        assert_eq!(p.last_command, 0);
164
        assert_eq!(p.input.len(), 4);
165
    }
166

            
167
    #[test]
168
    fn parser_new_on_empty_input_does_not_panic() {
169
        let p = PathParser::new(b"");
170
        assert!(p.at_end(), "empty input is immediately at_end");
171
        assert_eq!(p.peek(), None);
172
        assert!(!p.has_number());
173
    }
174

            
175
    #[test]
176
    fn at_end_and_peek_agree_across_the_whole_input() {
177
        let mut p = PathParser::new(b"ab");
178
        assert!(!p.at_end());
179
        assert_eq!(p.peek(), Some(b'a'));
180
        p.pos = 1;
181
        assert!(!p.at_end());
182
        assert_eq!(p.peek(), Some(b'b'));
183
        p.pos = 2;
184
        assert!(p.at_end());
185
        assert_eq!(p.peek(), None);
186
    }
187

            
188
    /// A cursor pushed far past the end must report `at_end` / `None`, never panic.
189
    #[test]
190
    fn peek_and_at_end_at_extreme_positions() {
191
        let mut p = PathParser::new(b"abc");
192
        p.pos = usize::MAX;
193
        assert!(p.at_end());
194
        assert_eq!(p.peek(), None);
195
        assert!(!p.has_number());
196
    }
197

            
198
    // ============================================================ skip_* (other)
199

            
200
    #[test]
201
    fn skip_whitespace_and_commas_consumes_all_separators() {
202
        let mut p = PathParser::new(b" \t\r\n,,, \tX");
203
        p.skip_whitespace_and_commas();
204
        assert_eq!(p.peek(), Some(b'X'));
205
    }
206

            
207
    /// `skip_whitespace` must *not* eat commas (they are only argument separators).
208
    #[test]
209
    fn skip_whitespace_stops_at_comma() {
210
        let mut p = PathParser::new(b"  ,1");
211
        p.skip_whitespace();
212
        assert_eq!(p.peek(), Some(b','));
213
        assert_eq!(p.pos, 2);
214
    }
215

            
216
    #[test]
217
    fn skip_on_empty_and_all_separator_input_terminates() {
218
        let mut p = PathParser::new(b"");
219
        p.skip_whitespace();
220
        p.skip_whitespace_and_commas();
221
        assert!(p.at_end());
222

            
223
        let all_ws = " \t\r\n,".repeat(20_000);
224
        let mut p = PathParser::new(all_ws.as_bytes());
225
        p.skip_whitespace_and_commas();
226
        assert!(
227
            p.at_end(),
228
            "a huge run of separators must be fully consumed"
229
        );
230
        assert_eq!(p.pos, all_ws.len());
231
    }
232

            
233
    /// Non-separator input leaves the cursor exactly where it was.
234
    #[test]
235
    fn skip_is_a_no_op_on_non_separator() {
236
        let mut p = PathParser::new("😀".as_bytes());
237
        p.skip_whitespace_and_commas();
238
        assert_eq!(p.pos, 0);
239
        // Form feed / vertical tab are NOT SVG wsp; the parser must leave them.
240
        let mut p = PathParser::new(b"\x0c\x0b1");
241
        p.skip_whitespace();
242
        assert_eq!(p.pos, 0);
243
    }
244

            
245
    // ======================================================= has_number (predicate)
246

            
247
    #[test]
248
    fn has_number_true_for_number_starters() {
249
        for s in ["0", "9", "+", "-", ".", "5.5", "-.5"] {
250
            assert!(
251
                PathParser::new(s.as_bytes()).has_number(),
252
                "{s:?} should look like a number start"
253
            );
254
        }
255
    }
256

            
257
    #[test]
258
    fn has_number_false_for_non_number_starters() {
259
        // Note 'e'/'E' only appear *inside* a number, never at its start.
260
        for s in ["", " ", ",", "M", "z", "e", "E", "😀", "\u{0301}"] {
261
            assert!(
262
                !PathParser::new(s.as_bytes()).has_number(),
263
                "{s:?} should not look like a number start"
264
            );
265
        }
266
    }
267

            
268
    // ========================================================= parse_number (parser)
269

            
270
    fn num(s: &str) -> Result<f32, SvgPathParseError> {
271
        PathParser::new(s.as_bytes()).parse_number()
272
    }
273

            
274
    #[test]
275
    fn parse_number_valid_minimal() {
276
        assert_eq!(num("0").unwrap(), 0.0);
277
        assert_eq!(num("5").unwrap(), 5.0);
278
        assert_eq!(num("+5").unwrap(), 5.0);
279
        assert_eq!(num("-5").unwrap(), -5.0);
280
        assert!(approx(num("12.34").unwrap(), 12.34));
281
        assert!(approx(num(".5").unwrap(), 0.5));
282
        assert_eq!(num("5.").unwrap(), 5.0);
283
        assert!(approx(num("1e2").unwrap(), 100.0));
284
        assert!(approx(num("1E-2").unwrap(), 0.01));
285
        assert!(
286
            approx(num("  ,, 7").unwrap(), 7.0),
287
            "leading separators skipped"
288
        );
289
    }
290

            
291
    #[test]
292
    fn parse_number_empty_input_is_err() {
293
        assert_eq!(num(""), Err(SvgPathParseError::ExpectedNumber { pos: 0 }));
294
    }
295

            
296
    /// Whitespace-only input reports the position *after* the skipped separators.
297
    #[test]
298
    fn parse_number_whitespace_only_is_err() {
299
        assert_eq!(
300
            num("   "),
301
            Err(SvgPathParseError::ExpectedNumber { pos: 3 })
302
        );
303
        assert_eq!(
304
            num("\t\n"),
305
            Err(SvgPathParseError::ExpectedNumber { pos: 2 })
306
        );
307
        assert_eq!(
308
            num(" , "),
309
            Err(SvgPathParseError::ExpectedNumber { pos: 3 })
310
        );
311
    }
312

            
313
    #[test]
314
    fn parse_number_garbage_is_err_never_panics() {
315
        for s in [
316
            "abc", "@", "#$%", "-", "+", ".", "-.", "+.", "e5", "NaN", "inf", "-inf",
317
        ] {
318
            assert!(
319
                matches!(num(s), Err(SvgPathParseError::ExpectedNumber { .. })),
320
                "{s:?} must be rejected, got {:?}",
321
                num(s)
322
            );
323
        }
324
    }
325

            
326
    /// A dangling exponent is consumed by the tokenizer but rejected by `f32::from_str`.
327
    #[test]
328
    fn parse_number_dangling_exponent_is_err() {
329
        for s in ["1e", "1E", "1e+", "1e-", "1.5e"] {
330
            assert!(
331
                matches!(num(s), Err(SvgPathParseError::ExpectedNumber { pos: 0 })),
332
                "{s:?} must be rejected"
333
            );
334
        }
335
    }
336

            
337
    #[test]
338
    fn parse_number_unicode_does_not_panic() {
339
        for s in ["😀", "\u{0301}", "ü", "€1", "1"] {
340
            assert!(num(s).is_err(), "{s:?} must be rejected");
341
        }
342
        // A number immediately followed by a multibyte char stops at the boundary.
343
        let mut p = PathParser::new("1😀".as_bytes());
344
        assert_eq!(p.parse_number().unwrap(), 1.0);
345
        assert_eq!(p.pos, 1);
346
    }
347

            
348
    /// Boundary numerics: overflow saturates to +/-inf, underflow flushes to zero,
349
    /// and `-0` keeps its sign. None of these panic.
350
    #[test]
351
    fn parse_number_boundary_values_saturate() {
352
        assert!(
353
            num("-0").unwrap().is_sign_negative(),
354
            "-0 keeps its sign bit"
355
        );
356
        assert_eq!(num("-0").unwrap(), -0.0);
357

            
358
        assert!(num("1e999").unwrap().is_infinite());
359
        assert!(num("1e999").unwrap().is_sign_positive());
360
        assert!(num("-1e999").unwrap().is_infinite());
361
        assert!(num("-1e999").unwrap().is_sign_negative());
362

            
363
        assert_eq!(num("1e-999").unwrap(), 0.0, "underflow flushes to zero");
364

            
365
        // i64::MAX / f32 extremes round to a finite f32.
366
        assert!(num("9223372036854775807").unwrap().is_finite());
367
        assert!(num("340282350000000000000000000000000000000")
368
            .unwrap()
369
            .is_finite());
370
        // Just past f32::MAX -> +inf, not a panic.
371
        assert!(num("1e39").unwrap().is_infinite());
372
    }
373

            
374
    /// A 20k-digit literal must not hang or panic; it saturates to +inf.
375
    #[test]
376
    fn parse_number_extremely_long_input_terminates() {
377
        let huge = "9".repeat(20_000);
378
        assert!(num(&huge).unwrap().is_infinite());
379

            
380
        let long_frac = format!("0.{}", "0".repeat(20_000));
381
        assert_eq!(num(&long_frac).unwrap(), 0.0);
382

            
383
        let long_zeros = format!("{}1", "0".repeat(20_000));
384
        assert_eq!(num(&long_zeros).unwrap(), 1.0);
385
    }
386

            
387
    /// Trailing junk is left on the cursor rather than swallowed: `"1.2.3"` yields
388
    /// `1.2` and stops at the second dot (SVG's own "1.5.5" == two numbers rule).
389
    #[test]
390
    fn parse_number_stops_at_trailing_junk() {
391
        let mut p = PathParser::new(b"1.2.3");
392
        assert!(approx(p.parse_number().unwrap(), 1.2));
393
        assert_eq!(p.pos, 3, "second '.' must not be consumed");
394

            
395
        let mut p = PathParser::new(b"5;garbage");
396
        assert_eq!(p.parse_number().unwrap(), 5.0);
397
        assert_eq!(p.peek(), Some(b';'));
398
    }
399

            
400
    /// The cursor is never advanced past the end of the input, whatever happens.
401
    #[test]
402
    fn parse_number_never_overruns_the_buffer() {
403
        for s in ["", "-", ".", "1e", "1e+", "1.", "+.e", "1e-", "999"] {
404
            let mut p = PathParser::new(s.as_bytes());
405
            let _ = p.parse_number();
406
            assert!(p.pos <= s.len(), "{s:?}: pos {} > len {}", p.pos, s.len());
407
        }
408
    }
409

            
410
    // =========================================================== parse_flag (parser)
411

            
412
    fn flag(s: &str) -> Result<bool, SvgPathParseError> {
413
        PathParser::new(s.as_bytes()).parse_flag()
414
    }
415

            
416
    #[test]
417
    fn parse_flag_valid_minimal() {
418
        assert!(!flag("0").unwrap());
419
        assert!(flag("1").unwrap());
420
        assert!(flag("  , 1").unwrap(), "separators are skipped first");
421
    }
422

            
423
    /// A flag is exactly one byte: "11" is two flags, not the number eleven.
424
    #[test]
425
    fn parse_flag_consumes_exactly_one_byte() {
426
        let mut p = PathParser::new(b"10");
427
        assert!(p.parse_flag().unwrap());
428
        assert_eq!(p.pos, 1);
429
        assert!(!p.parse_flag().unwrap());
430
        assert_eq!(p.pos, 2);
431
    }
432

            
433
    #[test]
434
    fn parse_flag_empty_and_whitespace_only_are_err() {
435
        assert_eq!(flag(""), Err(SvgPathParseError::InvalidArcFlag { pos: 0 }));
436
        assert_eq!(
437
            flag("   "),
438
            Err(SvgPathParseError::InvalidArcFlag { pos: 3 })
439
        );
440
    }
441

            
442
    /// Any byte other than `0`/`1` is rejected and the cursor stays put.
443
    #[test]
444
    fn parse_flag_garbage_is_err_and_does_not_advance() {
445
        for s in ["2", "9", "-1", "+1", "x", ".", "😀", "0.5"] {
446
            let mut p = PathParser::new(s.as_bytes());
447
            let before = p.pos;
448
            match p.parse_flag() {
449
                Err(SvgPathParseError::InvalidArcFlag { pos }) => {
450
                    assert_eq!(pos, p.pos, "{s:?}: reported pos must be the cursor");
451
                    assert_eq!(p.pos, before, "{s:?}: rejected flag must not advance");
452
                }
453
                // "0.5" legitimately parses its leading '0' as the flag.
454
                Ok(v) => assert!(s == "0.5" && !v, "{s:?} unexpectedly parsed as {v}"),
455
                other => panic!("{s:?}: unexpected {other:?}"),
456
            }
457
        }
458
    }
459

            
460
    /// A 100k-byte separator run followed by no flag terminates with an error.
461
    #[test]
462
    fn parse_flag_extremely_long_separator_run_terminates() {
463
        let s = " ".repeat(100_000);
464
        assert_eq!(
465
            flag(&s),
466
            Err(SvgPathParseError::InvalidArcFlag { pos: 100_000 })
467
        );
468
    }
469

            
470
    // ================================================ parse_coordinate_pair (parser)
471

            
472
    fn pair(s: &str) -> Result<(f32, f32), SvgPathParseError> {
473
        PathParser::new(s.as_bytes()).parse_coordinate_pair()
474
    }
475

            
476
    #[test]
477
    fn parse_coordinate_pair_valid_minimal() {
478
        assert_eq!(pair("1 2").unwrap(), (1.0, 2.0));
479
        assert_eq!(pair("1,2").unwrap(), (1.0, 2.0));
480
        assert_eq!(pair(" 1 , 2 ").unwrap(), (1.0, 2.0));
481
        // SVG allows a sign to act as the separator.
482
        assert_eq!(pair("-1-2").unwrap(), (-1.0, -2.0));
483
    }
484

            
485
    /// SVG's notorious "1.5.5" == (1.5, 0.5) tokenization.
486
    #[test]
487
    fn parse_coordinate_pair_splits_on_second_dot() {
488
        let (x, y) = pair("1.5.5").unwrap();
489
        assert!(approx(x, 1.5) && approx(y, 0.5), "got ({x}, {y})");
490
    }
491

            
492
    #[test]
493
    fn parse_coordinate_pair_empty_and_partial_are_err() {
494
        assert!(pair("").is_err());
495
        assert!(pair("   ").is_err());
496
        assert!(pair("1").is_err(), "a lone x with no y must be rejected");
497
        assert!(pair("1 ").is_err());
498
        assert!(pair("1,").is_err());
499
    }
500

            
501
    #[test]
502
    fn parse_coordinate_pair_garbage_and_unicode_are_err() {
503
        for s in ["abc", "1 abc", "😀 1", "1 😀", ";;", "1;2"] {
504
            assert!(pair(s).is_err(), "{s:?} must be rejected");
505
        }
506
    }
507

            
508
    #[test]
509
    fn parse_coordinate_pair_boundary_values() {
510
        let (x, y) = pair("1e999 -1e999").unwrap();
511
        assert!(x.is_infinite() && x.is_sign_positive());
512
        assert!(y.is_infinite() && y.is_sign_negative());
513

            
514
        let (x, y) = pair("-0 0").unwrap();
515
        assert!(x.is_sign_negative() && y.is_sign_positive());
516
    }
517

            
518
    #[test]
519
    fn parse_coordinate_pair_extremely_long_input_terminates() {
520
        let s = format!("{} {}", "9".repeat(10_000), "9".repeat(10_000));
521
        let (x, y) = pair(&s).unwrap();
522
        assert!(x.is_infinite() && y.is_infinite());
523
    }
524

            
525
    // ======================================================= make_absolute (numeric)
526

            
527
    #[test]
528
    fn make_absolute_zero_and_absolute_mode_is_identity() {
529
        let mut p = PathParser::new(b"");
530
        p.current = SvgPoint { x: 7.0, y: -3.0 };
531
        // Absolute: current is ignored entirely.
532
        assert_eq!(
533
            p.make_absolute(0.0, 0.0, false),
534
            SvgPoint { x: 0.0, y: 0.0 }
535
        );
536
        assert_eq!(
537
            p.make_absolute(1.0, 2.0, false),
538
            SvgPoint { x: 1.0, y: 2.0 }
539
        );
540
        // Relative: offsets from current.
541
        assert_eq!(
542
            p.make_absolute(0.0, 0.0, true),
543
            SvgPoint { x: 7.0, y: -3.0 }
544
        );
545
        assert_eq!(
546
            p.make_absolute(-7.0, 3.0, true),
547
            SvgPoint { x: 0.0, y: 0.0 }
548
        );
549
    }
550

            
551
    #[test]
552
    fn make_absolute_negative_inputs() {
553
        let mut p = PathParser::new(b"");
554
        p.current = SvgPoint { x: -10.0, y: -10.0 };
555
        assert_eq!(
556
            p.make_absolute(-5.0, -5.0, true),
557
            SvgPoint { x: -15.0, y: -15.0 }
558
        );
559
        assert_eq!(
560
            p.make_absolute(-5.0, -5.0, false),
561
            SvgPoint { x: -5.0, y: -5.0 }
562
        );
563
    }
564

            
565
    /// f32 addition saturates to infinity; it never wraps or debug-panics.
566
    #[test]
567
    fn make_absolute_overflow_saturates_to_infinity() {
568
        let mut p = PathParser::new(b"");
569
        p.current = SvgPoint {
570
            x: f32::MAX,
571
            y: f32::MIN,
572
        };
573
        let r = p.make_absolute(f32::MAX, f32::MIN, true);
574
        assert!(r.x.is_infinite() && r.x.is_sign_positive());
575
        assert!(r.y.is_infinite() && r.y.is_sign_negative());
576
    }
577

            
578
    #[test]
579
    fn make_absolute_nan_and_inf_are_defined_not_panics() {
580
        let mut p = PathParser::new(b"");
581
        p.current = SvgPoint {
582
            x: f32::INFINITY,
583
            y: 0.0,
584
        };
585
        // inf + (-inf) is NaN by IEEE-754 -- defined, not a panic.
586
        let r = p.make_absolute(f32::NEG_INFINITY, f32::NAN, true);
587
        assert!(r.x.is_nan(), "inf + -inf must be NaN");
588
        assert!(r.y.is_nan());
589

            
590
        // Absolute mode passes NaN straight through.
591
        let r = p.make_absolute(f32::NAN, f32::INFINITY, false);
592
        assert!(r.x.is_nan());
593
        assert!(r.y.is_infinite());
594
    }
595

            
596
    // ============================================================ handle_* (other)
597

            
598
    /// Drive one handler over `input` starting from `current`, returning the
599
    /// pushed elements plus the parser's post-state.
600
    fn run_handler<F>(
601
        input: &str,
602
        current: SvgPoint,
603
        last_command: u8,
604
        last_control: Option<SvgPoint>,
605
        f: F,
606
    ) -> (Result<(), SvgPathParseError>, Vec<SvgPathElement>, SvgPoint)
607
    where
608
        F: FnOnce(&mut PathParser<'_>, &mut Vec<SvgPathElement>) -> Result<(), SvgPathParseError>,
609
    {
610
        let mut p = PathParser::new(input.as_bytes());
611
        p.current = current;
612
        p.last_command = last_command;
613
        p.last_control = last_control;
614
        let mut els = Vec::new();
615
        let r = f(&mut p, &mut els);
616
        (r, els, p.current)
617
    }
618

            
619
    const ORIGIN: SvgPoint = SvgPoint { x: 0.0, y: 0.0 };
620

            
621
    #[test]
622
    fn handle_line_to_absolute_and_relative() {
623
        let start = SvgPoint { x: 10.0, y: 10.0 };
624
        let (r, els, cur) =
625
            run_handler("5 5", start, b'L', None, |p, e| p.handle_line_to(false, e));
626
        assert!(r.is_ok());
627
        assert_eq!(els.len(), 1);
628
        assert_eq!(els[0].get_start(), start);
629
        assert_eq!(els[0].get_end(), SvgPoint { x: 5.0, y: 5.0 });
630
        assert_eq!(cur, SvgPoint { x: 5.0, y: 5.0 });
631

            
632
        let (r, els, cur) = run_handler("5 5", start, b'l', None, |p, e| p.handle_line_to(true, e));
633
        assert!(r.is_ok());
634
        assert_eq!(els[0].get_end(), SvgPoint { x: 15.0, y: 15.0 });
635
        assert_eq!(cur, SvgPoint { x: 15.0, y: 15.0 });
636
    }
637

            
638
    /// H keeps y, V keeps x -- including when the incoming coordinate is infinite.
639
    #[test]
640
    fn handle_horizontal_and_vertical_preserve_the_other_axis() {
641
        let start = SvgPoint { x: 3.0, y: 4.0 };
642
        let (_, els, _) = run_handler("9", start, b'H', None, |p, e| {
643
            p.handle_horizontal_to(false, e)
644
        });
645
        assert_eq!(els[0].get_end(), SvgPoint { x: 9.0, y: 4.0 });
646

            
647
        let (_, els, _) = run_handler("9", start, b'V', None, |p, e| {
648
            p.handle_vertical_to(false, e)
649
        });
650
        assert_eq!(els[0].get_end(), SvgPoint { x: 3.0, y: 9.0 });
651

            
652
        let (_, els, _) = run_handler("1e999", start, b'h', None, |p, e| {
653
            p.handle_horizontal_to(true, e)
654
        });
655
        let end = els[0].get_end();
656
        assert!(end.x.is_infinite(), "relative H by +inf saturates");
657
        assert_eq!(end.y, 4.0, "y must be untouched");
658
    }
659

            
660
    #[test]
661
    fn handlers_reject_empty_and_garbage_input_without_panicking() {
662
        for input in ["", "   ", "abc", "😀", ";", "1"] {
663
            // Each handler needs >= 1 number; "1" is enough only for H/V.
664
            let (r, _, _) = run_handler(input, ORIGIN, 0, None, |p, e| p.handle_line_to(false, e));
665
            assert!(r.is_err(), "line_to({input:?}) must be Err");
666

            
667
            let (r, _, _) = run_handler(input, ORIGIN, 0, None, |p, e| p.handle_cubic_to(false, e));
668
            assert!(r.is_err(), "cubic_to({input:?}) must be Err");
669

            
670
            let (r, _, _) = run_handler(input, ORIGIN, 0, None, |p, e| {
671
                p.handle_quadratic_to(false, e)
672
            });
673
            assert!(r.is_err(), "quadratic_to({input:?}) must be Err");
674

            
675
            let (r, _, _) = run_handler(input, ORIGIN, 0, None, |p, e| p.handle_arc_to(false, e));
676
            assert!(r.is_err(), "arc_to({input:?}) must be Err");
677

            
678
            if input != "1" {
679
                let (r, _, _) = run_handler(input, ORIGIN, 0, None, |p, e| {
680
                    p.handle_horizontal_to(false, e)
681
                });
682
                assert!(r.is_err(), "horizontal_to({input:?}) must be Err");
683
                let (r, _, _) = run_handler(input, ORIGIN, 0, None, |p, e| {
684
                    p.handle_vertical_to(false, e)
685
                });
686
                assert!(r.is_err(), "vertical_to({input:?}) must be Err");
687
            }
688
        }
689
    }
690

            
691
    #[test]
692
    fn handle_cubic_to_records_second_control_point() {
693
        let (r, els, _) = run_handler("1 1 2 2 3 3", ORIGIN, b'C', None, |p, e| {
694
            p.handle_cubic_to(false, e)
695
        });
696
        assert!(r.is_ok());
697
        match els[0] {
698
            SvgPathElement::CubicCurve(c) => {
699
                assert_eq!(c.start, ORIGIN);
700
                assert_eq!(c.ctrl_1, SvgPoint { x: 1.0, y: 1.0 });
701
                assert_eq!(c.ctrl_2, SvgPoint { x: 2.0, y: 2.0 });
702
                assert_eq!(c.end, SvgPoint { x: 3.0, y: 3.0 });
703
            }
704
            other => panic!("expected CubicCurve, got {other:?}"),
705
        }
706
    }
707

            
708
    /// S reflects the previous control point only when the previous command was
709
    /// C or S; otherwise ctrl_1 collapses onto the current point.
710
    #[test]
711
    fn handle_smooth_cubic_reflects_only_after_c_or_s() {
712
        let cur = SvgPoint { x: 10.0, y: 10.0 };
713
        let lc = Some(SvgPoint { x: 8.0, y: 6.0 });
714

            
715
        let (_, els, _) = run_handler("1 1 2 2", cur, b'C', lc, |p, e| {
716
            p.handle_smooth_cubic_to(false, e)
717
        });
718
        match els[0] {
719
            // reflection of (8,6) about (10,10) == (12,14)
720
            SvgPathElement::CubicCurve(c) => assert_eq!(c.ctrl_1, SvgPoint { x: 12.0, y: 14.0 }),
721
            other => panic!("expected CubicCurve, got {other:?}"),
722
        }
723

            
724
        // Previous command was L: no reflection, ctrl_1 == current.
725
        let (_, els, _) = run_handler("1 1 2 2", cur, b'L', lc, |p, e| {
726
            p.handle_smooth_cubic_to(false, e)
727
        });
728
        match els[0] {
729
            SvgPathElement::CubicCurve(c) => assert_eq!(c.ctrl_1, cur),
730
            other => panic!("expected CubicCurve, got {other:?}"),
731
        }
732

            
733
        // No stored control point at all: no reflection either.
734
        let (_, els, _) = run_handler("1 1 2 2", cur, b'S', None, |p, e| {
735
            p.handle_smooth_cubic_to(false, e)
736
        });
737
        match els[0] {
738
            SvgPathElement::CubicCurve(c) => assert_eq!(c.ctrl_1, cur),
739
            other => panic!("expected CubicCurve, got {other:?}"),
740
        }
741
    }
742

            
743
    #[test]
744
    fn handle_smooth_quadratic_reflects_only_after_q_or_t() {
745
        let cur = SvgPoint { x: 10.0, y: 10.0 };
746
        let lc = Some(SvgPoint { x: 8.0, y: 6.0 });
747

            
748
        let (_, els, _) = run_handler("2 2", cur, b'Q', lc, |p, e| {
749
            p.handle_smooth_quadratic_to(false, e)
750
        });
751
        match els[0] {
752
            SvgPathElement::QuadraticCurve(q) => assert_eq!(q.ctrl, SvgPoint { x: 12.0, y: 14.0 }),
753
            other => panic!("expected QuadraticCurve, got {other:?}"),
754
        }
755

            
756
        let (_, els, _) = run_handler("2 2", cur, b'M', lc, |p, e| {
757
            p.handle_smooth_quadratic_to(false, e)
758
        });
759
        match els[0] {
760
            SvgPathElement::QuadraticCurve(q) => assert_eq!(q.ctrl, cur),
761
            other => panic!("expected QuadraticCurve, got {other:?}"),
762
        }
763
    }
764

            
765
    /// Arc radii are absolute-valued, so a negative radius still draws an arc.
766
    #[test]
767
    fn handle_arc_to_takes_abs_of_radii() {
768
        let (r, els, cur) = run_handler("-5 -5 0 0 1 10 0", ORIGIN, b'A', None, |p, e| {
769
            p.handle_arc_to(false, e)
770
        });
771
        assert!(r.is_ok());
772
        assert!(!els.is_empty(), "negative radii must still produce an arc");
773
        assert!(
774
            els.iter()
775
                .all(|e| matches!(e, SvgPathElement::CubicCurve(_))),
776
            "abs() of the radii keeps this a real arc, not a line fallback"
777
        );
778
        assert_eq!(cur, SvgPoint { x: 10.0, y: 0.0 });
779
    }
780

            
781
    /// A zero radius degenerates to a straight line (SVG spec F.6.6).
782
    #[test]
783
    fn handle_arc_to_zero_radius_degenerates_to_line() {
784
        let (r, els, _) = run_handler("0 0 0 0 1 10 0", ORIGIN, b'A', None, |p, e| {
785
            p.handle_arc_to(false, e)
786
        });
787
        assert!(r.is_ok());
788
        assert_eq!(els.len(), 1);
789
        assert!(matches!(els[0], SvgPathElement::Line(_)));
790
        assert_eq!(els[0].get_end(), SvgPoint { x: 10.0, y: 0.0 });
791
    }
792

            
793
    #[test]
794
    fn handle_arc_to_rejects_out_of_range_flags() {
795
        for input in [
796
            "5 5 0 2 1 10 0",
797
            "5 5 0 1 2 10 0",
798
            "5 5 0 x 1 10 0",
799
            "5 5 0",
800
        ] {
801
            let (r, _, _) =
802
                run_handler(input, ORIGIN, b'A', None, |p, e| p.handle_arc_to(false, e));
803
            assert!(r.is_err(), "arc flags in {input:?} must be rejected");
804
        }
805
        let (r, _, _) = run_handler("5 5 0 2 1 10 0", ORIGIN, b'A', None, |p, e| {
806
            p.handle_arc_to(false, e)
807
        });
808
        assert!(matches!(r, Err(SvgPathParseError::InvalidArcFlag { .. })));
809
    }
810

            
811
    /// Infinite radii feed NaN through the endpoint parameterization. The
812
    /// segment count must still be bounded (no runaway loop) and no panic.
813
    #[test]
814
    fn handle_arc_to_infinite_radii_is_bounded() {
815
        let (r, els, _) = run_handler("1e999 1e999 0 0 1 10 10", ORIGIN, b'A', None, |p, e| {
816
            p.handle_arc_to(false, e)
817
        });
818
        assert!(r.is_ok());
819
        assert!(
820
            els.len() <= 4,
821
            "a single arc must never expand past 4 cubics, got {}",
822
            els.len()
823
        );
824
    }
825

            
826
    // ===================================================== parse_svg_path_d (parser)
827

            
828
    #[test]
829
    fn parse_path_empty_and_whitespace_only_is_empty_path_err() {
830
        for s in ["", "   ", "\t\n", "\r\n  \t"] {
831
            assert_eq!(
832
                parse_svg_path_d(s),
833
                Err(SvgPathParseError::EmptyPath),
834
                "{s:?} must be EmptyPath"
835
            );
836
        }
837
    }
838

            
839
    #[test]
840
    fn parse_path_valid_minimal() {
841
        let mp = parse_svg_path_d("M10 20 L30 40").unwrap();
842
        let rings = mp.rings.as_ref();
843
        assert_eq!(rings.len(), 1);
844
        let items = rings[0].items.as_ref();
845
        assert_eq!(items.len(), 1);
846
        assert_eq!(items[0].get_start(), SvgPoint { x: 10.0, y: 20.0 });
847
        assert_eq!(items[0].get_end(), SvgPoint { x: 30.0, y: 40.0 });
848
    }
849

            
850
    /// Relative commands accumulate from the current point.
851
    #[test]
852
    fn parse_path_relative_accumulates() {
853
        let mp = parse_svg_path_d("m10 20 l30 40").unwrap();
854
        let items_owner = &mp.rings.as_ref()[0];
855
        let items = items_owner.items.as_ref();
856
        assert_eq!(items[0].get_start(), SvgPoint { x: 10.0, y: 20.0 });
857
        assert_eq!(items[0].get_end(), SvgPoint { x: 40.0, y: 60.0 });
858
    }
859

            
860
    /// A moveto with no drawing commands produces no geometry (but is not an error).
861
    #[test]
862
    fn parse_path_moveto_only_yields_no_rings() {
863
        let mp = parse_svg_path_d("M10 10").unwrap();
864
        assert_eq!(mp.rings.as_ref().len(), 0);
865
    }
866

            
867
    /// Extra coordinate pairs after an M are implicit linetos (SVG spec).
868
    #[test]
869
    fn parse_path_implicit_lineto_after_moveto() {
870
        let mp = parse_svg_path_d("M0 0 10 0 20 0").unwrap();
871
        let items_owner = &mp.rings.as_ref()[0];
872
        let items = items_owner.items.as_ref();
873
        assert_eq!(items.len(), 2, "two implicit L commands");
874
        assert_eq!(items[0].get_end(), SvgPoint { x: 10.0, y: 0.0 });
875
        assert_eq!(items[1].get_end(), SvgPoint { x: 20.0, y: 0.0 });
876
    }
877

            
878
    #[test]
879
    fn parse_path_garbage_is_err_never_panics() {
880
        for s in [
881
            "@#$", "hello", "?", "-", ".", ",", "0 0", "5", ";;;", "\u{0}",
882
        ] {
883
            assert!(parse_svg_path_d(s).is_err(), "{s:?} must be rejected");
884
        }
885
    }
886

            
887
    /// A leading non-command byte is reported as a real Unicode char at byte 0.
888
    #[test]
889
    fn parse_path_unicode_does_not_panic() {
890
        assert_eq!(
891
            parse_svg_path_d("\u{1F600}"),
892
            Err(SvgPathParseError::UnexpectedChar {
893
                pos: 0,
894
                ch: '\u{1F600}',
895
            })
896
        );
897
        assert_eq!(
898
            parse_svg_path_d("\u{0301}M0 0"),
899
            Err(SvgPathParseError::UnexpectedChar {
900
                pos: 0,
901
                ch: '\u{0301}',
902
            })
903
        );
904
        // A multibyte char *after* a valid command falls into the argument
905
        // parser and is rejected as a missing number, at the right byte offset.
906
        assert_eq!(
907
            parse_svg_path_d("M0 0L1 1ü"),
908
            Err(SvgPathParseError::ExpectedNumber { pos: 8 })
909
        );
910
    }
911

            
912
    /// Trailing junk after a valid prefix is rejected deterministically.
913
    #[test]
914
    fn parse_path_trailing_junk_is_rejected() {
915
        assert!(parse_svg_path_d("M0 0 L1 1;garbage").is_err());
916
        assert!(parse_svg_path_d("M0 0 L").is_err(), "command with no args");
917
        assert!(
918
            parse_svg_path_d("M0 0 L1").is_err(),
919
            "half a coordinate pair"
920
        );
921
        assert!(
922
            parse_svg_path_d("M0 0 X10 10").is_err(),
923
            "unknown command letter"
924
        );
925
        // Surrounding whitespace is trimmed, not rejected.
926
        assert!(parse_svg_path_d("  \n M0 0 L1 1 \t ").is_ok());
927
    }
928

            
929
    /// An unknown ASCII command letter reports its own offset.
930
    #[test]
931
    fn parse_path_unknown_command_reports_its_offset() {
932
        assert_eq!(
933
            parse_svg_path_d("M0 0 X10 10"),
934
            Err(SvgPathParseError::UnexpectedChar { pos: 5, ch: 'X' })
935
        );
936
    }
937

            
938
    /// Closepath only emits a joining line when the gap exceeds CLOSEPATH_EPSILON.
939
    #[test]
940
    fn parse_path_closepath_epsilon_boundary() {
941
        // Well above the epsilon: a closing line is added.
942
        let mp = parse_svg_path_d("M0 0 L1 0 Z").unwrap();
943
        assert_eq!(mp.rings.as_ref()[0].items.as_ref().len(), 2);
944

            
945
        // Exactly at the epsilon (dx*dx == eps*eps, and the test is strictly `>`):
946
        // no closing line.
947
        let mp = parse_svg_path_d("M0 0 L0.001 0 Z").unwrap();
948
        assert_eq!(mp.rings.as_ref()[0].items.as_ref().len(), 1);
949

            
950
        // Below the epsilon: no closing line.
951
        let mp = parse_svg_path_d("M0 0 L0.0005 0 Z").unwrap();
952
        assert_eq!(mp.rings.as_ref()[0].items.as_ref().len(), 1);
953

            
954
        // Degenerate closepath on an empty subpath yields no rings at all.
955
        assert_eq!(parse_svg_path_d("M0 0 Z").unwrap().rings.as_ref().len(), 0);
956
    }
957

            
958
    /// Every M and every Z flushes a ring.
959
    #[test]
960
    fn parse_path_multiple_subpaths_produce_multiple_rings() {
961
        let mp = parse_svg_path_d("M0 0 L10 0 Z M20 20 L30 20 Z M40 40 L50 40").unwrap();
962
        assert_eq!(mp.rings.as_ref().len(), 3);
963
    }
964

            
965
    /// Structural invariant: within a ring, each element's end is the next
966
    /// element's start -- for every command type, including arcs and closepath.
967
    #[test]
968
    fn parse_path_rings_are_contiguous_chains() {
969
        let d = "M0 0 L10 0 H20 V10 C25 15 30 20 35 20 S45 25 50 20 Q55 15 60 20 T70 20 A5 5 0 1 \
970
                 1 80 30 Z m100 100 l10 0 z";
971
        let mp = parse_svg_path_d(d).unwrap();
972
        assert!(mp.rings.as_ref().len() >= 2);
973
        for (i, ring) in mp.rings.as_ref().iter().enumerate() {
974
            assert_contiguous(ring.items.as_ref(), &format!("ring {i}"));
975
            assert!(
976
                !ring.items.as_ref().is_empty(),
977
                "ring {i} must not be empty"
978
            );
979
        }
980
    }
981

            
982
    /// A closed ring ends where it started.
983
    #[test]
984
    fn parse_path_closed_ring_returns_to_subpath_start() {
985
        let mp = parse_svg_path_d("M0 0 L10 0 L10 10 Z").unwrap();
986
        let ring = &mp.rings.as_ref()[0];
987
        let items = ring.items.as_ref();
988
        assert_eq!(items.last().unwrap().get_end(), SvgPoint { x: 0.0, y: 0.0 });
989
        assert_eq!(
990
            items.first().unwrap().get_start(),
991
            SvgPoint { x: 0.0, y: 0.0 }
992
        );
993
    }
994

            
995
    /// Boundary numerics survive the full parse: coordinates saturate to inf
996
    /// rather than panicking or wrapping.
997
    #[test]
998
    fn parse_path_boundary_numbers_saturate() {
999
        let mp = parse_svg_path_d("M1e999 -1e999 L1e-999 0").unwrap();
        let items_owner = &mp.rings.as_ref()[0];
        let start = items_owner.items.as_ref()[0].get_start();
        assert!(start.x.is_infinite() && start.x.is_sign_positive());
        assert!(start.y.is_infinite() && start.y.is_sign_negative());
        // f32::MAX-ish coordinates with a *relative* lineto overflow to +inf.
        let mp = parse_svg_path_d("M3.4e38 0 l3.4e38 0").unwrap();
        let items_owner = &mp.rings.as_ref()[0];
        assert!(items_owner.items.as_ref()[0].get_end().x.is_infinite());
        // "NaN" / "inf" are not valid SVG numbers -- they must be rejected,
        // so a NaN coordinate can never enter the geometry via the parser.
        assert!(parse_svg_path_d("M NaN 0").is_err());
        assert!(parse_svg_path_d("M inf 0").is_err());
    }
    /// 5000 implicit repeats: the parser is iterative, so this must neither
    /// hang nor blow the stack.
    #[test]
    fn parse_path_extremely_long_input_terminates() {
        let mut d = String::from("M0 0");
        for _ in 0..5_000 {
            d.push_str(" L1 1");
        }
        let mp = parse_svg_path_d(&d).unwrap();
        let items_owner = &mp.rings.as_ref()[0];
        assert_eq!(items_owner.items.as_ref().len(), 5_000);
        // 5000 subpaths -> 5000 rings, still iterative.
        let mut d = String::new();
        for _ in 0..5_000 {
            d.push_str("M0 0 L1 1 Z ");
        }
        assert_eq!(parse_svg_path_d(&d).unwrap().rings.as_ref().len(), 5_000);
    }
    /// A long run of adversarial fragments: every one must *return* (Ok or Err)
    /// and never spin. The `Z`-followed-by-a-digit case used to loop forever.
    #[test]
    fn parse_path_adversarial_fragments_all_terminate() {
        let fragments = [
            "Z",
            "z",
            "ZZZ",
            "M0 0ZZ",
            "M0 0Z0",
            "M0 0zZ5",
            "M0 0Z Z Z",
            "M",
            "M0",
            "M0 0 C",
            "M0 0 A",
            "M0 0 A1",
            "M0 0 A1 1 0 0 0 0",
            "M0 0 S",
            "M0 0 T",
            "M0 0 H",
            "M0 0 V",
            "M0 0 Q1",
            "M0 0 L1 1 1",
            "M0 0 L1 1 1 1 1",
            "M0 0 A0 0 0 0 0 0 0",
            "M0 0 l-.5-.5-.5-.5",
            "M0 0 t1 1 2 2",
            "M0 0 s1 1 2 2 3 3 4 4",
            "M0,0,1,1",
            "M0 0e",
            "M0 0 1e1e1",
            "M.5.5.5.5",
            "M0 0 A1 1 0 11 10 10",
            "M0 0 A1 1 0 1 1 10 10 A1 1 0 0 0 0 0",
            "M0 0 h1e999 v1e999 h-1e999",
            "M-0-0-0-0",
        ];
        for f in fragments {
            // The assertion is termination itself; the result is merely pinned
            // as "did not panic".
            let r = parse_svg_path_d(f);
            assert!(r.is_ok() || r.is_err(), "{f:?} must return, not panic");
        }
    }
    proptest! {
        #[test]
        fn parse_path_random_fragments_all_terminate(f in any::<String>()) {
            let r = parse_svg_path_d(&f);
            assert!(r.is_ok() || r.is_err(), "{f:?} must return, not panic");
        }
    }
    /// All 14 commands round-trip through the tokenizer into geometry of the
    /// expected kind.
    #[test]
    fn parse_path_every_command_produces_its_element_kind() {
        let cases: [(&str, usize); 10] = [
            ("M0 0 L1 1", 1),
            ("M0 0 l1 1", 1),
            ("M0 0 H1", 1),
            ("M0 0 V1", 1),
            ("M0 0 C1 1 2 2 3 3", 1),
            ("M0 0 S1 1 2 2", 1),
            ("M0 0 Q1 1 2 2", 1),
            ("M0 0 T1 1", 1),
            ("M0 0 L1 0 Z", 2),          // the Z adds the closing line
            ("M0 0 A5 5 0 0 1 10 0", 2), // a half-turn arc splits into 2 cubics
        ];
        for (d, expected) in cases {
            let mp = parse_svg_path_d(d).unwrap_or_else(|e| panic!("{d:?} failed: {e:?}"));
            let rings = mp.rings.as_ref();
            assert_eq!(rings.len(), 1, "{d:?}");
            assert_eq!(rings[0].items.as_ref().len(), expected, "{d:?}");
        }
    }
    // ======================================================= arc_to_cubics (numeric)
    #[test]
    fn arc_to_cubics_coincident_endpoints_emit_nothing() {
        let mut out = Vec::new();
        arc_to_cubics(ORIGIN, ORIGIN, 5.0, 5.0, 0.0, true, true, &mut out);
        assert!(out.is_empty(), "a zero-length arc is dropped per SVG F.6.2");
        // Within POINT_EPSILON also counts as coincident.
        let near = SvgPoint { x: 1e-9, y: 1e-9 };
        arc_to_cubics(ORIGIN, near, 5.0, 5.0, 0.0, false, false, &mut out);
        assert!(out.is_empty());
    }
    #[test]
    fn arc_to_cubics_zero_radius_emits_a_line() {
        let end = SvgPoint { x: 10.0, y: 10.0 };
        for (rx, ry) in [(0.0, 5.0), (5.0, 0.0), (0.0, 0.0)] {
            let mut out = Vec::new();
            arc_to_cubics(ORIGIN, end, rx, ry, 0.0, false, true, &mut out);
            assert_eq!(out.len(), 1, "rx={rx} ry={ry}");
            assert!(matches!(out[0], SvgPathElement::Line(_)));
            assert_eq!(out[0].get_start(), ORIGIN);
            assert_eq!(out[0].get_end(), end);
        }
    }
    /// For every flag combination, the arc is 1..=4 cubics that start exactly at
    /// `start` and end exactly at `end` (the endpoint is snapped, not computed).
    proptest! {
        #[test]
        fn arc_to_cubics_endpoints_are_exact_for_all_flag_combos(
            large_arc in proptest::bool::ANY, sweep in proptest::bool::ANY
        ) {
            let start = SvgPoint { x: 0.0, y: 0.0 };
            let end = SvgPoint { x: 10.0, y: 10.0 };
            let mut out = Vec::new();
            arc_to_cubics(start, end, 8.0, 6.0, 30.0, large_arc, sweep, &mut out);
            assert!(
                (1..=4).contains(&out.len()),
                "large_arc={large_arc} sweep={sweep}: got {} cubics",
                out.len()
            );
            assert_eq!(out[0].get_start(), start);
            assert_eq!(out.last().unwrap().get_end(), end);
            assert_contiguous(&out, "arc");
            for p in out.iter().flat_map(|e| [e.get_start(), e.get_end()]) {
                assert!(p.x.is_finite() && p.y.is_finite(), "arc produced {p:?}");
            }
        }
    }
    /// Radii that are too small to span the endpoints are scaled up (F.6.6 step 3),
    /// so the arc still lands exactly on the endpoint instead of NaN-ing out.
    #[test]
    fn arc_to_cubics_undersized_radii_are_scaled_up() {
        let start = ORIGIN;
        let end = SvgPoint { x: 100.0, y: 0.0 };
        let mut out = Vec::new();
        arc_to_cubics(start, end, 1.0, 1.0, 0.0, false, true, &mut out);
        assert!(!out.is_empty());
        assert_eq!(out.last().unwrap().get_end(), end);
        for p in all_points(&SvgPath {
            items: SvgPathElementVec::from_vec(out),
        }) {
            assert!(
                p.x.is_finite() && p.y.is_finite(),
                "scaled arc produced {p:?}"
            );
        }
    }
    /// NaN / infinite radii must not spin the segment loop: `n_segs` comes from a
    /// NaN -> usize cast, which saturates to 0 and is then clamped to 1.
    #[test]
    fn arc_to_cubics_nan_and_inf_inputs_are_bounded() {
        let end = SvgPoint { x: 10.0, y: 10.0 };
        let bad = [
            (f32::NAN, 5.0, 0.0),
            (5.0, f32::NAN, 0.0),
            (f32::INFINITY, f32::INFINITY, 0.0),
            (5.0, 5.0, f32::NAN),
            (5.0, 5.0, f32::INFINITY),
            (f32::MAX, f32::MAX, 360.0),
        ];
        for (rx, ry, rot) in bad {
            let mut out = Vec::new();
            arc_to_cubics(ORIGIN, end, rx, ry, rot, true, false, &mut out);
            assert!(
                out.len() <= 4,
                "rx={rx} ry={ry} rot={rot}: {} elements (segment loop ran away)",
                out.len()
            );
        }
    }
    /// Extreme but finite endpoints do not panic and stay bounded.
    #[test]
    fn arc_to_cubics_extreme_endpoints_do_not_panic() {
        let mut out = Vec::new();
        arc_to_cubics(
            SvgPoint {
                x: f32::MIN,
                y: f32::MIN,
            },
            SvgPoint {
                x: f32::MAX,
                y: f32::MAX,
            },
            f32::MAX,
            f32::MAX,
            0.0,
            true,
            true,
            &mut out,
        );
        assert!(out.len() <= 4);
    }
    // ======================================================= angle_between (numeric)
    #[test]
    fn angle_between_known_angles() {
        assert!(approx(angle_between(1.0, 0.0, 1.0, 0.0), 0.0));
        assert!(approx(
            angle_between(1.0, 0.0, 0.0, 1.0),
            core::f32::consts::FRAC_PI_2
        ));
        assert!(approx(
            angle_between(1.0, 0.0, 0.0, -1.0),
            -core::f32::consts::FRAC_PI_2
        ));
        assert!(approx(
            angle_between(1.0, 0.0, -1.0, 0.0),
            core::f32::consts::PI
        ));
        // Magnitude is irrelevant -- only direction matters.
        assert!(approx(
            angle_between(100.0, 0.0, 0.0, 0.001),
            core::f32::consts::FRAC_PI_2
        ));
    }
    /// A zero-length (or underflowing) vector short-circuits to 0.0.
    #[test]
    fn angle_between_zero_length_vectors_return_zero() {
        assert_eq!(angle_between(0.0, 0.0, 1.0, 0.0), 0.0);
        assert_eq!(angle_between(1.0, 0.0, 0.0, 0.0), 0.0);
        assert_eq!(angle_between(0.0, 0.0, 0.0, 0.0), 0.0);
        // Denormal-scale vectors: the squared length underflows to 0.
        assert_eq!(angle_between(1e-30, 1e-30, 1e-30, 1e-30), 0.0);
    }
    /// Result is always within [-PI, PI] for finite inputs (the acos argument is
    /// clamped, so rounding can never push it out of the domain).
    proptest! {
        #[test]
        fn angle_between_is_always_within_pi_for_finite_inputs(
            ux in proptest::num::f32::ANY, uy in proptest::num::f32::ANY,
            vx in proptest::num::f32::ANY, vy in proptest::num::f32::ANY
        ) {
            let a = angle_between(ux, uy, vx, vy);
            assert!(
                a.is_nan() || a.abs() <= core::f32::consts::PI + 1e-5,
                "angle_between({ux},{uy},{vx},{vy}) = {a} is out of range"
            );
        }
    }
    /// Antiparallel/parallel unit vectors do not fall out of acos's domain even
    /// when the dot product rounds slightly past +/-1.
    #[test]
    fn angle_between_clamps_the_acos_domain() {
        let a = angle_between(0.1, 0.2, 0.1, 0.2);
        assert!(
            !a.is_nan(),
            "parallel vectors must not produce NaN, got {a}"
        );
        assert!(approx(a, 0.0));
        let a = angle_between(0.1, 0.2, -0.1, -0.2);
        assert!(!a.is_nan());
        assert!(approx(a.abs(), core::f32::consts::PI));
    }
    /// NaN / inf inputs produce NaN, not a panic.
    #[test]
    fn angle_between_nan_and_inf_do_not_panic() {
        assert!(angle_between(f32::NAN, 0.0, 1.0, 0.0).is_nan());
        assert!(angle_between(1.0, 0.0, f32::NAN, f32::NAN).is_nan());
        assert!(angle_between(f32::INFINITY, 0.0, f32::INFINITY, 0.0).is_nan());
        assert!(angle_between(f32::INFINITY, 0.0, 1.0, 0.0).is_nan());
    }
    // ================================================ arc_segment_to_cubic (numeric)
    #[test]
    fn arc_segment_to_cubic_quarter_circle() {
        // Unit circle, no rotation, 0 -> PI/2: the endpoint must land on (0, 1).
        let (c1, c2, ep) = arc_segment_to_cubic(
            0.0,
            0.0,
            1.0,
            1.0,
            1.0,
            0.0,
            0.0,
            core::f32::consts::FRAC_PI_2,
        );
        assert!(approx(ep.x, 0.0) && approx(ep.y, 1.0), "ep = {ep:?}");
        // Control points bulge outward by kappa.
        assert!(approx(c1.x, 1.0) && approx(c1.y, KAPPA), "c1 = {c1:?}");
        assert!(approx(c2.x, KAPPA) && approx(c2.y, 1.0), "c2 = {c2:?}");
    }
    /// A zero-width segment collapses every point onto the start of the arc.
    #[test]
    fn arc_segment_to_cubic_zero_sweep_collapses() {
        let (c1, c2, ep) = arc_segment_to_cubic(5.0, 5.0, 2.0, 2.0, 1.0, 0.0, 0.7, 0.7);
        assert!(approx(c1.x, c2.x) && approx(c1.y, c2.y));
        assert!(approx(c2.x, ep.x) && approx(c2.y, ep.y));
        // ...and that point is on the circle around (5,5).
        assert!(approx((ep.x - 5.0).hypot(ep.y - 5.0), 2.0));
    }
    /// Zero radii put all three points at the center.
    #[test]
    fn arc_segment_to_cubic_zero_radius_is_the_center() {
        let (c1, c2, ep) = arc_segment_to_cubic(3.0, 4.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0);
        for p in [c1, c2, ep] {
            assert_eq!(p, SvgPoint { x: 3.0, y: 4.0 });
        }
    }
    /// Rotation is applied via the caller-supplied cos/sin pair.
    #[test]
    fn arc_segment_to_cubic_applies_rotation() {
        // 90-degree rotation (cos=0, sin=1) maps the theta=0 point (rx, 0) to (0, rx).
        let (_, _, ep) = arc_segment_to_cubic(0.0, 0.0, 2.0, 1.0, 0.0, 1.0, 0.0, 0.0);
        assert!(approx(ep.x, 0.0) && approx(ep.y, 2.0), "ep = {ep:?}");
    }
    #[test]
    fn arc_segment_to_cubic_nan_and_inf_do_not_panic() {
        let bad = [
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::MAX,
            f32::MIN,
        ];
        for v in bad {
            let (c1, c2, ep) = arc_segment_to_cubic(v, v, v, v, v, v, v, v);
            // The only contract is "returns a defined value without panicking".
            for p in [c1, c2, ep] {
                assert!(p.x.is_nan() || p.x.is_finite() || p.x.is_infinite());
                assert!(p.y.is_nan() || p.y.is_finite() || p.y.is_infinite());
            }
        }
        // A full-circle sweep drives tan(PI/2) to a huge value; still no panic.
        let (c1, _, _) =
            arc_segment_to_cubic(0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, core::f32::consts::TAU);
        assert!(!c1.x.is_nan() || c1.x.is_nan(), "must not panic");
    }
    // =================================================== svg_circle_to_paths (numeric)
    #[test]
    fn circle_has_four_cubics_and_closes_on_itself() {
        let p = svg_circle_to_paths(10.0, 20.0, 5.0);
        let items = p.items.as_ref();
        assert_eq!(items.len(), 4);
        assert!(items
            .iter()
            .all(|e| matches!(e, SvgPathElement::CubicCurve(_))));
        assert_contiguous(items, "circle");
        assert_eq!(
            items.last().unwrap().get_end(),
            items.first().unwrap().get_start(),
            "the circle must close exactly"
        );
        // The four anchors are the cardinal points.
        assert_eq!(items[0].get_start(), SvgPoint { x: 10.0, y: 15.0 });
        assert_eq!(items[0].get_end(), SvgPoint { x: 15.0, y: 20.0 });
        assert_eq!(items[1].get_end(), SvgPoint { x: 10.0, y: 25.0 });
        assert_eq!(items[2].get_end(), SvgPoint { x: 5.0, y: 20.0 });
    }
    /// r = 0 degenerates to four zero-length curves at the center, not a panic.
    #[test]
    fn circle_zero_radius_collapses_to_the_center() {
        let p = svg_circle_to_paths(3.0, 4.0, 0.0);
        let items = p.items.as_ref();
        assert_eq!(items.len(), 4);
        for pt in all_points(&p) {
            assert_eq!(pt, SvgPoint { x: 3.0, y: 4.0 });
        }
    }
    /// A negative radius mirrors the circle (it is not rejected or abs()'d);
    /// it still yields a closed 4-curve path.
    #[test]
    fn circle_negative_radius_is_mirrored_not_rejected() {
        let p = svg_circle_to_paths(0.0, 0.0, -5.0);
        let items = p.items.as_ref();
        assert_eq!(items.len(), 4);
        assert_contiguous(items, "negative-r circle");
        assert_eq!(items[0].get_start(), SvgPoint { x: 0.0, y: 5.0 });
        for pt in all_points(&p) {
            assert!(pt.x.is_finite() && pt.y.is_finite());
        }
    }
    #[test]
    fn circle_nan_inf_and_max_do_not_panic() {
        for (cx, cy, r) in [
            (f32::NAN, 0.0, 1.0),
            (0.0, 0.0, f32::NAN),
            (0.0, 0.0, f32::INFINITY),
            (f32::MAX, f32::MAX, f32::MAX),
            (f32::MIN, f32::MIN, f32::MIN),
        ] {
            let p = svg_circle_to_paths(cx, cy, r);
            assert_eq!(p.items.as_ref().len(), 4, "cx={cx} cy={cy} r={r}");
        }
        // f32::MAX radius overflows the control points to infinity rather than
        // wrapping.
        let p = svg_circle_to_paths(f32::MAX, 0.0, f32::MAX);
        assert!(all_points(&p).iter().any(|pt| pt.x.is_infinite()));
    }
    // ==================================================== svg_rect_to_path (numeric)
    #[test]
    fn rect_sharp_corners_are_four_lines() {
        let p = svg_rect_to_path(1.0, 2.0, 10.0, 20.0, 0.0, 0.0);
        let items = p.items.as_ref();
        assert_eq!(items.len(), 4);
        assert!(items.iter().all(|e| matches!(e, SvgPathElement::Line(_))));
        assert_contiguous(items, "sharp rect");
        assert_eq!(items[0].get_start(), SvgPoint { x: 1.0, y: 2.0 });
        assert_eq!(items[1].get_start(), SvgPoint { x: 11.0, y: 2.0 });
        assert_eq!(items[2].get_start(), SvgPoint { x: 11.0, y: 22.0 });
        assert_eq!(items[3].get_start(), SvgPoint { x: 1.0, y: 22.0 });
        assert_eq!(
            items.last().unwrap().get_end(),
            items.first().unwrap().get_start(),
            "the rect must close exactly"
        );
    }
    #[test]
    fn rect_rounded_is_eight_alternating_segments_and_closes() {
        let p = svg_rect_to_path(0.0, 0.0, 100.0, 50.0, 10.0, 5.0);
        let items = p.items.as_ref();
        assert_eq!(items.len(), 8);
        for (i, e) in items.iter().enumerate() {
            if i % 2 == 0 {
                assert!(
                    matches!(e, SvgPathElement::Line(_)),
                    "item {i} should be an edge"
                );
            } else {
                assert!(
                    matches!(e, SvgPathElement::CubicCurve(_)),
                    "item {i} should be a corner"
                );
            }
        }
        assert_contiguous(items, "rounded rect");
        assert_eq!(
            items.last().unwrap().get_end(),
            items.first().unwrap().get_start(),
            "the rounded rect must close exactly"
        );
    }
    /// Radii larger than half the rect are clamped to half (SVG spec), so an
    /// over-large rx cannot invert the geometry.
    #[test]
    fn rect_oversized_radii_are_clamped_to_half() {
        let p = svg_rect_to_path(0.0, 0.0, 10.0, 10.0, 1000.0, 1000.0);
        let items = p.items.as_ref();
        assert_eq!(items.len(), 8);
        // rx clamps to 5 => the top edge runs from x+5 to x+w-5, i.e. zero length.
        match items[0] {
            SvgPathElement::Line(l) => {
                assert_eq!(l.start, SvgPoint { x: 5.0, y: 0.0 });
                assert_eq!(l.end, SvgPoint { x: 5.0, y: 0.0 });
            }
            other => panic!("expected Line, got {other:?}"),
        }
        assert_contiguous(items, "clamped rect");
        for pt in all_points(&p) {
            assert!(pt.x.is_finite() && pt.y.is_finite());
            assert!((0.0..=10.0).contains(&pt.x), "x {} escaped the rect", pt.x);
            assert!((0.0..=10.0).contains(&pt.y), "y {} escaped the rect", pt.y);
        }
    }
    /// Only one of rx/ry being zero still takes the rounded path.
    #[test]
    fn rect_single_zero_radius_still_rounds() {
        let p = svg_rect_to_path(0.0, 0.0, 100.0, 100.0, 0.0, 10.0);
        assert_eq!(p.items.as_ref().len(), 8);
        let p = svg_rect_to_path(0.0, 0.0, 100.0, 100.0, 10.0, 0.0);
        assert_eq!(p.items.as_ref().len(), 8);
    }
    /// A negative width drives `rx.min(w / 2.0)` negative, which falls below the
    /// epsilon and takes the sharp-corner branch. Deterministic, no panic.
    #[test]
    fn rect_negative_extent_takes_the_sharp_branch() {
        let p = svg_rect_to_path(0.0, 0.0, -10.0, -10.0, 4.0, 4.0);
        let items = p.items.as_ref();
        assert_eq!(items.len(), 4);
        assert!(items.iter().all(|e| matches!(e, SvgPathElement::Line(_))));
        assert_contiguous(items, "negative rect");
        assert_eq!(items[1].get_start(), SvgPoint { x: -10.0, y: 0.0 });
    }
    /// `f32::min` returns the non-NaN operand, so a NaN radius silently becomes
    /// half the extent -- and every coordinate stays finite.
    #[test]
    fn rect_nan_radius_falls_back_to_half_extent() {
        let p = svg_rect_to_path(0.0, 0.0, 100.0, 100.0, f32::NAN, f32::NAN);
        let items = p.items.as_ref();
        assert_eq!(
            items.len(),
            8,
            "NaN radii clamp to w/2, h/2 -> rounded path"
        );
        for pt in all_points(&p) {
            assert!(
                pt.x.is_finite() && pt.y.is_finite(),
                "NaN leaked into {pt:?}"
            );
        }
        // rx == 50 => the top edge collapses (x+50 .. x+100-50).
        match items[0] {
            SvgPathElement::Line(l) => assert_eq!(l.start, l.end),
            other => panic!("expected Line, got {other:?}"),
        }
    }
    /// A NaN extent cannot be repaired -- but it must still return a well-formed
    /// path rather than panicking.
    #[test]
    fn rect_nan_extent_is_deterministic() {
        let p = svg_rect_to_path(0.0, 0.0, f32::NAN, f32::NAN, 0.0, 0.0);
        // rx = 0.min(NaN) = 0 -> sharp branch.
        assert_eq!(p.items.as_ref().len(), 4);
        let p = svg_rect_to_path(f32::NAN, f32::NAN, 10.0, 10.0, 0.0, 0.0);
        assert_eq!(p.items.as_ref().len(), 4);
    }
    #[test]
    fn rect_inf_and_max_extents_do_not_panic() {
        for (x, y, w, h, rx, ry) in [
            (0.0, 0.0, f32::INFINITY, f32::INFINITY, 0.0, 0.0),
            (0.0, 0.0, f32::MAX, f32::MAX, 0.0, 0.0),
            (f32::MIN, f32::MIN, f32::MAX, f32::MAX, f32::MAX, f32::MAX),
            (
                0.0,
                0.0,
                f32::INFINITY,
                f32::INFINITY,
                f32::INFINITY,
                f32::INFINITY,
            ),
        ] {
            let p = svg_rect_to_path(x, y, w, h, rx, ry);
            let n = p.items.as_ref().len();
            assert!(
                n == 4 || n == 8,
                "w={w} h={h} rx={rx} ry={ry}: got {n} items"
            );
        }
    }
}