Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. use std::hash::Hash;
  2. use std::pin::Pin;
  3. use std::ptr::NonNull;
  4. use std::collections::HashMap;
  5. use std::marker::Unpin;
  6.  
  7. use std::ops::Deref;
  8. use std::ops::DerefMut;
  9.  
  10. trait MultiLookup {
  11. type FirstKey: Hash + Eq + Clone;
  12. type SecondKey: Hash + Eq + Clone;
  13.  
  14. fn index_one(&self) -> Self::FirstKey;
  15. fn index_two(&self) -> Self::SecondKey;
  16. }
  17.  
  18. struct MultiLookupMap<K>
  19. where K: MultiLookup {
  20. by_one: HashMap<K::FirstKey, Pin<Box<K>>>,
  21. by_two: HashMap<K::SecondKey, NonNull<K>>,
  22. }
  23.  
  24. impl<K> MultiLookupMap<K>
  25. where K: MultiLookup + Unpin {
  26. pub fn new() -> Self {
  27. MultiLookupMap{ by_one: HashMap::new(), by_two: HashMap::new() }
  28. }
  29.  
  30. pub fn insert(&mut self, val: K) {
  31. let idx_one = val.index_one();
  32. let idx_two = val.index_two();
  33. let mut pinned = Box::pin(val);
  34. self.by_one.insert(idx_one.clone(), pinned);
  35. //let mut inserted: &Pin<Box<K>> = self.by_one.get_mut(&idx_one).unwrap();
  36. let ptr = unsafe { Pin::deref_mut(self.by_one.get_mut(&idx_one).unwrap()) as *mut K};
  37. self.by_two.insert(idx_two, unsafe { NonNull::new_unchecked(ptr) });
  38. }
  39.  
  40. pub fn get(&self, key: &K::FirstKey) -> Option<&K> {
  41. match self.by_one.get(key) {
  42. Some(val) => Some(unsafe { val.deref() }),
  43. None => None,
  44. }
  45. }
  46.  
  47. pub fn get_second(&self, key: &K::SecondKey) -> Option<&K> {
  48. match self.by_two.get(key) {
  49. Some(val) => Some(unsafe{ val.as_ref() }),
  50. None => None,
  51. }
  52. }
  53. }
  54.  
  55. #[derive(Debug)]
  56. struct Example {
  57. first: usize,
  58. second: u32,
  59. val: bool,
  60. }
  61.  
  62. impl MultiLookup for Example {
  63. type FirstKey = usize;
  64. type SecondKey = u32;
  65.  
  66. fn index_one(&self) -> usize {
  67. self.first
  68. }
  69.  
  70. fn index_two(&self) -> u32 {
  71. self.second
  72. }
  73. }
  74.  
  75.  
  76.  
  77. fn main() {
  78. let ex1 = Example{first: 10, second: 20, val: true};
  79. let ex2 = Example{first:4, second: 12, val: false};
  80. let mut map: MultiLookupMap<Example> = MultiLookupMap::new();
  81. map.insert(ex1);
  82. map.insert(ex2);
  83. println!("{:?}", map.get(&10));
  84. println!("{:?}", map.get_second(&20));
  85. println!("{:?}", map.get(&4));
  86. println!("{:?}", map.get_second(&12));
  87.  
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement