dxfscan 0.1.0

Binary DXF parser with typed entity data and lookup indices
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
// SPDX-License-Identifier: ISC
use alloc::vec::Vec;

use crate::block::Block;
use crate::drawing::Drawing;
use crate::entity::*;
use crate::error::Error;
use crate::reader::BinaryReader;
use crate::table::{Layer, Style};
use crate::value::GroupValue;

/// Parses a binary DXF byte slice into a [`Drawing`].
///
/// The input must start with the 22-byte binary DXF sentinel.
/// All borrowed string data in the returned `Drawing` references
/// the input slice.
pub fn scan<'a>(data: &'a [u8]) -> Result<Drawing<'a>, Error> {
    let mut reader = BinaryReader::new(data)?;
    let mut drawing = Drawing::default();

    // The scanner carries forward the "next type name" from the last
    // entity boundary (code 0) instead of rewinding the reader.
    let mut next = read_type_name(&mut reader)?;

    while let Some(type_name) = next {
        match type_name {
            b"SECTION" => {
                let section_name = read_section_name(&mut reader)?;
                next = match section_name {
                    b"HEADER" => scan_header(&mut reader, &mut drawing)?,
                    b"TABLES" => scan_tables(&mut reader, &mut drawing)?,
                    b"BLOCKS" => scan_blocks(&mut reader, &mut drawing)?,
                    b"ENTITIES" => scan_entities(&mut reader, &mut drawing)?,
                    _ => skip_to_code0(&mut reader)?,
                };
            }
            b"EOF" => break,
            _ => {
                next = read_type_name(&mut reader)?;
            }
        }
    }

    // Build indices.
    for (i, layer) in drawing.layers.iter().enumerate() {
        drawing.layers_by_name.insert(layer.name, i);
    }
    for (i, style) in drawing.styles.iter().enumerate() {
        drawing.styles_by_name.insert(style.name, i);
    }
    for (i, block) in drawing.blocks.iter().enumerate() {
        drawing.blocks_by_name.insert(block.name, i);
    }
    for (i, entity) in drawing.entities.iter().enumerate() {
        let handle = entity.common().handle;
        if !handle.is_empty() {
            drawing.entity_by_handle.insert(handle, i);
        }
    }

    Ok(drawing)
}

/// Reads pairs until code 0, returns the string value of that code-0 pair.
fn read_type_name<'a>(reader: &mut BinaryReader<'a>) -> Result<Option<&'a [u8]>, Error> {
    loop {
        let Some((code, val)) = reader.next_pair()? else {
            return Ok(None);
        };
        if code == 0 {
            return Ok(val.as_str_bytes());
        }
    }
}

/// Reads the (2, section_name) pair that follows (0, "SECTION") or (0, "TABLE").
fn read_section_name<'a>(reader: &mut BinaryReader<'a>) -> Result<&'a [u8], Error> {
    match reader.next_pair()? {
        Some((2, GroupValue::String(name))) => Ok(name),
        _ => Ok(b""),
    }
}

/// Skips all pairs until code 0, returns the type name (or None at EOF).
/// Used to skip entire sections (HEADER, CLASSES, etc).
fn skip_to_code0<'a>(reader: &mut BinaryReader<'a>) -> Result<Option<&'a [u8]>, Error> {
    loop {
        let Some((code, val)) = reader.next_pair()? else {
            return Ok(None);
        };
        if code == 0 {
            return Ok(val.as_str_bytes());
        }
    }
}

/// Reads pairs into an entity builder until code 0 is hit.
/// Returns the next type name (from the code-0 boundary).
fn feed_entity_pairs<'a>(
    reader: &mut BinaryReader<'a>,
    common: &mut EntityCommon<'a>,
    mut feed_specific: impl FnMut(u16, &GroupValue<'a>),
) -> Result<Option<&'a [u8]>, Error> {
    loop {
        let Some((code, val)) = reader.next_pair()? else {
            return Ok(None);
        };
        if code == 0 {
            return Ok(val.as_str_bytes());
        }
        if !common.feed(code, &val) {
            feed_specific(code, &val);
        }
    }
}

// --- HEADER ---

/// Parses the HEADER section into a map of variable name → first value.
fn scan_header<'a>(
    reader: &mut BinaryReader<'a>,
    drawing: &mut Drawing<'a>,
) -> Result<Option<&'a [u8]>, Error> {
    let mut current_var: Option<&'a str> = None;
    loop {
        let Some((code, val)) = reader.next_pair()? else {
            return Ok(None);
        };
        if code == 0 {
            return Ok(val.as_str_bytes());
        }
        if code == 9 {
            current_var = val
                .as_str_bytes()
                .and_then(|b| core::str::from_utf8(b).ok());
        } else if let Some(name) = current_var.take() {
            drawing.headers.insert(name, val);
        }
    }
}

// --- TABLES ---

fn scan_tables<'a>(
    reader: &mut BinaryReader<'a>,
    drawing: &mut Drawing<'a>,
) -> Result<Option<&'a [u8]>, Error> {
    let mut next = read_type_name(reader)?;
    loop {
        let type_name = match next {
            Some(t) => t,
            None => return Ok(None),
        };
        match type_name {
            b"ENDSEC" => return read_type_name(reader),
            b"TABLE" => {
                let table_name = read_section_name(reader)?;
                next = scan_table(reader, drawing, table_name)?;
            }
            _ => {
                // Skip non-table entries (e.g. TABLE header data is already consumed).
                next = read_type_name(reader)?;
            }
        }
    }
}

fn scan_table<'a>(
    reader: &mut BinaryReader<'a>,
    drawing: &mut Drawing<'a>,
    table_name: &[u8],
) -> Result<Option<&'a [u8]>, Error> {
    let mut next = read_type_name(reader)?;
    loop {
        let type_name = match next {
            Some(t) => t,
            None => return Ok(None),
        };
        match type_name {
            b"ENDTAB" => return read_type_name(reader),
            b"LAYER" if table_name == b"LAYER" => {
                let mut layer = Layer::default();
                next = feed_pairs(reader, |c, v| layer.feed(c, v))?;
                drawing.layers.push(layer);
            }
            b"STYLE" if table_name == b"STYLE" => {
                let mut style = Style::default();
                next = feed_pairs(reader, |c, v| style.feed(c, v))?;
                drawing.styles.push(style);
            }
            _ => {
                next = skip_to_code0(reader)?;
            }
        }
    }
}

/// Reads pairs until code 0, feeding each to a callback.
fn feed_pairs<'a>(
    reader: &mut BinaryReader<'a>,
    mut feed: impl FnMut(u16, &GroupValue<'a>),
) -> Result<Option<&'a [u8]>, Error> {
    loop {
        let Some((code, val)) = reader.next_pair()? else {
            return Ok(None);
        };
        if code == 0 {
            return Ok(val.as_str_bytes());
        }
        feed(code, &val);
    }
}

// --- BLOCKS ---

fn scan_blocks<'a>(
    reader: &mut BinaryReader<'a>,
    drawing: &mut Drawing<'a>,
) -> Result<Option<&'a [u8]>, Error> {
    let mut next = read_type_name(reader)?;
    loop {
        let type_name = match next {
            Some(t) => t,
            None => return Ok(None),
        };
        match type_name {
            b"ENDSEC" => return read_type_name(reader),
            b"BLOCK" => {
                let (block, n) = scan_one_block(reader)?;
                drawing.blocks.push(block);
                next = n;
            }
            _ => {
                next = skip_to_code0(reader)?;
            }
        }
    }
}

fn scan_one_block<'a>(
    reader: &mut BinaryReader<'a>,
) -> Result<(Block<'a>, Option<&'a [u8]>), Error> {
    let mut block = Block::default();

    // Read block header pairs (name, base_point) until code 0.
    let mut next = feed_entity_pairs(reader, &mut EntityCommon::new(), |code, val| match code {
        2 => {
            if let Some(s) = val.as_str_bytes() {
                block.name = s;
            }
        }
        10 => {
            if let Some(f) = val.as_f64() {
                block.base_point.x = f;
            }
        }
        20 => {
            if let Some(f) = val.as_f64() {
                block.base_point.y = f;
            }
        }
        30 => {
            if let Some(f) = val.as_f64() {
                block.base_point.z = f;
            }
        }
        _ => {}
    })?;

    // Parse entities within the block until ENDBLK.
    loop {
        let type_name = match next {
            Some(t) => t,
            None => return Ok((block, None)),
        };
        if type_name == b"ENDBLK" {
            // Skip ENDBLK's own pairs.
            next = skip_to_code0(reader)?;
            return Ok((block, next));
        }
        next = scan_one_entity(reader, type_name, &mut block.entities)?;
    }
}

// --- ENTITIES ---

fn scan_entities<'a>(
    reader: &mut BinaryReader<'a>,
    drawing: &mut Drawing<'a>,
) -> Result<Option<&'a [u8]>, Error> {
    let mut next = read_type_name(reader)?;
    loop {
        let type_name = match next {
            Some(t) => t,
            None => return Ok(None),
        };
        if type_name == b"ENDSEC" {
            return read_type_name(reader);
        }
        next = scan_one_entity(reader, type_name, &mut drawing.entities)?;
    }
}

/// Scans a single entity (including POLYLINE/VERTEX/SEQEND and INSERT/ATTRIB/SEQEND children).
/// Returns the next type name after this entity.
fn scan_one_entity<'a>(
    reader: &mut BinaryReader<'a>,
    type_name: &'a [u8],
    dest: &mut Vec<Entity<'a>>,
) -> Result<Option<&'a [u8]>, Error> {
    match type_name {
        b"POLYLINE" => {
            let mut common = EntityCommon::new();
            let mut poly = Polyline::default();
            let mut next = feed_entity_pairs(reader, &mut common, |c, v| poly.feed(c, v))?;
            // Collect VERTEX children until SEQEND.
            while let Some(tn) = next {
                match tn {
                    b"VERTEX" => {
                        let mut vc = EntityCommon::new();
                        let mut v = Vertex::default();
                        next = feed_entity_pairs(reader, &mut vc, |c, val| v.feed(c, val))?;
                        poly.vertices.push(v);
                    }
                    b"SEQEND" => {
                        next = skip_to_code0(reader)?;
                        break;
                    }
                    _ => {
                        next = skip_to_code0(reader)?;
                    }
                }
            }
            dest.push(Entity::Polyline(common, poly));
            Ok(next)
        }
        _ => {
            let (entity, next) = scan_typed_entity(reader, type_name)?;

            // Handle INSERT with attributes.
            if let Entity::Insert(_, ref ins) = entity
                && ins.has_attributes
            {
                let mut entity = entity;
                let next = collect_insert_attributes(reader, &mut entity, next)?;
                dest.push(entity);
                return Ok(next);
            }

            dest.push(entity);
            Ok(next)
        }
    }
}

/// Scans a single typed entity (not POLYLINE). Returns (entity, next_type_name).
fn scan_typed_entity<'a>(
    reader: &mut BinaryReader<'a>,
    type_name: &'a [u8],
) -> Result<(Entity<'a>, Option<&'a [u8]>), Error> {
    let mut common = EntityCommon::new();

    macro_rules! scan_entity {
        ($variant:ident, $ty:ty) => {{
            let mut e = <$ty>::default();
            let next = feed_entity_pairs(reader, &mut common, |c, v| e.feed(c, v))?;
            Ok((Entity::$variant(common, e), next))
        }};
        ($variant:ident, $ty:ty, finish) => {{
            let mut e = <$ty>::default();
            let next = feed_entity_pairs(reader, &mut common, |c, v| e.feed(c, v))?;
            e.finish();
            Ok((Entity::$variant(common, e), next))
        }};
        ($variant:ident, $ty:ty, new) => {{
            let mut e = <$ty>::new();
            let next = feed_entity_pairs(reader, &mut common, |c, v| e.feed(c, v))?;
            Ok((Entity::$variant(common, e), next))
        }};
    }

    match type_name {
        b"LINE" => scan_entity!(Line, Line),
        b"CIRCLE" => scan_entity!(Circle, Circle),
        b"ARC" => scan_entity!(Arc, Arc),
        b"ELLIPSE" => scan_entity!(Ellipse, Ellipse),
        b"LWPOLYLINE" => scan_entity!(LwPolyline, LwPolyline, finish),
        b"SPLINE" => scan_entity!(Spline, Spline, finish),
        b"SOLID" => scan_entity!(Solid, Solid),
        b"TRACE" => scan_entity!(Trace, Trace),
        b"3DFACE" => scan_entity!(Face3d, Face3d, finish),
        b"POINT" => scan_entity!(Point, DxfPoint),
        b"TEXT" => scan_entity!(Text, Text),
        b"MTEXT" => scan_entity!(MText, MText),
        b"INSERT" => scan_entity!(Insert, Insert, new),
        b"DIMENSION" => scan_entity!(Dimension, Dimension),
        b"LEADER" => scan_entity!(Leader, Leader, finish),
        b"HATCH" => {
            let mut builder = crate::entity::hatch::HatchBuilder::new();
            let next = feed_entity_pairs(reader, &mut common, |c, v| builder.feed(c, v))?;
            Ok((Entity::Hatch(common, builder.hatch), next))
        }
        b"WIPEOUT" => scan_entity!(Wipeout, Wipeout),
        b"ATTRIB" => scan_entity!(Attrib, Attrib),
        b"ATTDEF" => scan_entity!(AttDef, AttDef),
        _ => {
            let next = feed_entity_pairs(reader, &mut common, |_, _| {})?;
            Ok((Entity::Unknown(common, type_name), next))
        }
    }
}

/// Collects ATTRIB entities following an INSERT until SEQEND.
fn collect_insert_attributes<'a>(
    reader: &mut BinaryReader<'a>,
    entity: &mut Entity<'a>,
    mut next: Option<&'a [u8]>,
) -> Result<Option<&'a [u8]>, Error> {
    let attrs = match entity {
        Entity::Insert(_, ins) => &mut ins.attributes,
        _ => return Ok(next),
    };
    loop {
        let tn = match next {
            Some(t) => t,
            None => return Ok(None),
        };
        match tn {
            b"ATTRIB" => {
                let mut common = EntityCommon::new();
                let mut a = Attrib::default();
                next = feed_entity_pairs(reader, &mut common, |c, v| a.feed(c, v))?;
                attrs.push(a);
            }
            b"SEQEND" => {
                next = skip_to_code0(reader)?;
                return Ok(next);
            }
            _ => {
                next = skip_to_code0(reader)?;
            }
        }
    }
}