simple_db_rust/btree/
catalog.rs

1use std::{cell::RefCell, collections::HashMap, rc::Rc};
2
3use log::debug;
4use std::{mem, sync::Once};
5
6use super::table::BTreeTable;
7
8pub struct Catalog {
9    map: HashMap<Key, Value>,
10}
11
12type Key = i32;
13type Value = Rc<RefCell<BTreeTable>>;
14
15impl Catalog {
16    fn new() -> Self {
17        Self {
18            map: HashMap::new(),
19        }
20    }
21
22    pub fn global() -> &'static mut Self {
23        // Initialize it to a null value
24        static mut SINGLETON: *mut Catalog = 0 as *mut Catalog;
25        static ONCE: Once = Once::new();
26
27        ONCE.call_once(|| {
28            // Make it
29            let singleton = Self::new();
30
31            unsafe {
32                // Put it in the heap so it can outlive this call
33                SINGLETON = mem::transmute(Box::new(singleton));
34            }
35        });
36
37        unsafe {
38            // Now we give out a copy of the data that is safe to use
39            // concurrently.
40            SINGLETON.as_mut().unwrap()
41        }
42    }
43
44    pub fn get_table(&self, key: &Key) -> Option<&Value> {
45        self.map.get(key)
46    }
47
48    pub fn add_table(&mut self, file: Value) {
49        debug!("add table to catalog, id: {}", file.borrow().get_id());
50        self.map.insert(file.borrow().get_id(), Rc::clone(&file));
51    }
52}