regex_lite/
pool.rs

1use core::panic::{RefUnwindSafe, UnwindSafe};
2
3use alloc::{boxed::Box, vec, vec::Vec};
4
5use crate::pikevm;
6
7// Literally the only reason that this crate requires 'std' currently.
8//
9// In regex-automata, we support the no-std use case by rolling our own
10// spin-lock based Mutex. That's questionable on its own, but it's not clear if
11// we should be doing that here. It will require introducing non-safe code in a
12// crate that is otherwise safe. But maybe it's worth doing?
13use std::sync::Mutex;
14
15/// A type alias for our pool of meta::Cache that fixes the type parameters to
16/// what we use for the meta regex below.
17pub(crate) type CachePool = Pool<pikevm::Cache, CachePoolFn>;
18
19/// Same as above, but for the guard returned by a pool.
20pub(crate) type CachePoolGuard<'a> = PoolGuard<'a, pikevm::Cache, CachePoolFn>;
21
22/// The type of the closure we use to create new caches. We need to spell out
23/// all of the marker traits or else we risk leaking !MARKER impls.
24pub(crate) type CachePoolFn =
25    Box<dyn Fn() -> pikevm::Cache + Send + Sync + UnwindSafe + RefUnwindSafe>;
26
27/// A thread safe pool utilizing alloc-only features.
28///
29/// Unlike the pool in regex-automata, this has no "fast path." We could add
30/// it, but it's more code and requires reasoning about safety.
31pub(crate) struct Pool<T, F> {
32    /// A stack of T values to hand out. These are used when a Pool is
33    /// accessed by a thread that didn't create it.
34    stack: Mutex<Vec<Box<T>>>,
35    /// A function to create more T values when stack is empty and a caller
36    /// has requested a T.
37    create: F,
38}
39
40// If T is UnwindSafe, then since we provide exclusive access to any
41// particular value in the pool, it should therefore also be considered
42// RefUnwindSafe.
43impl<T: UnwindSafe, F: UnwindSafe> RefUnwindSafe for Pool<T, F> {}
44
45impl<T, F> Pool<T, F> {
46    /// Create a new pool. The given closure is used to create values in
47    /// the pool when necessary.
48    pub(crate) const fn new(create: F) -> Pool<T, F> {
49        Pool { stack: Mutex::new(vec![]), create }
50    }
51}
52
53impl<T: Send, F: Fn() -> T> Pool<T, F> {
54    /// Get a value from the pool. This may block if another thread is also
55    /// attempting to retrieve a value from the pool.
56    pub(crate) fn get(&self) -> PoolGuard<'_, T, F> {
57        let mut stack = self.stack.lock().unwrap();
58        let value = match stack.pop() {
59            None => Box::new((self.create)()),
60            Some(value) => value,
61        };
62        PoolGuard { pool: self, value: Some(value) }
63    }
64
65    /// Puts a value back into the pool. Callers don't need to call this.
66    /// Once the guard that's returned by 'get' is dropped, it is put back
67    /// into the pool automatically.
68    fn put_value(&self, value: Box<T>) {
69        let mut stack = self.stack.lock().unwrap();
70        stack.push(value);
71    }
72}
73
74impl<T: core::fmt::Debug, F> core::fmt::Debug for Pool<T, F> {
75    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
76        f.debug_struct("Pool").field("stack", &self.stack).finish()
77    }
78}
79
80/// A guard that is returned when a caller requests a value from the pool.
81pub(crate) struct PoolGuard<'a, T: Send, F: Fn() -> T> {
82    /// The pool that this guard is attached to.
83    pool: &'a Pool<T, F>,
84    /// This is None after the guard has been put back into the pool.
85    value: Option<Box<T>>,
86}
87
88impl<'a, T: Send, F: Fn() -> T> Drop for PoolGuard<'a, T, F> {
89    fn drop(&mut self) {
90        if let Some(value) = self.value.take() {
91            self.pool.put_value(value);
92        }
93    }
94}
95
96impl<'a, T: Send, F: Fn() -> T> core::ops::Deref for PoolGuard<'a, T, F> {
97    type Target = T;
98
99    fn deref(&self) -> &T {
100        self.value.as_deref().unwrap()
101    }
102}
103
104impl<'a, T: Send, F: Fn() -> T> core::ops::DerefMut for PoolGuard<'a, T, F> {
105    fn deref_mut(&mut self) -> &mut T {
106        self.value.as_deref_mut().unwrap()
107    }
108}
109
110impl<'a, T: Send + core::fmt::Debug, F: Fn() -> T> core::fmt::Debug
111    for PoolGuard<'a, T, F>
112{
113    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
114        f.debug_struct("PoolGuard")
115            .field("pool", &self.pool)
116            .field("value", &self.value)
117            .finish()
118    }
119}