rust_css_parser/utils/
pool.rs1use std::cell::RefCell;
6use std::ops::{Deref, DerefMut};
7
8const MAX_POOLED: usize = 32;
10const MAX_CAPACITY: usize = 1 << 16;
12
13thread_local! {
14 static POOL: RefCell<Vec<Vec<u32>>> = const { RefCell::new(Vec::new()) };
15}
16
17pub struct PooledVec(Vec<u32>);
19
20impl PooledVec {
21 pub fn new() -> Self {
23 PooledVec(POOL.with(|p| p.borrow_mut().pop()).unwrap_or_default())
24 }
25
26 pub fn from_slice(values: &[u32]) -> Self {
28 let mut v = Self::new();
29 v.0.extend_from_slice(values);
30 v
31 }
32}
33
34impl Default for PooledVec {
35 fn default() -> Self {
36 Self::new()
37 }
38}
39
40impl Drop for PooledVec {
41 fn drop(&mut self) {
42 let mut v = std::mem::take(&mut self.0);
43 if v.capacity() == 0 || v.capacity() > MAX_CAPACITY {
44 return;
45 }
46 v.clear();
47 let _ = POOL.try_with(|p| {
49 let mut pool = p.borrow_mut();
50 if pool.len() < MAX_POOLED {
51 pool.push(v);
52 }
53 });
54 }
55}
56
57impl Deref for PooledVec {
58 type Target = Vec<u32>;
59
60 #[inline]
61 fn deref(&self) -> &Vec<u32> {
62 &self.0
63 }
64}
65
66impl DerefMut for PooledVec {
67 #[inline]
68 fn deref_mut(&mut self) -> &mut Vec<u32> {
69 &mut self.0
70 }
71}