slint/examples/todo-mvc/rust/src/callback.rs
Florian Blasius 0870585c32
Added TodoMVC example (Rust mock version) (#5396)
* Added TodoMVC example (Rust mock version)

* TodoMVC: use visible-width instead of width for selection items

and format

* TodoMVC: layout fix for qt checkbox

* TdodoMVC: fix license issues in the example

* Update examples/todo_mvc/ui/views/task_list_view.slint

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* TdodoMVC: fix license issues in the example

* TodoMVC: code review changes

* TodoMVC: code review changes

* Update .reuse/dep5

Co-authored-by: Simon Hausmann <simon.hausmann@slint.dev>

* Update examples/todo_mvc/rust/src/adapters/navigation_adapter.rs

Co-authored-by: Simon Hausmann <simon.hausmann@slint.dev>

* Update examples/todo_mvc/rust/src/adapters/navigation_adapter.rs

Co-authored-by: Simon Hausmann <simon.hausmann@slint.dev>

* TodoMVC: refactor task list model (code review feedback)

* TodoMVC: code review feedback

* Update examples/todo-mvc/rust/src/mvc/controllers/task_list_controller.rs

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* TodoMVC: add missing link in dep5

* dep5 fix

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Simon Hausmann <simon.hausmann@slint.dev>
2024-06-13 13:05:44 +02:00

46 lines
1.2 KiB
Rust

// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: MIT
use std::cell::Cell;
type CallbackWrapper<Arguments, Result = ()> =
Cell<Option<Box<dyn FnMut(&Arguments, &mut Result)>>>;
pub struct Callback<Arguments: ?Sized, Result = ()> {
callback: CallbackWrapper<Arguments, Result>,
}
impl<Arguments: ?Sized, Res> Default for Callback<Arguments, Res> {
fn default() -> Self {
Self { callback: Default::default() }
}
}
impl<Arguments: ?Sized, Result: Default> Callback<Arguments, Result> {
pub fn on(&self, mut f: impl FnMut(&Arguments) -> Result + 'static) {
self.callback.set(Some(Box::new(move |a: &Arguments, r: &mut Result| *r = f(a))));
}
pub fn invoke(&self, a: &Arguments) -> Result {
let mut result = Result::default();
if let Some(mut callback) = self.callback.take() {
callback(a, &mut result);
self.callback.set(Some(callback));
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_invoke() {
let callback: Callback<(i32, i32), i32> = Callback::default();
callback.on(|(a, b)| a + b);
assert_eq!(callback.invoke(&(3, 2)), 5);
}
}