mahf/components/utils/
debug.rs

1//! Components for debugging.
2
3use dyn_clone::DynClone;
4use serde::{Serialize, Serializer};
5use trait_set::trait_set;
6
7use crate::{component::ExecResult, components::Component, Problem, State};
8
9trait_set! {
10    /// Helper trait to allow cloning of debug functions.
11    pub trait DebugFn<P: Problem> = Fn(&P, &mut State<P>) + Send + Sync + DynClone + 'static;
12}
13
14dyn_clone::clone_trait_object!(<P: Problem> DebugFn<P>);
15
16/// Enables arbitrary `behaviour` for debugging purposes.
17///
18/// Note that this is for debugging purposes **only**.
19///
20/// The recommended way of implementing larger custom functionality is to implement
21/// [`Component`] for your struct.
22///
23/// # Serialization
24///
25/// The contents of the function passed to this component are **not** serialized.
26#[derive(derivative::Derivative)]
27#[derivative(Clone(bound = ""))]
28pub struct Debug<P: Problem>(Box<dyn DebugFn<P, Output = ()>>);
29
30impl<P: Problem> Debug<P> {
31    pub fn from_params(debug: impl DebugFn<P>) -> Self {
32        Self(Box::new(debug))
33    }
34
35    pub fn new(debug: impl DebugFn<P>) -> Box<dyn Component<P>> {
36        Box::new(Self::from_params(debug))
37    }
38}
39
40impl<P: Problem> Component<P> for Debug<P> {
41    fn execute(&self, problem: &P, state: &mut State<P>) -> ExecResult<()> {
42        self.0(problem, state);
43        Ok(())
44    }
45}
46
47impl<P: Problem> Serialize for Debug<P> {
48    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
49    where
50        S: Serializer,
51    {
52        serializer.serialize_unit_struct("Debug")
53    }
54}