Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. #![feature(core_intrinsics)]
  2.  
  3. fn main() {
  4. let mut e = EventManager::default();
  5. e.add_listener(&foo);
  6. }
  7.  
  8. trait IEventData {
  9. fn get_timestamp(&self) -> std::time::Duration;
  10. fn get_name() -> &'static str where Self: Sized;
  11. }
  12.  
  13.  
  14. trait IEventManager<'a> {
  15. fn add_listener<E, F>(&mut self, f: F) where E: 'static + IEventData + Sized, F: 'a + FnMut(&E);
  16. }
  17.  
  18. struct Event;
  19. impl IEventData for Event {
  20. fn get_timestamp(&self) -> std::time::Duration {
  21. std::time::Duration::from_millis(0)
  22. }
  23. fn get_name() -> &'static str {
  24. unsafe { std::intrinsics::type_name::<Self>() }
  25. }
  26. }
  27.  
  28. fn foo(e: &Event) {}
  29.  
  30. #[derive(Default)]
  31. struct EventManager<'a> {
  32. events: std::collections::VecDeque<Box<dyn IEventData>>,
  33. listeners: std::collections::HashMap<&'static str, Box<FnMut(&dyn std::any::Any) + 'a>>
  34. }
  35.  
  36. impl<'a> IEventManager<'a> for EventManager<'a> {
  37. fn add_listener<E, F>(&mut self, mut f: F) where E: 'static + IEventData + Sized, F: 'a + FnMut(&E) {
  38. let name = E::get_name();
  39. self.listeners.insert(name, Box::new(move |e| f(e.downcast_ref::<E>().unwrap())));
  40. }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement