JSValue

Struct JSValue 

Source
pub struct JSValue { /* private fields */ }
Expand description

A JavaScript value.

The base type for all JavaScript values, and polymorphic functions on them.

All values passed between Rust and JavaScriptCore will be boxed with a JSValue.

§Creating JS values

§JSON

§Retrieving Rust values

Implementations§

Source§

impl JSValue

Source

pub const unsafe fn from_raw(ctx: JSContextRef, raw: JSValueRef) -> Self

Create a new Self from its raw pointer directly.

§Safety

Ensure raw is valid.

Source

pub fn new_undefined(ctx: &JSContext) -> Self

Creates a JavaScript value of the undefined type.

  • ctx: The execution context to use.

Returns the unique undefined value.

let ctx = JSContext::default();

let v = JSValue::new_undefined(&ctx);
assert!(v.is_undefined());
§See also
Source

pub fn new_null(ctx: &JSContext) -> Self

Creates a JavaScript value of the null type.

  • ctx: The execution context to use.

Returns the unique null value.

let ctx = JSContext::default();

let v = JSValue::new_null(&ctx);
assert!(v.is_null());
§See also
Source

pub fn new_boolean(ctx: &JSContext, boolean: bool) -> Self

Creates a JavaScript value of the boolean type.

  • ctx: The execution context to use.
  • boolean: The bool to assign to the newly created JSValue.

Returns a JSValue of the boolean type, representing the value of boolean.

let ctx = JSContext::default();

let v = JSValue::new_boolean(&ctx, true /* or false */);
assert!(v.is_boolean());
§See also
Source

pub fn new_number(ctx: &JSContext, number: f64) -> Self

Creates a JavaScript value of the number type.

  • ctx: The execution context to use.
  • number: The f64 to assign to the newly created JSValue.

Returns a JSValue of the number type, representing the value of number.

let ctx = JSContext::default();

let v = JSValue::new_number(&ctx, 3.0f64);
assert!(v.is_number());

let v = JSValue::new_number(&ctx, 3.0f32 as f64);
assert!(v.is_number());

let v = JSValue::new_number(&ctx, 3 as f64);
assert!(v.is_number());
§See also
Source

pub fn new_string<S: Into<JSString>>(ctx: &JSContext, string: S) -> Self

Creates a JavaScript value of the string type.

  • ctx: The execution context to use.
  • string: A value that can be converted into a JSString to assign to the newly created JSValue. The newly created JSValue retains string, and releases it upon garbage collection.

Returns a JSValue of the string type, representing the value of string.

let ctx = JSContext::default();

let v = JSValue::new_string(&ctx, "abc");
assert!(v.is_string());
§See also
Source

pub fn new_symbol<S: Into<JSString>>(ctx: &JSContext, description: S) -> Self

Creates a JavaScript value of the symbol type.

  • ctx: The execution context to use.
  • description: A value that can be converted into a JSString to assign to the newly created JSValue.

Returns a JSValue of the symbol type, whose description matches the one provided.

let ctx = JSContext::default();

let v = JSValue::new_symbol(&ctx, "abc");
assert!(v.is_symbol());
§See also
Source

pub fn new_array( ctx: &JSContext, items: &[JSValue], ) -> Result<Self, JSException>

Creates a JavaScript value of the array type.

  • ctx: The execution context to use.
  • items: The array items as JSValues.

Returns a JSValue of the array type, otherwise an exception.

let ctx = JSContext::default();
let value = JSValue::new_array(
    &ctx,
    &[JSValue::new_number(&ctx, 1.), JSValue::new_number(&ctx, 2.)]
).unwrap();
assert!(value.is_array());
§See also
Source

pub unsafe fn new_typed_array_with_bytes( ctx: &JSContext, _bytes: &mut [u8], ) -> Result<Self, JSException>

Creates a JavaScript value of the TypedArray type.

  • ctx: The execution context to use.
  • bytes: The typed array bytes. The constructed TypedArray doesn’t copy the bytes, thus this method takes a &mut reference as it is possible to mutate the bytes via TypedArray or via Rust.

Returns a JSValue of the TypedArray type, otherwise an exception.

§Safety

bytes can be mutated both by Rust or JavaScript. There is no lock, no mutex, no guard. Be extremely careful when using this API. bytes aren’t copied, they are borrowed mutably by JavaScript. Dropping the value in Rust will clear them in JavaScript, and vice versa. Hence, this method is marked as unsafe.

§Example
let ctx = JSContext::default();
let mut bytes = vec![1u8, 2, 3, 4, 5];
let value = unsafe {
    JSValue::new_typed_array_with_bytes(&ctx, bytes.as_mut_slice())
        .unwrap()
};
§See also
Source

pub fn new_function<N>( ctx: &JSContext, name: N, function: JSObjectCallAsFunctionCallback, ) -> Self
where N: Into<JSString>,

Creates a JavaScript function where the function implementation is written in Rust.

  • ctx: The execution context to use.
  • name: The function name.
  • function: The function implementation.

The easiest way to declare such a function is to use the crate::function_callback procedural macro:

use javascriptcore::*;
let ctx = JSContext::default();

#[function_callback]
fn greet(
    ctx: &JSContext,
    _function: Option<&JSObject>,
    _this_object: Option<&JSObject>,
    arguments: &[JSValue],
) -> Result<JSValue, JSException> {
    if arguments.len() != 1 {
        return Err(JSValue::new_string(ctx, "must receive 1 argument").into());
    }

    let who = arguments[0].as_string()?;

    Ok(JSValue::new_string(&ctx, format!("Hello, {who}!")))
}

let greet = JSValue::new_function(&ctx, "greet", Some(greet)).as_object().unwrap();

let result = greet.call_as_function(
    None,
    &[JSValue::new_string(&ctx, "Gordon")],
).unwrap();

assert_eq!(result.as_string().unwrap().to_string(), "Hello, Gordon!");
Source

pub fn new_from_json<S: Into<JSString>>( ctx: &JSContext, string: S, ) -> Option<Self>

Creates a JavaScript value from a JSON formatted string.

  • ctx: The execution context to use.
  • string: A value that can be converted into a JSString containing the JSON string to be parsed.

Returns an Option with the JSValue containing the parsed value, or None if the input is invalid.

let ctx = JSContext::default();

let v = JSValue::new_from_json(&ctx, "true").expect("value");
assert!(v.is_boolean());
Source

pub fn to_json_string(&self, indent: u32) -> Result<JSString, JSException>

Creates a JavaScript string containing the JSON serialized representation of a JS value.

  • indent: The number of spaces to indent when nesting. If 0, the resulting JSON will not contains newlines. The size of the indent is clamped to 10 spaces.

Returns either a JSString with the result of serialization, or an exception if one was thrown.

let ctx = JSContext::default();

let v = JSValue::new_boolean(&ctx, false);
let s = v.to_json_string(0).unwrap();
assert_eq!(s, "false");
Source

pub fn get_type(&self) -> JSType

Returns a JavaScript value’s type.

Returns a value of type JSType that identifies value’s type.

let ctx = JSContext::default();

let v = JSValue::new_from_json(&ctx, "true").expect("value");
assert_eq!(v.get_type(), JSType::Boolean);

let v = JSValue::new_from_json(&ctx, "5.0").expect("value");
assert_eq!(v.get_type(), JSType::Number);

let v = JSValue::new_from_json(&ctx, "null").expect("value");
assert_eq!(v.get_type(), JSType::Null);
Source

pub fn is_undefined(&self) -> bool

Tests whether a JavaScript value’s type is the undefined type.

Returns true if value’s type is the undefined type, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_undefined(&ctx);
assert!(v.is_undefined());
§See also
Source

pub fn is_null(&self) -> bool

Tests whether a JavaScript value’s type is the null type.

Returns true if value’s type is the null type, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_from_json(&ctx, "null").expect("value");
assert!(v.is_null());
§See also
Source

pub fn is_boolean(&self) -> bool

Tests whether a JavaScript value’s type is the boolean type.

Returns true if value’s type is the boolean type, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_from_json(&ctx, "false").expect("value");
assert!(v.is_boolean());
§See also
Source

pub fn is_number(&self) -> bool

Tests whether a JavaScript value’s type is the number type.

Returns true if value’s type is the number type, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_from_json(&ctx, "-23").expect("value");
assert!(v.is_number());
§See also
Source

pub fn is_string(&self) -> bool

Tests whether a JavaScript value’s type is the string type.

Returns true if value’s type is the string type, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_from_json(&ctx, "\"Pueri et puellae\"").expect("value");
assert!(v.is_string());
§See also
Source

pub fn is_symbol(&self) -> bool

Tests whether a JavaScript value’s type is the symbol type.

Returns true if value’s type is the symbol type, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_symbol(&ctx, "abc");
assert!(v.is_symbol());
§See also
Source

pub fn is_object(&self) -> bool

Tests whether a JavaScript value’s type is the object type.

Returns true if value’s type is the object type, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_from_json(&ctx, "{\"id\": 123}").expect("valid object");
assert!(v.is_object());
§See also
Source

pub fn is_object_of_class(&self, js_class: &JSClass) -> bool

Tests whether a JavaScript value is an object with a given class in its class chain.

  • js_class: The JSClass to test against.

Returns true if value is an object and has jsClass in its class chain, otherwise false.

§See also
Source

pub fn is_array(&self) -> bool

Tests whether a JavaScript value is an array.

Returns true if value is an array, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_array(&ctx, &[JSValue::new_number(&ctx, 123.), JSValue::new_number(&ctx, 456.)]).unwrap();
assert!(v.is_array());

// But an object is not an array.
let v = JSValue::new_from_json(&ctx, "{\"id\": 123}").expect("valid object");
assert!(!v.is_array());
Source

pub fn is_typed_array(&self) -> bool

Tests whether a JavaScript value is a Typed Array.

let ctx = JSContext::default();

let value = JSValue::new_number(&ctx, 123.);
assert!(!value.is_typed_array());

let mut bytes = vec![1u8, 2, 3, 4, 5];
let value = unsafe {
    JSValue::new_typed_array_with_bytes(&ctx, bytes.as_mut_slice())
        .unwrap()
};
assert!(value.is_typed_array());
§See also
Source

pub fn is_date(&self) -> bool

Tests whether a JavaScript value is a date.

Returns true if value is a date, otherwise false.

Source

pub fn as_boolean(&self) -> bool

Converts a JavaScript value to boolean and returns the resulting boolean.

Returns the boolean result of conversion.

let ctx = JSContext::default();

let v = JSValue::new_boolean(&ctx, false);
assert_eq!(v.as_boolean(), false);
§See also
Source

pub fn as_number(&self) -> Result<f64, JSException>

Converts a JavaScript value to number and returns the resulting number.

Returns either the numeric result of conversion, or an exception if one was thrown.

let ctx = JSContext::default();

let v = JSValue::new_number(&ctx, 5.0);
let n = v.as_number().expect("valid number");
assert_eq!(n, 5.0);
§See also
Source

pub fn as_string(&self) -> Result<JSString, JSException>

Converts a JavaScript value to string and copies the result into a JavaScript string.

Returns either JSString with the result of conversion, or an exception if one was thrown. Ownership follows the Create Rule.

let ctx = JSContext::default();

let v = JSValue::new_string(&ctx, "Cave canem.");
let s = v.as_string().expect("valid string");
assert_eq!(s, "Cave canem.");
§See also
Source

pub fn as_object(&self) -> Result<JSObject, JSException>

Converts a JavaScript value to object and returns the resulting object.

Returns either the JSObject result of conversion, or an exception if one was thrown.

let ctx = JSContext::default();

let v = JSValue::new_from_json(&ctx, "{\"id\": 123}").expect("valid object");
let o = v.as_object().expect("object");
// We now have an object that we can inspect.
§See also
Source

pub fn as_typed_array(&self) -> Result<JSTypedArray, JSException>

Converts a JavaScript value to a Typed Array object and returns the resulting object.

Returns either the JSTypedArray result of conversion, or an exception if one was thrown.

let ctx = JSContext::default();
let array = evaluate_script(
    &ctx,
    "new Uint8Array([1, 2, 3, 4, 5])",
    None,
    "foo.js",
    1,
).unwrap();

assert!(array.is_typed_array());

let array = array.as_typed_array().unwrap();
§See also
Source

pub fn protect(&self)

Protects a JavaScript value from garbage collection.

Use this method when you want to store a JSValue in a global or on the heap, where the garbage collector will not be able to discover your reference to it.

A value may be protected multiple times and must be unprotected an equal number of times before becoming eligible for garbage collection.

§See also
Source

pub fn unprotect(&self)

Unprotects a JavaScript value from garbage collection.

A value may be protected multiple times and must be unprotected an equal number of times before becoming eligible for garbage collection.

§See also

Trait Implementations§

Source§

impl Debug for JSValue

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<&JSObject> for JSValue

Source§

fn from(object: &JSObject) -> Self

Converts to this type from the input type.
Source§

impl From<JSObject> for JSValue

Source§

fn from(object: JSObject) -> Self

Converts to this type from the input type.
Source§

impl From<JSValue> for JSValueRef

Source§

fn from(value: JSValue) -> Self

Converts to this type from the input type.
Source§

impl From<JSValue> for JSObjectRef

Source§

fn from(value: JSValue) -> Self

Converts to this type from the input type.
Source§

impl From<JSValue> for JSException

Source§

fn from(value: JSValue) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for JSValue

Implement partial equality checks for JSValue.

These are performed in the same manner as === (strict equality) in JavaScript.

Source§

fn eq(&self, other: &JSValue) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where 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 T
where 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 T
where U: Into<T>,

Source§

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 T
where U: TryFrom<T>,

Source§

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.