rcus-core 0.1.0

Core types for rcus: retained view tree, style, input, and the host bridge protocol
Documentation
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};

static NEXT_ENTITY_ID: AtomicU64 = AtomicU64::new(1);

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct EntityId(u64);

impl EntityId {
    pub fn next() -> Self {
        Self(NEXT_ENTITY_ID.fetch_add(1, Ordering::Relaxed))
    }

    pub fn raw(self) -> u64 {
        self.0
    }
}

#[derive(Clone)]
pub struct Entity<T> {
    id: EntityId,
    value: Rc<RefCell<T>>,
}

impl<T> Entity<T> {
    pub fn new(value: T) -> Self {
        Self {
            id: EntityId::next(),
            value: Rc::new(RefCell::new(value)),
        }
    }

    pub fn id(&self) -> EntityId {
        self.id
    }

    pub fn get(&self) -> std::cell::Ref<'_, T> {
        self.value.borrow()
    }

    pub fn update(&self, f: impl FnOnce(&mut T)) {
        f(&mut self.value.borrow_mut());
    }

    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        f(&self.value.borrow())
    }

    pub fn replace(&self, value: T) {
        *self.value.borrow_mut() = value;
    }

    pub fn ptr_eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.value, &other.value)
    }
}