1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use std::convert::TryFrom;
use std::ops::Deref;

use crate::{Error, JsString, Result, Status};

pub struct JsStringUtf16 {
  pub(crate) inner: JsString,
  pub(crate) buf: Vec<u16>,
}

impl JsStringUtf16 {
  pub fn as_str(&self) -> Result<String> {
    if let Some((_, prefix)) = self.as_slice().split_last() {
      String::from_utf16(prefix).map_err(|e| Error::new(Status::InvalidArg, format!("{}", e)))
    } else {
      Ok(String::new())
    }
  }

  pub fn as_slice(&self) -> &[u16] {
    self.buf.as_slice()
  }

  pub fn len(&self) -> usize {
    self.buf.len()
  }

  pub fn is_empty(&self) -> bool {
    self.buf.is_empty()
  }

  pub fn into_value(self) -> JsString {
    self.inner
  }
}

impl TryFrom<JsStringUtf16> for String {
  type Error = Error;

  fn try_from(value: JsStringUtf16) -> Result<String> {
    value.as_str()
  }
}

impl Deref for JsStringUtf16 {
  type Target = [u16];

  fn deref(&self) -> &[u16] {
    self.buf.as_slice()
  }
}

impl AsRef<Vec<u16>> for JsStringUtf16 {
  fn as_ref(&self) -> &Vec<u16> {
    &self.buf
  }
}

impl From<JsStringUtf16> for Vec<u16> {
  fn from(value: JsStringUtf16) -> Self {
    value.as_slice().to_vec()
  }
}