Struct quickjs_rs::Context

source ·
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

source

pub fn builder() -> ContextBuilder

Create a ContextBuilder that allows customization of JS Runtime settings.

For details, see the methods on ContextBuilder.

let _context = quickjs_rs::Context::builder()
    .memory_limit(100_000)
    .build()
    .unwrap();
source

pub fn new() -> Result<Self, ContextError>

Create a new Javascript context with default settings.

Examples found in repository?
examples/eval.rs (line 4)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
pub fn main() {
    let context = Context::new().unwrap();

    let value = context.eval("1 + 2").unwrap();
    println!("js: 1 + 2 = {:?}", value);

    context
        .add_callback("myCallback", |a: i32, b: i32| a + b * b)
        .unwrap();

    let value = context
        .eval(
            r#"
       var x = myCallback(10, 20);
       x;
"#,
        )
        .unwrap();
    println!("js: callback = {:?}", value);
}
source

pub fn reset(self) -> Result<Self, ContextError>

Reset the Javascript engine.

All state and callbacks will be removed.

source

pub fn eval(&self, code: &str) -> Result<JsValue, ExecutionError>

Evaluates Javascript code and returns the value of the final expression.

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_rs::{Context, JsValue};
let context = Context::new().unwrap();

let value = context.eval(" 1 + 2 + 3 ");
assert_eq!(
    value,
    Ok(JsValue::Int(6)),
);

let value = context.eval(r#"
    function f() { return 55 * 3; }
    let y = f();
    var x = y.toString() + "!"
    x
"#);
assert_eq!(
    value,
    Ok(JsValue::String("165!".to_string())),
);
Examples found in repository?
examples/eval.rs (line 6)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
pub fn main() {
    let context = Context::new().unwrap();

    let value = context.eval("1 + 2").unwrap();
    println!("js: 1 + 2 = {:?}", value);

    context
        .add_callback("myCallback", |a: i32, b: i32| a + b * b)
        .unwrap();

    let value = context
        .eval(
            r#"
       var x = myCallback(10, 20);
       x;
"#,
        )
        .unwrap();
    println!("js: callback = {:?}", value);
}
source

pub fn eval_as<R>(&self, code: &str) -> Result<R, ExecutionError>where R: TryFrom<JsValue>, R::Error: Into<ValueError>,

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_rs::{Context};
let context = Context::new().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,
);
source

pub fn set_global<V>(&self, name: &str, value: V) -> Result<(), ExecutionError>where V: Into<JsValue>,

Set a global variable.

use quickjs_rs::{Context, JsValue};
let context = Context::new().unwrap();

context.set_global("someGlobalVariable", 42).unwrap();
let value = context.eval_as::<i32>("someGlobalVariable").unwrap();
assert_eq!(
    value,
    42,
);
source

pub fn call_function( &self, function_name: &str, args: impl IntoIterator<Item = impl Into<JsValue>> ) -> Result<JsValue, 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_rs::{Context, JsValue};
let context = Context::new().unwrap();

let res = context.call_function("encodeURIComponent", vec!["a=b"]);
assert_eq!(
    res,
    Ok(JsValue::String("a%3Db".to_string())),
);
source

pub fn add_callback<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_rs::{Context, JsValue};
let context = Context::new().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,
);
Examples found in repository?
examples/eval.rs (line 10)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
pub fn main() {
    let context = Context::new().unwrap();

    let value = context.eval("1 + 2").unwrap();
    println!("js: 1 + 2 = {:?}", value);

    context
        .add_callback("myCallback", |a: i32, b: i32| a + b * b)
        .unwrap();

    let value = context
        .eval(
            r#"
       var x = myCallback(10, 20);
       x;
"#,
        )
        .unwrap();
    println!("js: callback = {:?}", value);
}

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.