2023-01-13 02:51:32 -05:00
|
|
|
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
|
|
|
|
|
2023-04-26 20:12:39 -04:00
|
|
|
use crate::error::value_to_type_str;
|
2022-03-23 16:15:01 -04:00
|
|
|
use crate::Error;
|
2022-03-15 19:22:00 -04:00
|
|
|
|
2023-01-14 23:18:58 -05:00
|
|
|
use super::transl8::impl_magic;
|
|
|
|
use super::transl8::impl_wrapper;
|
|
|
|
use super::transl8::FromV8;
|
|
|
|
use super::transl8::ToV8;
|
2023-01-13 02:51:32 -05:00
|
|
|
|
2022-04-02 08:37:11 -04:00
|
|
|
impl_wrapper!(
|
|
|
|
pub struct U16String(Vec<u16>);
|
|
|
|
);
|
2022-03-23 16:15:01 -04:00
|
|
|
impl_magic!(U16String);
|
2022-03-15 19:22:00 -04:00
|
|
|
|
2022-03-23 16:15:01 -04:00
|
|
|
impl ToV8 for U16String {
|
|
|
|
fn to_v8<'a>(
|
2022-09-01 06:24:40 -04:00
|
|
|
&mut self,
|
2022-03-23 16:15:01 -04:00
|
|
|
scope: &mut v8::HandleScope<'a>,
|
|
|
|
) -> Result<v8::Local<'a, v8::Value>, crate::Error> {
|
2022-05-26 11:15:44 -04:00
|
|
|
let maybe_v =
|
|
|
|
v8::String::new_from_two_byte(scope, self, v8::NewStringType::Normal);
|
|
|
|
|
|
|
|
// 'new_from_two_byte' can return 'None' if buffer length > kMaxLength.
|
|
|
|
if let Some(v) = maybe_v {
|
|
|
|
Ok(v.into())
|
|
|
|
} else {
|
|
|
|
Err(Error::Message(String::from(
|
|
|
|
"Cannot allocate String from UTF-16: buffer exceeds maximum length.",
|
|
|
|
)))
|
|
|
|
}
|
2022-03-15 19:22:00 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-23 16:15:01 -04:00
|
|
|
impl FromV8 for U16String {
|
|
|
|
fn from_v8(
|
|
|
|
scope: &mut v8::HandleScope,
|
|
|
|
value: v8::Local<v8::Value>,
|
|
|
|
) -> Result<Self, crate::Error> {
|
|
|
|
let v8str = v8::Local::<v8::String>::try_from(value)
|
2023-04-26 20:12:39 -04:00
|
|
|
.map_err(|_| Error::ExpectedString(value_to_type_str(value)))?;
|
2022-03-23 16:15:01 -04:00
|
|
|
let len = v8str.length();
|
|
|
|
let mut buffer = Vec::with_capacity(len);
|
2022-07-01 09:28:06 -04:00
|
|
|
#[allow(clippy::uninit_vec)]
|
2022-03-23 16:15:01 -04:00
|
|
|
// SAFETY: we set length == capacity (see previous line),
|
|
|
|
// before immediately writing into that buffer and sanity check with an assert
|
|
|
|
unsafe {
|
|
|
|
buffer.set_len(len);
|
|
|
|
let written = v8str.write(
|
|
|
|
scope,
|
|
|
|
&mut buffer,
|
|
|
|
0,
|
|
|
|
v8::WriteOptions::NO_NULL_TERMINATION,
|
|
|
|
);
|
|
|
|
assert!(written == len);
|
|
|
|
}
|
2022-04-02 08:37:11 -04:00
|
|
|
Ok(buffer.into())
|
2022-03-23 16:15:01 -04:00
|
|
|
}
|
|
|
|
}
|