continuity_engine/
delta_history.rs1use std::collections::VecDeque;
4
5use ahash::AHashMap;
6use continuity_buffer::BufferId;
7use continuity_text::RopeEditDelta;
8
9use crate::RopeEditDeltaWithPoints;
10
11const DELTA_HISTORY_CAP: usize = 512;
12
13#[derive(Clone, Debug)]
14struct DeltaHistoryEntry {
15 revision: u64,
16 deltas: Vec<RopeEditDeltaWithPoints>,
17}
18
19#[derive(Debug, Default)]
20struct BufferDeltaHistory {
21 entries: VecDeque<DeltaHistoryEntry>,
22 evicted_revision: u64,
23}
24
25#[derive(Debug, Default)]
27pub struct DeltaHistory {
28 buffers: AHashMap<BufferId, BufferDeltaHistory>,
29}
30
31impl DeltaHistory {
32 pub(crate) fn push(
33 &mut self,
34 buffer_id: BufferId,
35 revision: u64,
36 deltas: Vec<RopeEditDeltaWithPoints>,
37 ) {
38 let history = self.buffers.entry(buffer_id).or_default();
39 history
40 .entries
41 .push_back(DeltaHistoryEntry { revision, deltas });
42 while history.entries.len() > DELTA_HISTORY_CAP {
43 if let Some(evicted) = history.entries.pop_front() {
44 history.evicted_revision = history.evicted_revision.max(evicted.revision);
45 }
46 }
47 }
48
49 pub(crate) fn forget(&mut self, buffer_id: BufferId) {
50 self.buffers.remove(&buffer_id);
51 }
52
53 #[must_use]
55 pub fn since(&self, buffer_id: BufferId, since_revision: u64) -> (Vec<RopeEditDelta>, bool) {
56 let (deltas, covered) = self.with_points_since(buffer_id, since_revision);
57 (
58 deltas.into_iter().map(|delta| delta.delta).collect(),
59 covered,
60 )
61 }
62
63 #[must_use]
65 pub fn with_points_since(
66 &self,
67 buffer_id: BufferId,
68 since_revision: u64,
69 ) -> (Vec<RopeEditDeltaWithPoints>, bool) {
70 let Some(history) = self.buffers.get(&buffer_id) else {
71 return (Vec::new(), true);
72 };
73 if since_revision < history.evicted_revision {
74 return (Vec::new(), false);
75 }
76 let deltas = history
77 .entries
78 .iter()
79 .filter(|entry| entry.revision > since_revision)
80 .flat_map(|entry| entry.deltas.iter().copied())
81 .collect();
82 (deltas, true)
83 }
84}