Fix String roundtrip with interior nul bytes

This commit is contained in:
messense 2022-02-04 16:29:17 +08:00
parent 666118d69f
commit a1be16530b
6 changed files with 17 additions and 3 deletions
crates/napi/src/bindgen_runtime/js_values

View file

@ -2,7 +2,6 @@ use crate::{bindgen_prelude::*, check_status, sys, Error, Result, Status};
use std::ffi::{c_void, CStr};
use std::fmt::Display;
#[cfg(feature = "latin1")]
use std::mem;
use std::ops::Deref;
use std::ptr;
@ -53,12 +52,15 @@ impl FromNapiValue for String {
"Failed to convert napi `string` into rust type `String`"
)?;
match unsafe { CStr::from_ptr(buf_ptr) }.to_str() {
let mut ret = mem::ManuallyDrop::new(ret);
let buf_ptr = ret.as_mut_ptr();
let bytes = unsafe { Vec::from_raw_parts(buf_ptr as *mut u8, written_char_count, len) };
match String::from_utf8(bytes) {
Err(e) => Err(Error::new(
Status::InvalidArg,
format!("Failed to read utf8 string, {}", e),
)),
Ok(s) => Ok(s.to_owned()),
Ok(s) => Ok(s),
}
}
}