Skip to main content

ifc_model/mutation/
edit.rs

1//! Schema-agnostic edit operations: update an existing entity's attributes
2//! or remove it, without corrupting the derived by-type index.
3//!
4//! # Why not a raw `&mut Entity`
5//!
6//! `Model.get_mut` cannot exist as a bare accessor: an entity's `type_name`
7//! is also a key into `Model::by_type`, so mutating the type field through a
8//! `&mut Entity` would silently desynchronize the index (`ids_of_type` keeps
9//! reporting the old type, or both). Every write therefore goes through this
10//! module, which knows how to keep the index correct.
11//!
12//! # What is NOT checked here
13//!
14//! These operations are schema-agnostic: they trust the caller with slot
15//! indices and don't know an entity's declared attribute count. Reference
16//! integrity, arity, and declared-type checks are `ifc-author`'s job on
17//! construction (`EntityBuilder`) and
18//! `ifc-validate`'s job on audit. This is the primitive both build on.
19
20use crate::entity::Entity;
21use crate::index::Footprint;
22use crate::model::Model;
23use crate::mutation::Step;
24use crate::value::{EntityId, Value};
25
26impl Model {
27    /// Set one positional attribute on an existing entity.
28    ///
29    /// Returns the value previously at that slot, or `None` if `id` does not
30    /// name an entity in this model. Growing past the entity's current
31    /// attribute count pads with [`Value::Null`], matching how STEP itself
32    /// treats a missing trailing optional attribute.
33    ///
34    /// Does not touch `type_name`, so the by-type index stays correct without
35    /// needing to run the same reindex logic [`Model::insert`] does. Renaming
36    /// an entity's type is a structural change, not an attribute edit: use
37    /// [`Model::retype`].
38    ///
39    /// ```
40    /// use ifc_model::{Entity, EntityId, Model, Value};
41    ///
42    /// let mut model = Model::new();
43    /// let id = model.push(Entity::new("IFCCARTESIANPOINT", vec![Value::List(vec![
44    ///     Value::Real(0.0), Value::Real(0.0),
45    /// ])]));
46    ///
47    /// let previous = model.set_attribute(id, 0, Value::List(vec![
48    ///     Value::Real(10.0), Value::Real(20.0),
49    /// ]));
50    /// assert!(previous.is_some());
51    /// let coords = model.get(id).unwrap().attribute(0).unwrap().as_list().unwrap();
52    /// assert_eq!(coords[0].as_f64(), Some(10.0));
53    /// ```
54    ///
55    /// # Panics
56    ///
57    /// If `index` is `usize::MAX`, before anything is written.
58    pub fn set_attribute(&mut self, id: EntityId, index: usize, value: Value) -> Option<Value> {
59        // Before any write: a panic must leave the entity as it was.
60        let width = slot_width(index);
61        let recording = self.is_recording();
62        let built = self.derived_is_built();
63        let entity = self.entity_mut(id)?;
64        let before = built.then(|| Footprint::of_slots(entity, &[index]));
65        let len = entity.attributes.len();
66        if index >= len {
67            entity.attributes.resize(width, Value::Null);
68        }
69        let previous = std::mem::replace(&mut entity.attributes[index], value);
70        let after = built.then(|| Footprint::of_slots(entity, &[index]));
71        self.note_write(id, before, after);
72        if recording {
73            let value = (index < len).then(|| previous.clone());
74            self.record(Step::Slot {
75                id,
76                slot: index,
77                value,
78                len,
79            });
80        }
81        self.bump_revision();
82        Some(previous)
83    }
84
85    /// Apply several attribute edits to one entity as a single unit.
86    ///
87    /// `edits` are applied in order; a later edit to the same slot wins. This
88    /// exists because a caller updating several attributes wants to do it in
89    /// one lookup rather than repeating [`Model::set_attribute`]'s entity
90    /// lookup per field — the practical difference for callers is that this
91    /// is one indexmap probe instead of N, not a transactional guarantee
92    /// (there is nothing to roll back: slot writes cannot themselves fail).
93    ///
94    /// Returns the previous values in `edits` order, or `None` if `id` does
95    /// not name an entity. An empty `edits` changes nothing, revision
96    /// included.
97    ///
98    /// # Panics
99    ///
100    /// If any index is `usize::MAX`, before anything is written.
101    pub fn set_attributes(
102        &mut self,
103        id: EntityId,
104        edits: impl IntoIterator<Item = (usize, Value)>,
105    ) -> Option<Vec<Value>> {
106        let recording = self.is_recording();
107        let built = self.derived_is_built();
108        let edits: Vec<(usize, Value)> = edits.into_iter().collect();
109        // Before any write: a panic must leave the entity as it was.
110        for (index, _) in &edits {
111            slot_width(*index);
112        }
113        let slots: Vec<usize> = if built {
114            edits.iter().map(|(index, _)| *index).collect()
115        } else {
116            Vec::new()
117        };
118        let entity = self.entity_mut(id)?;
119        let before = built.then(|| Footprint::of_slots(entity, &slots));
120        let mut previous = Vec::new();
121        let mut steps = Vec::new();
122        for (index, value) in edits {
123            let len = entity.attributes.len();
124            if index >= len {
125                entity.attributes.resize(index + 1, Value::Null);
126            }
127            let old = std::mem::replace(&mut entity.attributes[index], value);
128            if recording {
129                steps.push(Step::Slot {
130                    id,
131                    slot: index,
132                    value: (index < len).then(|| old.clone()),
133                    len,
134                });
135            }
136            previous.push(old);
137        }
138        if previous.is_empty() {
139            // Nothing written: no change to count or to undo.
140            return Some(previous);
141        }
142        let after = built.then(|| Footprint::of_slots(entity, &slots));
143        self.note_write(id, before, after);
144        for step in steps {
145            self.record(step);
146        }
147        self.bump_revision();
148        Some(previous)
149    }
150
151    /// Shorten an entity's record to its first `len` attributes.
152    ///
153    /// Returns the dropped tail in slot order, or `None` if `id` does not
154    /// name an entity. A record of `len` attributes or fewer is left alone:
155    /// `Some(vec![])`, no revision bump, nothing recorded.
156    ///
157    /// Recorded like every write, so [`Inverse`](crate::Inverse), history and
158    /// [`Model::preview`] restore the dropped tail exactly. Like
159    /// [`Model::set_attribute`] it does not check the declared attribute
160    /// count: that is the caller's concern.
161    ///
162    /// ```
163    /// use ifc_model::{Entity, Model, Value};
164    ///
165    /// let mut model = Model::new();
166    /// let id = model.push(Entity::new("IFCWALL", vec![
167    ///     Value::Null, Value::Integer(1), Value::Integer(2),
168    /// ]));
169    /// let tail = model.truncate_attributes(id, 1).unwrap();
170    /// assert_eq!(tail.len(), 2);
171    /// assert_eq!(model.get(id).unwrap().attributes.len(), 1);
172    /// ```
173    pub fn truncate_attributes(&mut self, id: EntityId, len: usize) -> Option<Vec<Value>> {
174        let recording = self.is_recording();
175        let built = self.derived_is_built();
176        let entity = self.entity_mut(id)?;
177        let old_len = entity.attributes.len();
178        if len >= old_len {
179            return Some(Vec::new());
180        }
181        let dropped: Vec<usize> = (len..old_len).collect();
182        let before = built.then(|| Footprint::of_slots(entity, &dropped));
183        let tail = entity.attributes.split_off(len);
184        let after = built.then(|| Footprint::of_slots(entity, &[]));
185        self.note_write(id, before, after);
186        if recording {
187            // Descending, so `end_recording`'s reversal restores ascending.
188            for (offset, value) in tail.iter().enumerate().rev() {
189                let slot = len + offset;
190                self.record(Step::Slot {
191                    id,
192                    slot,
193                    value: Some(value.clone()),
194                    len: slot + 1,
195                });
196            }
197        }
198        self.bump_revision();
199        Some(tail)
200    }
201
202    /// Change an entity's type in place, keeping its id and attributes.
203    ///
204    /// Reindexes `by_type` so `ids_of_type` reflects the new type immediately
205    /// -- the operation [`Model::insert`] already performs when an id is
206    /// reused with a different type, exposed here without requiring the
207    /// caller to reconstruct the whole entity.
208    ///
209    /// Returns the previous type name, or `None` if `id` does not name an
210    /// entity.
211    pub fn retype(
212        &mut self,
213        id: EntityId,
214        type_name: impl Into<std::sync::Arc<str>>,
215    ) -> Option<std::sync::Arc<str>> {
216        let recording = self.is_recording();
217        let entity = self.entity_mut(id)?;
218        let previous = entity.type_name.clone();
219        let new_name = type_name.into();
220        #[cfg(feature = "authored-dump")]
221        crate::authored_dump::record(&new_name, "retype");
222        if previous.eq_ignore_ascii_case(&new_name) {
223            entity.type_name = new_name;
224            if recording {
225                self.record(Step::Retype {
226                    id,
227                    type_name: previous.clone(),
228                    bucket: 0,
229                });
230            }
231            self.bump_revision();
232            return Some(previous);
233        }
234        entity.type_name = new_name.clone();
235
236        let old_key = previous.to_ascii_uppercase();
237        let new_key = new_name.to_ascii_uppercase();
238        if recording {
239            let bucket = self.bucket_position(&old_key, id);
240            self.record(Step::Retype {
241                id,
242                type_name: previous.clone(),
243                bucket,
244            });
245        }
246        self.unindex(&old_key, id);
247        self.by_type_mut().entry(new_key).or_default().push(id);
248        self.bump_revision();
249
250        Some(previous)
251    }
252
253    /// Remove an entity entirely.
254    ///
255    /// Returns the removed entity, or `None` if `id` was not present. Leaves
256    /// every reference to `id` from other entities dangling -- detect those
257    /// with [`Model::dangling_references`] after a batch of removals, the
258    /// same way a codec would detect them in a hand-edited file.
259    pub fn remove(&mut self, id: EntityId) -> Option<Entity> {
260        let recording = self.is_recording();
261        let built = self.derived_is_built();
262        let entity = self.take_entity(id)?;
263        self.note_write(id, built.then(|| Footprint::of(&entity)), None);
264        let key = entity.type_name.to_ascii_uppercase();
265        // From the end, like the undo of a batch: ids are unique, so the
266        // position is the same and the common one is near the end.
267        let position = self
268            .order_mut()
269            .iter()
270            .rposition(|existing| *existing == id);
271        if recording {
272            // `take_entity` already left storage, so the bucket and file
273            // positions are read from the indices, which still list `id`.
274            let bucket = self.bucket_position(&key, id);
275            let order = position.expect("an entity in storage is in file order");
276            self.record(Step::Insert {
277                id,
278                entity: entity.clone(),
279                order,
280                bucket,
281            });
282        }
283        self.unindex(&key, id);
284        if let Some(position) = position {
285            self.order_mut().remove(position);
286        }
287        self.bump_revision();
288        Some(entity)
289    }
290}
291
292/// The attribute count that holds slot `index`; panics, rather than wrap,
293/// for an index no entity can hold.
294fn slot_width(index: usize) -> usize {
295    index
296        .checked_add(1)
297        .expect("an attribute index must be below usize::MAX")
298}