Skip to main content

openbim_ifc_capi/
tape.rs

1//! The value tape: attribute values as flat C data.
2//!
3//! A value is a pre-order array of [`OpenbimIfcValueNode`]. A container node
4//! (`list`, `typed`) is followed by its children; `list` records how many,
5//! `typed` always has exactly one. Strings are not in the nodes: each node
6//! carries an `(offset, len)` byte range into one shared UTF-8 buffer, which
7//! is how text and names cross without any Rust-owned pointer.
8//!
9//! `$`, `*`, `.U.` and `.F.` are distinct kinds or payloads, never folded,
10//! for the same reason as in the JavaScript and Python bindings (ADR 0013).
11//!
12//! A tape rather than recursive structs or a cursor API: one call returns a
13//! whole value, the caller owns both buffers, and no allocation crosses the
14//! ABI.
15
16use openbim_ifc_binding_core::value::{Kind, Tagged, MAX_NESTING};
17use openbim_ifc_binding_core::{BindingError, Plain};
18
19/// Kind codes. Plain integers, not a Rust enum, so an unknown value from C
20/// is rejected rather than read as an invalid discriminant.
21pub const OPENBIM_IFC_KIND_NULL: i32 = 0;
22/// `*`.
23pub const OPENBIM_IFC_KIND_DERIVED: i32 = 1;
24/// `.T.`/`.F.`; `int_value` is 1 or 0.
25pub const OPENBIM_IFC_KIND_BOOL: i32 = 2;
26/// `.U.`.
27pub const OPENBIM_IFC_KIND_UNKNOWN: i32 = 3;
28/// Integer in `int_value`.
29pub const OPENBIM_IFC_KIND_INTEGER: i32 = 4;
30/// Finite real in `real_value`.
31pub const OPENBIM_IFC_KIND_REAL: i32 = 5;
32/// Text in the string range.
33pub const OPENBIM_IFC_KIND_TEXT: i32 = 6;
34/// Binary digits in the string range.
35pub const OPENBIM_IFC_KIND_BINARY: i32 = 7;
36/// Enumeration name in the string range.
37pub const OPENBIM_IFC_KIND_ENUM: i32 = 8;
38/// Entity id in `int_value` (non-negative).
39pub const OPENBIM_IFC_KIND_REF: i32 = 9;
40/// Aggregate; `child_count` children follow.
41pub const OPENBIM_IFC_KIND_LIST: i32 = 10;
42/// Typed wrapper; type name in the string range, one child follows.
43pub const OPENBIM_IFC_KIND_TYPED: i32 = 11;
44/// Only in a plain value (`openbim_ifc_v0_1_entity_set_attribute_by_name_plain`,
45/// #342): one child follows and is written exactly as given, never
46/// coerced. Refused in every other tape.
47pub const OPENBIM_IFC_KIND_EXACT: i32 = 12;
48
49/// One node of a value tape. Fields a kind does not use are zero.
50#[repr(C)]
51#[derive(Debug, Default, Clone, Copy, PartialEq)]
52pub struct OpenbimIfcValueNode {
53    /// One of the `OPENBIM_IFC_KIND_*` codes.
54    pub kind: i32,
55    /// Children following a `list` node; 0 otherwise.
56    pub child_count: u32,
57    /// Payload of `bool` (0/1), `integer` and `ref`.
58    pub int_value: i64,
59    /// Payload of `real`.
60    pub real_value: f64,
61    /// Byte offset of this node's string in the string buffer.
62    pub str_offset: u64,
63    /// Byte length of this node's string (no NUL terminator).
64    pub str_len: u64,
65}
66
67/// A value flattened to a tape: the nodes plus their shared string bytes.
68#[derive(Debug, Default, Clone, PartialEq)]
69pub struct Tape {
70    /// Nodes in pre-order.
71    pub nodes: Vec<OpenbimIfcValueNode>,
72    /// UTF-8 bytes every string range points into.
73    pub strings: Vec<u8>,
74}
75
76impl Tape {
77    /// Flatten one value.
78    pub fn encode(value: &Tagged) -> Self {
79        let mut tape = Self::default();
80        tape.push(value);
81        tape
82    }
83
84    /// Flatten several values back to back, as `attributes` returns them.
85    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            // Ids come from `EntityId(u64)` but real files stay far below
111            // 2^63; the decoder refuses a negative id instead of wrapping.
112            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
132/// The C code for a kind.
133pub 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
154/// Reads values back off a caller's tape, checking every field.
155pub struct Reader<'a> {
156    nodes: &'a [OpenbimIfcValueNode],
157    strings: &'a [u8],
158    next: usize,
159}
160
161impl<'a> Reader<'a> {
162    /// Read from `nodes`, whose string ranges index into `strings`.
163    pub fn new(nodes: &'a [OpenbimIfcValueNode], strings: &'a [u8]) -> Self {
164        Self {
165            nodes,
166            strings,
167            next: 0,
168        }
169    }
170
171    /// Decode exactly one value, then require the tape to be used up.
172    pub fn single(mut self) -> Result<Tagged, BindingError> {
173        let value = self.value(0)?;
174        self.finish()?;
175        Ok(value)
176    }
177
178    /// Decode exactly one plain value (#342), then require the tape to be
179    /// used up.
180    ///
181    /// `null`, `bool`, `integer`, `real`, `text`, `ref` and `list` nodes
182    /// are plain host values, coerced against the declared type; an
183    /// `exact` node's child, and the kinds with no plain form (`derived`,
184    /// `unknown`, `binary`, `enum`, `typed`), are written as given.
185    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    /// Decode `count` values back to back, then require the tape used up.
230    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    /// Trailing nodes mean the caller's counts disagree with the tape;
239    /// refusing them catches an off-by-one in the host instead of ignoring it.
240    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                // Bounded by the tape: each child consumes a node, so a huge
314                // count fails at "tape ends" instead of allocating up front.
315                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;