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

            
7
use alloc::{string::String, vec::Vec};
8

            
9
use azul_css::props::basic::{SvgCubicCurve, SvgPoint, SvgQuadraticCurve};
10

            
11
use crate::svg::{
12
    SvgLine, SvgMultiPolygon, SvgPath, SvgPathElement, SvgPathElementVec, SvgPathVec,
13
};
14

            
15
/// Bezier approximation constant for quarter-circle arcs.
16
const KAPPA: f32 = 0.552_284_8;
17

            
18
/// Tolerance for treating two points as coincident (used in closepath and arc degeneracy checks).
19
const POINT_EPSILON: f32 = 1e-6;
20

            
21
/// Tolerance for snapping a closepath line (slightly larger to avoid micro-segments).
22
const CLOSEPATH_EPSILON: f32 = 0.001;
23

            
24
/// Tolerance for treating a vector length as zero in angle computation.
25
const ZERO_LENGTH_EPSILON: f32 = 1e-10;
26

            
27
/// Small offset added to PI/2 when splitting arcs to avoid exact-boundary floating-point issues.
28
const ARC_SPLIT_FUDGE: f32 = 0.001;
29

            
30
/// Decode the UTF-8 character starting at `pos` in `input`.
31
///
32
/// `input` is always the byte view of a valid `&str` and `pos` is always at a
33
/// char boundary (only whole ASCII tokens are consumed), so the UTF-8 decode
34
/// succeeds; a corrupt offset falls back to the replacement character rather
35
/// than panicking. Used so error messages report the real Unicode char instead
36
/// of a Latin-1 reinterpretation of a single UTF-8 byte (`b as char`).
37
282
fn char_at(input: &[u8], pos: usize) -> char {
38
282
    input
39
282
        .get(pos..)
40
282
        .and_then(|rest| core::str::from_utf8(rest).ok())
41
282
        .and_then(|s| s.chars().next())
42
282
        .unwrap_or(char::REPLACEMENT_CHARACTER)
43
282
}
44

            
45
/// Errors that can occur during SVG path parsing.
46
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47
pub enum SvgPathParseError {
48
    /// The path string is empty.
49
    EmptyPath,
50
    /// Unexpected character encountered at the given byte offset.
51
    UnexpectedChar { pos: usize, ch: char },
52
    /// Expected a number but found something else.
53
    ExpectedNumber { pos: usize },
54
    /// Invalid arc flag (must be 0 or 1).
55
    InvalidArcFlag { pos: usize },
56
}
57

            
58
/// Human-readable error messages for SVG path parse failures.
59
impl core::fmt::Display for SvgPathParseError {
60
10
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
61
10
        match self {
62
1
            Self::EmptyPath => write!(f, "empty path"),
63
5
            Self::UnexpectedChar { pos, ch } => {
64
5
                write!(f, "unexpected char '{ch}' at byte {pos}")
65
            }
66
2
            Self::ExpectedNumber { pos } => write!(f, "expected number at byte {pos}"),
67
2
            Self::InvalidArcFlag { pos } => write!(f, "invalid arc flag at byte {pos}"),
68
        }
69
10
    }
70
}
71

            
72
/// Internal parser state.
73
struct PathParser<'a> {
74
    input: &'a [u8],
75
    pos: usize,
76
    current: SvgPoint,
77
    subpath_start: SvgPoint,
78
    last_control: Option<SvgPoint>,
79
    last_command: u8,
80
}
81

            
82
impl<'a> PathParser<'a> {
83
3918
    const fn new(input: &'a [u8]) -> Self {
84
3918
        Self {
85
3918
            input,
86
3918
            pos: 0,
87
3918
            current: SvgPoint { x: 0.0, y: 0.0 },
88
3918
            subpath_start: SvgPoint { x: 0.0, y: 0.0 },
89
3918
            last_control: None,
90
3918
            last_command: 0,
91
3918
        }
92
3918
    }
93

            
94
1916353
    const fn at_end(&self) -> bool {
95
1916353
        self.pos >= self.input.len()
96
1916353
    }
97

            
98
1274092
    fn peek(&self) -> Option<u8> {
99
1274092
        self.input.get(self.pos).copied()
100
1274092
    }
101

            
102
2640218
    fn skip_whitespace_and_commas(&mut self) {
103
4744923
        while let Some(&b) = self.input.get(self.pos) {
104
4744475
            if b == b' ' || b == b'\t' || b == b'\n' || b == b'\r' || b == b',' {
105
2104705
                self.pos += 1;
106
2104705
            } else {
107
2639770
                break;
108
            }
109
        }
110
2640218
    }
111

            
112
3743
    fn skip_whitespace(&mut self) {
113
3745
        while let Some(&b) = self.input.get(self.pos) {
114
3744
            if b == b' ' || b == b'\t' || b == b'\n' || b == b'\r' {
115
2
                self.pos += 1;
116
2
            } else {
117
3742
                break;
118
            }
119
        }
120
3743
    }
121

            
122
    /// Returns true if the current position looks like the start of a number.
123
14247
    fn has_number(&self) -> bool {
124
14247
        match self.input.get(self.pos) {
125
4565
            Some(b'+' | b'-' | b'.') => true,
126
9679
            Some(b) if b.is_ascii_digit() => true,
127
13
            _ => false,
128
        }
129
14247
    }
130

            
131
1365592
    fn parse_number(&mut self) -> Result<f32, SvgPathParseError> {
132
1365592
        self.skip_whitespace_and_commas();
133
1365592
        let start = self.pos;
134

            
135
        // Optional sign
136
1365592
        if let Some(&b) = self.input.get(self.pos) {
137
1365526
            if b == b'+' || b == b'-' {
138
59441
                self.pos += 1;
139
1306085
            }
140
66
        }
141

            
142
1365592
        let mut has_digits = false;
143

            
144
        // Integer part
145
7371910
        while let Some(&b) = self.input.get(self.pos) {
146
7371485
            if b.is_ascii_digit() {
147
6006318
                self.pos += 1;
148
6006318
                has_digits = true;
149
6006318
            } else {
150
1365167
                break;
151
            }
152
        }
153

            
154
        // Decimal part
155
1365592
        if self.input.get(self.pos) == Some(&b'.') {
156
106670
            self.pos += 1;
157
318442
            while let Some(&b) = self.input.get(self.pos) {
158
318346
                if b.is_ascii_digit() {
159
211772
                    self.pos += 1;
160
211772
                    has_digits = true;
161
211772
                } else {
162
106574
                    break;
163
                }
164
            }
165
1258922
        }
166

            
167
1365592
        if !has_digits {
168
144
            return Err(SvgPathParseError::ExpectedNumber { pos: start });
169
1365448
        }
170

            
171
        // Exponent
172
1365448
        if let Some(&b) = self.input.get(self.pos) {
173
1365000
            if b == b'e' || b == b'E' {
174
31
                self.pos += 1;
175
31
                if let Some(&b) = self.input.get(self.pos) {
176
26
                    if b == b'+' || b == b'-' {
177
7
                        self.pos += 1;
178
19
                    }
179
5
                }
180
88
                while let Some(&b) = self.input.get(self.pos) {
181
68
                    if b.is_ascii_digit() {
182
57
                        self.pos += 1;
183
57
                    } else {
184
11
                        break;
185
                    }
186
                }
187
1364969
            }
188
448
        }
189

            
190
1365448
        let s = core::str::from_utf8(&self.input[start..self.pos])
191
1365448
            .map_err(|_| SvgPathParseError::ExpectedNumber { pos: start })?;
192
1365448
        s.parse::<f32>()
193
1365448
            .map_err(|_| SvgPathParseError::ExpectedNumber { pos: start })
194
1365592
    }
195

            
196
162
    fn parse_flag(&mut self) -> Result<bool, SvgPathParseError> {
197
162
        self.skip_whitespace_and_commas();
198
162
        match self.input.get(self.pos) {
199
            Some(b'0') => {
200
121
                self.pos += 1;
201
121
                Ok(false)
202
            }
203
            Some(b'1') => {
204
26
                self.pos += 1;
205
26
                Ok(true)
206
            }
207
15
            _ => Err(SvgPathParseError::InvalidArcFlag { pos: self.pos }),
208
        }
209
162
    }
210

            
211
682602
    fn parse_coordinate_pair(&mut self) -> Result<(f32, f32), SvgPathParseError> {
212
682602
        let x = self.parse_number()?;
213
682536
        let y = self.parse_number()?;
214
682506
        Ok((x, y))
215
682602
    }
216

            
217
682507
    fn make_absolute(&self, x: f32, y: f32, relative: bool) -> SvgPoint {
218
682507
        if relative {
219
65457
            SvgPoint {
220
65457
                x: self.current.x + x,
221
65457
                y: self.current.y + y,
222
65457
            }
223
        } else {
224
617050
            SvgPoint { x, y }
225
        }
226
682507
    }
227

            
228
613077
    fn handle_line_to(
229
613077
        &mut self,
230
613077
        relative: bool,
231
613077
        elements: &mut Vec<SvgPathElement>,
232
613077
    ) -> Result<(), SvgPathParseError> {
233
613077
        let (x, y) = self.parse_coordinate_pair()?;
234
613046
        let end = self.make_absolute(x, y, relative);
235
613046
        elements.push(SvgPathElement::Line(SvgLine {
236
613046
            start: self.current,
237
613046
            end,
238
613046
        }));
239
613046
        self.current = end;
240
613046
        self.last_control = None;
241
613046
        Ok(())
242
613077
    }
243

            
244
39
    fn handle_horizontal_to(
245
39
        &mut self,
246
39
        relative: bool,
247
39
        elements: &mut Vec<SvgPathElement>,
248
39
    ) -> Result<(), SvgPathParseError> {
249
39
        let x = self.parse_number()?;
250
30
        let abs_x = if relative { self.current.x + x } else { x };
251
30
        let end = SvgPoint {
252
30
            x: abs_x,
253
30
            y: self.current.y,
254
30
        };
255
30
        elements.push(SvgPathElement::Line(SvgLine {
256
30
            start: self.current,
257
30
            end,
258
30
        }));
259
30
        self.current = end;
260
30
        self.last_control = None;
261
30
        Ok(())
262
39
    }
263

            
264
119
    fn handle_vertical_to(
265
119
        &mut self,
266
119
        relative: bool,
267
119
        elements: &mut Vec<SvgPathElement>,
268
119
    ) -> Result<(), SvgPathParseError> {
269
119
        let y = self.parse_number()?;
270
112
        let abs_y = if relative { self.current.y + y } else { y };
271
112
        let end = SvgPoint {
272
112
            x: self.current.x,
273
112
            y: abs_y,
274
112
        };
275
112
        elements.push(SvgPathElement::Line(SvgLine {
276
112
            start: self.current,
277
112
            end,
278
112
        }));
279
112
        self.current = end;
280
112
        self.last_control = None;
281
112
        Ok(())
282
119
    }
283

            
284
    #[allow(clippy::similar_names)] // domain-standard coordinate/control-point names
285
15612
    fn handle_cubic_to(
286
15612
        &mut self,
287
15612
        relative: bool,
288
15612
        elements: &mut Vec<SvgPathElement>,
289
15612
    ) -> Result<(), SvgPathParseError> {
290
15612
        let (c1x, c1y) = self.parse_coordinate_pair()?;
291
15603
        let (c2x, c2y) = self.parse_coordinate_pair()?;
292
15603
        let (ex, ey) = self.parse_coordinate_pair()?;
293
15603
        let ctrl_1 = self.make_absolute(c1x, c1y, relative);
294
15603
        let ctrl_2 = self.make_absolute(c2x, c2y, relative);
295
15603
        let end = self.make_absolute(ex, ey, relative);
296
15603
        elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
297
15603
            start: self.current,
298
15603
            ctrl_1,
299
15603
            ctrl_2,
300
15603
            end,
301
15603
        }));
302
15603
        self.last_control = Some(ctrl_2);
303
15603
        self.current = end;
304
15603
        Ok(())
305
15612
    }
306

            
307
    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
308
    #[allow(clippy::similar_names)] // domain-standard coordinate/control-point names
309
7042
    fn handle_smooth_cubic_to(
310
7042
        &mut self,
311
7042
        relative: bool,
312
7042
        elements: &mut Vec<SvgPathElement>,
313
7042
    ) -> Result<(), SvgPathParseError> {
314
7042
        let ctrl_1 = match self.last_control {
315
4204
            Some(lc) if matches!(self.last_command.to_ascii_uppercase(), b'C' | b'S') => SvgPoint {
316
4203
                x: 2.0 * self.current.x - lc.x,
317
4203
                y: 2.0 * self.current.y - lc.y,
318
4203
            },
319
2839
            _ => self.current,
320
        };
321
7042
        let (c2x, c2y) = self.parse_coordinate_pair()?;
322
7039
        let (ex, ey) = self.parse_coordinate_pair()?;
323
7039
        let ctrl_2 = self.make_absolute(c2x, c2y, relative);
324
7039
        let end = self.make_absolute(ex, ey, relative);
325
7039
        elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
326
7039
            start: self.current,
327
7039
            ctrl_1,
328
7039
            ctrl_2,
329
7039
            end,
330
7039
        }));
331
7039
        self.last_control = Some(ctrl_2);
332
7039
        self.current = end;
333
7039
        Ok(())
334
7042
    }
335

            
336
35
    fn handle_quadratic_to(
337
35
        &mut self,
338
35
        relative: bool,
339
35
        elements: &mut Vec<SvgPathElement>,
340
35
    ) -> Result<(), SvgPathParseError> {
341
35
        let (cx, cy) = self.parse_coordinate_pair()?;
342
26
        let (ex, ey) = self.parse_coordinate_pair()?;
343
26
        let ctrl = self.make_absolute(cx, cy, relative);
344
26
        let end = self.make_absolute(ex, ey, relative);
345
26
        elements.push(SvgPathElement::QuadraticCurve(SvgQuadraticCurve {
346
26
            start: self.current,
347
26
            ctrl,
348
26
            end,
349
26
        }));
350
26
        self.last_control = Some(ctrl);
351
26
        self.current = end;
352
26
        Ok(())
353
35
    }
354

            
355
    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target
356
                                       // +fma; keep explicit a*b+c
357
19
    fn handle_smooth_quadratic_to(
358
19
        &mut self,
359
19
        relative: bool,
360
19
        elements: &mut Vec<SvgPathElement>,
361
19
    ) -> Result<(), SvgPathParseError> {
362
19
        let ctrl = match self.last_control {
363
16
            Some(lc) if matches!(self.last_command.to_ascii_uppercase(), b'Q' | b'T') => SvgPoint {
364
15
                x: 2.0 * self.current.x - lc.x,
365
15
                y: 2.0 * self.current.y - lc.y,
366
15
            },
367
4
            _ => self.current,
368
        };
369
19
        let (ex, ey) = self.parse_coordinate_pair()?;
370
18
        let end = self.make_absolute(ex, ey, relative);
371
18
        elements.push(SvgPathElement::QuadraticCurve(SvgQuadraticCurve {
372
18
            start: self.current,
373
18
            ctrl,
374
18
            end,
375
18
        }));
376
18
        self.last_control = Some(ctrl);
377
18
        self.current = end;
378
18
        Ok(())
379
19
    }
380

            
381
83
    fn handle_arc_to(
382
83
        &mut self,
383
83
        relative: bool,
384
83
        elements: &mut Vec<SvgPathElement>,
385
83
    ) -> Result<(), SvgPathParseError> {
386
83
        let rx = self.parse_number()?.abs();
387
77
        let ry = self.parse_number()?.abs();
388
75
        let x_rotation = self.parse_number()?;
389
75
        let large_arc = self.parse_flag()?;
390
71
        let sweep = self.parse_flag()?;
391
70
        let (ex, ey) = self.parse_coordinate_pair()?;
392
69
        let end = self.make_absolute(ex, ey, relative);
393
69
        arc_to_cubics(
394
69
            self.current,
395
69
            end,
396
69
            rx,
397
69
            ry,
398
69
            x_rotation,
399
69
            large_arc,
400
69
            sweep,
401
69
            elements,
402
        );
403
69
        self.current = end;
404
69
        self.last_control = None;
405
69
        Ok(())
406
83
    }
407
}
408

            
409
/// Parse an SVG path `d` attribute string into a `SvgMultiPolygon`.
410
///
411
/// Each M/m command starts a new subpath (ring). All 14 SVG path commands are
412
/// supported including arcs (converted to cubic beziers).
413
///
414
/// # Panics
415
///
416
/// Panics if the path tokenizer signals a command but then yields no token
417
/// (an internal parser invariant that should not occur for any input).
418
#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
419
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
420
/// # Errors
421
///
422
/// Returns an error if `d` is not a valid SVG path-data string.
423
3824
pub fn parse_svg_path_d(d: &str) -> Result<SvgMultiPolygon, SvgPathParseError> {
424
3824
    let d = d.trim();
425
3824
    if d.is_empty() {
426
84
        return Err(SvgPathParseError::EmptyPath);
427
3740
    }
428

            
429
3740
    let mut parser = PathParser::new(d.as_bytes());
430
3740
    let mut rings: Vec<SvgPath> = Vec::new();
431
3740
    let mut current_elements: Vec<SvgPathElement> = Vec::new();
432

            
433
3740
    parser.skip_whitespace();
434

            
435
641886
    while !parser.at_end() {
436
638531
        parser.skip_whitespace_and_commas();
437
638531
        if parser.at_end() {
438
1
            break;
439
638530
        }
440

            
441
638530
        let b = parser.peek().unwrap();
442

            
443
        // Determine if this is a command letter or an implicit repeat
444
638530
        let cmd = if b.is_ascii_alphabetic() {
445
638115
            parser.pos += 1;
446
638115
            b
447
415
        } else if parser.last_command != 0 {
448
            // Implicit repeat: after M/m, implicit commands become L/l
449
181
            match parser.last_command {
450
41
                b'M' => b'L',
451
108
                b'm' => b'l',
452
                // AUDIT 2026-07-08: a `Z`/`z` closepath takes no arguments, so it
453
                // cannot be implicitly repeated. Reaching here means a stray
454
                // non-command byte followed a closepath (e.g. the `5` in "M0 0Z5").
455
                // The old `other => other` fell through to the `Z` arm, which
456
                // consumes zero bytes, so `pos` never advanced -> 100% CPU infinite
457
                // loop. Reject it as an unexpected character instead.
458
                b'Z' | b'z' => {
459
30
                    return Err(SvgPathParseError::UnexpectedChar {
460
30
                        pos: parser.pos,
461
30
                        ch: char_at(parser.input, parser.pos),
462
30
                    });
463
                }
464
2
                other => other,
465
            }
466
        } else {
467
234
            return Err(SvgPathParseError::UnexpectedChar {
468
234
                pos: parser.pos,
469
234
                ch: char_at(parser.input, parser.pos),
470
234
            });
471
        };
472

            
473
638266
        let relative = cmd.is_ascii_lowercase();
474
638266
        let cmd_upper = cmd.to_ascii_uppercase();
475

            
476
638266
        match cmd_upper {
477
            b'M' => {
478
                // Flush current subpath
479
8457
                if !current_elements.is_empty() {
480
12
                    rings.push(SvgPath {
481
12
                        items: SvgPathElementVec::from_vec(core::mem::take(&mut current_elements)),
482
12
                    });
483
8445
                }
484
8457
                let (x, y) = parser.parse_coordinate_pair()?;
485
8426
                let pt = parser.make_absolute(x, y, relative);
486
8426
                parser.current = pt;
487
8426
                parser.subpath_start = pt;
488
8426
                parser.last_control = None;
489
8426
                parser.last_command = cmd;
490
            }
491
            b'L' => {
492
612368
                parser.handle_line_to(relative, &mut current_elements)?;
493
612345
                parser.last_command = cmd;
494
            }
495
            b'H' => {
496
32
                parser.handle_horizontal_to(relative, &mut current_elements)?;
497
28
                parser.last_command = cmd;
498
            }
499
            b'V' => {
500
113
                parser.handle_vertical_to(relative, &mut current_elements)?;
501
111
                parser.last_command = cmd;
502
            }
503
            b'C' => {
504
4469
                parser.handle_cubic_to(relative, &mut current_elements)?;
505
4466
                parser.last_command = cmd;
506
            }
507
            b'S' => {
508
4686
                parser.handle_smooth_cubic_to(relative, &mut current_elements)?;
509
4683
                parser.last_command = cmd;
510
            }
511
            b'Q' => {
512
29
                parser.handle_quadratic_to(relative, &mut current_elements)?;
513
26
                parser.last_command = cmd;
514
            }
515
            b'T' => {
516
16
                parser.handle_smooth_quadratic_to(relative, &mut current_elements)?;
517
15
                parser.last_command = cmd;
518
            }
519
            b'A' => {
520
33
                parser.handle_arc_to(relative, &mut current_elements)?;
521
30
                parser.last_command = cmd;
522
            }
523
            b'Z' => {
524
                // Close subpath
525
8018
                let dx = parser.current.x - parser.subpath_start.x;
526
8018
                let dy = parser.current.y - parser.subpath_start.y;
527
8018
                if dx * dx + dy * dy > CLOSEPATH_EPSILON * CLOSEPATH_EPSILON {
528
5285
                    current_elements.push(SvgPathElement::Line(SvgLine {
529
5285
                        start: parser.current,
530
5285
                        end: parser.subpath_start,
531
5285
                    }));
532
7721
                }
533
8018
                parser.current = parser.subpath_start;
534
8018
                parser.last_control = None;
535
8018
                parser.last_command = cmd;
536

            
537
                // Flush current subpath
538
8018
                if !current_elements.is_empty() {
539
7963
                    rings.push(SvgPath {
540
7963
                        items: SvgPathElementVec::from_vec(core::mem::take(&mut current_elements)),
541
7963
                    });
542
7963
                }
543
            }
544
            _ => {
545
45
                return Err(SvgPathParseError::UnexpectedChar {
546
45
                    pos: parser.pos - 1,
547
45
                    ch: cmd as char,
548
45
                });
549
            }
550
        }
551

            
552
        // After processing one argument group, try to consume more
553
        // argument groups for the same command (implicit repeats)
554
638148
        if cmd_upper != b'M' && cmd_upper != b'Z' {
555
            loop {
556
635929
                parser.skip_whitespace_and_commas();
557
635929
                if parser.at_end() {
558
375
                    break;
559
635554
                }
560
635554
                let next = parser.peek().unwrap();
561
635554
                if next.is_ascii_alphabetic() {
562
621325
                    break; // Next command letter
563
14229
                }
564
14229
                if !parser.has_number() {
565
2
                    break;
566
14227
                }
567

            
568
                // Implicit repeat of the same command
569
14227
                match cmd_upper {
570
701
                    b'L' => parser.handle_line_to(relative, &mut current_elements)?,
571
                    b'H' => parser.handle_horizontal_to(relative, &mut current_elements)?,
572
                    b'V' => parser.handle_vertical_to(relative, &mut current_elements)?,
573
11136
                    b'C' => parser.handle_cubic_to(relative, &mut current_elements)?,
574
2353
                    b'S' => parser.handle_smooth_cubic_to(relative, &mut current_elements)?,
575
                    b'Q' => parser.handle_quadratic_to(relative, &mut current_elements)?,
576
1
                    b'T' => parser.handle_smooth_quadratic_to(relative, &mut current_elements)?,
577
36
                    b'A' => parser.handle_arc_to(relative, &mut current_elements)?,
578
                    _ => break,
579
                }
580
            }
581
16444
        }
582
    }
583

            
584
    // Flush any remaining elements
585
3356
    if !current_elements.is_empty() {
586
374
        rings.push(SvgPath {
587
374
            items: SvgPathElementVec::from_vec(current_elements),
588
374
        });
589
2990
    }
590

            
591
    // A `d` made up solely of comma/whitespace filler (e.g. ",") consumes to EOF
592
    // without ever reading a command and used to be accepted as an empty Ok. The SVG
593
    // path grammar requires a moveto to start; a bare separator is only valid BETWEEN
594
    // commands, never as the whole string.
595
3356
    if parser.last_command == 0 && rings.is_empty() {
596
1
        return Err(SvgPathParseError::UnexpectedChar {
597
1
            pos: 0,
598
1
            ch: char_at(parser.input, 0),
599
1
        });
600
3355
    }
601

            
602
3355
    Ok(SvgMultiPolygon {
603
3355
        rings: SvgPathVec::from_vec(rings),
604
3355
    })
605
3824
}
606

            
607
/// Convert an SVG arc to 1–4 cubic bezier curves.
608
///
609
/// Implements the SVG spec arc endpoint-to-center parameterization (Appendix F.6).
610
#[allow(clippy::suboptimal_flops)]
611
// mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
612
// n_segs is a tiny arc-quadrant count (<= ~6) and its loop index; the float<->usize
613
// casts are exact for these bounded values.
614
#[allow(
615
    clippy::cast_possible_truncation,
616
    clippy::cast_precision_loss,
617
    clippy::cast_sign_loss
618
)]
619
#[allow(clippy::similar_names)] // domain-standard coordinate/control-point names
620
338
fn arc_to_cubics(
621
338
    start: SvgPoint,
622
338
    end: SvgPoint,
623
338
    mut rx: f32,
624
338
    mut ry: f32,
625
338
    x_rotation_deg: f32,
626
338
    large_arc: bool,
627
338
    sweep: bool,
628
338
    out: &mut Vec<SvgPathElement>,
629
338
) {
630
    // Degenerate cases
631
338
    if (start.x - end.x).abs() < POINT_EPSILON && (start.y - end.y).abs() < POINT_EPSILON {
632
3
        return;
633
335
    }
634
335
    if rx < POINT_EPSILON || ry < POINT_EPSILON {
635
4
        out.push(SvgPathElement::Line(SvgLine { start, end }));
636
4
        return;
637
331
    }
638

            
639
331
    let phi = x_rotation_deg.to_radians();
640
331
    let cos_phi = phi.cos();
641
331
    let sin_phi = phi.sin();
642

            
643
    // Step 1: Compute (x1', y1')
644
331
    let dx = (start.x - end.x) / 2.0;
645
331
    let dy = (start.y - end.y) / 2.0;
646
331
    let x1p = cos_phi * dx + sin_phi * dy;
647
331
    let y1p = -sin_phi * dx + cos_phi * dy;
648

            
649
    // Step 2: Compute (cx', cy') - correct radii if too small
650
331
    let x1p2 = x1p * x1p;
651
331
    let y1p2 = y1p * y1p;
652
331
    let mut rx2 = rx * rx;
653
331
    let mut ry2 = ry * ry;
654

            
655
331
    let lambda = x1p2 / rx2 + y1p2 / ry2;
656
331
    if lambda > 1.0 {
657
5
        let sqrt_lambda = lambda.sqrt();
658
5
        rx *= sqrt_lambda;
659
5
        ry *= sqrt_lambda;
660
5
        rx2 = rx * rx;
661
5
        ry2 = ry * ry;
662
326
    }
663

            
664
331
    let num = (rx2 * ry2 - rx2 * y1p2 - ry2 * x1p2).max(0.0);
665
331
    let den = rx2 * y1p2 + ry2 * x1p2;
666
331
    let sq = if den > 0.0 { (num / den).sqrt() } else { 0.0 };
667

            
668
331
    let sign = if large_arc == sweep { -1.0 } else { 1.0 };
669
331
    let cxp = sign * sq * (rx * y1p / ry);
670
331
    let cyp = sign * sq * -(ry * x1p / rx);
671

            
672
    // Step 3: Compute (cx, cy) from (cx', cy')
673
331
    let mx = f32::midpoint(start.x, end.x);
674
331
    let my = f32::midpoint(start.y, end.y);
675
331
    let cx = cos_phi * cxp - sin_phi * cyp + mx;
676
331
    let cy = sin_phi * cxp + cos_phi * cyp + my;
677

            
678
    // Step 4: Compute theta1 and dtheta
679
331
    let theta1 = angle_between(1.0, 0.0, (x1p - cxp) / rx, (y1p - cyp) / ry);
680
331
    let mut dtheta = angle_between(
681
331
        (x1p - cxp) / rx,
682
331
        (y1p - cyp) / ry,
683
331
        (-x1p - cxp) / rx,
684
331
        (-y1p - cyp) / ry,
685
    );
686

            
687
331
    if !sweep && dtheta > 0.0 {
688
68
        dtheta -= core::f32::consts::TAU;
689
263
    } else if sweep && dtheta < 0.0 {
690
66
        dtheta += core::f32::consts::TAU;
691
197
    }
692

            
693
    // Split into segments of at most PI/2
694
331
    let n_segs = (dtheta.abs() / (core::f32::consts::FRAC_PI_2 + ARC_SPLIT_FUDGE)).ceil() as usize;
695
331
    let n_segs = n_segs.max(1);
696
331
    let seg_angle = dtheta / n_segs as f32;
697

            
698
331
    let mut prev = start;
699
739
    for i in 0..n_segs {
700
739
        let t1 = theta1 + seg_angle * i as f32;
701
739
        let t2 = theta1 + seg_angle * (i + 1) as f32;
702

            
703
739
        let (c1, c2, ep) = arc_segment_to_cubic(cx, cy, rx, ry, cos_phi, sin_phi, t1, t2);
704

            
705
739
        let seg_end = if i + 1 == n_segs { end } else { ep };
706
739
        out.push(SvgPathElement::CubicCurve(SvgCubicCurve {
707
739
            start: prev,
708
739
            ctrl_1: c1,
709
739
            ctrl_2: c2,
710
739
            end: seg_end,
711
739
        }));
712
739
        prev = seg_end;
713
    }
714
338
}
715

            
716
/// Compute the angle between two vectors.
717
#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma;
718
                                   // keep explicit a*b+c
719
933
fn angle_between(ux: f32, uy: f32, vx: f32, vy: f32) -> f32 {
720
933
    let dot = ux * vx + uy * vy;
721
933
    let len = ((ux * ux + uy * uy) * (vx * vx + vy * vy)).sqrt();
722
933
    if len < ZERO_LENGTH_EPSILON {
723
36
        return 0.0;
724
897
    }
725
897
    let cos_val = (dot / len).clamp(-1.0, 1.0);
726
897
    let angle = cos_val.acos();
727
897
    if ux * vy - uy * vx < 0.0 {
728
406
        -angle
729
    } else {
730
491
        angle
731
    }
732
933
}
733

            
734
/// Convert a single arc segment (<=90 degrees) to a cubic bezier.
735
#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
736
#[allow(clippy::similar_names)] // domain-standard coordinate/control-point names
737
749
fn arc_segment_to_cubic(
738
749
    cx: f32,
739
749
    cy: f32,
740
749
    rx: f32,
741
749
    ry: f32,
742
749
    cos_phi: f32,
743
749
    sin_phi: f32,
744
749
    theta1: f32,
745
749
    theta2: f32,
746
749
) -> (SvgPoint, SvgPoint, SvgPoint) {
747
749
    let alpha = 4.0 / 3.0 * ((theta2 - theta1) / 4.0).tan();
748

            
749
749
    let cos1 = theta1.cos();
750
749
    let sin1 = theta1.sin();
751
749
    let cos2 = theta2.cos();
752
749
    let sin2 = theta2.sin();
753

            
754
    // Control point 1 (relative to unit circle)
755
749
    let dx1 = rx * (cos1 - alpha * sin1);
756
749
    let dy1 = ry * (sin1 + alpha * cos1);
757
    // Control point 2
758
749
    let dx2 = rx * (cos2 + alpha * sin2);
759
749
    let dy2 = ry * (sin2 - alpha * cos2);
760
    // End point
761
749
    let dx3 = rx * cos2;
762
749
    let dy3 = ry * sin2;
763

            
764
749
    let c1 = SvgPoint {
765
749
        x: cos_phi * dx1 - sin_phi * dy1 + cx,
766
749
        y: sin_phi * dx1 + cos_phi * dy1 + cy,
767
749
    };
768
749
    let c2 = SvgPoint {
769
749
        x: cos_phi * dx2 - sin_phi * dy2 + cx,
770
749
        y: sin_phi * dx2 + cos_phi * dy2 + cy,
771
749
    };
772
749
    let ep = SvgPoint {
773
749
        x: cos_phi * dx3 - sin_phi * dy3 + cx,
774
749
        y: sin_phi * dx3 + cos_phi * dy3 + cy,
775
749
    };
776

            
777
749
    (c1, c2, ep)
778
749
}
779

            
780
/// Approximate a circle with 4 cubic bezier curves.
781
///
782
/// Uses the standard kappa constant (0.5522847498) for quarter-arc approximation.
783
#[must_use]
784
153
pub fn svg_circle_to_paths(cx: f32, cy: f32, r: f32) -> SvgPath {
785
153
    let k = r * KAPPA;
786

            
787
153
    let elements = vec![
788
        // Top to right
789
153
        SvgPathElement::CubicCurve(SvgCubicCurve {
790
153
            start: SvgPoint { x: cx, y: cy - r },
791
153
            ctrl_1: SvgPoint {
792
153
                x: cx + k,
793
153
                y: cy - r,
794
153
            },
795
153
            ctrl_2: SvgPoint {
796
153
                x: cx + r,
797
153
                y: cy - k,
798
153
            },
799
153
            end: SvgPoint { x: cx + r, y: cy },
800
153
        }),
801
        // Right to bottom
802
153
        SvgPathElement::CubicCurve(SvgCubicCurve {
803
153
            start: SvgPoint { x: cx + r, y: cy },
804
153
            ctrl_1: SvgPoint {
805
153
                x: cx + r,
806
153
                y: cy + k,
807
153
            },
808
153
            ctrl_2: SvgPoint {
809
153
                x: cx + k,
810
153
                y: cy + r,
811
153
            },
812
153
            end: SvgPoint { x: cx, y: cy + r },
813
153
        }),
814
        // Bottom to left
815
153
        SvgPathElement::CubicCurve(SvgCubicCurve {
816
153
            start: SvgPoint { x: cx, y: cy + r },
817
153
            ctrl_1: SvgPoint {
818
153
                x: cx - k,
819
153
                y: cy + r,
820
153
            },
821
153
            ctrl_2: SvgPoint {
822
153
                x: cx - r,
823
153
                y: cy + k,
824
153
            },
825
153
            end: SvgPoint { x: cx - r, y: cy },
826
153
        }),
827
        // Left to top
828
153
        SvgPathElement::CubicCurve(SvgCubicCurve {
829
153
            start: SvgPoint { x: cx - r, y: cy },
830
153
            ctrl_1: SvgPoint {
831
153
                x: cx - r,
832
153
                y: cy - k,
833
153
            },
834
153
            ctrl_2: SvgPoint {
835
153
                x: cx - k,
836
153
                y: cy - r,
837
153
            },
838
153
            end: SvgPoint { x: cx, y: cy - r },
839
153
        }),
840
    ];
841

            
842
153
    SvgPath {
843
153
        items: SvgPathElementVec::from_vec(elements),
844
153
    }
845
153
}
846

            
847
/// Convert an SVG `<rect>` to a path with optional rounded corners.
848
///
849
/// If `rx` and `ry` are both 0, produces 4 line segments.
850
/// Otherwise, produces lines for straight edges and cubic curves for corners.
851
#[must_use]
852
// builds the rounded-rect path segment-by-segment with a matching capacity hint;
853
// a `vec![..]` literal of the 8 multi-line elements would be less readable here.
854
#[allow(clippy::vec_init_then_push)]
855
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one
856
                                 // branch per input variant)
857
60865
pub fn svg_rect_to_path(x: f32, y: f32, w: f32, h: f32, rx: f32, ry: f32) -> SvgPath {
858
60865
    let rx = rx.min(w / 2.0);
859
60865
    let ry = ry.min(h / 2.0);
860

            
861
60865
    if rx < CLOSEPATH_EPSILON && ry < CLOSEPATH_EPSILON {
862
        // Simple rectangle: 4 lines
863
60786
        let tl = SvgPoint { x, y };
864
60786
        let tr = SvgPoint { x: x + w, y };
865
60786
        let br = SvgPoint { x: x + w, y: y + h };
866
60786
        let bl = SvgPoint { x, y: y + h };
867

            
868
60786
        let elements = vec![
869
60786
            SvgPathElement::Line(SvgLine { start: tl, end: tr }),
870
60786
            SvgPathElement::Line(SvgLine { start: tr, end: br }),
871
60786
            SvgPathElement::Line(SvgLine { start: br, end: bl }),
872
60786
            SvgPathElement::Line(SvgLine { start: bl, end: tl }),
873
        ];
874

            
875
60786
        return SvgPath {
876
60786
            items: SvgPathElementVec::from_vec(elements),
877
60786
        };
878
79
    }
879

            
880
    // Rounded rectangle
881
79
    let kx = rx * KAPPA;
882
79
    let ky = ry * KAPPA;
883

            
884
79
    let mut elements = Vec::with_capacity(8);
885

            
886
    // Top edge (left to right)
887
79
    elements.push(SvgPathElement::Line(SvgLine {
888
79
        start: SvgPoint { x: x + rx, y },
889
79
        end: SvgPoint { x: x + w - rx, y },
890
79
    }));
891
    // Top-right corner
892
79
    elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
893
79
        start: SvgPoint { x: x + w - rx, y },
894
79
        ctrl_1: SvgPoint {
895
79
            x: x + w - rx + kx,
896
79
            y,
897
79
        },
898
79
        ctrl_2: SvgPoint {
899
79
            x: x + w,
900
79
            y: y + ry - ky,
901
79
        },
902
79
        end: SvgPoint {
903
79
            x: x + w,
904
79
            y: y + ry,
905
79
        },
906
79
    }));
907
    // Right edge
908
79
    elements.push(SvgPathElement::Line(SvgLine {
909
79
        start: SvgPoint {
910
79
            x: x + w,
911
79
            y: y + ry,
912
79
        },
913
79
        end: SvgPoint {
914
79
            x: x + w,
915
79
            y: y + h - ry,
916
79
        },
917
79
    }));
918
    // Bottom-right corner
919
79
    elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
920
79
        start: SvgPoint {
921
79
            x: x + w,
922
79
            y: y + h - ry,
923
79
        },
924
79
        ctrl_1: SvgPoint {
925
79
            x: x + w,
926
79
            y: y + h - ry + ky,
927
79
        },
928
79
        ctrl_2: SvgPoint {
929
79
            x: x + w - rx + kx,
930
79
            y: y + h,
931
79
        },
932
79
        end: SvgPoint {
933
79
            x: x + w - rx,
934
79
            y: y + h,
935
79
        },
936
79
    }));
937
    // Bottom edge (right to left)
938
79
    elements.push(SvgPathElement::Line(SvgLine {
939
79
        start: SvgPoint {
940
79
            x: x + w - rx,
941
79
            y: y + h,
942
79
        },
943
79
        end: SvgPoint {
944
79
            x: x + rx,
945
79
            y: y + h,
946
79
        },
947
79
    }));
948
    // Bottom-left corner
949
79
    elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
950
79
        start: SvgPoint {
951
79
            x: x + rx,
952
79
            y: y + h,
953
79
        },
954
79
        ctrl_1: SvgPoint {
955
79
            x: x + rx - kx,
956
79
            y: y + h,
957
79
        },
958
79
        ctrl_2: SvgPoint {
959
79
            x,
960
79
            y: y + h - ry + ky,
961
79
        },
962
79
        end: SvgPoint { x, y: y + h - ry },
963
79
    }));
964
    // Left edge
965
79
    elements.push(SvgPathElement::Line(SvgLine {
966
79
        start: SvgPoint { x, y: y + h - ry },
967
79
        end: SvgPoint { x, y: y + ry },
968
79
    }));
969
    // Top-left corner
970
79
    elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
971
79
        start: SvgPoint { x, y: y + ry },
972
79
        ctrl_1: SvgPoint { x, y: y + ry - ky },
973
79
        ctrl_2: SvgPoint { x: x + rx - kx, y },
974
79
        end: SvgPoint { x: x + rx, y },
975
79
    }));
976

            
977
79
    SvgPath {
978
79
        items: SvgPathElementVec::from_vec(elements),
979
79
    }
980
60865
}
981

            
982
#[cfg(test)]
983
mod tests {
984
    use super::*;
985

            
986
    /// AUDIT 2026-07-08 regression: `"M0 0Z5"` used to spin at 100% CPU forever
987
    /// because the trailing `5` re-derived `cmd = Z` (zero-length consume) and
988
    /// the cursor never advanced. It must now terminate with `UnexpectedChar`.
989
    #[test]
990
1
    fn m0_0z5_does_not_hang() {
991
1
        let err = parse_svg_path_d("M0 0Z5").unwrap_err();
992
1
        match err {
993
1
            SvgPathParseError::UnexpectedChar { ch, .. } => assert_eq!(ch, '5'),
994
            other => panic!("expected UnexpectedChar, got {other:?}"),
995
        }
996
1
    }
997

            
998
    /// Any digit or symbol directly after a closepath is rejected, not looped on.
999
    #[test]
1
    fn stray_byte_after_closepath_rejected() {
3
        for s in ["M0 0Z9", "m0 0z-", "M0 0Z."] {
3
            assert!(
                matches!(
3
                    parse_svg_path_d(s),
                    Err(SvgPathParseError::UnexpectedChar { .. })
                ),
                "expected UnexpectedChar for {s:?}"
            );
        }
1
    }
    /// A leading non-command byte reports the real Unicode char, not a Latin-1
    /// reinterpretation of a single UTF-8 byte (the old `b as char`).
    #[test]
1
    fn error_char_is_unicode_not_byte() {
        // 'ü' is two UTF-8 bytes; `b as char` would have yielded a mojibake char.
1
        let err = parse_svg_path_d("ü10 10").unwrap_err();
1
        match err {
1
            SvgPathParseError::UnexpectedChar { ch, pos } => {
1
                assert_eq!(ch, 'ü');
1
                assert_eq!(pos, 0);
            }
            other => panic!("expected UnexpectedChar, got {other:?}"),
        }
1
    }
    /// A well-formed closepath followed by a real command still parses.
    #[test]
1
    fn valid_closepath_then_command_ok() {
1
        let parsed = parse_svg_path_d("M0 0 L10 0 Z M20 20 L30 20 Z");
1
        assert!(parsed.is_ok(), "valid multi-subpath path should parse");
1
    }
}
#[cfg(test)]
#[path = "path_parser_test.rs"]
mod path_parser_test;