causa_kernel/context/material/state/
edit.rs1use super::Context;
4use crate::context::block::ContextBlock;
5use crate::context::ids::BlockId;
6use std::collections::{HashMap, HashSet};
7use std::ops::Range;
8
9#[derive(Debug, Clone, PartialEq)]
11pub struct Replacement {
12 pub range: Range<usize>,
14 pub with: Vec<ContextBlock>,
16}
17
18#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
20pub enum EditError {
21 #[error("replacement {replacement_index} range {range:?} is invalid for length {len}")]
23 InvalidRange {
24 replacement_index: usize,
26 range: Range<usize>,
28 len: usize,
30 },
31 #[error("duplicate block id: {0:?}")]
33 DuplicateBlockId(BlockId),
34 #[error("block identity reused with different content or metadata: {0:?}")]
36 BlockIdentityMismatch(BlockId),
37}
38
39#[derive(Debug, Clone, PartialEq, thiserror::Error)]
41#[error("context edit failed: {reason}")]
42pub struct EditFailure {
43 #[source]
45 pub reason: EditError,
46 pub replacements: Vec<Replacement>,
48 pub appended: Vec<ContextBlock>,
50}
51
52#[derive(Debug)]
54pub struct ContextEdit<'a> {
55 context: &'a mut Context,
56 replacements: Vec<Replacement>,
57 appended: Vec<ContextBlock>,
58}
59
60impl<'a> ContextEdit<'a> {
61 pub fn blocks(&self) -> &[ContextBlock] {
63 self.context.blocks()
64 }
65
66 pub fn replace(
68 mut self,
69 range: Range<usize>,
70 with: impl IntoIterator<Item = ContextBlock>,
71 ) -> Self {
72 self.replacements.push(Replacement {
73 range,
74 with: with.into_iter().collect(),
75 });
76 self
77 }
78
79 pub fn append(mut self, blocks: impl IntoIterator<Item = ContextBlock>) -> Self {
81 self.appended.extend(blocks);
82 self
83 }
84
85 pub fn commit(self) -> Result<(), EditFailure> {
87 self.context.apply(self.replacements, self.appended)
88 }
89}
90
91impl Context {
92 pub fn apply(
110 &mut self,
111 mut replacements: Vec<Replacement>,
112 appended: Vec<ContextBlock>,
113 ) -> Result<(), EditFailure> {
114 let effective = match self.validate_edit(&replacements, &appended) {
115 Ok(effective) => effective,
116 Err(reason) => {
117 return Err(EditFailure {
118 reason,
119 replacements,
120 appended,
121 });
122 }
123 };
124
125 if replacements.is_empty() {
126 self.blocks.extend(appended);
127 return Ok(());
128 }
129
130 let removed = effective
131 .iter()
132 .map(|index| replacements[*index].range.end - replacements[*index].range.start)
133 .sum::<usize>();
134 let capacity = self.blocks.len() - removed
135 + appended.len()
136 + effective
137 .iter()
138 .map(|index| replacements[*index].with.len())
139 .sum::<usize>();
140 let mut output = Vec::with_capacity(capacity);
141 let original = std::mem::take(&mut self.blocks);
142 let mut source = original.into_iter();
143 let mut source_index = 0;
144 for index in effective {
145 let replacement = &mut replacements[index];
146 while source_index < replacement.range.start {
147 output.push(source.next().expect("range validated"));
148 source_index += 1;
149 }
150 while source_index < replacement.range.end {
151 source.next().expect("range validated");
152 source_index += 1;
153 }
154 output.extend(std::mem::take(&mut replacement.with));
155 }
156 output.extend(source);
157 output.extend(appended);
158 self.blocks = output;
159 Ok(())
160 }
161
162 pub fn edit(&mut self) -> ContextEdit<'_> {
164 ContextEdit {
165 context: self,
166 replacements: Vec::new(),
167 appended: Vec::new(),
168 }
169 }
170
171 fn validate_edit(
172 &self,
173 replacements: &[Replacement],
174 appended: &[ContextBlock],
175 ) -> Result<Vec<usize>, EditError> {
176 let len = self.blocks.len();
177 for (replacement_index, replacement) in replacements.iter().enumerate() {
178 if replacement.range.start > replacement.range.end || replacement.range.end > len {
179 return Err(EditError::InvalidRange {
180 replacement_index,
181 range: replacement.range.clone(),
182 len,
183 });
184 }
185 }
186
187 let mut effective: Vec<usize> = Vec::with_capacity(replacements.len());
188 for (index, replacement) in replacements.iter().enumerate() {
189 effective.retain(|&previous| {
190 !(ranges_conflict(&replacement.range, &replacements[previous].range))
191 });
192 effective.push(index);
193 }
194 effective.sort_by_key(|index| replacements[*index].range.start);
195
196 let originals = self
197 .blocks
198 .iter()
199 .map(|block| (block.id(), block))
200 .collect::<HashMap<_, _>>();
201 for &index in &effective {
202 for block in &replacements[index].with {
203 validate_identity(&originals, block)?;
204 }
205 }
206 for block in appended {
207 validate_identity(&originals, block)?;
208 }
209
210 let mut ids = HashSet::with_capacity(len + appended.len());
211 let mut source_index = 0;
212 for &index in &effective {
213 let range = &replacements[index].range;
214 while source_index < range.start {
215 let id = self.blocks[source_index].id();
216 if !ids.insert(id) {
217 return Err(EditError::DuplicateBlockId(id));
218 }
219 source_index += 1;
220 }
221 for block in &replacements[index].with {
222 if !ids.insert(block.id()) {
223 return Err(EditError::DuplicateBlockId(block.id()));
224 }
225 }
226 source_index = range.end;
227 }
228 while source_index < len {
229 let id = self.blocks[source_index].id();
230 if !ids.insert(id) {
231 return Err(EditError::DuplicateBlockId(id));
232 }
233 source_index += 1;
234 }
235 for block in appended {
236 if !ids.insert(block.id()) {
237 return Err(EditError::DuplicateBlockId(block.id()));
238 }
239 }
240 Ok(effective)
241 }
242}
243
244fn validate_identity(
245 originals: &HashMap<BlockId, &ContextBlock>,
246 incoming: &ContextBlock,
247) -> Result<(), EditError> {
248 if let Some(existing) = originals.get(&incoming.id())
249 && *existing != incoming
250 {
251 return Err(EditError::BlockIdentityMismatch(incoming.id()));
252 }
253 Ok(())
254}
255
256fn ranges_conflict(left: &Range<usize>, right: &Range<usize>) -> bool {
257 match (left.is_empty(), right.is_empty()) {
258 (true, true) => left.start == right.start,
259 (true, false) => right.start <= left.start && left.start < right.end,
260 (false, true) => left.start <= right.start && right.start < left.end,
261 (false, false) => left.start < right.end && right.start < left.end,
262 }
263}