diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index a2c22d29d..ee3a26c28 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -96,15 +96,15 @@ fn is_pointer(code: i32) -> bool { } /// The records of a run of tags: (type, index of the record's `0` group, groups after it). -fn split(tags: &[Tag]) -> Vec<(String, usize, &[Tag])> { +fn split(tags: &[Tag]) -> Recs<'_> { let mut out = Vec::new(); - let mut open: Option<(String, usize)> = None; + let mut open: Option<(&str, usize)> = None; for (i, t) in tags.iter().enumerate() { if t.code == 0 { if let Some((k, s)) = open.take() { out.push((k, s, tags.get(s + 1..i).unwrap_or(&[]))); } - open = Some((t.str(), i)); + open = Some((t.str_ref().unwrap_or_default(), i)); } } if let Some((k, s)) = open { @@ -113,7 +113,7 @@ fn split(tags: &[Tag]) -> Vec<(String, usize, &[Tag])> { out } -type Recs<'a> = Vec<(String, usize, &'a [Tag])>; +type Recs<'a> = Vec<(&'a str, usize, &'a [Tag])>; /// A record's handle, owner, reactors and extension dictionary (groups before its xdata). #[derive(Default)] @@ -131,23 +131,29 @@ fn head(tags: &[Tag]) -> Head { for t in tags.iter().take_while(|t| t.code < 1000) { match (t.code, group.as_deref()) { (102, _) => { - let v = t.str(); - group = v.trim().strip_prefix('{').map(str::to_string); + group = t.str_ref().and_then(|v| v.trim().strip_prefix('{')).map(str::to_string); h.has_reactors |= group.as_deref() == Some("ACAD_REACTORS"); } - (_, Some("ACAD_REACTORS")) => h.reactors.push(norm(&t.str())), + (_, Some("ACAD_REACTORS")) => h.reactors.extend(t.str_ref().map(norm)), (_, Some("ACAD_XDICTIONARY")) if h.xdict.is_none() => { - h.xdict = Some(norm(&t.str())); + h.xdict = t.str_ref().map(norm); } (_, Some(_)) => {} - (5 | 105, None) if h.handle.is_none() => h.handle = Some(norm(&t.str())), - (330, None) if h.owner.is_none() => h.owner = Some(norm(&t.str())), + (5 | 105, None) if h.handle.is_none() => h.handle = t.str_ref().map(norm), + (330, None) if h.owner.is_none() => h.owner = t.str_ref().map(norm), _ => {} } } h } +/// Whether a record has any `102` group (reactors, an extension dictionary or an application's +/// own group). Without one [`head`] finds no reactors and no extension dictionary, so the scan +/// and its handle text are spared: most entities of a large drawing have none (#1076). +fn has_groups(tags: &[Tag]) -> bool { + tags.iter().take_while(|t| t.code < 1000).any(|t| t.code == 102) +} + fn val(tags: &[Tag], code: i32) -> Option { tags.iter().take_while(|t| t.code < 1000).find(|t| t.code == code).map(Tag::str) } @@ -190,13 +196,13 @@ fn identities(tables: &Recs, blocks: &Recs, objects: &Recs) -> HashMap { block = up(&val(t, 2).unwrap_or_default()); put(head(t).handle, ("BLOCK".into(), block.clone())); @@ -207,7 +213,7 @@ fn identities(tables: &Recs, blocks: &Recs, objects: &Recs) -> HashMap = objects.iter().filter_map(|(k, _, t)| Some((head(t).handle?, (k.as_str(), *t)))).rev().collect(); + let by_handle: HashMap = objects.iter().filter_map(|(k, _, t)| Some((head(t).handle?, (*k, *t)))).rev().collect(); for (key, h) in entries(root) { put(Some(h.clone()), ("NOD".into(), up(&key))); if let Some((k, t)) = by_handle.get(&h) @@ -232,7 +238,7 @@ fn foreign_xdata(kind: &str, tags: &[Tag]) -> Vec { let len = rest.get(i + 1..).map_or(0, |r| r.iter().position(|t| t.code == 1001).unwrap_or(r.len())); let chunk = rest.get(i..i + 1 + len).unwrap_or(&[]); i += 1 + len; - let app = up(&first.str()); + let app = first.str_ref().map(up).unwrap_or_default(); let own = OWN_APPS.contains(&app.as_str()) || (app == "ACAD" && matches!(kind, "DIMENSION" | "DIMSTYLE")); if app.is_empty() || own || out.len() + chunk.len() > MAX_XDATA_GROUPS { continue; @@ -240,10 +246,10 @@ fn foreign_xdata(kind: &str, tags: &[Tag]) -> Vec { let mut depth = 0i32; let mut ok = true; for t in chunk.iter().skip(1) { - match (t.code, t.str().trim()) { + match (t.code, t.str_ref().map(str::trim)) { (c, _) if c < 1000 => ok = false, - (1002, "{") => depth += 1, - (1002, "}") => { + (1002, Some("{")) => depth += 1, + (1002, Some("}")) => { depth -= 1; ok &= depth >= 0; } @@ -259,7 +265,7 @@ fn foreign_xdata(kind: &str, tags: &[Tag]) -> Vec { /// The groups of an entity's AcDbEntity subclass (after `100 AcDbEntity`, up to the next `100`). fn entity_groups(tags: &[Tag]) -> &[Tag] { - let Some(start) = tags.iter().position(|t| t.code == 100 && t.str().trim() == "AcDbEntity") else { return &[] }; + let Some(start) = tags.iter().position(|t| t.code == 100 && t.str_ref().is_some_and(|s| s.trim() == "AcDbEntity")) else { return &[] }; let rest = tags.get(start + 1..).unwrap_or(&[]); let end = rest.iter().position(|t| t.code == 100 || t.code >= 1000).unwrap_or(rest.len()); rest.get(..end).unwrap_or(&[]) @@ -268,7 +274,7 @@ fn entity_groups(tags: &[Tag]) -> &[Tag] { /// What an entity record (`entity`) or a table record carries beyond the model; reactors and /// the extension dictionary only when kept (`kept`). fn extra(kind: &str, tags: &[Tag], entity: bool, unknown: bool, kept: &HashSet) -> ForeignExtra { - let h = head(tags); + let h = if has_groups(tags) { head(tags) } else { Head::default() }; let mut x = ForeignExtra { xdict: h.xdict.filter(|x| kept.contains(x)).and_then(|x| handle(&x)), reactors: h.reactors.iter().filter(|r| kept.contains(*r)).filter_map(|r| handle(r)).collect(), @@ -334,7 +340,7 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { // Objects by handle: the first of each, and none that has an entity's handle. let mut by_handle: HashMap = HashMap::new(); for (i, (_, _, t)) in objects.iter().enumerate() { - if let Some(h) = head(t).handle.filter(|h| handle(h).is_some() && !ents.contains_key(h)) { + if let Some(h) = head(t).handle.filter(|h| handle(h).is_some_and(|hh| !ents.contains_key(&hh))) { by_handle.entry(h).or_insert(i); } } @@ -347,7 +353,7 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { let Some((_, _, t)) = objects.get(k) else { return false }; let hd = head(t); let (Some(h), Some(o)) = (hd.handle, hd.owner) else { return false }; - !by_handle.contains_key(&o) && xdict_of.get(&o) == Some(&h) && (ents.contains_key(&o) || ids.contains_key(&o)) + !by_handle.contains_key(&o) && xdict_of.get(&o) == Some(&h) && (handle(&o).is_some_and(|oh| ents.contains_key(&oh)) || ids.contains_key(&o)) }; let memo = retained_objects(&objects, &ents, &ids, &by_handle, root.as_deref(), &root_entries, &xdict_of); let mut f = Foreign::default(); @@ -367,18 +373,17 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { f.dictionary.push((key, h)); } kept.insert(h.hex()); - f.objects.push(ForeignObject { handle: h, kind: kind.clone(), tags }); + f.objects.push(ForeignObject { handle: h, kind: kind.to_string(), tags }); } // Extras of entities, tables, table records and blocks. let mut xdata_of: HashMap> = HashMap::new(); for (kind, _, t) in blocks.iter().chain(&entities) { - if matches!(kind.as_str(), "BLOCK" | "ENDBLK") { + if matches!(*kind, "BLOCK" | "ENDBLK") { continue; } - let Some(h) = head(t).handle else { continue }; - let Some(&unknown) = ents.get(&h) else { continue }; + let Some(hh) = head(t).handle.as_deref().and_then(handle) else { continue }; + let Some(&unknown) = ents.get(&hh) else { continue }; let mut x = extra(kind, t, true, unknown, &kept); - let Some(hh) = handle(&h) else { continue }; // Xdata belongs to the entity itself (it follows the entity's copies). let xd = std::mem::take(&mut x.xdata); if !xd.is_empty() { @@ -389,9 +394,9 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { } } put_xdata(d, xdata_of); - for (kind, _, t) in tables.iter().chain(blocks.iter().filter(|(k, _, _)| k == "BLOCK")) { + for (kind, _, t) in tables.iter().chain(blocks.iter().filter(|(k, _, _)| *k == "BLOCK")) { let Some(key) = head(t).handle.and_then(|h| ids.get(&h).cloned()) else { continue }; - let x = extra(kind, t, kind == "BLOCK", false, &kept); + let x = extra(kind, t, *kind == "BLOCK", false, &kept); if !x.is_empty() { f.records.entry(key).or_insert(x); } @@ -405,7 +410,7 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { // A proxy's class is the one its group 91 numbers in the file's CLASSES: keep it too, and the // file's class order, by which saving renumbers the proxy. let class_order: Vec = - classes.iter().filter(|(k, _, _)| k == "CLASS").take(MAX_OBJECTS).map(|(_, _, t)| up(&val(t, 1).unwrap_or_default())).collect(); + classes.iter().filter(|(k, _, _)| *k == "CLASS").take(MAX_OBJECTS).map(|(_, _, t)| up(&val(t, 1).unwrap_or_default())).collect(); let mut proxies = false; let proxy_tags = f.objects.iter().filter(|o| is_proxy(&o.kind)).map(|o| &o.tags); let proxy_tags = proxy_tags.chain(all_entities(d).filter_map(|e| match &e.kind { @@ -419,11 +424,11 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { } } if proxies { - f.complete_class_table = classes.iter().filter(|(k, _, _)| k == "CLASS").count() <= MAX_OBJECTS; + f.complete_class_table = classes.iter().filter(|(k, _, _)| *k == "CLASS").count() <= MAX_OBJECTS; f.class_order = class_order; } for (kind, _, t) in &classes { - if kind == "CLASS" && (f.complete_class_table || val(t, 1).is_some_and(|n| types.contains(&up(&n)))) && f.classes.len() < MAX_OBJECTS { + if *kind == "CLASS" && (f.complete_class_table || val(t, 1).is_some_and(|n| types.contains(&up(&n)))) && f.classes.len() < MAX_OBJECTS { f.classes.push(t.iter().map(raw).collect()); } } @@ -459,10 +464,16 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { } // Added after the version: registered applications alone are no kept objects whose groups // the DWG writer must read as the file's version, and nearly every file has some (ACAD). - let appids = tables.iter().filter(|(k, _, _)| k == "APPID").filter_map(|(_, _, t)| val(t, 2)).map(|n| n.trim().to_string()); + let appids = tables.iter().filter(|(k, _, _)| *k == "APPID").filter_map(|(_, _, t)| val(t, 2)).map(|n| n.trim().to_string()); f.appids = appids.take(MAX_OBJECTS).collect(); // The file's handles of the objects CADCraft writes itself (AutoLISP's `handent`). - f.handles = ids.iter().filter(|(h, _)| !ents.contains_key(*h)).filter_map(|(h, k)| Some((handle(h)?, k.clone()))).take(MAX_OBJECTS).collect(); + f.handles = ids + .iter() + .filter_map(|(h, k)| Some((handle(h)?, k))) + .filter(|(h, _)| !ents.contains_key(h)) + .map(|(h, k)| (h, k.clone())) + .take(MAX_OBJECTS) + .collect(); if !f.is_empty() || !f.handles.is_empty() { d.foreign = Arc::new(f); } @@ -478,22 +489,22 @@ fn file_version(secs: &[SectionRef<'_>]) -> Option { (!value.is_empty()).then(|| value.to_string()) } -fn entity_types(drawing: &Drawing) -> HashMap { +fn entity_types(drawing: &Drawing) -> HashMap { let mut types = HashMap::new(); for entity in all_entities(drawing) { - types.entry(entity.handle.hex()).or_insert(matches!(entity.kind, EntityKind::Unknown(_))); + types.entry(entity.handle).or_insert(matches!(entity.kind, EntityKind::Unknown(_))); } types } fn extension_dictionaries( - tables: &[(String, usize, &[Tag])], - blocks: &[(String, usize, &[Tag])], - entities: &[(String, usize, &[Tag])], + tables: &[(&str, usize, &[Tag])], + blocks: &[(&str, usize, &[Tag])], + entities: &[(&str, usize, &[Tag])], ) -> HashMap { let mut dictionaries = HashMap::new(); for (kind, _, tags) in tables.iter().chain(blocks).chain(entities) { - if kind == "ENDBLK" { + if *kind == "ENDBLK" || !has_groups(tags) { continue; } let header = head(tags); @@ -516,8 +527,8 @@ fn root_key_index(root_entries: &[(String, String)]) -> HashMap<&str, &str> { /// Determine which objects belong to unmodelled dictionary entries or owners. fn retained_objects( - objects: &[(String, usize, &[Tag])], - entities: &HashMap, + objects: &[(&str, usize, &[Tag])], + entities: &HashMap, records: &HashMap, by_handle: &HashMap, root: Option<&str>, @@ -530,7 +541,9 @@ fn retained_objects( let Some((_, _, tags)) = objects.get(index) else { return false }; let header = head(tags); let (Some(handle), Some(owner)) = (header.handle, header.owner) else { return false }; - !by_handle.contains_key(&owner) && xdict_of.get(&owner) == Some(&handle) && (entities.contains_key(&owner) || records.contains_key(&owner)) + !by_handle.contains_key(&owner) + && xdict_of.get(&owner) == Some(&handle) + && (self::handle(&owner).is_some_and(|owner| entities.contains_key(&owner)) || records.contains_key(&owner)) }; let modelled_entry = |tags: &[Tag], handle: &str| { entries(tags).iter().any(|(key, entry_handle)| entry_handle == handle && MODELLED_XDICT_KEYS.contains(&up(key).as_str())) @@ -578,7 +591,7 @@ fn retained_objects( if is_xdict(current) { break entries(tags).iter().any(|(key, _)| !MODELLED_XDICT_KEYS.contains(&up(key).as_str())); } - break entities.get(&owner) == Some(&true); + break self::handle(&owner).and_then(|owner| entities.get(&owner)) == Some(&true); }; for visited in path { retained.insert(visited, keep); @@ -868,7 +881,7 @@ fn written_records(tags: &[Tag]) -> Vec { if kind == "SECTION" { sec = body.iter().find(|t| t.code == 2).map(Tag::str).unwrap_or_default(); } - out.push(Rec { sec: sec.clone(), kind, start, end: start + 1 + body.len() }); + out.push(Rec { sec: sec.clone(), kind: kind.to_string(), start, end: start + 1 + body.len() }); if out.last().is_some_and(|r| r.kind == "ENDSEC") { sec.clear(); } @@ -890,16 +903,16 @@ pub fn object_records(d: &Drawing) -> Vec { let recs = written_records(&tags); let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]); let by_sec = |name: &str| -> Recs { - recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.clone(), r.start, body(r))).collect() + recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.as_str(), r.start, body(r))).collect() }; let (tables, blocks, objects) = (by_sec("TABLES"), by_sec("BLOCKS"), by_sec("OBJECTS")); let ids = identities(&tables, &blocks, &objects); - let tables = tables.iter().filter(|(k, _, _)| k != "ENDTAB"); - let blocks = blocks.iter().filter(|(k, _, _)| k == "BLOCK"); + let tables = tables.iter().filter(|(k, _, _)| *k != "ENDTAB"); + let blocks = blocks.iter().filter(|(k, _, _)| *k == "BLOCK"); tables .chain(blocks) .chain(objects.iter()) - .map(|(kind, _, t)| (kind.clone(), t.to_vec(), head(t).handle.and_then(|h| ids.get(&h).cloned()))) + .map(|(kind, _, t)| (kind.to_string(), t.to_vec(), head(t).handle.and_then(|h| ids.get(&h).cloned()))) .collect() } @@ -1178,7 +1191,7 @@ pub(crate) fn finish( let recs = written_records(tags); let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]); let by_sec = |name: &str| -> Recs { - recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.clone(), r.start, body(r))).collect() + recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.as_str(), r.start, body(r))).collect() }; let (tables, blocks, objects) = (by_sec("TABLES"), by_sec("BLOCKS"), by_sec("OBJECTS")); let mut roles: HashMap = HashMap::new(); diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index a892f5b35..5c9cf1ec1 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -197,7 +197,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) .iter() .filter(|s| s.name == "ENTITIES") .flat_map(|s| record_slices(s.tags)) - .filter_map(|(_, tags)| common::T(tags).s(5).and_then(|h| Handle::parse_hex(&h))) + .filter_map(|(_, tags)| tags.iter().find(|t| t.code == 5).and_then(Tag::str_ref).and_then(Handle::parse_hex)) .collect(); let mut objs = Objects::default(); // Every handle another program's file already uses is taken before anything gets a new one: @@ -207,7 +207,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) // (#495), so for it only the entity records are reserved. Handles in the reserved band are // reserved for allocation rather than followed (#913): a handle-less entity read before the // section that names one is placed would otherwise be given it and replace the record (#1276). - let ours = secs.iter().any(|s| s.name == "OBJECTS" && s.tags.iter().any(|t| t.code == 3 && t.str() == crate::dxf_ext::HANDSEED_KEY)); + let ours = secs.iter().any(|s| s.name == "OBJECTS" && s.tags.iter().any(|t| t.code == 3 && t.str_ref() == Some(crate::dxf_ext::HANDSEED_KEY))); if ours { // Its table and object records are numbered above its seed and rebuilt on save (#495), // so only its entities are reserved. Reading is section by section: an entity that has @@ -218,7 +218,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) if matches!(kind.as_str(), "BLOCK" | "ENDBLK") { continue; } - if let Some(h) = tags.iter().find(|t| t.code == 5).and_then(|t| Handle::parse_hex(t.str().trim())) { + if let Some(h) = tags.iter().find(|t| t.code == 5).and_then(Tag::str_ref).and_then(Handle::parse_hex) { d.bump_handseed(h); d.reserve_handle(h); } @@ -227,7 +227,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) for s in &secs { let entity_section = s.name == "BLOCKS" || s.name == "ENTITIES"; for t in s.tags.iter().filter(|t| t.code == 5 || t.code == 105) { - if let Some(h) = Handle::parse_hex(t.str().trim()) { + if let Some(h) = t.str_ref().and_then(Handle::parse_hex) { d.bump_handseed(h); if entity_section { d.reserve_handle(h); @@ -243,7 +243,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) "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, &mut seen_handles, &reserved_entity_handles)) + 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" => { @@ -255,7 +255,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) &mut n, &mut table_cells_left, &mut HandlePolicy { seen: &mut seen_handles, reserved: &reserved_entity_handles, source_wins: true }, - )); + )?); count_skipped(&mut skipped, "ENTITIES", n); } "OBJECTS" => read_objects(s.tags, &mut objs, &mut layout_objs), @@ -454,3 +454,39 @@ mod hatch_budget_tests { assert!(matches!(d.read_notes.as_slice(), [note] if note.contains("2 hatches")), "{:?}", d.read_notes); } } + +#[cfg(test)] +mod entity_list_tests { + use super::*; + /// Vertices, attributes and SEQEND fold into the record before them, so they reserve no slots. + #[test] + fn follower_records_reserve_no_entity_slots() -> Result<()> { + let rec = |kind: &str, tags: Vec| (kind.to_string(), tags); + let mut recs = vec![rec("POLYLINE", vec![Tag::s(8, "0"), Tag::i(66, 1)])]; + for x in 0..200 { + recs.push(rec("VERTEX", vec![Tag::s(8, "0"), Tag::f(10, f64::from(x)), Tag::f(20, 0.0)])); + } + recs.push(rec("SEQEND", vec![Tag::s(8, "0")])); + recs.push(rec("LINE", vec![Tag::s(8, "0"), Tag::f(11, 1.0)])); + let recs: Vec<(String, &[Tag])> = recs.iter().map(|(kind, tags)| (kind.clone(), tags.as_slice())).collect(); + let mut d = Drawing::new_imperial(); + let (mut rx, mut skipped, mut cells) = (Rx::default(), 0, 100); + let (mut seen, reserved) = (HashSet::new(), HashSet::new()); + let mut hp = HandlePolicy { seen: &mut seen, reserved: &reserved, source_wins: true }; + let out = parse_entities(&recs, &mut d, &mut rx, &mut skipped, &mut cells, &mut hp)?; + assert_eq!(out.len(), 2, "the polyline and the line"); + assert!(out.capacity() < 10, "capacity {}", out.capacity()); + Ok(()) + } + + /// The reservation stops at its cap, and one that can't be had is an error, not an abort. + #[test] + fn entity_list_reservation_is_capped_and_fallible() -> Result<()> { + use document::entity_list; + assert_eq!(entity_list(100, 8)?.capacity(), 8); + assert_eq!(entity_list(5, 8)?.capacity(), 5); + assert_eq!(entity_list(0, 8)?.capacity(), 0); + assert!(matches!(entity_list(usize::MAX / 2, usize::MAX), Err(IoError::Format(m)) if m.contains("out of memory"))); + Ok(()) + } +} diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index 3bafa85bc..86af57150 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -4,6 +4,7 @@ use super::common::T; use super::entities::{entity_extras, entity_plot_style, entity_with_table_budget, insert_attribs, polyline_entity, reference_left_tilted}; use super::objects::{MAX_OBJECTS, Objects, page_setup}; use super::{Block, BlockDef, Drawing, Entity, EntityKind, Handle, HashMap, Layout, LayoutDef, Rx, Tag, Vec2, record_slices}; +use crate::{IoError, Result}; /// Allocate an entity handle that is unique within the DXF, including against handles assigned /// to earlier malformed or generated entities. @@ -45,6 +46,22 @@ pub(super) struct HandlePolicy<'a> { pub source_wins: bool, } +/// Most entities an entity list reserves room for before its records are read. The record count +/// is bounded by the tag limit, but a file of tiny records could still ask for gigabytes (an +/// entry takes several hundred bytes) before any record is admitted. Drawings of up to this many +/// entities are sized in one step; larger ones grow as usual. At the cap the reservation is +/// about 46 MiB (728 bytes an entry on 64-bit targets). +pub(super) const MAX_RESERVED_ENTITIES: usize = 1 << 16; + +/// An empty entity list with room for `records` entities, or `cap` if that is fewer. A refused +/// reservation is an error rather than an abort. +pub(super) fn entity_list(records: usize, cap: usize) -> Result, bool, Entity)>> { + let mut out = Vec::new(); + let n = records.min(cap); + out.try_reserve_exact(n).map_err(|_| IoError::Format(format!("DXF: out of memory reserving {n} entities")))?; + Ok(out) +} + pub(super) fn parse_entities( recs: &[(String, &[Tag])], d: &mut Drawing, @@ -52,14 +69,19 @@ pub(super) fn parse_entities( skipped: &mut usize, table_cells_left: &mut usize, hp: &mut HandlePolicy<'_>, -) -> Vec<(Option, bool, Entity)> { - let mut out = Vec::new(); +) -> Result, bool, Entity)>> { + // Every record but a polyline's vertices, a reference's attributes and their SEQEND becomes + // at most one entity (`recs` is already in memory, bounded by the tag limit), so the list is + // sized once rather than moved at every doubling, up to MAX_RESERVED_ENTITIES; past that, and + // for mesh faces past the count, it grows as usual. + let mut out = + entity_list(recs.iter().filter(|(kind, _)| !matches!(kind.as_str(), "VERTEX" | "ATTRIB" | "SEQEND")).count(), MAX_RESERVED_ENTITIES)?; let mut i = 0; while let Some((kind, tags)) = recs.get(i) { let t = T(tags); let owner = crate::dxf_ext::owner(tags); let paper = t.i(67) == Some(1); - let handle = t.s(5).and_then(|h| Handle::parse_hex(&h)); + let handle = tags.iter().find(|t| t.code == 5).and_then(Tag::str_ref).and_then(Handle::parse_hex); if kind == "VIEWPORT" && crate::dxf_ext::is_paper_view(tags) { rx.paper_views_dropped.push((owner.clone(), paper, rx.block.clone())); } @@ -122,7 +144,7 @@ pub(super) fn parse_entities( *skipped = skipped.saturating_add(1); } } - out + Ok(out) } /// Read the BLOCKS section: the xref paths of external blocks, then each block's entities. @@ -134,7 +156,7 @@ pub(super) fn read_blocks( skipped: &mut std::collections::BTreeMap, seen_handles: &mut HashSet, reserved_handles: &HashSet, -) -> Vec { +) -> Result> { let recs = record_slices(tags); for (k, tg) in &recs { let t = T(tg); @@ -166,7 +188,7 @@ pub(super) fn read_blocks( &mut n, table_cells_left, &mut HandlePolicy { seen: seen_handles, reserved: reserved_handles, source_wins: false }, - ); + )?; rx.block = None; blocks.push((name, base, description, ents, xref)); i = j + 1; @@ -179,7 +201,7 @@ pub(super) fn read_blocks( } } count_skipped(skipped, "BLOCKS", n); - blocks + Ok(blocks) } /// Read the OBJECTS section into `objs`, and each LAYOUT into `layout_objs`. diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 3f2b427ac..2900eb7d2 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -502,10 +502,10 @@ pub(super) fn entity_plot_style(tags: &[Tag], rx: &Rx) -> Option { if in_entity { break; } - in_entity = t.str() == "AcDbEntity"; + in_entity = t.str_ref() == Some("AcDbEntity"); } else if in_entity { match t.code { - 390 => return rx.pstyles.get(&t.str().trim().to_ascii_uppercase()).cloned(), + 390 => return rx.pstyles.get(&t.str_ref().unwrap_or_default().trim().to_ascii_uppercase()).cloned(), 380 => by_block = t.i64() == 1, _ => {} }