yuuang_test_napi/js_values/string/
utf8.rs1use std::convert::TryFrom;
2use std::ffi::CStr;
3use std::os::raw::c_char;
4use std::str;
5
6use crate::{Error, JsString, Result, Status};
7
8pub struct JsStringUtf8 {
9 pub(crate) inner: JsString,
10 pub(crate) buf: Vec<c_char>,
11}
12
13impl JsStringUtf8 {
14 #[inline]
15 pub fn as_str(&self) -> Result<&str> {
16 unsafe { CStr::from_ptr(self.buf.as_ptr()) }
17 .to_str()
18 .map_err(|e| Error::new(Status::InvalidArg, format!("{}", e)))
19 }
20
21 #[inline]
22 pub fn as_slice(&self) -> &[u8] {
23 unsafe { CStr::from_ptr(self.buf.as_ptr()) }.to_bytes()
24 }
25
26 #[inline]
27 pub fn len(&self) -> usize {
28 self.buf.len()
29 }
30
31 #[inline]
32 pub fn is_empty(&self) -> bool {
33 self.buf.is_empty()
34 }
35
36 #[inline]
37 pub fn into_owned(self) -> Result<String> {
38 Ok(self.as_str()?.to_owned())
39 }
40
41 #[inline]
42 pub fn take(self) -> Vec<u8> {
43 self.as_slice().to_vec()
44 }
45
46 #[inline]
47 pub fn into_value(self) -> JsString {
48 self.inner
49 }
50}
51
52impl TryFrom<JsStringUtf8> for String {
53 type Error = Error;
54
55 fn try_from(value: JsStringUtf8) -> Result<String> {
56 value.into_owned()
57 }
58}
59
60impl From<JsStringUtf8> for Vec<u8> {
61 fn from(value: JsStringUtf8) -> Self {
62 value.take()
63 }
64}