napi-rs / napi-rs

A framework for building compiled Node.js add-ons in Rust via Node-API

Home Page:https://napi.rs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Difference in Strings with null chars in Behavior in compat mode and normal mode.

sheki opened this issue · comments

Summary

Compat mode truncates strings passed to it when it encounters the first NULL charecter.

Likely the issue is in

impl JsStringUtf8 {
  pub fn as_str(&self) -> Result<&str> {
    unsafe { CStr::from_ptr(self.buf.as_ptr()) }
      .to_str()
      .map_err(|e| Error::new(Status::InvalidArg, format!("{}", e)))
  }

Example

Js Code

const { hello, greet } = require('./index')

const str = ['a', '\0', 'b', '\0', 'c'].join('')

console.log(str === 'abc')
console.log(str.length)
console.log(str)
console.log('Passing in string with nulls, expect to print abc')
console.log('#[js_function] : ', hello(str))
console.log('#[js_function] length: ', hello(str).length)
console.log('#[napi] : ', greet(str))
console.log('#[napi] length ', greet(str).length)

Rust code

#[napi]
fn greet(name: String) -> String {
	format!("{}", name)
}
#[js_function(1)]
fn hello(ctx: CallContext) -> Result<JsString> {
  let argument_one = ctx.get::<JsString>(0)?.into_utf8()?;
  ctx.env.create_string_from_std(format!("{}", argument_one.as_str()?)) ## The loss happens in the as_str implementation 
}

#[module_exports]
fn init(mut exports: JsObject) -> Result<() > {
  exports.create_named_method("hello", hello)?;
  Ok(())
}

Output

false
5
abc
Passing in string with nulls, expect to print abc
#[js_function] :  a
#[js_function] length:  1
#[napi] :  abc
#[napi] length  5