Skip to main content

codex_patcher/
pool.rs

1//! Thread-local parser pooling for performance optimization.
2//!
3//! Eliminates redundant parser creation by maintaining a thread-local pool
4//! of reusable parsers. Creates new parser on first use per thread, reuses
5//! for subsequent operations.
6
7use crate::ts::{RustParser, TreeSitterError};
8use std::cell::RefCell;
9
10thread_local! {
11    static RUST_PARSER: RefCell<Option<RustParser>> = const { RefCell::new(None) };
12}
13
14/// Execute function with pooled parser instance.
15///
16/// On first call per thread, creates new parser. Subsequent calls reuse
17/// the same parser instance, avoiding allocation and initialization overhead.
18///
19/// # Example
20///
21/// ```no_run
22/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
23/// use codex_patcher::pool::with_parser;
24///
25/// let result = with_parser(|parser| {
26///     parser.parse_with_source("fn main() {}")
27/// })?;
28/// # Ok(())
29/// # }
30/// ```
31pub fn with_parser<F, R>(f: F) -> Result<R, TreeSitterError>
32where
33    F: FnOnce(&mut RustParser) -> R,
34{
35    RUST_PARSER.with(|cell| {
36        let mut opt = cell.borrow_mut();
37        if opt.is_none() {
38            *opt = Some(RustParser::new()?);
39        }
40        Ok(f(opt.as_mut().expect("parser was just initialized above")))
41    })
42}