From 3532ddf65ebd8cc7e6ca451e8d6d508a6ab2ba54 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:07:49 +0700 Subject: [PATCH 1/2] fix(doc): look layers and blocks up by name through an index, so crafted files don't open in quadratic time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drawing::layer scanned every layer, and Drawing::block scanned every block when the exact name missed. Both run once per entity while a drawing is read, measured and inspected, so a file with N layers, or with N blocks and N references to blocks it doesn't have, opened in N² comparisons (40 000 missing-block references: 75.7 s in a dev build; 40 000 layers: 6.8 s). Drawing::layers is now a NamedList and Drawing::blocks a NamedMap>. They read and change as the Vec and BTreeMap they wrap, and keep an index from a keyed hash of the case-folded name to the first entry of that hash. A hit is checked against the name and falls back to the scan, so results are the same as before: same case rule, first match in table order, exact block name first. Every change goes through DerefMut, which drops the index; a clone (undo snapshot) shares it. The index is built only for tables of 64 entries or more, after 32 scans since the last change, so code that changes a table between lookups costs what it did. Part of #1924 (F-04). Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/lib.rs | 22 +- crates/doc/src/names.rs | 484 +++++++++++++++++++++++++++++ crates/doc/src/tables.rs | 4 +- crates/doc/src/tests.rs | 19 ++ crates/engine/src/cmd/clipboard.rs | 2 +- crates/engine/src/cmd/layer.rs | 4 +- crates/engine/src/spatial.rs | 2 +- crates/ui-egui/src/layers.rs | 2 +- 8 files changed, 525 insertions(+), 14 deletions(-) create mode 100644 crates/doc/src/names.rs diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 386fca347..32839b1ae 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -14,6 +14,7 @@ mod format; mod gdt; mod header; pub mod library; +mod names; mod plotstyle; mod plotter; mod raster; @@ -36,6 +37,7 @@ pub use extents::{ pub use format::Format; pub use gdt::*; pub use header::{HVal, Header}; +pub use names::{Named, NamedList, NamedMap}; pub use plotstyle::*; pub use plotter::*; pub use raster::{Raster, Rasters}; @@ -101,7 +103,8 @@ pub struct Drawing { pub header: Header, /// File data CADCraft does not model, written back on save. pub foreign: std::sync::Arc, - pub layers: Vec, + /// Layers in table order; [`Drawing::layer`] looks them up by name. + pub layers: NamedList, pub linetypes: Vec, pub text_styles: Vec, pub dim_styles: Vec, @@ -109,7 +112,8 @@ pub struct Drawing { pub table_styles: Vec, /// Multiline styles (MLSTYLE); STANDARD is always there. pub mline_styles: Vec, - pub blocks: BTreeMap>, + /// Block definitions by name; [`Drawing::block`] looks them up. + pub blocks: NamedMap>, pub model: EntityStore, /// Model layout's page setup, or the default extents-to-fit setup for a new drawing. pub model_page: Option, @@ -195,7 +199,7 @@ impl Drawing { Drawing { header: Header::default(), foreign: std::sync::Arc::default(), - layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }], + layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }].into(), linetypes: vec![ Linetype { name: "ByBlock".into(), description: String::new(), pattern: Vec::new() }, Linetype { name: "ByLayer".into(), description: String::new(), pattern: Vec::new() }, @@ -206,7 +210,7 @@ impl Drawing { mleader_styles: vec![MLeaderStyle::default()], table_styles: vec![TableStyle::default()], mline_styles: vec![MLineStyle::default()], - blocks: BTreeMap::new(), + blocks: NamedMap::default(), model: EntityStore::new(), model_page: None, layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)], @@ -313,11 +317,14 @@ impl Drawing { } } + /// The first layer named `name`, without case. pub fn layer(&self, name: &str) -> Option<&Layer> { - self.layers.iter().find(|l| l.name.eq_ignore_ascii_case(name)) + self.layers.by_name(name) } + /// The first layer named `name`, without case, to change. pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> { - self.layers.iter_mut().find(|l| l.name.eq_ignore_ascii_case(name)) + let i = self.layers.position_by_name(name)?; + self.layers.get_mut(i) } pub fn linetype(&self, name: &str) -> Option<&Linetype> { self.linetypes.iter().find(|l| l.name.eq_ignore_ascii_case(name)) @@ -394,8 +401,9 @@ impl Drawing { } } } + /// The block named exactly `name`, else the first by name order named `name` without case. pub fn block(&self, name: &str) -> Option<&std::sync::Arc> { - self.blocks.get(name).or_else(|| self.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v)) + self.blocks.by_name(name) } pub fn layout(&self, name: &str) -> Option<&Layout> { self.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(name)) diff --git a/crates/doc/src/names.rs b/crates/doc/src/names.rs new file mode 100644 index 000000000..a5618533b --- /dev/null +++ b/crates/doc/src/names.rs @@ -0,0 +1,484 @@ +//! The layer and block tables, whose names are looked up without case in about constant time. +//! +//! [`Drawing::layer`](crate::Drawing::layer) and [`Drawing::block`](crate::Drawing::block) run for +//! every entity while a drawing is read, measured and drawn. Scanning the table on each made a file +//! of N layers, or of N blocks and N references to blocks it does not have, cost N² name +//! comparisons: tens of seconds to open at a few tens of thousands (#1924, F-04). +//! +//! Each table keeps an index from the hash of a name with its ASCII letters lower-cased to the +//! table's first entry of that hash, so a lookup returns what a scan in table order returns. +//! Every change to a table goes through `DerefMut`, which drops the index, so it can never be +//! stale. The index is built only once a table has been scanned [`SCANS_BEFORE_INDEX`] times since +//! it last changed: a table changed between every few lookups costs what scanning it always did, +//! and one looked up many times in between is indexed once. + +use std::collections::{BTreeMap, HashMap, btree_map}; +use std::hash::{BuildHasher, Hasher}; +use std::ops::{Deref, DerefMut}; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Arc, OnceLock}; + +/// Tables with fewer entries than this are always scanned: comparing a few names costs less than +/// hashing one. +const MIN_INDEXED: usize = 64; +/// Lookups that scan a table after it changed before its index is built. A build costs about as +/// much as some tens of scans. +const SCANS_BEFORE_INDEX: u32 = 32; + +/// From the hash of a name without case to the first entry, in table order, of a name with that +/// hash. The hash is keyed per index (the map's `RandomState`), so a file cannot choose names that +/// collide. +struct Index(HashMap); + +impl Index { + fn build<'a>(entries: impl Iterator) -> Self { + let mut map = HashMap::new(); + for (name, v) in entries { + map.entry(folded_hash(map.hasher(), name)).or_insert(v); + } + Index(map) + } + + /// The first entry whose name hashes as `name` does: the first named `name` without case when + /// its name is that, else another name with the same hash, and the caller scans. + fn get(&self, name: &str) -> Option<&V> { + self.0.get(&folded_hash(self.0.hasher(), name)) + } +} + +/// The hash of `name` with its ASCII letters lower-cased: names that `eq_ignore_ascii_case` finds +/// equal hash the same. +fn folded_hash(state: &impl BuildHasher, name: &str) -> u64 { + let mut h = state.build_hasher(); + let mut buf = [0u8; 64]; + for chunk in name.as_bytes().chunks(buf.len()) { + if let Some(part) = buf.get_mut(..chunk.len()) { + part.copy_from_slice(chunk); + part.make_ascii_lowercase(); + h.write(part); + } + } + h.write_usize(name.len()); + h.finish() +} + +/// A table's index: built on demand, shared by copies of the unchanged table (an undo snapshot), +/// dropped when the table changes. +struct Lazy { + index: OnceLock>>, + /// Lookups that scanned the table since it last changed. + scans: AtomicU32, +} + +impl Lazy { + /// The index of a table of `len` entries, built with `build` once the table has been scanned + /// often enough since it changed; `None` while it is to be scanned. + fn get(&self, len: usize, build: impl FnOnce() -> Index) -> Option<&Index> { + if let Some(ix) = self.index.get() { + return Some(ix); + } + if len < MIN_INDEXED || self.scans.fetch_add(1, Ordering::Relaxed) < SCANS_BEFORE_INDEX { + return None; + } + Some(self.index.get_or_init(|| Arc::new(build()))) + } + + /// Forget the index: the table may change. + fn clear(&mut self) { + self.index = OnceLock::new(); + *self.scans.get_mut() = 0; + } +} + +impl Default for Lazy { + fn default() -> Self { + Lazy { index: OnceLock::new(), scans: AtomicU32::new(0) } + } +} + +impl Clone for Lazy { + fn clone(&self) -> Self { + Lazy { index: self.index.clone(), scans: AtomicU32::new(0) } + } +} + +/// An entry of a [`NamedList`]: what it is looked up by. +pub trait Named { + fn name(&self) -> &str; +} + +impl Named for crate::Layer { + fn name(&self) -> &str { + &self.name + } +} + +/// A list of named entries in their own order (the drawing's layers). It reads and changes as a +/// `Vec`; [`NamedList::by_name`] finds the first entry of a name without case. +pub struct NamedList { + list: Vec, + index: Lazy, +} + +impl NamedList { + /// The position of the first entry named `name`, without case. + pub fn position_by_name(&self, name: &str) -> Option { + let scan = || self.list.iter().position(|t| t.name().eq_ignore_ascii_case(name)); + let Some(ix) = self.index.get(self.list.len(), || Index::build(self.list.iter().enumerate().map(|(i, t)| (t.name(), i)))) else { + return scan(); + }; + match ix.get(name) { + None => None, + Some(&i) if self.list.get(i).is_some_and(|t| t.name().eq_ignore_ascii_case(name)) => Some(i), + Some(_) => scan(), + } + } + + /// The first entry named `name`, without case. + pub fn by_name(&self, name: &str) -> Option<&T> { + self.position_by_name(name).and_then(|i| self.list.get(i)) + } +} + +impl Deref for NamedList { + type Target = Vec; + fn deref(&self) -> &Vec { + &self.list + } +} + +impl DerefMut for NamedList { + fn deref_mut(&mut self) -> &mut Vec { + self.index.clear(); + &mut self.list + } +} + +impl Default for NamedList { + fn default() -> Self { + Vec::new().into() + } +} + +impl Clone for NamedList { + fn clone(&self) -> Self { + NamedList { list: self.list.clone(), index: self.index.clone() } + } +} + +impl std::fmt::Debug for NamedList { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.list.fmt(f) + } +} + +impl PartialEq for NamedList { + fn eq(&self, other: &Self) -> bool { + self.list == other.list + } +} + +impl From> for NamedList { + fn from(list: Vec) -> Self { + NamedList { list, index: Lazy::default() } + } +} + +impl From> for Vec { + fn from(l: NamedList) -> Self { + l.list + } +} + +impl serde::Serialize for NamedList { + fn serialize(&self, s: S) -> Result { + self.list.serialize(s) + } +} + +impl FromIterator for NamedList { + fn from_iter>(iter: I) -> Self { + Vec::from_iter(iter).into() + } +} + +impl IntoIterator for NamedList { + type Item = T; + type IntoIter = std::vec::IntoIter; + fn into_iter(self) -> Self::IntoIter { + self.list.into_iter() + } +} + +impl<'a, T> IntoIterator for &'a NamedList { + type Item = &'a T; + type IntoIter = std::slice::Iter<'a, T>; + fn into_iter(self) -> Self::IntoIter { + self.list.iter() + } +} + +impl<'a, T> IntoIterator for &'a mut NamedList { + type Item = &'a mut T; + type IntoIter = std::slice::IterMut<'a, T>; + fn into_iter(self) -> Self::IntoIter { + self.deref_mut().iter_mut() + } +} + +/// Entries by name, in name order (the drawing's block definitions). It reads and changes as a +/// `BTreeMap`; [`NamedMap::by_name`] finds an entry by its exact name, else the first in name +/// order whose name matches without case. +pub struct NamedMap { + map: BTreeMap, + index: Lazy>, +} + +impl NamedMap { + /// The entry named exactly `name`, else the first in name order named `name` without case. + pub fn by_name(&self, name: &str) -> Option<&V> { + if let Some(v) = self.map.get(name) { + return Some(v); + } + let scan = || self.map.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v); + let Some(ix) = self.index.get(self.map.len(), || Index::build(self.map.keys().map(|k| (k.as_str(), Box::from(k.as_str()))))) else { + return scan(); + }; + match ix.get(name) { + None => None, + Some(k) if k.eq_ignore_ascii_case(name) => self.map.get(&**k).or_else(scan), + Some(_) => scan(), + } + } +} + +impl Deref for NamedMap { + type Target = BTreeMap; + fn deref(&self) -> &BTreeMap { + &self.map + } +} + +impl DerefMut for NamedMap { + fn deref_mut(&mut self) -> &mut BTreeMap { + self.index.clear(); + &mut self.map + } +} + +impl Default for NamedMap { + fn default() -> Self { + BTreeMap::new().into() + } +} + +impl Clone for NamedMap { + fn clone(&self) -> Self { + NamedMap { map: self.map.clone(), index: self.index.clone() } + } +} + +impl std::fmt::Debug for NamedMap { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.map.fmt(f) + } +} + +impl PartialEq for NamedMap { + fn eq(&self, other: &Self) -> bool { + self.map == other.map + } +} + +impl From> for NamedMap { + fn from(map: BTreeMap) -> Self { + NamedMap { map, index: Lazy::default() } + } +} + +impl FromIterator<(String, V)> for NamedMap { + fn from_iter>(iter: I) -> Self { + BTreeMap::from_iter(iter).into() + } +} + +impl IntoIterator for NamedMap { + type Item = (String, V); + type IntoIter = btree_map::IntoIter; + fn into_iter(self) -> Self::IntoIter { + self.map.into_iter() + } +} + +impl<'a, V> IntoIterator for &'a NamedMap { + type Item = (&'a String, &'a V); + type IntoIter = btree_map::Iter<'a, String, V>; + fn into_iter(self) -> Self::IntoIter { + self.map.iter() + } +} + +impl<'a, V> IntoIterator for &'a mut NamedMap { + type Item = (&'a String, &'a mut V); + type IntoIter = btree_map::IterMut<'a, String, V>; + fn into_iter(self) -> Self::IntoIter { + self.deref_mut().iter_mut() + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::MIN_INDEXED; + use crate::{Block, Drawing, Layer}; + + /// Names to look up: each given name as it is, upper-cased, lower-cased and with a character + /// added (a miss). + fn probes<'a>(names: impl Iterator) -> Vec { + names.flat_map(|n| [n.to_string(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]).collect() + } + + fn layers_indexed(d: &Drawing) -> bool { + d.layers.index.index.get().is_some() + } + + fn blocks_indexed(d: &Drawing) -> bool { + d.blocks.index.index.get().is_some() + } + + /// `layer_mut` finds the first layer of a name and drops the index, as the table may change + /// through it. Then every layer lookup finds what a scan in table order finds (the first of a + /// name without case), and a large table looked up this often is left indexed. + fn check_layers(d: &mut Drawing, extra: &[&str]) { + let p = extra.first().copied().unwrap_or("L1"); + let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(p)).and_then(|i| d.layers.get(i)).map(std::ptr::from_ref); + assert_eq!(d.layer_mut(p).map(|l| std::ptr::from_ref(&*l)), want, "{p}"); + assert!(want.is_none() || !layers_indexed(d)); + let names: Vec = d.layers.iter().map(|l| l.name.clone()).collect(); + for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) { + let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(&p)); + assert_eq!(d.layers.position_by_name(&p), want, "{p}"); + let at = want.and_then(|i| d.layers.get(i)).map(std::ptr::from_ref); + assert_eq!(d.layer(&p).map(std::ptr::from_ref), at, "{p}"); + } + assert_eq!(layers_indexed(d), d.layers.len() >= MIN_INDEXED); + } + + /// Every block lookup finds what `Drawing::block` always found: the block of that exact name, + /// else the first in name order of that name without case. + fn check_blocks(d: &Drawing, extra: &[&str]) { + let names: Vec = d.blocks.keys().cloned().collect(); + for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) { + let want = d.blocks.get(&p).or_else(|| d.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(&p)).map(|(_, v)| v)); + assert_eq!(d.block(&p).map(std::ptr::from_ref), want.map(std::ptr::from_ref), "{p}"); + } + assert_eq!(blocks_indexed(d), d.blocks.len() >= MIN_INDEXED); + } + + #[test] + fn layer_lookups_find_the_first_of_a_name_through_every_change() { + let mut d = Drawing::new_imperial(); + d.layers = (0..200).map(|i| Layer::new(&format!("L{i}"))).chain([Layer::new("l5"), Layer::new("Doors")]).collect(); + check_layers(&mut d, &["l5", "missing"]); + + // Renamed through layer_mut (RENAME). + d.layer_mut("l7").unwrap().name = "Seven".into(); + assert!(!layers_indexed(&d)); + assert!(d.layer("L7").is_none()); + check_layers(&mut d, &["SEVEN", "L7"]); + // Added (LAYER New, or a file's later record of a name it already has). + d.layers.push(Layer::new("SEVEN")); + assert!(!layers_indexed(&d)); + check_layers(&mut d, &["seven"]); + // Removed (PURGE, LAYDEL): the later `l5` becomes the first of that name. + d.layers.retain(|l| l.name != "L5"); + assert!(!layers_indexed(&d)); + assert_eq!(d.layer("L5").map(|l| l.name.as_str()), Some("l5")); + check_layers(&mut d, &["L5"]); + // Inserted before an earlier layer of the same name. + d.layers.insert(0, Layer::new("l9")); + assert!(!layers_indexed(&d)); + assert_eq!(d.layer("L9").map(|l| l.name.as_str()), Some("l9")); + check_layers(&mut d, &["L9"]); + // Changed by position, and by a loop over all of them. + d.layers[3].name = "Third".into(); + assert!(!layers_indexed(&d)); + check_layers(&mut d, &["third"]); + for l in &mut d.layers { + l.name.make_ascii_uppercase(); + } + assert!(!layers_indexed(&d)); + check_layers(&mut d, &["doors"]); + + // Undo: a snapshot keeps the table it was taken with, and its index. + let names = |d: &Drawing| d.layers.iter().map(|l| l.name.clone()).collect::>(); + assert!(layers_indexed(&d)); + let (snap, before) = (d.clone(), names(&d)); + d.layers.clear(); + d.layers.push(Layer::new("Only")); + check_layers(&mut d, &["only", "L1"]); + d = snap; + assert!(layers_indexed(&d)); + assert_eq!(names(&d), before); + check_layers(&mut d, &["THIRD"]); + // The whole table replaced (LAYERP, LAYUNISO). + d.layers = vec![Layer::new("0"), Layer::new("A"), Layer::new("a")].into(); + check_layers(&mut d, &["a"]); + } + + #[test] + fn block_lookups_find_an_exact_name_else_the_first_without_case_through_every_change() { + let block = |name: &str| Arc::new(Block::new(name)); + let mut d = Drawing::new_imperial(); + for name in (0..100).map(|i| format!("B{i}")).chain(["Door", "DOOR", "door"].map(String::from)) { + d.blocks.insert(name.clone(), block(&name)); + } + check_blocks(&d, &["dOOR", "missing"]); + // An exact name wins; otherwise the first in name order ("DOOR" < "Door" < "door"). + assert_eq!(d.block("door").map(|b| b.name.as_str()), Some("door")); + assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DOOR")); + + // Removed (PURGE, a definition replaced under another name). + d.blocks.remove("DOOR"); + assert!(!blocks_indexed(&d)); + assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("Door")); + check_blocks(&d, &["dOOR"]); + // Added before the first of that name. + d.blocks.insert("DoOr".into(), block("DoOr")); + assert!(!blocks_indexed(&d)); + assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DoOr")); + check_blocks(&d, &["dOOR"]); + // Renamed (RENAME takes the definition out and puts it back under the new name). + let b1 = d.blocks.remove("B1").unwrap(); + d.blocks.insert("Renamed".into(), b1); + assert!(d.block("b1").is_none() && d.block("RENAMED").is_some()); + check_blocks(&d, &["b1", "RENAMED"]); + // Redefined in place, and changed through get_mut: the names stay. + d.blocks.insert("Door".into(), block("Door")); + assert!(!blocks_indexed(&d)); + check_blocks(&d, &["DOOR"]); + Arc::make_mut(d.blocks.get_mut("B2").unwrap()).description = "changed".into(); + assert!(!blocks_indexed(&d)); + check_blocks(&d, &["b2"]); + // Many removed at once. + d.blocks.retain(|k, _| !k.starts_with("B9")); + assert!(!blocks_indexed(&d)); + check_blocks(&d, &["b9", "b90"]); + // A loop over all of them. + for (_, b) in &mut d.blocks { + Arc::make_mut(b).description = "looped".into(); + } + assert!(!blocks_indexed(&d)); + check_blocks(&d, &["b3"]); + + // Undo: a snapshot keeps the table it was taken with, and its index. + let snap = d.clone(); + d.blocks.clear(); + d.blocks.insert("Only".into(), block("Only")); + check_blocks(&d, &["only", "door"]); + d = snap; + assert!(blocks_indexed(&d)); + check_blocks(&d, &["DOOR", "only"]); + } +} diff --git a/crates/doc/src/tables.rs b/crates/doc/src/tables.rs index b6b192ee9..f3fd8f6dc 100644 --- a/crates/doc/src/tables.rs +++ b/crates/doc/src/tables.rs @@ -1018,8 +1018,8 @@ impl LayerState { pub const ALL: u32 = 2047; /// A state of every property of `layers`, with `current` the layer restoring makes current. - pub fn new(name: impl Into, layers: Vec, current: impl Into) -> Self { - LayerState { name: name.into(), layers, current: current.into(), ..LayerState::default() } + pub fn new(name: impl Into, layers: impl Into>, current: impl Into) -> Self { + LayerState { name: name.into(), layers: layers.into(), current: current.into(), ..LayerState::default() } } } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 5b5bcf8c6..e40d6edec 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -890,3 +890,22 @@ fn constant_values_count_in_extents_as_attmode_shows_them() { assert!(top(1, true) < 40.0); assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one"); } + +/// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N +/// blocks and N references to blocks it does not have, opened in N² name comparisons (#1924). +#[test] +fn layer_and_block_lookups_by_name_cost_about_the_same_for_any_table_size() { + const N: usize = 40_000; + let mut d = Drawing::new_imperial(); + d.layers = (0..N).map(|i| Layer::new(&format!("L{i}"))).collect(); + for i in 0..N { + let name = format!("B{i}"); + d.blocks.insert(name.clone(), std::sync::Arc::new(Block::new(&name))); + } + let started = std::time::Instant::now(); + for i in 0..N { + assert!(d.layer(&format!("l{i}")).is_some() && d.layer(&format!("M{i}")).is_none()); + assert!(d.block(&format!("b{i}")).is_some() && d.block(&format!("Z{i}")).is_none()); + } + assert!(started.elapsed() < std::time::Duration::from_secs(5), "took {:?}", started.elapsed()); +} diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 3ddf8cf5b..58c23361a 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -265,7 +265,7 @@ fn defs_for(src: &Drawing, ents: &[Entity]) -> Drawing { } let mut d = Drawing::new_imperial(); d.header = src.header.clone(); - d.layers = pick(&src.layers, &used.layers, |l| &l.name); + d.layers = pick(&src.layers, &used.layers, |l| &l.name).into(); d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name); d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name); d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index b3bd61e0c..9bb40610b 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -297,7 +297,7 @@ fn run_layerp(s: &mut Session, _p: &Value) -> Result { let d = s.doc_mut()?; let snap = d.header.str("CADCRAFT_LAYERP", ""); let layers: Vec = serde_json::from_str(&snap).map_err(|_| bad("layerp", "No previous layer state."))?; - d.layers = layers; + d.layers = layers.into(); Ok(json!({"message": "Restored previous layer states."})) } @@ -375,7 +375,7 @@ fn run_layuniso(s: &mut Session, _p: &Value) -> Result { let d = s.doc_mut()?; let snap = d.header.str("CADCRAFT_LAYISO", ""); let layers: Vec = serde_json::from_str(&snap).map_err(|_| bad("layuniso", "No isolated layers."))?; - d.layers = layers; + d.layers = layers.into(); ok() } diff --git a/crates/engine/src/spatial.rs b/crates/engine/src/spatial.rs index f4607bed5..d15f73201 100644 --- a/crates/engine/src/spatial.rs +++ b/crates/engine/src/spatial.rs @@ -161,7 +161,7 @@ impl SpatialIndex { let infinite = chunks.iter().flat_map(|(off, c)| c.infinite.iter().map(move |i| off + i)).collect(); SpatialIndex { store: store.clone(), - blocks: d.blocks.clone(), + blocks: (*d.blocks).clone(), dim_styles: d.dim_styles.clone(), dimscale: d.header.f64("DIMSCALE", 1.0), anno: anno_key(d), diff --git a/crates/ui-egui/src/layers.rs b/crates/ui-egui/src/layers.rs index 5abc6aede..a8c1c8931 100644 --- a/crates/ui-egui/src/layers.rs +++ b/crates/ui-egui/src/layers.rs @@ -234,7 +234,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let linetypes: Vec = d.linetypes.clone(); let library: Vec = cadcraft_doc::library::standard_linetypes().into_iter().map(|l| l.name).filter(|n| d.linetype(n).is_none()).collect(); let states: Vec = d.layer_states.iter().map(|s| s.name.clone()).collect(); - let mut layers: Vec = d.layers.clone(); + let mut layers: Vec = d.layers.to_vec(); layers.sort_by_key(|l| natural_lower(&l.name)); if st.sort_desc { layers.reverse(); From 04c880e96fd357a6da72c5aba9b05ebc2b72e2c9 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:39:36 +0700 Subject: [PATCH 2/2] fix(doc): key the layer and block name index by the folded name, not a hash The index mapped a hash of the case-folded name to the first entry of that hash, and scanned the table when the entry's name differed. On wasm32-unknown-unknown, std's RandomState takes its keys from a stack and a heap address (library/std/src/sys/random/unsupported.rs), so a crafted file could pick colliding names and keep every lookup a full scan on the web build (review of #3484). The index is now a BTreeMap from the name's bytes with ASCII letters lower-cased to the first entry of that name. eq_ignore_ascii_case compares exactly those bytes, so a lookup returns what the scan returns without a fallback, and costs O(log N) comparisons whatever the names are. Short names are folded on the stack. Measured, one search costs about a scan of 100 names and a build about 100-350 scans, so tables are indexed from 128 entries and after 256 scans since their last change. A new test builds the index alone and finds the first entry of every name: case variants, names that differ after a long shared prefix, names of 64 bytes and longer, non-ASCII names and the empty name. The cost test now uses 60 000 names and a 10 s bound (166.6 s on main). Part of #1924 (F-04). Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/names.rs | 123 +++++++++++++++++++++++----------------- crates/doc/src/tests.rs | 4 +- 2 files changed, 73 insertions(+), 54 deletions(-) diff --git a/crates/doc/src/names.rs b/crates/doc/src/names.rs index a5618533b..ca19140de 100644 --- a/crates/doc/src/names.rs +++ b/crates/doc/src/names.rs @@ -1,65 +1,63 @@ -//! The layer and block tables, whose names are looked up without case in about constant time. +//! The layer and block tables, whose names are looked up without case through an index instead of a +//! scan once a table is large and looked up often. //! //! [`Drawing::layer`](crate::Drawing::layer) and [`Drawing::block`](crate::Drawing::block) run for //! every entity while a drawing is read, measured and drawn. Scanning the table on each made a file //! of N layers, or of N blocks and N references to blocks it does not have, cost N² name //! comparisons: tens of seconds to open at a few tens of thousands (#1924, F-04). //! -//! Each table keeps an index from the hash of a name with its ASCII letters lower-cased to the -//! table's first entry of that hash, so a lookup returns what a scan in table order returns. +//! Each table keeps an index from a name with its ASCII letters lower-cased to the table's first +//! entry of that name, so a lookup returns what a scan in table order returns. The index is ordered +//! by those bytes, not hashed: a lookup costs a logarithmic number of name comparisons whatever +//! the names are, also where a file could predict a hash's keys (the web build's `RandomState`). //! Every change to a table goes through `DerefMut`, which drops the index, so it can never be //! stale. The index is built only once a table has been scanned [`SCANS_BEFORE_INDEX`] times since -//! it last changed: a table changed between every few lookups costs what scanning it always did, -//! and one looked up many times in between is indexed once. +//! it last changed: a table changed between every few hundred lookups costs at most about 2.5 times +//! what scanning it always did, and one looked up many times in between is indexed once. -use std::collections::{BTreeMap, HashMap, btree_map}; -use std::hash::{BuildHasher, Hasher}; +use std::collections::{BTreeMap, btree_map}; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{Arc, OnceLock}; -/// Tables with fewer entries than this are always scanned: comparing a few names costs less than -/// hashing one. -const MIN_INDEXED: usize = 64; -/// Lookups that scan a table after it changed before its index is built. A build costs about as -/// much as some tens of scans. -const SCANS_BEFORE_INDEX: u32 = 32; +/// Tables with fewer entries than this are always scanned: a search of the index costs about what a +/// scan of 100 names does (measured), so a smaller table gains nothing from one. +const MIN_INDEXED: usize = 128; +/// Lookups that scan a table after it changed before its index is built. A build costs about 100 +/// to 350 scans (measured on tables of 100 to 40 000 names), so a table changed after every few +/// hundred lookups costs at most about 2.5 times what scanning it always did. +const SCANS_BEFORE_INDEX: u32 = 256; -/// From the hash of a name without case to the first entry, in table order, of a name with that -/// hash. The hash is keyed per index (the map's `RandomState`), so a file cannot choose names that -/// collide. -struct Index(HashMap); +/// From a name with its ASCII letters lower-cased to the first entry, in table order, of that name. +struct Index(BTreeMap, V>); impl Index { fn build<'a>(entries: impl Iterator) -> Self { - let mut map = HashMap::new(); + let mut map = BTreeMap::new(); for (name, v) in entries { - map.entry(folded_hash(map.hasher(), name)).or_insert(v); + map.entry(name.to_ascii_lowercase().into_bytes().into_boxed_slice()).or_insert(v); } Index(map) } - /// The first entry whose name hashes as `name` does: the first named `name` without case when - /// its name is that, else another name with the same hash, and the caller scans. + /// The first entry named `name`, without case. fn get(&self, name: &str) -> Option<&V> { - self.0.get(&folded_hash(self.0.hasher(), name)) + with_folded(name, |folded| self.0.get(folded)) } } -/// The hash of `name` with its ASCII letters lower-cased: names that `eq_ignore_ascii_case` finds -/// equal hash the same. -fn folded_hash(state: &impl BuildHasher, name: &str) -> u64 { - let mut h = state.build_hasher(); +/// `f` of the bytes of `name` with its ASCII letters lower-cased, which are equal for the names +/// `eq_ignore_ascii_case` finds equal. A short name is folded on the stack. +fn with_folded(name: &str, f: impl FnOnce(&[u8]) -> R) -> R { let mut buf = [0u8; 64]; - for chunk in name.as_bytes().chunks(buf.len()) { - if let Some(part) = buf.get_mut(..chunk.len()) { - part.copy_from_slice(chunk); - part.make_ascii_lowercase(); - h.write(part); + match buf.get_mut(..name.len()) { + Some(short) => { + short.copy_from_slice(name.as_bytes()); + short.make_ascii_lowercase(); + f(short) } + None => f(name.to_ascii_lowercase().as_bytes()), } - h.write_usize(name.len()); - h.finish() } /// A table's index: built on demand, shared by copies of the unchanged table (an undo snapshot), @@ -123,14 +121,9 @@ pub struct NamedList { impl NamedList { /// The position of the first entry named `name`, without case. pub fn position_by_name(&self, name: &str) -> Option { - let scan = || self.list.iter().position(|t| t.name().eq_ignore_ascii_case(name)); - let Some(ix) = self.index.get(self.list.len(), || Index::build(self.list.iter().enumerate().map(|(i, t)| (t.name(), i)))) else { - return scan(); - }; - match ix.get(name) { - None => None, - Some(&i) if self.list.get(i).is_some_and(|t| t.name().eq_ignore_ascii_case(name)) => Some(i), - Some(_) => scan(), + match self.index.get(self.list.len(), || Index::build(self.list.iter().enumerate().map(|(i, t)| (t.name(), i)))) { + Some(ix) => ix.get(name).copied(), + None => self.list.iter().position(|t| t.name().eq_ignore_ascii_case(name)), } } @@ -240,14 +233,9 @@ impl NamedMap { if let Some(v) = self.map.get(name) { return Some(v); } - let scan = || self.map.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v); - let Some(ix) = self.index.get(self.map.len(), || Index::build(self.map.keys().map(|k| (k.as_str(), Box::from(k.as_str()))))) else { - return scan(); - }; - match ix.get(name) { - None => None, - Some(k) if k.eq_ignore_ascii_case(name) => self.map.get(&**k).or_else(scan), - Some(_) => scan(), + match self.index.get(self.map.len(), || Index::build(self.map.keys().map(|k| (k.as_str(), Box::from(k.as_str()))))) { + Some(ix) => ix.get(name).and_then(|k| self.map.get(&**k)), + None => self.map.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v), } } } @@ -366,16 +354,47 @@ mod tests { } /// Every block lookup finds what `Drawing::block` always found: the block of that exact name, - /// else the first in name order of that name without case. + /// else the first in name order of that name without case. Only names that miss an exact name + /// count towards building the index, so the names are looked up twice. fn check_blocks(d: &Drawing, extra: &[&str]) { let names: Vec = d.blocks.keys().cloned().collect(); - for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) { + for p in probes(names.iter().chain(&names).map(String::as_str).chain(extra.iter().copied())) { let want = d.blocks.get(&p).or_else(|| d.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(&p)).map(|(_, v)| v)); assert_eq!(d.block(&p).map(std::ptr::from_ref), want.map(std::ptr::from_ref), "{p}"); } assert_eq!(blocks_indexed(d), d.blocks.len() >= MIN_INDEXED); } + /// The index answers by itself, with no scan to fall back on: every name finds the first entry + /// of its name without case, also names that differ only after a long shared prefix, names + /// that fill the stack buffer or are longer, and names with non-ASCII letters (which keep their + /// case). Names are compared, not hashed, so no two names can share a slot. + #[test] + fn the_index_alone_finds_the_first_entry_of_every_name() { + let long = "x".repeat(100); + let names: Vec = vec![ + "Door".into(), + "DOOR".into(), + "door2".into(), + format!("{long}A"), + format!("{long}a"), + format!("{long}B"), + format!("{}b", "P".repeat(63)), + format!("{}B", "p".repeat(63)), + "Ärea".into(), + "ärea".into(), + "ÄREA".into(), + String::new(), + ]; + let ix = super::Index::build(names.iter().enumerate().map(|(i, n)| (n.as_str(), i))); + for p in names.iter().flat_map(|n| [n.clone(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]) { + let want = names.iter().position(|n| n.eq_ignore_ascii_case(&p)); + assert_eq!(ix.get(&p).copied(), want, "{p:?}"); + } + assert_eq!(ix.get(&format!("{long}a")), Some(&3)); + assert_eq!(ix.get("ärea"), Some(&9)); + } + #[test] fn layer_lookups_find_the_first_of_a_name_through_every_change() { let mut d = Drawing::new_imperial(); @@ -431,7 +450,7 @@ mod tests { fn block_lookups_find_an_exact_name_else_the_first_without_case_through_every_change() { let block = |name: &str| Arc::new(Block::new(name)); let mut d = Drawing::new_imperial(); - for name in (0..100).map(|i| format!("B{i}")).chain(["Door", "DOOR", "door"].map(String::from)) { + for name in (0..150).map(|i| format!("B{i}")).chain(["Door", "DOOR", "door"].map(String::from)) { d.blocks.insert(name.clone(), block(&name)); } check_blocks(&d, &["dOOR", "missing"]); diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index e40d6edec..5c290fe6a 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -895,7 +895,7 @@ fn constant_values_count_in_extents_as_attmode_shows_them() { /// blocks and N references to blocks it does not have, opened in N² name comparisons (#1924). #[test] fn layer_and_block_lookups_by_name_cost_about_the_same_for_any_table_size() { - const N: usize = 40_000; + const N: usize = 60_000; let mut d = Drawing::new_imperial(); d.layers = (0..N).map(|i| Layer::new(&format!("L{i}"))).collect(); for i in 0..N { @@ -907,5 +907,5 @@ fn layer_and_block_lookups_by_name_cost_about_the_same_for_any_table_size() { assert!(d.layer(&format!("l{i}")).is_some() && d.layer(&format!("M{i}")).is_none()); assert!(d.block(&format!("b{i}")).is_some() && d.block(&format!("Z{i}")).is_none()); } - assert!(started.elapsed() < std::time::Duration::from_secs(5), "took {:?}", started.elapsed()); + assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed()); }