use crate::entity::Entity;
use crate::model::Model;
use crate::value::{EntityId, Value};
impl Model {
pub fn set_attribute(&mut self, id: EntityId, index: usize, value: Value) -> Option<Value> {
let entity = self.entity_mut(id)?;
if index >= entity.attributes.len() {
entity.attributes.resize(index + 1, Value::Null);
}
let previous = std::mem::replace(&mut entity.attributes[index], value);
self.bump_revision();
Some(previous)
}
pub fn set_attributes(
&mut self,
id: EntityId,
edits: impl IntoIterator<Item = (usize, Value)>,
) -> Option<Vec<Value>> {
let entity = self.entity_mut(id)?;
let mut previous = Vec::new();
for (index, value) in edits {
if index >= entity.attributes.len() {
entity.attributes.resize(index + 1, Value::Null);
}
previous.push(std::mem::replace(&mut entity.attributes[index], value));
}
self.bump_revision();
Some(previous)
}
pub fn retype(
&mut self,
id: EntityId,
type_name: impl Into<std::sync::Arc<str>>,
) -> Option<std::sync::Arc<str>> {
let entity = self.entity_mut(id)?;
let previous = entity.type_name.clone();
let new_name = type_name.into();
#[cfg(feature = "authored-dump")]
crate::authored_dump::record(&new_name, "retype");
if previous.eq_ignore_ascii_case(&new_name) {
entity.type_name = new_name;
self.bump_revision();
return Some(previous);
}
entity.type_name = new_name.clone();
let old_key = previous.to_ascii_uppercase();
let new_key = new_name.to_ascii_uppercase();
if let Some(ids) = self.by_type_mut().get_mut(&old_key) {
ids.retain(|existing| *existing != id);
}
self.by_type_mut().entry(new_key).or_default().push(id);
self.bump_revision();
Some(previous)
}
pub fn remove(&mut self, id: EntityId) -> Option<Entity> {
let entity = self.entities_mut().remove(&id)?;
let key = entity.type_name.to_ascii_uppercase();
if let Some(ids) = self.by_type_mut().get_mut(&key) {
ids.retain(|existing| *existing != id);
}
self.order_mut().retain(|existing| *existing != id);
self.bump_revision();
Some(entity)
}
fn entity_mut(&mut self, id: EntityId) -> Option<&mut Entity> {
self.entities_mut().get_mut(&id)
}
}