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