* The MIT License (MIT)
* Copyright (C) 2024 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*/
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()
}
}