Skip to main content

openbim_ifc_binding_core/
record.rs

1//! The host-independent shape of a domain record (#123).
2//!
3//! A domain view borrows the model and cannot cross a language boundary,
4//! so each domain operation returns an owned snapshot: typed Rust structs
5//! for native callers, and the same data as a [`Record`] for the hosts. A
6//! record is a named list of named fields in a fixed order, so every host
7//! converts every domain with one function and the three cannot disagree
8//! about a field:
9//!
10//! - JavaScript: a plain object; field names become camelCase, ids and
11//!   [`Field::Int`] are `bigint`, counts and reals `number`, an absent
12//!   value `undefined`.
13//! - Python: a frozen dataclass named [`Record::name`], field names as
14//!   written here (snake_case), ids `int`, absent `None`.
15//! - C: one value tape, through [`Record::to_tagged`]: each record is a
16//!   `LIST` of its field values in declaration order.
17//!
18//! IFC values travel as [`Field::Value`], in the lossless tagged encoding
19//! (ADR 0013), never folded into a host number.
20
21use crate::value::Tagged;
22
23/// A named, ordered list of fields.
24#[derive(Debug, Clone, PartialEq)]
25pub struct Record {
26    /// The record type, e.g. `PropertySet`; the Python dataclass name and
27    /// the TypeScript interface name.
28    pub name: &'static str,
29    /// Fields in declaration order: the order of the C tape.
30    pub fields: Vec<(&'static str, Field)>,
31}
32
33/// One field value.
34#[derive(Debug, Clone, PartialEq)]
35pub enum Field {
36    /// Absent: an optional field with no value.
37    Null,
38    /// An entity id (`bigint` in JavaScript, `REF` on the C tape).
39    Id(u64),
40    /// A boolean.
41    Bool(bool),
42    /// A non-negative count or index (`number` in JavaScript, `INTEGER` on
43    /// the C tape).
44    Count(usize),
45    /// A 64-bit integer that is data, not a count (`bigint` in JavaScript).
46    Int(i64),
47    /// A real number that is a resolved parameter, not an IFC value.
48    Real(f64),
49    /// Text.
50    Text(String),
51    /// An IFC value in the tagged encoding.
52    Value(Tagged),
53    /// A list of fields.
54    List(Vec<Field>),
55    /// A nested record.
56    Record(Record),
57}
58
59impl Record {
60    /// A record of type `name` with `fields`.
61    pub fn new(name: &'static str, fields: Vec<(&'static str, Field)>) -> Self {
62        Self { name, fields }
63    }
64
65    /// The field named `name`, if the record has one.
66    pub fn get(&self, name: &str) -> Option<&Field> {
67        self.fields
68            .iter()
69            .find(|(field, _)| *field == name)
70            .map(|(_, value)| value)
71    }
72
73    /// The C binding's tape form: a `LIST` of the field values in
74    /// declaration order, nested records and lists as nested `LIST`s.
75    pub fn to_tagged(&self) -> Tagged {
76        Tagged::List(
77            self.fields
78                .iter()
79                .map(|(_, field)| field.to_tagged())
80                .collect(),
81        )
82    }
83}
84
85impl Field {
86    /// An optional field.
87    pub fn optional<T>(value: Option<T>, map: impl FnOnce(T) -> Field) -> Self {
88        value.map_or(Field::Null, map)
89    }
90
91    /// Optional text.
92    pub fn text(value: Option<impl Into<String>>) -> Self {
93        Self::optional(value, |text| Field::Text(text.into()))
94    }
95
96    /// An optional id.
97    pub fn id(value: Option<u64>) -> Self {
98        Self::optional(value, Field::Id)
99    }
100
101    /// A list of ids.
102    pub fn ids(values: impl IntoIterator<Item = u64>) -> Self {
103        Field::List(values.into_iter().map(Field::Id).collect())
104    }
105
106    /// A list of records.
107    pub fn records<T: ToRecord>(values: &[T]) -> Self {
108        Field::List(
109            values
110                .iter()
111                .map(|value| Field::Record(value.to_record()))
112                .collect(),
113        )
114    }
115
116    /// An optional record.
117    pub fn record<T: ToRecord>(value: Option<&T>) -> Self {
118        Self::optional(value, |value| Field::Record(value.to_record()))
119    }
120
121    /// The tape form of this field (see [`Record::to_tagged`]).
122    pub fn to_tagged(&self) -> Tagged {
123        match self {
124            Field::Null => Tagged::Null,
125            Field::Id(id) => Tagged::Ref(*id),
126            Field::Bool(value) => Tagged::Bool(*value),
127            // A count is far below i64::MAX.
128            Field::Count(count) => Tagged::Integer(i64::try_from(*count).unwrap_or(i64::MAX)),
129            Field::Int(value) => Tagged::Integer(*value),
130            Field::Real(value) => Tagged::Real(*value),
131            Field::Text(text) => Tagged::Text(text.clone()),
132            Field::Value(value) => value.clone(),
133            Field::List(items) => Tagged::List(items.iter().map(Field::to_tagged).collect()),
134            Field::Record(record) => record.to_tagged(),
135        }
136    }
137}
138
139/// A snapshot that every host carries as a [`Record`].
140pub trait ToRecord {
141    /// This snapshot as a record.
142    fn to_record(&self) -> Record;
143}
144
145/// Convert a list of snapshots, the shape every list-returning domain
146/// operation hands to a host.
147pub fn to_records<T: ToRecord>(values: &[T]) -> Vec<Record> {
148    values.iter().map(ToRecord::to_record).collect()
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    #[test]
156    fn a_record_crosses_as_a_list_of_its_field_values_in_order() {
157        let record = Record::new(
158            "Example",
159            vec![
160                ("id", Field::Id(7)),
161                ("name", Field::text(None::<String>)),
162                ("count", Field::Count(2)),
163                (
164                    "value",
165                    Field::Value(Tagged::Typed {
166                        type_name: "IFCLABEL".into(),
167                        value: Box::new(Tagged::Text("x".into())),
168                    }),
169                ),
170                ("ids", Field::ids([1, 2])),
171            ],
172        );
173        assert_eq!(record.get("count"), Some(&Field::Count(2)));
174        assert_eq!(
175            record.to_tagged(),
176            Tagged::List(vec![
177                Tagged::Ref(7),
178                Tagged::Null,
179                Tagged::Integer(2),
180                Tagged::Typed {
181                    type_name: "IFCLABEL".into(),
182                    value: Box::new(Tagged::Text("x".into())),
183                },
184                Tagged::List(vec![Tagged::Ref(1), Tagged::Ref(2)]),
185            ])
186        );
187    }
188}