mirror of
https://github.com/napi-rs/napi-rs.git
synced 2025-12-08 19:56:07 +00:00
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:
parent
bd864d2906
commit
19e3488efc
@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@ -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 {
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@ -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))
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user