napi_h/js_values/string/
utf8.rs

1use 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  pub fn as_str(&self) -> Result<&str> {
15    unsafe { CStr::from_ptr(self.buf.as_ptr()) }
16      .to_str()
17      .map_err(|e| Error::new(Status::InvalidArg, format!("{}", e)))
18  }
19
20  pub fn as_slice(&self) -> &[u8] {
21    unsafe { CStr::from_ptr(self.buf.as_ptr()) }.to_bytes()
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_owned(self) -> Result<String> {
33    Ok(self.as_str()?.to_owned())
34  }
35
36  pub fn take(self) -> Vec<u8> {
37    self.as_slice().to_vec()
38  }
39
40  pub fn into_value(self) -> JsString {
41    self.inner
42  }
43}
44
45impl TryFrom<JsStringUtf8> for String {
46  type Error = Error;
47
48  fn try_from(value: JsStringUtf8) -> Result<String> {
49    value.into_owned()
50  }
51}
52
53impl From<JsStringUtf8> for Vec<u8> {
54  fn from(value: JsStringUtf8) -> Self {
55    value.take()
56  }
57}