rust_css_parser/parser/
input.rs1use crate::parser::utils::codes::CodeUnits;
7use std::rc::Rc;
8
9#[derive(Clone, Debug)]
11pub enum CssInput {
12 Str(Rc<str>),
13 Bytes(Rc<[u8]>),
14}
15
16impl From<&str> for CssInput {
17 fn from(s: &str) -> Self {
18 CssInput::Str(Rc::from(s))
19 }
20}
21
22impl From<String> for CssInput {
23 fn from(s: String) -> Self {
24 CssInput::Str(Rc::from(s))
25 }
26}
27
28impl From<Vec<u8>> for CssInput {
29 fn from(b: Vec<u8>) -> Self {
30 CssInput::Bytes(Rc::from(b))
31 }
32}
33
34#[derive(Clone, Debug)]
36pub struct CssCodeUnits {
37 pub codes: CodeUnits,
39 pub text: Rc<str>,
41}
42
43pub fn rc_bytes_to_str(bytes: Rc<[u8]>) -> Result<Rc<str>, Rc<[u8]>> {
45 if std::str::from_utf8(&bytes).is_err() {
46 return Err(bytes);
47 }
48 Ok(unsafe { Rc::from_raw(Rc::into_raw(bytes) as *const str) })
50}
51
52pub fn rc_str_to_bytes(text: Rc<str>) -> Rc<[u8]> {
54 unsafe { Rc::from_raw(Rc::into_raw(text) as *const [u8]) }
56}
57
58pub fn is_empty_input(input: &CssInput) -> bool {
60 match input {
61 CssInput::Str(s) => s.is_empty(),
62 CssInput::Bytes(b) => b.is_empty(),
63 }
64}
65
66pub fn to_code_units(input: Option<&CssInput>) -> CssCodeUnits {
70 let empty = || CssCodeUnits { codes: CodeUnits::Bytes(Rc::from(&[][..])), text: Rc::from("") };
71 match input {
72 None => empty(),
73 Some(CssInput::Str(text)) => {
74 if text.is_empty() {
75 return empty();
76 }
77 if text.is_ascii() {
78 CssCodeUnits { codes: CodeUnits::Bytes(rc_str_to_bytes(text.clone())), text: text.clone() }
79 } else {
80 CssCodeUnits { codes: CodeUnits::Utf16(text.encode_utf16().collect::<Vec<u16>>().into()), text: text.clone() }
81 }
82 }
83 Some(CssInput::Bytes(bytes)) => {
84 if bytes.is_empty() {
85 return empty();
86 }
87 if bytes.is_ascii() {
88 let text = rc_bytes_to_str(bytes.clone()).expect("ascii is utf-8");
89 return CssCodeUnits { codes: CodeUnits::Bytes(bytes.clone()), text };
90 }
91 let body = bytes.strip_prefix(&[0xef, 0xbb, 0xbf][..]).unwrap_or(bytes);
93 let text: Rc<str> = Rc::from(String::from_utf8_lossy(body).as_ref());
94 if text.is_ascii() {
95 return CssCodeUnits { codes: CodeUnits::Bytes(rc_str_to_bytes(text.clone())), text };
96 }
97 CssCodeUnits { codes: CodeUnits::Utf16(text.encode_utf16().collect::<Vec<u16>>().into()), text }
98 }
99 }
100}