EPS import: complexity tests count the work done instead of timing it

Four EPS import tests asserted elapsed time (5 s, 20 s, a 20 s receive
timeout, and 1,000 copies against 5 times one copy). A busy test runner
could fail them, and a slower run that was still bounded could pass them.
Each now reads a test-only counter on its own thread:

- `]` without its `[`: the operand stack slots that `[` and `]` look at.
  200,000 brackets look at no more than 4 slots each.
- The outline check: the point-to-segment distances it works out. A look
  drawn 5,000 times works out no more than `MAX_OUTLINE_PAIRS`.
- Objects on a path: the paths and objects the records measure. A
  thousand copies of a record measure as many as one copy.
- File fonts: the glyphs `fits` compares. A string of 250,000 of one
  character makes fewer comparisons than it has glyphs.

Outside tests the counters do nothing.
This commit is contained in:
dotCooCoo committed 2026-11-28 01:55:59 -08:00
1 parent c996fbba08
commit d19a3305a4
5 files changed
+100 -31

No files matched your search

+4
View File
@@ -155,6 +155,10 @@ pub use document::{
};
pub(crate) use document::{slot_frame, slot_of};
use graph::Graph;
#[cfg(test)]
pub(crate) use on_path::on_path_measured;
#[cfg(test)]
pub(crate) use ops::array_slots;
pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, parsed_type_color, read_parsed_style, read_style_list};
#[cfg(test)]
pub(crate) use raster::with_image_limits;
+16
View File
@@ -123,6 +123,18 @@ impl Reader<'_> {
}
}
#[cfg(test)]
thread_local! {
/// How many paths and objects the records on this thread have measured.
static MEASURED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// [`MEASURED`] of this thread.
#[cfg(test)]
pub(crate) fn on_path_measured() -> u64 {
MEASURED.get()
}
/// Give each group that a record of `found` names exactly its [`ObjectsOnPath`] record.
pub(super) fn apply(doc: &mut Document, found: &OnPath) {
if found.records.is_empty() {
@@ -174,11 +186,15 @@ fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap<NodeId, Vec<usize>
if !tried.insert(g.id) {
return None;
}
#[cfg(test)]
MEASURED.set(MEASURED.get() + 1);
attachable_path(children.iter().find(|c| c.id == path)?)?;
let mut members = Vec::with_capacity(placed.len());
for (id, place, angle) in placed {
// The frame the object is drawn in: turned by its angle (the document's y points down)
// about the center of its bounds.
#[cfg(test)]
MEASURED.set(MEASURED.get() + 1);
let center = doc.node_at(place)?.geometric_bounds()?.center();
members.push(Member { id, frame: Affine::rotate_about(angle, center), angle });
}
+46 -6
View File
@@ -9,6 +9,29 @@ use super::{
use vectorcraft_doc::{ArrowAlign, Arrowhead};
use vectorcraft_geom::PathData;
#[cfg(test)]
thread_local! {
/// The operand stack slots that `[` and `]` have looked at on this thread, to find the open
/// `[` or to take an array's items: their work.
static ARRAY_SLOTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// The point-to-segment distances [`draws_look_outline`] has worked out on this thread.
static OUTLINE_PAIRS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// [`ARRAY_SLOTS`] of this thread.
#[cfg(test)]
pub(crate) fn array_slots() -> u64 {
ARRAY_SLOTS.get()
}
/// Count `slots` that `[` or `]` looked at in [`ARRAY_SLOTS`]; nothing outside tests.
fn array_slots_looked_at(slots: usize) {
#[cfg(test)]
ARRAY_SLOTS.set(ARRAY_SLOTS.get().saturating_add(u64::try_from(slots).unwrap_or(u64::MAX)));
#[cfg(not(test))]
let _ = slots;
}
impl<'a> Reader<'a> {
// ---- operators -------------------------------------------------------------------------
@@ -16,11 +39,13 @@ impl<'a> Reader<'a> {
// The innermost `[` still on the stack (the stack is cut back by operators).
let mut at = self.stack.len();
while let Some(m) = self.marks.pop() {
array_slots_looked_at(1);
if matches!(self.stack.get(m), Some(V::Mark)) {
at = m;
break;
}
}
array_slots_looked_at(self.stack.len() - at);
let items: Vec<V> = self.stack.split_off(at).into_iter().skip(1).collect();
self.push(V::Arr(items))
}
@@ -172,6 +197,7 @@ impl<'a> Reader<'a> {
"[" => {
// Drop marks that operators have taken off, so `marks` is the open nesting.
while self.marks.last().is_some_and(|&m| !matches!(self.stack.get(m), Some(V::Mark))) {
array_slots_looked_at(1);
self.marks.pop();
}
// Arrays nest as deep as their `[`s; dropping a deeper one would overflow the stack.
@@ -1635,7 +1661,13 @@ fn draws_look_outline(object: &Node, appearance: &Appearance, look: &Node) -> bo
/// projection onto it) is taken from `budget`: `false` once that runs out.
fn near(a: &[kurbo::Line], b: &[kurbo::Line], budget: &mut usize) -> bool {
use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest};
let close = |p: kurbo::Point| b.iter().any(|t| t.nearest(p, 1e-6).distance_sq <= OUTLINE_POINT_LIMIT * OUTLINE_POINT_LIMIT);
let close = |p: kurbo::Point| {
b.iter().any(|t| {
#[cfg(test)]
OUTLINE_PAIRS.set(OUTLINE_PAIRS.get() + 1);
t.nearest(p, 1e-6).distance_sq <= OUTLINE_POINT_LIMIT * OUTLINE_POINT_LIMIT
})
};
for s in a {
let steps = (s.arclen(1e-6) / OUTLINE_SPACING).ceil();
let steps = if steps.is_finite() && steps >= 1.0 { steps as usize } else { 1 };
@@ -2019,7 +2051,8 @@ mod tests {
/// The outline check works from one budget for the object: a look of the outline drawn twice
/// (a fill and a stroke) matches, one drawn thousands of times gives up and keeps the drawn
/// look instead of comparing every copy.
/// look instead of comparing every copy, having worked out no more distances than the budget
/// holds.
#[test]
fn the_outline_check_has_one_budget_for_the_object() {
let zig = vectorcraft_doc::Effect {
@@ -2035,10 +2068,17 @@ mod tests {
let drawn = (0..copies).map(|i| Arc::new(Node::path(NodeId(10 + i), outline.clone(), Appearance::default()))).collect();
Node::group(NodeId(2), drawn)
};
assert!(draws_look_outline(&object, &appearance, &look(2)));
let started = std::time::Instant::now();
assert!(!draws_look_outline(&object, &appearance, &look(5_000)));
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
// Whether the object draws `look`, and how many distances the check worked out.
let check = |look: &Node| {
let before = OUTLINE_PAIRS.get();
let drawn = draws_look_outline(&object, &appearance, look);
(drawn, OUTLINE_PAIRS.get() - before)
};
let (drawn, two) = check(&look(2));
assert!(drawn);
let (drawn, many) = check(&look(5_000));
assert!(many <= u64::try_from(MAX_OUTLINE_PAIRS).unwrap(), "5,000 copies: {many} distances; 2 copies: {two}");
assert!(!drawn);
}
/// The outline check reshapes the object as it is drawn, its effects working from its bounds
+15 -17
View File
@@ -6440,13 +6440,16 @@ fn a_zstandard_frame_ending_in_a_zero_byte_is_read_whole() {
}
}
/// A `]` without its `[` looks at a few operand stack slots, not at every slot below it: hundreds
/// of thousands of them look at no more than four slots each.
#[test]
fn closing_brackets_without_their_opening_dont_rescan_the_stack() {
let n = 200_000;
let body = format!("{}\n{}\n", "1 ".repeat(n), "] ".repeat(n));
let started = std::time::Instant::now();
let before = read::array_slots();
let _ = read(stream(&layer(&body)).as_bytes());
assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed());
let slots = read::array_slots() - before;
assert!(slots <= 4 * u64::try_from(n).unwrap(), "{n} brackets looked at {slots} slots");
}
#[test]
@@ -10833,9 +10836,9 @@ fn an_objects_on_path_record_that_doesnt_fit_leaves_a_plain_group() {
}
/// The path and objects of a group are measured once however many records name it: a thousand
/// copies of a record open about as fast as one copy followed by 999 records whose path id is
/// missing, when the group opens live, when its long path has no length, and when its first object
/// is a group of many paths and its last object has no bounds.
/// copies of a record measure as many paths and objects as one copy followed by 999 records whose
/// path id is missing, when the group opens live, when its long path has no length, and when its
/// first object is a group of many paths and its last object has no bounds.
#[test]
fn repeated_objects_on_path_records_dont_measure_the_objects_again() {
use vectorcraft_testkit::ai::{on_path_member, on_path_options, on_path_record};
@@ -10860,23 +10863,18 @@ fn repeated_objects_on_path_records_dont_measure_the_objects_again() {
let unresolved = copy.replace(ids[0], "0a6d1e52-ffff-4000-8000-000000000000");
let one = format!("{}{copy}{}{}", &record[..start], unresolved.repeat(999), &record[end..]);
let many = format!("{}{}{}", &record[..start], copy.repeat(1000), &record[end..]);
let time = |data: &str| {
let started = std::time::Instant::now();
let measure = |data: &str| {
let before = read::on_path_measured();
let doc = read_ok(&format!("{data}{}", layer(&group))).doc;
let elapsed = started.elapsed();
let measured = read::on_path_measured() - before;
let g = art(&doc)[0].clone();
assert_eq!(g.children().unwrap().len(), n, "{why}");
assert_eq!(g.extras().objects_on_path.is_some(), live, "{why}");
elapsed
measured
};
// The fastest of three runs each, taken in turn, so that other tests running at the same
// time weigh on both.
let (mut fastest_one, mut fastest_many) = (std::time::Duration::MAX, std::time::Duration::MAX);
for _ in 0..3 {
fastest_one = fastest_one.min(time(&one));
fastest_many = fastest_many.min(time(&many));
}
assert!(fastest_many < fastest_one * 5, "{why}: one copy: {fastest_one:?}, 1000 copies: {fastest_many:?}");
let (measured_one, measured_many) = (measure(&one), measure(&many));
assert!(measured_one > 0, "{why}");
assert_eq!(measured_many, measured_one, "{why}: 1000 copies measured {measured_many} times, one copy {measured_one}");
}
}
+19 -8
View File
@@ -38,6 +38,12 @@ struct Gathered {
chars: HashMap<char, usize>,
}
#[cfg(test)]
thread_local! {
/// How many glyphs [`FileFontGlyphs::fits`] has compared with another glyph on this thread.
static COMPARED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
impl FileFontGlyphs {
/// The font of `family` and `style` (made with `info` the first time): its index.
pub fn font(&mut self, family: &str, style: &str, info: impl FnOnce() -> FileFontInfo) -> usize {
@@ -59,6 +65,10 @@ impl FileFontGlyphs {
let mut new: HashMap<char, &FileGlyph> = HashMap::new();
for g in glyphs {
let kept = f.chars.get(&g.ch).and_then(|&k| f.glyphs.get(k)).or_else(|| new.get(&g.ch).copied());
#[cfg(test)]
if kept.is_some() {
COMPARED.set(COMPARED.get() + 1);
}
match kept {
Some(k) if k.outline != g.outline || k.advance != g.advance => return false,
Some(_) => {}
@@ -178,15 +188,16 @@ mod tests {
}
/// A long string of one character compares each glyph with that character's once, not with
/// every one before it: a quarter of a million of them fit at once.
/// every one before it: a quarter of a million of them fit at once, with fewer comparisons
/// than glyphs.
#[test]
fn a_long_string_of_one_character_fits_in_linear_time() {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut g = FileFontGlyphs::default();
let f = g.font("F", "Regular", FileFontInfo::default);
tx.send(g.fits(f, &vec![glyph('A'); 250_000])).ok();
});
assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(20)), Ok(true));
let n = 250_000;
let mut g = FileFontGlyphs::default();
let f = g.font("F", "Regular", FileFontInfo::default);
let before = COMPARED.get();
assert!(g.fits(f, &vec![glyph('A'); n]));
let compared = COMPARED.get() - before;
assert!(compared < u64::try_from(n).unwrap(), "{n} glyphs: {compared} comparisons");
}
}