alchemy_lifecycle/reconciler/
key.rs

1//! Implements an auto-incrementing ID for Component instances.
2
3use std::sync::Mutex;
4
5use alchemy_styles::lazy_static;
6
7lazy_static! {
8    /// Global stretch instance id allocator.
9    pub(crate) static ref INSTANCE_ALLOCATOR: Mutex<Allocator> = Mutex::new(Allocator::new());
10}
11
12#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
13pub(crate) struct Id {
14    id: u32
15}
16
17pub(crate) struct Allocator {
18    new_id: u32
19}
20
21impl Allocator {
22    pub fn new() -> Self {
23        Allocator { new_id: 1 }
24    }
25
26    pub fn allocate(&mut self) -> Id {
27        let id = self.new_id;
28        self.new_id += 1;
29        Id { id: id }
30    }
31}
32
33/// Used as a key for Component storage. Component instances receive these
34/// in their constructor methods, and should retain them as a tool to update their 
35/// state.
36#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
37pub struct ComponentKey {
38    pub(crate) instance: Id,
39    pub(crate) local: Id,
40}
41
42impl ComponentKey {
43    /// A placeholder value, used purely for ensuring the diffing algorithm remains 
44    /// readable by reducing some unwrapping hell.
45    pub fn placeholder() -> ComponentKey {
46        ComponentKey {
47            instance: Id { id: 0 },
48            local: Id { id: 0 }
49        }
50    }
51}