diff --git a/crates/doc/src/inline.rs b/crates/doc/src/inline.rs index b22f6cbfc7..731fba6d34 100644 --- a/crates/doc/src/inline.rs +++ b/crates/doc/src/inline.rs @@ -308,16 +308,8 @@ fn resolve_kids( layout: &mut dyn FnMut(&mut TextObject), changed: &mut Vec, ) -> Vec<(usize, Arc)> { - let mut by_id: Option>> = None; let mut out = vec![]; - for (i, c) in kids.iter().enumerate() { - let o = old.and_then(|old| match old.get(i) { - Some(b) if b.id == c.id => Some(b), - _ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(), - }); - if o.is_some_and(|o| Arc::ptr_eq(o, c)) { - continue; - } + for (i, c, o) in crate::changed_nodes(old.unwrap_or_default(), kids) { let mut c = c.clone(); if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) { out.push((i, c)); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 470b0a94c4..6a331c6b77 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -116,6 +116,7 @@ pub use live_paint::{GapOptions, GapSize}; pub use metadata::{CopyrightStatus, DocMetadata}; pub use node::Knockout; pub use node::Scaling; +pub use node::changed_nodes; pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask}; pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; pub use orient::OrientedBox; diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 87b9a375db..3a4b2abd03 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -15,6 +15,7 @@ use crate::symbols::{SYMBOL_SQUARE, SymbolBoxes}; use crate::text::TextObject; mod attributes; +mod changed; mod clip; mod extras; mod ids; @@ -25,6 +26,9 @@ mod ops; mod wire; pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; +#[cfg(test)] +pub(crate) use changed::COUNTERPART_LOOKUPS; +pub use changed::changed_nodes; pub use clip::{ClipPaint, Uniter}; pub use extras::{Extras, ExtrasMut, NodeExtras}; pub use ids::{LAYER_COLORS, LayerColor, NodeId}; diff --git a/crates/doc/src/node/changed.rs b/crates/doc/src/node/changed.rs new file mode 100644 index 0000000000..4aba12f78e --- /dev/null +++ b/crates/doc/src/node/changed.rs @@ -0,0 +1,33 @@ +use std::collections::HashMap; + +use super::{Arc, Node, NodeId}; + +#[cfg(test)] +thread_local! { + /// Tests: how many nodes [`changed_nodes`] looked up a counterpart for on this thread. + pub(crate) static COUNTERPART_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The nodes of `after` that are not the same nodes as their counterparts in `before` (the same +/// list before an edit), with their positions in `after`. A node's counterpart is the node at the +/// same position when it has the same id, else the node in `before` with its id, else `None` (the +/// node is new). A node that is the same node as the one at its position in `before` is skipped +/// without reading it, so a list of many unchanged nodes costs one pointer comparison per node. +pub fn changed_nodes<'a>(before: &'a [Arc], after: &'a [Arc]) -> impl Iterator, Option<&'a Arc>)> { + let mut by_id: Option>> = None; + after.iter().enumerate().filter_map(move |(i, a)| { + if before.get(i).is_some_and(|b| Arc::ptr_eq(b, a)) { + return None; + } + #[cfg(test)] + COUNTERPART_LOOKUPS.with(|c| c.set(c.get() + 1)); + let b = match before.get(i) { + Some(b) if b.id == a.id => Some(b), + _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), + }; + if b.is_some_and(|b| Arc::ptr_eq(b, a)) { + return None; + } + Some((i, a, b)) + }) +} diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 8d6520265a..ed2fdb08d9 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -947,3 +947,37 @@ fn try_walk_ends_at_the_break() { assert_eq!(flow, ControlFlow::Break(NodeId(3))); assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]); } + +/// After an edit of one node in a list of 1,000, `changed_nodes` gives that node and a new one +/// with their counterparts, and looks a counterpart up for those two only: the 999 nodes that are +/// the same nodes in the same places are passed over by their pointers. +#[test] +fn changed_nodes_looks_up_only_the_nodes_that_changed() { + let leaf = |id| Arc::new(Node::group(NodeId(id), vec![])); + let before: Vec> = (0..1000).map(leaf).collect(); + let mut after = before.clone(); + let mut edited = (*after[500]).clone(); + edited.name = Some("edited".into()); + after[500] = Arc::new(edited); + after.push(leaf(5000)); + COUNTERPART_LOOKUPS.with(|c| c.set(0)); + let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect(); + assert_eq!(changed, [(500, NodeId(500), Some(NodeId(500))), (1000, NodeId(5000), None)]); + assert_eq!(COUNTERPART_LOOKUPS.with(|c| c.get()), 2); +} + +/// A node that moved to another place in the list is paired with itself by its id and left out +/// when it is the same node; a changed node that moved is paired with its old node, and a node +/// that is gone from the list gives nothing. +#[test] +fn changed_nodes_pairs_moved_nodes_by_id() { + let leaf = |id| Arc::new(Node::group(NodeId(id), vec![])); + let before = vec![leaf(1), leaf(2), leaf(3), leaf(4)]; + let mut edited = (*before[0]).clone(); + edited.locked = true; + let after = vec![Arc::clone(&before[2]), Arc::clone(&before[1]), Arc::new(edited)]; + let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect(); + assert_eq!(changed, [(2, NodeId(1), Some(NodeId(1)))]); + assert!(changed_nodes(&[], &after).map(|(_, _, b)| b).all(|b| b.is_none()), "every node is new against an empty list"); + assert_eq!(changed_nodes(&[], &after).count(), 3); +} diff --git a/crates/engine/src/cmd/addons/image/mask.rs b/crates/engine/src/cmd/addons/image/mask.rs index 7fdb0c5c3e..a46818befb 100644 --- a/crates/engine/src/cmd/addons/image/mask.rs +++ b/crates/engine/src/cmd/addons/image/mask.rs @@ -14,7 +14,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::color_mask::{ColorMask, MaskBackground, MaskMatch}; -use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind, changed_nodes}; use vectorcraft_geom::Affine; use super::super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process}; @@ -367,14 +367,7 @@ fn stale_in(doc: &Document, n: &Arc, old: Option<&Arc>) -> bool { } let Some(children) = n.children() else { return false }; let before = old.and_then(|o| o.children()).map_or(&[][..], Vec::as_slice); - let mut by_id: Option>> = None; - children.iter().enumerate().any(|(i, c)| { - let b = match before.get(i) { - Some(b) if b.id == c.id => Some(b), - _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(), - }; - stale_in(doc, c, b) - }) + changed_nodes(before, children).any(|(_, c, b)| stale_in(doc, c, b)) } /// Whether `n` is an image whose color mask was not made from its own pixels (or whose masked diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 81909da76f..7bef1cbc69 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -5,7 +5,7 @@ use std::collections::HashMap; -use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign}; +use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign, changed_nodes}; use super::{ Affine, Arc, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Scaling, Session, Value, Vec2, bad, json, @@ -226,15 +226,7 @@ fn refresh_symbols(before: &Document, doc: &mut Document) { /// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity /// mask art holds such instances (`masked`). fn changed_instances(before: &[Arc], after: &[Arc], natural: &HashMap, ids: &mut Vec, masked: &mut Vec) { - let mut by_id: Option>> = None; - for (i, a) in after.iter().enumerate() { - let b = match before.get(i) { - Some(b) if b.id == a.id => Some(b), - _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), - }; - if b.is_some_and(|b| Arc::ptr_eq(b, a)) { - continue; - } + for (_, a, b) in changed_nodes(before, after) { if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) { masked.push(a.id); } @@ -423,15 +415,7 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) { /// pixel-aligned or hold pixel-aligned art in a linked opacity mask. Inside such an object the /// walk stops: [`keep_pixel_aligned`] visits what it holds. fn changed_aligned(before: &[Arc], after: &[Arc], out: &mut Vec) { - let mut by_id: Option>> = None; - for (i, a) in after.iter().enumerate() { - let b = match before.get(i) { - Some(b) if b.id == a.id => Some(b), - _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), - }; - if b.is_some_and(|b| Arc::ptr_eq(b, a)) { - continue; - } + for (_, a, b) in changed_nodes(before, after) { if a.extras().pixel_aligned || a.extras().mask.as_ref().is_some_and(|m| m.linked && holds_aligned(&m.art)) { out.push(a.id); } else if let Some(children) = a.children() { diff --git a/crates/engine/src/cmd/objects_on_path.rs b/crates/engine/src/cmd/objects_on_path.rs index 7dc8aec1c9..299ed5f49c 100644 --- a/crates/engine/src/cmd/objects_on_path.rs +++ b/crates/engine/src/cmd/objects_on_path.rs @@ -25,12 +25,12 @@ //! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and //! the objects that move up the path after it; Expand). -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::objects_on_path::{CENTER, Held, ObjectsOnPath, attachable_path, held, is_objects_on_path, place}; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, changed_nodes}; use vectorcraft_geom::Rect; use super::edit::{roots_of, selected_roots}; @@ -499,15 +499,7 @@ fn place_in(doc: &mut Document, id: NodeId) -> bool { /// The Objects on Path groups among `after` and inside them that are not the same nodes as before /// (`before`: the same list before the edit), outer ones first. fn changed_groups(before: &[Arc], after: &[Arc], out: &mut Vec) { - let mut by_id: Option>> = None; - for (i, a) in after.iter().enumerate() { - let b = match before.get(i) { - Some(b) if b.id == a.id => Some(b), - _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), - }; - if b.is_some_and(|b| Arc::ptr_eq(b, a)) { - continue; - } + for (_, a, b) in changed_nodes(before, after) { if is_objects_on_path(a) { out.push(a.id); } diff --git a/crates/engine/src/cmd/shaper.rs b/crates/engine/src/cmd/shaper.rs index 228251fa13..93e479033f 100644 --- a/crates/engine/src/cmd/shaper.rs +++ b/crates/engine/src/cmd/shaper.rs @@ -6,12 +6,9 @@ use super::{ CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, number_or, object_param, point_param, }; use serde_json::{Value, json}; -use std::{ - collections::{BTreeMap, HashMap}, - sync::Arc, -}; +use std::{collections::BTreeMap, sync::Arc}; use vectorcraft_doc::shaper::{EdgeEdit, FILL_PREFIX, FaceEdit, FaceSelector, SOURCES, STROKE_PREFIX, ShaperSpec}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, changed_nodes}; use vectorcraft_geom::{FillRule, PathData, Point, Rect, Shape as _}; use vectorcraft_pathops as po; use vectorcraft_tools::builder::{self as b, BuilderMap}; @@ -392,15 +389,7 @@ fn generated(d: &mut Document, src: &[Arc], spec: &ShaperSpec, map: &Build } fn changed_shaper_groups(before: &[Arc], after: &[Arc], out: &mut Vec) { - let mut by_id: Option>> = None; - for (i, a) in after.iter().enumerate() { - let b = match before.get(i) { - Some(b) if b.id == a.id => Some(b), - _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), - }; - if b.is_some_and(|b| Arc::ptr_eq(b, a)) { - continue; - } + for (_, a, b) in changed_nodes(before, after) { if a.extras().shaper.is_some() { out.push(a.id); }