forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

full_state.rs377 lines, 13.4 KiBHistoryRawDownload
1//! Applying a full-state diff to a re-activated mergeable child in `LoroDoc::apply_diff`.
2//!
3//! Events and `LoroDoc::diff` describe a container that becomes visible with its full state.
4//! `apply_diff` recreates a regular container under a fresh id, so a full state is exactly
5//! right for it. A mergeable child is re-activated at its deterministic cid, which may already
6//! hold hidden state in the target doc (the same, different, or none). [`align_full_state`]
7//! turns the full state into an edit of that hidden state, keeping the characters, elements,
8//! entries and tree nodes the two share. See context/mergeable-containers.md.
9
10use super::{Handler, ValueOrHandler};
11use crate::{
12 delta::{ResolvedMapDelta, ResolvedMapValue, TreeDiff, TreeDiffItem, TreeExternalDiff},
13 event::{Diff, ListDeltaMeta, ListDiff, TextDiff, TextMeta},
14 state::TreeParentId,
15 utils::{
16 string_slice::StringSlice,
17 utf16::{count_unicode_chars, count_utf16_len},
18 },
19};
20use fractional_index::FractionalIndex;
21use loro_common::{ContainerID, InternalString, LoroValue, TreeID};
22use loro_delta::{array_vec::ArrayVec, DeltaItem, DeltaRope};
23use rustc_hash::{FxHashMap, FxHashSet};
24
25/// Given `target`, a full-state diff for `handler`, and `current`, the handler's current state
26/// as a full-state diff, returns the edit that turns `current` into `target`, or `None` if
27/// there is nothing to do. Returns `target` unchanged if it is not a full-state diff.
28///
29/// Has no side effects, so `LoroDoc::_apply_diff` can plan a whole batch before applying it.
30/// Child containers that keep their id are added to `full_state_targets`: their own diffs in
31/// the batch are full states as well.
32pub(crate) fn align_full_state(
33 handler: &Handler,
34 target: &Diff,
35 current: Diff,
36 full_state_targets: &mut FxHashSet<ContainerID>,
37) -> Option<Diff> {
38 match (target, current) {
39 (Diff::Map(target), Diff::Map(current)) => {
40 align_map(target, current, full_state_targets).map(Diff::Map)
41 }
42 #[cfg(feature = "counter")]
43 (Diff::Counter(target), Diff::Counter(current)) => {
44 let delta = target - current;
45 (matches!(handler, Handler::Counter(_)) && delta != 0.0).then_some(Diff::Counter(delta))
46 }
47 (Diff::Text(target), Diff::Text(current)) => match align_text(target, &current) {
48 Some(edit) => (!edit.is_empty()).then_some(Diff::Text(edit)),
49 None => Some(Diff::Text(target.clone())),
50 },
51 (Diff::List(target), Diff::List(current)) => {
52 let movable = matches!(handler, Handler::MovableList(_));
53 match align_list(target, &current, movable, full_state_targets) {
54 Some(edit) => (!edit.is_empty()).then_some(Diff::List(edit)),
55 None => Some(Diff::List(target.clone())),
56 }
57 }
58 (Diff::Tree(target), Diff::Tree(current)) => {
59 match align_tree(target, &current, full_state_targets) {
60 Some(edit) => (!edit.diff.is_empty()).then_some(Diff::Tree(edit)),
61 None => Some(Diff::Tree(target.clone())),
62 }
63 }
64 (Diff::Unknown, _) => None,
65 (target, _) => Some(target.clone()),
66 }
67}
68
69fn map_value(v: &ResolvedMapValue) -> Option<LoroValue> {
70 v.value.as_ref().map(ValueOrHandler::to_value)
71}
72
73/// Per key, so entries (and the child containers they hold) that already match are kept.
74fn align_map(
75 target: &ResolvedMapDelta,
76 current: ResolvedMapDelta,
77 full_state_targets: &mut FxHashSet<ContainerID>,
78) -> Option<ResolvedMapDelta> {
79 let current: FxHashMap<InternalString, LoroValue> = current
80 .updated
81 .iter()
82 .filter_map(|(k, v)| Some((k.clone(), map_value(v)?)))
83 .collect();
84 let mut updated = FxHashMap::default();
85 let mut target_keys = FxHashSet::default();
86 for (key, value) in target.updated.iter() {
87 let Some(target_value) = map_value(value) else {
88 continue;
89 };
90 target_keys.insert(key.clone());
91 if current.get(key) == Some(&target_value) {
92 if let LoroValue::Container(id) = target_value {
93 full_state_targets.insert(id);
94 }
95 } else {
96 updated.insert(key.clone(), value.clone());
97 }
98 }
99 for key in current.keys() {
100 if !target_keys.contains(key) {
101 updated.insert(key.clone(), ResolvedMapValue::new_unset());
102 }
103 }
104 (!updated.is_empty()).then_some(ResolvedMapDelta { updated })
105}
106
107/// Length of `s` in the units of text diffs (see `StringSlice::rle_len`).
108fn text_len(s: &str) -> usize {
109 if cfg!(feature = "wasm") {
110 count_utf16_len(s.as_bytes())
111 } else {
112 count_unicode_chars(s.as_bytes())
113 }
114}
115
116/// Style runs of a pure-insertion text diff, or `None` if it is not one.
117fn text_runs(diff: &TextDiff) -> Option<Vec<(&str, &TextMeta)>> {
118 let mut ans = Vec::new();
119 for item in diff.iter() {
120 let DeltaItem::Replace {
121 value,
122 attr,
123 delete: 0,
124 } = item
125 else {
126 return None;
127 };
128 ans.push((value.as_str(), attr));
129 }
130 Some(ans)
131}
132
133/// The pieces of `runs` that cover the byte range `range` of their concatenated text.
134fn slice_runs<'a>(
135 runs: &[(&'a str, &'a TextMeta)],
136 range: std::ops::Range<usize>,
137) -> Vec<(&'a str, &'a TextMeta)> {
138 let mut ans = Vec::new();
139 let mut offset = 0;
140 for &(text, attr) in runs {
141 let (start, end) = (offset, offset + text.len());
142 offset = end;
143 let (from, to) = (range.start.max(start), range.end.min(end));
144 if from < to {
145 ans.push((&text[from - start..to - start], attr));
146 }
147 }
148 ans
149}
150
151/// Lengths of the longest common prefix and of the longest common suffix of the rest.
152fn common_ends<T: PartialEq>(a: &[T], b: &[T]) -> (usize, usize) {
153 common_ends_by(a, b, |x, y| x == y)
154}
155
156fn common_ends_by<T>(a: &[T], b: &[T], eq: impl Fn(&T, &T) -> bool) -> (usize, usize) {
157 let prefix = a.iter().zip(b).take_while(|(x, y)| eq(x, y)).count();
158 let suffix = a[prefix..]
159 .iter()
160 .rev()
161 .zip(b[prefix..].iter().rev())
162 .take_while(|(x, y)| eq(x, y))
163 .count();
164 (prefix, suffix)
165}
166
167/// The styles to mark on a kept char so that `current` becomes `target` (`null` unmarks).
168fn style_change(current: &TextMeta, target: &TextMeta) -> TextMeta {
169 let mut change = TextMeta::default();
170 for (key, value) in target.0.iter() {
171 if current.0.get(key) != Some(value) {
172 change.0.insert(key.clone(), value.clone());
173 }
174 }
175 for key in current.0.keys() {
176 if !target.0.contains_key(key) {
177 change.0.insert(key.clone(), LoroValue::Null);
178 }
179 }
180 change
181}
182
183/// Retains a kept text range given as the `current` and `target` runs over the same text,
184/// re-marking the pieces whose styles differ.
185fn push_restyled_retain(
186 edit: &mut TextDiff,
187 current: &[(&str, &TextMeta)],
188 target: &[(&str, &TextMeta)],
189) {
190 let (mut ci, mut ti) = (0, 0);
191 let (mut c_off, mut t_off) = (0, 0);
192 while ci < current.len() && ti < target.len() {
193 let (c_text, c_attr) = current[ci];
194 let (t_text, t_attr) = target[ti];
195 let take = (c_text.len() - c_off).min(t_text.len() - t_off);
196 let piece = &c_text[c_off..c_off + take];
197 let change = if c_attr == t_attr {
198 TextMeta::default()
199 } else {
200 style_change(c_attr, t_attr)
201 };
202 edit.push_retain(text_len(piece), change);
203 c_off += take;
204 t_off += take;
205 if c_off == c_text.len() {
206 ci += 1;
207 c_off = 0;
208 }
209 if t_off == t_text.len() {
210 ti += 1;
211 t_off = 0;
212 }
213 }
214}
215
216/// Keeps the text of the common prefix and suffix (compared by content; differing styles are
217/// re-marked) and replaces the middle. Works on style runs, so its cost is a byte comparison
218/// of the two texts plus the number of runs.
219fn align_text(target: &TextDiff, current: &TextDiff) -> Option<TextDiff> {
220 let target = text_runs(target)?;
221 let current = text_runs(current)?;
222 let target_text: String = target.iter().map(|(s, _)| *s).collect();
223 let current_text: String = current.iter().map(|(s, _)| *s).collect();
224 let (t, c) = (target_text.as_bytes(), current_text.as_bytes());
225 let mut prefix = t.iter().zip(c).take_while(|(x, y)| x == y).count();
226 while !target_text.is_char_boundary(prefix) {
227 prefix -= 1;
228 }
229 let mut suffix = t[prefix..]
230 .iter()
231 .rev()
232 .zip(c[prefix..].iter().rev())
233 .take_while(|(x, y)| x == y)
234 .count();
235 while !target_text.is_char_boundary(t.len() - suffix) {
236 suffix -= 1;
237 }
238 let mut edit = TextDiff::new();
239 push_restyled_retain(
240 &mut edit,
241 &slice_runs(&current, 0..prefix),
242 &slice_runs(&target, 0..prefix),
243 );
244 edit.push_delete(text_len(&current_text[prefix..c.len() - suffix]));
245 for (text, attr) in slice_runs(&target, prefix..t.len() - suffix) {
246 edit.push_insert(StringSlice::from(text), attr.clone());
247 }
248 push_restyled_retain(
249 &mut edit,
250 &slice_runs(&current, c.len() - suffix..c.len()),
251 &slice_runs(&target, t.len() - suffix..t.len()),
252 );
253 Some(edit)
254}
255
256/// `None` if `diff` is not a pure insertion.
257fn list_items(diff: &ListDiff) -> Option<Vec<&ValueOrHandler>> {
258 let mut ans = Vec::new();
259 for item in diff.iter() {
260 let DeltaItem::Replace {
261 value, delete: 0, ..
262 } = item
263 else {
264 return None;
265 };
266 ans.extend(value.iter());
267 }
268 Some(ans)
269}
270
271/// Keeps the common prefix and suffix (equal values, containers by id) and replaces the middle.
272///
273/// In a movable list, `apply_delta` turns deleting a child container and re-inserting it into
274/// a move (see `movable_list_apply_delta.rs`), so middle children that exist in both lists
275/// keep their id as well. A plain list recreates them under fresh ids.
276fn align_list(
277 target: &ListDiff,
278 current: &ListDiff,
279 movable: bool,
280 full_state_targets: &mut FxHashSet<ContainerID>,
281) -> Option<ListDiff> {
282 let target = list_items(target)?;
283 let current = list_items(current)?;
284 let target_values: Vec<LoroValue> = target.iter().map(|v| v.to_value()).collect();
285 let current_values: Vec<LoroValue> = current.iter().map(|v| v.to_value()).collect();
286 let (prefix, suffix) = common_ends(&target_values, &current_values);
287 let mut kept: Vec<&LoroValue> = target_values[..prefix]
288 .iter()
289 .chain(&target_values[target_values.len() - suffix..])
290 .collect();
291 if movable {
292 let current_middle: FxHashSet<&ContainerID> = current_values
293 [prefix..current_values.len() - suffix]
294 .iter()
295 .filter_map(|v| v.as_container())
296 .collect();
297 kept.extend(
298 target_values[prefix..target_values.len() - suffix]
299 .iter()
300 .filter(|v| {
301 v.as_container()
302 .is_some_and(|id| current_middle.contains(id))
303 }),
304 );
305 }
306 for v in kept {
307 if let LoroValue::Container(id) = v {
308 full_state_targets.insert(id.clone());
309 }
310 }
311 let mut edit: ListDiff = DeltaRope::new();
312 if prefix == target.len() && prefix == current.len() {
313 return Some(edit);
314 }
315 edit.push_retain(prefix, ListDeltaMeta::default());
316 edit.push_delete(current.len() - prefix - suffix);
317 for v in &target[prefix..target.len() - suffix] {
318 edit.push_insert(ArrayVec::from([(*v).clone()]), ListDeltaMeta::default());
319 }
320 Some(edit)
321}
322
323/// Keeps nodes by `TreeID`: creates missing ones, moves kept ones whose parent or position
324/// differ, and deletes the rest.
325fn align_tree(
326 target: &TreeDiff,
327 current: &TreeDiff,
328 full_state_targets: &mut FxHashSet<ContainerID>,
329) -> Option<TreeDiff> {
330 let mut current_nodes: FxHashMap<TreeID, (TreeParentId, &FractionalIndex, usize)> =
331 FxHashMap::default();
332 for item in current.diff.iter() {
333 let TreeExternalDiff::Create {
334 parent,
335 index,
336 position,
337 } = &item.action
338 else {
339 return None;
340 };
341 current_nodes.insert(item.target, (*parent, position, *index));
342 }
343 let mut edit = TreeDiff::default();
344 let mut target_nodes = FxHashSet::default();
345 for item in target.diff.iter() {
346 let TreeExternalDiff::Create {
347 parent, position, ..
348 } = &item.action
349 else {
350 return None;
351 };
352 target_nodes.insert(item.target);
353 match current_nodes.get(&item.target) {
354 Some((p, pos, _)) if p == parent && *pos == position => {
355 full_state_targets.insert(item.target.associated_meta_container());
356 }
357 Some(_) => {
358 // `apply_diff` moves a `Create` target that is still alive.
359 full_state_targets.insert(item.target.associated_meta_container());
360 edit.diff.push(item.clone());
361 }
362 None => edit.diff.push(item.clone()),
363 }
364 }
365 for (id, (parent, _, index)) in current_nodes {
366 if !target_nodes.contains(&id) {
367 edit.diff.push(TreeDiffItem {
368 target: id,
369 action: TreeExternalDiff::Delete {
370 old_parent: parent,
371 old_index: index,
372 },
373 });
374 }
375 }
376 Some(edit)
377}