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
JSValue::new_undefined()JSValue::new_null()JSValue::new_boolean()JSValue::new_number()JSValue::new_string()JSValue::new_typed_array_with_bytes()JSValue::new_function()JSValue::new_from_json()
§JSON
§Retrieving Rust values
Implementations§
Source§impl JSValue
impl JSValue
Sourcepub const unsafe fn from_raw(ctx: JSContextRef, raw: JSValueRef) -> Self
pub const unsafe fn from_raw(ctx: JSContextRef, raw: JSValueRef) -> Self
Sourcepub fn new_undefined(ctx: &JSContext) -> Self
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
Sourcepub fn new_null(ctx: &JSContext) -> Self
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
Sourcepub fn new_boolean(ctx: &JSContext, boolean: bool) -> Self
pub fn new_boolean(ctx: &JSContext, boolean: bool) -> Self
Creates a JavaScript value of the boolean type.
ctx: The execution context to use.boolean: Theboolto assign to the newly createdJSValue.
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
Sourcepub fn new_number(ctx: &JSContext, number: f64) -> Self
pub fn new_number(ctx: &JSContext, number: f64) -> Self
Creates a JavaScript value of the number type.
ctx: The execution context to use.number: Thef64to assign to the newly createdJSValue.
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
Sourcepub fn new_string<S: Into<JSString>>(ctx: &JSContext, string: S) -> Self
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 aJSStringto assign to the newly createdJSValue. The newly createdJSValueretainsstring, 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
Sourcepub fn new_symbol<S: Into<JSString>>(ctx: &JSContext, description: S) -> Self
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 aJSStringto assign to the newly createdJSValue.
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
Sourcepub fn new_array(
ctx: &JSContext,
items: &[JSValue],
) -> Result<Self, JSException>
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 asJSValues.
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
Sourcepub unsafe fn new_typed_array_with_bytes(
ctx: &JSContext,
_bytes: &mut [u8],
) -> Result<Self, JSException>
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 constructedTypedArraydoesn’t copy the bytes, thus this method takes a&mutreference as it is possible to mutate the bytes viaTypedArrayor 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
Sourcepub fn new_function<N>(
ctx: &JSContext,
name: N,
function: JSObjectCallAsFunctionCallback,
) -> Self
pub fn new_function<N>( ctx: &JSContext, name: N, function: JSObjectCallAsFunctionCallback, ) -> Self
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!");Sourcepub fn new_from_json<S: Into<JSString>>(
ctx: &JSContext,
string: S,
) -> Option<Self>
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 aJSStringcontaining 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());Sourcepub fn to_json_string(&self, indent: u32) -> Result<JSString, JSException>
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. If0, the resulting JSON will not contains newlines. The size of the indent is clamped to10spaces.
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");Sourcepub fn get_type(&self) -> JSType
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);Sourcepub fn is_undefined(&self) -> bool
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
Sourcepub fn is_null(&self) -> bool
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
Sourcepub fn is_boolean(&self) -> bool
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
Sourcepub fn is_number(&self) -> bool
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
Sourcepub fn is_string(&self) -> bool
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
Sourcepub fn is_symbol(&self) -> bool
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
Sourcepub fn is_object(&self) -> bool
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
Sourcepub fn is_object_of_class(&self, js_class: &JSClass) -> bool
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: TheJSClassto test against.
Returns true if value is an object and has jsClass in its
class chain, otherwise false.
§See also
Sourcepub fn is_array(&self) -> bool
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());Sourcepub fn is_typed_array(&self) -> bool
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
Sourcepub fn is_date(&self) -> bool
pub fn is_date(&self) -> bool
Tests whether a JavaScript value is a date.
Returns true if value is a date, otherwise false.
Sourcepub fn as_boolean(&self) -> bool
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
Sourcepub fn as_number(&self) -> Result<f64, JSException>
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
Sourcepub fn as_string(&self) -> Result<JSString, JSException>
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
Sourcepub fn as_object(&self) -> Result<JSObject, JSException>
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
Sourcepub fn as_typed_array(&self) -> Result<JSTypedArray, JSException>
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
Sourcepub fn protect(&self)
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.