Skip to main content

rust_css_parser/parser/
input.rs

1//! Port of `src/parser/input.ts`.
2//!
3//! css input: utf-8 bytes (the preferred input: the bindings pass the bytes of an `ArrayBuffer`) or a string. ascii
4//! input is read from its bytes without copy: the same shared buffer is the text and the code units.
5
6use crate::parser::utils::codes::CodeUnits;
7use std::rc::Rc;
8
9/// css input
10#[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/// the css read by the tokenizer: the code units and the text
35#[derive(Clone, Debug)]
36pub struct CssCodeUnits {
37    /// the utf-16 code units of the css. ascii css: the bytes of the input, without copy
38    pub codes: CodeUnits,
39    /// the text of the css
40    pub text: Rc<str>,
41}
42
43/// view shared ascii / utf-8 bytes as a string without copy
44pub 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    // SAFETY: `str` and `[u8]` have the same layout and the bytes are valid utf-8
49    Ok(unsafe { Rc::from_raw(Rc::into_raw(bytes) as *const str) })
50}
51
52/// view a shared string as bytes without copy
53pub fn rc_str_to_bytes(text: Rc<str>) -> Rc<[u8]> {
54    // SAFETY: `str` and `[u8]` have the same layout
55    unsafe { Rc::from_raw(Rc::into_raw(text) as *const [u8]) }
56}
57
58/// true if the input is empty
59pub 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
66/// convert the css input to code units. an ascii input is read from its bytes: the code units are the bytes. the other
67/// inputs are decoded (utf-8, without byte order mark) to utf-16 code units: the positions of the tokens are utf-16
68/// positions, like the positions in a javascript string
69pub 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            // TextDecoder: lossy utf-8, the byte order mark is removed
92            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}