fix(napi): JsString should respect \0 character to align with String (#2138)

* fix(napi): JsString should respect \0 character to align with String

* chore(test): update snapshot
This commit is contained in:
Ranger 2024-06-12 15:20:27 +08:00 committed by GitHub
parent bd864d2906
commit 19e3488efc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 20 additions and 8 deletions

View File

@ -69,9 +69,13 @@ impl JsString {
)
})?;
// respect '\0' with js string, for example: `let hello = [a,'\0',b,'\0',c].join('')`
let mut result = mem::ManuallyDrop::new(result);
let buf_ptr = result.as_mut_ptr();
let bytes = unsafe { Vec::from_raw_parts(buf_ptr as *mut u8, written_char_count, len) };
Ok(JsStringUtf8 {
inner: self,
buf: result,
buf: bytes,
})
}

View File

@ -1,24 +1,26 @@
use std::convert::TryFrom;
use std::ffi::CStr;
use std::os::raw::c_char;
use std::str;
use crate::{Error, JsString, Result, Status};
pub struct JsStringUtf8 {
pub(crate) inner: JsString,
pub(crate) buf: Vec<c_char>,
pub(crate) buf: Vec<u8>,
}
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)))
match str::from_utf8(&self.buf) {
Err(e) => Err(Error::new(
Status::InvalidArg,
format!("Failed to read utf8 string, {}", e),
)),
Ok(s) => Ok(s),
}
}
pub fn as_slice(&self) -> &[u8] {
unsafe { CStr::from_ptr(self.buf.as_ptr()) }.to_bytes()
self.buf.as_slice()
}
pub fn len(&self) -> usize {

View File

@ -7,6 +7,12 @@ test('should be able to concat string', (t) => {
t.snapshot(bindings.concatString(fixture))
})
test('should be able to concat string with char \0', (t) => {
const fixture = 'JavaScript \0 🌳 你好 \0 napi'
t.snapshot(fixture)
t.snapshot(bindings.concatString(fixture))
})
test('should be able to concat utf16 string', (t) => {
const fixture = 'JavaScript 🌳 你好 napi'
t.snapshot(bindings.concatUTF16String(fixture))