pub struct Context { /* private fields */ }Expand description
Context is a wrapper around a QuickJS Javascript context. It is the primary way to interact with the runtime.
For each Context instance a new instance of QuickJS
runtime is created. It means that it is safe to use
different contexts in different threads, but each
Context instance must be used only from a single thread.
Implementations§
Source§impl Context
impl Context
Sourcepub fn builder() -> ContextBuilder
pub fn builder() -> ContextBuilder
Create a ContextBuilder that allows customization of JS Runtime settings.
For details, see the methods on ContextBuilder.
let _context = quickjs_rusty::Context::builder()
.memory_limit(100_000)
.build()
.unwrap();Sourcepub fn new(memory_limit: Option<usize>) -> Result<Self, ContextError>
pub fn new(memory_limit: Option<usize>) -> Result<Self, ContextError>
Initialize a wrapper by creating a JSRuntime and JSContext.
pub fn set_console( &self, backend: Box<dyn ConsoleBackend>, ) -> Result<(), ExecutionError>
Sourcepub fn reset(self) -> Result<Self, ContextError>
pub fn reset(self) -> Result<Self, ContextError>
Reset the Javascript engine.
All state and callbacks will be removed.
pub unsafe fn context_raw(&self) -> *mut JSContext
Sourcepub fn global(&self) -> Result<OwnedJsObject, ExecutionError>
pub fn global(&self) -> Result<OwnedJsObject, ExecutionError>
Get the global object.
Sourcepub fn set_global<T>(&self, name: &str, value: T) -> Result<(), ExecutionError>where
T: ToOwnedJsValue,
pub fn set_global<T>(&self, name: &str, value: T) -> Result<(), ExecutionError>where
T: ToOwnedJsValue,
Set a global variable.
use quickjs_rusty::Context;
let context = Context::builder().build().unwrap();
context.set_global("someGlobalVariable", 42).unwrap();
let value = context.eval_as::<i32>("someGlobalVariable").unwrap();
assert_eq!(
value,
42,
);Sourcepub fn update_stack_top(&self)
pub fn update_stack_top(&self)
Execute the pending job in the event loop. Update the QuickJS runtime’s stack top reference to the current native stack pointer.
This should be called before any JS execution when entering from Rust, so that QuickJS measures the JS stack depth from the current position rather than from wherever the runtime was first created.
This is especially important in debug builds where Rust/C frames are significantly larger than in release builds.
Sourcepub fn set_max_stack_size(&self, size: usize)
pub fn set_max_stack_size(&self, size: usize)
Set the maximum JS stack size (in bytes).
The default is 1MB. In debug builds the QuickJS C interpreter frames are unoptimized and consume more native stack per JS call, so a larger limit (e.g. 4MB) may be required to run the same code that works fine in release builds.
Use 0 to disable the stack size limit entirely.
pub fn execute_pending_job(&self) -> Result<(), ExecutionError>
Sourcepub fn check_exception(
&self,
value: &OwnedJsValue,
) -> Result<(), ExecutionError>
pub fn check_exception( &self, value: &OwnedJsValue, ) -> Result<(), ExecutionError>
Check if the given value is an exception, and return the exception if it is.
Sourcepub fn resolve_value(
&self,
value: OwnedJsValue,
) -> Result<OwnedJsValue, ExecutionError>
pub fn resolve_value( &self, value: OwnedJsValue, ) -> Result<OwnedJsValue, ExecutionError>
If the given value is a promise, run the event loop until it is resolved, and return the final value.
Sourcepub fn eval(
&self,
code: &str,
resolve: bool,
) -> Result<OwnedJsValue, ExecutionError>
pub fn eval( &self, code: &str, resolve: bool, ) -> Result<OwnedJsValue, ExecutionError>
Evaluates Javascript code and returns the value of the final expression.
resolve: Whether to resolve the returned value if it is a promise. See more details as follows.
Promises:
If the evaluated code returns a Promise, the event loop
will be executed until the promise is finished. The final value of
the promise will be returned, or a ExecutionError::Exception if the
promise failed.
use quickjs_rusty::Context;
let context = Context::builder().build().unwrap();
let value = context.eval(" 1 + 2 + 3 ", false).unwrap();
assert_eq!(
value.to_int(),
Ok(6),
);
let value = context.eval(r#"
function f() { return 55 * 3; }
let y = f();
var x = y.toString() + "!"
x
"#, false).unwrap();
assert_eq!(
value.to_string().unwrap(),
"165!",
);Sourcepub fn eval_module(
&self,
code: &str,
resolve: bool,
) -> Result<OwnedJsValue, ExecutionError>
pub fn eval_module( &self, code: &str, resolve: bool, ) -> Result<OwnedJsValue, ExecutionError>
Evaluates Javascript code and returns the value of the final expression on module mode.
resolve: Whether to resolve the returned value if it is a promise. See more details as follows.
Promises:
If the evaluated code returns a Promise, the event loop
will be executed until the promise is finished. The final value of
the promise will be returned, or a ExecutionError::Exception if the
promise failed.
Returns: Return value will always be undefined on module mode.
use quickjs_rusty::Context;
let context = Context::builder().build().unwrap();
let value = context.eval_module("import {foo} from 'bar'; foo();", false).unwrap();Sourcepub fn eval_as<R>(&self, code: &str) -> Result<R, ExecutionError>
pub fn eval_as<R>(&self, code: &str) -> Result<R, ExecutionError>
Evaluates Javascript code and returns the value of the final expression as a Rust type.
Promises:
If the evaluated code returns a Promise, the event loop
will be executed until the promise is finished. The final value of
the promise will be returned, or a ExecutionError::Exception if the
promise failed.
use quickjs_rusty::{Context};
let context = Context::builder().build().unwrap();
let res = context.eval_as::<bool>(" 100 > 10 ");
assert_eq!(
res,
Ok(true),
);
let value: i32 = context.eval_as(" 10 + 10 ").unwrap();
assert_eq!(
value,
20,
);Sourcepub fn run_module(
&self,
filename: &str,
) -> Result<OwnedJsPromise, ExecutionError>
pub fn run_module( &self, filename: &str, ) -> Result<OwnedJsPromise, ExecutionError>
Evaluates Javascript code and returns the value of the final expression on module mode.
Promises:
If the evaluated code returns a Promise, the event loop
will be executed until the promise is finished. The final value of
the promise will be returned, or a ExecutionError::Exception if the
promise failed.
use quickjs_rusty::Context;
let context = Context::builder().build().unwrap();
let value = context.run_module("./module");Sourcepub fn set_module_loader(
&self,
module_loader_func: JSModuleLoaderFunc,
module_normalize: Option<JSModuleNormalizeFunc>,
opaque: *mut c_void,
)
pub fn set_module_loader( &self, module_loader_func: JSModuleLoaderFunc, module_normalize: Option<JSModuleNormalizeFunc>, opaque: *mut c_void, )
register module loader function, giving module name as input and return module code as output.
Sourcepub fn set_host_promise_rejection_tracker(
&self,
func: JSHostPromiseRejectionTracker,
opaque: *mut c_void,
)
pub fn set_host_promise_rejection_tracker( &self, func: JSHostPromiseRejectionTracker, opaque: *mut c_void, )
Set the host promise rejection tracker.
This function works not as expected, see more details in the example.
Sourcepub fn set_interrupt_handler(
&self,
func: JSInterruptHandler,
opaque: *mut c_void,
)
pub fn set_interrupt_handler( &self, func: JSInterruptHandler, opaque: *mut c_void, )
Set the interrupt handler.
Return != 0 if the JS code needs to be interrupted.
Sourcepub fn call_function(
&self,
function_name: &str,
args: impl IntoIterator<Item = impl ToOwnedJsValue>,
) -> Result<OwnedJsValue, ExecutionError>
pub fn call_function( &self, function_name: &str, args: impl IntoIterator<Item = impl ToOwnedJsValue>, ) -> Result<OwnedJsValue, ExecutionError>
Call a global function in the Javascript namespace.
Promises:
If the evaluated code returns a Promise, the event loop
will be executed until the promise is finished. The final value of
the promise will be returned, or a ExecutionError::Exception if the
promise failed.
use quickjs_rusty::Context;
let context = Context::builder().build().unwrap();
let res = context.call_function("encodeURIComponent", vec!["a=b"]).unwrap();
assert_eq!(
res.to_string(),
Ok("a%3Db".to_string()),
);Sourcepub fn create_callback<'a, F>(
&self,
callback: impl Callback<F> + 'static,
) -> Result<JsFunction, ExecutionError>
pub fn create_callback<'a, F>( &self, callback: impl Callback<F> + 'static, ) -> Result<JsFunction, ExecutionError>
Create a JS function that is backed by a Rust function or closure. Can be used to create a function and add it to an object.
The callback must satisfy several requirements:
- accepts 0 - 5 arguments
- each argument must be convertible from a JsValue
- must return a value
- the return value must either:
- be convertible to JsValue
- be a Result<T, E> where T is convertible to JsValue if Err(e) is returned, a Javascript exception will be raised
use quickjs_rusty::{Context, OwnedJsValue};
use std::collections::HashMap;
let context = Context::builder().build().unwrap();
// Register an object.
let mut obj = HashMap::<String, OwnedJsValue>::new();
let func = context
.create_callback(|a: i32, b: i32| a + b)
.unwrap();
let func = OwnedJsValue::from((unsafe{context.context_raw()}, func));
// insert add function into the object.
obj.insert("add".to_string(), func);
// insert the myObj to global.
context.set_global("myObj", obj).unwrap();
// Now we try out the 'myObj.add' function via eval.
let output = context.eval_as::<i32>("myObj.add( 3 , 4 ) ").unwrap();
assert_eq!(output, 7);Sourcepub fn add_callback<'a, F>(
&self,
name: &str,
callback: impl Callback<F> + 'static,
) -> Result<(), ExecutionError>
pub fn add_callback<'a, F>( &self, name: &str, callback: impl Callback<F> + 'static, ) -> Result<(), ExecutionError>
Add a global JS function that is backed by a Rust function or closure.
The callback must satisfy several requirements:
- accepts 0 - 5 arguments
- each argument must be convertible from a JsValue
- must return a value
- the return value must either:
- be convertible to JsValue
- be a Result<T, E> where T is convertible to JsValue if Err(e) is returned, a Javascript exception will be raised
use quickjs_rusty::Context;
let context = Context::builder().build().unwrap();
// Register a closue as a callback under the "add" name.
// The 'add' function can now be called from Javascript code.
context.add_callback("add", |a: i32, b: i32| { a + b }).unwrap();
// Now we try out the 'add' function via eval.
let output = context.eval_as::<i32>(" add( 3 , 4 ) ").unwrap();
assert_eq!(
output,
7,
);Sourcepub fn create_custom_callback(
&self,
callback: CustomCallback,
) -> Result<JsFunction, ExecutionError>
pub fn create_custom_callback( &self, callback: CustomCallback, ) -> Result<JsFunction, ExecutionError>
create a custom callback function