1use openbim_ifc_binding_core::value::{Kind, Tagged, MAX_NESTING};
17use openbim_ifc_binding_core::{BindingError, Plain};
18
19pub const OPENBIM_IFC_KIND_NULL: i32 = 0;
22pub const OPENBIM_IFC_KIND_DERIVED: i32 = 1;
24pub const OPENBIM_IFC_KIND_BOOL: i32 = 2;
26pub const OPENBIM_IFC_KIND_UNKNOWN: i32 = 3;
28pub const OPENBIM_IFC_KIND_INTEGER: i32 = 4;
30pub const OPENBIM_IFC_KIND_REAL: i32 = 5;
32pub const OPENBIM_IFC_KIND_TEXT: i32 = 6;
34pub const OPENBIM_IFC_KIND_BINARY: i32 = 7;
36pub const OPENBIM_IFC_KIND_ENUM: i32 = 8;
38pub const OPENBIM_IFC_KIND_REF: i32 = 9;
40pub const OPENBIM_IFC_KIND_LIST: i32 = 10;
42pub const OPENBIM_IFC_KIND_TYPED: i32 = 11;
44pub const OPENBIM_IFC_KIND_EXACT: i32 = 12;
48
49#[repr(C)]
51#[derive(Debug, Default, Clone, Copy, PartialEq)]
52pub struct OpenbimIfcValueNode {
53 pub kind: i32,
55 pub child_count: u32,
57 pub int_value: i64,
59 pub real_value: f64,
61 pub str_offset: u64,
63 pub str_len: u64,
65}
66
67#[derive(Debug, Default, Clone, PartialEq)]
69pub struct Tape {
70 pub nodes: Vec<OpenbimIfcValueNode>,
72 pub strings: Vec<u8>,
74}
75
76impl Tape {
77 pub fn encode(value: &Tagged) -> Self {
79 let mut tape = Self::default();
80 tape.push(value);
81 tape
82 }
83
84 pub fn encode_all(values: &[Tagged]) -> Self {
86 let mut tape = Self::default();
87 for value in values {
88 tape.push(value);
89 }
90 tape
91 }
92
93 fn string(&mut self, node: &mut OpenbimIfcValueNode, text: &str) {
94 node.str_offset = self.strings.len() as u64;
95 node.str_len = text.len() as u64;
96 self.strings.extend_from_slice(text.as_bytes());
97 }
98
99 fn push(&mut self, value: &Tagged) {
100 let mut node = OpenbimIfcValueNode {
101 kind: kind_code(value.kind()),
102 ..OpenbimIfcValueNode::default()
103 };
104 match value {
105 Tagged::Null | Tagged::Derived | Tagged::Unknown => {}
106 Tagged::Bool(b) => node.int_value = i64::from(*b),
107 Tagged::Integer(i) => node.int_value = *i,
108 Tagged::Real(r) => node.real_value = *r,
109 Tagged::Text(s) | Tagged::Binary(s) | Tagged::Enum(s) => self.string(&mut node, s),
110 Tagged::Ref(id) => node.int_value = i64::try_from(*id).unwrap_or(i64::MAX),
113 Tagged::List(items) => {
114 node.child_count = u32::try_from(items.len()).unwrap_or(u32::MAX);
115 self.nodes.push(node);
116 for item in items {
117 self.push(item);
118 }
119 return;
120 }
121 Tagged::Typed { type_name, value } => {
122 self.string(&mut node, type_name);
123 self.nodes.push(node);
124 self.push(value);
125 return;
126 }
127 }
128 self.nodes.push(node);
129 }
130}
131
132pub const fn kind_code(kind: Kind) -> i32 {
134 match kind {
135 Kind::Null => OPENBIM_IFC_KIND_NULL,
136 Kind::Derived => OPENBIM_IFC_KIND_DERIVED,
137 Kind::Bool => OPENBIM_IFC_KIND_BOOL,
138 Kind::Unknown => OPENBIM_IFC_KIND_UNKNOWN,
139 Kind::Integer => OPENBIM_IFC_KIND_INTEGER,
140 Kind::Real => OPENBIM_IFC_KIND_REAL,
141 Kind::Text => OPENBIM_IFC_KIND_TEXT,
142 Kind::Binary => OPENBIM_IFC_KIND_BINARY,
143 Kind::Enum => OPENBIM_IFC_KIND_ENUM,
144 Kind::Ref => OPENBIM_IFC_KIND_REF,
145 Kind::List => OPENBIM_IFC_KIND_LIST,
146 Kind::Typed => OPENBIM_IFC_KIND_TYPED,
147 }
148}
149
150fn invalid(detail: impl Into<String>) -> BindingError {
151 BindingError::InvalidValue(detail.into())
152}
153
154pub struct Reader<'a> {
156 nodes: &'a [OpenbimIfcValueNode],
157 strings: &'a [u8],
158 next: usize,
159}
160
161impl<'a> Reader<'a> {
162 pub fn new(nodes: &'a [OpenbimIfcValueNode], strings: &'a [u8]) -> Self {
164 Self {
165 nodes,
166 strings,
167 next: 0,
168 }
169 }
170
171 pub fn single(mut self) -> Result<Tagged, BindingError> {
173 let value = self.value(0)?;
174 self.finish()?;
175 Ok(value)
176 }
177
178 pub fn plain_single(mut self) -> Result<Plain, BindingError> {
186 let value = self.plain(0)?;
187 self.finish()?;
188 Ok(value)
189 }
190
191 fn plain(&mut self, depth: usize) -> Result<Plain, BindingError> {
192 if depth > MAX_NESTING {
193 return Err(invalid(format!("nesting deeper than {MAX_NESTING}")));
194 }
195 let node = *self
196 .nodes
197 .get(self.next)
198 .ok_or_else(|| invalid("tape ends before the value does"))?;
199 match node.kind {
200 OPENBIM_IFC_KIND_LIST => {
201 Self::no_string(&node)?;
202 self.next += 1;
203 let mut items = Vec::new();
204 for _ in 0..node.child_count {
205 items.push(self.plain(depth + 1)?);
206 }
207 Ok(Plain::List(items))
208 }
209 OPENBIM_IFC_KIND_EXACT => {
210 Self::no_string(&node)?;
211 if node.child_count != 0 {
212 return Err(invalid("an exact node has one child and no child count"));
213 }
214 self.next += 1;
215 Ok(Plain::Exact(self.value(depth + 1)?))
216 }
217 _ => Ok(match self.value(depth)? {
218 Tagged::Null => Plain::Null,
219 Tagged::Bool(b) => Plain::Bool(b),
220 Tagged::Integer(i) => Plain::Integer(i),
221 Tagged::Real(r) => Plain::Real(r),
222 Tagged::Text(s) => Plain::Text(s),
223 Tagged::Ref(id) => Plain::Ref(id),
224 exact => Plain::Exact(exact),
225 }),
226 }
227 }
228
229 pub fn many(mut self, count: usize) -> Result<Vec<Tagged>, BindingError> {
231 let values = (0..count)
232 .map(|_| self.value(0))
233 .collect::<Result<Vec<_>, _>>()?;
234 self.finish()?;
235 Ok(values)
236 }
237
238 fn finish(self) -> Result<(), BindingError> {
241 if self.next == self.nodes.len() {
242 Ok(())
243 } else {
244 Err(invalid(format!(
245 "tape has {} nodes but only {} were used",
246 self.nodes.len(),
247 self.next
248 )))
249 }
250 }
251
252 fn string(&self, node: &OpenbimIfcValueNode) -> Result<String, BindingError> {
253 let start = usize::try_from(node.str_offset).map_err(|_| invalid("string offset"))?;
254 let len = usize::try_from(node.str_len).map_err(|_| invalid("string length"))?;
255 let end = start
256 .checked_add(len)
257 .filter(|end| *end <= self.strings.len())
258 .ok_or_else(|| invalid("string range outside the string buffer"))?;
259 std::str::from_utf8(&self.strings[start..end])
260 .map(str::to_owned)
261 .map_err(|_| invalid("string is not UTF-8"))
262 }
263
264 fn no_string(node: &OpenbimIfcValueNode) -> Result<(), BindingError> {
265 if node.str_len == 0 {
266 Ok(())
267 } else {
268 Err(invalid("this kind carries no string"))
269 }
270 }
271
272 fn value(&mut self, depth: usize) -> Result<Tagged, BindingError> {
273 if depth > MAX_NESTING {
274 return Err(invalid(format!("nesting deeper than {MAX_NESTING}")));
275 }
276 let node = *self
277 .nodes
278 .get(self.next)
279 .ok_or_else(|| invalid("tape ends before the value does"))?;
280 self.next += 1;
281 if node.kind != OPENBIM_IFC_KIND_LIST && node.child_count != 0 {
282 return Err(invalid("only a list node may have children"));
283 }
284 let string_kind = matches!(
285 node.kind,
286 OPENBIM_IFC_KIND_TEXT
287 | OPENBIM_IFC_KIND_BINARY
288 | OPENBIM_IFC_KIND_ENUM
289 | OPENBIM_IFC_KIND_TYPED
290 );
291 if !string_kind {
292 Self::no_string(&node)?;
293 }
294 Ok(match node.kind {
295 OPENBIM_IFC_KIND_NULL => Tagged::Null,
296 OPENBIM_IFC_KIND_DERIVED => Tagged::Derived,
297 OPENBIM_IFC_KIND_UNKNOWN => Tagged::Unknown,
298 OPENBIM_IFC_KIND_BOOL => match node.int_value {
299 0 => Tagged::Bool(false),
300 1 => Tagged::Bool(true),
301 other => return Err(invalid(format!("bool must be 0 or 1, got {other}"))),
302 },
303 OPENBIM_IFC_KIND_INTEGER => Tagged::Integer(node.int_value),
304 OPENBIM_IFC_KIND_REAL => Tagged::Real(node.real_value),
305 OPENBIM_IFC_KIND_TEXT => Tagged::Text(self.string(&node)?),
306 OPENBIM_IFC_KIND_BINARY => Tagged::Binary(self.string(&node)?),
307 OPENBIM_IFC_KIND_ENUM => Tagged::Enum(self.string(&node)?),
308 OPENBIM_IFC_KIND_REF => Tagged::Ref(
309 u64::try_from(node.int_value)
310 .map_err(|_| invalid("ref id must not be negative"))?,
311 ),
312 OPENBIM_IFC_KIND_LIST => {
313 let mut items = Vec::new();
316 for _ in 0..node.child_count {
317 items.push(self.value(depth + 1)?);
318 }
319 Tagged::List(items)
320 }
321 OPENBIM_IFC_KIND_TYPED => Tagged::Typed {
322 type_name: self.string(&node)?,
323 value: Box::new(self.value(depth + 1)?),
324 },
325 other => return Err(invalid(format!("unknown kind code {other}"))),
326 })
327 }
328}
329
330#[cfg(test)]
331mod tests;