DXF read: fewer allocations on the per-group and per-entity paths (#1076) (#1833)

* Key the raw reader's entity map by handle, not hex text

dxf_raw::read built a HashMap<String, bool> from Handle::hex() of every
entity and probed it with the handle text of every entity record: for
the #1076 reference drawing that is 1.1 M String allocations plus
SipHash over text, and the record's handle was parsed, formatted and
parsed again. Keyed by Handle, the map is built from the entities' own
handles and probed with the handle the record's head already yields.
handle() only rejects null and absurd handles, which the lookups' users
skipped a few lines later anyway.

Reading the #1076 reference DXF: 0.34 s less of 5.85 s.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Skip the raw reader's head scan for records without 102 groups

dxf_raw::read ran head() three times per entity (its extras, the
extension-dictionary map and the per-entity handle), and each call
allocates the handle and owner text (parsed, then formatted again) even
when the record has no reactors and no extension dictionary, which is
the case for most entities of a large drawing. Both scans that only
need those two fields now first check whether the record has any 102
group at all; without one there is nothing to find.

Reading the #1076 reference DXF: 0.28 s less.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Unescape DXF text only when it holds a backslash

The ASCII parser allocated every string value twice: once in typed()
and once in unescape_unicode(), which copies its input even when there
is no \U+ or \M+ escape to resolve, after two scans for them. Half the
16.7 M groups of the #1076 reference drawing are strings, so that was
8 M needless allocation pairs. A value without a backslash cannot hold
an escape and now moves into the tag as it is. The end-of-file check
reads the value before it is pushed, as the binary parser already did,
instead of cloning the text of every record's type group.

Reading the #1076 reference DXF: tag parsing 1.22 s to 1.17 s, 0.12 s
less overall.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Size the DXF tag list from the line count

parse_with_limit already counts the file's lines to refuse an oversized
drawing before reading it; that count is the number of groups, so the
tag list is now created at that size instead of growing by doubling.
For the 16.7 M groups of the #1076 reference drawing the doubling moved
about 670 MB of tags in all and, at the last step, held the 335 MB old
list next to the 670 MB new one. The hint is capped by the tag limit
and never trusted beyond it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Size the entity list of a DXF section from its record count

parse_entities grew its list of (owner, paper, Entity) by doubling: for
the 1.1 M entities of the #1076 reference drawing that is a list of
about 700 MB moved at every doubling and, at the last one, held beside
its 350 MB predecessor. The records come from the file but are already
in memory and bounded by the tag limit, so the list is sized to their
count once; nearly every record becomes an entity.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Borrow group text in the DXF reader's per-tag scans

Tag::str() clones the value, and the reader called it in loops that run
over every group of the file or every group of a record: the handle
seed scan over every 5/105 group (1.2 M clones for the #1076 reference
drawing), the CADCRAFT_HANDSEED probe over the OBJECTS section, the
entity plot style lookup, the handle of every entity record, the record
split of every section, the AcDbEntity marker search, the xdata brace
check and the head scan's handle, owner and group names. A private
text() helper in the io crate borrows a string or hex value instead
(the dxf crate's API is left alone), and split() keeps a record's type
as a borrowed &str, as the writer's record list already can.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Bound the tag-list reservation by the text's length

The reservation came from the newline count alone, so a file of blank
lines (`0`, `EOF`, then megabytes of newlines) reserved a tag slot per
two newlines before the parser found its one group: far more than the
grow-as-needed list would ever have taken for that input. A group is two
lines of at least two bytes each, so the text's length over four bounds
what any file of that size can hold; the reservation now stops there.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Size the entity list by the records that can become entities

VERTEX, ATTRIB and SEQEND fold into the POLYLINE or INSERT before them,
so a heavy polyline file reserved a slot per vertex it never filled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Reserve the tag list fallibly, so a refused reservation grows the list instead of aborting

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Bound the entity list's reservation and make it fallible

parse_entities reserved its staging list for every record that can become
an entity, infallibly, before any record was read. The reservation now
stops at MAX_RESERVED_ENTITIES (1 << 16 entries, about 46 MiB; larger
lists grow as usual) and goes through try_reserve_exact, so a refused
reservation is a "DXF: out of memory reserving N entities" error rather
than an abort; parse_entities and read_blocks return a Result for it.
Review by FredApps on PR #1833.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
This commit is contained in:
Moritz Boelling
2026-11-28 16:14:57 +01:00
committed by GitHub
co-authored by Claude Opus 5.5 FredApps
parent fcf353c74b
commit c5770734e2
4 changed files with 136 additions and 65 deletions
+63 -50
View File
@@ -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<String> {
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<String, F
};
for (kind, _, t) in tables {
let name = up(&val(t, 2).unwrap_or_default());
if kind == "TABLE" || !name.is_empty() {
put(head(t).handle, (if kind == "TABLE" { "TABLE".into() } else { kind.clone() }, name));
if *kind == "TABLE" || !name.is_empty() {
put(head(t).handle, (if *kind == "TABLE" { "TABLE".into() } else { kind.to_string() }, name));
}
}
let mut block = String::new();
for (kind, _, t) in blocks {
match kind.as_str() {
match *kind {
"BLOCK" => {
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<String, F
}
let Some((_, _, root)) = objects.first().filter(|(k, _, _)| is_dictionary(k)) else { return out };
put(head(root).handle, ("NOD".into(), String::new()));
let by_handle: HashMap<String, (&str, &[Tag])> = objects.iter().filter_map(|(k, _, t)| Some((head(t).handle?, (k.as_str(), *t)))).rev().collect();
let by_handle: HashMap<String, (&str, &[Tag])> = 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<RawTag> {
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<RawTag> {
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<RawTag> {
/// 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<String>) -> 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<String, usize> = 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<Handle, Vec<RawTag>> = 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<String> =
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<String> {
(!value.is_empty()).then(|| value.to_string())
}
fn entity_types(drawing: &Drawing) -> HashMap<String, bool> {
fn entity_types(drawing: &Drawing) -> HashMap<Handle, bool> {
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<String, String> {
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<String, bool>,
objects: &[(&str, usize, &[Tag])],
entities: &HashMap<Handle, bool>,
records: &HashMap<String, ForeignKey>,
by_handle: &HashMap<String, usize>,
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<Rec> {
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<ObjectRecord> {
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<ForeignKey, String> = HashMap::new();
+42 -6
View File
@@ -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<Tag>| (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(())
}
}
+29 -7
View File
@@ -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<Vec<(Option<String>, 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<String>, bool, Entity)> {
let mut out = Vec::new();
) -> Result<Vec<(Option<String>, 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<String, usize>,
seen_handles: &mut HashSet<Handle>,
reserved_handles: &HashSet<Handle>,
) -> Vec<BlockDef> {
) -> Result<Vec<BlockDef>> {
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`.
+2 -2
View File
@@ -502,10 +502,10 @@ pub(super) fn entity_plot_style(tags: &[Tag], rx: &Rx) -> Option<String> {
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,
_ => {}
}