SHARE
TWEET

Untitled

a guest Oct 23rd, 2019 87 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::any::TypeId;
  2. use std::marker;
  3. use std::collections::HashMap;
  4.  
  5. #[derive(Clone, Copy)]
  6. struct Database<KC, DC> {
  7.     dbi: i32,
  8.     marker: marker::PhantomData<(KC, DC)>,
  9. }
  10.  
  11. impl<KC, DC> Database<KC, DC> {
  12.     fn new(dbi: i32) -> Database<KC, DC> {
  13.         Database { dbi, marker: marker::PhantomData }
  14.     }
  15. }
  16.  
  17. #[derive(Default)]
  18. struct DatabaseStore {
  19.     store: HashMap<String, (TypeId, TypeId, i32)>,
  20. }
  21.  
  22. impl DatabaseStore {
  23.     pub fn store_db<KC, DC>(&mut self, name: &str, db: Database<KC, DC>)
  24.     where KC: 'static, DC: 'static,
  25.     {
  26.         let kc = TypeId::of::<KC>();
  27.         let dc = TypeId::of::<DC>();
  28.         self.store.insert(name.to_owned(), (kc, dc, db.dbi));
  29.     }
  30.  
  31.     pub fn open_db<KC, DC>(&self, name: &str) -> Option<Database<KC, DC>>
  32.     where KC: 'static, DC: 'static,
  33.     {
  34.         let curr_kc = TypeId::of::<KC>();
  35.         let curr_dc = TypeId::of::<DC>();
  36.  
  37.         let (kc, dc, dbi) = self.store.get(name).cloned()?;
  38.        
  39.         if curr_kc == kc && curr_dc == dc {
  40.             Some(Database::new(dbi))
  41.         } else {
  42.             None
  43.         }
  44.     }
  45. }
  46.  
  47. fn main() {
  48.     let mut store = DatabaseStore::default();
  49.  
  50.     let db = Database::<i32, u64>::new(32);
  51.     store.store_db("i32-u64", db);
  52.  
  53.     let db = store.open_db::<u32, i64>("i32-u64");
  54.     assert!(db.is_none());
  55.  
  56.     let db = store.open_db::<u32, String>("i32-u64");
  57.     assert!(db.is_none());
  58.  
  59.     let db = store.open_db::<i32, u64>("i32-u64");
  60.     assert!(db.is_some());
  61. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top