diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 02935bac60..9d260300c7 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -110,3 +110,7 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper ## Non-seeking WAV primitives `crates/audio/src/wav_stream.rs` is extracted from AniCraft `crates/audio/src/wav.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0). Tanish Manku is retained as the primary import author, from original commit `30c121d269a49d9abe54a3834ed4aa0201542535`. Odd-data padding accounting, shared API documentation and regression tests are subsequent Dylan M. Taylor changes. + +## GIMP palette reader + +`crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes. diff --git a/Cargo.lock b/Cargo.lock index 658f5139bb..01d0421057 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2593,6 +2593,10 @@ dependencies = [ "zip 9.1.3", ] +[[package]] +name = "craft-palette" +version = "0.1.0" + [[package]] name = "craft-pcraft-bundle" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 72ae0083a2..2c0f4dfeaf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-palette = { path = "crates/palette" } craft-shx = { path = "crates/shx" } craft-http-url = { path = "crates/http-url" } craft-usd = { path = "crates/usd" } diff --git a/crates/palette/Cargo.toml b/crates/palette/Cargo.toml new file mode 100644 index 0000000000..d39a80b677 --- /dev/null +++ b/crates/palette/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "craft-palette" +description = "Bounded, application-independent GIMP palette reading" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true diff --git a/crates/palette/src/lib.rs b/crates/palette/src/lib.rs new file mode 100644 index 0000000000..c49b0666d6 --- /dev/null +++ b/crates/palette/src/lib.rs @@ -0,0 +1,97 @@ +//! GIMP palette (.gpl) reading with neutral RGB8 colours and names. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +/// Largest accepted palette, bounding all parsing allocations. +pub const MAX_BYTES: usize = 1 << 20; +/// Maximum colours returned; later rows are ignored. +pub const MAX_COLORS: usize = 1024; +/// A named RGB colour. Display-name sanitization belongs to the caller. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Color { + /// Whitespace-normalized colour label; "Untitled" remains literal. + pub name: String, + /// Red, green and blue channels. + pub rgb: [u8; 3], +} +/// A palette's title and colours, in file order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Palette { + /// Last Name header before the colour limit; leading value whitespace is retained. + pub name: String, + /// Valid colour rows in file order. + pub colors: Vec, +} +/// Reads GPL text, accepting BOM/CRLF, comments and metadata headers. +/// Malformed colour rows are skipped. Missing magic, empty palettes and oversized +/// input are errors. Columns and Channels headers are ignored for legacy compatibility. +pub fn parse_gpl(text: &str) -> Result { + if text.len() > MAX_BYTES { + return Err("the palette file is too large".into()); + } + let mut lines = text.lines(); + let first = lines.next().unwrap_or("").trim_start_matches('\u{feff}').trim(); + if first != "GIMP Palette" { + return Err("this isn't a GIMP palette (its first line must be \"GIMP Palette\")".into()); + } + let mut name = String::new(); + let mut out = Vec::new(); + for line in lines { + let l = line.trim(); + if l.is_empty() || l.starts_with('#') { + continue; + } + if let Some(n) = l.strip_prefix("Name:") { + name = n.to_string(); + continue; + } + if l.starts_with("Columns:") || l.starts_with("Channels:") { + continue; + } + let mut parts = l.split_whitespace(); + let channel = |s: Option<&str>| s.and_then(|v| v.parse::().ok()).filter(|v| *v <= 255).map(|v| v as u8); + let (Some(r), Some(g), Some(b)) = (channel(parts.next()), channel(parts.next()), channel(parts.next())) else { continue }; + let rest: Vec<&str> = parts.collect(); + let label = rest.join(" "); + out.push(Color { name: label, rgb: [r, g, b] }); + if out.len() >= MAX_COLORS { + break; + } + } + if out.is_empty() { + return Err("the palette has no colours in it".into()); + } + Ok(Palette { name, colors: out }) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::indexing_slicing)] +mod tests { + use super::*; + + #[test] + fn metadata_rgb_names_and_legacy_rows() { + let p = parse_gpl("\u{feff}GIMP Palette\r\nName: First\r\nName: Last\nColumns: 4\nChannels: RGB\n# comment\n255 0 128 Pink ink\n256 0 0 invalid\n-1 2 3 invalid\n1 2 3 Untitled\n4 5 6\n").unwrap(); + assert_eq!(p.name, " Last"); + assert_eq!( + p.colors, + vec![ + Color { name: "Pink ink".into(), rgb: [255, 0, 128] }, + Color { name: "Untitled".into(), rgb: [1, 2, 3] }, + Color { name: String::new(), rgb: [4, 5, 6] } + ] + ); + } + + #[test] + fn limits_and_empty_input() { + for text in ["", "not a palette", "GIMP Palette", "GIMP Palette\n256 0 0"] { + assert!(parse_gpl(text).is_err()); + } + assert!(parse_gpl(&"x".repeat(MAX_BYTES + 1)).is_err()); + let many = format!("GIMP Palette\n{}Name: ignored", "1 2 3 é\n".repeat(MAX_COLORS + 1)); + let p = parse_gpl(&many).unwrap(); + assert_eq!(p.colors.len(), MAX_COLORS); + assert!(p.name.is_empty()); + assert_eq!(p.colors[0].name, "é"); + } +} diff --git a/crates/penpot/src/lib.rs b/crates/penpot/src/lib.rs index aafc555c33..eda3bdf857 100644 --- a/crates/penpot/src/lib.rs +++ b/crates/penpot/src/lib.rs @@ -382,16 +382,43 @@ pub fn manifest(generated_by: &str, files: &[(&str, &str, Value)]) -> Value { serde_json::json!({"type": MANIFEST_TYPE, "version": 1, "generatedBy": generated_by, "refer": "penpot", "files": files, "relations": []}) } +/// Incremental in-memory Penpot container writer. Members are compressed as they are added; +/// the writer retains their names and archive output, not a second collection of payloads. +/// Paths must be safe and distinct. Entries keep insertion order and use deflate level 3. +/// If [`Writer::add`] fails, discard the writer: additions are not transactional, and a ZIP +/// failure may leave a reserved member name or partially written output. Do not finish or reuse +/// a writer after an error. +#[derive(Default)] +pub struct Writer { + zip: craft_zip::Writer, + seen: BTreeSet, +} + +impl Writer { + pub fn new() -> Self { + Self::default() + } + + /// Write one member immediately; the caller may release its serialized payload afterwards. + /// On any error, discard this writer rather than retrying or calling [`Writer::finish`]. + pub fn add(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error> { + if path.is_empty() || !safe_name(path) || !self.seen.insert(path.to_owned()) { + return Err(Error::Io(format!("unsafe or repeated member path: {}", path.chars().take(200).collect::()))); + } + self.zip.add(path, bytes, craft_zip::Compression::Level(3)).map_err(|e| Error::Io(e.to_string())) + } + + pub fn finish(self) -> Result, Error> { + self.zip.finish().map_err(|e| Error::Io(e.to_string())) + } +} + /// A Penpot archive of `members` (path, bytes), deflated, in the order given. Paths must be safe /// and distinct, as [`Archive::open`] requires of what it reads. pub fn write_archive<'a>(members: impl IntoIterator) -> Result, Error> { - let mut z = craft_zip::Writer::new(); - let mut seen = BTreeSet::new(); + let mut writer = Writer::new(); for (path, bytes) in members { - if path.is_empty() || !safe_name(path) || !seen.insert(path) { - return Err(Error::Io(format!("unsafe or repeated member path: {}", path.chars().take(200).collect::()))); - } - z.add(path, bytes, craft_zip::Compression::Level(3)).map_err(|e| Error::Io(e.to_string()))?; + writer.add(path, bytes)?; } - z.finish().map_err(|e| Error::Io(e.to_string())) + writer.finish() } diff --git a/crates/penpot/src/tests.rs b/crates/penpot/src/tests.rs index c5f14ef720..2644157ff9 100644 --- a/crates/penpot/src/tests.rs +++ b/crates/penpot/src/tests.rs @@ -438,3 +438,23 @@ fn an_archive_declaring_too_many_members_is_refused_before_it_is_indexed() { let bomb = craft_zip::zip64_entry_count_sample(MAX_ENTRIES as u64 + 1); assert_eq!(Archive::open(&bomb).err(), Some(Error::Corrupt("too many ZIP members".into()))); } + +#[test] +fn incremental_writer_keeps_members_and_rejects_ambiguous_paths() { + let all = members(); + let mut writer = Writer::new(); + for (name, bytes) in &all { + writer.add(name, bytes).unwrap(); + } + let output = writer.finish().unwrap(); + assert_eq!(output, write_archive(all.iter().map(|(n, b)| (n.as_str(), b.as_slice()))).unwrap()); + let mut archive = Archive::open(&output).unwrap(); + assert_eq!(archive.names().first().map(String::as_str), Some("manifest.json")); + assert_eq!(archive.page_shapes(FILE, PAGE).unwrap().len(), 2); + for bad in ["../x", "/abs", "a/./b", "a\\b", "", "a\u{1}b"] { + assert!(Writer::new().add(bad, b"x").is_err()); + } + let mut duplicate = Writer::new(); + duplicate.add("a", b"first").unwrap(); + assert!(duplicate.add("a", b"second").is_err()); +} diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 286bd36d55..0c3c362a41 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -31,5 +31,7 @@ pub mod svgz; pub mod tree; pub mod write; +/// Prefix-preserving kurbo path compatibility for legacy SVG importers. +pub mod prefix_path; /// Compatibility CSS subset for simple SVG importers. pub mod simple_css; diff --git a/crates/svg/src/prefix_path.rs b/crates/svg/src/prefix_path.rs new file mode 100644 index 0000000000..0553d606d1 --- /dev/null +++ b/crates/svg/src/prefix_path.rs @@ -0,0 +1,480 @@ +//! 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). +//! +//! Compatibility API for importers requiring kurbo quadratics and cubic arc expansion, +//! distinct from the strict neutral [`crate::path_data::parse_path`] API. Retains EffectCraft's +//! malformed-prefix, close-path, finite-coordinate, radius-scaled tolerance and endpoint rules. +//! Source: EffectCraft `pathdata.rs` at `05fc7f28352361f8f183da900ac5f4dfc9b69799`. +//! Brandon Thomas authored the parser and post-Z termination fix; NetterSilver the arc +//! tolerance/endpoint fixes; FredApps the finite-coordinate and element-budget safeguards. + +use kurbo::{BezPath, PathEl, Point, SvgArc, Vec2}; + +/// Maximum path elements retained from one SVG path or point list. +pub 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 { + 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 { + 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::().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 { + self.skip_sep(); + let c = *self.b.get(self.i)?; + self.i += 1; + match c { + b'0' => Some(false), + b'1' => Some(true), + _ => None, + } + } +} + +/// Maximum values retained from a points list (two coordinates per path element). +pub const MAX_NUMBER_VALUES: usize = MAX_PATH_ELEMENTS * 2; + +/// Parse a finite numeric prefix, retaining at most `min(max_values, MAX_NUMBER_VALUES)`. +/// The flag reports a possible next number after the cap, not a malformed suffix. +/// The caller must decide whether to refuse the document when the flag is set. +pub fn numbers_bounded(s: &str, max_values: usize) -> (Vec, bool) { + let max_values = max_values.min(MAX_NUMBER_VALUES); + 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, + /// Last quadratic control point, for smooth curves. + last_quad: Option, + /// 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 `min(max_elements, MAX_PATH_ELEMENTS)` kurbo elements. +/// The flag reports a reached cap with trailing input or a non-finite output coordinate. +/// Malformed syntax alone returns the valid prefix without setting the flag. Importers +/// should refuse the document on a true flag; [`parse_path_data`] intentionally keeps only +/// the bounded prefix. Move/close commands and expanded arc cubics count toward the cap. +pub fn parse_path_data_bounded(d: &str, max_elements: usize) -> (BezPath, bool) { + let max_elements = max_elements.min(MAX_PATH_ELEMENTS); + 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 = 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 { 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 { 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 +} + +#[cfg(test)] +mod tests { + use super::*; + use kurbo::PathEl; + + #[test] + /// Huge arc radii stay bounded. + fn huge_arc_radius_stays_bounded() { + let p = parse_path_data("M0 0A1e36 1e36 0 1 1 1e30 0"); + assert!(p.elements().len() < 1000, "got {} elements", p.elements().len()); + } + + #[test] + fn commands() { + let p = parse_path_data("M10,10 L20,10 h10 v10 H10 z m5 5 l1-1.5.5.5e1 C 0 0 1 1 2 2 s3 3 4 4 Q1 1 2 2 t3 3 A5 5 0 0 1 20 20 a5 5 0 1010 0"); + let els = p.elements(); + assert_eq!(els[0], PathEl::MoveTo(Point::new(10.0, 10.0))); + assert_eq!(els[2], PathEl::LineTo(Point::new(30.0, 10.0))); + assert_eq!(els[3], PathEl::LineTo(Point::new(30.0, 20.0))); + assert!(els.iter().any(|e| matches!(e, PathEl::ClosePath))); + // Relative move after Z is relative to the subpath start (10,10). + assert!(els.contains(&PathEl::MoveTo(Point::new(15.0, 15.0)))); + // "l1-1.5.5.5e1": two implicit linetos (1,-1.5) then (.5,5). + assert!(els.contains(&PathEl::LineTo(Point::new(16.0, 13.5)))); + assert!(els.contains(&PathEl::LineTo(Point::new(16.5, 18.5)))); + assert!(els.iter().filter(|e| matches!(e, PathEl::CurveTo(..))).count() >= 4); + } + + #[test] + fn errors_keep_prefix() { + let p = parse_path_data("M0 0 L10 0 L10 x10 L0 10"); + assert_eq!(p.elements().len(), 2); + assert!(parse_path_data("garbage").elements().is_empty()); + assert!(parse_path_data("").elements().is_empty()); + } + + #[test] + fn number_after_close_stops_instead_of_looping() { + // "Z9": Z was repeated implicitly without consuming the number, appending close-paths + // until memory ran out. + let p = parse_path_data("M0 0 L10 0 L10 10 Z9 C1 2 3 4 5 6"); + assert_eq!(p.elements().len(), 4); + assert!(parse_path_data("M0 0 L10 0 z 9 9").elements().len() <= 4); + } + + #[test] + /// Huge-radius arcs still reach their end point. + fn huge_radius_arc_still_reaches_end_point() { + for d in ["M0 0 A1e20 1e20 0 0 1 10 0 L10 10", "M0 0 A1e20 1e20 0 1 1 10 0 L10 10", "M0 0 a1e20 1e20 0 0 1 10 0 L10 10"] { + let p = parse_path_data(d); + let reaches = p.elements().iter().any(|e| match e { + PathEl::LineTo(q) | PathEl::CurveTo(_, _, q) => (q.x - 10.0).abs() < 1e-6 && q.y.abs() < 1e-6, + _ => false, + }); + assert!(reaches, "{d}: {:?}", p.elements()); + } + } + + #[test] + fn number_lists() { + assert_eq!(numbers_bounded("0 0,100 50", 8).0, vec![0.0, 0.0, 100.0, 50.0]); + assert_eq!(numbers_bounded("-1-2.5.5", 8).0, vec![-1.0, -2.5, 0.5]); + assert_eq!(numbers_bounded("1e2,2E-1", 8).0, vec![100.0, 0.2]); + } + + #[test] + /// The element cap stops expansion and reports truncation. + fn path_element_limit_stops_expansion_and_reports_truncation() { + let data = format!("M0 0{}", "h1".repeat(MAX_PATH_ELEMENTS + 1)); + let (path, exceeded) = parse_path_data_bounded(&data, 32); + assert!(exceeded); + assert!(path.elements().len() <= 32); + } + + #[test] + /// The number list cap stops retaining values. + fn number_list_limit_stops_retaining_values() { + let (values, exceeded) = numbers_bounded("1 2 3 4", 3); + assert_eq!(values, [1.0, 2.0, 3.0]); + assert!(exceeded); + } +} + +#[cfg(test)] +mod shared_boundary_tests { + use super::*; + + #[test] + fn huge_caller_budgets_remain_bounded() { + let (path, limited) = parse_path_data_bounded(&format!("M0 0{}", "h1".repeat(MAX_PATH_ELEMENTS)), usize::MAX); + assert!(limited); + assert!(path.elements().len() <= MAX_PATH_ELEMENTS); + let (values, limited) = numbers_bounded(&"1 ".repeat(MAX_NUMBER_VALUES + 1), usize::MAX); + assert!(limited); + assert_eq!(values.len(), MAX_NUMBER_VALUES); + } + + #[test] + fn prefix_and_non_finite_flags_stay_distinct() { + let (path, limited) = parse_path_data_bounded("M0 0 L1 1 Lx", 20); + assert!(!limited); + assert_eq!(path.elements().len(), 2); + let (path, limited) = parse_path_data_bounded("M1e308 0 l1e308 0", 20); + assert!(limited); + assert!(path.elements().is_empty()); + assert!(parse_path_data_bounded("M0 0", 0).1); + assert!(!parse_path_data_bounded("", 0).1); + } +} diff --git a/crates/xlsx/tests/xlsb.rs b/crates/xlsx/tests/xlsb.rs index 3611cafbb4..ef1464dd4b 100644 --- a/crates/xlsx/tests/xlsb.rs +++ b/crates/xlsx/tests/xlsb.rs @@ -1010,7 +1010,7 @@ const NAMES_XML: &str = r#""#; let root = r#""#; - let bytes = zip(&[("[Content_Types].xml", types.as_bytes()), ("_rels/.rels", root.as_bytes()), ("xl/workbook.xml", xml.as_bytes())]); + let bytes = zip(&[("[Content_Types].xml", types.as_bytes()), ("_rels/.rels", root.as_bytes()), ("xl/workbook.xml", xml.as_bytes())]).unwrap(); Package::open(&bytes, &Limits::default()).unwrap().workbook().unwrap().defined_names } @@ -1146,7 +1146,8 @@ fn xml_sheet(xml: &str) -> (Vec, SheetPart) { ("xl/workbook.xml", book.as_bytes()), ("xl/_rels/workbook.xml.rels", rels.as_bytes()), ("xl/sheet.xml", xml.as_bytes()), - ]); + ]) + .unwrap(); let (rows, part, _) = sizes_of(&bytes).unwrap(); (rows, part) } @@ -1256,6 +1257,7 @@ fn styled_file(styles: &[u8], types: &str) -> Vec { ("data/two.bin", &worksheet(&[], &[])), ("look/styles.bin", styles), ]) + .unwrap() } /// The styles part of a package, and the warnings reading it gave. @@ -1440,7 +1442,8 @@ fn xml_styles(xml: &str) -> Styles { ("xl/workbook.xml", br#""#), ("xl/_rels/workbook.xml.rels", rels.as_bytes()), ("xl/styles.xml", xml.as_bytes()), - ]); + ]) + .unwrap(); styles_of(&bytes).0.unwrap() } @@ -1793,7 +1796,7 @@ fn book_with_tables(data: &[u8], tables: &[Vec]) -> Vec { ("text/strings.bin", &strings), ]; entries.extend(names.iter().map(String::as_str).zip(tables.iter().map(Vec::as_slice))); - zip(&entries) + zip(&entries).unwrap() } /// Sheet one's tables through `Package`, and its warnings. @@ -1834,7 +1837,8 @@ fn a_name_using_a_structured_reference_is_decoded_after_tables_are_indexed() { ("data/two.bin", two.as_slice()), ("text/strings.bin", strings.as_slice()), ("tables/t1.bin", table.as_slice()), - ]); + ]) + .unwrap(); let names = Package::open(&bytes, &Limits::default()).unwrap().workbook().unwrap().defined_names; assert_eq!(names.iter().find(|n| n.name == "Vals").map(|n| n.formula.as_str()), Some("Sales[Val]")); let wb = read(&bytes).unwrap(); diff --git a/crates/xtask/src/report.rs b/crates/xtask/src/report.rs index f876d06f99..3c021cb97a 100644 --- a/crates/xtask/src/report.rs +++ b/crates/xtask/src/report.rs @@ -90,6 +90,10 @@ mod tests { fn set_permissions(&self, file: &File, perms: Permissions) -> io::Result<()> { RealFs.set_permissions(file, perms) } + #[cfg(unix)] + fn set_group(&self, file: &File, gid: u32) -> io::Result<()> { + RealFs.set_group(file, gid) + } } fn keys(v: &Value) -> Vec<&str> {