Skip to main content

azul_core/
path_parser.rs

1//! SVG `d=""` path data parser.
2//!
3//! Parses the `d` attribute of SVG `<path>` elements into `SvgMultiPolygon`
4//! geometry, supporting all 14 SVG path commands (M/m, L/l, H/h, V/v,
5//! C/c, S/s, Q/q, T/t, A/a, Z/z).
6
7use alloc::{string::String, vec::Vec};
8use azul_css::props::basic::{SvgCubicCurve, SvgPoint, SvgQuadraticCurve};
9
10use crate::svg::{SvgLine, SvgMultiPolygon, SvgPath, SvgPathElement, SvgPathElementVec, SvgPathVec};
11
12/// Bezier approximation constant for quarter-circle arcs.
13const KAPPA: f32 = 0.552_284_8;
14
15/// Tolerance for treating two points as coincident (used in closepath and arc degeneracy checks).
16const POINT_EPSILON: f32 = 1e-6;
17
18/// Tolerance for snapping a closepath line (slightly larger to avoid micro-segments).
19const CLOSEPATH_EPSILON: f32 = 0.001;
20
21/// Tolerance for treating a vector length as zero in angle computation.
22const ZERO_LENGTH_EPSILON: f32 = 1e-10;
23
24/// Small offset added to PI/2 when splitting arcs to avoid exact-boundary floating-point issues.
25const ARC_SPLIT_FUDGE: f32 = 0.001;
26
27/// Decode the UTF-8 character starting at `pos` in `input`.
28///
29/// `input` is always the byte view of a valid `&str` and `pos` is always at a
30/// char boundary (only whole ASCII tokens are consumed), so the UTF-8 decode
31/// succeeds; a corrupt offset falls back to the replacement character rather
32/// than panicking. Used so error messages report the real Unicode char instead
33/// of a Latin-1 reinterpretation of a single UTF-8 byte (`b as char`).
34fn char_at(input: &[u8], pos: usize) -> char {
35    input
36        .get(pos..)
37        .and_then(|rest| core::str::from_utf8(rest).ok())
38        .and_then(|s| s.chars().next())
39        .unwrap_or(char::REPLACEMENT_CHARACTER)
40}
41
42/// Errors that can occur during SVG path parsing.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum SvgPathParseError {
45    /// The path string is empty.
46    EmptyPath,
47    /// Unexpected character encountered at the given byte offset.
48    UnexpectedChar { pos: usize, ch: char },
49    /// Expected a number but found something else.
50    ExpectedNumber { pos: usize },
51    /// Invalid arc flag (must be 0 or 1).
52    InvalidArcFlag { pos: usize },
53}
54
55/// Human-readable error messages for SVG path parse failures.
56impl core::fmt::Display for SvgPathParseError {
57    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
58        match self {
59            Self::EmptyPath => write!(f, "empty path"),
60            Self::UnexpectedChar { pos, ch } => {
61                write!(f, "unexpected char '{ch}' at byte {pos}")
62            }
63            Self::ExpectedNumber { pos } => write!(f, "expected number at byte {pos}"),
64            Self::InvalidArcFlag { pos } => write!(f, "invalid arc flag at byte {pos}"),
65        }
66    }
67}
68
69/// Internal parser state.
70struct PathParser<'a> {
71    input: &'a [u8],
72    pos: usize,
73    current: SvgPoint,
74    subpath_start: SvgPoint,
75    last_control: Option<SvgPoint>,
76    last_command: u8,
77}
78
79impl<'a> PathParser<'a> {
80    const fn new(input: &'a [u8]) -> Self {
81        Self {
82            input,
83            pos: 0,
84            current: SvgPoint { x: 0.0, y: 0.0 },
85            subpath_start: SvgPoint { x: 0.0, y: 0.0 },
86            last_control: None,
87            last_command: 0,
88        }
89    }
90
91    const fn at_end(&self) -> bool {
92        self.pos >= self.input.len()
93    }
94
95    fn peek(&self) -> Option<u8> {
96        self.input.get(self.pos).copied()
97    }
98
99    fn skip_whitespace_and_commas(&mut self) {
100        while let Some(&b) = self.input.get(self.pos) {
101            if b == b' ' || b == b'\t' || b == b'\n' || b == b'\r' || b == b',' {
102                self.pos += 1;
103            } else {
104                break;
105            }
106        }
107    }
108
109    fn skip_whitespace(&mut self) {
110        while let Some(&b) = self.input.get(self.pos) {
111            if b == b' ' || b == b'\t' || b == b'\n' || b == b'\r' {
112                self.pos += 1;
113            } else {
114                break;
115            }
116        }
117    }
118
119    /// Returns true if the current position looks like the start of a number.
120    fn has_number(&self) -> bool {
121        match self.input.get(self.pos) {
122            Some(b'+' | b'-' | b'.') => true,
123            Some(b) if b.is_ascii_digit() => true,
124            _ => false,
125        }
126    }
127
128    fn parse_number(&mut self) -> Result<f32, SvgPathParseError> {
129        self.skip_whitespace_and_commas();
130        let start = self.pos;
131
132        // Optional sign
133        if let Some(&b) = self.input.get(self.pos) {
134            if b == b'+' || b == b'-' {
135                self.pos += 1;
136            }
137        }
138
139        let mut has_digits = false;
140
141        // Integer part
142        while let Some(&b) = self.input.get(self.pos) {
143            if b.is_ascii_digit() {
144                self.pos += 1;
145                has_digits = true;
146            } else {
147                break;
148            }
149        }
150
151        // Decimal part
152        if self.input.get(self.pos) == Some(&b'.') {
153            self.pos += 1;
154            while let Some(&b) = self.input.get(self.pos) {
155                if b.is_ascii_digit() {
156                    self.pos += 1;
157                    has_digits = true;
158                } else {
159                    break;
160                }
161            }
162        }
163
164        if !has_digits {
165            return Err(SvgPathParseError::ExpectedNumber { pos: start });
166        }
167
168        // Exponent
169        if let Some(&b) = self.input.get(self.pos) {
170            if b == b'e' || b == b'E' {
171                self.pos += 1;
172                if let Some(&b) = self.input.get(self.pos) {
173                    if b == b'+' || b == b'-' {
174                        self.pos += 1;
175                    }
176                }
177                while let Some(&b) = self.input.get(self.pos) {
178                    if b.is_ascii_digit() {
179                        self.pos += 1;
180                    } else {
181                        break;
182                    }
183                }
184            }
185        }
186
187        let s = core::str::from_utf8(&self.input[start..self.pos])
188            .map_err(|_| SvgPathParseError::ExpectedNumber { pos: start })?;
189        s.parse::<f32>()
190            .map_err(|_| SvgPathParseError::ExpectedNumber { pos: start })
191    }
192
193    fn parse_flag(&mut self) -> Result<bool, SvgPathParseError> {
194        self.skip_whitespace_and_commas();
195        match self.input.get(self.pos) {
196            Some(b'0') => {
197                self.pos += 1;
198                Ok(false)
199            }
200            Some(b'1') => {
201                self.pos += 1;
202                Ok(true)
203            }
204            _ => Err(SvgPathParseError::InvalidArcFlag { pos: self.pos }),
205        }
206    }
207
208    fn parse_coordinate_pair(&mut self) -> Result<(f32, f32), SvgPathParseError> {
209        let x = self.parse_number()?;
210        let y = self.parse_number()?;
211        Ok((x, y))
212    }
213
214    fn make_absolute(&self, x: f32, y: f32, relative: bool) -> SvgPoint {
215        if relative {
216            SvgPoint {
217                x: self.current.x + x,
218                y: self.current.y + y,
219            }
220        } else {
221            SvgPoint { x, y }
222        }
223    }
224
225    fn handle_line_to(&mut self, relative: bool, elements: &mut Vec<SvgPathElement>) -> Result<(), SvgPathParseError> {
226        let (x, y) = self.parse_coordinate_pair()?;
227        let end = self.make_absolute(x, y, relative);
228        elements.push(SvgPathElement::Line(SvgLine { start: self.current, end }));
229        self.current = end;
230        self.last_control = None;
231        Ok(())
232    }
233
234    fn handle_horizontal_to(&mut self, relative: bool, elements: &mut Vec<SvgPathElement>) -> Result<(), SvgPathParseError> {
235        let x = self.parse_number()?;
236        let abs_x = if relative { self.current.x + x } else { x };
237        let end = SvgPoint { x: abs_x, y: self.current.y };
238        elements.push(SvgPathElement::Line(SvgLine { start: self.current, end }));
239        self.current = end;
240        self.last_control = None;
241        Ok(())
242    }
243
244    fn handle_vertical_to(&mut self, relative: bool, elements: &mut Vec<SvgPathElement>) -> Result<(), SvgPathParseError> {
245        let y = self.parse_number()?;
246        let abs_y = if relative { self.current.y + y } else { y };
247        let end = SvgPoint { x: self.current.x, y: abs_y };
248        elements.push(SvgPathElement::Line(SvgLine { start: self.current, end }));
249        self.current = end;
250        self.last_control = None;
251        Ok(())
252    }
253
254    #[allow(clippy::similar_names)] // domain-standard coordinate/control-point names
255    fn handle_cubic_to(&mut self, relative: bool, elements: &mut Vec<SvgPathElement>) -> Result<(), SvgPathParseError> {
256        let (c1x, c1y) = self.parse_coordinate_pair()?;
257        let (c2x, c2y) = self.parse_coordinate_pair()?;
258        let (ex, ey) = self.parse_coordinate_pair()?;
259        let ctrl_1 = self.make_absolute(c1x, c1y, relative);
260        let ctrl_2 = self.make_absolute(c2x, c2y, relative);
261        let end = self.make_absolute(ex, ey, relative);
262        elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
263            start: self.current, ctrl_1, ctrl_2, end,
264        }));
265        self.last_control = Some(ctrl_2);
266        self.current = end;
267        Ok(())
268    }
269
270    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
271    #[allow(clippy::similar_names)] // domain-standard coordinate/control-point names
272    fn handle_smooth_cubic_to(&mut self, relative: bool, elements: &mut Vec<SvgPathElement>) -> Result<(), SvgPathParseError> {
273        let ctrl_1 = match self.last_control {
274            Some(lc) if matches!(self.last_command.to_ascii_uppercase(), b'C' | b'S') => {
275                SvgPoint {
276                    x: 2.0 * self.current.x - lc.x,
277                    y: 2.0 * self.current.y - lc.y,
278                }
279            }
280            _ => self.current,
281        };
282        let (c2x, c2y) = self.parse_coordinate_pair()?;
283        let (ex, ey) = self.parse_coordinate_pair()?;
284        let ctrl_2 = self.make_absolute(c2x, c2y, relative);
285        let end = self.make_absolute(ex, ey, relative);
286        elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
287            start: self.current, ctrl_1, ctrl_2, end,
288        }));
289        self.last_control = Some(ctrl_2);
290        self.current = end;
291        Ok(())
292    }
293
294    fn handle_quadratic_to(&mut self, relative: bool, elements: &mut Vec<SvgPathElement>) -> Result<(), SvgPathParseError> {
295        let (cx, cy) = self.parse_coordinate_pair()?;
296        let (ex, ey) = self.parse_coordinate_pair()?;
297        let ctrl = self.make_absolute(cx, cy, relative);
298        let end = self.make_absolute(ex, ey, relative);
299        elements.push(SvgPathElement::QuadraticCurve(SvgQuadraticCurve {
300            start: self.current, ctrl, end,
301        }));
302        self.last_control = Some(ctrl);
303        self.current = end;
304        Ok(())
305    }
306
307    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
308    fn handle_smooth_quadratic_to(&mut self, relative: bool, elements: &mut Vec<SvgPathElement>) -> Result<(), SvgPathParseError> {
309        let ctrl = match self.last_control {
310            Some(lc) if matches!(self.last_command.to_ascii_uppercase(), b'Q' | b'T') => {
311                SvgPoint {
312                    x: 2.0 * self.current.x - lc.x,
313                    y: 2.0 * self.current.y - lc.y,
314                }
315            }
316            _ => self.current,
317        };
318        let (ex, ey) = self.parse_coordinate_pair()?;
319        let end = self.make_absolute(ex, ey, relative);
320        elements.push(SvgPathElement::QuadraticCurve(SvgQuadraticCurve {
321            start: self.current, ctrl, end,
322        }));
323        self.last_control = Some(ctrl);
324        self.current = end;
325        Ok(())
326    }
327
328    fn handle_arc_to(&mut self, relative: bool, elements: &mut Vec<SvgPathElement>) -> Result<(), SvgPathParseError> {
329        let rx = self.parse_number()?.abs();
330        let ry = self.parse_number()?.abs();
331        let x_rotation = self.parse_number()?;
332        let large_arc = self.parse_flag()?;
333        let sweep = self.parse_flag()?;
334        let (ex, ey) = self.parse_coordinate_pair()?;
335        let end = self.make_absolute(ex, ey, relative);
336        arc_to_cubics(self.current, end, rx, ry, x_rotation, large_arc, sweep, elements);
337        self.current = end;
338        self.last_control = None;
339        Ok(())
340    }
341}
342
343/// Parse an SVG path `d` attribute string into a `SvgMultiPolygon`.
344///
345/// Each M/m command starts a new subpath (ring). All 14 SVG path commands are
346/// supported including arcs (converted to cubic beziers).
347///
348/// # Panics
349///
350/// Panics if the path tokenizer signals a command but then yields no token
351/// (an internal parser invariant that should not occur for any input).
352#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
353#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
354/// # Errors
355///
356/// Returns an error if `d` is not a valid SVG path-data string.
357pub fn parse_svg_path_d(d: &str) -> Result<SvgMultiPolygon, SvgPathParseError> {
358    let d = d.trim();
359    if d.is_empty() {
360        return Err(SvgPathParseError::EmptyPath);
361    }
362
363    let mut parser = PathParser::new(d.as_bytes());
364    let mut rings: Vec<SvgPath> = Vec::new();
365    let mut current_elements: Vec<SvgPathElement> = Vec::new();
366
367    parser.skip_whitespace();
368
369    while !parser.at_end() {
370        parser.skip_whitespace_and_commas();
371        if parser.at_end() {
372            break;
373        }
374
375        let b = parser.peek().unwrap();
376
377        // Determine if this is a command letter or an implicit repeat
378        let cmd = if b.is_ascii_alphabetic() {
379            parser.pos += 1;
380            b
381        } else if parser.last_command != 0 {
382            // Implicit repeat: after M/m, implicit commands become L/l
383            match parser.last_command {
384                b'M' => b'L',
385                b'm' => b'l',
386                // AUDIT 2026-07-08: a `Z`/`z` closepath takes no arguments, so it
387                // cannot be implicitly repeated. Reaching here means a stray
388                // non-command byte followed a closepath (e.g. the `5` in "M0 0Z5").
389                // The old `other => other` fell through to the `Z` arm, which
390                // consumes zero bytes, so `pos` never advanced -> 100% CPU infinite
391                // loop. Reject it as an unexpected character instead.
392                b'Z' | b'z' => {
393                    return Err(SvgPathParseError::UnexpectedChar {
394                        pos: parser.pos,
395                        ch: char_at(parser.input, parser.pos),
396                    });
397                }
398                other => other,
399            }
400        } else {
401            return Err(SvgPathParseError::UnexpectedChar {
402                pos: parser.pos,
403                ch: char_at(parser.input, parser.pos),
404            });
405        };
406
407        let relative = cmd.is_ascii_lowercase();
408        let cmd_upper = cmd.to_ascii_uppercase();
409
410        match cmd_upper {
411            b'M' => {
412                // Flush current subpath
413                if !current_elements.is_empty() {
414                    rings.push(SvgPath {
415                        items: SvgPathElementVec::from_vec(core::mem::take(&mut current_elements)),
416                    });
417                }
418                let (x, y) = parser.parse_coordinate_pair()?;
419                let pt = parser.make_absolute(x, y, relative);
420                parser.current = pt;
421                parser.subpath_start = pt;
422                parser.last_control = None;
423                parser.last_command = cmd;
424            }
425            b'L' => {
426                parser.handle_line_to(relative, &mut current_elements)?;
427                parser.last_command = cmd;
428            }
429            b'H' => {
430                parser.handle_horizontal_to(relative, &mut current_elements)?;
431                parser.last_command = cmd;
432            }
433            b'V' => {
434                parser.handle_vertical_to(relative, &mut current_elements)?;
435                parser.last_command = cmd;
436            }
437            b'C' => {
438                parser.handle_cubic_to(relative, &mut current_elements)?;
439                parser.last_command = cmd;
440            }
441            b'S' => {
442                parser.handle_smooth_cubic_to(relative, &mut current_elements)?;
443                parser.last_command = cmd;
444            }
445            b'Q' => {
446                parser.handle_quadratic_to(relative, &mut current_elements)?;
447                parser.last_command = cmd;
448            }
449            b'T' => {
450                parser.handle_smooth_quadratic_to(relative, &mut current_elements)?;
451                parser.last_command = cmd;
452            }
453            b'A' => {
454                parser.handle_arc_to(relative, &mut current_elements)?;
455                parser.last_command = cmd;
456            }
457            b'Z' => {
458                // Close subpath
459                let dx = parser.current.x - parser.subpath_start.x;
460                let dy = parser.current.y - parser.subpath_start.y;
461                if dx * dx + dy * dy > CLOSEPATH_EPSILON * CLOSEPATH_EPSILON {
462                    current_elements.push(SvgPathElement::Line(SvgLine {
463                        start: parser.current,
464                        end: parser.subpath_start,
465                    }));
466                }
467                parser.current = parser.subpath_start;
468                parser.last_control = None;
469                parser.last_command = cmd;
470
471                // Flush current subpath
472                if !current_elements.is_empty() {
473                    rings.push(SvgPath {
474                        items: SvgPathElementVec::from_vec(core::mem::take(&mut current_elements)),
475                    });
476                }
477            }
478            _ => {
479                return Err(SvgPathParseError::UnexpectedChar {
480                    pos: parser.pos - 1,
481                    ch: cmd as char,
482                });
483            }
484        }
485
486        // After processing one argument group, try to consume more
487        // argument groups for the same command (implicit repeats)
488        if cmd_upper != b'M' && cmd_upper != b'Z' {
489            loop {
490                parser.skip_whitespace_and_commas();
491                if parser.at_end() {
492                    break;
493                }
494                let next = parser.peek().unwrap();
495                if next.is_ascii_alphabetic() {
496                    break; // Next command letter
497                }
498                if !parser.has_number() {
499                    break;
500                }
501
502                // Implicit repeat of the same command
503                match cmd_upper {
504                    b'L' => parser.handle_line_to(relative, &mut current_elements)?,
505                    b'H' => parser.handle_horizontal_to(relative, &mut current_elements)?,
506                    b'V' => parser.handle_vertical_to(relative, &mut current_elements)?,
507                    b'C' => parser.handle_cubic_to(relative, &mut current_elements)?,
508                    b'S' => parser.handle_smooth_cubic_to(relative, &mut current_elements)?,
509                    b'Q' => parser.handle_quadratic_to(relative, &mut current_elements)?,
510                    b'T' => parser.handle_smooth_quadratic_to(relative, &mut current_elements)?,
511                    b'A' => parser.handle_arc_to(relative, &mut current_elements)?,
512                    _ => break,
513                }
514            }
515        }
516    }
517
518    // Flush any remaining elements
519    if !current_elements.is_empty() {
520        rings.push(SvgPath {
521            items: SvgPathElementVec::from_vec(current_elements),
522        });
523    }
524
525    Ok(SvgMultiPolygon {
526        rings: SvgPathVec::from_vec(rings),
527    })
528}
529
530/// Convert an SVG arc to 1–4 cubic bezier curves.
531///
532/// Implements the SVG spec arc endpoint-to-center parameterization (Appendix F.6).
533#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
534// n_segs is a tiny arc-quadrant count (<= ~6) and its loop index; the float<->usize
535// casts are exact for these bounded values.
536#[allow(
537    clippy::cast_possible_truncation,
538    clippy::cast_precision_loss,
539    clippy::cast_sign_loss
540)]
541#[allow(clippy::similar_names)] // domain-standard coordinate/control-point names
542fn arc_to_cubics(
543    start: SvgPoint,
544    end: SvgPoint,
545    mut rx: f32,
546    mut ry: f32,
547    x_rotation_deg: f32,
548    large_arc: bool,
549    sweep: bool,
550    out: &mut Vec<SvgPathElement>,
551) {
552    // Degenerate cases
553    if (start.x - end.x).abs() < POINT_EPSILON && (start.y - end.y).abs() < POINT_EPSILON {
554        return;
555    }
556    if rx < POINT_EPSILON || ry < POINT_EPSILON {
557        out.push(SvgPathElement::Line(SvgLine { start, end }));
558        return;
559    }
560
561    let phi = x_rotation_deg.to_radians();
562    let cos_phi = phi.cos();
563    let sin_phi = phi.sin();
564
565    // Step 1: Compute (x1', y1')
566    let dx = (start.x - end.x) / 2.0;
567    let dy = (start.y - end.y) / 2.0;
568    let x1p = cos_phi * dx + sin_phi * dy;
569    let y1p = -sin_phi * dx + cos_phi * dy;
570
571    // Step 2: Compute (cx', cy') - correct radii if too small
572    let x1p2 = x1p * x1p;
573    let y1p2 = y1p * y1p;
574    let mut rx2 = rx * rx;
575    let mut ry2 = ry * ry;
576
577    let lambda = x1p2 / rx2 + y1p2 / ry2;
578    if lambda > 1.0 {
579        let sqrt_lambda = lambda.sqrt();
580        rx *= sqrt_lambda;
581        ry *= sqrt_lambda;
582        rx2 = rx * rx;
583        ry2 = ry * ry;
584    }
585
586    let num = (rx2 * ry2 - rx2 * y1p2 - ry2 * x1p2).max(0.0);
587    let den = rx2 * y1p2 + ry2 * x1p2;
588    let sq = if den > 0.0 {
589        (num / den).sqrt()
590    } else {
591        0.0
592    };
593
594    let sign = if large_arc == sweep { -1.0 } else { 1.0 };
595    let cxp = sign * sq * (rx * y1p / ry);
596    let cyp = sign * sq * -(ry * x1p / rx);
597
598    // Step 3: Compute (cx, cy) from (cx', cy')
599    let mx = f32::midpoint(start.x, end.x);
600    let my = f32::midpoint(start.y, end.y);
601    let cx = cos_phi * cxp - sin_phi * cyp + mx;
602    let cy = sin_phi * cxp + cos_phi * cyp + my;
603
604    // Step 4: Compute theta1 and dtheta
605    let theta1 = angle_between(1.0, 0.0, (x1p - cxp) / rx, (y1p - cyp) / ry);
606    let mut dtheta = angle_between(
607        (x1p - cxp) / rx,
608        (y1p - cyp) / ry,
609        (-x1p - cxp) / rx,
610        (-y1p - cyp) / ry,
611    );
612
613    if !sweep && dtheta > 0.0 {
614        dtheta -= core::f32::consts::TAU;
615    } else if sweep && dtheta < 0.0 {
616        dtheta += core::f32::consts::TAU;
617    }
618
619    // Split into segments of at most PI/2
620    let n_segs = (dtheta.abs() / (core::f32::consts::FRAC_PI_2 + ARC_SPLIT_FUDGE)).ceil() as usize;
621    let n_segs = n_segs.max(1);
622    let seg_angle = dtheta / n_segs as f32;
623
624    let mut prev = start;
625    for i in 0..n_segs {
626        let t1 = theta1 + seg_angle * i as f32;
627        let t2 = theta1 + seg_angle * (i + 1) as f32;
628
629        let (c1, c2, ep) =
630            arc_segment_to_cubic(cx, cy, rx, ry, cos_phi, sin_phi, t1, t2);
631
632        let seg_end = if i + 1 == n_segs { end } else { ep };
633        out.push(SvgPathElement::CubicCurve(SvgCubicCurve {
634            start: prev,
635            ctrl_1: c1,
636            ctrl_2: c2,
637            end: seg_end,
638        }));
639        prev = seg_end;
640    }
641}
642
643/// Compute the angle between two vectors.
644#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
645fn angle_between(ux: f32, uy: f32, vx: f32, vy: f32) -> f32 {
646    let dot = ux * vx + uy * vy;
647    let len = ((ux * ux + uy * uy) * (vx * vx + vy * vy)).sqrt();
648    if len < ZERO_LENGTH_EPSILON {
649        return 0.0;
650    }
651    let cos_val = (dot / len).clamp(-1.0, 1.0);
652    let angle = cos_val.acos();
653    if ux * vy - uy * vx < 0.0 {
654        -angle
655    } else {
656        angle
657    }
658}
659
660/// Convert a single arc segment (<=90 degrees) to a cubic bezier.
661#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
662#[allow(clippy::similar_names)] // domain-standard coordinate/control-point names
663fn arc_segment_to_cubic(
664    cx: f32,
665    cy: f32,
666    rx: f32,
667    ry: f32,
668    cos_phi: f32,
669    sin_phi: f32,
670    theta1: f32,
671    theta2: f32,
672) -> (SvgPoint, SvgPoint, SvgPoint) {
673    let alpha = 4.0 / 3.0 * ((theta2 - theta1) / 4.0).tan();
674
675    let cos1 = theta1.cos();
676    let sin1 = theta1.sin();
677    let cos2 = theta2.cos();
678    let sin2 = theta2.sin();
679
680    // Control point 1 (relative to unit circle)
681    let dx1 = rx * (cos1 - alpha * sin1);
682    let dy1 = ry * (sin1 + alpha * cos1);
683    // Control point 2
684    let dx2 = rx * (cos2 + alpha * sin2);
685    let dy2 = ry * (sin2 - alpha * cos2);
686    // End point
687    let dx3 = rx * cos2;
688    let dy3 = ry * sin2;
689
690    let c1 = SvgPoint {
691        x: cos_phi * dx1 - sin_phi * dy1 + cx,
692        y: sin_phi * dx1 + cos_phi * dy1 + cy,
693    };
694    let c2 = SvgPoint {
695        x: cos_phi * dx2 - sin_phi * dy2 + cx,
696        y: sin_phi * dx2 + cos_phi * dy2 + cy,
697    };
698    let ep = SvgPoint {
699        x: cos_phi * dx3 - sin_phi * dy3 + cx,
700        y: sin_phi * dx3 + cos_phi * dy3 + cy,
701    };
702
703    (c1, c2, ep)
704}
705
706/// Approximate a circle with 4 cubic bezier curves.
707///
708/// Uses the standard kappa constant (0.5522847498) for quarter-arc approximation.
709#[must_use]
710pub fn svg_circle_to_paths(cx: f32, cy: f32, r: f32) -> SvgPath {
711    let k = r * KAPPA;
712
713    let elements = vec![
714        // Top to right
715        SvgPathElement::CubicCurve(SvgCubicCurve {
716            start: SvgPoint { x: cx, y: cy - r },
717            ctrl_1: SvgPoint {
718                x: cx + k,
719                y: cy - r,
720            },
721            ctrl_2: SvgPoint {
722                x: cx + r,
723                y: cy - k,
724            },
725            end: SvgPoint { x: cx + r, y: cy },
726        }),
727        // Right to bottom
728        SvgPathElement::CubicCurve(SvgCubicCurve {
729            start: SvgPoint { x: cx + r, y: cy },
730            ctrl_1: SvgPoint {
731                x: cx + r,
732                y: cy + k,
733            },
734            ctrl_2: SvgPoint {
735                x: cx + k,
736                y: cy + r,
737            },
738            end: SvgPoint { x: cx, y: cy + r },
739        }),
740        // Bottom to left
741        SvgPathElement::CubicCurve(SvgCubicCurve {
742            start: SvgPoint { x: cx, y: cy + r },
743            ctrl_1: SvgPoint {
744                x: cx - k,
745                y: cy + r,
746            },
747            ctrl_2: SvgPoint {
748                x: cx - r,
749                y: cy + k,
750            },
751            end: SvgPoint { x: cx - r, y: cy },
752        }),
753        // Left to top
754        SvgPathElement::CubicCurve(SvgCubicCurve {
755            start: SvgPoint { x: cx - r, y: cy },
756            ctrl_1: SvgPoint {
757                x: cx - r,
758                y: cy - k,
759            },
760            ctrl_2: SvgPoint {
761                x: cx - k,
762                y: cy - r,
763            },
764            end: SvgPoint { x: cx, y: cy - r },
765        }),
766    ];
767
768    SvgPath {
769        items: SvgPathElementVec::from_vec(elements),
770    }
771}
772
773/// Convert an SVG `<rect>` to a path with optional rounded corners.
774///
775/// If `rx` and `ry` are both 0, produces 4 line segments.
776/// Otherwise, produces lines for straight edges and cubic curves for corners.
777#[must_use]
778// builds the rounded-rect path segment-by-segment with a matching capacity hint;
779// a `vec![..]` literal of the 8 multi-line elements would be less readable here.
780#[allow(clippy::vec_init_then_push)]
781#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
782pub fn svg_rect_to_path(x: f32, y: f32, w: f32, h: f32, rx: f32, ry: f32) -> SvgPath {
783    let rx = rx.min(w / 2.0);
784    let ry = ry.min(h / 2.0);
785
786    if rx < CLOSEPATH_EPSILON && ry < CLOSEPATH_EPSILON {
787        // Simple rectangle: 4 lines
788        let tl = SvgPoint { x, y };
789        let tr = SvgPoint { x: x + w, y };
790        let br = SvgPoint { x: x + w, y: y + h };
791        let bl = SvgPoint { x, y: y + h };
792
793        let elements = vec![
794            SvgPathElement::Line(SvgLine { start: tl, end: tr }),
795            SvgPathElement::Line(SvgLine { start: tr, end: br }),
796            SvgPathElement::Line(SvgLine {
797                start: br,
798                end: bl,
799            }),
800            SvgPathElement::Line(SvgLine { start: bl, end: tl }),
801        ];
802
803        return SvgPath {
804            items: SvgPathElementVec::from_vec(elements),
805        };
806    }
807
808    // Rounded rectangle
809    let kx = rx * KAPPA;
810    let ky = ry * KAPPA;
811
812    let mut elements = Vec::with_capacity(8);
813
814    // Top edge (left to right)
815    elements.push(SvgPathElement::Line(SvgLine {
816        start: SvgPoint { x: x + rx, y },
817        end: SvgPoint { x: x + w - rx, y },
818    }));
819    // Top-right corner
820    elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
821        start: SvgPoint { x: x + w - rx, y },
822        ctrl_1: SvgPoint {
823            x: x + w - rx + kx,
824            y,
825        },
826        ctrl_2: SvgPoint {
827            x: x + w,
828            y: y + ry - ky,
829        },
830        end: SvgPoint {
831            x: x + w,
832            y: y + ry,
833        },
834    }));
835    // Right edge
836    elements.push(SvgPathElement::Line(SvgLine {
837        start: SvgPoint {
838            x: x + w,
839            y: y + ry,
840        },
841        end: SvgPoint {
842            x: x + w,
843            y: y + h - ry,
844        },
845    }));
846    // Bottom-right corner
847    elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
848        start: SvgPoint {
849            x: x + w,
850            y: y + h - ry,
851        },
852        ctrl_1: SvgPoint {
853            x: x + w,
854            y: y + h - ry + ky,
855        },
856        ctrl_2: SvgPoint {
857            x: x + w - rx + kx,
858            y: y + h,
859        },
860        end: SvgPoint {
861            x: x + w - rx,
862            y: y + h,
863        },
864    }));
865    // Bottom edge (right to left)
866    elements.push(SvgPathElement::Line(SvgLine {
867        start: SvgPoint {
868            x: x + w - rx,
869            y: y + h,
870        },
871        end: SvgPoint { x: x + rx, y: y + h },
872    }));
873    // Bottom-left corner
874    elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
875        start: SvgPoint { x: x + rx, y: y + h },
876        ctrl_1: SvgPoint {
877            x: x + rx - kx,
878            y: y + h,
879        },
880        ctrl_2: SvgPoint {
881            x,
882            y: y + h - ry + ky,
883        },
884        end: SvgPoint { x, y: y + h - ry },
885    }));
886    // Left edge
887    elements.push(SvgPathElement::Line(SvgLine {
888        start: SvgPoint { x, y: y + h - ry },
889        end: SvgPoint { x, y: y + ry },
890    }));
891    // Top-left corner
892    elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
893        start: SvgPoint { x, y: y + ry },
894        ctrl_1: SvgPoint {
895            x,
896            y: y + ry - ky,
897        },
898        ctrl_2: SvgPoint {
899            x: x + rx - kx,
900            y,
901        },
902        end: SvgPoint { x: x + rx, y },
903    }));
904
905    SvgPath {
906        items: SvgPathElementVec::from_vec(elements),
907    }
908}
909
910#[cfg(test)]
911mod tests {
912    use super::*;
913
914    /// AUDIT 2026-07-08 regression: `"M0 0Z5"` used to spin at 100% CPU forever
915    /// because the trailing `5` re-derived `cmd = Z` (zero-length consume) and
916    /// the cursor never advanced. It must now terminate with `UnexpectedChar`.
917    #[test]
918    fn m0_0z5_does_not_hang() {
919        let err = parse_svg_path_d("M0 0Z5").unwrap_err();
920        match err {
921            SvgPathParseError::UnexpectedChar { ch, .. } => assert_eq!(ch, '5'),
922            other => panic!("expected UnexpectedChar, got {other:?}"),
923        }
924    }
925
926    /// Any digit or symbol directly after a closepath is rejected, not looped on.
927    #[test]
928    fn stray_byte_after_closepath_rejected() {
929        for s in ["M0 0Z9", "m0 0z-", "M0 0Z."] {
930            assert!(
931                matches!(
932                    parse_svg_path_d(s),
933                    Err(SvgPathParseError::UnexpectedChar { .. })
934                ),
935                "expected UnexpectedChar for {s:?}"
936            );
937        }
938    }
939
940    /// A leading non-command byte reports the real Unicode char, not a Latin-1
941    /// reinterpretation of a single UTF-8 byte (the old `b as char`).
942    #[test]
943    fn error_char_is_unicode_not_byte() {
944        // 'ü' is two UTF-8 bytes; `b as char` would have yielded a mojibake char.
945        let err = parse_svg_path_d("ü10 10").unwrap_err();
946        match err {
947            SvgPathParseError::UnexpectedChar { ch, pos } => {
948                assert_eq!(ch, 'ü');
949                assert_eq!(pos, 0);
950            }
951            other => panic!("expected UnexpectedChar, got {other:?}"),
952        }
953    }
954
955    /// A well-formed closepath followed by a real command still parses.
956    #[test]
957    fn valid_closepath_then_command_ok() {
958        let parsed = parse_svg_path_d("M0 0 L10 0 Z M20 20 L30 20 Z");
959        assert!(parsed.is_ok(), "valid multi-subpath path should parse");
960    }
961}
962
963#[cfg(test)]
964#[allow(clippy::float_cmp)] // exact float equality is the point: the parser propagates values bit-for-bit
965mod autotest_generated {
966    use alloc::format;
967
968    use super::*;
969
970    // ---------------------------------------------------------------- helpers
971
972    fn approx(a: f32, b: f32) -> bool {
973        (a - b).abs() < 1e-4
974    }
975
976    /// Every point produced by a path, in element order.
977    fn all_points(path: &SvgPath) -> Vec<SvgPoint> {
978        let mut out = Vec::new();
979        for e in path.items.as_ref() {
980            match e {
981                SvgPathElement::Line(l) => {
982                    out.push(l.start);
983                    out.push(l.end);
984                }
985                SvgPathElement::QuadraticCurve(q) => {
986                    out.push(q.start);
987                    out.push(q.ctrl);
988                    out.push(q.end);
989                }
990                SvgPathElement::CubicCurve(c) => {
991                    out.push(c.start);
992                    out.push(c.ctrl_1);
993                    out.push(c.ctrl_2);
994                    out.push(c.end);
995                }
996            }
997        }
998        out
999    }
1000
1001    /// Each element's end must be the next element's start (the parser threads
1002    /// `self.current` through every handler, so this holds bit-for-bit).
1003    fn assert_contiguous(items: &[SvgPathElement], what: &str) {
1004        for w in items.windows(2) {
1005            assert_eq!(
1006                w[0].get_end(),
1007                w[1].get_start(),
1008                "{what}: element chain is not contiguous"
1009            );
1010        }
1011    }
1012
1013    // ======================================================= char_at (numeric)
1014
1015    #[test]
1016    fn char_at_zero_and_ascii() {
1017        assert_eq!(char_at(b"M0 0", 0), 'M');
1018        assert_eq!(char_at(b"M0 0", 3), ' ');
1019    }
1020
1021    #[test]
1022    fn char_at_empty_input_is_replacement() {
1023        assert_eq!(char_at(b"", 0), char::REPLACEMENT_CHARACTER);
1024    }
1025
1026    #[test]
1027    fn char_at_past_end_is_replacement_not_panic() {
1028        assert_eq!(char_at(b"abc", 3), char::REPLACEMENT_CHARACTER);
1029        assert_eq!(char_at(b"abc", 4), char::REPLACEMENT_CHARACTER);
1030    }
1031
1032    /// `pos = usize::MAX` must be a `get(pos..)` miss, not an arithmetic panic.
1033    #[test]
1034    fn char_at_usize_max_is_replacement() {
1035        assert_eq!(char_at(b"abc", usize::MAX), char::REPLACEMENT_CHARACTER);
1036        assert_eq!(char_at(b"", usize::MAX), char::REPLACEMENT_CHARACTER);
1037    }
1038
1039    /// The whole point of `char_at`: report the real char, not one UTF-8 byte.
1040    #[test]
1041    fn char_at_decodes_multibyte_not_latin1() {
1042        assert_eq!(char_at("ü".as_bytes(), 0), 'ü');
1043        assert_eq!(char_at("€".as_bytes(), 0), '€');
1044        assert_eq!(char_at("\u{1F600}".as_bytes(), 0), '\u{1F600}');
1045    }
1046
1047    /// A corrupt (mid-codepoint) offset falls back rather than panicking.
1048    #[test]
1049    fn char_at_mid_codepoint_offset_is_replacement() {
1050        let bytes = "😀".as_bytes(); // 4 bytes
1051        for pos in 1..bytes.len() {
1052            assert_eq!(
1053                char_at(bytes, pos),
1054                char::REPLACEMENT_CHARACTER,
1055                "mid-codepoint offset {pos} must not panic"
1056            );
1057        }
1058    }
1059
1060    /// Trailing garbage after a valid char makes the *whole rest* invalid UTF-8,
1061    /// so even a valid leading char decodes to the replacement char. Pinned as
1062    /// deterministic (never a panic).
1063    #[test]
1064    fn char_at_invalid_utf8_tail_is_replacement() {
1065        assert_eq!(char_at(&[b'A', 0xFF], 0), char::REPLACEMENT_CHARACTER);
1066        assert_eq!(char_at(&[0xFF], 0), char::REPLACEMENT_CHARACTER);
1067        // ...but a clean tail after the char still decodes.
1068        assert_eq!(char_at(&[b'A', b'B'], 0), 'A');
1069    }
1070
1071    // ============================================ SvgPathParseError (serializer)
1072
1073    #[test]
1074    fn error_display_is_non_empty_for_every_variant() {
1075        let variants = [
1076            SvgPathParseError::EmptyPath,
1077            SvgPathParseError::UnexpectedChar { pos: 0, ch: 'x' },
1078            SvgPathParseError::ExpectedNumber { pos: 0 },
1079            SvgPathParseError::InvalidArcFlag { pos: 0 },
1080        ];
1081        for v in variants {
1082            let s = format!("{v}");
1083            assert!(!s.is_empty(), "Display for {v:?} must not be empty");
1084            assert!(!format!("{v:?}").is_empty(), "Debug must not be empty");
1085        }
1086    }
1087
1088    #[test]
1089    fn error_display_edge_values_do_not_panic() {
1090        let s = format!(
1091            "{}",
1092            SvgPathParseError::UnexpectedChar {
1093                pos: usize::MAX,
1094                ch: char::REPLACEMENT_CHARACTER,
1095            }
1096        );
1097        assert!(s.contains(&format!("{}", usize::MAX)));
1098        assert!(s.contains(char::REPLACEMENT_CHARACTER));
1099
1100        // NUL, an emoji and a combining mark all format without panicking.
1101        for ch in ['\0', '\u{1F600}', '\u{0301}'] {
1102            let s = format!("{}", SvgPathParseError::UnexpectedChar { pos: 0, ch });
1103            assert!(!s.is_empty());
1104        }
1105        assert!(!format!("{}", SvgPathParseError::ExpectedNumber { pos: usize::MAX }).is_empty());
1106        assert!(!format!("{}", SvgPathParseError::InvalidArcFlag { pos: usize::MAX }).is_empty());
1107    }
1108
1109    // ================================================= PathParser::new / getters
1110
1111    #[test]
1112    fn parser_new_invariants_hold() {
1113        let p = PathParser::new(b"M0 0");
1114        assert_eq!(p.pos, 0);
1115        assert_eq!(p.current, SvgPoint { x: 0.0, y: 0.0 });
1116        assert_eq!(p.subpath_start, SvgPoint { x: 0.0, y: 0.0 });
1117        assert!(p.last_control.is_none());
1118        assert_eq!(p.last_command, 0);
1119        assert_eq!(p.input.len(), 4);
1120    }
1121
1122    #[test]
1123    fn parser_new_on_empty_input_does_not_panic() {
1124        let p = PathParser::new(b"");
1125        assert!(p.at_end(), "empty input is immediately at_end");
1126        assert_eq!(p.peek(), None);
1127        assert!(!p.has_number());
1128    }
1129
1130    #[test]
1131    fn at_end_and_peek_agree_across_the_whole_input() {
1132        let mut p = PathParser::new(b"ab");
1133        assert!(!p.at_end());
1134        assert_eq!(p.peek(), Some(b'a'));
1135        p.pos = 1;
1136        assert!(!p.at_end());
1137        assert_eq!(p.peek(), Some(b'b'));
1138        p.pos = 2;
1139        assert!(p.at_end());
1140        assert_eq!(p.peek(), None);
1141    }
1142
1143    /// A cursor pushed far past the end must report `at_end` / `None`, never panic.
1144    #[test]
1145    fn peek_and_at_end_at_extreme_positions() {
1146        let mut p = PathParser::new(b"abc");
1147        p.pos = usize::MAX;
1148        assert!(p.at_end());
1149        assert_eq!(p.peek(), None);
1150        assert!(!p.has_number());
1151    }
1152
1153    // ============================================================ skip_* (other)
1154
1155    #[test]
1156    fn skip_whitespace_and_commas_consumes_all_separators() {
1157        let mut p = PathParser::new(b" \t\r\n,,, \tX");
1158        p.skip_whitespace_and_commas();
1159        assert_eq!(p.peek(), Some(b'X'));
1160    }
1161
1162    /// `skip_whitespace` must *not* eat commas (they are only argument separators).
1163    #[test]
1164    fn skip_whitespace_stops_at_comma() {
1165        let mut p = PathParser::new(b"  ,1");
1166        p.skip_whitespace();
1167        assert_eq!(p.peek(), Some(b','));
1168        assert_eq!(p.pos, 2);
1169    }
1170
1171    #[test]
1172    fn skip_on_empty_and_all_separator_input_terminates() {
1173        let mut p = PathParser::new(b"");
1174        p.skip_whitespace();
1175        p.skip_whitespace_and_commas();
1176        assert!(p.at_end());
1177
1178        let all_ws = " \t\r\n,".repeat(20_000);
1179        let mut p = PathParser::new(all_ws.as_bytes());
1180        p.skip_whitespace_and_commas();
1181        assert!(p.at_end(), "a huge run of separators must be fully consumed");
1182        assert_eq!(p.pos, all_ws.len());
1183    }
1184
1185    /// Non-separator input leaves the cursor exactly where it was.
1186    #[test]
1187    fn skip_is_a_no_op_on_non_separator() {
1188        let mut p = PathParser::new("😀".as_bytes());
1189        p.skip_whitespace_and_commas();
1190        assert_eq!(p.pos, 0);
1191        // Form feed / vertical tab are NOT SVG wsp; the parser must leave them.
1192        let mut p = PathParser::new(b"\x0c\x0b1");
1193        p.skip_whitespace();
1194        assert_eq!(p.pos, 0);
1195    }
1196
1197    // ======================================================= has_number (predicate)
1198
1199    #[test]
1200    fn has_number_true_for_number_starters() {
1201        for s in ["0", "9", "+", "-", ".", "5.5", "-.5"] {
1202            assert!(
1203                PathParser::new(s.as_bytes()).has_number(),
1204                "{s:?} should look like a number start"
1205            );
1206        }
1207    }
1208
1209    #[test]
1210    fn has_number_false_for_non_number_starters() {
1211        // Note 'e'/'E' only appear *inside* a number, never at its start.
1212        for s in ["", " ", ",", "M", "z", "e", "E", "😀", "\u{0301}"] {
1213            assert!(
1214                !PathParser::new(s.as_bytes()).has_number(),
1215                "{s:?} should not look like a number start"
1216            );
1217        }
1218    }
1219
1220    // ========================================================= parse_number (parser)
1221
1222    fn num(s: &str) -> Result<f32, SvgPathParseError> {
1223        PathParser::new(s.as_bytes()).parse_number()
1224    }
1225
1226    #[test]
1227    fn parse_number_valid_minimal() {
1228        assert_eq!(num("0").unwrap(), 0.0);
1229        assert_eq!(num("5").unwrap(), 5.0);
1230        assert_eq!(num("+5").unwrap(), 5.0);
1231        assert_eq!(num("-5").unwrap(), -5.0);
1232        assert!(approx(num("12.34").unwrap(), 12.34));
1233        assert!(approx(num(".5").unwrap(), 0.5));
1234        assert_eq!(num("5.").unwrap(), 5.0);
1235        assert!(approx(num("1e2").unwrap(), 100.0));
1236        assert!(approx(num("1E-2").unwrap(), 0.01));
1237        assert!(approx(num("  ,, 7").unwrap(), 7.0), "leading separators skipped");
1238    }
1239
1240    #[test]
1241    fn parse_number_empty_input_is_err() {
1242        assert_eq!(num(""), Err(SvgPathParseError::ExpectedNumber { pos: 0 }));
1243    }
1244
1245    /// Whitespace-only input reports the position *after* the skipped separators.
1246    #[test]
1247    fn parse_number_whitespace_only_is_err() {
1248        assert_eq!(num("   "), Err(SvgPathParseError::ExpectedNumber { pos: 3 }));
1249        assert_eq!(num("\t\n"), Err(SvgPathParseError::ExpectedNumber { pos: 2 }));
1250        assert_eq!(num(" , "), Err(SvgPathParseError::ExpectedNumber { pos: 3 }));
1251    }
1252
1253    #[test]
1254    fn parse_number_garbage_is_err_never_panics() {
1255        for s in ["abc", "@", "#$%", "-", "+", ".", "-.", "+.", "e5", "NaN", "inf", "-inf"] {
1256            assert!(
1257                matches!(num(s), Err(SvgPathParseError::ExpectedNumber { .. })),
1258                "{s:?} must be rejected, got {:?}",
1259                num(s)
1260            );
1261        }
1262    }
1263
1264    /// A dangling exponent is consumed by the tokenizer but rejected by `f32::from_str`.
1265    #[test]
1266    fn parse_number_dangling_exponent_is_err() {
1267        for s in ["1e", "1E", "1e+", "1e-", "1.5e"] {
1268            assert!(
1269                matches!(num(s), Err(SvgPathParseError::ExpectedNumber { pos: 0 })),
1270                "{s:?} must be rejected"
1271            );
1272        }
1273    }
1274
1275    #[test]
1276    fn parse_number_unicode_does_not_panic() {
1277        for s in ["😀", "\u{0301}", "ü", "€1", "1"] {
1278            assert!(matches!(num(s), Err(_)), "{s:?} must be rejected");
1279        }
1280        // A number immediately followed by a multibyte char stops at the boundary.
1281        let mut p = PathParser::new("1😀".as_bytes());
1282        assert_eq!(p.parse_number().unwrap(), 1.0);
1283        assert_eq!(p.pos, 1);
1284    }
1285
1286    /// Boundary numerics: overflow saturates to +/-inf, underflow flushes to zero,
1287    /// and `-0` keeps its sign. None of these panic.
1288    #[test]
1289    fn parse_number_boundary_values_saturate() {
1290        assert!(num("-0").unwrap().is_sign_negative(), "-0 keeps its sign bit");
1291        assert_eq!(num("-0").unwrap(), -0.0);
1292
1293        assert!(num("1e999").unwrap().is_infinite());
1294        assert!(num("1e999").unwrap().is_sign_positive());
1295        assert!(num("-1e999").unwrap().is_infinite());
1296        assert!(num("-1e999").unwrap().is_sign_negative());
1297
1298        assert_eq!(num("1e-999").unwrap(), 0.0, "underflow flushes to zero");
1299
1300        // i64::MAX / f32 extremes round to a finite f32.
1301        assert!(num("9223372036854775807").unwrap().is_finite());
1302        assert!(num("340282350000000000000000000000000000000").unwrap().is_finite());
1303        // Just past f32::MAX -> +inf, not a panic.
1304        assert!(num("1e39").unwrap().is_infinite());
1305    }
1306
1307    /// A 20k-digit literal must not hang or panic; it saturates to +inf.
1308    #[test]
1309    fn parse_number_extremely_long_input_terminates() {
1310        let huge = "9".repeat(20_000);
1311        assert!(num(&huge).unwrap().is_infinite());
1312
1313        let long_frac = format!("0.{}", "0".repeat(20_000));
1314        assert_eq!(num(&long_frac).unwrap(), 0.0);
1315
1316        let long_zeros = format!("{}1", "0".repeat(20_000));
1317        assert_eq!(num(&long_zeros).unwrap(), 1.0);
1318    }
1319
1320    /// Trailing junk is left on the cursor rather than swallowed: `"1.2.3"` yields
1321    /// `1.2` and stops at the second dot (SVG's own "1.5.5" == two numbers rule).
1322    #[test]
1323    fn parse_number_stops_at_trailing_junk() {
1324        let mut p = PathParser::new(b"1.2.3");
1325        assert!(approx(p.parse_number().unwrap(), 1.2));
1326        assert_eq!(p.pos, 3, "second '.' must not be consumed");
1327
1328        let mut p = PathParser::new(b"5;garbage");
1329        assert_eq!(p.parse_number().unwrap(), 5.0);
1330        assert_eq!(p.peek(), Some(b';'));
1331    }
1332
1333    /// The cursor is never advanced past the end of the input, whatever happens.
1334    #[test]
1335    fn parse_number_never_overruns_the_buffer() {
1336        for s in ["", "-", ".", "1e", "1e+", "1.", "+.e", "1e-", "999"] {
1337            let mut p = PathParser::new(s.as_bytes());
1338            let _ = p.parse_number();
1339            assert!(p.pos <= s.len(), "{s:?}: pos {} > len {}", p.pos, s.len());
1340        }
1341    }
1342
1343    // =========================================================== parse_flag (parser)
1344
1345    fn flag(s: &str) -> Result<bool, SvgPathParseError> {
1346        PathParser::new(s.as_bytes()).parse_flag()
1347    }
1348
1349    #[test]
1350    fn parse_flag_valid_minimal() {
1351        assert_eq!(flag("0").unwrap(), false);
1352        assert_eq!(flag("1").unwrap(), true);
1353        assert_eq!(flag("  , 1").unwrap(), true, "separators are skipped first");
1354    }
1355
1356    /// A flag is exactly one byte: "11" is two flags, not the number eleven.
1357    #[test]
1358    fn parse_flag_consumes_exactly_one_byte() {
1359        let mut p = PathParser::new(b"10");
1360        assert_eq!(p.parse_flag().unwrap(), true);
1361        assert_eq!(p.pos, 1);
1362        assert_eq!(p.parse_flag().unwrap(), false);
1363        assert_eq!(p.pos, 2);
1364    }
1365
1366    #[test]
1367    fn parse_flag_empty_and_whitespace_only_are_err() {
1368        assert_eq!(flag(""), Err(SvgPathParseError::InvalidArcFlag { pos: 0 }));
1369        assert_eq!(flag("   "), Err(SvgPathParseError::InvalidArcFlag { pos: 3 }));
1370    }
1371
1372    /// Any byte other than `0`/`1` is rejected and the cursor stays put.
1373    #[test]
1374    fn parse_flag_garbage_is_err_and_does_not_advance() {
1375        for s in ["2", "9", "-1", "+1", "x", ".", "😀", "0.5"] {
1376            let mut p = PathParser::new(s.as_bytes());
1377            let before = p.pos;
1378            match p.parse_flag() {
1379                Err(SvgPathParseError::InvalidArcFlag { pos }) => {
1380                    assert_eq!(pos, p.pos, "{s:?}: reported pos must be the cursor");
1381                    assert_eq!(p.pos, before, "{s:?}: rejected flag must not advance");
1382                }
1383                // "0.5" legitimately parses its leading '0' as the flag.
1384                Ok(v) => assert!(s == "0.5" && !v, "{s:?} unexpectedly parsed as {v}"),
1385                other => panic!("{s:?}: unexpected {other:?}"),
1386            }
1387        }
1388    }
1389
1390    /// A 100k-byte separator run followed by no flag terminates with an error.
1391    #[test]
1392    fn parse_flag_extremely_long_separator_run_terminates() {
1393        let s = " ".repeat(100_000);
1394        assert_eq!(
1395            flag(&s),
1396            Err(SvgPathParseError::InvalidArcFlag { pos: 100_000 })
1397        );
1398    }
1399
1400    // ================================================ parse_coordinate_pair (parser)
1401
1402    fn pair(s: &str) -> Result<(f32, f32), SvgPathParseError> {
1403        PathParser::new(s.as_bytes()).parse_coordinate_pair()
1404    }
1405
1406    #[test]
1407    fn parse_coordinate_pair_valid_minimal() {
1408        assert_eq!(pair("1 2").unwrap(), (1.0, 2.0));
1409        assert_eq!(pair("1,2").unwrap(), (1.0, 2.0));
1410        assert_eq!(pair(" 1 , 2 ").unwrap(), (1.0, 2.0));
1411        // SVG allows a sign to act as the separator.
1412        assert_eq!(pair("-1-2").unwrap(), (-1.0, -2.0));
1413    }
1414
1415    /// SVG's notorious "1.5.5" == (1.5, 0.5) tokenization.
1416    #[test]
1417    fn parse_coordinate_pair_splits_on_second_dot() {
1418        let (x, y) = pair("1.5.5").unwrap();
1419        assert!(approx(x, 1.5) && approx(y, 0.5), "got ({x}, {y})");
1420    }
1421
1422    #[test]
1423    fn parse_coordinate_pair_empty_and_partial_are_err() {
1424        assert!(pair("").is_err());
1425        assert!(pair("   ").is_err());
1426        assert!(pair("1").is_err(), "a lone x with no y must be rejected");
1427        assert!(pair("1 ").is_err());
1428        assert!(pair("1,").is_err());
1429    }
1430
1431    #[test]
1432    fn parse_coordinate_pair_garbage_and_unicode_are_err() {
1433        for s in ["abc", "1 abc", "😀 1", "1 😀", ";;", "1;2"] {
1434            assert!(pair(s).is_err(), "{s:?} must be rejected");
1435        }
1436    }
1437
1438    #[test]
1439    fn parse_coordinate_pair_boundary_values() {
1440        let (x, y) = pair("1e999 -1e999").unwrap();
1441        assert!(x.is_infinite() && x.is_sign_positive());
1442        assert!(y.is_infinite() && y.is_sign_negative());
1443
1444        let (x, y) = pair("-0 0").unwrap();
1445        assert!(x.is_sign_negative() && y.is_sign_positive());
1446    }
1447
1448    #[test]
1449    fn parse_coordinate_pair_extremely_long_input_terminates() {
1450        let s = format!("{} {}", "9".repeat(10_000), "9".repeat(10_000));
1451        let (x, y) = pair(&s).unwrap();
1452        assert!(x.is_infinite() && y.is_infinite());
1453    }
1454
1455    // ======================================================= make_absolute (numeric)
1456
1457    #[test]
1458    fn make_absolute_zero_and_absolute_mode_is_identity() {
1459        let mut p = PathParser::new(b"");
1460        p.current = SvgPoint { x: 7.0, y: -3.0 };
1461        // Absolute: current is ignored entirely.
1462        assert_eq!(p.make_absolute(0.0, 0.0, false), SvgPoint { x: 0.0, y: 0.0 });
1463        assert_eq!(p.make_absolute(1.0, 2.0, false), SvgPoint { x: 1.0, y: 2.0 });
1464        // Relative: offsets from current.
1465        assert_eq!(p.make_absolute(0.0, 0.0, true), SvgPoint { x: 7.0, y: -3.0 });
1466        assert_eq!(p.make_absolute(-7.0, 3.0, true), SvgPoint { x: 0.0, y: 0.0 });
1467    }
1468
1469    #[test]
1470    fn make_absolute_negative_inputs() {
1471        let mut p = PathParser::new(b"");
1472        p.current = SvgPoint { x: -10.0, y: -10.0 };
1473        assert_eq!(p.make_absolute(-5.0, -5.0, true), SvgPoint { x: -15.0, y: -15.0 });
1474        assert_eq!(p.make_absolute(-5.0, -5.0, false), SvgPoint { x: -5.0, y: -5.0 });
1475    }
1476
1477    /// f32 addition saturates to infinity; it never wraps or debug-panics.
1478    #[test]
1479    fn make_absolute_overflow_saturates_to_infinity() {
1480        let mut p = PathParser::new(b"");
1481        p.current = SvgPoint {
1482            x: f32::MAX,
1483            y: f32::MIN,
1484        };
1485        let r = p.make_absolute(f32::MAX, f32::MIN, true);
1486        assert!(r.x.is_infinite() && r.x.is_sign_positive());
1487        assert!(r.y.is_infinite() && r.y.is_sign_negative());
1488    }
1489
1490    #[test]
1491    fn make_absolute_nan_and_inf_are_defined_not_panics() {
1492        let mut p = PathParser::new(b"");
1493        p.current = SvgPoint {
1494            x: f32::INFINITY,
1495            y: 0.0,
1496        };
1497        // inf + (-inf) is NaN by IEEE-754 -- defined, not a panic.
1498        let r = p.make_absolute(f32::NEG_INFINITY, f32::NAN, true);
1499        assert!(r.x.is_nan(), "inf + -inf must be NaN");
1500        assert!(r.y.is_nan());
1501
1502        // Absolute mode passes NaN straight through.
1503        let r = p.make_absolute(f32::NAN, f32::INFINITY, false);
1504        assert!(r.x.is_nan());
1505        assert!(r.y.is_infinite());
1506    }
1507
1508    // ============================================================ handle_* (other)
1509
1510    /// Drive one handler over `input` starting from `current`, returning the
1511    /// pushed elements plus the parser's post-state.
1512    fn run_handler<F>(
1513        input: &str,
1514        current: SvgPoint,
1515        last_command: u8,
1516        last_control: Option<SvgPoint>,
1517        f: F,
1518    ) -> (Result<(), SvgPathParseError>, Vec<SvgPathElement>, SvgPoint)
1519    where
1520        F: FnOnce(&mut PathParser<'_>, &mut Vec<SvgPathElement>) -> Result<(), SvgPathParseError>,
1521    {
1522        let mut p = PathParser::new(input.as_bytes());
1523        p.current = current;
1524        p.last_command = last_command;
1525        p.last_control = last_control;
1526        let mut els = Vec::new();
1527        let r = f(&mut p, &mut els);
1528        (r, els, p.current)
1529    }
1530
1531    const ORIGIN: SvgPoint = SvgPoint { x: 0.0, y: 0.0 };
1532
1533    #[test]
1534    fn handle_line_to_absolute_and_relative() {
1535        let start = SvgPoint { x: 10.0, y: 10.0 };
1536        let (r, els, cur) = run_handler("5 5", start, b'L', None, |p, e| p.handle_line_to(false, e));
1537        assert!(r.is_ok());
1538        assert_eq!(els.len(), 1);
1539        assert_eq!(els[0].get_start(), start);
1540        assert_eq!(els[0].get_end(), SvgPoint { x: 5.0, y: 5.0 });
1541        assert_eq!(cur, SvgPoint { x: 5.0, y: 5.0 });
1542
1543        let (r, els, cur) = run_handler("5 5", start, b'l', None, |p, e| p.handle_line_to(true, e));
1544        assert!(r.is_ok());
1545        assert_eq!(els[0].get_end(), SvgPoint { x: 15.0, y: 15.0 });
1546        assert_eq!(cur, SvgPoint { x: 15.0, y: 15.0 });
1547    }
1548
1549    /// H keeps y, V keeps x -- including when the incoming coordinate is infinite.
1550    #[test]
1551    fn handle_horizontal_and_vertical_preserve_the_other_axis() {
1552        let start = SvgPoint { x: 3.0, y: 4.0 };
1553        let (_, els, _) = run_handler("9", start, b'H', None, |p, e| p.handle_horizontal_to(false, e));
1554        assert_eq!(els[0].get_end(), SvgPoint { x: 9.0, y: 4.0 });
1555
1556        let (_, els, _) = run_handler("9", start, b'V', None, |p, e| p.handle_vertical_to(false, e));
1557        assert_eq!(els[0].get_end(), SvgPoint { x: 3.0, y: 9.0 });
1558
1559        let (_, els, _) = run_handler("1e999", start, b'h', None, |p, e| p.handle_horizontal_to(true, e));
1560        let end = els[0].get_end();
1561        assert!(end.x.is_infinite(), "relative H by +inf saturates");
1562        assert_eq!(end.y, 4.0, "y must be untouched");
1563    }
1564
1565    #[test]
1566    fn handlers_reject_empty_and_garbage_input_without_panicking() {
1567        for input in ["", "   ", "abc", "😀", ";", "1"] {
1568            // Each handler needs >= 1 number; "1" is enough only for H/V.
1569            let (r, _, _) = run_handler(input, ORIGIN, 0, None, |p, e| p.handle_line_to(false, e));
1570            assert!(r.is_err(), "line_to({input:?}) must be Err");
1571
1572            let (r, _, _) = run_handler(input, ORIGIN, 0, None, |p, e| p.handle_cubic_to(false, e));
1573            assert!(r.is_err(), "cubic_to({input:?}) must be Err");
1574
1575            let (r, _, _) = run_handler(input, ORIGIN, 0, None, |p, e| p.handle_quadratic_to(false, e));
1576            assert!(r.is_err(), "quadratic_to({input:?}) must be Err");
1577
1578            let (r, _, _) = run_handler(input, ORIGIN, 0, None, |p, e| p.handle_arc_to(false, e));
1579            assert!(r.is_err(), "arc_to({input:?}) must be Err");
1580
1581            if input != "1" {
1582                let (r, _, _) =
1583                    run_handler(input, ORIGIN, 0, None, |p, e| p.handle_horizontal_to(false, e));
1584                assert!(r.is_err(), "horizontal_to({input:?}) must be Err");
1585                let (r, _, _) =
1586                    run_handler(input, ORIGIN, 0, None, |p, e| p.handle_vertical_to(false, e));
1587                assert!(r.is_err(), "vertical_to({input:?}) must be Err");
1588            }
1589        }
1590    }
1591
1592    #[test]
1593    fn handle_cubic_to_records_second_control_point() {
1594        let (r, els, _) = run_handler("1 1 2 2 3 3", ORIGIN, b'C', None, |p, e| {
1595            p.handle_cubic_to(false, e)
1596        });
1597        assert!(r.is_ok());
1598        match els[0] {
1599            SvgPathElement::CubicCurve(c) => {
1600                assert_eq!(c.start, ORIGIN);
1601                assert_eq!(c.ctrl_1, SvgPoint { x: 1.0, y: 1.0 });
1602                assert_eq!(c.ctrl_2, SvgPoint { x: 2.0, y: 2.0 });
1603                assert_eq!(c.end, SvgPoint { x: 3.0, y: 3.0 });
1604            }
1605            other => panic!("expected CubicCurve, got {other:?}"),
1606        }
1607    }
1608
1609    /// S reflects the previous control point only when the previous command was
1610    /// C or S; otherwise ctrl_1 collapses onto the current point.
1611    #[test]
1612    fn handle_smooth_cubic_reflects_only_after_c_or_s() {
1613        let cur = SvgPoint { x: 10.0, y: 10.0 };
1614        let lc = Some(SvgPoint { x: 8.0, y: 6.0 });
1615
1616        let (_, els, _) = run_handler("1 1 2 2", cur, b'C', lc, |p, e| p.handle_smooth_cubic_to(false, e));
1617        match els[0] {
1618            // reflection of (8,6) about (10,10) == (12,14)
1619            SvgPathElement::CubicCurve(c) => assert_eq!(c.ctrl_1, SvgPoint { x: 12.0, y: 14.0 }),
1620            other => panic!("expected CubicCurve, got {other:?}"),
1621        }
1622
1623        // Previous command was L: no reflection, ctrl_1 == current.
1624        let (_, els, _) = run_handler("1 1 2 2", cur, b'L', lc, |p, e| p.handle_smooth_cubic_to(false, e));
1625        match els[0] {
1626            SvgPathElement::CubicCurve(c) => assert_eq!(c.ctrl_1, cur),
1627            other => panic!("expected CubicCurve, got {other:?}"),
1628        }
1629
1630        // No stored control point at all: no reflection either.
1631        let (_, els, _) = run_handler("1 1 2 2", cur, b'S', None, |p, e| p.handle_smooth_cubic_to(false, e));
1632        match els[0] {
1633            SvgPathElement::CubicCurve(c) => assert_eq!(c.ctrl_1, cur),
1634            other => panic!("expected CubicCurve, got {other:?}"),
1635        }
1636    }
1637
1638    #[test]
1639    fn handle_smooth_quadratic_reflects_only_after_q_or_t() {
1640        let cur = SvgPoint { x: 10.0, y: 10.0 };
1641        let lc = Some(SvgPoint { x: 8.0, y: 6.0 });
1642
1643        let (_, els, _) = run_handler("2 2", cur, b'Q', lc, |p, e| p.handle_smooth_quadratic_to(false, e));
1644        match els[0] {
1645            SvgPathElement::QuadraticCurve(q) => assert_eq!(q.ctrl, SvgPoint { x: 12.0, y: 14.0 }),
1646            other => panic!("expected QuadraticCurve, got {other:?}"),
1647        }
1648
1649        let (_, els, _) = run_handler("2 2", cur, b'M', lc, |p, e| p.handle_smooth_quadratic_to(false, e));
1650        match els[0] {
1651            SvgPathElement::QuadraticCurve(q) => assert_eq!(q.ctrl, cur),
1652            other => panic!("expected QuadraticCurve, got {other:?}"),
1653        }
1654    }
1655
1656    /// Arc radii are absolute-valued, so a negative radius still draws an arc.
1657    #[test]
1658    fn handle_arc_to_takes_abs_of_radii() {
1659        let (r, els, cur) = run_handler("-5 -5 0 0 1 10 0", ORIGIN, b'A', None, |p, e| {
1660            p.handle_arc_to(false, e)
1661        });
1662        assert!(r.is_ok());
1663        assert!(!els.is_empty(), "negative radii must still produce an arc");
1664        assert!(
1665            els.iter().all(|e| matches!(e, SvgPathElement::CubicCurve(_))),
1666            "abs() of the radii keeps this a real arc, not a line fallback"
1667        );
1668        assert_eq!(cur, SvgPoint { x: 10.0, y: 0.0 });
1669    }
1670
1671    /// A zero radius degenerates to a straight line (SVG spec F.6.6).
1672    #[test]
1673    fn handle_arc_to_zero_radius_degenerates_to_line() {
1674        let (r, els, _) = run_handler("0 0 0 0 1 10 0", ORIGIN, b'A', None, |p, e| {
1675            p.handle_arc_to(false, e)
1676        });
1677        assert!(r.is_ok());
1678        assert_eq!(els.len(), 1);
1679        assert!(matches!(els[0], SvgPathElement::Line(_)));
1680        assert_eq!(els[0].get_end(), SvgPoint { x: 10.0, y: 0.0 });
1681    }
1682
1683    #[test]
1684    fn handle_arc_to_rejects_out_of_range_flags() {
1685        for input in ["5 5 0 2 1 10 0", "5 5 0 1 2 10 0", "5 5 0 x 1 10 0", "5 5 0"] {
1686            let (r, _, _) = run_handler(input, ORIGIN, b'A', None, |p, e| p.handle_arc_to(false, e));
1687            assert!(r.is_err(), "arc flags in {input:?} must be rejected");
1688        }
1689        let (r, _, _) = run_handler("5 5 0 2 1 10 0", ORIGIN, b'A', None, |p, e| {
1690            p.handle_arc_to(false, e)
1691        });
1692        assert!(matches!(r, Err(SvgPathParseError::InvalidArcFlag { .. })));
1693    }
1694
1695    /// Infinite radii feed NaN through the endpoint parameterization. The
1696    /// segment count must still be bounded (no runaway loop) and no panic.
1697    #[test]
1698    fn handle_arc_to_infinite_radii_is_bounded() {
1699        let (r, els, _) = run_handler("1e999 1e999 0 0 1 10 10", ORIGIN, b'A', None, |p, e| {
1700            p.handle_arc_to(false, e)
1701        });
1702        assert!(r.is_ok());
1703        assert!(
1704            els.len() <= 4,
1705            "a single arc must never expand past 4 cubics, got {}",
1706            els.len()
1707        );
1708    }
1709
1710    // ===================================================== parse_svg_path_d (parser)
1711
1712    #[test]
1713    fn parse_path_empty_and_whitespace_only_is_empty_path_err() {
1714        for s in ["", "   ", "\t\n", "\r\n  \t"] {
1715            assert_eq!(
1716                parse_svg_path_d(s),
1717                Err(SvgPathParseError::EmptyPath),
1718                "{s:?} must be EmptyPath"
1719            );
1720        }
1721    }
1722
1723    #[test]
1724    fn parse_path_valid_minimal() {
1725        let mp = parse_svg_path_d("M10 20 L30 40").unwrap();
1726        let rings = mp.rings.as_ref();
1727        assert_eq!(rings.len(), 1);
1728        let items = rings[0].items.as_ref();
1729        assert_eq!(items.len(), 1);
1730        assert_eq!(items[0].get_start(), SvgPoint { x: 10.0, y: 20.0 });
1731        assert_eq!(items[0].get_end(), SvgPoint { x: 30.0, y: 40.0 });
1732    }
1733
1734    /// Relative commands accumulate from the current point.
1735    #[test]
1736    fn parse_path_relative_accumulates() {
1737        let mp = parse_svg_path_d("m10 20 l30 40").unwrap();
1738        let items_owner = &mp.rings.as_ref()[0];
1739        let items = items_owner.items.as_ref();
1740        assert_eq!(items[0].get_start(), SvgPoint { x: 10.0, y: 20.0 });
1741        assert_eq!(items[0].get_end(), SvgPoint { x: 40.0, y: 60.0 });
1742    }
1743
1744    /// A moveto with no drawing commands produces no geometry (but is not an error).
1745    #[test]
1746    fn parse_path_moveto_only_yields_no_rings() {
1747        let mp = parse_svg_path_d("M10 10").unwrap();
1748        assert_eq!(mp.rings.as_ref().len(), 0);
1749    }
1750
1751    /// Extra coordinate pairs after an M are implicit linetos (SVG spec).
1752    #[test]
1753    fn parse_path_implicit_lineto_after_moveto() {
1754        let mp = parse_svg_path_d("M0 0 10 0 20 0").unwrap();
1755        let items_owner = &mp.rings.as_ref()[0];
1756        let items = items_owner.items.as_ref();
1757        assert_eq!(items.len(), 2, "two implicit L commands");
1758        assert_eq!(items[0].get_end(), SvgPoint { x: 10.0, y: 0.0 });
1759        assert_eq!(items[1].get_end(), SvgPoint { x: 20.0, y: 0.0 });
1760    }
1761
1762    #[test]
1763    fn parse_path_garbage_is_err_never_panics() {
1764        for s in ["@#$", "hello", "?", "-", ".", ",", "0 0", "5", ";;;", "\u{0}"] {
1765            assert!(parse_svg_path_d(s).is_err(), "{s:?} must be rejected");
1766        }
1767    }
1768
1769    /// A leading non-command byte is reported as a real Unicode char at byte 0.
1770    #[test]
1771    fn parse_path_unicode_does_not_panic() {
1772        assert_eq!(
1773            parse_svg_path_d("\u{1F600}"),
1774            Err(SvgPathParseError::UnexpectedChar {
1775                pos: 0,
1776                ch: '\u{1F600}',
1777            })
1778        );
1779        assert_eq!(
1780            parse_svg_path_d("\u{0301}M0 0"),
1781            Err(SvgPathParseError::UnexpectedChar {
1782                pos: 0,
1783                ch: '\u{0301}',
1784            })
1785        );
1786        // A multibyte char *after* a valid command falls into the argument
1787        // parser and is rejected as a missing number, at the right byte offset.
1788        assert_eq!(
1789            parse_svg_path_d("M0 0L1 1ü"),
1790            Err(SvgPathParseError::ExpectedNumber { pos: 8 })
1791        );
1792    }
1793
1794    /// Trailing junk after a valid prefix is rejected deterministically.
1795    #[test]
1796    fn parse_path_trailing_junk_is_rejected() {
1797        assert!(parse_svg_path_d("M0 0 L1 1;garbage").is_err());
1798        assert!(parse_svg_path_d("M0 0 L").is_err(), "command with no args");
1799        assert!(parse_svg_path_d("M0 0 L1").is_err(), "half a coordinate pair");
1800        assert!(parse_svg_path_d("M0 0 X10 10").is_err(), "unknown command letter");
1801        // Surrounding whitespace is trimmed, not rejected.
1802        assert!(parse_svg_path_d("  \n M0 0 L1 1 \t ").is_ok());
1803    }
1804
1805    /// An unknown ASCII command letter reports its own offset.
1806    #[test]
1807    fn parse_path_unknown_command_reports_its_offset() {
1808        assert_eq!(
1809            parse_svg_path_d("M0 0 X10 10"),
1810            Err(SvgPathParseError::UnexpectedChar { pos: 5, ch: 'X' })
1811        );
1812    }
1813
1814    /// Closepath only emits a joining line when the gap exceeds CLOSEPATH_EPSILON.
1815    #[test]
1816    fn parse_path_closepath_epsilon_boundary() {
1817        // Well above the epsilon: a closing line is added.
1818        let mp = parse_svg_path_d("M0 0 L1 0 Z").unwrap();
1819        assert_eq!(mp.rings.as_ref()[0].items.as_ref().len(), 2);
1820
1821        // Exactly at the epsilon (dx*dx == eps*eps, and the test is strictly `>`):
1822        // no closing line.
1823        let mp = parse_svg_path_d("M0 0 L0.001 0 Z").unwrap();
1824        assert_eq!(mp.rings.as_ref()[0].items.as_ref().len(), 1);
1825
1826        // Below the epsilon: no closing line.
1827        let mp = parse_svg_path_d("M0 0 L0.0005 0 Z").unwrap();
1828        assert_eq!(mp.rings.as_ref()[0].items.as_ref().len(), 1);
1829
1830        // Degenerate closepath on an empty subpath yields no rings at all.
1831        assert_eq!(parse_svg_path_d("M0 0 Z").unwrap().rings.as_ref().len(), 0);
1832    }
1833
1834    /// Every M and every Z flushes a ring.
1835    #[test]
1836    fn parse_path_multiple_subpaths_produce_multiple_rings() {
1837        let mp = parse_svg_path_d("M0 0 L10 0 Z M20 20 L30 20 Z M40 40 L50 40").unwrap();
1838        assert_eq!(mp.rings.as_ref().len(), 3);
1839    }
1840
1841    /// Structural invariant: within a ring, each element's end is the next
1842    /// element's start -- for every command type, including arcs and closepath.
1843    #[test]
1844    fn parse_path_rings_are_contiguous_chains() {
1845        let d = "M0 0 L10 0 H20 V10 C25 15 30 20 35 20 S45 25 50 20 \
1846                 Q55 15 60 20 T70 20 A5 5 0 1 1 80 30 Z \
1847                 m100 100 l10 0 z";
1848        let mp = parse_svg_path_d(d).unwrap();
1849        assert!(mp.rings.as_ref().len() >= 2);
1850        for (i, ring) in mp.rings.as_ref().iter().enumerate() {
1851            assert_contiguous(ring.items.as_ref(), &format!("ring {i}"));
1852            assert!(!ring.items.as_ref().is_empty(), "ring {i} must not be empty");
1853        }
1854    }
1855
1856    /// A closed ring ends where it started.
1857    #[test]
1858    fn parse_path_closed_ring_returns_to_subpath_start() {
1859        let mp = parse_svg_path_d("M0 0 L10 0 L10 10 Z").unwrap();
1860        let ring = &mp.rings.as_ref()[0];
1861        let items = ring.items.as_ref();
1862        assert_eq!(items.last().unwrap().get_end(), SvgPoint { x: 0.0, y: 0.0 });
1863        assert_eq!(items.first().unwrap().get_start(), SvgPoint { x: 0.0, y: 0.0 });
1864    }
1865
1866    /// Boundary numerics survive the full parse: coordinates saturate to inf
1867    /// rather than panicking or wrapping.
1868    #[test]
1869    fn parse_path_boundary_numbers_saturate() {
1870        let mp = parse_svg_path_d("M1e999 -1e999 L1e-999 0").unwrap();
1871        let items_owner = &mp.rings.as_ref()[0];
1872        let start = items_owner.items.as_ref()[0].get_start();
1873        assert!(start.x.is_infinite() && start.x.is_sign_positive());
1874        assert!(start.y.is_infinite() && start.y.is_sign_negative());
1875
1876        // f32::MAX-ish coordinates with a *relative* lineto overflow to +inf.
1877        let mp = parse_svg_path_d("M3.4e38 0 l3.4e38 0").unwrap();
1878        let items_owner = &mp.rings.as_ref()[0];
1879        assert!(items_owner.items.as_ref()[0].get_end().x.is_infinite());
1880
1881        // "NaN" / "inf" are not valid SVG numbers -- they must be rejected,
1882        // so a NaN coordinate can never enter the geometry via the parser.
1883        assert!(parse_svg_path_d("M NaN 0").is_err());
1884        assert!(parse_svg_path_d("M inf 0").is_err());
1885    }
1886
1887    /// 5000 implicit repeats: the parser is iterative, so this must neither
1888    /// hang nor blow the stack.
1889    #[test]
1890    fn parse_path_extremely_long_input_terminates() {
1891        let mut d = String::from("M0 0");
1892        for _ in 0..5_000 {
1893            d.push_str(" L1 1");
1894        }
1895        let mp = parse_svg_path_d(&d).unwrap();
1896        let items_owner = &mp.rings.as_ref()[0];
1897        assert_eq!(items_owner.items.as_ref().len(), 5_000);
1898
1899        // 5000 subpaths -> 5000 rings, still iterative.
1900        let mut d = String::new();
1901        for _ in 0..5_000 {
1902            d.push_str("M0 0 L1 1 Z ");
1903        }
1904        assert_eq!(parse_svg_path_d(&d).unwrap().rings.as_ref().len(), 5_000);
1905    }
1906
1907    /// A long run of adversarial fragments: every one must *return* (Ok or Err)
1908    /// and never spin. The `Z`-followed-by-a-digit case used to loop forever.
1909    #[test]
1910    fn parse_path_adversarial_fragments_all_terminate() {
1911        let fragments = [
1912            "Z", "z", "ZZZ", "M0 0ZZ", "M0 0Z0", "M0 0zZ5", "M0 0Z Z Z",
1913            "M", "M0", "M0 0 C", "M0 0 A", "M0 0 A1", "M0 0 A1 1 0 0 0 0",
1914            "M0 0 S", "M0 0 T", "M0 0 H", "M0 0 V", "M0 0 Q1",
1915            "M0 0 L1 1 1", "M0 0 L1 1 1 1 1", "M0 0 A0 0 0 0 0 0 0",
1916            "M0 0 l-.5-.5-.5-.5", "M0 0 t1 1 2 2", "M0 0 s1 1 2 2 3 3 4 4",
1917            "M0,0,1,1", "M0 0e", "M0 0 1e1e1", "M.5.5.5.5",
1918            "M0 0 A1 1 0 11 10 10", "M0 0 A1 1 0 1 1 10 10 A1 1 0 0 0 0 0",
1919            "M0 0 h1e999 v1e999 h-1e999", "M-0-0-0-0",
1920        ];
1921        for f in fragments {
1922            // The assertion is termination itself; the result is merely pinned
1923            // as "did not panic".
1924            let r = parse_svg_path_d(f);
1925            assert!(r.is_ok() || r.is_err(), "{f:?} must return, not panic");
1926        }
1927    }
1928
1929    /// All 14 commands round-trip through the tokenizer into geometry of the
1930    /// expected kind.
1931    #[test]
1932    fn parse_path_every_command_produces_its_element_kind() {
1933        let cases: [(&str, usize); 10] = [
1934            ("M0 0 L1 1", 1),
1935            ("M0 0 l1 1", 1),
1936            ("M0 0 H1", 1),
1937            ("M0 0 V1", 1),
1938            ("M0 0 C1 1 2 2 3 3", 1),
1939            ("M0 0 S1 1 2 2", 1),
1940            ("M0 0 Q1 1 2 2", 1),
1941            ("M0 0 T1 1", 1),
1942            ("M0 0 L1 0 Z", 2), // the Z adds the closing line
1943            ("M0 0 A5 5 0 0 1 10 0", 2), // a half-turn arc splits into 2 cubics
1944        ];
1945        for (d, expected) in cases {
1946            let mp = parse_svg_path_d(d).unwrap_or_else(|e| panic!("{d:?} failed: {e:?}"));
1947            let rings = mp.rings.as_ref();
1948            assert_eq!(rings.len(), 1, "{d:?}");
1949            assert_eq!(rings[0].items.as_ref().len(), expected, "{d:?}");
1950        }
1951    }
1952
1953    // ======================================================= arc_to_cubics (numeric)
1954
1955    #[test]
1956    fn arc_to_cubics_coincident_endpoints_emit_nothing() {
1957        let mut out = Vec::new();
1958        arc_to_cubics(ORIGIN, ORIGIN, 5.0, 5.0, 0.0, true, true, &mut out);
1959        assert!(out.is_empty(), "a zero-length arc is dropped per SVG F.6.2");
1960
1961        // Within POINT_EPSILON also counts as coincident.
1962        let near = SvgPoint { x: 1e-9, y: 1e-9 };
1963        arc_to_cubics(ORIGIN, near, 5.0, 5.0, 0.0, false, false, &mut out);
1964        assert!(out.is_empty());
1965    }
1966
1967    #[test]
1968    fn arc_to_cubics_zero_radius_emits_a_line() {
1969        let end = SvgPoint { x: 10.0, y: 10.0 };
1970        for (rx, ry) in [(0.0, 5.0), (5.0, 0.0), (0.0, 0.0)] {
1971            let mut out = Vec::new();
1972            arc_to_cubics(ORIGIN, end, rx, ry, 0.0, false, true, &mut out);
1973            assert_eq!(out.len(), 1, "rx={rx} ry={ry}");
1974            assert!(matches!(out[0], SvgPathElement::Line(_)));
1975            assert_eq!(out[0].get_start(), ORIGIN);
1976            assert_eq!(out[0].get_end(), end);
1977        }
1978    }
1979
1980    /// For every flag combination, the arc is 1..=4 cubics that start exactly at
1981    /// `start` and end exactly at `end` (the endpoint is snapped, not computed).
1982    #[test]
1983    fn arc_to_cubics_endpoints_are_exact_for_all_flag_combos() {
1984        let start = SvgPoint { x: 0.0, y: 0.0 };
1985        let end = SvgPoint { x: 10.0, y: 10.0 };
1986        for large_arc in [false, true] {
1987            for sweep in [false, true] {
1988                let mut out = Vec::new();
1989                arc_to_cubics(start, end, 8.0, 6.0, 30.0, large_arc, sweep, &mut out);
1990                assert!(
1991                    (1..=4).contains(&out.len()),
1992                    "large_arc={large_arc} sweep={sweep}: got {} cubics",
1993                    out.len()
1994                );
1995                assert_eq!(out[0].get_start(), start);
1996                assert_eq!(out.last().unwrap().get_end(), end);
1997                assert_contiguous(&out, "arc");
1998                for p in out.iter().flat_map(|e| [e.get_start(), e.get_end()]) {
1999                    assert!(p.x.is_finite() && p.y.is_finite(), "arc produced {p:?}");
2000                }
2001            }
2002        }
2003    }
2004
2005    /// Radii that are too small to span the endpoints are scaled up (F.6.6 step 3),
2006    /// so the arc still lands exactly on the endpoint instead of NaN-ing out.
2007    #[test]
2008    fn arc_to_cubics_undersized_radii_are_scaled_up() {
2009        let start = ORIGIN;
2010        let end = SvgPoint { x: 100.0, y: 0.0 };
2011        let mut out = Vec::new();
2012        arc_to_cubics(start, end, 1.0, 1.0, 0.0, false, true, &mut out);
2013        assert!(!out.is_empty());
2014        assert_eq!(out.last().unwrap().get_end(), end);
2015        for p in all_points(&SvgPath {
2016            items: SvgPathElementVec::from_vec(out),
2017        }) {
2018            assert!(p.x.is_finite() && p.y.is_finite(), "scaled arc produced {p:?}");
2019        }
2020    }
2021
2022    /// NaN / infinite radii must not spin the segment loop: `n_segs` comes from a
2023    /// NaN -> usize cast, which saturates to 0 and is then clamped to 1.
2024    #[test]
2025    fn arc_to_cubics_nan_and_inf_inputs_are_bounded() {
2026        let end = SvgPoint { x: 10.0, y: 10.0 };
2027        let bad = [
2028            (f32::NAN, 5.0, 0.0),
2029            (5.0, f32::NAN, 0.0),
2030            (f32::INFINITY, f32::INFINITY, 0.0),
2031            (5.0, 5.0, f32::NAN),
2032            (5.0, 5.0, f32::INFINITY),
2033            (f32::MAX, f32::MAX, 360.0),
2034        ];
2035        for (rx, ry, rot) in bad {
2036            let mut out = Vec::new();
2037            arc_to_cubics(ORIGIN, end, rx, ry, rot, true, false, &mut out);
2038            assert!(
2039                out.len() <= 4,
2040                "rx={rx} ry={ry} rot={rot}: {} elements (segment loop ran away)",
2041                out.len()
2042            );
2043        }
2044    }
2045
2046    /// Extreme but finite endpoints do not panic and stay bounded.
2047    #[test]
2048    fn arc_to_cubics_extreme_endpoints_do_not_panic() {
2049        let mut out = Vec::new();
2050        arc_to_cubics(
2051            SvgPoint { x: f32::MIN, y: f32::MIN },
2052            SvgPoint { x: f32::MAX, y: f32::MAX },
2053            f32::MAX,
2054            f32::MAX,
2055            0.0,
2056            true,
2057            true,
2058            &mut out,
2059        );
2060        assert!(out.len() <= 4);
2061    }
2062
2063    // ======================================================= angle_between (numeric)
2064
2065    #[test]
2066    fn angle_between_known_angles() {
2067        assert!(approx(angle_between(1.0, 0.0, 1.0, 0.0), 0.0));
2068        assert!(approx(
2069            angle_between(1.0, 0.0, 0.0, 1.0),
2070            core::f32::consts::FRAC_PI_2
2071        ));
2072        assert!(approx(
2073            angle_between(1.0, 0.0, 0.0, -1.0),
2074            -core::f32::consts::FRAC_PI_2
2075        ));
2076        assert!(approx(
2077            angle_between(1.0, 0.0, -1.0, 0.0),
2078            core::f32::consts::PI
2079        ));
2080        // Magnitude is irrelevant -- only direction matters.
2081        assert!(approx(
2082            angle_between(100.0, 0.0, 0.0, 0.001),
2083            core::f32::consts::FRAC_PI_2
2084        ));
2085    }
2086
2087    /// A zero-length (or underflowing) vector short-circuits to 0.0.
2088    #[test]
2089    fn angle_between_zero_length_vectors_return_zero() {
2090        assert_eq!(angle_between(0.0, 0.0, 1.0, 0.0), 0.0);
2091        assert_eq!(angle_between(1.0, 0.0, 0.0, 0.0), 0.0);
2092        assert_eq!(angle_between(0.0, 0.0, 0.0, 0.0), 0.0);
2093        // Denormal-scale vectors: the squared length underflows to 0.
2094        assert_eq!(angle_between(1e-30, 1e-30, 1e-30, 1e-30), 0.0);
2095    }
2096
2097    /// Result is always within [-PI, PI] for finite inputs (the acos argument is
2098    /// clamped, so rounding can never push it out of the domain).
2099    #[test]
2100    fn angle_between_is_always_within_pi_for_finite_inputs() {
2101        let vals = [-1e30_f32, -3.0, -1.0, -0.0, 0.0, 1.0, 3.0, 1e30];
2102        for ux in vals {
2103            for uy in vals {
2104                for vx in vals {
2105                    for vy in vals {
2106                        let a = angle_between(ux, uy, vx, vy);
2107                        assert!(
2108                            a.is_nan() || a.abs() <= core::f32::consts::PI + 1e-5,
2109                            "angle_between({ux},{uy},{vx},{vy}) = {a} is out of range"
2110                        );
2111                    }
2112                }
2113            }
2114        }
2115    }
2116
2117    /// Antiparallel/parallel unit vectors do not fall out of acos's domain even
2118    /// when the dot product rounds slightly past +/-1.
2119    #[test]
2120    fn angle_between_clamps_the_acos_domain() {
2121        let a = angle_between(0.1, 0.2, 0.1, 0.2);
2122        assert!(!a.is_nan(), "parallel vectors must not produce NaN, got {a}");
2123        assert!(approx(a, 0.0));
2124        let a = angle_between(0.1, 0.2, -0.1, -0.2);
2125        assert!(!a.is_nan());
2126        assert!(approx(a.abs(), core::f32::consts::PI));
2127    }
2128
2129    /// NaN / inf inputs produce NaN, not a panic.
2130    #[test]
2131    fn angle_between_nan_and_inf_do_not_panic() {
2132        assert!(angle_between(f32::NAN, 0.0, 1.0, 0.0).is_nan());
2133        assert!(angle_between(1.0, 0.0, f32::NAN, f32::NAN).is_nan());
2134        assert!(angle_between(f32::INFINITY, 0.0, f32::INFINITY, 0.0).is_nan());
2135        assert!(angle_between(f32::INFINITY, 0.0, 1.0, 0.0).is_nan());
2136    }
2137
2138    // ================================================ arc_segment_to_cubic (numeric)
2139
2140    #[test]
2141    fn arc_segment_to_cubic_quarter_circle() {
2142        // Unit circle, no rotation, 0 -> PI/2: the endpoint must land on (0, 1).
2143        let (c1, c2, ep) = arc_segment_to_cubic(
2144            0.0,
2145            0.0,
2146            1.0,
2147            1.0,
2148            1.0,
2149            0.0,
2150            0.0,
2151            core::f32::consts::FRAC_PI_2,
2152        );
2153        assert!(approx(ep.x, 0.0) && approx(ep.y, 1.0), "ep = {ep:?}");
2154        // Control points bulge outward by kappa.
2155        assert!(approx(c1.x, 1.0) && approx(c1.y, KAPPA), "c1 = {c1:?}");
2156        assert!(approx(c2.x, KAPPA) && approx(c2.y, 1.0), "c2 = {c2:?}");
2157    }
2158
2159    /// A zero-width segment collapses every point onto the start of the arc.
2160    #[test]
2161    fn arc_segment_to_cubic_zero_sweep_collapses() {
2162        let (c1, c2, ep) = arc_segment_to_cubic(5.0, 5.0, 2.0, 2.0, 1.0, 0.0, 0.7, 0.7);
2163        assert!(approx(c1.x, c2.x) && approx(c1.y, c2.y));
2164        assert!(approx(c2.x, ep.x) && approx(c2.y, ep.y));
2165        // ...and that point is on the circle around (5,5).
2166        assert!(approx((ep.x - 5.0).hypot(ep.y - 5.0), 2.0));
2167    }
2168
2169    /// Zero radii put all three points at the center.
2170    #[test]
2171    fn arc_segment_to_cubic_zero_radius_is_the_center() {
2172        let (c1, c2, ep) = arc_segment_to_cubic(3.0, 4.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0);
2173        for p in [c1, c2, ep] {
2174            assert_eq!(p, SvgPoint { x: 3.0, y: 4.0 });
2175        }
2176    }
2177
2178    /// Rotation is applied via the caller-supplied cos/sin pair.
2179    #[test]
2180    fn arc_segment_to_cubic_applies_rotation() {
2181        // 90-degree rotation (cos=0, sin=1) maps the theta=0 point (rx, 0) to (0, rx).
2182        let (_, _, ep) = arc_segment_to_cubic(0.0, 0.0, 2.0, 1.0, 0.0, 1.0, 0.0, 0.0);
2183        assert!(approx(ep.x, 0.0) && approx(ep.y, 2.0), "ep = {ep:?}");
2184    }
2185
2186    #[test]
2187    fn arc_segment_to_cubic_nan_and_inf_do_not_panic() {
2188        let bad = [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, f32::MIN];
2189        for v in bad {
2190            let (c1, c2, ep) = arc_segment_to_cubic(v, v, v, v, v, v, v, v);
2191            // The only contract is "returns a defined value without panicking".
2192            for p in [c1, c2, ep] {
2193                assert!(p.x.is_nan() || p.x.is_finite() || p.x.is_infinite());
2194                assert!(p.y.is_nan() || p.y.is_finite() || p.y.is_infinite());
2195            }
2196        }
2197        // A full-circle sweep drives tan(PI/2) to a huge value; still no panic.
2198        let (c1, _, _) = arc_segment_to_cubic(
2199            0.0,
2200            0.0,
2201            1.0,
2202            1.0,
2203            1.0,
2204            0.0,
2205            0.0,
2206            core::f32::consts::TAU,
2207        );
2208        assert!(!c1.x.is_nan() || c1.x.is_nan(), "must not panic");
2209    }
2210
2211    // =================================================== svg_circle_to_paths (numeric)
2212
2213    #[test]
2214    fn circle_has_four_cubics_and_closes_on_itself() {
2215        let p = svg_circle_to_paths(10.0, 20.0, 5.0);
2216        let items = p.items.as_ref();
2217        assert_eq!(items.len(), 4);
2218        assert!(items.iter().all(|e| matches!(e, SvgPathElement::CubicCurve(_))));
2219        assert_contiguous(items, "circle");
2220        assert_eq!(
2221            items.last().unwrap().get_end(),
2222            items.first().unwrap().get_start(),
2223            "the circle must close exactly"
2224        );
2225        // The four anchors are the cardinal points.
2226        assert_eq!(items[0].get_start(), SvgPoint { x: 10.0, y: 15.0 });
2227        assert_eq!(items[0].get_end(), SvgPoint { x: 15.0, y: 20.0 });
2228        assert_eq!(items[1].get_end(), SvgPoint { x: 10.0, y: 25.0 });
2229        assert_eq!(items[2].get_end(), SvgPoint { x: 5.0, y: 20.0 });
2230    }
2231
2232    /// r = 0 degenerates to four zero-length curves at the center, not a panic.
2233    #[test]
2234    fn circle_zero_radius_collapses_to_the_center() {
2235        let p = svg_circle_to_paths(3.0, 4.0, 0.0);
2236        let items = p.items.as_ref();
2237        assert_eq!(items.len(), 4);
2238        for pt in all_points(&p) {
2239            assert_eq!(pt, SvgPoint { x: 3.0, y: 4.0 });
2240        }
2241    }
2242
2243    /// A negative radius mirrors the circle (it is not rejected or abs()'d);
2244    /// it still yields a closed 4-curve path.
2245    #[test]
2246    fn circle_negative_radius_is_mirrored_not_rejected() {
2247        let p = svg_circle_to_paths(0.0, 0.0, -5.0);
2248        let items = p.items.as_ref();
2249        assert_eq!(items.len(), 4);
2250        assert_contiguous(items, "negative-r circle");
2251        assert_eq!(items[0].get_start(), SvgPoint { x: 0.0, y: 5.0 });
2252        for pt in all_points(&p) {
2253            assert!(pt.x.is_finite() && pt.y.is_finite());
2254        }
2255    }
2256
2257    #[test]
2258    fn circle_nan_inf_and_max_do_not_panic() {
2259        for (cx, cy, r) in [
2260            (f32::NAN, 0.0, 1.0),
2261            (0.0, 0.0, f32::NAN),
2262            (0.0, 0.0, f32::INFINITY),
2263            (f32::MAX, f32::MAX, f32::MAX),
2264            (f32::MIN, f32::MIN, f32::MIN),
2265        ] {
2266            let p = svg_circle_to_paths(cx, cy, r);
2267            assert_eq!(p.items.as_ref().len(), 4, "cx={cx} cy={cy} r={r}");
2268        }
2269        // f32::MAX radius overflows the control points to infinity rather than
2270        // wrapping.
2271        let p = svg_circle_to_paths(f32::MAX, 0.0, f32::MAX);
2272        assert!(all_points(&p).iter().any(|pt| pt.x.is_infinite()));
2273    }
2274
2275    // ==================================================== svg_rect_to_path (numeric)
2276
2277    #[test]
2278    fn rect_sharp_corners_are_four_lines() {
2279        let p = svg_rect_to_path(1.0, 2.0, 10.0, 20.0, 0.0, 0.0);
2280        let items = p.items.as_ref();
2281        assert_eq!(items.len(), 4);
2282        assert!(items.iter().all(|e| matches!(e, SvgPathElement::Line(_))));
2283        assert_contiguous(items, "sharp rect");
2284        assert_eq!(items[0].get_start(), SvgPoint { x: 1.0, y: 2.0 });
2285        assert_eq!(items[1].get_start(), SvgPoint { x: 11.0, y: 2.0 });
2286        assert_eq!(items[2].get_start(), SvgPoint { x: 11.0, y: 22.0 });
2287        assert_eq!(items[3].get_start(), SvgPoint { x: 1.0, y: 22.0 });
2288        assert_eq!(
2289            items.last().unwrap().get_end(),
2290            items.first().unwrap().get_start(),
2291            "the rect must close exactly"
2292        );
2293    }
2294
2295    #[test]
2296    fn rect_rounded_is_eight_alternating_segments_and_closes() {
2297        let p = svg_rect_to_path(0.0, 0.0, 100.0, 50.0, 10.0, 5.0);
2298        let items = p.items.as_ref();
2299        assert_eq!(items.len(), 8);
2300        for (i, e) in items.iter().enumerate() {
2301            if i % 2 == 0 {
2302                assert!(matches!(e, SvgPathElement::Line(_)), "item {i} should be an edge");
2303            } else {
2304                assert!(
2305                    matches!(e, SvgPathElement::CubicCurve(_)),
2306                    "item {i} should be a corner"
2307                );
2308            }
2309        }
2310        assert_contiguous(items, "rounded rect");
2311        assert_eq!(
2312            items.last().unwrap().get_end(),
2313            items.first().unwrap().get_start(),
2314            "the rounded rect must close exactly"
2315        );
2316    }
2317
2318    /// Radii larger than half the rect are clamped to half (SVG spec), so an
2319    /// over-large rx cannot invert the geometry.
2320    #[test]
2321    fn rect_oversized_radii_are_clamped_to_half() {
2322        let p = svg_rect_to_path(0.0, 0.0, 10.0, 10.0, 1000.0, 1000.0);
2323        let items = p.items.as_ref();
2324        assert_eq!(items.len(), 8);
2325        // rx clamps to 5 => the top edge runs from x+5 to x+w-5, i.e. zero length.
2326        match items[0] {
2327            SvgPathElement::Line(l) => {
2328                assert_eq!(l.start, SvgPoint { x: 5.0, y: 0.0 });
2329                assert_eq!(l.end, SvgPoint { x: 5.0, y: 0.0 });
2330            }
2331            other => panic!("expected Line, got {other:?}"),
2332        }
2333        assert_contiguous(items, "clamped rect");
2334        for pt in all_points(&p) {
2335            assert!(pt.x.is_finite() && pt.y.is_finite());
2336            assert!((0.0..=10.0).contains(&pt.x), "x {} escaped the rect", pt.x);
2337            assert!((0.0..=10.0).contains(&pt.y), "y {} escaped the rect", pt.y);
2338        }
2339    }
2340
2341    /// Only one of rx/ry being zero still takes the rounded path.
2342    #[test]
2343    fn rect_single_zero_radius_still_rounds() {
2344        let p = svg_rect_to_path(0.0, 0.0, 100.0, 100.0, 0.0, 10.0);
2345        assert_eq!(p.items.as_ref().len(), 8);
2346        let p = svg_rect_to_path(0.0, 0.0, 100.0, 100.0, 10.0, 0.0);
2347        assert_eq!(p.items.as_ref().len(), 8);
2348    }
2349
2350    /// A negative width drives `rx.min(w / 2.0)` negative, which falls below the
2351    /// epsilon and takes the sharp-corner branch. Deterministic, no panic.
2352    #[test]
2353    fn rect_negative_extent_takes_the_sharp_branch() {
2354        let p = svg_rect_to_path(0.0, 0.0, -10.0, -10.0, 4.0, 4.0);
2355        let items = p.items.as_ref();
2356        assert_eq!(items.len(), 4);
2357        assert!(items.iter().all(|e| matches!(e, SvgPathElement::Line(_))));
2358        assert_contiguous(items, "negative rect");
2359        assert_eq!(items[1].get_start(), SvgPoint { x: -10.0, y: 0.0 });
2360    }
2361
2362    /// `f32::min` returns the non-NaN operand, so a NaN radius silently becomes
2363    /// half the extent -- and every coordinate stays finite.
2364    #[test]
2365    fn rect_nan_radius_falls_back_to_half_extent() {
2366        let p = svg_rect_to_path(0.0, 0.0, 100.0, 100.0, f32::NAN, f32::NAN);
2367        let items = p.items.as_ref();
2368        assert_eq!(items.len(), 8, "NaN radii clamp to w/2, h/2 -> rounded path");
2369        for pt in all_points(&p) {
2370            assert!(pt.x.is_finite() && pt.y.is_finite(), "NaN leaked into {pt:?}");
2371        }
2372        // rx == 50 => the top edge collapses (x+50 .. x+100-50).
2373        match items[0] {
2374            SvgPathElement::Line(l) => assert_eq!(l.start, l.end),
2375            other => panic!("expected Line, got {other:?}"),
2376        }
2377    }
2378
2379    /// A NaN extent cannot be repaired -- but it must still return a well-formed
2380    /// path rather than panicking.
2381    #[test]
2382    fn rect_nan_extent_is_deterministic() {
2383        let p = svg_rect_to_path(0.0, 0.0, f32::NAN, f32::NAN, 0.0, 0.0);
2384        // rx = 0.min(NaN) = 0 -> sharp branch.
2385        assert_eq!(p.items.as_ref().len(), 4);
2386        let p = svg_rect_to_path(f32::NAN, f32::NAN, 10.0, 10.0, 0.0, 0.0);
2387        assert_eq!(p.items.as_ref().len(), 4);
2388    }
2389
2390    #[test]
2391    fn rect_inf_and_max_extents_do_not_panic() {
2392        for (x, y, w, h, rx, ry) in [
2393            (0.0, 0.0, f32::INFINITY, f32::INFINITY, 0.0, 0.0),
2394            (0.0, 0.0, f32::MAX, f32::MAX, 0.0, 0.0),
2395            (f32::MIN, f32::MIN, f32::MAX, f32::MAX, f32::MAX, f32::MAX),
2396            (0.0, 0.0, f32::INFINITY, f32::INFINITY, f32::INFINITY, f32::INFINITY),
2397        ] {
2398            let p = svg_rect_to_path(x, y, w, h, rx, ry);
2399            let n = p.items.as_ref().len();
2400            assert!(n == 4 || n == 8, "w={w} h={h} rx={rx} ry={ry}: got {n} items");
2401        }
2402    }
2403}