Skip to main content

ass_editor/core/incremental/
state.rs

1//! Construction and cache-state management for [`IncrementalParser`].
2//!
3//! Provides constructors, threshold configuration, cache priming, and the
4//! lightweight accessors used to inspect accumulated incremental state.
5
6use super::{DocumentChange, IncrementalParser};
7use crate::core::errors::EditorError;
8use crate::core::Result;
9use ass_core::parser::Script;
10
11#[cfg(not(feature = "std"))]
12use alloc::{string::ToString, vec::Vec};
13
14impl IncrementalParser {
15    /// Create a new incremental parser
16    pub fn new() -> Self {
17        Self {
18            cached_script: None,
19            pending_changes: Vec::new(),
20            next_change_id: 1,
21            reparse_threshold: 10_000, // 10KB of changes triggers full reparse
22            bytes_changed: 0,
23        }
24    }
25
26    /// Set the reparse threshold in bytes
27    pub fn set_reparse_threshold(&mut self, threshold: usize) {
28        self.reparse_threshold = threshold;
29    }
30
31    /// Initialize the cache with the current document content
32    /// This primes the incremental parser for efficient subsequent edits
33    pub fn initialize_cache(&mut self, content: &str) {
34        self.cached_script = Some(content.to_string());
35        self.pending_changes.clear();
36        self.bytes_changed = 0;
37    }
38
39    /// Check if there's a cached script available
40    pub fn has_cached_script(&self) -> bool {
41        self.cached_script.is_some()
42    }
43
44    /// Execute a function with the cached script (avoids re-parsing)
45    pub fn with_cached_script<F, R>(&self, f: F) -> Result<R>
46    where
47        F: FnOnce(&Script) -> Result<R>,
48    {
49        let cached = self
50            .cached_script
51            .as_ref()
52            .ok_or_else(|| EditorError::command_failed("No cached script available"))?;
53        let script = Script::parse(cached).map_err(EditorError::from)?;
54        f(&script)
55    }
56
57    /// Clear all cached state
58    pub fn clear_cache(&mut self) {
59        self.cached_script = None;
60        self.pending_changes.clear();
61        self.bytes_changed = 0;
62        self.next_change_id = 1;
63    }
64
65    /// Get accumulated changes since last full parse
66    pub fn pending_changes(&self) -> &[DocumentChange<'static>] {
67        &self.pending_changes
68    }
69
70    /// Check if a full reparse is recommended
71    pub fn should_reparse(&self) -> bool {
72        self.bytes_changed >= self.reparse_threshold || self.pending_changes.len() > 50
73    }
74}