1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//! Interop module containing traits and types to ease integration between Boa
//! and Rust.
/// Internal module only.
pub
/// A trait to convert a type into a JS function.
/// This trait does not require the implementing type to be `Copy`, which
/// can lead to undefined behaviour if it contains Garbage Collected objects.
///
/// This trait is implemented for functions with various signatures.
///
/// For example:
/// ```
/// # use boa_engine::{UnsafeIntoJsFunction, Context, JsValue, NativeFunction};
/// # let mut context = Context::default();
/// let f = |a: i32, b: i32| a + b;
/// let f = unsafe { f.into_js_function_unsafe(&mut context) };
/// let result = f
/// .call(
/// &JsValue::undefined(),
/// &[JsValue::from(1), JsValue::from(2)],
/// &mut context,
/// )
/// .unwrap();
/// assert_eq!(result, JsValue::new(3));
/// ```
///
/// Since the `IntoJsFunctionUnsafe` trait is implemented for `FnMut`, you can
/// also use closures directly:
/// ```
/// # use boa_engine::{UnsafeIntoJsFunction, Context, JsValue, NativeFunction};
/// # use std::cell::RefCell;
/// # use std::rc::Rc;
/// # let mut context = Context::default();
/// let mut x = Rc::new(RefCell::new(0));
/// // Because NativeFunction takes ownership of the closure,
/// // the compiler cannot be certain it won't outlive `x`, so
/// // we need to create a `Rc<RefCell>` and share it.
/// let f = unsafe {
/// let x = x.clone();
/// move |a: i32| *x.borrow_mut() += a
/// };
/// let f = unsafe { f.into_js_function_unsafe(&mut context) };
/// f.call(&JsValue::undefined(), &[JsValue::from(1)], &mut context)
/// .unwrap();
/// f.call(&JsValue::undefined(), &[JsValue::from(4)], &mut context)
/// .unwrap();
/// assert_eq!(*x.borrow(), 5);
/// ```
/// The safe equivalent of the [`UnsafeIntoJsFunction`] trait.
/// This can only be used on closures that have the `Copy` trait.
///
/// Since this function is implemented for `Fn(...)` closures, we can use
/// it directly when defining a function:
/// ```
/// # use boa_engine::{IntoJsFunctionCopied, Context, JsValue, NativeFunction};
/// # let mut context = Context::default();
/// let f = |a: i32, b: i32| a + b;
/// let f = f.into_js_function_copied(&mut context);
/// let result = f
/// .call(
/// &JsValue::undefined(),
/// &[JsValue::from(1), JsValue::from(2)],
/// &mut context,
/// )
/// .unwrap();
/// assert_eq!(result, JsValue::new(3));
/// ```
use crate::;
pub use *;
// Implement `IntoJsFunction` for functions with a various list of
// arguments.