Skip to main content

rust_css_parser/printer/
writer.rs

1//! Port of `src/printer/writer.ts`.
2//!
3//! Growable buffer the rendered css is written to, encoded as UTF-8. The bindings expose the written bytes to
4//! javascript as a view (no copy) and decode them lazily.
5
6use std::cell::Cell;
7
8thread_local! {
9    static WRITER_ID: Cell<u32> = const { Cell::new(0) };
10}
11
12/// a new writer id: a positive 31 bits integer
13fn next_writer_id() -> u32 {
14    WRITER_ID.with(|w| {
15        let id = (w.get() % 0x7ffffffe) + 1;
16        w.set(id);
17        id
18    })
19}
20
21/// default capacity of a writer, in bytes
22pub const DEFAULT_CAPACITY: usize = 1 << 12;
23
24/// growable utf-8 buffer
25#[derive(Debug)]
26pub struct Writer {
27    /// the written bytes
28    pub buffer: Vec<u8>,
29    /// unique id of the content of the writer: it changes when the writer is reset
30    pub id: u32,
31    /// number of bytes written minus the number of UTF-16 code units of the written strings
32    pub extra: i64,
33}
34
35impl Default for Writer {
36    fn default() -> Self {
37        Self::new(DEFAULT_CAPACITY)
38    }
39}
40
41impl Writer {
42    pub fn new(capacity: usize) -> Self {
43        Self {
44            buffer: Vec::with_capacity(if capacity > 0 { capacity } else { DEFAULT_CAPACITY }),
45            id: next_writer_id(),
46            extra: 0,
47        }
48    }
49
50    /// number of bytes written
51    #[inline]
52    pub fn length(&self) -> usize {
53        self.buffer.len()
54    }
55
56    /// write a string
57    #[inline]
58    pub fn write(&mut self, str: &str) {
59        self.buffer.extend_from_slice(str.as_bytes());
60        if !str.is_ascii() {
61            self.extra += str.len() as i64 - str.encode_utf16().count() as i64;
62        }
63    }
64
65    /// write an ascii character
66    #[inline]
67    pub fn write_byte(&mut self, code: u8) {
68        self.buffer.push(code);
69    }
70
71    /// copy bytes already written to the end of the buffer
72    pub fn copy(&mut self, start: usize, end: usize, extra: i64) {
73        self.buffer.extend_from_within(start..end);
74        self.extra += extra;
75    }
76
77    /// length of the written css once decoded, in UTF-16 code units
78    pub fn code_length(&self) -> usize {
79        (self.buffer.len() as i64 - self.extra) as usize
80    }
81
82    /// drop the written bytes: the writer is reused. it gets a new id
83    pub fn reset(&mut self) {
84        self.id = next_writer_id();
85        self.buffer.clear();
86        self.extra = 0;
87    }
88
89    /// drop the bytes written after a position
90    pub fn truncate(&mut self, length: usize, extra: i64) {
91        self.buffer.truncate(length);
92        self.extra = extra;
93    }
94
95    /// last byte written, -1 when nothing is written
96    pub fn last_byte(&self) -> i32 {
97        self.buffer.last().map_or(-1, |&b| b as i32)
98    }
99
100    /// make room for `size` more bytes
101    pub fn reserve(&mut self, size: usize) {
102        self.buffer.reserve(size);
103    }
104
105    /// the written bytes
106    pub fn bytes(&self) -> &[u8] {
107        &self.buffer
108    }
109
110    /// the written css
111    pub fn as_str(&self) -> &str {
112        // only strings and ascii bytes are written
113        std::str::from_utf8(&self.buffer).unwrap_or_default()
114    }
115
116    /// take the written bytes
117    pub fn into_bytes(self) -> Vec<u8> {
118        self.buffer
119    }
120}