Skip to main content

openbim_ifc_binding_core/
ifczip.rs

1//! ifcZIP (#450, feature `zip`): a STEP or ifcXML model in a ZIP archive.
2//!
3//! Every read entry point ([`IfcModel::parse`] and its variants,
4//! [`IfcModel::open`]) recognizes an archive by its ZIP signature and reads
5//! the one model entry it holds, within the facade's default decompression
6//! budget: STEP under the call's [`ParseOptions`], ifcXML in the layout its
7//! root declares. [`IfcModel::write_ifczip`] writes one.
8//!
9//! The facade's typed refusals map onto the shared codes: an archive with
10//! no model, several, or an entry in another format is `parse`; an
11//! encrypted entry or a compression method other than Stored and Deflate
12//! is `unsupported`; an entry that inflates past the budget is
13//! `budget-exceeded`. Without the feature, an archive is refused with
14//! `feature-disabled`.
15
16use crate::{BindingError, IfcModel, ParseOptions};
17
18/// Read the model in the ifcZIP archive `bytes`, STEP under `options`.
19#[cfg(feature = "zip")]
20pub(crate) fn load(bytes: &[u8], options: ParseOptions) -> Result<IfcModel, BindingError> {
21    use ifc::ifczip::{self, Budget, InnerFormat};
22    use ifc::Codec;
23
24    let entry = ifczip::extract(bytes, &Budget::DEFAULT).map_err(refusal)?;
25    match entry.format {
26        InnerFormat::Step => IfcModel::loaded_as(
27            "STEP in ifcZIP",
28            crate::model::reader(options).read_owned(entry.bytes),
29        ),
30        _ => ifczip::read_entry(entry)
31            .map(|inner| IfcModel {
32                inner,
33                guid_index: Default::default(),
34                history: Default::default(),
35                reverse_index: Default::default(),
36            })
37            .map_err(refusal),
38    }
39}
40
41#[cfg(not(feature = "zip"))]
42pub(crate) fn load(bytes: &[u8], options: ParseOptions) -> Result<IfcModel, BindingError> {
43    let _ = (bytes, options);
44    Err(BindingError::FeatureDisabled("zip"))
45}
46
47/// A facade refusal as the binding error with the same meaning.
48#[cfg(feature = "zip")]
49fn refusal(error: ifc::ifczip::IfcZipError) -> BindingError {
50    use ifc::ifczip::IfcZipError;
51    match error {
52        IfcZipError::BudgetExceeded { .. } => {
53            BindingError::BudgetExceeded(format!("ifcZIP {error}"))
54        }
55        IfcZipError::Encrypted { .. } | IfcZipError::UnsupportedCompression { .. } => {
56            BindingError::Unsupported(format!("ifcZIP {error}"))
57        }
58        IfcZipError::CodecNotCompiled { feature, .. } => BindingError::FeatureDisabled(feature),
59        IfcZipError::InvalidEntryName(_) | IfcZipError::Write(_) => {
60            BindingError::Write(format!("ifcZIP: {error}"))
61        }
62        other => BindingError::Parse(format!("ifcZIP: {other}")),
63    }
64}
65
66impl IfcModel {
67    /// Serialize as an ifcZIP archive: one Deflate entry holding STEP
68    /// (`inner` `None` or `"step"`, as `model.ifc`) or ifcXML (`"ifcxml"`,
69    /// as `model.ifcXML`, in the layout `xsd_profile` names as for
70    /// [`Self::write_ifcxml`]). Any case.
71    ///
72    /// Refused with `invalid-value` for another `inner`, or an
73    /// `xsd_profile` with STEP inside; otherwise as the inner write, and
74    /// with `feature-disabled` without the `zip` feature.
75    pub fn write_ifczip(
76        &self,
77        inner: Option<&str>,
78        xsd_profile: Option<&str>,
79    ) -> Result<Vec<u8>, BindingError> {
80        let xml = match inner {
81            None => false,
82            Some(token) if token.eq_ignore_ascii_case("step") => false,
83            Some(token) if token.eq_ignore_ascii_case("ifcxml") => true,
84            Some(other) => {
85                return Err(BindingError::InvalidValue(format!(
86                    "the ifcZIP inner format must be \"step\" or \"ifcxml\", not {other:?}"
87                )))
88            }
89        };
90        if !xml && xsd_profile.is_some() {
91            return Err(BindingError::InvalidValue(
92                "an XSD profile applies to ifcXML inside ifcZIP, not STEP".to_owned(),
93            ));
94        }
95        #[cfg(feature = "zip")]
96        {
97            use ifc::ifczip::{pack, InnerFormat};
98            let (document, format) = if xml {
99                (self.write_ifcxml(xsd_profile)?, InnerFormat::IfcXml)
100            } else {
101                (self.write()?, InnerFormat::Step)
102            };
103            pack(format.default_entry_name(), &document).map_err(refusal)
104        }
105        #[cfg(not(feature = "zip"))]
106        {
107            let _ = xml;
108            Err(BindingError::FeatureDisabled("zip"))
109        }
110    }
111}
112
113#[cfg(all(test, feature = "zip", feature = "ifcxml", feature = "ifc4"))]
114mod tests {
115    use super::*;
116
117    const FILE: &[u8] = include_bytes!(concat!(
118        env!("CARGO_MANIFEST_DIR"),
119        "/../../test/fixtures/synthetic-bindings/binding_geometry.ifc"
120    ));
121
122    fn code(result: Result<IfcModel, BindingError>) -> &'static str {
123        result.expect_err("refused").code()
124    }
125
126    #[test]
127    fn every_read_takes_an_archive_and_step_round_trips() {
128        let model = IfcModel::parse(FILE).unwrap();
129        let step = model.write().unwrap();
130        let zipped = model.write_ifczip(None, None).unwrap();
131        assert!(ifc::ifczip::is_zip(&zipped));
132        assert_eq!(zipped, model.write_ifczip(Some("STEP"), None).unwrap());
133        for back in [
134            IfcModel::parse(&zipped).unwrap(),
135            IfcModel::parse_owned(zipped.clone()).unwrap(),
136            IfcModel::parse_with(&zipped, ParseOptions::lenient()).unwrap(),
137        ] {
138            assert!(back.write().unwrap() == step, "STEP changed");
139        }
140    }
141
142    #[test]
143    fn ifcxml_inside_reads_in_either_layout() {
144        let model = IfcModel::parse(FILE).unwrap();
145        for profile in [None, Some("IFC4")] {
146            let xml = model.write_ifcxml(profile).unwrap();
147            let zipped = model.write_ifczip(Some("ifcxml"), profile).unwrap();
148            let entry = ifc::ifczip::extract(&zipped, &ifc::ifczip::Budget::DEFAULT).unwrap();
149            assert_eq!(entry.name, "model.ifcXML");
150            assert!(entry.bytes == xml, "the archive holds the ifcXML bytes");
151            let back = IfcModel::parse(&zipped).unwrap();
152            let direct = IfcModel::parse_ifcxml(&xml, profile).unwrap();
153            assert!(
154                back.write_ifcxml(profile).unwrap() == direct.write_ifcxml(profile).unwrap(),
155                "{profile:?}: the archive read differently"
156            );
157        }
158    }
159
160    #[test]
161    fn refusals_carry_the_shared_codes() {
162        let model = IfcModel::parse(FILE).unwrap();
163        assert_eq!(
164            model.write_ifczip(Some("json"), None).unwrap_err().code(),
165            "invalid-value"
166        );
167        assert_eq!(
168            model.write_ifczip(None, Some("IFC4")).unwrap_err().code(),
169            "invalid-value"
170        );
171        let empty = b"PK\x05\x06\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
172        assert_eq!(code(IfcModel::parse(empty)), "parse");
173        assert_eq!(code(IfcModel::parse(b"PK\x03\x04 damaged")), "parse");
174
175        let mut bomb = b"ISO-10303-21;\n".to_vec();
176        bomb.resize(64 << 20, b' ');
177        let zipped = ifc::ifczip::pack("model.ifc", &bomb).unwrap();
178        assert_eq!(code(IfcModel::parse(&zipped)), "budget-exceeded");
179
180        // An encrypted entry: the general purpose flag's bit 0 set in the
181        // local and central headers.
182        let mut encrypted = model.write_ifczip(None, None).unwrap();
183        for at in 0..encrypted.len() - 4 {
184            let offset = match &encrypted[at..at + 4] {
185                b"PK\x03\x04" => 6,
186                b"PK\x01\x02" => 8,
187                _ => continue,
188            };
189            encrypted[at + offset] |= 1;
190        }
191        assert_eq!(code(IfcModel::parse(&encrypted)), "unsupported");
192    }
193}