Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Library, can't be changed
- // In this particular case, this is a CPU emulator
- trait ExtLibInterface {
- fn run<C: ExtLibCallbacks>(&mut self, callbacks: &mut C);
- fn get_var(&mut self) -> u32;
- }
- struct ExtLib {}
- impl ExtLibInterface for ExtLib {
- fn run<C: ExtLibCallbacks>(&mut self, callbacks: &mut C) {
- // Lots of stuff here, but skip directly to the callbacks
- callbacks.eventhandler(self)
- }
- fn get_var(&mut self) -> u32 {
- 13
- }
- }
- impl ExtLib {
- fn new() -> ExtLib {
- ExtLib {}
- }
- fn run<C: ExtLibCallbacks>(&mut self, callbacks: &mut C) {
- // Lots of stuff here, but skip directly to the callbacks
- callbacks.eventhandler(self)
- }
- }
- trait ExtLibCallbacks {
- // Note thet it uses impl here...
- fn eventhandler(&mut self, lib: &mut impl ExtLibInterface);
- }
- // My device,
- // In this case, it's an emulator of a computer, with peripherals
- struct MyLib {
- // The reference to extlib can be wrapped within a container, like Box/Rc...
- extlib: ExtLib,
- }
- impl MyLib {
- fn new() -> MyLib {
- MyLib {
- extlib: ExtLib::new(),
- }
- }
- fn run(&mut self) {
- let lib = &mut self.extlib;
- lib.run(self)
- }
- }
- impl ExtLibCallbacks for MyLib {
- fn eventhandler(&mut self, _lib: &mut impl ExtLibInterface) {
- // want mutable access to self here, and possibility to call methods in
- // mylib expecting extlib to be available
- // In this case, I have mutable acess to the _lib variable, which would
- // mean it should be safe to "put it back" to the struct during the
- // lifetime of this method.
- println!("eventhandler called {}", self.extlib.get_var());
- // Also, I want to be able to call other methods in self, that depends
- // on extlib, similar to adding guards for depth and calling self.run()
- // recursively.
- }
- }
- // Main code
- fn main() {
- let mut lib = MyLib::new();
- lib.run();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement