Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. // Library, can't be changed
  2. // In this particular case, this is a CPU emulator
  3.  
  4. trait ExtLibInterface {
  5. fn run<C: ExtLibCallbacks>(&mut self, callbacks: &mut C);
  6.  
  7. fn get_var(&mut self) -> u32;
  8. }
  9.  
  10. struct ExtLib {}
  11.  
  12. impl ExtLibInterface for ExtLib {
  13. fn run<C: ExtLibCallbacks>(&mut self, callbacks: &mut C) {
  14. // Lots of stuff here, but skip directly to the callbacks
  15. callbacks.eventhandler(self)
  16. }
  17.  
  18. fn get_var(&mut self) -> u32 {
  19. 13
  20. }
  21. }
  22.  
  23. impl ExtLib {
  24. fn new() -> ExtLib {
  25. ExtLib {}
  26. }
  27.  
  28. fn run<C: ExtLibCallbacks>(&mut self, callbacks: &mut C) {
  29. // Lots of stuff here, but skip directly to the callbacks
  30. callbacks.eventhandler(self)
  31. }
  32. }
  33.  
  34. trait ExtLibCallbacks {
  35. // Note thet it uses impl here...
  36. fn eventhandler(&mut self, lib: &mut impl ExtLibInterface);
  37. }
  38.  
  39. // My device,
  40. // In this case, it's an emulator of a computer, with peripherals
  41.  
  42. struct MyLib {
  43. // The reference to extlib can be wrapped within a container, like Box/Rc...
  44. extlib: ExtLib,
  45. }
  46.  
  47. impl MyLib {
  48. fn new() -> MyLib {
  49. MyLib {
  50. extlib: ExtLib::new(),
  51. }
  52. }
  53.  
  54. fn run(&mut self) {
  55. let lib = &mut self.extlib;
  56. lib.run(self)
  57. }
  58. }
  59.  
  60. impl ExtLibCallbacks for MyLib {
  61. fn eventhandler(&mut self, _lib: &mut impl ExtLibInterface) {
  62. // want mutable access to self here, and possibility to call methods in
  63. // mylib expecting extlib to be available
  64.  
  65. // In this case, I have mutable acess to the _lib variable, which would
  66. // mean it should be safe to "put it back" to the struct during the
  67. // lifetime of this method.
  68.  
  69. println!("eventhandler called {}", self.extlib.get_var());
  70.  
  71. // Also, I want to be able to call other methods in self, that depends
  72. // on extlib, similar to adding guards for depth and calling self.run()
  73. // recursively.
  74. }
  75. }
  76.  
  77. // Main code
  78.  
  79. fn main() {
  80. let mut lib = MyLib::new();
  81.  
  82. lib.run();
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement