| 1 | // Copyright © SixtyFPS GmbH <info@slint.dev> |
| 2 | // SPDX-License-Identifier: MIT |
| 3 | |
| 4 | use std::cell::Cell; |
| 5 | |
| 6 | type CallbackWrapper<Arguments, Result = ()> = |
| 7 | Cell<Option<Box<dyn FnMut(&Arguments, &mut Result)>>>; |
| 8 | |
| 9 | pub struct Callback<Arguments: ?Sized, Result = ()> { |
| 10 | callback: CallbackWrapper<Arguments, Result>, |
| 11 | } |
| 12 | |
| 13 | impl<Arguments: ?Sized, Res> Default for Callback<Arguments, Res> { |
| 14 | fn default() -> Self { |
| 15 | Self { callback: Default::default() } |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | impl<Arguments: ?Sized, Result: Default> Callback<Arguments, Result> { |
| 20 | pub fn on(&self, mut f: impl FnMut(&Arguments) -> Result + 'static) { |
| 21 | self.callback.set(val:Some(Box::new(move |a: &Arguments, r: &mut Result| *r = f(a)))); |
| 22 | } |
| 23 | |
| 24 | pub fn invoke(&self, a: &Arguments) -> Result { |
| 25 | let mut result: Result = Result::default(); |
| 26 | |
| 27 | if let Some(mut callback: Box) = self.callback.take() { |
| 28 | callback(a, &mut result); |
| 29 | self.callback.set(val:Some(callback)); |
| 30 | } |
| 31 | |
| 32 | result |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | #[cfg (test)] |
| 37 | mod tests { |
| 38 | use super::*; |
| 39 | |
| 40 | #[test ] |
| 41 | fn test_invoke() { |
| 42 | let callback: Callback<(i32, i32), i32> = Callback::default(); |
| 43 | callback.on(|(a, b)| a + b); |
| 44 | assert_eq!(callback.invoke(&(3, 2)), 5); |
| 45 | } |
| 46 | } |
| 47 | |