feo_oop_engine/registration/
id.rs1use std::sync::{Arc, Mutex};
6
7#[derive(Debug, PartialEq, Eq, Hash)]
8#[derive(Clone)] pub struct ID(usize, IDSystem);
11
12impl PartialOrd for ID {
13 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
14 assert_eq!(self.1, other.1);
15 self.0.partial_cmp(&other.0)
16 }
17}
18
19impl Ord for ID {
20 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
21 assert_eq!(self.1, other.1);
22 self.0.cmp(&other.0)
23 }
24}
25
26impl std::fmt::Display for ID {
27 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28 write!(f, "{}", self.0)
29 }
30}
31
32impl ID{
33 pub fn get_value(&self) -> usize{ self.0 }
34 pub fn get_system(&self) -> IDSystem { self.1.clone() }
35}
36
37#[derive(Debug, Default, Clone)]
38pub struct IDSystem {
39 inner: Arc<Mutex<IDSystemInner>>
40}
41
42impl Eq for IDSystem {}
43
44impl PartialEq for IDSystem {
45 fn eq(&self, other: &Self) -> bool {
46 Arc::as_ptr(&self.inner) == Arc::as_ptr(&other.inner)
47 }
48}
49
50impl std::hash::Hash for IDSystem {
51 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
52 Arc::as_ptr(&self.inner).hash(state);
53 }
54}
55
56#[derive(Debug, Default)]
57struct IDSystemInner {
58 free: Vec<usize>,
59 current: usize,
60}
61
62impl IDSystem {
63
64 pub fn take(&self) -> ID {
65 let inner = self.inner.clone();
66 let inner = &mut inner.lock().unwrap();
67 match inner.free.pop() {
68 Some(id) => ID(id, self.clone()),
69 None => ID({inner.current += 1; inner.current}, self.clone())
70 }
71 }
72
73 pub fn free(&mut self, id: ID) {
74 self.inner.clone().lock().unwrap().free.push(id.0)
75 }
76}