use std::ffi::CString;
use quickjs::jsvalue::JsValue;
use quickjs::runtime::{self, JsContext, JsRuntime};
struct Engine {
runtime: *mut JsRuntime,
context: *mut JsContext,
}
impl Engine {
fn new() -> Engine {
unsafe {
let runtime = runtime::JS_NewRuntime();
let context = runtime::JS_NewContext(runtime);
Engine { runtime, context }
}
}
fn eval(&self, source: &str) -> JsValue {
let text = CString::new(source).expect("no NUL in a test source");
unsafe {
runtime::JS_Eval(
self.context,
text.as_ptr(),
source.len(),
c"<test>".as_ptr(),
0,
)
}
}
fn text(&self, source: &str) -> String {
let value = self.eval(source);
assert!(!value.is_exception(), "{source} threw");
self.to_text(value)
}
fn to_text(&self, value: JsValue) -> String {
unsafe {
let global = quickjs::objects::JS_GetGlobalObject(self.context);
quickjs::objects::JS_SetPropertyStr(self.context, global, c"__qc_tmp".as_ptr(), value);
runtime::release(global);
}
let text = self.eval("String(__qc_tmp)");
assert!(!text.is_exception(), "String(__qc_tmp) threw");
let c = unsafe {
quickjs::objects::JS_ToCStringLen2(self.context, std::ptr::null_mut(), text, 0)
};
let rendered = unsafe { std::ffi::CStr::from_ptr(c) }
.to_string_lossy()
.into_owned();
unsafe {
quickjs::objects::JS_FreeCString(self.context, c);
runtime::release(text);
}
rendered
}
fn write(&self, value: JsValue, flags: i32) -> Result<Vec<u8>, String> {
let mut size = 0usize;
let block =
unsafe { quickjs::bjson::JS_WriteObject(self.context, &mut size, value, flags) };
if block.is_null() {
return Err(self.pending_text());
}
let bytes = unsafe { std::slice::from_raw_parts(block, size) }.to_vec();
unsafe { quickjs::js_free(self.context, block.cast()) };
Ok(bytes)
}
fn read(&self, bytes: &[u8], flags: i32) -> JsValue {
unsafe { quickjs::bjson::JS_ReadObject(self.context, bytes.as_ptr(), bytes.len(), flags) }
}
fn round_trip(&self, source: &str, flags: i32) -> String {
let value = self.eval(source);
assert!(!value.is_exception(), "{source} threw");
let bytes = self
.write(value, flags)
.unwrap_or_else(|error| panic!("writing {source} failed: {error}"));
unsafe { runtime::release(value) };
let restored = self.read(&bytes, flags);
assert!(!restored.is_exception(), "reading {source} back threw");
self.to_text(restored)
}
fn pending_text(&self) -> String {
unsafe {
let exception = runtime::JS_GetException(self.context);
assert!(!exception.is_null(), "no pending exception");
self.to_text(exception)
}
}
}
impl Drop for Engine {
fn drop(&mut self) {
unsafe {
runtime::JS_FreeContext(self.context);
runtime::JS_FreeRuntime(self.runtime);
}
}
}
#[test]
fn primitives_round_trip() {
let engine = Engine::new();
for (source, expected) in [
("null", "null"),
("undefined", "undefined"),
("true", "true"),
("false", "false"),
("0", "0"),
("-7", "-7"),
("1.5", "1.5"),
("-0", "0"),
("NaN", "NaN"),
("-Infinity", "-Infinity"),
(r#""ab""#, "ab"),
("10n", "10"),
] {
assert_eq!(
engine.round_trip(source, 0),
expected,
"{source} round-tripped wrong"
);
}
}
#[test]
fn an_object_and_an_array_keep_their_contents() {
let engine = Engine::new();
assert_eq!(engine.round_trip("[1, 2, 3]", 0), "1,2,3");
assert_eq!(
engine.round_trip_json(r#"({x:1, y:2, if:3})"#),
r#"{"x":1,"y":2,"if":3}"#
);
assert_eq!(engine.round_trip_json("[1, , 2]"), "[1,null,2]");
}
#[test]
fn a_shared_object_stays_shared_with_reference_mode() {
let engine = Engine::new();
let source = "var shared = {v: 1}; [shared, shared]";
assert_eq!(engine.round_trip("({v: 1}).v", 0), "1");
let value = engine.eval(source);
let bytes = engine.write(value, quickjs::bjson::WRITE_OBJ_REFERENCE);
unsafe { runtime::release(value) };
let bytes = bytes.expect("writing a shared pair");
let restored = engine.read(&bytes, quickjs::bjson::READ_OBJ_REFERENCE);
assert!(!restored.is_exception(), "reading a shared pair back threw");
unsafe {
let global = quickjs::objects::JS_GetGlobalObject(engine.context);
quickjs::objects::JS_SetPropertyStr(
engine.context,
global,
c"__qc_scratch".as_ptr(),
restored,
);
runtime::release(global);
}
assert_eq!(
engine.text("__qc_scratch[0] === __qc_scratch[1] ? 'same' : 'copies'"),
"same"
);
}
#[test]
fn a_cycle_survives_and_a_cycle_without_reference_mode_is_refused() {
let engine = Engine::new();
let value = engine.eval("var o = {}; o.self = o; o");
assert!(!value.is_exception());
let plain = engine.write(value, 0);
unsafe { runtime::release(value) };
let message = plain.expect_err("a cycle without reference mode cannot be written");
assert!(message.contains("circular reference"), "{message}");
let value = engine.eval("var o = {}; o.self = o; o");
let bytes = engine.write(value, quickjs::bjson::WRITE_OBJ_REFERENCE);
unsafe { runtime::release(value) };
let bytes = bytes.expect("a cycle with reference mode writes");
let restored = engine.read(&bytes, quickjs::bjson::READ_OBJ_REFERENCE);
assert!(!restored.is_exception(), "reading a cycle back threw");
unsafe {
let global = quickjs::objects::JS_GetGlobalObject(engine.context);
quickjs::objects::JS_SetPropertyStr(
engine.context,
global,
c"__qc_scratch".as_ptr(),
restored,
);
runtime::release(global);
}
assert_eq!(
engine.text("__qc_scratch.self === __qc_scratch ? 'cycle' : 'broken'"),
"cycle"
);
}
#[test]
fn a_function_is_refused_like_any_unsupported_class() {
let engine = Engine::new();
let value = engine.eval("(function f(){})");
let written = engine.write(value, 0);
unsafe { runtime::release(value) };
let message = written.expect_err("a function has no serialisation");
assert!(message.contains("unsupported"), "{message}");
}
#[test]
fn an_array_buffer_keeps_its_resizability() {
let engine = Engine::new();
assert_eq!(
engine.round_trip("new ArrayBuffer(4).resizable ? 'yes' : 'no'", 0),
"no"
);
let value =
engine.eval("var b = new ArrayBuffer(4, {maxByteLength: 8}); new Uint8Array(b)[0] = 9; b");
let bytes = engine.write(value, 0).expect("writing a buffer");
unsafe { runtime::release(value) };
let restored = engine.read(&bytes, 0);
assert!(!restored.is_exception(), "reading a buffer back threw");
unsafe {
let global = quickjs::objects::JS_GetGlobalObject(engine.context);
quickjs::objects::JS_SetPropertyStr(
engine.context,
global,
c"__qc_scratch".as_ptr(),
restored,
);
runtime::release(global);
}
assert_eq!(
engine.text("__qc_scratch.byteLength + ' ' + __qc_scratch.maxByteLength + ' ' + __qc_scratch.resizable"),
"4 8 true"
);
assert_eq!(engine.text("new Uint8Array(__qc_scratch)[0]"), "9");
}
#[test]
fn a_typed_array_shares_the_buffer_it_was_built_from() {
let engine = Engine::new();
let value =
engine.eval("var ab = new ArrayBuffer(4); var v = new Uint8Array(ab, 2, 1); [ab, v]");
let bytes = engine
.write(value, quickjs::bjson::WRITE_OBJ_REFERENCE)
.expect("writing a buffer and a view");
unsafe { runtime::release(value) };
let restored = engine.read(&bytes, quickjs::bjson::READ_OBJ_REFERENCE);
assert!(!restored.is_exception());
unsafe {
let global = quickjs::objects::JS_GetGlobalObject(engine.context);
quickjs::objects::JS_SetPropertyStr(
engine.context,
global,
c"__qc_scratch".as_ptr(),
restored,
);
runtime::release(global);
}
assert_eq!(
engine.text("__qc_scratch[1].buffer === __qc_scratch[0] ? 'shared' : 'copied'"),
"shared"
);
assert_eq!(
engine.text("__qc_scratch[1].byteOffset + ' ' + __qc_scratch[1].length"),
"2 1"
);
}
#[test]
fn a_wrapper_round_trips_as_a_wrapper() {
let engine = Engine::new();
assert_eq!(engine.round_trip("new String('ab').valueOf()", 0), "ab");
let value = engine.eval("new Number(7)");
let bytes = engine.write(value, 0).expect("writing a wrapper");
unsafe { runtime::release(value) };
let restored = engine.read(&bytes, 0);
assert!(!restored.is_exception());
unsafe {
let global = quickjs::objects::JS_GetGlobalObject(engine.context);
quickjs::objects::JS_SetPropertyStr(
engine.context,
global,
c"__qc_scratch".as_ptr(),
restored,
);
runtime::release(global);
}
assert_eq!(
engine.text("(__qc_scratch instanceof Number) + ' ' + __qc_scratch.valueOf()"),
"true 7"
);
}
#[test]
fn a_date_round_trips_as_a_date() {
let engine = Engine::new();
let value = engine.eval("new Date(1234)");
let bytes = engine.write(value, 0).expect("writing a date");
unsafe { runtime::release(value) };
let restored = engine.read(&bytes, 0);
assert!(!restored.is_exception());
unsafe {
let global = quickjs::objects::JS_GetGlobalObject(engine.context);
quickjs::objects::JS_SetPropertyStr(
engine.context,
global,
c"__qc_scratch".as_ptr(),
restored,
);
runtime::release(global);
}
assert_eq!(
engine.text("(__qc_scratch instanceof Date) + ' ' + __qc_scratch.getTime()"),
"true 1234"
);
}
impl Engine {
fn round_trip_json(&self, source: &str) -> String {
let value = self.eval(source);
assert!(!value.is_exception(), "{source} threw");
let bytes = self
.write(value, 0)
.unwrap_or_else(|error| panic!("writing {source} failed: {error}"));
unsafe { runtime::release(value) };
let restored = self.read(&bytes, 0);
assert!(!restored.is_exception(), "reading {source} back threw");
unsafe {
let global = quickjs::objects::JS_GetGlobalObject(self.context);
quickjs::objects::JS_SetPropertyStr(
self.context,
global,
c"__qc_scratch".as_ptr(),
restored,
);
runtime::release(global);
}
self.text("JSON.stringify(__qc_scratch)")
}
}