use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;
use super::observer::{self, PropertyId};
pub struct Property<T> {
id: PropertyId,
value: Rc<RefCell<T>>,
}
impl<T> Property<T> {
pub fn new(value: T) -> Self {
Self {
id: observer::register_property(),
value: Rc::new(RefCell::new(value)),
}
}
pub fn id(&self) -> PropertyId {
self.id
}
pub fn peek(&self) -> T
where
T: Clone,
{
self.value.borrow().clone()
}
pub fn get(&self) -> T
where
T: Clone,
{
observer::track(self.id);
self.value.borrow().clone()
}
pub fn set(&self, value: T)
where
T: PartialEq,
{
let changed = {
let mut cell = self.value.borrow_mut();
if *cell == value {
false
} else {
*cell = value;
true
}
};
if changed {
observer::trigger(self.id);
}
}
pub fn update(&self, f: impl FnOnce(&mut T)) {
{
let mut cell = self.value.borrow_mut();
f(&mut cell);
}
observer::trigger(self.id);
}
}
impl<T> Clone for Property<T> {
fn clone(&self) -> Self {
Self {
id: self.id,
value: Rc::clone(&self.value),
}
}
}
impl<T: PartialEq> PartialEq for Property<T> {
fn eq(&self, other: &Self) -> bool {
*self.value.borrow() == *other.value.borrow()
}
}
impl<T> fmt::Debug for Property<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Property")
.field("id", &self.id)
.finish_non_exhaustive()
}
}