diff --git a/napi/src/js_values/string/utf16.rs b/napi/src/js_values/string/utf16.rs index 4ae5b71f..a61d997a 100644 --- a/napi/src/js_values/string/utf16.rs +++ b/napi/src/js_values/string/utf16.rs @@ -1,6 +1,6 @@ -use std::convert::TryFrom; use std::mem; use std::ops::Deref; +use std::{convert::TryFrom, mem::ManuallyDrop}; use crate::{Error, JsString, Result, Status}; @@ -33,6 +33,7 @@ impl JsStringUtf16 { #[inline] pub fn into_value(self) -> JsString { + ManuallyDrop::into_inner(self.buf); self.inner } } @@ -61,6 +62,6 @@ impl AsRef> for JsStringUtf16 { impl From for Vec { fn from(value: JsStringUtf16) -> Self { - value.as_slice().to_vec() + ManuallyDrop::into_inner(value.buf) } } diff --git a/napi/src/js_values/string/utf8.rs b/napi/src/js_values/string/utf8.rs index 5239b383..f5c2acd9 100644 --- a/napi/src/js_values/string/utf8.rs +++ b/napi/src/js_values/string/utf8.rs @@ -36,16 +36,24 @@ impl JsStringUtf8 { #[inline] pub fn into_owned(self) -> Result { - Ok(self.as_str()?.to_owned()) + let buffer = ManuallyDrop::into_inner(self.buf); + + let s = unsafe { CStr::from_ptr(buffer.as_ptr()) } + .to_str() + .map_err(|e| Error::new(Status::InvalidArg, format!("{}", e)))?; + + Ok(s.to_owned()) } #[inline] pub fn take(self) -> Vec { - self.as_slice().to_vec() + let bytes = unsafe { CStr::from_ptr(ManuallyDrop::into_inner(self.buf).as_ptr()) }.to_bytes(); + bytes.to_vec() } #[inline] pub fn into_value(self) -> JsString { + ManuallyDrop::into_inner(self.buf); self.inner } } @@ -54,7 +62,7 @@ impl TryFrom for String { type Error = Error; fn try_from(value: JsStringUtf8) -> Result { - Ok(value.as_str()?.to_owned()) + value.into_owned() } } diff --git a/rustfmt.toml b/rustfmt.toml index b196eaa2..e8fd890c 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1 +1,2 @@ tab_spaces = 2 +edition = "2018"