[oden-js] Value construction functions
Makes building composites a lot easier
This commit is contained in:
parent
a0afae092a
commit
3ef1a8e806
1 changed files with 54 additions and 1 deletions
|
|
@ -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<K, V, const N: usize>(&self, props: [(K, V); N]) -> ValueResult
|
||||
where
|
||||
K: AsRef<str>,
|
||||
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<T>(&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<K, V, const N: usize>(&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<Value> {
|
||||
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<Value> {
|
||||
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)]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue