y_engine/util/
registry.rs1use core::panic;
2use std::hash::Hash;
3
4use rustc_hash::FxHashMap;
5
6pub struct Registry<ID: Hash + Eq, T> {
24 items: FxHashMap<ID, T>,
25}
26
27impl<ID: Hash + Eq, T> Default for Registry<ID, T> {
28 fn default() -> Self {
29 Self {
30 items: FxHashMap::default(),
31 }
32 }
33}
34
35impl<ID: Hash + Eq, T> Registry<ID, T> {
36 pub fn new() -> Self {
37 Self::default()
38 }
39
40 pub fn insert(&mut self, id: ID, item: T) {
42 if self.items.insert(id, item).is_some() {
43 panic!("Item collision in registry.");
44 }
45 }
46
47 pub fn overwrite(&mut self, id: ID, item: T) {
49 if self.items.insert(id, item).is_none() {
50 panic!("Item not found in registry but overwrite was called.");
51 }
52 }
53
54 pub fn insert_or_overwrite(&mut self, id: ID, item: T) {
56 self.items.insert(id, item);
57 }
58
59 pub fn remove(&mut self, id: &ID) -> T {
61 self.items.remove(id).expect("Item not found in registry.")
62 }
63
64 pub fn try_remove(&mut self, id: &ID) -> Option<T> {
66 self.items.remove(id)
67 }
68
69 pub fn get(&self, id: &ID) -> &T {
71 self.items.get(id).expect("Item not found in registry.")
72 }
73
74 pub fn try_get(&self, id: &ID) -> Option<&T> {
76 self.items.get(id)
77 }
78
79 pub fn exists(&self, id: &ID) -> bool {
81 self.items.contains_key(id)
82 }
83}