1 | use std::convert::TryFrom; |
2 | use std::ops::Deref; |
3 | |
4 | use crate::{Error, JsString, Result, Status}; |
5 | |
6 | pub struct JsStringUtf16 { |
7 | pub(crate) inner: JsString, |
8 | pub(crate) buf: Vec<u16>, |
9 | } |
10 | |
11 | impl JsStringUtf16 { |
12 | pub fn as_str(&self) -> Result<String> { |
13 | if let Some((_, prefix)) = self.as_slice().split_last() { |
14 | String::from_utf16(prefix).map_err(|e| Error::new(Status::InvalidArg, format!(" {}" , e))) |
15 | } else { |
16 | Ok(String::new()) |
17 | } |
18 | } |
19 | |
20 | pub fn as_slice(&self) -> &[u16] { |
21 | self.buf.as_slice() |
22 | } |
23 | |
24 | pub fn len(&self) -> usize { |
25 | self.buf.len() |
26 | } |
27 | |
28 | pub fn is_empty(&self) -> bool { |
29 | self.buf.is_empty() |
30 | } |
31 | |
32 | pub fn into_value(self) -> JsString { |
33 | self.inner |
34 | } |
35 | } |
36 | |
37 | impl TryFrom<JsStringUtf16> for String { |
38 | type Error = Error; |
39 | |
40 | fn try_from(value: JsStringUtf16) -> Result<String> { |
41 | value.as_str() |
42 | } |
43 | } |
44 | |
45 | impl Deref for JsStringUtf16 { |
46 | type Target = [u16]; |
47 | |
48 | fn deref(&self) -> &[u16] { |
49 | self.buf.as_slice() |
50 | } |
51 | } |
52 | |
53 | impl AsRef<Vec<u16>> for JsStringUtf16 { |
54 | fn as_ref(&self) -> &Vec<u16> { |
55 | &self.buf |
56 | } |
57 | } |
58 | |
59 | impl From<JsStringUtf16> for Vec<u16> { |
60 | fn from(value: JsStringUtf16) -> Self { |
61 | value.as_slice().to_vec() |
62 | } |
63 | } |
64 | |