bevy_reflect/func/
into_function.rs1use crate::func::{DynamicFunction, ReflectFn, TypedFunction};
2
3pub trait IntoFunction<'env, Marker> {
23 fn into_function(self) -> DynamicFunction<'env>;
25}
26
27impl<'env, F, Marker1, Marker2> IntoFunction<'env, (Marker1, Marker2)> for F
28where
29 F: ReflectFn<'env, Marker1> + TypedFunction<Marker2> + Send + Sync + 'env,
30{
31 fn into_function(self) -> DynamicFunction<'env> {
32 DynamicFunction::new(move |args| self.reflect_call(args), Self::function_info())
33 }
34}
35
36#[cfg(test)]
37mod tests {
38 use super::*;
39 use crate::func::ArgList;
40
41 #[test]
42 fn should_create_dynamic_function_from_closure() {
43 let c = 23;
44 let func = (|a: i32, b: i32| a + b + c).into_function();
45 let args = ArgList::new().with_owned(25_i32).with_owned(75_i32);
46 let result = func.call(args).unwrap().unwrap_owned();
47 assert_eq!(result.try_downcast_ref::<i32>(), Some(&123));
48 }
49
50 #[test]
51 fn should_create_dynamic_function_from_function() {
52 fn add(a: i32, b: i32) -> i32 {
53 a + b
54 }
55
56 let func = add.into_function();
57 let args = ArgList::new().with_owned(25_i32).with_owned(75_i32);
58 let result = func.call(args).unwrap().unwrap_owned();
59 assert_eq!(result.try_downcast_ref::<i32>(), Some(&100));
60 }
61
62 #[test]
63 fn should_default_closure_name_to_none() {
64 let c = 23;
65 let func = (|a: i32, b: i32| a + b + c).into_function();
66 assert!(func.name().is_none());
67 }
68}