diff --git a/oden-js/src/context.rs b/oden-js/src/context.rs index 5eb6901a..a25eef51 100644 --- a/oden-js/src/context.rs +++ b/oden-js/src/context.rs @@ -1,6 +1,6 @@ use crate::{ callback::new_fn, conversion::RustFunction, module::Module, Atom, ClassID, Error, Promise, - Result, Runtime, Value, ValueRef, ValueResult, + Result, Runtime, TryIntoValue, Value, ValueRef, ValueResult, }; use bitflags::bitflags; use oden_js_sys as sys; @@ -177,6 +177,21 @@ impl ContextRef { self.check_exception(unsafe { sys::JS_NewObject(self.ctx) }) } + /// Construct a new value of type object with the specified properties. + pub fn new_object_props(&self, props: [(K, V); N]) -> ValueResult + where + K: AsRef, + V: TryIntoValue, + { + let mut obj = self.new_object()?; + for (k, v) in props.into_iter() { + let k: &str = k.as_ref(); + let v = v.try_into_value(self)?; + obj.set_property(self, k, &v)?; + } + Ok(obj) + } + /// Construct a new value from a boolean. pub fn new_bool(&self, value: T) -> ValueResult where @@ -249,6 +264,19 @@ impl ContextRef { self.check_exception(unsafe { sys::JS_NewArray(self.ctx) }) } + /// Construct a new array value with the given contents + pub fn new_array_values(&self, values: [V; N]) -> ValueResult + where + V: TryIntoValue, + { + let mut arr = self.new_array()?; + for (i, v) in values.into_iter().enumerate() { + let v = v.try_into_value(self)?; + arr.set_index(self, i.try_into().unwrap(), &v)?; + } + Ok(arr) + } + /// Construct a new value from a string. pub fn new_string(&self, value: &str) -> ValueResult { let c_value = CString::new(value)?; @@ -413,6 +441,31 @@ impl ContextRef { ) }) } + + /// Parse the specified JSON as data. `filename` is used for reporting + /// errors. + pub fn parse_json(&self, data: &str, filename: &str) -> Result { + let c_data = CString::new(data)?; + let c_filename = CString::new(filename)?; + + self.check_exception(unsafe { + sys::JS_ParseJSON(self.ctx, c_data.as_ptr(), data.len(), c_filename.as_ptr()) + }) + } + + /// Convert the value to a JSON string. + pub fn json_stringify(&self, value: &ValueRef) -> Result { + self.check_exception(unsafe { + let undef = sys::JSValue { + u: sys::JSValueUnion { + ptr: std::ptr::null_mut(), + }, + tag: sys::JS_TAG_UNDEFINED as i64, + }; + + sys::JS_JSONStringify(self.ctx, value.val, undef, undef) + }) + } } #[derive(Debug)]