azul-core 0.0.16

Common datatypes used for the Azul document object model, shared across all azul-* crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
//! SVG `d=""` path data parser.
//!
//! Parses the `d` attribute of SVG `<path>` elements into `SvgMultiPolygon`
//! geometry, supporting all 14 SVG path commands (M/m, L/l, H/h, V/v,
//! C/c, S/s, Q/q, T/t, A/a, Z/z).

use alloc::{string::String, vec::Vec};
use azul_css::props::basic::{SvgCubicCurve, SvgPoint, SvgQuadraticCurve};

use crate::svg::{
    SvgLine, SvgMultiPolygon, SvgPath, SvgPathElement, SvgPathElementVec, SvgPathVec,
};

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

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

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

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

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

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

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

/// Human-readable error messages for SVG path parse failures.
impl core::fmt::Display for SvgPathParseError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::EmptyPath => write!(f, "empty path"),
            Self::UnexpectedChar { pos, ch } => {
                write!(f, "unexpected char '{ch}' at byte {pos}")
            }
            Self::ExpectedNumber { pos } => write!(f, "expected number at byte {pos}"),
            Self::InvalidArcFlag { pos } => write!(f, "invalid arc flag at byte {pos}"),
        }
    }
}

/// Internal parser state.
struct PathParser<'a> {
    input: &'a [u8],
    pos: usize,
    current: SvgPoint,
    subpath_start: SvgPoint,
    last_control: Option<SvgPoint>,
    last_command: u8,
}

impl<'a> PathParser<'a> {
    const fn new(input: &'a [u8]) -> Self {
        Self {
            input,
            pos: 0,
            current: SvgPoint { x: 0.0, y: 0.0 },
            subpath_start: SvgPoint { x: 0.0, y: 0.0 },
            last_control: None,
            last_command: 0,
        }
    }

    const fn at_end(&self) -> bool {
        self.pos >= self.input.len()
    }

    fn peek(&self) -> Option<u8> {
        self.input.get(self.pos).copied()
    }

    fn skip_whitespace_and_commas(&mut self) {
        while let Some(&b) = self.input.get(self.pos) {
            if b == b' ' || b == b'\t' || b == b'\n' || b == b'\r' || b == b',' {
                self.pos += 1;
            } else {
                break;
            }
        }
    }

    fn skip_whitespace(&mut self) {
        while let Some(&b) = self.input.get(self.pos) {
            if b == b' ' || b == b'\t' || b == b'\n' || b == b'\r' {
                self.pos += 1;
            } else {
                break;
            }
        }
    }

    /// Returns true if the current position looks like the start of a number.
    fn has_number(&self) -> bool {
        match self.input.get(self.pos) {
            Some(b'+' | b'-' | b'.') => true,
            Some(b) if b.is_ascii_digit() => true,
            _ => false,
        }
    }

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

        // Optional sign
        if let Some(&b) = self.input.get(self.pos) {
            if b == b'+' || b == b'-' {
                self.pos += 1;
            }
        }

        let mut has_digits = false;

        // Integer part
        while let Some(&b) = self.input.get(self.pos) {
            if b.is_ascii_digit() {
                self.pos += 1;
                has_digits = true;
            } else {
                break;
            }
        }

        // Decimal part
        if self.input.get(self.pos) == Some(&b'.') {
            self.pos += 1;
            while let Some(&b) = self.input.get(self.pos) {
                if b.is_ascii_digit() {
                    self.pos += 1;
                    has_digits = true;
                } else {
                    break;
                }
            }
        }

        if !has_digits {
            return Err(SvgPathParseError::ExpectedNumber { pos: start });
        }

        // Exponent
        if let Some(&b) = self.input.get(self.pos) {
            if b == b'e' || b == b'E' {
                self.pos += 1;
                if let Some(&b) = self.input.get(self.pos) {
                    if b == b'+' || b == b'-' {
                        self.pos += 1;
                    }
                }
                while let Some(&b) = self.input.get(self.pos) {
                    if b.is_ascii_digit() {
                        self.pos += 1;
                    } else {
                        break;
                    }
                }
            }
        }

        let s = core::str::from_utf8(&self.input[start..self.pos])
            .map_err(|_| SvgPathParseError::ExpectedNumber { pos: start })?;
        s.parse::<f32>()
            .map_err(|_| SvgPathParseError::ExpectedNumber { pos: start })
    }

    fn parse_flag(&mut self) -> Result<bool, SvgPathParseError> {
        self.skip_whitespace_and_commas();
        match self.input.get(self.pos) {
            Some(b'0') => {
                self.pos += 1;
                Ok(false)
            }
            Some(b'1') => {
                self.pos += 1;
                Ok(true)
            }
            _ => Err(SvgPathParseError::InvalidArcFlag { pos: self.pos }),
        }
    }

    fn parse_coordinate_pair(&mut self) -> Result<(f32, f32), SvgPathParseError> {
        let x = self.parse_number()?;
        let y = self.parse_number()?;
        Ok((x, y))
    }

    fn make_absolute(&self, x: f32, y: f32, relative: bool) -> SvgPoint {
        if relative {
            SvgPoint {
                x: self.current.x + x,
                y: self.current.y + y,
            }
        } else {
            SvgPoint { x, y }
        }
    }

    fn handle_line_to(
        &mut self,
        relative: bool,
        elements: &mut Vec<SvgPathElement>,
    ) -> Result<(), SvgPathParseError> {
        let (x, y) = self.parse_coordinate_pair()?;
        let end = self.make_absolute(x, y, relative);
        elements.push(SvgPathElement::Line(SvgLine {
            start: self.current,
            end,
        }));
        self.current = end;
        self.last_control = None;
        Ok(())
    }

    fn handle_horizontal_to(
        &mut self,
        relative: bool,
        elements: &mut Vec<SvgPathElement>,
    ) -> Result<(), SvgPathParseError> {
        let x = self.parse_number()?;
        let abs_x = if relative { self.current.x + x } else { x };
        let end = SvgPoint {
            x: abs_x,
            y: self.current.y,
        };
        elements.push(SvgPathElement::Line(SvgLine {
            start: self.current,
            end,
        }));
        self.current = end;
        self.last_control = None;
        Ok(())
    }

    fn handle_vertical_to(
        &mut self,
        relative: bool,
        elements: &mut Vec<SvgPathElement>,
    ) -> Result<(), SvgPathParseError> {
        let y = self.parse_number()?;
        let abs_y = if relative { self.current.y + y } else { y };
        let end = SvgPoint {
            x: self.current.x,
            y: abs_y,
        };
        elements.push(SvgPathElement::Line(SvgLine {
            start: self.current,
            end,
        }));
        self.current = end;
        self.last_control = None;
        Ok(())
    }

    #[allow(clippy::similar_names)] // domain-standard coordinate/control-point names
    fn handle_cubic_to(
        &mut self,
        relative: bool,
        elements: &mut Vec<SvgPathElement>,
    ) -> Result<(), SvgPathParseError> {
        let (c1x, c1y) = self.parse_coordinate_pair()?;
        let (c2x, c2y) = self.parse_coordinate_pair()?;
        let (ex, ey) = self.parse_coordinate_pair()?;
        let ctrl_1 = self.make_absolute(c1x, c1y, relative);
        let ctrl_2 = self.make_absolute(c2x, c2y, relative);
        let end = self.make_absolute(ex, ey, relative);
        elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
            start: self.current,
            ctrl_1,
            ctrl_2,
            end,
        }));
        self.last_control = Some(ctrl_2);
        self.current = end;
        Ok(())
    }

    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
    #[allow(clippy::similar_names)] // domain-standard coordinate/control-point names
    fn handle_smooth_cubic_to(
        &mut self,
        relative: bool,
        elements: &mut Vec<SvgPathElement>,
    ) -> Result<(), SvgPathParseError> {
        let ctrl_1 = match self.last_control {
            Some(lc) if matches!(self.last_command.to_ascii_uppercase(), b'C' | b'S') => SvgPoint {
                x: 2.0 * self.current.x - lc.x,
                y: 2.0 * self.current.y - lc.y,
            },
            _ => self.current,
        };
        let (c2x, c2y) = self.parse_coordinate_pair()?;
        let (ex, ey) = self.parse_coordinate_pair()?;
        let ctrl_2 = self.make_absolute(c2x, c2y, relative);
        let end = self.make_absolute(ex, ey, relative);
        elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
            start: self.current,
            ctrl_1,
            ctrl_2,
            end,
        }));
        self.last_control = Some(ctrl_2);
        self.current = end;
        Ok(())
    }

    fn handle_quadratic_to(
        &mut self,
        relative: bool,
        elements: &mut Vec<SvgPathElement>,
    ) -> Result<(), SvgPathParseError> {
        let (cx, cy) = self.parse_coordinate_pair()?;
        let (ex, ey) = self.parse_coordinate_pair()?;
        let ctrl = self.make_absolute(cx, cy, relative);
        let end = self.make_absolute(ex, ey, relative);
        elements.push(SvgPathElement::QuadraticCurve(SvgQuadraticCurve {
            start: self.current,
            ctrl,
            end,
        }));
        self.last_control = Some(ctrl);
        self.current = end;
        Ok(())
    }

    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
    fn handle_smooth_quadratic_to(
        &mut self,
        relative: bool,
        elements: &mut Vec<SvgPathElement>,
    ) -> Result<(), SvgPathParseError> {
        let ctrl = match self.last_control {
            Some(lc) if matches!(self.last_command.to_ascii_uppercase(), b'Q' | b'T') => SvgPoint {
                x: 2.0 * self.current.x - lc.x,
                y: 2.0 * self.current.y - lc.y,
            },
            _ => self.current,
        };
        let (ex, ey) = self.parse_coordinate_pair()?;
        let end = self.make_absolute(ex, ey, relative);
        elements.push(SvgPathElement::QuadraticCurve(SvgQuadraticCurve {
            start: self.current,
            ctrl,
            end,
        }));
        self.last_control = Some(ctrl);
        self.current = end;
        Ok(())
    }

    fn handle_arc_to(
        &mut self,
        relative: bool,
        elements: &mut Vec<SvgPathElement>,
    ) -> Result<(), SvgPathParseError> {
        let rx = self.parse_number()?.abs();
        let ry = self.parse_number()?.abs();
        let x_rotation = self.parse_number()?;
        let large_arc = self.parse_flag()?;
        let sweep = self.parse_flag()?;
        let (ex, ey) = self.parse_coordinate_pair()?;
        let end = self.make_absolute(ex, ey, relative);
        arc_to_cubics(
            self.current,
            end,
            rx,
            ry,
            x_rotation,
            large_arc,
            sweep,
            elements,
        );
        self.current = end;
        self.last_control = None;
        Ok(())
    }
}

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

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

    parser.skip_whitespace();

    while !parser.at_end() {
        parser.skip_whitespace_and_commas();
        if parser.at_end() {
            break;
        }

        let b = parser.peek().unwrap();

        // Determine if this is a command letter or an implicit repeat
        let cmd = if b.is_ascii_alphabetic() {
            parser.pos += 1;
            b
        } else if parser.last_command != 0 {
            // Implicit repeat: after M/m, implicit commands become L/l
            match parser.last_command {
                b'M' => b'L',
                b'm' => b'l',
                // AUDIT 2026-07-08: a `Z`/`z` closepath takes no arguments, so it
                // cannot be implicitly repeated. Reaching here means a stray
                // non-command byte followed a closepath (e.g. the `5` in "M0 0Z5").
                // The old `other => other` fell through to the `Z` arm, which
                // consumes zero bytes, so `pos` never advanced -> 100% CPU infinite
                // loop. Reject it as an unexpected character instead.
                b'Z' | b'z' => {
                    return Err(SvgPathParseError::UnexpectedChar {
                        pos: parser.pos,
                        ch: char_at(parser.input, parser.pos),
                    });
                }
                other => other,
            }
        } else {
            return Err(SvgPathParseError::UnexpectedChar {
                pos: parser.pos,
                ch: char_at(parser.input, parser.pos),
            });
        };

        let relative = cmd.is_ascii_lowercase();
        let cmd_upper = cmd.to_ascii_uppercase();

        match cmd_upper {
            b'M' => {
                // Flush current subpath
                if !current_elements.is_empty() {
                    rings.push(SvgPath {
                        items: SvgPathElementVec::from_vec(core::mem::take(&mut current_elements)),
                    });
                }
                let (x, y) = parser.parse_coordinate_pair()?;
                let pt = parser.make_absolute(x, y, relative);
                parser.current = pt;
                parser.subpath_start = pt;
                parser.last_control = None;
                parser.last_command = cmd;
            }
            b'L' => {
                parser.handle_line_to(relative, &mut current_elements)?;
                parser.last_command = cmd;
            }
            b'H' => {
                parser.handle_horizontal_to(relative, &mut current_elements)?;
                parser.last_command = cmd;
            }
            b'V' => {
                parser.handle_vertical_to(relative, &mut current_elements)?;
                parser.last_command = cmd;
            }
            b'C' => {
                parser.handle_cubic_to(relative, &mut current_elements)?;
                parser.last_command = cmd;
            }
            b'S' => {
                parser.handle_smooth_cubic_to(relative, &mut current_elements)?;
                parser.last_command = cmd;
            }
            b'Q' => {
                parser.handle_quadratic_to(relative, &mut current_elements)?;
                parser.last_command = cmd;
            }
            b'T' => {
                parser.handle_smooth_quadratic_to(relative, &mut current_elements)?;
                parser.last_command = cmd;
            }
            b'A' => {
                parser.handle_arc_to(relative, &mut current_elements)?;
                parser.last_command = cmd;
            }
            b'Z' => {
                // Close subpath
                let dx = parser.current.x - parser.subpath_start.x;
                let dy = parser.current.y - parser.subpath_start.y;
                if dx * dx + dy * dy > CLOSEPATH_EPSILON * CLOSEPATH_EPSILON {
                    current_elements.push(SvgPathElement::Line(SvgLine {
                        start: parser.current,
                        end: parser.subpath_start,
                    }));
                }
                parser.current = parser.subpath_start;
                parser.last_control = None;
                parser.last_command = cmd;

                // Flush current subpath
                if !current_elements.is_empty() {
                    rings.push(SvgPath {
                        items: SvgPathElementVec::from_vec(core::mem::take(&mut current_elements)),
                    });
                }
            }
            _ => {
                return Err(SvgPathParseError::UnexpectedChar {
                    pos: parser.pos - 1,
                    ch: cmd as char,
                });
            }
        }

        // After processing one argument group, try to consume more
        // argument groups for the same command (implicit repeats)
        if cmd_upper != b'M' && cmd_upper != b'Z' {
            loop {
                parser.skip_whitespace_and_commas();
                if parser.at_end() {
                    break;
                }
                let next = parser.peek().unwrap();
                if next.is_ascii_alphabetic() {
                    break; // Next command letter
                }
                if !parser.has_number() {
                    break;
                }

                // Implicit repeat of the same command
                match cmd_upper {
                    b'L' => parser.handle_line_to(relative, &mut current_elements)?,
                    b'H' => parser.handle_horizontal_to(relative, &mut current_elements)?,
                    b'V' => parser.handle_vertical_to(relative, &mut current_elements)?,
                    b'C' => parser.handle_cubic_to(relative, &mut current_elements)?,
                    b'S' => parser.handle_smooth_cubic_to(relative, &mut current_elements)?,
                    b'Q' => parser.handle_quadratic_to(relative, &mut current_elements)?,
                    b'T' => parser.handle_smooth_quadratic_to(relative, &mut current_elements)?,
                    b'A' => parser.handle_arc_to(relative, &mut current_elements)?,
                    _ => break,
                }
            }
        }
    }

    // Flush any remaining elements
    if !current_elements.is_empty() {
        rings.push(SvgPath {
            items: SvgPathElementVec::from_vec(current_elements),
        });
    }

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

    Ok(SvgMultiPolygon {
        rings: SvgPathVec::from_vec(rings),
    })
}

/// Convert an SVG arc to 1–4 cubic bezier curves.
///
/// Implements the SVG spec arc endpoint-to-center parameterization (Appendix F.6).
#[allow(clippy::suboptimal_flops)]
// mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
// n_segs is a tiny arc-quadrant count (<= ~6) and its loop index; the float<->usize
// casts are exact for these bounded values.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss
)]
#[allow(clippy::similar_names)] // domain-standard coordinate/control-point names
fn arc_to_cubics(
    start: SvgPoint,
    end: SvgPoint,
    mut rx: f32,
    mut ry: f32,
    x_rotation_deg: f32,
    large_arc: bool,
    sweep: bool,
    out: &mut Vec<SvgPathElement>,
) {
    // Degenerate cases
    if (start.x - end.x).abs() < POINT_EPSILON && (start.y - end.y).abs() < POINT_EPSILON {
        return;
    }
    if rx < POINT_EPSILON || ry < POINT_EPSILON {
        out.push(SvgPathElement::Line(SvgLine { start, end }));
        return;
    }

    let phi = x_rotation_deg.to_radians();
    let cos_phi = phi.cos();
    let sin_phi = phi.sin();

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

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

    let lambda = x1p2 / rx2 + y1p2 / ry2;
    if lambda > 1.0 {
        let sqrt_lambda = lambda.sqrt();
        rx *= sqrt_lambda;
        ry *= sqrt_lambda;
        rx2 = rx * rx;
        ry2 = ry * ry;
    }

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

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

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

    // Step 4: Compute theta1 and dtheta
    let theta1 = angle_between(1.0, 0.0, (x1p - cxp) / rx, (y1p - cyp) / ry);
    let mut dtheta = angle_between(
        (x1p - cxp) / rx,
        (y1p - cyp) / ry,
        (-x1p - cxp) / rx,
        (-y1p - cyp) / ry,
    );

    if !sweep && dtheta > 0.0 {
        dtheta -= core::f32::consts::TAU;
    } else if sweep && dtheta < 0.0 {
        dtheta += core::f32::consts::TAU;
    }

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

    let mut prev = start;
    for i in 0..n_segs {
        let t1 = theta1 + seg_angle * i as f32;
        let t2 = theta1 + seg_angle * (i + 1) as f32;

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

        let seg_end = if i + 1 == n_segs { end } else { ep };
        out.push(SvgPathElement::CubicCurve(SvgCubicCurve {
            start: prev,
            ctrl_1: c1,
            ctrl_2: c2,
            end: seg_end,
        }));
        prev = seg_end;
    }
}

/// Compute the angle between two vectors.
#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
fn angle_between(ux: f32, uy: f32, vx: f32, vy: f32) -> f32 {
    let dot = ux * vx + uy * vy;
    let len = ((ux * ux + uy * uy) * (vx * vx + vy * vy)).sqrt();
    if len < ZERO_LENGTH_EPSILON {
        return 0.0;
    }
    let cos_val = (dot / len).clamp(-1.0, 1.0);
    let angle = cos_val.acos();
    if ux * vy - uy * vx < 0.0 {
        -angle
    } else {
        angle
    }
}

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

    let cos1 = theta1.cos();
    let sin1 = theta1.sin();
    let cos2 = theta2.cos();
    let sin2 = theta2.sin();

    // Control point 1 (relative to unit circle)
    let dx1 = rx * (cos1 - alpha * sin1);
    let dy1 = ry * (sin1 + alpha * cos1);
    // Control point 2
    let dx2 = rx * (cos2 + alpha * sin2);
    let dy2 = ry * (sin2 - alpha * cos2);
    // End point
    let dx3 = rx * cos2;
    let dy3 = ry * sin2;

    let c1 = SvgPoint {
        x: cos_phi * dx1 - sin_phi * dy1 + cx,
        y: sin_phi * dx1 + cos_phi * dy1 + cy,
    };
    let c2 = SvgPoint {
        x: cos_phi * dx2 - sin_phi * dy2 + cx,
        y: sin_phi * dx2 + cos_phi * dy2 + cy,
    };
    let ep = SvgPoint {
        x: cos_phi * dx3 - sin_phi * dy3 + cx,
        y: sin_phi * dx3 + cos_phi * dy3 + cy,
    };

    (c1, c2, ep)
}

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

    let elements = vec![
        // Top to right
        SvgPathElement::CubicCurve(SvgCubicCurve {
            start: SvgPoint { x: cx, y: cy - r },
            ctrl_1: SvgPoint {
                x: cx + k,
                y: cy - r,
            },
            ctrl_2: SvgPoint {
                x: cx + r,
                y: cy - k,
            },
            end: SvgPoint { x: cx + r, y: cy },
        }),
        // Right to bottom
        SvgPathElement::CubicCurve(SvgCubicCurve {
            start: SvgPoint { x: cx + r, y: cy },
            ctrl_1: SvgPoint {
                x: cx + r,
                y: cy + k,
            },
            ctrl_2: SvgPoint {
                x: cx + k,
                y: cy + r,
            },
            end: SvgPoint { x: cx, y: cy + r },
        }),
        // Bottom to left
        SvgPathElement::CubicCurve(SvgCubicCurve {
            start: SvgPoint { x: cx, y: cy + r },
            ctrl_1: SvgPoint {
                x: cx - k,
                y: cy + r,
            },
            ctrl_2: SvgPoint {
                x: cx - r,
                y: cy + k,
            },
            end: SvgPoint { x: cx - r, y: cy },
        }),
        // Left to top
        SvgPathElement::CubicCurve(SvgCubicCurve {
            start: SvgPoint { x: cx - r, y: cy },
            ctrl_1: SvgPoint {
                x: cx - r,
                y: cy - k,
            },
            ctrl_2: SvgPoint {
                x: cx - k,
                y: cy - r,
            },
            end: SvgPoint { x: cx, y: cy - r },
        }),
    ];

    SvgPath {
        items: SvgPathElementVec::from_vec(elements),
    }
}

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

    if rx < CLOSEPATH_EPSILON && ry < CLOSEPATH_EPSILON {
        // Simple rectangle: 4 lines
        let tl = SvgPoint { x, y };
        let tr = SvgPoint { x: x + w, y };
        let br = SvgPoint { x: x + w, y: y + h };
        let bl = SvgPoint { x, y: y + h };

        let elements = vec![
            SvgPathElement::Line(SvgLine { start: tl, end: tr }),
            SvgPathElement::Line(SvgLine { start: tr, end: br }),
            SvgPathElement::Line(SvgLine { start: br, end: bl }),
            SvgPathElement::Line(SvgLine { start: bl, end: tl }),
        ];

        return SvgPath {
            items: SvgPathElementVec::from_vec(elements),
        };
    }

    // Rounded rectangle
    let kx = rx * KAPPA;
    let ky = ry * KAPPA;

    let mut elements = Vec::with_capacity(8);

    // Top edge (left to right)
    elements.push(SvgPathElement::Line(SvgLine {
        start: SvgPoint { x: x + rx, y },
        end: SvgPoint { x: x + w - rx, y },
    }));
    // Top-right corner
    elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
        start: SvgPoint { x: x + w - rx, y },
        ctrl_1: SvgPoint {
            x: x + w - rx + kx,
            y,
        },
        ctrl_2: SvgPoint {
            x: x + w,
            y: y + ry - ky,
        },
        end: SvgPoint {
            x: x + w,
            y: y + ry,
        },
    }));
    // Right edge
    elements.push(SvgPathElement::Line(SvgLine {
        start: SvgPoint {
            x: x + w,
            y: y + ry,
        },
        end: SvgPoint {
            x: x + w,
            y: y + h - ry,
        },
    }));
    // Bottom-right corner
    elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
        start: SvgPoint {
            x: x + w,
            y: y + h - ry,
        },
        ctrl_1: SvgPoint {
            x: x + w,
            y: y + h - ry + ky,
        },
        ctrl_2: SvgPoint {
            x: x + w - rx + kx,
            y: y + h,
        },
        end: SvgPoint {
            x: x + w - rx,
            y: y + h,
        },
    }));
    // Bottom edge (right to left)
    elements.push(SvgPathElement::Line(SvgLine {
        start: SvgPoint {
            x: x + w - rx,
            y: y + h,
        },
        end: SvgPoint {
            x: x + rx,
            y: y + h,
        },
    }));
    // Bottom-left corner
    elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
        start: SvgPoint {
            x: x + rx,
            y: y + h,
        },
        ctrl_1: SvgPoint {
            x: x + rx - kx,
            y: y + h,
        },
        ctrl_2: SvgPoint {
            x,
            y: y + h - ry + ky,
        },
        end: SvgPoint { x, y: y + h - ry },
    }));
    // Left edge
    elements.push(SvgPathElement::Line(SvgLine {
        start: SvgPoint { x, y: y + h - ry },
        end: SvgPoint { x, y: y + ry },
    }));
    // Top-left corner
    elements.push(SvgPathElement::CubicCurve(SvgCubicCurve {
        start: SvgPoint { x, y: y + ry },
        ctrl_1: SvgPoint { x, y: y + ry - ky },
        ctrl_2: SvgPoint { x: x + rx - kx, y },
        end: SvgPoint { x: x + rx, y },
    }));

    SvgPath {
        items: SvgPathElementVec::from_vec(elements),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

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

    /// Any digit or symbol directly after a closepath is rejected, not looped on.
    #[test]
    fn stray_byte_after_closepath_rejected() {
        for s in ["M0 0Z9", "m0 0z-", "M0 0Z."] {
            assert!(
                matches!(
                    parse_svg_path_d(s),
                    Err(SvgPathParseError::UnexpectedChar { .. })
                ),
                "expected UnexpectedChar for {s:?}"
            );
        }
    }

    /// 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]
    fn error_char_is_unicode_not_byte() {
        // 'ü' is two UTF-8 bytes; `b as char` would have yielded a mojibake char.
        let err = parse_svg_path_d("ü10 10").unwrap_err();
        match err {
            SvgPathParseError::UnexpectedChar { ch, pos } => {
                assert_eq!(ch, 'ü');
                assert_eq!(pos, 0);
            }
            other => panic!("expected UnexpectedChar, got {other:?}"),
        }
    }

    /// A well-formed closepath followed by a real command still parses.
    #[test]
    fn valid_closepath_then_command_ok() {
        let parsed = parse_svg_path_d("M0 0 L10 0 Z M20 20 L30 20 Z");
        assert!(parsed.is_ok(), "valid multi-subpath path should parse");
    }
}

#[cfg(test)]
#[path = "path_parser_test.rs"]
mod path_parser_test;