napi@2.9.0
Core changes
as_object
for ClassInstance
You can use the ClassInstance
as Object
on the Rust side and manipulate it.
#[napi]
impl CanvasElement {
#[napi(constructor)]
pub fn new(mut env: Env, mut this: This, width: u32, height: u32) -> Result<Self> {
let ctx = CanvasRenderingContext2D::into_instance(
CanvasRenderingContext2D {
context: Context::new(width, height, ColorSpace::default())?,
},
env,
)?;
ctx.as_object(env).define_properties(&[
Property::new(FILL_STYLE_HIDDEN_NAME)?
.with_value(&env.create_string("#000")?)
.with_property_attributes(PropertyAttributes::Writable | PropertyAttributes::Configurable),
Property::new(STROKE_STYLE_HIDDEN_NAME)?
.with_value(&env.create_string("#000")?)
.with_property_attributes(PropertyAttributes::Writable | PropertyAttributes::Configurable),
])?;
env.adjust_external_memory((width * height * 4) as i64)?;
this.define_properties(&[Property::new("ctx")?
.with_value(&ctx)
.with_property_attributes(PropertyAttributes::Default)])?;
Ok(Self { width, height, ctx })
}
}
as_unknown
for Either
types
For the scenario that preserves original JavaScript values in Either
types and sets them into object property, and retrieves it back in the other place.
#[napi(getter)]
pub fn get_fill_style(&self, this: This) -> Result<Unknown> {
this.get_named_property_unchecked(FILL_STYLE_HIDDEN_NAME)
}
#[napi(setter, return_if_invalid)]
pub fn set_fill_style(
&mut self,
env: Env,
mut this: This,
fill_style: Either3<JsString, ClassInstance<CanvasGradient>, ClassInstance<CanvasPattern>>,
) -> Result<()> {
// ... some logic
let raw_fill_style = fill_style.as_unknown(env);
this.set(FILL_STYLE_HIDDEN_NAME, &raw_fill_style)?;
Ok(())
}
ToNapiValue
for f32
You can use f32
as the return type:
#[napi]
pub fn return_f32() -> f32 {
3.14
}
What's Changed
- fix(napi): segfault when
ThreadsafeFunction
's callback closure captures data by @messense in #1281 - feat(napi): implement as_object and validate for ClassInstance by @Brooooooklyn in #1284
- feat(napi): implement as_unknown and validate for Either types by @Brooooooklyn in #1285
- feat(napi): implement ToNapiValue for f32 by @Brooooooklyn in #1286
New Contributors
Full Changelog: https://github.com/napi-rs/napi-rs/compare/napi-derive@2.8.0...napi@2.9.0