feat(napi): unsafe cast JsUnknown to the other JsValue
This commit is contained in:
parent
28d380344b
commit
5989a79f0d
3 changed files with 29 additions and 0 deletions
|
@ -607,4 +607,15 @@ impl JsUnknown {
|
|||
pub fn get_type(&self) -> Result<ValueType> {
|
||||
unsafe { type_of!(self.0.env, self.0.value) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// # Safety
|
||||
/// This function should be called after `JsUnknown::get_type`
|
||||
/// And the `V` must be match with the return value of `get_type`
|
||||
pub unsafe fn cast<V>(self) -> V
|
||||
where
|
||||
V: NapiValue,
|
||||
{
|
||||
V::from_raw_unchecked(self.0.env, self.0.value)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -47,3 +47,14 @@ test('strict_equals', (t) => {
|
|||
t.false(bindings.strictEquals(NaN, NaN))
|
||||
t.true(bindings.strictEquals(a, a))
|
||||
})
|
||||
|
||||
test('cast_unknown', (t) => {
|
||||
const f = {}
|
||||
const r = bindings.castUnknown(f)
|
||||
t.is(f, r)
|
||||
})
|
||||
|
||||
test('cast_unknown will not throw', (t) => {
|
||||
const f = 1
|
||||
t.notThrows(() => bindings.castUnknown(f))
|
||||
})
|
||||
|
|
|
@ -26,10 +26,17 @@ pub fn strict_equals(ctx: CallContext) -> Result<JsBoolean> {
|
|||
ctx.env.get_boolean(ctx.env.strict_equals(a, b)?)
|
||||
}
|
||||
|
||||
#[js_function(1)]
|
||||
pub fn cast_unknown(ctx: CallContext) -> Result<JsObject> {
|
||||
let arg: JsUnknown = ctx.get(0)?;
|
||||
Ok(unsafe { arg.cast::<JsObject>() })
|
||||
}
|
||||
|
||||
pub fn register_js(exports: &mut JsObject) -> Result<()> {
|
||||
exports.create_named_method("instanceof", instanceof)?;
|
||||
exports.create_named_method("isTypedarray", is_typedarray)?;
|
||||
exports.create_named_method("isDataview", is_dataview)?;
|
||||
exports.create_named_method("strictEquals", strict_equals)?;
|
||||
exports.create_named_method("castUnknown", cast_unknown)?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue