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
66fn utf16_units(text: &str) -> Rc<[u16]> {
69 let bytes = text.as_bytes();
70 let mut units: Vec<u16> = Vec::with_capacity(bytes.len());
71 let mut i = 0;
72 while i < bytes.len() {
73 let byte = bytes[i];
74 if byte < 0x80 {
75 units.push(byte as u16);
76 i += 1;
77 continue;
78 }
79 let c = text[i..].chars().next().expect("utf-8 character");
81 let mut buffer = [0u16; 2];
82 units.extend_from_slice(c.encode_utf16(&mut buffer));
83 i += c.len_utf8();
84 }
85 units.into()
86}
87
88pub fn to_code_units(input: Option<&CssInput>) -> CssCodeUnits {
92 let empty = || CssCodeUnits { codes: CodeUnits::Bytes(Rc::from(&[][..])), text: Rc::from("") };
93 match input {
94 None => empty(),
95 Some(CssInput::Str(text)) => {
96 if text.is_empty() {
97 return empty();
98 }
99 if text.is_ascii() {
100 CssCodeUnits { codes: CodeUnits::Bytes(rc_str_to_bytes(text.clone())), text: text.clone() }
101 } else {
102 CssCodeUnits { codes: CodeUnits::Utf16(utf16_units(&text)), text: text.clone() }
103 }
104 }
105 Some(CssInput::Bytes(bytes)) => {
106 if bytes.is_empty() {
107 return empty();
108 }
109 if bytes.is_ascii() {
110 let text = rc_bytes_to_str(bytes.clone()).expect("ascii is utf-8");
111 return CssCodeUnits { codes: CodeUnits::Bytes(bytes.clone()), text };
112 }
113 let body = bytes.strip_prefix(&[0xef, 0xbb, 0xbf][..]).unwrap_or(bytes);
115 let text: Rc<str> = Rc::from(String::from_utf8_lossy(body).as_ref());
116 if text.is_ascii() {
117 return CssCodeUnits { codes: CodeUnits::Bytes(rc_str_to_bytes(text.clone())), text };
118 }
119 CssCodeUnits { codes: CodeUnits::Utf16(utf16_units(&text)), text }
120 }
121 }
122}