Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. #![allow(dead_code)]
  2.  
  3. struct Input<'a, T: USBKeyOut> {
  4. handlers: &'a mut [Box<dyn ProcessKeys<T>>],
  5. output: T,
  6. }
  7.  
  8. impl<T: USBKeyOut> Input<'_, T> {
  9.  
  10. fn handle_keys(&mut self) -> Result<(), String> {
  11. Ok(())
  12. }
  13. }
  14.  
  15. trait ProcessKeys<T: USBKeyOut> {
  16. fn process_keys(&mut self, output: &mut T) -> ();
  17. }
  18.  
  19. trait USBKeyOut {}
  20.  
  21. struct ToggleMacro<'a, T, F1: FnMut(&mut T)> {
  22. keycode: u32,
  23. on_toggle_on: F1,
  24. state: bool,
  25. phantom: core::marker::PhantomData<&'a T>,
  26. }
  27. impl<'a, T: USBKeyOut, F1: FnMut(&mut T)> ToggleMacro<'a, T, F1> {
  28. fn new(trigger: u32, on_toggle_on: F1) -> ToggleMacro<'a, T, F1> {
  29. ToggleMacro {
  30. keycode: trigger,
  31. on_toggle_on,
  32. state: false,
  33. phantom: core::marker::PhantomData,
  34. }
  35. }
  36. }
  37.  
  38. impl<T: USBKeyOut, F1: FnMut(&mut T)> ProcessKeys<T>
  39. for ToggleMacro<'_, T, F1>
  40. {
  41. fn process_keys(&mut self, output: &mut T) -> () {
  42. (self.on_toggle_on)(output);
  43. }
  44. }
  45.  
  46. #[cfg(test)]
  47. mod tests {
  48.  
  49. #[allow(unused_imports)]
  50. use crate::{Input, ProcessKeys, ToggleMacro, USBKeyOut};
  51.  
  52. struct KeyOutCatcher {
  53. }
  54. impl USBKeyOut for KeyOutCatcher {}
  55.  
  56. #[test]
  57. fn test_toggle_macro() {
  58. use core::cell::RefCell;
  59. let down_counter = RefCell::new(0);
  60. let _up_counter = RefCell::new(0);
  61. let t = ToggleMacro::new(
  62. 0xF0000u32,
  63. |_output: &mut KeyOutCatcher| {
  64. let mut dc = down_counter.borrow_mut();
  65. *dc += 1;
  66. },
  67. );
  68. let mut h = [Box::new(t) as Box<dyn ProcessKeys<KeyOutCatcher>>];
  69.  
  70. let mut input = Input{handlers: &mut h, output: KeyOutCatcher{}};
  71. input.handle_keys().unwrap();
  72. assert!(*down_counter.borrow() == 1);
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement