From 44f026833cd7d435fd79ecd50a3e379d94430a34 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Sun, 1 Nov 2026 05:19:01 +0300 Subject: [PATCH] io: a handle repeated across ENTITIES sections keeps both entities --- crates/io/src/dxf_read.rs | 29 +++++++- crates/io/src/dxf_read/document.rs | 64 +++++++++++++---- crates/io/tests/it/exhausted_handseed.rs | 57 +++++++++++++++ crates/io/tests/it/main.rs | 1 + crates/io/tests/it/split_entities_section.rs | 76 +++++++++++++++++++- 5 files changed, 210 insertions(+), 17 deletions(-) create mode 100644 crates/io/tests/it/exhausted_handseed.rs diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 1489f4def..ffdc19795 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -1,6 +1,6 @@ //! DXF → Drawing. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use cadcraft_color::{Color, Rgb}; use cadcraft_doc::{ @@ -90,6 +90,18 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { let mut blocks: Vec = Vec::new(); let mut layout_objs: Vec = Vec::new(); let mut entities = Vec::new(); + // One set for every list: a generated handle must be unique across blocks and ENTITIES + // (a *MODEL_SPACE block and an ENTITIES record both land in the model space). + let mut seen_handles = HashSet::new(); + // Model/paper-space handles retain priority if an in-memory drawing or damaged DXF also + // assigns one to a block entity. This preserves top-level references while letting block + // handles be repaired before their deferred fixups are recorded. + let reserved_entity_handles: HashSet = secs + .iter() + .filter(|s| s.name == "ENTITIES") + .flat_map(|s| records(&s.tags)) + .filter_map(|(_, tags)| common::T(&tags).s(5).and_then(|h| Handle::parse_hex(&h))) + .collect(); let mut objs = Objects::default(); // Every handle another program's file already uses is taken before anything gets a new one: // its $HANDSEED can be lower than its handles, and entities made while reading (the faces of @@ -108,11 +120,22 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { match s.name.as_str() { "HEADER" => header(&s.tags, &mut d), "TABLES" => tables(&s.tags, &mut d, &mut rx), - "BLOCKS" => blocks.extend(read_blocks(&s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped)), + "BLOCKS" => { + blocks.extend(read_blocks(&s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped, &mut seen_handles, &reserved_entity_handles)) + } // A damaged file may split its entities over several ENTITIES sections (#865). "ENTITIES" => { let mut n = 0; - entities.extend(parse_entities(&records(&s.tags), &mut d, &mut rx, &mut n, &mut table_cells_left)); + entities.extend(parse_entities( + &records(&s.tags), + &mut d, + &mut rx, + &mut n, + &mut table_cells_left, + &mut seen_handles, + &reserved_entity_handles, + true, + )); count_skipped(&mut skipped, "ENTITIES", n); } "OBJECTS" => read_objects(&s.tags, &mut objs, &mut layout_objs), diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index d732f4450..096148515 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -1,14 +1,51 @@ +use std::collections::HashSet; + use super::common::T; use super::entities::{entity_extras, entity_plot_style, entity_with_table_budget, insert_attribs, polyline_entity}; use super::objects::{MAX_OBJECTS, Objects, page_setup}; use super::{Block, BlockDef, Drawing, Entity, EntityKind, Handle, HashMap, Layout, LayoutDef, Rx, Tag, records}; +/// Allocate an entity handle that is unique within the DXF, including against handles assigned +/// to earlier malformed or generated entities. +fn fresh_entity_handle(d: &mut Drawing, seen: &mut HashSet, reserved: &HashSet) -> Handle { + // The seed saturates at `u64::MAX`: once a file uses that handle, `new_handle` keeps + // returning it and a plain retry loop would never terminate. Stop as soon as it stops + // advancing. + let mut previous = None; + loop { + let h = d.new_handle(); + if !reserved.contains(&h) && seen.insert(h) { + return h; + } + if previous == Some(h) { + break; + } + previous = Some(h); + } + // Every value the seed can still reach is taken, so scan from the bottom: the occupied set + // is finite, which guarantees a free handle within its size plus one candidates. + let limit = seen.len().saturating_add(reserved.len()).saturating_add(1); + let mut candidate = 1u64; + for _ in 0..limit { + let h = Handle(candidate); + if !reserved.contains(&h) && seen.insert(h) { + return h; + } + candidate = candidate.saturating_add(1); + } + // Unreachable in practice (pigeonhole over the finite occupied set); never lose the entity. + d.new_handle() +} + pub(super) fn parse_entities( recs: &[(String, Vec)], d: &mut Drawing, rx: &mut Rx, skipped: &mut usize, table_cells_left: &mut usize, + seen_handles: &mut HashSet, + reserved_handles: &HashSet, + source_handles_win: bool, ) -> Vec<(Option, bool, Entity)> { let mut out = Vec::new(); let mut i = 0; @@ -54,13 +91,20 @@ pub(super) fn parse_entities( let h = match handle { Some(h) => { d.bump_handseed(h); - h + // A file's own handle wins when it is the first copy on a source list that + // keeps them (ENTITIES); block copies yield to the reserved top-level ones. + let kept = if source_handles_win { seen_handles.insert(h) } else { !reserved_handles.contains(&h) && seen_handles.insert(h) }; + if kept { h } else { fresh_entity_handle(d, seen_handles, reserved_handles) } } - None => d.new_handle(), + None => fresh_entity_handle(d, seen_handles, reserved_handles), }; entity_extras(kind, tags, h, &mut k, rx); - let more: Vec<_> = - extra.into_iter().map(|f| (owner.clone(), paper, Entity { handle: d.new_handle(), common: c.clone(), kind: f })).collect(); + let more: Vec<_> = extra + .into_iter() + .map(|f| { + (owner.clone(), paper, Entity { handle: fresh_entity_handle(d, seen_handles, reserved_handles), common: c.clone(), kind: f }) + }) + .collect(); out.push((owner, paper, Entity { handle: h, common: c, kind: k })); out.extend(more); } else if kind == "HATCH" { @@ -69,14 +113,6 @@ pub(super) fn parse_entities( *skipped = skipped.saturating_add(1); } } - // Assign fresh handles to duplicates (hostile files). - let mut seen = std::collections::HashSet::new(); - for (_, _, e) in &mut out { - if !seen.insert(e.handle) { - e.handle = d.new_handle(); - seen.insert(e.handle); - } - } out } @@ -87,6 +123,8 @@ pub(super) fn read_blocks( rx: &mut Rx, table_cells_left: &mut usize, skipped: &mut std::collections::BTreeMap, + seen_handles: &mut HashSet, + reserved_handles: &HashSet, ) -> Vec { let recs = records(tags); for (k, tg) in &recs { @@ -111,7 +149,7 @@ pub(super) fn read_blocks( j += 1; } let body = recs.get(i + 1..j).unwrap_or(&[]); - let ents = parse_entities(body, d, rx, &mut n, table_cells_left); + let ents = parse_entities(body, d, rx, &mut n, table_cells_left, seen_handles, reserved_handles, false); blocks.push((name, base, description, ents, xref)); i = j + 1; } else { diff --git a/crates/io/tests/it/exhausted_handseed.rs b/crates/io/tests/it/exhausted_handseed.rs new file mode 100644 index 000000000..448eed024 --- /dev/null +++ b/crates/io/tests/it/exhausted_handseed.rs @@ -0,0 +1,57 @@ +//! A file whose `$HANDSEED` is the top of the handle range must not hang the importer: the seed +//! saturates at `u64::MAX`, so allocating past a taken handle has to stop and fall back to a free +//! one instead of retrying the same handle forever. + +use std::collections::HashSet; + +use cadcraft_doc::Handle; + +/// One line holding the top handle, and one line with no handle at all, so the importer has to +/// allocate one after the seed is exhausted. +fn dxf() -> String { + "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\nFFFFFFFFFFFFFFFF\n0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n\ + 0\nLINE\n5\nFFFFFFFFFFFFFFFF\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n1.0\n31\n0.0\n\ + 0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n2.0\n21\n2.0\n31\n0.0\n\ + 0\nENDSEC\n0\nEOF\n" + .to_string() +} + +#[test] +fn an_exhausted_handle_seed_still_finds_a_free_handle() { + let d = cadcraft_io::read_dxf(dxf().as_bytes()).unwrap(); + assert_eq!(d.model.iter().count(), 2); + let handles: Vec = d.model.iter().map(|e| e.handle).collect(); + let unique: HashSet = handles.iter().copied().collect(); + assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}"); + // The file's own top handle stays with its entity. + assert!(handles.contains(&Handle(u64::MAX))); +} + +/// A `*MODEL_SPACE` block entity with no handle, a handleless `ENTITIES` record, and a later +/// `ENTITIES` record declaring handle 1: the two generated handles must differ (both lists land +/// in the model space) and must not take the handle the later record declares. +fn dxf_with_model_space_block() -> String { + "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\nFFFFFFFFFFFFFFFF\n0\nENDSEC\n\ + 0\nSECTION\n2\nBLOCKS\n\ + 0\nBLOCK\n5\n20\n8\n0\n2\n*MODEL_SPACE\n70\n0\n10\n0.0\n20\n0.0\n30\n0.0\n\ + 0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n1.0\n31\n0.0\n\ + 0\nENDBLK\n5\n21\n8\n0\n\ + 0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n\ + 0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n2.0\n21\n2.0\n31\n0.0\n\ + 0\nLINE\n5\n1\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n3.0\n21\n3.0\n31\n0.0\n\ + 0\nENDSEC\n0\nEOF\n" + .to_string() +} + +#[test] +fn generated_handles_are_unique_across_lists_and_avoid_later_source_handles() { + let d = cadcraft_io::read_dxf(dxf_with_model_space_block().as_bytes()).unwrap(); + let handles: Vec = d.model.iter().map(|e| e.handle).collect(); + assert_eq!(handles.len(), 3, "{handles:?}"); + let unique: HashSet = handles.iter().copied().collect(); + assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}"); + // The record that declares handle 1 keeps it; the generated ones went elsewhere. + assert!(handles.contains(&Handle(1)), "{handles:?}"); +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 52f37068a..5755ea9b0 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -26,6 +26,7 @@ mod dwt_template; mod dxf_versions; mod dynblock_read; mod entity_props_roundtrip; +mod exhausted_handseed; mod followups_626; mod groups_roundtrip; mod hatch_assoc_roundtrip; diff --git a/crates/io/tests/it/split_entities_section.rs b/crates/io/tests/it/split_entities_section.rs index 6d89725a3..0ab6f63e9 100644 --- a/crates/io/tests/it/split_entities_section.rs +++ b/crates/io/tests/it/split_entities_section.rs @@ -2,7 +2,7 @@ //! variables and ENDSECs between them, and no EOF). Every section is read, not just the last //! one (#865). -use cadcraft_doc::EntityKind; +use cadcraft_doc::{EntityKind, Handle}; #[test] fn entities_of_every_entities_section_are_read() { @@ -17,3 +17,77 @@ fn entities_of_every_entities_section_are_read() { let texts = d.model.iter().filter(|e| matches!(e.kind, EntityKind::Text(_))).count(); assert_eq!((lines, texts, d.model.len()), (2, 1, 3)); } + +#[test] +fn repeated_handles_across_entities_sections_keep_both_entities() { + // A damaged file can repeat a handle across its sections (within one section duplicates are + // already renumbered). The store replaces an entity with the same handle, so the earlier + // section's line was silently lost — and a save kept only the later one (#939). + let text = "0\nSECTION\n2\nENTITIES\n\ + 0\nLINE\n5\n300\n8\n0\n10\n0\n20\n0\n11\n1\n21\n0\n\ + 0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n300\n8\n0\n10\n0\n20\n1\n11\n1\n21\n1\n0\nENDSEC\n\ + 0\nEOF\n"; + let d = cadcraft_io::read(text.as_bytes(), "t.dxf").unwrap(); + let lines = d.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(); + assert_eq!(lines, 2, "the second section's line replaced the first"); + let handles: Vec = d.model.iter().map(|e| e.handle).collect(); + let unique: std::collections::HashSet = handles.iter().copied().collect(); + assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}"); + assert!(d.entity(Handle::parse_hex("300").unwrap()).is_some(), "the file's own handle stays with one of them"); +} + +#[test] +fn duplicate_mleader_handles_keep_each_deferred_style_fixup() { + let mleader = |style: &str| format!("0\nMULTILEADER\n5\n300\n100\nAcDbEntity\n8\n0\n100\nAcDbMLeader\n340\n{style}\n"); + let text = format!( + "0\nSECTION\n2\nOBJECTS\n\ + 0\nDICTIONARY\n5\nD\n3\nACAD_MLEADERSTYLE\n350\nE\n\ + 0\nDICTIONARY\n5\nE\n3\nFirst\n350\nA\n3\nSecond\n350\nB\n3\nThird\n350\nC\n\ + 0\nMLEADERSTYLE\n5\nA\n0\nMLEADERSTYLE\n5\nB\n0\nMLEADERSTYLE\n5\nC\n0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n{}{}0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n{}0\nENDSEC\n0\nEOF\n", + mleader("A"), + mleader("B"), + mleader("C"), + ); + let d = cadcraft_io::read(text.as_bytes(), "t.dxf").unwrap(); + let mut handles_by_style = std::collections::HashMap::new(); + for e in d.model.iter() { + if let EntityKind::MLeader(m) = &e.kind { + assert!(handles_by_style.insert(m.style.as_str(), e.handle).is_none(), "duplicate style {}", m.style); + } + } + assert_eq!(handles_by_style.len(), 3, "styles were assigned to the wrong records: {handles_by_style:?}"); + assert_eq!(handles_by_style.get("First"), Some(&Handle::parse_hex("300").unwrap())); + assert_ne!(handles_by_style.get("First"), handles_by_style.get("Second")); + assert_ne!(handles_by_style.get("Second"), handles_by_style.get("Third")); +} + +#[test] +fn duplicate_table_handles_keep_each_deferred_style_fixup() { + let table = |style: &str| format!("0\nACAD_TABLE\n5\n400\n100\nAcDbEntity\n8\n0\n100\nAcDbTable\n91\n1\n92\n1\n141\n1\n142\n1\n342\n{style}\n"); + let text = format!( + "0\nSECTION\n2\nOBJECTS\n\ + 0\nDICTIONARY\n5\nD\n3\nACAD_TABLESTYLE\n350\nE\n\ + 0\nDICTIONARY\n5\nE\n3\nFirst\n350\nA\n3\nSecond\n350\nB\n\ + 0\nTABLESTYLE\n5\nA\n100\nAcDbTableStyle\n70\n0\n280\n0\n281\n0\n7\nStandard\n140\n0.45\n\ + 0\nTABLESTYLE\n5\nB\n100\nAcDbTableStyle\n70\n0\n280\n0\n281\n0\n7\nStandard\n140\n0.85\n0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n{}{}0\nENDSEC\n0\nEOF\n", + table("A"), + table("B"), + ); + let d = cadcraft_io::read(text.as_bytes(), "t.dxf").unwrap(); + let tables: Vec<_> = d + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Table(t) => Some((e.handle, t)), + _ => None, + }) + .collect(); + assert_eq!(tables.len(), 2); + assert_eq!((tables[0].1.style.as_str(), tables[0].1.text_height), ("First", 0.45)); + assert_eq!((tables[1].1.style.as_str(), tables[1].1.text_height), ("Second", 0.85)); + assert_ne!(tables[0].0, tables[1].0); +}