Skip to main content

rust_css_parser/utils/
pool.rs

1//! Reused scratch buffers: the walkers and the traversals use a stack of node ids that is taken from a thread local
2//! pool and returned when it is dropped, instead of allocating a stack for each traversal (the typescript port shares
3//! a single stack for the same reason, see `visitStack` in `src/ast/arena.ts`).
4
5use std::cell::RefCell;
6use std::ops::{Deref, DerefMut};
7
8/// the buffers kept by the pool
9const MAX_POOLED: usize = 32;
10/// a buffer larger than this is released instead of being kept
11const MAX_CAPACITY: usize = 1 << 16;
12
13thread_local! {
14    static POOL: RefCell<Vec<Vec<u32>>> = const { RefCell::new(Vec::new()) };
15}
16
17/// a `Vec<u32>` taken from the pool, returned to the pool when it is dropped
18pub struct PooledVec(Vec<u32>);
19
20impl PooledVec {
21    /// an empty buffer
22    pub fn new() -> Self {
23        PooledVec(POOL.with(|p| p.borrow_mut().pop()).unwrap_or_default())
24    }
25
26    /// a buffer containing the values
27    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        // the pool is not available while the thread is being destroyed
48        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}