bevy_reflect/func/
into_function_mut.rs1use crate::func::{DynamicFunctionMut, ReflectFnMut, TypedFunction};
2
3pub trait IntoFunctionMut<'env, Marker> {
26 fn into_function_mut(self) -> DynamicFunctionMut<'env>;
28}
29
30impl<'env, F, Marker1, Marker2> IntoFunctionMut<'env, (Marker1, Marker2)> for F
31where
32 F: ReflectFnMut<'env, Marker1> + TypedFunction<Marker2> + 'env,
33{
34 fn into_function_mut(mut self) -> DynamicFunctionMut<'env> {
35 DynamicFunctionMut::new(
36 move |args| self.reflect_call_mut(args),
37 Self::function_info(),
38 )
39 }
40}
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45 use crate::func::{ArgList, IntoFunction};
46
47 #[test]
48 fn should_create_dynamic_function_mut_from_closure() {
49 let c = 23;
50 let func = (|a: i32, b: i32| a + b + c).into_function();
51 let args = ArgList::new().with_owned(25_i32).with_owned(75_i32);
52 let result = func.call(args).unwrap().unwrap_owned();
53 assert_eq!(result.try_downcast_ref::<i32>(), Some(&123));
54 }
55
56 #[test]
57 fn should_create_dynamic_function_mut_from_closure_with_mutable_capture() {
58 let mut total = 0;
59 let func = (|a: i32, b: i32| total = a + b).into_function_mut();
60 let args = ArgList::new().with_owned(25_i32).with_owned(75_i32);
61 func.call_once(args).unwrap();
62 assert_eq!(total, 100);
63 }
64
65 #[test]
66 fn should_create_dynamic_function_mut_from_function() {
67 fn add(a: i32, b: i32) -> i32 {
68 a + b
69 }
70
71 let mut func = add.into_function_mut();
72 let args = ArgList::new().with_owned(25_i32).with_owned(75_i32);
73 let result = func.call(args).unwrap().unwrap_owned();
74 assert_eq!(result.try_downcast_ref::<i32>(), Some(&100));
75 }
76
77 #[test]
78 fn should_default_closure_name_to_none() {
79 let mut total = 0;
80 let func = (|a: i32, b: i32| total = a + b).into_function_mut();
81 assert!(func.name().is_none());
82 }
83}