|
| 1 | +//! This module defines wrappers for callbacks that can be registered with a state machine's |
| 2 | +//! [EventMonitor](crate::event::EventMonitor). Use the [Callback] wrapper if the state machine was |
| 3 | +//! generated with the Framec feature `thread_safe` set to `false` . Use the [CallbackSend] wrapper |
| 4 | +//! if the state machine was generated with `thread_safe=true`. |
| 5 | +
|
| 6 | +use std::sync::{Arc, Mutex}; |
| 7 | + |
| 8 | +/// Trait for wrappers around callback functions that have a name and accept a reference to `Arg` |
| 9 | +/// as an argument. |
| 10 | +pub trait IsCallback<Arg> { |
| 11 | + /// A name/ID associated with this callback to enable removing it later. |
| 12 | + fn name(&self) -> &str; |
| 13 | + |
| 14 | + /// Apply the wrapped function. |
| 15 | + fn apply(&mut self, arg: &Arg); |
| 16 | +} |
| 17 | + |
| 18 | +/// A named callback function that accepts a reference to `Arg` as an argument. Use this struct to |
| 19 | +/// wrap callbacks if the state machine was generated with `thread_safe=false`. |
| 20 | +pub struct Callback<Arg> { |
| 21 | + name: String, |
| 22 | + closure: Box<dyn FnMut(&Arg) + 'static>, |
| 23 | +} |
| 24 | + |
| 25 | +impl<Arg> Callback<Arg> { |
| 26 | + /// Create a new callback from the given closure. |
| 27 | + pub fn new(name: &str, f: impl FnMut(&Arg) + 'static) -> Self { |
| 28 | + Callback { |
| 29 | + closure: Box::new(f), |
| 30 | + name: name.to_string(), |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +impl<Arg> IsCallback<Arg> for Callback<Arg> { |
| 36 | + fn name(&self) -> &str { |
| 37 | + &self.name |
| 38 | + } |
| 39 | + fn apply(&mut self, arg: &Arg) { |
| 40 | + (*self.closure)(arg) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +/// A named callback function that accepts a reference to `Arg` as an argument and implements the |
| 45 | +/// [Send] trait. Use this struct to wrap callbacks if the state machine was generated with |
| 46 | +/// `thread_safe=true`. |
| 47 | +pub struct CallbackSend<Arg> { |
| 48 | + name: String, |
| 49 | + closure: Arc<Mutex<dyn FnMut(&Arg) + Send + 'static>>, |
| 50 | +} |
| 51 | + |
| 52 | +impl<Arg> CallbackSend<Arg> { |
| 53 | + /// Create a new callback from the given closure. |
| 54 | + pub fn new(name: &str, f: impl FnMut(&Arg) + Send + 'static) -> Self { |
| 55 | + CallbackSend { |
| 56 | + closure: Arc::new(Mutex::new(f)), |
| 57 | + name: name.to_string(), |
| 58 | + } |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +impl<Arg> IsCallback<Arg> for CallbackSend<Arg> { |
| 63 | + fn name(&self) -> &str { |
| 64 | + &self.name |
| 65 | + } |
| 66 | + fn apply(&mut self, arg: &Arg) { |
| 67 | + (*self.closure.lock().unwrap())(arg) |
| 68 | + } |
| 69 | +} |
0 commit comments