use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, OnceLock};
use crate::document::{Document, ObjectId};
use crate::property::Property;
pub trait ObjectType: Send + Sync {
fn default_properties(&self) -> Vec<(String, Property, u32)> {
Vec::new()
}
fn property_meta(&self, name: &str) -> Option<(String, String)> {
let _ = name;
None
}
fn execute(&self, doc: &mut Document, id: ObjectId) {
let _ = (doc, id);
}
}
fn registry() -> &'static Mutex<BTreeMap<String, Arc<dyn ObjectType>>> {
static REGISTRY: OnceLock<Mutex<BTreeMap<String, Arc<dyn ObjectType>>>> = OnceLock::new();
REGISTRY.get_or_init(|| Mutex::new(BTreeMap::new()))
}
pub fn register(type_id: &str, behavior: Arc<dyn ObjectType>) {
registry()
.lock()
.unwrap()
.insert(type_id.to_string(), behavior);
}
pub fn get(type_id: &str) -> Option<Arc<dyn ObjectType>> {
registry().lock().unwrap().get(type_id).cloned()
}
pub fn is_registered(type_id: &str) -> bool {
registry().lock().unwrap().contains_key(type_id)
}
pub fn names() -> Vec<String> {
registry().lock().unwrap().keys().cloned().collect()
}
#[cfg(test)]
mod tests {
use super::*;
struct Counter;
impl ObjectType for Counter {
fn default_properties(&self) -> Vec<(String, Property, u32)> {
vec![("Count".to_string(), Property::Integer(0), 0)]
}
fn execute(&self, doc: &mut Document, id: ObjectId) {
let next = doc
.object(id)
.and_then(|o| o.properties.get("Count"))
.and_then(|p| match p {
Property::Integer(n) => Some(*n + 1),
_ => None,
})
.unwrap_or(1);
doc.set_property_raw(id, "Count", Property::Integer(next));
}
}
#[test]
fn registering_a_type_gives_defaults() {
register("Test::Counter", Arc::new(Counter));
assert!(is_registered("Test::Counter"));
let behavior = get("Test::Counter").unwrap();
assert_eq!(behavior.default_properties().len(), 1);
}
#[test]
fn a_registered_type_constructs_and_executes() {
register("Test::Counter2", Arc::new(Counter));
let mut doc = Document::new();
let id = doc.add_object("counter", "Test::Counter2");
assert_eq!(
doc.object(id).unwrap().properties.get("Count"),
Some(&Property::Integer(0))
);
doc.touch(id, false);
let _ = doc.recompute();
assert_eq!(
doc.object(id).unwrap().properties.get("Count"),
Some(&Property::Integer(1))
);
}
#[test]
fn unknown_type_has_no_behaviour() {
assert!(get("Nope::Nope").is_none());
}
}