Merge pull request #3557 from RickiNano/fix/xfl-edges-resume-3282

craft-xfl: an unreadable edge command ends only its run (#3282)
This commit is contained in:
FredApps authored and GitHub committed 2026-11-26 14:34:25 +01:00
commit a0b1d127ae
2 files changed
+94 -32

No files matched your search

+88 -31
View File
@@ -5,8 +5,10 @@
//! Coordinates may be decimal or signed 24.8 fixed-point hexadecimal (`#A.8` is 10.5).
//!
//! This module returns neutral points and segments so consumers can map them to their own
//! geometry model. Like Animate files in the wild, a damaged suffix ends parsing while keeping
//! the valid prefix. The segment cap bounds output allocation.
//! geometry model. Each `!` starts a run that depends on nothing before it, so an unknown or
//! malformed command ends only its own run: the run's valid prefix is kept and parsing resumes
//! at the next `!`. [`parse_edges`](crate::edges::parse_edges) reports how many runs were cut
//! short. The segment cap bounds output allocation.
/// Most segments parsed from one edge attribute.
pub const MAX_EDGE_SEGMENTS: usize = 2_000_000;
@@ -26,6 +28,15 @@ pub struct Segment {
pub to: Point,
}
/// Segments parsed from one edge attribute, with a count of the runs that were not read whole.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ParsedEdges {
pub segments: Vec<Segment>,
/// Runs that ended early at an unknown or malformed command, or that the segment cap cut off
/// or left unread. A run's segments before the point where it ended are still in `segments`.
pub cut_runs: usize,
}
const TWIPS_PER_PIXEL: f32 = 20.0;
fn number(input: &[u8], at: &mut usize) -> Option<f32> {
@@ -58,8 +69,17 @@ fn number(input: &[u8], at: &mut usize) -> Option<f32> {
if matches!(input.get(*at), Some(b'-' | b'+')) {
*at += 1;
}
while input.get(*at).is_some_and(|b| b.is_ascii_digit() || matches!(b, b'.' | b'e' | b'E')) {
*at += 1;
while let Some(&b) = input.get(*at) {
if b.is_ascii_digit() || b == b'.' {
*at += 1;
} else if matches!(b, b'e' | b'E') {
*at += 1;
if matches!(input.get(*at), Some(b'-' | b'+')) {
*at += 1;
}
} else {
break;
}
}
std::str::from_utf8(input.get(start..*at)?).ok()?.parse::<f32>().ok().filter(|v| v.is_finite())
}
@@ -70,47 +90,63 @@ fn point(input: &[u8], at: &mut usize) -> Option<Point> {
/// Parses an XFL `<Edge edges="…">` attribute into pixel-coordinate line and quadratic segments.
///
/// Stops at the first unknown or malformed command, preserving the valid prefix. The current
/// An unknown or malformed command ends its run, keeping the run's valid prefix, and parsing
/// resumes at the next `!`; use [`parse_edges`] to learn how many runs were cut short. The current
/// point starts at the origin. Move and selection commands do not produce segments.
pub fn parse_edge_segments(source: &str) -> Vec<Segment> {
parse_edges(source).segments
}
/// Parses an XFL `<Edge edges="…">` attribute like [`parse_edge_segments`], and also counts the
/// runs that were cut short, so a consumer can report that part of the edge is missing.
pub fn parse_edges(source: &str) -> ParsedEdges {
let input = source.as_bytes();
let mut at = 0;
let mut current = Point::default();
let mut segments = Vec::new();
let mut parsed = ParsedEdges::default();
while let Some(&command) = input.get(at) {
at += 1;
match command {
b'!' => match point(input, &mut at) {
Some(p) => current = p,
None => break,
},
b'|' | b'/' => match point(input, &mut at) {
Some(to) => {
segments.push(Segment { from: current, control: None, to });
current = to;
}
None => break,
},
b'[' | b']' => match (point(input, &mut at), point(input, &mut at)) {
(Some(control), Some(to)) => {
segments.push(Segment { from: current, control: Some(control), to });
current = to;
}
_ => break,
},
let read = match command {
b'!' => point(input, &mut at).map(|p| current = p),
b'|' | b'/' => point(input, &mut at).map(|to| {
parsed.segments.push(Segment { from: current, control: None, to });
current = to;
}),
b'[' | b']' => point(input, &mut at).zip(point(input, &mut at)).map(|(control, to)| {
parsed.segments.push(Segment { from: current, control: Some(control), to });
current = to;
}),
b'S' => {
while input.get(at).is_some_and(u8::is_ascii_digit) {
at += 1;
}
Some(())
}
b if b.is_ascii_whitespace() => {}
_ => break,
b if b.is_ascii_whitespace() => Some(()),
_ => None,
};
if read.is_none() {
parsed.cut_runs += 1;
at = next_run(input, at);
}
if segments.len() >= MAX_EDGE_SEGMENTS {
if parsed.segments.len() >= MAX_EDGE_SEGMENTS {
parsed.cut_runs += unread_runs(input.get(at..).unwrap_or_default());
break;
}
}
segments
parsed
}
/// The index of the next run's `!` at or after `at`, or the end of the input.
fn next_run(input: &[u8], at: usize) -> usize {
input.get(at..).and_then(|rest| rest.iter().position(|&b| b == b'!')).map_or(input.len(), |offset| at + offset)
}
/// Runs in `rest` that parsing will not reach: the current run if anything but whitespace is left
/// of it, and every later run.
fn unread_runs(rest: &[u8]) -> usize {
let current_run = rest.iter().take_while(|&&b| b != b'!').any(|b| !b.is_ascii_whitespace());
usize::from(current_run) + rest.iter().filter(|&&b| b == b'!').count()
}
#[cfg(test)]
@@ -142,11 +178,32 @@ mod tests {
assert!(parse_edge_segments("!NaN 2|5 5").is_empty());
}
#[test]
fn unreadable_command_ends_only_its_run() {
let line = |from: (f32, f32), to: (f32, f32)| Segment { from: Point { x: from.0, y: from.1 }, control: None, to: Point { x: to.0, y: to.1 } };
let parsed = parse_edges("!0 0|200 0?7|300 0!400 0|600 0");
assert_eq!(parsed.segments, [line((0.0, 0.0), (10.0, 0.0)), line((20.0, 0.0), (30.0, 0.0))]);
assert_eq!(parsed.cut_runs, 1);
let parsed = parse_edges("!x 0|200 0!0 20[1 2 nope|5 5!0 0|0 200");
assert_eq!(parsed.segments, [line((0.0, 0.0), (0.0, 10.0))]);
assert_eq!(parsed.cut_runs, 2);
assert_eq!(parse_edges("!0 0|200 0S2 !0 0|0 200").cut_runs, 0);
}
#[test]
fn decimal_coordinates_take_a_signed_exponent() {
let segments = parse_edge_segments("!0 0|2e+2 400E-1");
assert_eq!(segments.len(), 1);
assert_eq!(segments[0].to, Point { x: 10.0, y: 2.0 });
}
#[test]
fn oversized_coordinate_numbers_and_segment_lists_are_bounded() {
assert!(parse_edge_segments("!999999999999999999999999999999999999999999999999 0|1 1").is_empty());
let source = "|0 0".repeat(MAX_EDGE_SEGMENTS + 1);
let segments = parse_edge_segments(&source);
assert_eq!(segments.len(), MAX_EDGE_SEGMENTS);
let parsed = parse_edges(&source);
assert_eq!(parsed.segments.len(), MAX_EDGE_SEGMENTS);
assert_eq!(parsed.cut_runs, 1);
}
}
+6 -1
View File
@@ -4,7 +4,7 @@
//! application's geometry, paint, or animation types. They work with `craft_xml::El` and with
//! compatible borrowed element adapters implemented by consumers.
use crate::edges::{self, Segment};
use crate::edges::{self, ParsedEdges, Segment};
use std::borrow::Cow;
/// An element source used by the borrowed XFL schema views.
@@ -529,6 +529,11 @@ impl<E: XflElement> Edge<'_, E> {
pub fn segments(&self) -> Vec<Segment> {
self.encoded_segments().map(edges::parse_edge_segments).unwrap_or_default()
}
/// Parsed XFL path segments, with a count of the runs that were cut short.
pub fn parsed_edges(&self) -> ParsedEdges {
self.encoded_segments().map(edges::parse_edges).unwrap_or_default()
}
}
#[cfg(test)]