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