Skip to main content

openbim_ifc_binding_core/
xml.rs

1//! The ifcXML codec (feature `ifcxml`).
2//!
3//! Two layouts, both the facade's:
4//!
5//! - **native** (no profile): `XmlCodec::default()`, this library's own
6//!   lossless layout. Any model round-trips, whatever schema it declares,
7//!   with no schema tables needed.
8//! - **XSD** (a profile token, `IFC4` or `IFC4X3_ADD2`): `XmlCodec::xsd`,
9//!   the buildingSMART configuration the release XSD declares. It reads and
10//!   writes schema-strictly and refuses what it cannot carry exactly.
11//!
12//! Without the feature, both operations refuse with `feature-disabled`.
13
14use crate::{BindingError, IfcModel};
15
16impl IfcModel {
17    /// Parse an ifcXML document: the native layout when `xsd_profile` is
18    /// `None`, else the XSD configuration of that profile (`IFC4` or
19    /// `IFC4X3_ADD2`, case-insensitive).
20    ///
21    /// Refused with `unsupported-profile` for any other token, with
22    /// `unsupported-schema` when the profile's release is not bundled, and
23    /// with `parse` when the document does not read.
24    pub fn parse_ifcxml(bytes: &[u8], xsd_profile: Option<&str>) -> Result<Self, BindingError> {
25        #[cfg(feature = "ifcxml")]
26        {
27            use ifc::Codec;
28            Self::loaded_as("ifcXML", codec(xsd_profile)?.read_bytes(bytes))
29        }
30        #[cfg(not(feature = "ifcxml"))]
31        {
32            let _ = (bytes, xsd_profile);
33            Err(BindingError::FeatureDisabled("ifcxml"))
34        }
35    }
36
37    /// Serialize as ifcXML, in the layout [`Self::parse_ifcxml`] reads.
38    ///
39    /// An XSD-layout write needs the header to declare the profile's schema
40    /// token, and refuses with `write` what the configuration cannot carry.
41    pub fn write_ifcxml(&self, xsd_profile: Option<&str>) -> Result<Vec<u8>, BindingError> {
42        #[cfg(feature = "ifcxml")]
43        {
44            use ifc::Codec;
45            codec(xsd_profile)?
46                .write_bytes(&self.inner)
47                .map_err(|error| BindingError::Write(format!("ifcXML: {error}")))
48        }
49        #[cfg(not(feature = "ifcxml"))]
50        {
51            let _ = xsd_profile;
52            Err(BindingError::FeatureDisabled("ifcxml"))
53        }
54    }
55}
56
57/// The codec for a layout choice.
58#[cfg(feature = "ifcxml")]
59fn codec(xsd_profile: Option<&str>) -> Result<ifc::XmlCodec, BindingError> {
60    use std::sync::{Arc, OnceLock};
61
62    use ifc::{Schema, XmlCodec, XmlProfile};
63
64    let Some(token) = xsd_profile else {
65        return Ok(XmlCodec::default());
66    };
67    // The profiles the facade offers, by their schema token. The codec
68    // takes its schema shared; one copy per release is made on first use
69    // rather than one per call.
70    static IFC4: OnceLock<Arc<Schema>> = OnceLock::new();
71    static IFC4X3: OnceLock<Arc<Schema>> = OnceLock::new();
72    let (profile, cache) = [
73        (XmlProfile::Ifc4Add2Tc1, &IFC4),
74        (XmlProfile::Ifc4x3Add2, &IFC4X3),
75    ]
76    .into_iter()
77    .find(|(profile, _)| profile.schema_token().eq_ignore_ascii_case(token))
78    .ok_or_else(|| BindingError::UnsupportedProfile(token.to_owned()))?;
79    let schema = match cache.get() {
80        Some(schema) => Arc::clone(schema),
81        None => {
82            let bundled = ifc::schema::for_version(profile.version()).map_err(|refused| {
83                BindingError::UnsupportedSchema(format!("{} ({refused})", profile.schema_token()))
84            })?;
85            Arc::clone(cache.get_or_init(|| Arc::new(bundled.clone())))
86        }
87    };
88    Ok(XmlCodec::xsd(schema, profile))
89}