rust_css_parser/printer/
writer.rs1use std::cell::Cell;
7
8thread_local! {
9 static WRITER_ID: Cell<u32> = const { Cell::new(0) };
10}
11
12fn 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
21pub const DEFAULT_CAPACITY: usize = 1 << 12;
23
24#[derive(Debug)]
26pub struct Writer {
27 pub buffer: Vec<u8>,
29 pub id: u32,
31 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 #[inline]
52 pub fn length(&self) -> usize {
53 self.buffer.len()
54 }
55
56 #[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 #[inline]
67 pub fn write_byte(&mut self, code: u8) {
68 self.buffer.push(code);
69 }
70
71 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 pub fn code_length(&self) -> usize {
79 (self.buffer.len() as i64 - self.extra) as usize
80 }
81
82 pub fn reset(&mut self) {
84 self.id = next_writer_id();
85 self.buffer.clear();
86 self.extra = 0;
87 }
88
89 pub fn truncate(&mut self, length: usize, extra: i64) {
91 self.buffer.truncate(length);
92 self.extra = extra;
93 }
94
95 pub fn last_byte(&self) -> i32 {
97 self.buffer.last().map_or(-1, |&b| b as i32)
98 }
99
100 pub fn reserve(&mut self, size: usize) {
102 self.buffer.reserve(size);
103 }
104
105 pub fn bytes(&self) -> &[u8] {
107 &self.buffer
108 }
109
110 pub fn as_str(&self) -> &str {
112 std::str::from_utf8(&self.buffer).unwrap_or_default()
114 }
115
116 pub fn into_bytes(self) -> Vec<u8> {
118 self.buffer
119 }
120}