Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions runtime/src/method_call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -974,6 +974,10 @@ impl MethodCall {

let mut buffer_args = Vec::new();
let mut reference_arrays = Vec::new();
// In-param strings pass as fast-pass references to a copy on the stack: no heap
// HSTRING per call. Reserved up front so no entry moves while the call holds its handle.
let string_count = self.si.parse_parameter_types.iter().filter(|t| matches!(t, NativeType::String)).count();
let mut string_refs: SmallVec<[crate::value::StringRef; 4]> = SmallVec::with_capacity(string_count);
for (i, native_type) in self.si.parse_parameter_types.iter().enumerate() {
let parameter = &self.si.parameters[i];
// Use the pre-computed signature string (cached at construction time) to avoid
Expand Down Expand Up @@ -1048,6 +1052,17 @@ impl MethodCall {

let value = args.get(i as i32);

if matches!(native_type, NativeType::String) && string_refs.len() < string_refs.capacity() {
if let Ok(text) = v8::Local::<v8::String>::try_from(value) {
string_refs.push(crate::value::StringRef::default());
let handle = string_refs.last_mut().unwrap().reference(scope, text);
self.argument_buf.push(NativeValue { pointer: handle });
// A reference owns nothing, so the release pass skips it.
self.argument_parse_types.push(None);
continue;
}
}

let value = match *native_type {
NativeType::Void => return (call_failure(), std::ptr::null_mut(), Vec::new()),
NativeType::Bool => ffi_parse_bool_arg(value),
Expand Down Expand Up @@ -1736,6 +1751,9 @@ impl MethodCall {

let mut buffer_args = Vec::new();
let mut reference_arrays = Vec::new();
// In-param strings pass as fast-pass references; reserved so no entry moves mid-call.
let string_count = self.si.parse_parameter_types.iter().filter(|t| matches!(t, NativeType::String)).count();
let mut string_refs: SmallVec<[crate::value::StringRef; 4]> = SmallVec::with_capacity(string_count);
for (i, native_type) in self.si.parse_parameter_types.iter().enumerate() {
let parameter = &self.si.parameters[i];
let param_sig = &self.si.param_sigs[i];
Expand Down Expand Up @@ -1808,6 +1826,22 @@ impl MethodCall {
};
let vt = value.get_type().unwrap_or(ValueType::Undefined);

if matches!(native_type, NativeType::String) && vt == ValueType::String && string_refs.len() < string_refs.capacity() {
string_refs.push(crate::value::StringRef::default());
match nv::napi_string_reference(env, &value, string_refs.last_mut().unwrap()) {
Ok(reference) => {
self.argument_buf.push(reference);
// A reference owns nothing, so the release pass skips it.
self.argument_parse_types.push(None);
continue;
}
Err(e) => {
crate::error::set_argument_error(e);
return fail3();
}
}
}

let value = match *native_type {
NativeType::Void => return fail3(),
NativeType::Bool => nv::napi_parse_bool(&value),
Expand Down
27 changes: 27 additions & 0 deletions runtime/src/napi_engine/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,33 @@ pub fn napi_parse_f64(arg: &JsUnknown) -> Result<NativeValue, AnyError> {
Ok(NativeValue { f64_value: f })
}

/// A string in-param as a fast-pass reference over `slot`: napi writes the UTF-16 straight into
/// it, with no `Vec` and no heap HSTRING. `slot` must stay put for the call.
pub fn napi_string_reference(
env: &Env,
arg: &JsUnknown,
slot: &mut crate::value::StringRef,
) -> Result<NativeValue, AnyError> {
if value_type(arg)? != ValueType::String {
return Err(type_error("Invalid FFI String type, expected String"));
}
let (raw_env, raw_value) = (env.raw(), unsafe { arg.raw() });
let mut len = 0usize;
let st = unsafe { sys::napi_get_value_string_utf16(raw_env, raw_value, std::ptr::null_mut(), 0, &mut len) };
if st != sys::Status::napi_ok {
return Err(type_error("Invalid FFI String type, expected String"));
}
let buffer = slot.buffer(len);
let mut written = 0usize;
let st = unsafe {
sys::napi_get_value_string_utf16(raw_env, raw_value, buffer.as_mut_ptr(), buffer.len(), &mut written)
};
if st != sys::Status::napi_ok {
return Err(type_error("Invalid FFI String type, expected String"));
}
Ok(NativeValue { pointer: slot.handle(written) })
}

#[inline]
pub fn napi_parse_string(arg: &JsUnknown) -> Result<NativeValue, AnyError> {
// `v8::String::try_from` requires an actual string (no ToString coercion). The rusty_v8
Expand Down
49 changes: 49 additions & 0 deletions runtime/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,55 @@ fn hstring_from_v8_string(scope: &mut v8::PinScope<'_, '_>, s: v8::Local<v8::Str
HSTRING::from_wide(&buf)
}

/// A fast-pass HSTRING (`WindowsCreateStringReference`) over a UTF-16 copy of a JS string, for
/// an in-param: valid while this value stays where it is, which callers keep for the call.
#[derive(Default)]
pub struct StringRef {
header: windows::Win32::System::WinRT::HSTRING_HEADER,
text: smallvec::SmallVec<[u16; 64]>,
}

impl StringRef {
/// Room for `len` code units and the NUL after them.
pub fn buffer(&mut self, len: usize) -> &mut [u16] {
self.text.resize(len + 1, 0);
&mut self.text[..]
}

/// The raw HSTRING handle over the first `len` code units (null for an empty string); never
/// released.
pub fn handle(&mut self, len: usize) -> *mut c_void {
if len == 0 || self.text.len() <= len {
return std::ptr::null_mut();
}
self.text[len] = 0;
let mut handle = std::mem::MaybeUninit::<HSTRING>::zeroed();
let made = unsafe {
windows::Win32::System::WinRT::WindowsCreateStringReference(
windows_core::PCWSTR(self.text.as_ptr()),
len as u32,
&mut self.header,
handle.as_mut_ptr(),
)
};
if made.is_err() {
return std::ptr::null_mut();
}
// The HSTRING wrapper would delete the handle on drop; a reference needs none.
unsafe { handle.as_ptr().cast::<*mut c_void>().read() }
}

#[cfg(feature = "classic")]
pub fn reference(&mut self, scope: &mut v8::PinScope<'_, '_>, s: v8::Local<v8::String>) -> *mut c_void {
let len = s.length();
if len == 0 {
return std::ptr::null_mut();
}
s.write_v2(scope, 0, &mut self.buffer(len)[..len], v8::WriteFlags::empty());
self.handle(len)
}
}

/// As `hstring_from_v8_string`, but coerces a non-string JS value via ToString first (matching
/// `Value::to_rust_string_lossy`'s behavior). Empty HSTRING if coercion fails.
#[cfg(feature = "classic")]
Expand Down