svg: use shared bounded prefix path parsing (#3800)

This commit is contained in:
Dylan M. Taylor
2026-11-16 21:58:04 -05:00
committed by GitHub
parent 6d908d1301
commit defa16a26f
3 changed files with 20 additions and 476 deletions
Generated
+15 -123
View File
@@ -147,21 +147,6 @@ dependencies = [
"equator",
]
[[package]]
name = "alloc-no-stdlib"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
[[package]]
name = "alloc-stdlib"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
dependencies = [
"alloc-no-stdlib",
]
[[package]]
name = "allocator-api2"
version = "0.2.21"
@@ -796,16 +781,6 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "brotli-decompressor"
version = "6.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
]
[[package]]
name = "built"
version = "0.8.1"
@@ -1376,39 +1351,6 @@ dependencies = [
"writeable",
]
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
dependencies = [
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)",
"craft-metadata",
"crc32fast",
"exr",
"flate2",
"half",
"hayro-jpeg2000",
"image",
"image-webp",
"jpeg-encoder",
"png",
"rayon",
"serde_json",
"thiserror 2.0.21",
"tiff",
"zune-core",
"zune-jpeg",
"zune-jpegxl",
]
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-jpeg"
version = "0.1.0"
@@ -1461,18 +1403,6 @@ dependencies = [
"serde_json",
]
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
dependencies = [
"brotli-decompressor",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)",
"quick-xml 0.41.0",
"serde",
]
[[package]]
name = "craft-mime"
version = "0.1.0"
@@ -1543,7 +1473,7 @@ name = "craft-raw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac#bea91b1861eea3889bec9d26338076f2ff31c4ac"
dependencies = [
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac)",
"craft-tiff",
"miniz_oxide 0.9.1",
"rayon",
"serde",
@@ -1555,10 +1485,9 @@ dependencies = [
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
source = "git+https://github.com/storytold/craft-libs?rev=e52cd9a889adbeeda447c75a546133960cf3382d#e52cd9a889adbeeda447c75a546133960cf3382d"
dependencies = [
"craft-image-codecs",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e52cd9a889adbeeda447c75a546133960cf3382d)",
"flate2",
"kurbo",
"quick-xml 0.41.0",
@@ -1576,15 +1505,6 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-tiff"
version = "0.1.0"
@@ -1747,16 +1667,6 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
@@ -1777,6 +1687,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e52cd9a889adbeeda447c75a546133960cf3382d#e52cd9a889adbeeda447c75a546133960cf3382d"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-y4m"
version = "0.1.0"
@@ -3039,7 +2959,7 @@ version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
dependencies = [
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=937ac93c5cf3cd4b6a81e195b078fe161eb081b9)",
"craft-jpeg",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-y4m",
@@ -3071,7 +2991,7 @@ version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
dependencies = [
"craft-raw",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac)",
"craft-tiff",
"image",
"rayon",
"thiserror 2.0.21",
@@ -3760,9 +3680,6 @@ name = "hayro-jpeg2000"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
dependencies = [
"fearless_simd",
]
[[package]]
name = "hayro-syntax"
@@ -4024,7 +3941,6 @@ dependencies = [
"moxcms",
"num-traits",
"png",
"qoi",
"tiff",
"zune-core",
"zune-jpeg",
@@ -4175,12 +4091,6 @@ dependencies = [
"libc",
]
[[package]]
name = "jpeg-encoder"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f"
[[package]]
name = "js-sys"
version = "0.3.106"
@@ -5573,15 +5483,6 @@ version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "qoi"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
dependencies = [
"bytemuck",
]
[[package]]
name = "quick-error"
version = "1.2.3"
@@ -9001,15 +8902,6 @@ dependencies = [
"zune-core",
]
[[package]]
name = "zune-jpegxl"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4"
dependencies = [
"zune-core",
]
[[package]]
name = "zvariant"
version = "5.15.0"
+1 -1
View File
@@ -22,7 +22,7 @@ craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs",
craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ce2ec507c2e6a6a078a5f450f641487f8931816d" }
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e52cd9a889adbeeda447c75a546133960cf3382d" }
craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", default-features = false, features = ["stl", "obj", "gltf", "fbx"] }
+4 -352
View File
@@ -1,360 +1,12 @@
//! SVG path data (SVG 1.1 §8.3 / SVG 2 §9.3): every command, implicit repeats, relative
//! coordinates, smooth curves and elliptical arcs (converted to cubics through kurbo's `SvgArc`).
//! Parsing stops at the first error, keeping what was read (as the specification asks).
//! Prefix-preserving SVG path and numeric-list parsing is shared with craft-svg.
//! App document budgets and geometry policy remain with the importer.
use kurbo::{BezPath, PathEl, Point, SvgArc, Vec2};
/// Maximum path elements retained from one SVG path or point list.
pub(crate) const MAX_PATH_ELEMENTS: usize = 100_000;
/// Tokenizer over numbers and command letters.
struct Lex<'a> {
b: &'a [u8],
i: usize,
}
impl Lex<'_> {
fn skip_sep(&mut self) {
while self.i < self.b.len() && (self.b[self.i].is_ascii_whitespace() || self.b[self.i] == b',') {
self.i += 1;
}
}
fn command(&mut self) -> Option<u8> {
self.skip_sep();
let c = *self.b.get(self.i)?;
if c.is_ascii_alphabetic() && c != b'e' && c != b'E' {
self.i += 1;
Some(c)
} else {
None
}
}
fn at_number(&mut self) -> bool {
self.skip_sep();
self.b.get(self.i).is_some_and(|c| c.is_ascii_digit() || matches!(c, b'-' | b'+' | b'.'))
}
fn number(&mut self) -> Option<f64> {
self.skip_sep();
let start = self.i;
let b = self.b;
let mut i = self.i;
if i < b.len() && matches!(b[i], b'-' | b'+') {
i += 1;
}
let mut digits = false;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
digits = true;
}
if i < b.len() && b[i] == b'.' {
i += 1;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
digits = true;
}
}
if !digits {
return None;
}
if i < b.len() && matches!(b[i], b'e' | b'E') {
let mut j = i + 1;
if j < b.len() && matches!(b[j], b'-' | b'+') {
j += 1;
}
if j < b.len() && b[j].is_ascii_digit() {
while j < b.len() && b[j].is_ascii_digit() {
j += 1;
}
i = j;
}
}
self.i = i;
let number = std::str::from_utf8(&b[start..i]).ok()?.parse::<f64>().ok()?;
number.is_finite().then_some(number)
}
/// Arc flags may be written without separators ("a1 1 0 00 1 1").
fn flag(&mut self) -> Option<bool> {
self.skip_sep();
let c = *self.b.get(self.i)?;
self.i += 1;
match c {
b'0' => Some(false),
b'1' => Some(true),
_ => None,
}
}
}
/// Parse no more than `max_values`; the flag reports whether another valid value was present.
pub(crate) fn numbers_bounded(s: &str, max_values: usize) -> (Vec<f64>, bool) {
let mut l = Lex { b: s.as_bytes(), i: 0 };
let mut v = vec![];
while l.at_number() {
if v.len() >= max_values {
return (v, true);
}
match l.number() {
Some(x) => v.push(x),
None => break,
}
}
(v, false)
}
/// Parse path data into a kurbo path, retaining at most [`MAX_PATH_ELEMENTS`] elements.
/// Malformed or overlong input returns the prefix parsed before the problem.
pub fn parse_path_data(d: &str) -> BezPath {
parse_path_data_bounded(d, MAX_PATH_ELEMENTS).0
}
/// Pen position and reflection state while parsing path commands.
struct PathState {
/// Current point.
current: Point,
/// Start of the current subpath.
start: Point,
/// Last cubic control point, for smooth curves.
last_cubic: Option<Point>,
/// Last quadratic control point, for smooth curves.
last_quad: Option<Point>,
/// Whether a subpath is open.
open: bool,
}
/// Cap on path elements and whether it has been hit.
struct PathLimit {
/// Maximum number of path elements.
max_elements: usize,
/// Set when the cap or a non-finite coordinate stopped output.
exceeded: bool,
}
/// Parse at most `max_elements`, reporting when more path geometry was present.
pub(crate) fn parse_path_data_bounded(d: &str, max_elements: usize) -> (BezPath, bool) {
let mut l = Lex { b: d.as_bytes(), i: 0 };
let mut p = BezPath::new();
let mut state = PathState { current: Point::ZERO, start: Point::ZERO, last_cubic: None, last_quad: None, open: false };
let mut limit = PathLimit { max_elements, exceeded: false };
let mut cmd: Option<u8> = None;
loop {
if p.elements().len() >= limit.max_elements {
l.skip_sep();
limit.exceeded = l.i < l.b.len();
break;
}
let c = match l.command() {
Some(c) => c,
None => match cmd {
// Implicit repeat (a moveto repeats as lineto). Z takes no numbers, so a number
// after it is an error: repeating Z would loop forever without consuming input.
Some(c) if l.at_number() && !c.eq_ignore_ascii_case(&b'z') => match c {
b'M' => b'L',
b'm' => b'l',
other => other,
},
_ => break,
},
};
let rel = c.is_ascii_lowercase();
let base = if rel { state.current.to_vec2() } else { Vec2::ZERO };
let pt = |l: &mut Lex| -> Option<Point> { Some(Point::new(l.number()?, l.number()?) + base) };
let ok = (|| -> Option<()> {
match c.to_ascii_uppercase() {
b'M' => {
state.current = pt(&mut l)?;
if !push_element(&mut p, PathEl::MoveTo(state.current), &mut limit) {
return None;
}
state.start = state.current;
state.open = true;
state.last_cubic = None;
state.last_quad = None;
}
b'Z' => {
if state.open && !push_element(&mut p, PathEl::ClosePath, &mut limit) {
return None;
}
state.current = state.start;
state.last_cubic = None;
state.last_quad = None;
}
_ if !state.open => {
// A segment without a preceding moveto starts at the current point.
if !push_element(&mut p, PathEl::MoveTo(state.current), &mut limit) {
return None;
}
state.open = true;
return segment(&mut l, c, base, &mut p, &mut state, &mut limit);
}
_ => return segment(&mut l, c, base, &mut p, &mut state, &mut limit),
}
Some(())
})();
if ok.is_none() {
break;
}
if limit.exceeded {
break;
}
cmd = Some(c);
if c.eq_ignore_ascii_case(&b'z') {
// After Z a new segment starts from the subpath start (an unused move is dropped
// below).
if !push_element(&mut p, PathEl::MoveTo(state.start), &mut limit) {
break;
}
state.open = true;
}
}
(strip_trailing_moves(p), limit.exceeded)
}
/// Push an element if finite and under the cap; otherwise mark the limit exceeded and return false.
fn push_element(p: &mut BezPath, element: PathEl, limit: &mut PathLimit) -> bool {
let finite = match element {
PathEl::MoveTo(point) | PathEl::LineTo(point) => point.x.is_finite() && point.y.is_finite(),
PathEl::QuadTo(control, point) => [control.x, control.y, point.x, point.y].iter().all(|value| value.is_finite()),
PathEl::CurveTo(first, second, point) => [first.x, first.y, second.x, second.y, point.x, point.y].iter().all(|value| value.is_finite()),
PathEl::ClosePath => true,
};
if p.elements().len() >= limit.max_elements || !finite {
limit.exceeded = true;
return false;
}
p.push(element);
true
}
/// Parse one path command's arguments into `p`, returning `None` on malformed or over-limit input.
fn segment(l: &mut Lex, c: u8, base: Vec2, p: &mut BezPath, state: &mut PathState, limit: &mut PathLimit) -> Option<()> {
let num = |l: &mut Lex| l.number();
let pt = |l: &mut Lex| -> Option<Point> { Some(Point::new(l.number()?, l.number()?) + base) };
match c.to_ascii_uppercase() {
b'L' => {
let current = pt(l)?;
if !push_element(p, PathEl::LineTo(current), limit) {
return None;
}
state.current = current;
state.last_cubic = None;
state.last_quad = None;
}
b'H' => {
let x = num(l)? + base.x;
let current = Point::new(x, state.current.y);
if !push_element(p, PathEl::LineTo(current), limit) {
return None;
}
state.current = current;
state.last_cubic = None;
state.last_quad = None;
}
b'V' => {
let y = num(l)? + base.y;
let current = Point::new(state.current.x, y);
if !push_element(p, PathEl::LineTo(current), limit) {
return None;
}
state.current = current;
state.last_cubic = None;
state.last_quad = None;
}
b'C' => {
let (c1, c2, e) = (pt(l)?, pt(l)?, pt(l)?);
if !push_element(p, PathEl::CurveTo(c1, c2, e), limit) {
return None;
}
state.last_cubic = Some(c2);
state.last_quad = None;
state.current = e;
}
b'S' => {
let c1 = state.last_cubic.map_or(state.current, |c| state.current + (state.current - c));
let (c2, e) = (pt(l)?, pt(l)?);
if !push_element(p, PathEl::CurveTo(c1, c2, e), limit) {
return None;
}
state.last_cubic = Some(c2);
state.last_quad = None;
state.current = e;
}
b'Q' => {
let (q, e) = (pt(l)?, pt(l)?);
if !push_element(p, PathEl::QuadTo(q, e), limit) {
return None;
}
state.last_quad = Some(q);
state.last_cubic = None;
state.current = e;
}
b'T' => {
let q = state.last_quad.map_or(state.current, |c| state.current + (state.current - c));
let e = pt(l)?;
if !push_element(p, PathEl::QuadTo(q, e), limit) {
return None;
}
state.last_quad = Some(q);
state.last_cubic = None;
state.current = e;
}
b'A' => {
let rx = num(l)?.abs();
let ry = num(l)?.abs();
let rot = num(l)?;
let large = l.flag()?;
let sweep = l.flag()?;
let e = pt(l)?;
let arc = SvgArc { from: state.current, to: e, radii: Vec2::new(rx, ry), x_rotation: rot.to_radians(), large_arc: large, sweep };
let mut last_end = None;
if let Some(a) = kurbo::Arc::from_svg_arc(&arc) {
// Scale tolerance with the radius so the segment count stays bounded.
let tol = 0.1_f64.max(a.radii.x.max(a.radii.y) * 1e-4);
a.to_cubic_beziers(tol, |c1, c2, end| {
if limit.exceeded {
return;
}
if push_element(p, PathEl::CurveTo(c1, c2, end), limit) {
last_end = Some(end);
}
});
}
if limit.exceeded {
return None;
}
// Degenerate arcs (e.g. huge radii) may emit nothing or stop short of the end point.
if last_end.is_none_or(|q| (q - e).hypot() > 1e-3 * (1.0 + e.to_vec2().hypot())) && !push_element(p, PathEl::LineTo(e), limit) {
return None;
}
state.current = e;
state.last_cubic = None;
state.last_quad = None;
}
_ => return None,
}
Some(())
}
/// Drop move-tos that start no segment (from closepath bookkeeping).
fn strip_trailing_moves(p: BezPath) -> BezPath {
use kurbo::PathEl;
let els = p.elements();
let mut out = BezPath::new();
for (i, e) in els.iter().enumerate() {
if let PathEl::MoveTo(_) = e {
let next_is_seg = els.get(i + 1).is_some_and(|n| !matches!(n, PathEl::MoveTo(_)));
if !next_is_seg {
continue;
}
}
out.push(*e);
}
out
}
pub use craft_svg::prefix_path::{MAX_PATH_ELEMENTS, numbers_bounded, parse_path_data, parse_path_data_bounded};
#[cfg(test)]
mod tests {
use super::*;
use kurbo::PathEl;
use kurbo::{PathEl, Point};
#[test]
/// Huge arc radii stay bounded.