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