openbim_ifc_binding_core/
xml.rs1use crate::{BindingError, IfcModel};
15
16impl IfcModel {
17 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 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#[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 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}