Skip to main content

cadkit_dwg/
lib.rs

1//! Clean-room reader for DWG drawings, AC1014 (R14) through AC1032 (2018), including 2007.
2//! The AC1012 (R13) path is implemented but untested; see the repository's DWG format notes.
3//! Entity coverage is still growing. There is no DWG writer.
4//!
5//! Contract used by the `cadkit` facade: [`sniff`], [`inspect`] and [`read`]. The [`native`]
6//! module exposes the decoded file losslessly (header variables, classes, object
7//! map, every object with its common data, type-specific data and raw bytes).
8//!
9//! Layers, following the ODA *Open Design Specification for .dwg files* v5.4.1:
10//! - `container`: file header, section maps, page decompression (LZ77 variants,
11//!   R2007 Reed-Solomon de-interleaving);
12//! - `header`, `classes`, `handles`: the header variables, class list and object map;
13//! - `object`: the per-object bit streams, common data and type decoders
14//!   (extension point: `object::registry`);
15//! - `mapping`: native objects → [`cadkit_core::Document`].
16
17pub mod bits;
18mod classes;
19mod codepage;
20mod container;
21mod crc;
22mod handles;
23mod header;
24mod mapping;
25pub mod native;
26mod object;
27mod reader;
28mod version;
29
30use cadkit_core::{Document, Format, ReadOptions, Result, Summary, Units};
31
32pub use version::DwgVersion;
33
34/// Returns true when `bytes` start with the magic of a supported DWG version.
35pub fn sniff(bytes: &[u8]) -> bool {
36    bytes.get(..6).and_then(DwgVersion::from_magic).is_some()
37}
38
39/// Inspects the DWG file header and `AcDb:Header` variables without decoding object streams.
40pub fn inspect(bytes: &[u8], options: &ReadOptions) -> Result<Summary> {
41    let c = container::read_header_only(bytes, &options.limits)?;
42    let (encoding, _) = codepage::resolve(c.codepage, options.fallback_codepage.as_deref());
43    let ctx = object::DecodeContext {
44        version: c.version,
45        encoding,
46        max_string: options.limits.max_string_bytes,
47        max_vertices: options.limits.max_vertices,
48    };
49    let (units, is_3d) = match &c.header {
50        Some(section) => match header::parse(section, c.maintenance, ctx) {
51            Ok((vars, _)) => {
52                let units = vars
53                    .int("INSUNITS")
54                    .map_or_else(Units::default, |u| Units::from_insunits(u as i32));
55                let is_3d = match (vars.point3("EXTMIN"), vars.point3("EXTMAX")) {
56                    (Some([_, _, z0]), Some([_, _, z1]))
57                        if z0.is_finite() && z1.is_finite() && z0 <= z1 =>
58                    {
59                        (z0.abs() > 1e-12 || z1.abs() > 1e-12).then_some(true)
60                    }
61                    _ => None,
62                };
63                (Some(units), is_3d)
64            }
65            Err(_) => (None, None),
66        },
67        None => (None, None),
68    };
69    Ok(Summary::new(Format::Dwg, c.version.magic())
70        .with_is_3d(is_3d)
71        .with_units(units)
72        .with_codepage(Some(encoding.name().to_owned())))
73}
74
75/// Reads a whole file into the format-neutral model.
76///
77/// Fails only when no useful document can be built (unknown format, broken file
78/// header or object map, a limit exceeded); recoverable problems become
79/// [`Document::warnings`].
80pub fn read(bytes: &[u8], options: &ReadOptions) -> Result<Document> {
81    let file = reader::read_file(bytes, options, options.keep_raw)?;
82    mapping::to_document(&file, options)
83}
84
85#[cfg(test)]
86mod tests {
87    use super::*;
88
89    #[test]
90    fn sniff_accepts_supported_magics_only() {
91        assert!(sniff(b"AC1015\0\0\0\0\0"));
92        assert!(sniff(b"AC1032"));
93        assert!(!sniff(b"AC1009"));
94        assert!(!sniff(b"AC10"));
95        assert!(!sniff(b""));
96    }
97
98    #[test]
99    fn read_rejects_garbage_without_panicking() {
100        let options = ReadOptions::default();
101        assert!(read(b"not a drawing", &options).is_err());
102        assert!(read(b"AC1015", &options).is_err());
103        assert!(read(b"AC1018", &options).is_err());
104        assert!(read(b"AC1021", &options).is_err());
105        assert!(inspect(b"not a drawing", &options).is_err());
106        assert!(inspect(b"AC1015", &options).is_err());
107    }
108}