Allow dropping of string&buffer values when converting

This commit is contained in:
Julius de Bruijn 2021-05-27 19:41:37 +02:00
parent 03fcd19580
commit 3db5c56fbf
3 changed files with 15 additions and 5 deletions

View file

@ -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<Vec<u16>> for JsStringUtf16 {
impl From<JsStringUtf16> for Vec<u16> {
fn from(value: JsStringUtf16) -> Self {
value.as_slice().to_vec()
ManuallyDrop::into_inner(value.buf)
}
}

View file

@ -36,16 +36,24 @@ impl JsStringUtf8 {
#[inline]
pub fn into_owned(self) -> Result<String> {
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<u8> {
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<JsStringUtf8> for String {
type Error = Error;
fn try_from(value: JsStringUtf8) -> Result<String> {
Ok(value.as_str()?.to_owned())
value.into_owned()
}
}

View file

@ -1 +1,2 @@
tab_spaces = 2
edition = "2018"