Skip to main content

rcus_core/
entity.rs

1use std::cell::RefCell;
2use std::rc::Rc;
3use std::sync::atomic::{AtomicU64, Ordering};
4
5static NEXT_ENTITY_ID: AtomicU64 = AtomicU64::new(1);
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
8pub struct EntityId(u64);
9
10impl EntityId {
11    pub fn next() -> Self {
12        Self(NEXT_ENTITY_ID.fetch_add(1, Ordering::Relaxed))
13    }
14
15    pub fn raw(self) -> u64 {
16        self.0
17    }
18}
19
20#[derive(Clone)]
21pub struct Entity<T> {
22    id: EntityId,
23    value: Rc<RefCell<T>>,
24}
25
26impl<T> Entity<T> {
27    pub fn new(value: T) -> Self {
28        Self {
29            id: EntityId::next(),
30            value: Rc::new(RefCell::new(value)),
31        }
32    }
33
34    pub fn id(&self) -> EntityId {
35        self.id
36    }
37
38    pub fn get(&self) -> std::cell::Ref<'_, T> {
39        self.value.borrow()
40    }
41
42    pub fn update(&self, f: impl FnOnce(&mut T)) {
43        f(&mut self.value.borrow_mut());
44    }
45
46    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
47        f(&self.value.borrow())
48    }
49
50    pub fn replace(&self, value: T) {
51        *self.value.borrow_mut() = value;
52    }
53
54    pub fn ptr_eq(&self, other: &Self) -> bool {
55        Rc::ptr_eq(&self.value, &other.value)
56    }
57}