refactor(napi): create_buffer_with_borrowed_data now accept not-null finalize_callback

This commit is contained in:
LongYinan 2020-12-24 15:45:59 +08:00
parent ac2f3bd00e
commit 2a6c452ce7
No known key found for this signature in database
GPG key ID: A3FFE134A3E20881
2 changed files with 9 additions and 11 deletions

View file

@ -318,12 +318,14 @@ impl Env {
/// Mostly the same with `create_buffer_with_data` /// Mostly the same with `create_buffer_with_data`
/// ///
/// Provided `finalize_callback` will be called when `Buffer` got dropped. /// Provided `finalize_callback` will be called when `Buffer` got dropped.
///
/// You can pass in `noop_finalize` if you have nothing to do in finalize phase.
pub unsafe fn create_buffer_with_borrowed_data<Hint, Finalize>( pub unsafe fn create_buffer_with_borrowed_data<Hint, Finalize>(
&self, &self,
data: *const u8, data: *const u8,
length: usize, length: usize,
hint: Hint, hint: Hint,
finalize_callback: Option<Finalize>, finalize_callback: Finalize,
) -> Result<JsBufferValue> ) -> Result<JsBufferValue>
where where
Finalize: FnOnce(Hint, Env), Finalize: FnOnce(Hint, Env),
@ -1129,8 +1131,6 @@ unsafe extern "C" fn raw_finalize_with_custom_callback<Hint, Finalize>(
) where ) where
Finalize: FnOnce(Hint, Env), Finalize: FnOnce(Hint, Env),
{ {
let (hint, maybe_callback) = *Box::from_raw(finalize_hint as *mut (Hint, Option<Finalize>)); let (hint, callback) = *Box::from_raw(finalize_hint as *mut (Hint, Finalize));
if let Some(callback) = maybe_callback { callback(hint, Env::from_raw(env));
callback(hint, Env::from_raw(env));
};
} }

View file

@ -33,10 +33,8 @@ pub fn create_borrowed_buffer_with_noop_finalize(env: Env) -> ContextlessResult<
let length = data.len(); let length = data.len();
let manually_drop = ManuallyDrop::new(data); let manually_drop = ManuallyDrop::new(data);
unsafe { unsafe { env.create_buffer_with_borrowed_data(data_ptr, length, manually_drop, noop_finalize) }
env.create_buffer_with_borrowed_data(data_ptr, length, manually_drop, Some(noop_finalize)) .map(|b| Some(b.into_raw()))
}
.map(|b| Some(b.into_raw()))
} }
#[contextless_function] #[contextless_function]
@ -51,9 +49,9 @@ pub fn create_borrowed_buffer_with_finalize(env: Env) -> ContextlessResult<JsBuf
data_ptr, data_ptr,
length, length,
manually_drop, manually_drop,
Some(|mut hint: ManuallyDrop<Vec<u8>>, _| { |mut hint: ManuallyDrop<Vec<u8>>, _| {
ManuallyDrop::drop(&mut hint); ManuallyDrop::drop(&mut hint);
}), },
) )
} }
.map(|b| Some(b.into_raw())) .map(|b| Some(b.into_raw()))