scarf_parser/preprocessor/cache.rs
1// =======================================================================
2// cache.rs
3// =======================================================================
4//! A cache for storing data generated during preprocessing
5
6use crate::*;
7use elsa::FrozenVec;
8
9/// A cache for storing generated [`Span`]s and strings.
10///
11/// These objects are only meant to be used internal to the
12/// preprocessor. Since the CST only stores references to copy as
13/// little as possible, the [`PreprocessorCache`] stores new
14/// [`Span`]s and strings created as part of preprocessing (such
15/// as when referencing `` `include `` directives and elaborating
16/// preprocessor identifiers, respectively). Since the CST stores
17/// references to these, a [`PreprocessorCache`] used as part
18/// of preprocessing must be kept alive as long as the CST itself.
19pub struct PreprocessorCache<'a> {
20 spans: FrozenVec<Box<Span<'a>>>,
21 strings: FrozenVec<Box<str>>,
22}
23
24impl<'a> PreprocessorCache<'a> {
25 /// Store a [`Span`] for the cache's lifetime
26 pub fn retain_span(&self, span: Span<'a>) -> &Span<'a> {
27 self.spans.push_get(Box::new(span))
28 }
29 /// Store a [`String`] for the cache's lifetime
30 pub fn retain_string(&self, string: String) -> &str {
31 self.strings.push_get(string.into_boxed_str())
32 }
33 /// Create a new cache for storing preprocessor results
34 pub fn new() -> Self {
35 Self {
36 spans: FrozenVec::new(),
37 strings: FrozenVec::new(),
38 }
39 }
40}