use super::PropertyValue;
use crate::compat::HashMap;
use crate::core::{CoreObject, MutexExt, ObjectId};
use core::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
#[derive(Debug, Clone)]
pub struct Object {
id: ObjectId,
class_name: &'static str,
ref_count: Arc<()>,
properties: Arc<Mutex<HashMap<String, PropertyValue>>>,
}
impl Object {
pub fn new(class_name: &'static str) -> Self {
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
Self {
id,
class_name,
ref_count: Arc::new(()),
properties: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn class_name(&self) -> &'static str {
self.class_name
}
pub fn id(&self) -> ObjectId {
self.id
}
pub fn strong_count(&self) -> usize {
Arc::strong_count(&self.ref_count)
}
pub fn set_property(&self, key: impl Into<String>, value: PropertyValue) {
self.properties.lock_guard().insert(key.into(), value);
}
pub fn property(&self, key: &str) -> Option<PropertyValue> {
self.properties.lock_guard().get(key).cloned()
}
pub fn remove_property(&self, key: &str) -> Option<PropertyValue> {
self.properties.lock_guard().remove(key)
}
pub fn property_keys(&self) -> Vec<String> {
self.properties.lock_guard().keys().cloned().collect()
}
}
impl CoreObject for Object {
fn id(&self) -> ObjectId {
self.id
}
fn set_id(&mut self, id: ObjectId) {
self.id = id;
}
fn type_name(&self) -> &'static str {
"Object"
}
}