Skip to content
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
480dc00
Key the raw reader's entity map by handle, not hex text
mbolling Oct 21, 2026
0e10f47
Skip the raw reader's head scan for records without 102 groups
mbolling Oct 21, 2026
dd115c1
Unescape DXF text only when it holds a backslash
mbolling Oct 21, 2026
a50debd
Size the DXF tag list from the line count
mbolling Oct 21, 2026
3b9a43d
Size the entity list of a DXF section from its record count
mbolling Oct 21, 2026
02a2ea4
Borrow group text in the DXF reader's per-tag scans
mbolling Oct 21, 2026
82f7af0
Bound the tag-list reservation by the text's length
mbolling Oct 21, 2026
1cb9dcf
Merge main: entity list reserved beside the table-cell budget; class …
mbolling Oct 24, 2026
1ac345f
Merge main: re-apply the borrowed reads and the reserved entity list …
mbolling Oct 27, 2026
4f6c1a8
Size the entity list by the records that can become entities
mbolling Oct 27, 2026
4d47698
Merge remote-tracking branch 'origin/main' into dxf-read-allocs
mbolling Oct 27, 2026
ec70c89
Merge remote-tracking branch 'origin/main' into dxf-read-allocs
mbolling Oct 30, 2026
cbdc97c
Reserve the tag list fallibly, so a refused reservation grows the lis…
mbolling Nov 1, 2026
a0cf1ef
Merge remote-tracking branch 'origin/main' into dxf-read-allocs
mbolling Nov 1, 2026
4d04da4
Merge remote-tracking branch 'origin/main' into dxf-read-allocs
mbolling Nov 3, 2026
acc375a
Merge remote-tracking branch 'origin/main' into dxf-read-allocs
mbolling Nov 9, 2026
2d69621
Merge remote-tracking branch 'origin/main' into dxf-read-allocs
mbolling Nov 12, 2026
bd7b2d6
Merge remote-tracking branch 'origin/main' into dxf-read-allocs
mbolling Nov 21, 2026
150ea93
Merge remote-tracking branch 'origin/main' into dxf-read-allocs
mbolling Nov 21, 2026
1666ad0
Bound the entity list's reservation and make it fallible
mbolling Nov 21, 2026
0978212
Merge branch 'main' into dxf-read-allocs
FredApps Nov 28, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 63 additions & 50 deletions crates/io/src/dxf_raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)]
Expand All @@ -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)
}
Expand Down Expand Up @@ -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()));
Expand All @@ -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)
Expand All @@ -232,18 +238,18 @@ 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;
}
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;
}
Expand All @@ -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(&[])
Expand All @@ -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(),
Expand Down Expand Up @@ -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);
}
}
Expand All @@ -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();
Expand All @@ -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() {
Expand All @@ -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);
}
Expand All @@ -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 {
Expand All @@ -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());
}
}
Expand Down Expand Up @@ -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);
}
Expand All @@ -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);
Expand All @@ -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>,
Expand All @@ -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()))
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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();
}
Expand All @@ -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()
}

Expand Down Expand Up @@ -1100,7 +1113,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();
Expand Down
Loading
Loading