Advertisement
Guest User

Untitled

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