forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

richtext_state.rs1979 lines, 75.9 KiBHistoryRawDownload
1use generic_btree::{rle::HasLength, rle::Sliceable as _, Cursor};
2use loro_common::{ContainerID, InternalString, LoroError, LoroResult, LoroValue, ID};
3use loro_delta::{DeltaRope, DeltaRopeBuilder};
4use rustc_hash::{FxHashMap, FxHashSet};
5use smallvec::SmallVec;
6use std::ops::Range;
7use std::sync::{Arc, Weak};
8
9use crate::{
10 container::{
11 idx::ContainerIdx,
12 list::list_op,
13 richtext::{
14 config::StyleConfigMap,
15 richtext_state::{DrainInfo, EntityRanges, IterRangeItem, PosType, RichtextStateChunk},
16 AnchorType, RichtextState as InnerState, StyleKey, StyleOp, Styles,
17 },
18 },
19 delta::{StyleMeta, StyleMetaItem},
20 event::{Diff, Index, InternalDiff, TextDiff},
21 handler::TextDelta,
22 op::{Op, RawOp},
23 sync::RwLock,
24 utils::{lazy::LazyLoad, string_slice::StringSlice},
25 LoroDocInner,
26};
27
28use super::{ApplyLocalOpReturn, ContainerState, DiffApplyContext};
29
30#[derive(Debug)]
31pub struct RichtextState {
32 idx: ContainerIdx,
33 config: Arc<RwLock<StyleConfigMap>>,
34 state: LazyLoad<RichtextStateLoader, InnerState>,
35 /// This is used to indicate whether the richtext state is changed, so the downstream has an easy way to cache
36 /// NOTE: We need to ensure the invariance that the version id is always increased when the richtext state is changed
37 version_id: usize,
38}
39
40struct Pos {
41 entity_index: usize,
42 event_index: usize,
43}
44
45impl RichtextState {
46 #[inline]
47 pub fn new(idx: ContainerIdx, config: Arc<RwLock<StyleConfigMap>>) -> Self {
48 Self {
49 idx,
50 config,
51 state: LazyLoad::Src(Default::default()),
52 version_id: 0,
53 }
54 }
55
56 #[inline]
57 fn update_version(&mut self) {
58 self.version_id = self.version_id.wrapping_add(1);
59 }
60
61 /// Get the version id of the richtext
62 ///
63 /// This can be used to detect whether the richtext is changed
64 #[inline]
65 pub fn get_version_id(&self) -> usize {
66 self.version_id
67 }
68
69 /// Get the text content of the richtext
70 ///
71 /// This uses `mut` because we may need to build the state from snapshot
72 #[inline]
73 pub fn to_string_mut(&mut self) -> String {
74 self.state.get_mut().to_string()
75 }
76
77 #[allow(unused)]
78 #[inline(always)]
79 pub(crate) fn is_empty(&self) -> bool {
80 match &self.state {
81 LazyLoad::Src(s) => s.elements.is_empty(),
82 LazyLoad::Dst(d) => d.is_empty(),
83 }
84 }
85
86 pub(crate) fn diagnose(&self) {
87 match &self.state {
88 LazyLoad::Src(_) => {}
89 LazyLoad::Dst(d) => d.diagnose(),
90 }
91 }
92
93 #[allow(unused)]
94 pub(crate) fn get_text_slice_by_event_index(
95 &mut self,
96 pos: usize,
97 len: usize,
98 ) -> LoroResult<String> {
99 self.state.get_mut().get_text_slice_by_event_index(pos, len)
100 }
101
102 pub(crate) fn slice_delta(
103 &mut self,
104 start_index: usize,
105 end_index: usize,
106 pos_type: PosType,
107 ) -> LoroResult<Vec<(String, StyleMeta)>> {
108 self.state
109 .get_mut()
110 .slice_delta(start_index, end_index, pos_type)
111 }
112
113 #[allow(unused)]
114 pub(crate) fn get_char_by_event_index(&mut self, pos: usize) -> Result<char, ()> {
115 self.state.get_mut().get_char_by_event_index(pos)
116 }
117
118 pub(crate) fn iter(&mut self, mut callback: impl FnMut(&str) -> bool) {
119 for span in self.state.get_mut().iter_chunk() {
120 match span {
121 RichtextStateChunk::Text(text_chunk) => {
122 if !callback(text_chunk.as_str()) {
123 return;
124 }
125 }
126 RichtextStateChunk::Style { .. } => {}
127 }
128 }
129 }
130
131 pub(crate) fn iter_raw(&self, callback: &mut dyn FnMut(&RichtextStateChunk)) {
132 let iter: &mut dyn Iterator<Item = &RichtextStateChunk>;
133 let mut a;
134 let mut b;
135 match &self.state {
136 LazyLoad::Src(s) => {
137 a = Some(s.elements.iter());
138 iter = &mut *a.as_mut().unwrap();
139 }
140 LazyLoad::Dst(s) => {
141 b = Some(s.iter_chunk());
142 iter = &mut *b.as_mut().unwrap();
143 }
144 }
145
146 for c in iter {
147 callback(c);
148 }
149 }
150
151 fn get_style_start(
152 &mut self,
153 style_starts: &mut FxHashMap<Arc<StyleOp>, Pos>,
154 style: &Arc<StyleOp>,
155 ) -> Pos {
156 self.update_version();
157 match style_starts.remove(style) {
158 Some(x) => x,
159 None => {
160 // this should happen rarely, so it should be fine to scan
161 let mut pos = Pos {
162 entity_index: 0,
163 event_index: 0,
164 };
165
166 for c in self.state.get_mut().iter_chunk() {
167 match c {
168 RichtextStateChunk::Style {
169 style: s,
170 anchor_type: AnchorType::Start,
171 } if style == s => {
172 break;
173 }
174 RichtextStateChunk::Text(t) => {
175 pos.entity_index += t.unicode_len() as usize;
176 pos.event_index += t.event_len() as usize;
177 }
178 RichtextStateChunk::Style { .. } => {
179 pos.entity_index += 1;
180 }
181 }
182 }
183 pos
184 }
185 }
186 }
187
188 pub fn get_index_of_id(&self, id: ID) -> Option<usize> {
189 let iter: &mut dyn Iterator<Item = &RichtextStateChunk>;
190 let mut a;
191 let mut b;
192 match &self.state {
193 LazyLoad::Src(s) => {
194 a = Some(s.elements.iter());
195 iter = &mut *a.as_mut().unwrap();
196 }
197 LazyLoad::Dst(s) => {
198 b = Some(s.iter_chunk());
199 iter = &mut *b.as_mut().unwrap();
200 }
201 }
202
203 let mut index = 0;
204 for elem in iter {
205 let span = elem.get_id_span();
206 if span.contains(id) {
207 return Some(index + (id.counter - span.counter.start) as usize);
208 }
209
210 index += elem.rle_len();
211 }
212
213 None
214 }
215
216 pub fn get_text_index_of_id(&self, id: ID, use_event_index: bool) -> Option<usize> {
217 let iter: &mut dyn Iterator<Item = &RichtextStateChunk>;
218 let mut a;
219 let mut b;
220 match &self.state {
221 LazyLoad::Src(s) => {
222 a = Some(s.elements.iter());
223 iter = &mut *a.as_mut().unwrap();
224 }
225 LazyLoad::Dst(s) => {
226 b = Some(s.iter_chunk());
227 iter = &mut *b.as_mut().unwrap();
228 }
229 }
230
231 let mut index = 0;
232 for elem in iter {
233 let span = elem.get_id_span();
234 if span.contains(id) {
235 match elem {
236 RichtextStateChunk::Text(t) => {
237 if use_event_index {
238 let event_offset = t.convert_unicode_offset_to_event_offset(
239 (id.counter - span.counter.start) as usize,
240 );
241 return Some(index + event_offset);
242 } else {
243 return Some(index + (id.counter - span.counter.start) as usize);
244 }
245 }
246 RichtextStateChunk::Style { .. } => {
247 return Some(index);
248 }
249 }
250 }
251
252 index += match elem {
253 RichtextStateChunk::Text(t) => {
254 if use_event_index {
255 t.event_len() as usize
256 } else {
257 t.unicode_len() as usize
258 }
259 }
260 RichtextStateChunk::Style { .. } => 0,
261 };
262 }
263
264 None
265 }
266
267 pub(crate) fn get_delta(&mut self) -> Vec<TextDelta> {
268 let mut delta = Vec::new();
269 for span in self.state.get_mut().iter() {
270 let next_attr = span.attributes.to_option_map();
271 match delta.last_mut() {
272 Some(TextDelta::Insert { insert, attributes }) if &next_attr == attributes => {
273 insert.push_str(span.text.as_str());
274 continue;
275 }
276 _ => {}
277 }
278 delta.push(TextDelta::Insert {
279 insert: span.text.as_str().to_string(),
280 attributes: next_attr,
281 })
282 }
283 delta
284 }
285}
286
287#[cfg(test)]
288mod tests {
289 use crate::{container::richtext::StyleKey, cursor::PosType, handler::HandlerTrait, LoroDoc};
290
291 #[test]
292 fn has_style_key_in_entity_range_basic() {
293 let loro = LoroDoc::new_auto_commit();
294 let text = loro.get_text("text");
295 text.insert(0, "abcdef", PosType::Unicode).unwrap();
296 text.mark(1, 3, "bold", true.into(), PosType::Unicode)
297 .unwrap();
298
299 let bold_key = StyleKey::Key("bold".into());
300 let has_style = text
301 .with_state(|state| {
302 let st = state.as_richtext_state_mut().unwrap();
303 let (entity_range, _) =
304 st.get_entity_range_and_styles_at_range(1..3, PosType::Unicode);
305 Ok(st.has_style_key_in_entity_range(entity_range, &bold_key))
306 })
307 .unwrap();
308 assert!(has_style);
309
310 let missing = text
311 .with_state(|state| {
312 let st = state.as_richtext_state_mut().unwrap();
313 let (entity_range, _) =
314 st.get_entity_range_and_styles_at_range(4..5, PosType::Unicode);
315 Ok(st.has_style_key_in_entity_range(entity_range, &bold_key))
316 })
317 .unwrap();
318 assert!(!missing);
319 }
320
321 #[test]
322 fn has_style_key_in_entity_range_spans_elements() {
323 let loro = LoroDoc::new_auto_commit();
324 let text = loro.get_text("text");
325 text.insert(0, "abcdefgh", PosType::Unicode).unwrap();
326 text.mark(0, 2, "bold", true.into(), PosType::Unicode)
327 .unwrap();
328 text.mark(3, 5, "bold", true.into(), PosType::Unicode)
329 .unwrap();
330
331 let bold_key = StyleKey::Key("bold".into());
332
333 let has_style_across_segments = text
334 .with_state(|state| {
335 let st = state.as_richtext_state_mut().unwrap();
336 let (entity_range, _) =
337 st.get_entity_range_and_styles_at_range(0..5, PosType::Unicode);
338 Ok(st.has_style_key_in_entity_range(entity_range, &bold_key))
339 })
340 .unwrap();
341 assert!(has_style_across_segments);
342
343 let gap_has_style = text
344 .with_state(|state| {
345 let st = state.as_richtext_state_mut().unwrap();
346 let (entity_range, _) =
347 st.get_entity_range_and_styles_at_range(6..7, PosType::Unicode);
348 Ok(st.has_style_key_in_entity_range(entity_range, &bold_key))
349 })
350 .unwrap();
351 assert!(!gap_has_style);
352 }
353}
354
355impl Clone for RichtextState {
356 fn clone(&self) -> Self {
357 Self {
358 idx: self.idx,
359 config: self.config.clone(),
360 state: self.state.clone(),
361 version_id: self.version_id,
362 }
363 }
364}
365
366impl ContainerState for RichtextState {
367 fn container_idx(&self) -> ContainerIdx {
368 self.idx
369 }
370
371 fn is_state_empty(&self) -> bool {
372 match &self.state {
373 LazyLoad::Src(s) => s.is_empty(),
374 LazyLoad::Dst(s) => s.is_empty(),
375 }
376 }
377
378 // TODO: refactor
379 fn apply_diff_and_convert(&mut self, diff: InternalDiff, _ctx: DiffApplyContext) -> Diff {
380 self.update_version();
381 let InternalDiff::RichtextRaw(richtext) = diff else {
382 unreachable!()
383 };
384
385 // tracing::info!("Self state = {:#?}", &self);
386 // PERF: compose delta
387 let mut ans: TextDiff = TextDiff::new();
388 let mut style_delta: TextDiff = TextDiff::new();
389 let mut style_starts: FxHashMap<Arc<StyleOp>, Pos> = FxHashMap::default();
390 let mut entity_index = 0;
391 let mut event_index = 0;
392 let mut new_style_deltas: Vec<TextDiff> = Vec::new();
393 for span in richtext.iter() {
394 match span {
395 loro_delta::DeltaItem::Retain { len, .. } => {
396 entity_index += len;
397 }
398 loro_delta::DeltaItem::Replace { value, delete, .. } => {
399 if *delete > 0 {
400 // Deletions
401 let mut deleted_style_keys: FxHashSet<InternalString> =
402 FxHashSet::default();
403 let DrainInfo {
404 start_event_index: start,
405 end_event_index: end,
406 affected_style_range,
407 } = self.state.get_mut().drain_by_entity_index(
408 entity_index,
409 *delete,
410 Some(&mut |c| match c {
411 RichtextStateChunk::Style {
412 style,
413 anchor_type: AnchorType::Start,
414 } => {
415 deleted_style_keys.insert(style.key.clone());
416 }
417 RichtextStateChunk::Style {
418 style,
419 anchor_type: AnchorType::End,
420 } => {
421 deleted_style_keys.insert(style.key.clone());
422 }
423 _ => {}
424 }),
425 );
426
427 if start > event_index {
428 ans.push_retain(start - event_index, Default::default());
429 event_index = start;
430 }
431
432 if let Some((entity_range, event_range)) = affected_style_range {
433 let mut delta: TextDiff = DeltaRopeBuilder::new()
434 .retain(event_range.start, Default::default())
435 .build();
436 let mut entity_len_sum = 0;
437 let expected_sum = entity_range.len();
438
439 for IterRangeItem {
440 event_len,
441 chunk,
442 styles,
443 entity_len,
444 ..
445 } in self.state.get_mut().iter_range(entity_range)
446 {
447 entity_len_sum += entity_len;
448 match chunk {
449 RichtextStateChunk::Text(_) => {
450 let mut style_meta: StyleMeta = styles.into();
451 for key in deleted_style_keys.iter() {
452 if !style_meta.contains_key(key) {
453 style_meta.insert(
454 key.clone(),
455 StyleMetaItem {
456 lamport: 0,
457 peer: 0,
458 value: LoroValue::Null,
459 },
460 )
461 }
462 }
463 delta.push_retain(
464 event_len,
465 style_meta.to_option_map().unwrap_or_default().into(),
466 );
467 }
468 RichtextStateChunk::Style { .. } => {}
469 }
470 }
471
472 debug_assert_eq!(entity_len_sum, expected_sum);
473 delta.chop();
474 style_delta.compose(&delta);
475 }
476
477 ans.push_delete(end - start);
478 }
479
480 if value.rle_len() > 0 {
481 // Insertions
482 match value {
483 RichtextStateChunk::Text(s) => {
484 let (pos, styles) =
485 self.state.get_mut().insert_elem_at_entity_index(
486 entity_index,
487 RichtextStateChunk::Text(s.clone()),
488 );
489 // PERF: this can be optimized
490 let insert_styles = Into::<StyleMeta>::into(styles.clone())
491 .to_option_map()
492 .unwrap_or_default();
493
494 if pos > event_index {
495 ans.push_retain(pos - event_index, Default::default());
496 }
497 event_index = pos + s.event_len() as usize;
498 ans.push_insert(
499 StringSlice::from(s.bytes().clone()),
500 insert_styles.into(),
501 );
502 }
503 RichtextStateChunk::Style { anchor_type, style } => {
504 let (new_event_index, _) =
505 self.state.get_mut().insert_elem_at_entity_index(
506 entity_index,
507 RichtextStateChunk::Style {
508 style: style.clone(),
509 anchor_type: *anchor_type,
510 },
511 );
512
513 if new_event_index > event_index {
514 ans.push_retain(
515 new_event_index - event_index,
516 Default::default(),
517 );
518 // inserting style anchor will not affect event_index's positions
519 event_index = new_event_index;
520 }
521
522 match anchor_type {
523 AnchorType::Start => {
524 style_starts.insert(
525 style.clone(),
526 Pos {
527 entity_index,
528 event_index: new_event_index,
529 },
530 );
531 }
532 AnchorType::End => {
533 // get the pair of style anchor. now we can annotate the range
534 let Pos {
535 entity_index: start_entity_index,
536 event_index: start_event_index,
537 } = self.get_style_start(&mut style_starts, style);
538 let mut delta: TextDiff = DeltaRopeBuilder::new()
539 .retain(start_event_index, Default::default())
540 .build();
541 // we need to + 1 because we also need to annotate the end anchor
542 let event =
543 self.state.get_mut().annotate_style_range_with_event(
544 start_entity_index..entity_index + 1,
545 style.clone(),
546 );
547 for (s, l) in event {
548 delta.push_retain(
549 l,
550 s.to_option_map().unwrap_or_default().into(),
551 );
552 }
553
554 delta.chop();
555 new_style_deltas.push(delta);
556 }
557 }
558 }
559 }
560
561 entity_index += value.rle_len();
562 }
563 }
564 }
565 }
566
567 for s in new_style_deltas {
568 style_delta.compose(&s);
569 }
570 // self.check_consistency_between_content_and_style_ranges();
571 ans.compose(&style_delta);
572 Diff::Text(ans)
573 }
574
575 fn validate_diff(&self, diff: &InternalDiff) -> LoroResult<()> {
576 let InternalDiff::RichtextRaw(delta) = diff else {
577 unreachable!()
578 };
579
580 // Text items are addressed by entity index (style anchors included).
581 let mut cursor = 0usize;
582 let mut projected = match &self.state {
583 LazyLoad::Src(s) => s.entity_index,
584 LazyLoad::Dst(s) => s.len_entity(),
585 };
586 for span in delta.iter() {
587 match span {
588 loro_delta::DeltaItem::Retain { len, .. } => {
589 cursor += len;
590 if cursor > projected {
591 return Err(LoroError::DecodeError(
592 format!(
593 "text diff retains {cursor} items but state only has {projected}"
594 )
595 .into_boxed_str(),
596 ));
597 }
598 }
599 loro_delta::DeltaItem::Replace { value, delete, .. } => {
600 if cursor + delete > projected {
601 return Err(LoroError::DecodeError(
602 format!("text diff deletes {delete} at {cursor} but state only has {projected}")
603 .into_boxed_str(),
604 ));
605 }
606 projected = projected - delete + value.rle_len();
607 cursor += value.rle_len();
608 }
609 }
610 }
611
612 Ok(())
613 }
614
615 fn apply_diff(&mut self, diff: InternalDiff, _ctx: DiffApplyContext) -> LoroResult<()> {
616 self.update_version();
617 let InternalDiff::RichtextRaw(richtext) = diff else {
618 unreachable!()
619 };
620
621 if let LazyLoad::Src(loader) = &mut self.state {
622 if loader.try_apply_append_delta(&richtext) {
623 return Ok(());
624 }
625 }
626
627 // Fast path for plain-text deltas (no style anchors / style ranges).
628 //
629 // Rebuilding avoids repeated BTree queries and mutations when the delta is very "choppy"
630 // (many small edit spans), but it allocates and clones chunks, so it can be slower for
631 // small deltas. Use a cheap cost model to enable it only when it's likely beneficial.
632 let should_fast_apply = {
633 #[inline]
634 fn ilog2_ceil(x: usize) -> usize {
635 debug_assert!(x > 0);
636 (usize::BITS - (x - 1).leading_zeros()) as usize
637 }
638
639 let state = self.state.get_mut();
640 if state.has_styles() {
641 false
642 } else {
643 // `edit_actions` approximates how many BTree mutations the incremental path will do:
644 // each Replace with delete>0 becomes a drain, and each Replace with value>0 becomes an insert.
645 let mut edit_actions: usize = 0;
646 let mut is_plain_text_delta = true;
647 for span in richtext.iter() {
648 match span {
649 loro_delta::DeltaItem::Retain { .. } => {}
650 loro_delta::DeltaItem::Replace { value, delete, .. } => {
651 if *delete > 0 {
652 edit_actions += 1;
653 }
654 if value.rle_len() > 0 {
655 if !matches!(value, RichtextStateChunk::Text(_)) {
656 is_plain_text_delta = false;
657 break;
658 }
659 edit_actions += 1;
660 }
661 }
662 }
663 }
664
665 if !is_plain_text_delta || edit_actions == 0 {
666 false
667 } else {
668 let content_nodes = state.content_node_len().max(1);
669 let log_n = ilog2_ceil(content_nodes + 1).max(1);
670 let incremental_score = edit_actions.saturating_mul(log_n);
671 let rebuild_score = content_nodes.saturating_add(edit_actions);
672
673 let old_len = richtext.old_len().max(1);
674 let avg_action_span = old_len / edit_actions;
675 // A very rough proxy for "choppiness": many edit actions with small average span.
676 // The thresholds are intentionally conservative to avoid rebuilding for small or
677 // localized deltas.
678 let is_choppy = edit_actions >= 256 && avg_action_span <= 32;
679
680 is_choppy && incremental_score >= rebuild_score.saturating_mul(4)
681 }
682 }
683 };
684
685 if should_fast_apply {
686 let new_state = {
687 let state = self.state.get_mut();
688 let mut chunks: Vec<RichtextStateChunk> = Vec::new();
689
690 let mut src_iter = state.iter_chunk();
691 let mut cur = src_iter.next();
692 let mut cur_offset: usize = 0;
693
694 for span in richtext.iter() {
695 match span {
696 loro_delta::DeltaItem::Retain { len, .. } => {
697 let mut left = *len;
698 while left > 0 {
699 let chunk = cur.expect("Delta retain exceeds source length");
700 let chunk_len = chunk.rle_len();
701 if chunk_len == 0 {
702 cur = src_iter.next();
703 cur_offset = 0;
704 continue;
705 }
706 let available = chunk_len - cur_offset;
707 let take = left.min(available);
708 if take == chunk_len && cur_offset == 0 {
709 chunks.push(chunk.clone());
710 } else {
711 chunks.push(chunk.slice(cur_offset..cur_offset + take));
712 }
713
714 left -= take;
715 cur_offset += take;
716 if cur_offset == chunk_len {
717 cur = src_iter.next();
718 cur_offset = 0;
719 }
720 }
721 }
722 loro_delta::DeltaItem::Replace { value, delete, .. } => {
723 let mut left = *delete;
724 while left > 0 {
725 let chunk = cur.expect("Delta delete exceeds source length");
726 let chunk_len = chunk.rle_len();
727 if chunk_len == 0 {
728 cur = src_iter.next();
729 cur_offset = 0;
730 continue;
731 }
732 let available = chunk_len - cur_offset;
733 let take = left.min(available);
734 left -= take;
735 cur_offset += take;
736 if cur_offset == chunk_len {
737 cur = src_iter.next();
738 cur_offset = 0;
739 }
740 }
741
742 if value.rle_len() > 0 {
743 chunks.push(value.clone());
744 }
745 }
746 }
747 }
748
749 if let Some(chunk) = cur {
750 let chunk_len = chunk.rle_len();
751 if cur_offset < chunk_len {
752 if cur_offset == 0 {
753 chunks.push(chunk.clone());
754 } else {
755 chunks.push(chunk.slice(cur_offset..chunk_len));
756 }
757 }
758 }
759 for chunk in src_iter {
760 chunks.push(chunk.clone());
761 }
762
763 InnerState::from_chunks(chunks.into_iter())
764 };
765
766 *self.state.get_mut() = new_state;
767 return Ok(());
768 }
769
770 let mut style_starts: FxHashMap<Arc<StyleOp>, usize> = FxHashMap::default();
771 let mut entity_index = 0;
772 for span in richtext.iter() {
773 match span {
774 loro_delta::DeltaItem::Retain { len, .. } => {
775 entity_index += len;
776 }
777 loro_delta::DeltaItem::Replace { value, delete, .. } => {
778 if *delete > 0 {
779 // Deletions
780 self.state
781 .get_mut()
782 .drain_by_entity_index(entity_index, *delete, None);
783 }
784 if value.rle_len() > 0 {
785 // Insertions
786 match value {
787 RichtextStateChunk::Text(s) => {
788 self.state.get_mut().insert_elem_at_entity_index(
789 entity_index,
790 RichtextStateChunk::Text(s.clone()),
791 );
792 }
793 RichtextStateChunk::Style { style, anchor_type } => {
794 self.state.get_mut().insert_elem_at_entity_index(
795 entity_index,
796 RichtextStateChunk::Style {
797 style: style.clone(),
798 anchor_type: *anchor_type,
799 },
800 );
801
802 if *anchor_type == AnchorType::Start {
803 style_starts.insert(style.clone(), entity_index);
804 } else {
805 let start_pos = match style_starts.get(style) {
806 Some(x) => *x,
807 None => {
808 // This should be rare, so it should be fine to scan
809 let mut start_entity_index = 0;
810 for c in self.state.get_mut().iter_chunk() {
811 match c {
812 RichtextStateChunk::Style {
813 style: s,
814 anchor_type: AnchorType::Start,
815 } if style == s => {
816 break;
817 }
818 RichtextStateChunk::Text(t) => {
819 start_entity_index +=
820 t.unicode_len() as usize;
821 }
822 RichtextStateChunk::Style { .. } => {
823 start_entity_index += 1;
824 }
825 }
826 }
827 start_entity_index
828 }
829 };
830 // we need to + 1 because we also need to annotate the end anchor
831 self.state.get_mut().annotate_style_range(
832 start_pos..entity_index + 1,
833 style.clone(),
834 );
835 }
836 }
837 }
838 entity_index += value.rle_len();
839 }
840 }
841 }
842 }
843
844 // self.check_consistency_between_content_and_style_ranges()
845 Ok(())
846 }
847
848 fn apply_local_op(&mut self, r_op: &RawOp, op: &Op) -> LoroResult<ApplyLocalOpReturn> {
849 self.update_version();
850 match &op.content {
851 crate::op::InnerContent::List(l) => match l {
852 list_op::InnerListOp::Insert { slice: _, pos: _ } => {
853 unreachable!()
854 }
855 list_op::InnerListOp::InsertText {
856 slice,
857 unicode_len: _,
858 pos,
859 } => {
860 self.state.get_mut().insert_at_entity_index(
861 *pos as usize,
862 slice.clone(),
863 r_op.id_full(),
864 );
865 }
866 list_op::InnerListOp::Delete(del) => {
867 self.state.get_mut().drain_by_entity_index(
868 del.start() as usize,
869 rle::HasLength::atom_len(&del),
870 None,
871 );
872 }
873 list_op::InnerListOp::StyleStart {
874 start,
875 end,
876 key,
877 value,
878 info,
879 } => {
880 // Behavior here is a little different from apply_diff.
881 //
882 // When apply_diff, we only do the mark when we have included both
883 // StyleStart and StyleEnd.
884 //
885 // When applying local op, we can do the mark when we have StyleStart.
886 // We can assume StyleStart and StyleEnd are always appear in a pair
887 // for apply_local_op. (Because for local behavior, when we mark,
888 // we always create a pair of style ops.)
889 self.state.get_mut().mark_with_entity_index(
890 *start as usize..*end as usize,
891 Arc::new(StyleOp {
892 lamport: r_op.lamport,
893 peer: r_op.id.peer,
894 cnt: r_op.id.counter,
895 key: key.clone(),
896 value: value.clone(),
897 info: *info,
898 }),
899 );
900 }
901 list_op::InnerListOp::Set { .. } => {}
902 list_op::InnerListOp::StyleEnd => {}
903 list_op::InnerListOp::Move { .. } => unreachable!(),
904 },
905 _ => unreachable!(),
906 }
907
908 // self.check_consistency_between_content_and_style_ranges();
909 Ok(Default::default())
910 }
911
912 fn to_diff(&mut self, _doc: &Weak<LoroDocInner>) -> Diff {
913 // Coalesce adjacent spans first: each `push_insert` re-measures the merged
914 // slice, so pushing many small contiguous spans is quadratic. (project_note patch)
915 use generic_btree::rle::Mergeable;
916 let mut delta = TextDiff::new();
917 let mut pending: Option<(crate::utils::string_slice::StringSlice, crate::event::TextMeta)> = None;
918 for span in self.state.get_mut().iter() {
919 let meta: crate::event::TextMeta = span.attributes.to_option_map().unwrap_or_default().into();
920 if let Some((text, m)) = &mut pending {
921 if *m == meta && text.can_merge(&span.text) {
922 text.merge_right(&span.text);
923 continue;
924 }
925 }
926 if let Some((text, m)) = pending.replace((span.text, meta)) {
927 delta.push_insert(text, m);
928 }
929 }
930 if let Some((text, m)) = pending {
931 delta.push_insert(text, m);
932 }
933
934 Diff::Text(delta)
935 }
936
937 // value is a list
938 fn get_value(&mut self) -> LoroValue {
939 match &self.state {
940 LazyLoad::Src(loader) => loader.to_plain_string().into(),
941 LazyLoad::Dst(_) => self.state.get_mut().to_string().into(),
942 }
943 }
944
945 #[doc = r" Get the index of the child container"]
946 #[allow(unused)]
947 fn get_child_index(&self, id: &ContainerID) -> Option<Index> {
948 None
949 }
950
951 #[allow(unused)]
952 fn get_child_containers(&self) -> Vec<ContainerID> {
953 Vec::new()
954 }
955
956 fn contains_child(&self, _id: &ContainerID) -> bool {
957 false
958 }
959
960 fn fork(&self, config: &crate::configure::Configure) -> Self {
961 Self {
962 idx: self.idx,
963 config: config.text_style_config.clone(),
964 state: self.state.clone(),
965 version_id: 0,
966 }
967 }
968}
969
970impl RichtextState {
971 #[inline(always)]
972 pub fn len_utf8(&mut self) -> usize {
973 self.state.get_mut().len_utf8()
974 }
975
976 #[inline(always)]
977 pub fn len(&mut self, pos_type: PosType) -> usize {
978 self.state.get_mut().len(pos_type)
979 }
980
981 #[inline(always)]
982 pub fn len_utf16(&mut self) -> usize {
983 self.state.get_mut().len_utf16()
984 }
985
986 #[inline(always)]
987 pub fn len_entity(&self) -> usize {
988 match &self.state {
989 LazyLoad::Src(s) => s.entity_index,
990 LazyLoad::Dst(d) => d.len_entity(),
991 }
992 }
993
994 pub fn len_event(&mut self) -> usize {
995 if cfg!(feature = "wasm") {
996 self.len_utf16()
997 } else {
998 self.len_unicode()
999 }
1000 }
1001
1002 #[inline]
1003 #[allow(dead_code)]
1004 pub(crate) fn has_styles(&mut self) -> bool {
1005 self.state.get_mut().has_styles()
1006 }
1007
1008 pub(crate) fn has_style_key_in_entity_range(
1009 &mut self,
1010 range: Range<usize>,
1011 key: &StyleKey,
1012 ) -> bool {
1013 self.state.get_mut().range_has_style_key(range, key)
1014 }
1015
1016 pub(crate) fn has_style_key_value_in_entity_range(
1017 &mut self,
1018 range: Range<usize>,
1019 key: &str,
1020 value: &LoroValue,
1021 ) -> bool {
1022 self.state
1023 .get_mut()
1024 .range_has_style_key_value(range, key, value)
1025 }
1026
1027 /// Check if the content and style ranges are consistent.
1028 ///
1029 /// Panic if inconsistent.
1030 #[allow(unused)]
1031 pub(crate) fn check_consistency_between_content_and_style_ranges(&mut self) {
1032 if !cfg!(debug_assertions) {
1033 return;
1034 }
1035
1036 self.state
1037 .get_mut()
1038 .check_consistency_between_content_and_style_ranges();
1039 }
1040
1041 #[inline]
1042 pub fn len_unicode(&mut self) -> usize {
1043 self.state.get_mut().len_unicode()
1044 }
1045
1046 #[cfg(test)]
1047 pub(crate) fn inner_state_mut(&mut self) -> &mut InnerState {
1048 self.state.get_mut()
1049 }
1050
1051 #[inline]
1052 pub(crate) fn get_entity_index_for_text_insert(
1053 &mut self,
1054 index: usize,
1055 pos_type: PosType,
1056 ) -> Result<(usize, Option<Cursor>), LoroError> {
1057 self.state
1058 .get_mut()
1059 .get_entity_index_for_text_insert(index, pos_type)
1060 }
1061
1062 #[inline]
1063 pub(crate) fn get_event_index_by_cursor(&mut self, cursor: Cursor) -> usize {
1064 self.state.get_mut().cursor_to_event_index_cached(cursor)
1065 }
1066
1067 pub(crate) fn get_entity_range_and_styles_at_range(
1068 &mut self,
1069 range: Range<usize>,
1070 pos_type: PosType,
1071 ) -> (Range<usize>, Option<&Styles>) {
1072 self.state
1073 .get_mut()
1074 .get_entity_range_and_text_styles_at_range(range, pos_type)
1075 }
1076
1077 #[inline]
1078 pub(crate) fn get_styles_at_entity_index(&mut self, entity_index: usize) -> StyleMeta {
1079 self.state
1080 .get_mut()
1081 .get_styles_at_entity_index_for_insert(entity_index)
1082 }
1083
1084 #[inline]
1085 pub(crate) fn get_text_entity_ranges_in_event_index_range(
1086 &mut self,
1087 pos: usize,
1088 len: usize,
1089 ) -> LoroResult<EntityRanges> {
1090 self.state
1091 .get_mut()
1092 .get_text_entity_ranges(pos, len, PosType::Event)
1093 }
1094
1095 #[inline]
1096 pub fn get_richtext_value(&mut self) -> LoroValue {
1097 self.state.get_mut().get_richtext_value()
1098 }
1099
1100 #[inline]
1101 pub(crate) fn get_stable_position(
1102 &mut self,
1103 event_index: usize,
1104 get_by_event_index: bool,
1105 ) -> Option<ID> {
1106 self.state.get_mut().get_stable_position_at_event_index(
1107 event_index,
1108 if get_by_event_index {
1109 PosType::Event
1110 } else {
1111 PosType::Unicode
1112 },
1113 )
1114 }
1115
1116 pub(crate) fn entity_index_to_event_index(&mut self, entity_index: usize) -> usize {
1117 self.state
1118 .get_mut()
1119 .entity_index_to_event_index(entity_index)
1120 }
1121
1122 pub(crate) fn index_to_event_index(&mut self, index: usize, pos_type: PosType) -> usize {
1123 self.state.get_mut().index_to_event_index(index, pos_type)
1124 }
1125
1126 pub(crate) fn event_index_to_unicode_index(&mut self, event_index: usize) -> usize {
1127 self.state
1128 .get_mut()
1129 .event_index_to_unicode_index(event_index)
1130 }
1131
1132 pub(crate) fn event_index_to_index(&mut self, event_index: usize, pos_type: PosType) -> usize {
1133 self.state
1134 .get_mut()
1135 .event_index_to_index(event_index, pos_type)
1136 }
1137}
1138
1139#[derive(Debug, Default, Clone)]
1140pub(crate) struct RichtextStateLoader {
1141 start_anchor_pos: FxHashMap<ID, usize>,
1142 elements: SmallVec<[RichtextStateChunk; 1]>,
1143 style_ranges: Vec<(Arc<StyleOp>, Range<usize>)>,
1144 entity_index: usize,
1145}
1146
1147impl From<RichtextStateLoader> for InnerState {
1148 fn from(value: RichtextStateLoader) -> Self {
1149 value.into_state()
1150 }
1151}
1152
1153impl RichtextStateLoader {
1154 pub fn push(&mut self, elem: RichtextStateChunk) {
1155 if let RichtextStateChunk::Style { style, anchor_type } = &elem {
1156 if *anchor_type == AnchorType::Start {
1157 self.start_anchor_pos
1158 .insert(ID::new(style.peer, style.cnt), self.entity_index);
1159 } else {
1160 let start_pos = self
1161 .start_anchor_pos
1162 .remove(&ID::new(style.peer, style.cnt))
1163 .expect("Style start not found");
1164
1165 // we need to + 1 because we also need to annotate the end anchor
1166 self.style_ranges
1167 .push((style.clone(), start_pos..self.entity_index + 1));
1168 }
1169 }
1170
1171 self.entity_index += elem.rle_len();
1172 if matches!(&elem, RichtextStateChunk::Text(t) if t.bytes().len() > 2048) {
1173 self.elements.extend(elem.into_pieces());
1174 } else {
1175 self.elements.push(elem);
1176 }
1177 }
1178
1179 pub fn into_state(self) -> InnerState {
1180 let mut state = InnerState::from_chunks(self.elements.into_iter());
1181 for (style, range) in self.style_ranges {
1182 state.annotate_style_range(range, style);
1183 }
1184
1185 if cfg!(debug_assertions) {
1186 state.check();
1187 }
1188
1189 state
1190 }
1191
1192 fn is_empty(&self) -> bool {
1193 self.elements.is_empty()
1194 }
1195
1196 fn to_plain_string(&self) -> String {
1197 let len = self
1198 .elements
1199 .iter()
1200 .map(|elem| match elem {
1201 RichtextStateChunk::Text(text) => text.bytes().len(),
1202 RichtextStateChunk::Style { .. } => 0,
1203 })
1204 .sum();
1205 let mut text = String::with_capacity(len);
1206 for elem in &self.elements {
1207 if let RichtextStateChunk::Text(chunk) = elem {
1208 text.push_str(chunk.as_str());
1209 }
1210 }
1211 text
1212 }
1213
1214 fn try_apply_append_delta(&mut self, delta: &DeltaRope<RichtextStateChunk, ()>) -> bool {
1215 // Style anchors/ranges need InnerState's range maintenance.
1216 if !self.start_anchor_pos.is_empty() || !self.style_ranges.is_empty() {
1217 return false;
1218 }
1219
1220 let old_len = self.entity_index;
1221 let mut current_len = self.entity_index;
1222 let mut entity_index = 0;
1223 let mut appended = Vec::new();
1224 for span in delta.iter() {
1225 match span {
1226 loro_delta::DeltaItem::Retain { len, .. } => {
1227 entity_index += len;
1228 if entity_index > old_len {
1229 return false;
1230 }
1231 }
1232 loro_delta::DeltaItem::Replace { value, delete, .. } => {
1233 if *delete > 0 {
1234 return false;
1235 }
1236
1237 let insert_len = value.rle_len();
1238 if insert_len == 0 {
1239 continue;
1240 }
1241
1242 if !matches!(value, RichtextStateChunk::Text(_)) {
1243 return false;
1244 }
1245
1246 if entity_index != current_len {
1247 return false;
1248 }
1249
1250 appended.push(value.clone());
1251 entity_index += insert_len;
1252 current_len += insert_len;
1253 }
1254 }
1255 }
1256
1257 if appended.is_empty() {
1258 return false;
1259 }
1260
1261 for elem in appended {
1262 self.push(elem);
1263 }
1264 true
1265 }
1266}
1267
1268pub(crate) use snapshot::redact_dead_style_values;
1269
1270mod snapshot {
1271 use loro_common::{IdFull, InternalString, LoroResult, LoroValue, PeerID, ID};
1272 use rustc_hash::{FxHashMap, FxHashSet};
1273 use serde_columnar::columnar;
1274 use std::sync::Arc;
1275
1276 use crate::{
1277 container::richtext::{
1278 self, richtext_state::RichtextStateChunk, str_slice::StrSlice, StyleOp,
1279 TextStyleInfoFlag,
1280 },
1281 encoding::value_register::ValueRegister,
1282 state::{
1283 decode_lamport_from_delta, decode_peer_from_table, decode_peer_table,
1284 state_decode_error, ContainerCreationContext, ContainerState, FastStateSnapshot,
1285 },
1286 utils::lazy::LazyLoad,
1287 };
1288
1289 use super::{RichtextState, RichtextStateLoader};
1290
1291 #[columnar(vec, ser, de, iterable)]
1292 #[derive(Debug, Clone)]
1293 struct EncodedTextSpan {
1294 #[columnar(strategy = "DeltaRle")]
1295 peer_idx: usize,
1296 #[columnar(strategy = "DeltaRle")]
1297 counter: i32,
1298 #[columnar(strategy = "DeltaRle")]
1299 lamport_sub_counter: i32,
1300 /// positive for text
1301 /// 0 for mark start
1302 /// -1 for mark end
1303 #[columnar(strategy = "DeltaRle")]
1304 len: i32,
1305 }
1306
1307 #[columnar(vec, ser, de, iterable)]
1308 #[derive(Debug, Clone)]
1309 struct EncodedMark {
1310 key_idx: usize,
1311 value: LoroValue,
1312 info: u8,
1313 }
1314
1315 #[columnar(ser, de)]
1316 struct EncodedText {
1317 #[columnar(class = "vec", iter = "EncodedTextSpan")]
1318 spans: Vec<EncodedTextSpan>,
1319 keys: Vec<InternalString>,
1320 marks: Vec<EncodedMark>,
1321 }
1322
1323 impl EncodedText {
1324 // The columnar derives encode the outer struct and each mark as
1325 // three-element postcard sequences. Only the nested value field needs
1326 // a dedicated codec; spans still use the existing columnar strategies.
1327 fn decode(mut bytes: &[u8]) -> LoroResult<Self> {
1328 fn take<'a, T: serde::Deserialize<'a>>(bytes: &mut &'a [u8]) -> LoroResult<T> {
1329 let (value, rest) = postcard::take_from_bytes(bytes).map_err(|err| {
1330 state_decode_error(format!("Decode richtext fields failed: {err}"))
1331 })?;
1332 *bytes = rest;
1333 Ok(value)
1334 }
1335 if take::<usize>(&mut bytes)? != 3 {
1336 return Err(state_decode_error(
1337 "Decode richtext fields failed: invalid field count",
1338 ));
1339 }
1340 let spans: serde_columnar::ColumnarVec<'_, EncodedTextSpan, Vec<EncodedTextSpan>> =
1341 take(&mut bytes)?;
1342 let keys = take(&mut bytes)?;
1343 let count = take::<usize>(&mut bytes)?;
1344 let mut marks = Vec::new();
1345 for _ in 0..count {
1346 if take::<usize>(&mut bytes)? != 3 {
1347 return Err(state_decode_error(
1348 "Decode richtext mark failed: invalid field count",
1349 ));
1350 }
1351 let key_idx = take(&mut bytes)?;
1352 let (value, rest) = crate::state::value_decode::decode_value(bytes)?;
1353 bytes = rest;
1354 let info = take(&mut bytes)?;
1355 marks.push(EncodedMark {
1356 key_idx,
1357 value,
1358 info,
1359 });
1360 }
1361 if !bytes.is_empty() {
1362 return Err(state_decode_error(
1363 "Decode richtext fields failed: trailing bytes",
1364 ));
1365 }
1366 Ok(Self {
1367 spans: spans.into_vec(),
1368 keys,
1369 marks,
1370 })
1371 }
1372
1373 fn encode(&self) -> Vec<u8> {
1374 let mut bytes = Vec::new();
1375 postcard::to_io(&3usize, &mut bytes).unwrap();
1376 postcard::to_io(&serde_columnar::ColumnarVec::new(&self.spans), &mut bytes).unwrap();
1377 postcard::to_io(&self.keys, &mut bytes).unwrap();
1378 postcard::to_io(&self.marks.len(), &mut bytes).unwrap();
1379 for mark in &self.marks {
1380 postcard::to_io(&3usize, &mut bytes).unwrap();
1381 postcard::to_io(&mark.key_idx, &mut bytes).unwrap();
1382 crate::state::value_decode::encode_value(&mark.value, &mut bytes).unwrap();
1383 postcard::to_io(&mark.info, &mut bytes).unwrap();
1384 }
1385 bytes
1386 }
1387 }
1388
1389 /// Nulls out the values of style-anchor pairs that no longer enclose any text
1390 /// ("dead" pairs) in an encoded richtext state payload (the bytes produced by
1391 /// `RichtextState::encode_snapshot_fast`).
1392 ///
1393 /// Shallow-snapshot export uses this: history before the shallow root is
1394 /// trimmed, so a dead pair's value would otherwise ship in the export even
1395 /// though no read API can reach it. See
1396 /// `context/shallow-snapshot-style-redaction.md` for the invariants:
1397 ///
1398 /// - Anchors themselves must be preserved: op positions are entity indexes
1399 /// that count each anchor, so removing them would corrupt replay.
1400 /// - Pairs whose style expands on both sides are kept intact: an empty
1401 /// both-expand pair still captures future inserts, so its value is live.
1402 /// - When `only_pairs` is `Some`, only pairs whose `StyleStart` id is in the
1403 /// set are touched (used to keep an exported latest state consistent with
1404 /// the redacted shallow-root state).
1405 ///
1406 /// Returns `None` when nothing changed, otherwise the rewritten payload and
1407 /// the `StyleStart` ids of the redacted pairs.
1408 pub(crate) fn redact_dead_style_values(
1409 payload: &[u8],
1410 only_pairs: Option<&FxHashSet<ID>>,
1411 ) -> LoroResult<Option<(Vec<u8>, Vec<ID>)>> {
1412 const CTX: &str = "Redact dead style values failed";
1413 // Borrow the text prefix without copying it; only the columnar tail is
1414 // ever rewritten.
1415 let (_text, mut rest) = postcard::take_from_bytes::<&str>(payload)
1416 .map_err(|_| state_decode_error(format!("{CTX}: invalid text value")))?;
1417 let peers = decode_peer_table(&mut rest, CTX)?;
1418 let prefix_len = payload.len() - rest.len();
1419 let encoded = EncodedText::decode(rest)
1420 .map_err(|err| state_decode_error(format!("{CTX}: invalid spans: {err}")))?;
1421 if encoded.marks.is_empty() {
1422 return Ok(None);
1423 }
1424
1425 let EncodedText {
1426 spans,
1427 keys,
1428 mut marks,
1429 } = encoded;
1430 // Open pairs keyed by the id the matching `StyleEnd` span will carry
1431 // (`encode_snapshot_fast` writes the end span with start.counter + 1).
1432 // The value records the pair's mark index, its start counter, and how
1433 // many text spans had been seen when it opened: if that count is
1434 // unchanged when the pair closes, no text lies between the anchors.
1435 let mut open: FxHashMap<(usize, i32), (usize, i32, usize)> = FxHashMap::default();
1436 let mut start_count = 0usize;
1437 let mut text_spans_seen = 0usize;
1438 let mut redacted = Vec::new();
1439 for span in &spans {
1440 match span.len {
1441 0 => {
1442 let mark_idx = start_count;
1443 start_count += 1;
1444 if mark_idx >= marks.len() {
1445 return Err(state_decode_error(format!("{CTX}: missing style mark")));
1446 }
1447 let end_counter = span
1448 .counter
1449 .checked_add(1)
1450 .ok_or_else(|| state_decode_error(format!("{CTX}: counter overflow")))?;
1451 if open
1452 .insert(
1453 (span.peer_idx, end_counter),
1454 (mark_idx, span.counter, text_spans_seen),
1455 )
1456 .is_some()
1457 {
1458 return Err(state_decode_error(format!("{CTX}: duplicated style start")));
1459 }
1460 }
1461 -1 => {
1462 let Some((mark_idx, start_counter, text_spans_at_open)) =
1463 open.remove(&(span.peer_idx, span.counter))
1464 else {
1465 return Err(state_decode_error(format!("{CTX}: unmatched style end")));
1466 };
1467 if text_spans_at_open != text_spans_seen {
1468 // Text lies between the anchors; the pair is alive.
1469 continue;
1470 }
1471 let mark = &mut marks[mark_idx];
1472 let info = TextStyleInfoFlag::from_byte(mark.info);
1473 if info.expand_before() && info.expand_after() {
1474 // An empty both-expand pair still styles future inserts.
1475 continue;
1476 }
1477 if mark.value.is_null() {
1478 continue;
1479 }
1480 let peer = decode_peer_from_table(&peers, span.peer_idx, CTX)?;
1481 let id = ID::new(peer, start_counter);
1482 if only_pairs.is_some_and(|allow| !allow.contains(&id)) {
1483 continue;
1484 }
1485 mark.value = LoroValue::Null;
1486 redacted.push(id);
1487 }
1488 len if len > 0 => text_spans_seen += 1,
1489 _ => {
1490 return Err(state_decode_error(format!(
1491 "{CTX}: invalid text span length"
1492 )));
1493 }
1494 }
1495 }
1496
1497 // Pairs still open are a version that holds a mark's `StyleStart` but not its
1498 // `StyleEnd` (loro-dev/loro#1165). They style nothing yet, but the end may
1499 // still arrive, so leave their values alone.
1500 if start_count != marks.len() {
1501 return Err(state_decode_error(format!("{CTX}: unused style mark")));
1502 }
1503 if redacted.is_empty() {
1504 return Ok(None);
1505 }
1506
1507 let mut out = Vec::with_capacity(payload.len());
1508 out.extend_from_slice(&payload[..prefix_len]);
1509 out.extend_from_slice(&EncodedText { spans, keys, marks }.encode());
1510 Ok(Some((out, redacted)))
1511 }
1512
1513 impl FastStateSnapshot for RichtextState {
1514 /// Encodes the RichtextState into a compact binary format for fast snapshot storage and retrieval.
1515 ///
1516 /// The encoding format consists of:
1517 /// 1. The full text content as a string, encoded using postcard serialization.
1518 /// 2. A series of EncodedTextSpan structs representing text chunks and style markers:
1519 /// - peer_idx: Index of the peer ID in a value register (delta-RLE encoded)
1520 /// - counter: Operation counter (delta-RLE encoded)
1521 /// - lamport_sub_counter: Lamport timestamp - counter (delta-RLE encoded)
1522 /// - len: Length of text chunk or marker type (-1 for end, 0 for start, positive for text)
1523 /// 3. A list of unique style keys as InternalString.
1524 /// 4. A series of EncodedMark structs for style information:
1525 /// - key_idx: Index of the style key in the keys list
1526 /// - value: The style value
1527 /// - info: Additional style information as a byte
1528 fn encode_snapshot_fast<W: std::io::prelude::Write>(&mut self, mut w: W) {
1529 let value = self.get_value().into_string().unwrap();
1530 postcard::to_io(&*value, &mut w).unwrap();
1531 let mut spans = Vec::new();
1532 let mut marks = Vec::new();
1533
1534 let mut peers: ValueRegister<PeerID> = ValueRegister::new();
1535 let iter: &mut dyn Iterator<Item = &RichtextStateChunk>;
1536 let mut a;
1537 let mut b;
1538 match &self.state {
1539 LazyLoad::Src(s) => {
1540 a = Some(s.elements.iter());
1541 iter = &mut *a.as_mut().unwrap();
1542 }
1543 LazyLoad::Dst(s) => {
1544 b = Some(s.iter_chunk());
1545 iter = &mut *b.as_mut().unwrap();
1546 }
1547 }
1548
1549 let mut keys: ValueRegister<InternalString> = ValueRegister::new();
1550
1551 for chunk in iter {
1552 match chunk {
1553 RichtextStateChunk::Text(t) => {
1554 let id = t.id_full();
1555 assert!(t.unicode_len() > 0);
1556 spans.push(EncodedTextSpan {
1557 peer_idx: peers.register(&id.peer),
1558 counter: id.counter,
1559 lamport_sub_counter: id.lamport as i32 - id.counter,
1560 len: t.unicode_len(),
1561 })
1562 }
1563 RichtextStateChunk::Style { style, anchor_type } => match anchor_type {
1564 richtext::AnchorType::Start => {
1565 let id = style.id_full();
1566 spans.push(EncodedTextSpan {
1567 peer_idx: peers.register(&id.peer),
1568 counter: id.counter,
1569 lamport_sub_counter: id.lamport as i32 - id.counter,
1570 len: 0,
1571 });
1572 marks.push(EncodedMark {
1573 key_idx: keys.register(&style.key),
1574 value: style.value.clone(),
1575 info: style.info.to_byte(),
1576 })
1577 }
1578 richtext::AnchorType::End => {
1579 let id = style.id_full();
1580 spans.push(EncodedTextSpan {
1581 peer_idx: peers.register(&id.peer),
1582 counter: id.counter + 1,
1583 lamport_sub_counter: id.lamport as i32 - id.counter,
1584 len: -1,
1585 })
1586 }
1587 },
1588 }
1589 }
1590
1591 let peers = peers.unwrap_vec();
1592 leb128::write::unsigned(&mut w, peers.len() as u64).unwrap();
1593 for peer in peers {
1594 w.write_all(&peer.to_le_bytes()).unwrap();
1595 }
1596
1597 let bytes = EncodedText {
1598 spans,
1599 keys: keys.unwrap_vec(),
1600 marks,
1601 }
1602 .encode();
1603 w.write_all(&bytes).unwrap();
1604 }
1605
1606 fn decode_value(bytes: &[u8]) -> loro_common::LoroResult<(loro_common::LoroValue, &[u8])> {
1607 let (value, bytes) = postcard::take_from_bytes(bytes).map_err(|_| {
1608 loro_common::LoroError::DecodeError(
1609 "Decode list value failed".to_string().into_boxed_str(),
1610 )
1611 })?;
1612 let s: String = value;
1613 Ok((LoroValue::String(s.into()), bytes))
1614 }
1615
1616 fn decode_snapshot_fast(
1617 idx: crate::container::idx::ContainerIdx,
1618 (string, mut bytes): (loro_common::LoroValue, &[u8]),
1619 ctx: ContainerCreationContext,
1620 ) -> loro_common::LoroResult<Self>
1621 where
1622 Self: Sized,
1623 {
1624 let mut text = RichtextState::new(idx, ctx.configure.text_style_config.clone());
1625 let mut loader = RichtextStateLoader::default();
1626 let peers = decode_peer_table(&mut bytes, "Decode richtext state failed")?;
1627
1628 let string = string.into_string().map_err(|_| {
1629 state_decode_error("Decode richtext state failed: value is not a string")
1630 })?;
1631 let mut s = StrSlice::new_from_str(&string);
1632 let iters = EncodedText::decode(bytes).map_err(|err| {
1633 state_decode_error(format!(
1634 "Decode richtext state failed: invalid spans: {err}"
1635 ))
1636 })?;
1637 let keys = iters.keys;
1638 let span_iter = iters.spans.into_iter();
1639 let mut mark_iter = iters.marks.into_iter();
1640 let mut id_to_style = FxHashMap::default();
1641 for span in span_iter {
1642 let EncodedTextSpan {
1643 peer_idx,
1644 counter,
1645 lamport_sub_counter,
1646 len,
1647 } = span;
1648 let peer =
1649 decode_peer_from_table(&peers, peer_idx, "Decode richtext state failed")?;
1650 let lamport = decode_lamport_from_delta(
1651 counter,
1652 lamport_sub_counter,
1653 "Decode richtext state failed",
1654 )?;
1655 let id_full = IdFull::new(peer, counter, lamport);
1656 let chunk = match len {
1657 0 => {
1658 // Style Start
1659 let EncodedMark {
1660 key_idx,
1661 value,
1662 info,
1663 } = mark_iter.next().ok_or_else(|| {
1664 state_decode_error("Decode richtext state failed: missing style mark")
1665 })?;
1666 let key = keys.get(key_idx).ok_or_else(|| {
1667 state_decode_error(
1668 "Decode richtext state failed: style key index out of range",
1669 )
1670 })?;
1671 let style_op = Arc::new(StyleOp {
1672 lamport,
1673 peer: id_full.peer,
1674 cnt: id_full.counter,
1675 key: key.clone(),
1676 value,
1677 info: TextStyleInfoFlag::from_byte(info),
1678 });
1679 id_to_style.insert(id_full.id(), style_op.clone());
1680 RichtextStateChunk::new_style(style_op, richtext::AnchorType::Start)
1681 }
1682 -1 => {
1683 // Style End
1684 let style = id_to_style.remove(&id_full.id().inc(-1)).ok_or_else(|| {
1685 state_decode_error("Decode richtext state failed: unmatched style end")
1686 })?;
1687 RichtextStateChunk::new_style(style, richtext::AnchorType::End)
1688 }
1689 len => {
1690 if len < -1 {
1691 return Err(state_decode_error(
1692 "Decode richtext state failed: invalid text span length",
1693 ));
1694 }
1695
1696 // Text
1697 if s.as_str().chars().take(len as usize).count() < len as usize {
1698 return Err(state_decode_error(
1699 "Decode richtext state failed: text span exceeds value length",
1700 ));
1701 }
1702
1703 let (new, rest) = s.split_at_unicode_pos(len as usize);
1704 s = rest;
1705 RichtextStateChunk::new_text(new.bytes().clone(), id_full)
1706 }
1707 };
1708
1709 loader.push(chunk);
1710 }
1711 if !s.as_str().is_empty() {
1712 return Err(state_decode_error(
1713 "Decode richtext state failed: text value not fully covered",
1714 ));
1715 }
1716 if mark_iter.next().is_some() {
1717 return Err(state_decode_error(
1718 "Decode richtext state failed: unused style mark",
1719 ));
1720 }
1721 // A `StyleStart` without its `StyleEnd` is valid: a version can include the
1722 // start op but not the end op (their counters are consecutive), and
1723 // `checkout` keeps the lone start anchor the same way. The style applies
1724 // to nothing until the end anchor arrives (loro-dev/loro#1165).
1725 text.state = LazyLoad::Src(loader);
1726 // NOTE: We need to ensure the invariance that the version id is always increased when the richtext state is changed
1727 // This is used to avoid the version_id to be the same as the previous zero version
1728 text.version_id = 1;
1729 Ok(text)
1730 }
1731 }
1732
1733 #[cfg(test)]
1734 mod tests {
1735 use loro_common::{ContainerType, LoroValue};
1736
1737 use crate::container::idx::ContainerIdx;
1738
1739 use super::*;
1740
1741 #[test]
1742 fn iterative_mark_codec_matches_the_original_columnar_bytes() {
1743 let encoded = EncodedText {
1744 spans: vec![span(0, 0), span(2, 5), span(1, -1)],
1745 keys: vec!["hl".into(), "x".into()],
1746 marks: vec![
1747 mark(LoroValue::Null, richtext::ExpandType::After),
1748 mark(
1749 LoroValue::List(
1750 vec![
1751 LoroValue::Binary(vec![0, 255].into()),
1752 LoroValue::Map(vec![("a".into(), 42.into())].into()),
1753 ]
1754 .into(),
1755 ),
1756 richtext::ExpandType::Before,
1757 ),
1758 ],
1759 };
1760 let old = serde_columnar::to_vec(&encoded).unwrap();
1761 assert_eq!(encoded.encode(), old);
1762 let decoded = EncodedText::decode(&old).unwrap();
1763 assert_eq!(decoded.encode(), old);
1764 assert_eq!(decoded.marks[1].value, encoded.marks[1].value);
1765 for len in 0..old.len() {
1766 assert!(EncodedText::decode(&old[..len]).is_err());
1767 }
1768 }
1769
1770 #[test]
1771 fn richtext_fast_snapshot_rejects_corrupt_state_metadata() {
1772 let idx = ContainerIdx::from_index_and_type(0, ContainerType::Text);
1773 let configure = Default::default();
1774 let ctx = ContainerCreationContext {
1775 configure: &configure,
1776 peer: 0,
1777 };
1778
1779 assert!(RichtextState::decode_snapshot_fast(
1780 idx,
1781 (LoroValue::String("a".into()), &[1]),
1782 ctx,
1783 )
1784 .is_err());
1785
1786 let mut text = RichtextState::new(idx, configure.text_style_config.clone());
1787 let mut bytes = Vec::new();
1788 text.encode_snapshot_fast(&mut bytes);
1789 let (_, state_bytes) = RichtextState::decode_value(&bytes).unwrap();
1790 assert!(RichtextState::decode_snapshot_fast(
1791 idx,
1792 (LoroValue::String("a".into()), state_bytes),
1793 ctx,
1794 )
1795 .is_err());
1796 }
1797
1798 const PEER: PeerID = 7;
1799
1800 fn payload(text: &str, spans: Vec<EncodedTextSpan>, marks: Vec<EncodedMark>) -> Vec<u8> {
1801 let mut out = Vec::new();
1802 postcard::to_io(text, &mut out).unwrap();
1803 leb128::write::unsigned(&mut out, 1).unwrap();
1804 out.extend_from_slice(&PEER.to_le_bytes());
1805 out.extend_from_slice(
1806 &serde_columnar::to_vec(&EncodedText {
1807 spans,
1808 keys: vec!["hl".into(), "x".into()],
1809 marks,
1810 })
1811 .unwrap(),
1812 );
1813 out
1814 }
1815
1816 fn span(counter: i32, len: i32) -> EncodedTextSpan {
1817 EncodedTextSpan {
1818 peer_idx: 0,
1819 counter,
1820 lamport_sub_counter: 0,
1821 len,
1822 }
1823 }
1824
1825 fn mark(value: LoroValue, expand: richtext::ExpandType) -> EncodedMark {
1826 EncodedMark {
1827 key_idx: 0,
1828 value,
1829 info: TextStyleInfoFlag::new(expand).to_byte(),
1830 }
1831 }
1832
1833 fn decoded_mark_values(payload: &[u8]) -> Vec<LoroValue> {
1834 let (_, mut rest) = postcard::take_from_bytes::<&str>(payload).unwrap();
1835 decode_peer_table(&mut rest, "test").unwrap();
1836 serde_columnar::from_bytes::<EncodedText>(rest)
1837 .unwrap()
1838 .marks
1839 .into_iter()
1840 .map(|m| m.value)
1841 .collect()
1842 }
1843
1844 /// "a" [S] [E] "d" — a dead pair between two text chunks.
1845 fn dead_pair_payload(expand: richtext::ExpandType) -> Vec<u8> {
1846 payload(
1847 "ad",
1848 vec![span(0, 1), span(10, 0), span(11, -1), span(1, 1)],
1849 vec![mark(LoroValue::String("SECRET".into()), expand)],
1850 )
1851 }
1852
1853 #[test]
1854 fn redacts_dead_pair_and_is_idempotent() {
1855 let p = dead_pair_payload(richtext::ExpandType::After);
1856 let (new_payload, ids) = redact_dead_style_values(&p, None).unwrap().unwrap();
1857 assert_eq!(ids, vec![ID::new(PEER, 10)]);
1858 assert_eq!(decoded_mark_values(&new_payload), vec![LoroValue::Null]);
1859
1860 // The redacted payload still decodes into a valid state.
1861 let idx = ContainerIdx::from_index_and_type(0, ContainerType::Text);
1862 let configure = crate::configure::Configure::default();
1863 let ctx = ContainerCreationContext {
1864 configure: &configure,
1865 peer: 0,
1866 };
1867 let (value, rest) = RichtextState::decode_value(&new_payload).unwrap();
1868 let mut state = RichtextState::decode_snapshot_fast(idx, (value, rest), ctx).unwrap();
1869 assert_eq!(state.get_value().into_string().unwrap().to_string(), "ad");
1870
1871 // Idempotent: a second pass reports nothing to do.
1872 assert!(redact_dead_style_values(&new_payload, None)
1873 .unwrap()
1874 .is_none());
1875 }
1876
1877 #[test]
1878 fn keeps_alive_and_both_expand_pairs() {
1879 // Text between the anchors: alive, untouched.
1880 let alive = payload(
1881 "a",
1882 vec![span(10, 0), span(0, 1), span(11, -1)],
1883 vec![mark(
1884 LoroValue::String("SECRET".into()),
1885 richtext::ExpandType::After,
1886 )],
1887 );
1888 assert!(redact_dead_style_values(&alive, None).unwrap().is_none());
1889
1890 // Dead but both-expand: still styles future inserts, untouched.
1891 let both = dead_pair_payload(richtext::ExpandType::Both);
1892 assert!(redact_dead_style_values(&both, None).unwrap().is_none());
1893 }
1894
1895 #[test]
1896 fn respects_only_pairs_whitelist() {
1897 let p = dead_pair_payload(richtext::ExpandType::None);
1898 let mut allow = FxHashSet::default();
1899 allow.insert(ID::new(PEER, 999));
1900 assert!(redact_dead_style_values(&p, Some(&allow))
1901 .unwrap()
1902 .is_none());
1903
1904 allow.insert(ID::new(PEER, 10));
1905 let (_, ids) = redact_dead_style_values(&p, Some(&allow)).unwrap().unwrap();
1906 assert_eq!(ids, vec![ID::new(PEER, 10)]);
1907 }
1908
1909 #[test]
1910 fn handles_interleaved_pairs() {
1911 // "ab" [S1 "a"..] [S2] [E1] [E2]: pair 1 encloses text via its start
1912 // before "b"? Layout: [S1] "b" [S2] [E1] [E2] over text "ab" with a
1913 // leading "a": S1 opens before "b" so it is alive; S2 opens after all
1914 // text and closes empty, so it is dead.
1915 let p = payload(
1916 "ab",
1917 vec![
1918 span(0, 1), // "a"
1919 span(10, 0), // S1
1920 span(1, 1), // "b"
1921 span(20, 0), // S2
1922 span(11, -1), // E1
1923 span(21, -1), // E2
1924 ],
1925 vec![
1926 mark(
1927 LoroValue::String("ALIVE".into()),
1928 richtext::ExpandType::After,
1929 ),
1930 mark(
1931 LoroValue::String("DEAD".into()),
1932 richtext::ExpandType::After,
1933 ),
1934 ],
1935 );
1936 let (new_payload, ids) = redact_dead_style_values(&p, None).unwrap().unwrap();
1937 assert_eq!(ids, vec![ID::new(PEER, 20)]);
1938 assert_eq!(
1939 decoded_mark_values(&new_payload),
1940 vec![LoroValue::String("ALIVE".into()), LoroValue::Null]
1941 );
1942 }
1943
1944 #[test]
1945 fn rejects_malformed_span_structures() {
1946 // Start without a matching end is valid (loro-dev/loro#1165): a version can
1947 // hold a mark's StyleStart but not its StyleEnd. It is left untouched.
1948 let unclosed = payload(
1949 "",
1950 vec![span(10, 0)],
1951 vec![mark(LoroValue::Bool(true), richtext::ExpandType::After)],
1952 );
1953 assert!(redact_dead_style_values(&unclosed, None).unwrap().is_none());
1954
1955 // End without a start. (An empty mark list short-circuits before
1956 // validation, so give it one mark to reach the scan.)
1957 let unmatched = payload(
1958 "",
1959 vec![span(11, -1)],
1960 vec![mark(LoroValue::Bool(true), richtext::ExpandType::After)],
1961 );
1962 assert!(redact_dead_style_values(&unmatched, None).is_err());
1963
1964 // More starts than marks.
1965 let missing_mark = payload(
1966 "",
1967 vec![span(10, 0), span(11, -1), span(20, 0), span(21, -1)],
1968 vec![mark(LoroValue::Bool(true), richtext::ExpandType::After)],
1969 );
1970 assert!(redact_dead_style_values(&missing_mark, None).is_err());
1971 }
1972
1973 #[test]
1974 fn skips_payload_without_marks() {
1975 let p = payload("ab", vec![span(0, 2)], vec![]);
1976 assert!(redact_dead_style_values(&p, None).unwrap().is_none());
1977 }
1978 }
1979}