1use ifc_model::{Entity, EntityId, Model, Value};
18use ifc_schema::{for_version, Schema, SchemaVersion};
19
20use crate::error::CostError;
21
22const fn proven(version: SchemaVersion) -> bool {
24 matches!(
25 version,
26 SchemaVersion::Ifc2x3 | SchemaVersion::Ifc4 | SchemaVersion::Ifc4x3
27 )
28}
29
30#[derive(Debug, Clone, Copy)]
32pub(crate) struct ReadRelease {
33 version: SchemaVersion,
34 schema: &'static Schema,
35}
36
37impl ReadRelease {
38 pub(crate) fn of_version(version: SchemaVersion) -> Result<Self, CostError> {
40 if !proven(version) {
41 return Err(CostError::UnsupportedSchema {
42 schema: version.release_id().to_owned(),
43 });
44 }
45 let schema = for_version(version).map_err(|_| CostError::UnsupportedSchema {
46 schema: version.release_id().to_owned(),
47 })?;
48 Ok(Self { version, schema })
49 }
50
51 pub(crate) fn of(model: &Model) -> Result<Self, CostError> {
53 match model.header().schema.as_slice() {
54 [] => Self::of_version(SchemaVersion::Ifc4),
55 [token] => SchemaVersion::from_header_token(token)
56 .filter(|version| proven(*version))
57 .ok_or_else(|| CostError::UnsupportedSchema {
58 schema: token.clone(),
59 })
60 .and_then(Self::of_version),
61 tokens => Err(CostError::MultipleSchemas {
62 schemas: tokens.len(),
63 }),
64 }
65 }
66
67 pub(crate) const fn version(self) -> SchemaVersion {
69 self.version
70 }
71
72 pub(crate) fn value<'m>(
76 self,
77 entity_type: &str,
78 record: &'m Entity,
79 attribute: &str,
80 ) -> Option<&'m Value> {
81 let slot = self
82 .schema
83 .attribute_names(entity_type)
84 .iter()
85 .position(|name| name.eq_ignore_ascii_case(attribute))?;
86 match record.attribute(slot)? {
87 Value::Null => None,
88 value => Some(value),
89 }
90 }
91
92 pub(crate) fn text<'m>(
94 self,
95 entity_type: &str,
96 record: &'m Entity,
97 attribute: &str,
98 ) -> Option<&'m str> {
99 self.value(entity_type, record, attribute)?
100 .unwrap_typed()
101 .as_text()
102 }
103
104 pub(crate) fn date_time<'m>(
107 self,
108 entity_type: &str,
109 record: &'m Entity,
110 attribute: &str,
111 ) -> Option<AuthoredDateTime<'m>> {
112 match self.value(entity_type, record, attribute)? {
113 Value::Ref(target) => Some(AuthoredDateTime::Record(*target)),
114 value => value.unwrap_typed().as_text().map(AuthoredDateTime::Text),
115 }
116 }
117}
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125#[non_exhaustive]
126pub enum AuthoredDateTime<'m> {
127 Text(&'m str),
129 Record(EntityId),
131}
132
133impl<'m> AuthoredDateTime<'m> {
134 #[must_use]
136 pub const fn text(self) -> Option<&'m str> {
137 match self {
138 Self::Text(text) => Some(text),
139 Self::Record(_) => None,
140 }
141 }
142
143 #[must_use]
145 pub const fn record(self) -> Option<EntityId> {
146 match self {
147 Self::Record(id) => Some(id),
148 Self::Text(_) => None,
149 }
150 }
151}