forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

richtext_state.rs3690 lines, 122.6 KiBHistoryRawDownload
1use append_only_bytes::BytesSlice;
2use generic_btree::{
3 rle::{CanRemove, HasLength, Mergeable, Sliceable, TryInsert},
4 BTree, BTreeTrait, Cursor, LeafIndex,
5};
6use loro_common::{Counter, IdFull, IdSpan, LoroError, LoroResult, LoroValue, ID};
7use query::{ByteQuery, ByteQueryT};
8use rustc_hash::{FxHashMap, FxHashSet};
9use serde::{ser::SerializeStruct, Serialize};
10use smallvec::SmallVec;
11use std::{
12 fmt::{Display, Formatter},
13 ops::{Bound, RangeBounds},
14};
15use std::{
16 ops::{Add, AddAssign, Range, Sub},
17 str::Utf8Error,
18 sync::Arc,
19};
20use tracing::instrument;
21
22use crate::{
23 container::richtext::style_range_map::EMPTY_STYLES,
24 delta::{DeltaValue, StyleMeta},
25 utils::query_by_len::{EntityIndexQueryWithEventIndex, IndexQueryWithEntityIndex, QueryByLen},
26};
27
28use self::query::{
29 EntityQuery, EntityQueryT, EventIndexQuery, EventIndexQueryT, UnicodeQuery, UnicodeQueryT,
30 Utf16Query, Utf16QueryT,
31};
32
33use super::{
34 style_range_map::{IterAnchorItem, StyleRangeMap, Styles},
35 AnchorType, RichtextSpan, StyleKey, StyleOp,
36};
37
38pub(crate) use crate::cursor::PosType;
39
40#[derive(Clone, Debug, Default)]
41pub(crate) struct RichtextState {
42 tree: BTree<RichtextTreeTrait>,
43 style_ranges: Option<Box<StyleRangeMap>>,
44 cached_cursor: Option<CachedCursor>,
45}
46
47impl Display for RichtextState {
48 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
49 for span in self.tree.iter() {
50 match span {
51 RichtextStateChunk::Style { .. } => {}
52 RichtextStateChunk::Text(s) => {
53 f.write_str(s.as_str())?;
54 }
55 }
56 }
57
58 Ok(())
59 }
60}
61
62use cache::CachedCursor;
63
64mod cache {
65 use super::*;
66
67 #[derive(Clone, Debug)]
68 pub(super) struct CachedCursor {
69 leaf: LeafIndex,
70 index: FxHashMap<PosType, usize>,
71 }
72
73 impl RichtextState {
74 pub(super) fn clear_cache(&mut self) {
75 self.cached_cursor = None;
76 }
77
78 pub(super) fn record_cache(
79 &mut self,
80 leaf: LeafIndex,
81 pos: usize,
82 pos_type: PosType,
83 entity_offset: usize,
84 entity_index: Option<usize>,
85 ) {
86 let offset = if entity_offset != 0 {
87 let elem = self.tree.get_elem(leaf).unwrap();
88 entity_offset_to_pos_type_offset(pos_type, elem, entity_offset)
89 } else {
90 0
91 };
92
93 let pos = pos - offset;
94 match &mut self.cached_cursor {
95 Some(c) => {
96 if c.leaf == leaf {
97 c.index.insert(pos_type, pos);
98 } else {
99 c.leaf = leaf;
100 c.index.clear();
101 c.index.insert(pos_type, pos);
102 }
103 }
104 None => {
105 self.cached_cursor = Some(CachedCursor {
106 leaf,
107 index: FxHashMap::default(),
108 });
109 self.cached_cursor
110 .as_mut()
111 .unwrap()
112 .index
113 .insert(pos_type, pos);
114 }
115 }
116 if let Some(entity_index) = entity_index {
117 self.cached_cursor
118 .as_mut()
119 .unwrap()
120 .index
121 .insert(PosType::Entity, entity_index - entity_offset);
122 }
123 }
124
125 pub(super) fn try_get_cache_or_clean(
126 &mut self,
127 index: usize,
128 pos_type: PosType,
129 ) -> Option<Cursor> {
130 let mut cursor = self.cached_cursor.take();
131 let ans = 'block: {
132 match &mut cursor {
133 Some(c) => {
134 let cache_index = c.index.get(&pos_type);
135 if let Some(cache_index) = cache_index {
136 if index < *cache_index {
137 return None;
138 }
139 }
140
141 let cached_index = match c.index.entry(pos_type) {
142 std::collections::hash_map::Entry::Vacant(vacant_entry) => {
143 let index = self.get_index_from_cursor(
144 Cursor {
145 leaf: c.leaf,
146 offset: 0,
147 },
148 pos_type,
149 )?;
150 vacant_entry.insert(index);
151 index
152 }
153 std::collections::hash_map::Entry::Occupied(occupied_entry) => {
154 *occupied_entry.get()
155 }
156 };
157
158 if index < cached_index {
159 return None;
160 }
161
162 if cached_index == index {
163 break 'block Some(Cursor {
164 leaf: c.leaf,
165 offset: 0,
166 });
167 }
168
169 let elem = self.tree.get_elem(c.leaf)?;
170 let elem_len = elem.len_with(pos_type);
171 if cached_index + elem_len == index {
172 let offset = elem.len_with(PosType::Entity);
173 break 'block Some(Cursor {
174 leaf: c.leaf,
175 offset,
176 });
177 }
178
179 if index > cached_index + elem_len {
180 return None;
181 }
182
183 let offset =
184 pos_type_offset_to_entity_offset(pos_type, elem, index - cached_index)?;
185 Some(Cursor {
186 leaf: c.leaf,
187 offset,
188 })
189 }
190 None => None,
191 }
192 };
193
194 self.cached_cursor = cursor;
195 #[cfg(debug_assertions)]
196 {
197 if let Some(c) = ans.as_ref() {
198 let actual = self.get_index_from_cursor(*c, pos_type);
199 assert_eq!(actual.unwrap(), index);
200 }
201 }
202 ans
203 }
204
205 pub(super) fn get_cache_entity_index(&mut self) -> Option<usize> {
206 self.get_cache_leaf_start_index(PosType::Entity)
207 }
208
209 /// Index (in `pos_type` units) of the start of the currently cached leaf,
210 /// computing it once via `get_index_from_cursor` and memoizing it on the
211 /// cached cursor for reuse by later same-leaf queries.
212 pub(super) fn get_cache_leaf_start_index(&mut self, pos_type: PosType) -> Option<usize> {
213 let mut cursor = self.cached_cursor.take()?;
214 let ans = {
215 let leaf = cursor.leaf;
216 match cursor.index.entry(pos_type) {
217 std::collections::hash_map::Entry::Vacant(vacant_entry) => {
218 let index =
219 self.get_index_from_cursor(Cursor { leaf, offset: 0 }, pos_type)?;
220 vacant_entry.insert(index);
221 index
222 }
223 std::collections::hash_map::Entry::Occupied(occupied_entry) => {
224 *occupied_entry.get()
225 }
226 }
227 };
228
229 self.cached_cursor = Some(cursor);
230 Some(ans)
231 }
232
233 /// Resolve the `pos_type` index of an arbitrary cursor using the cached
234 /// leaf, avoiding a full `visit_previous_caches` walk when the cursor
235 /// lands in the currently cached leaf. Returns `None` (miss) otherwise.
236 pub(super) fn cursor_index_via_cache(
237 &mut self,
238 cursor: Cursor,
239 pos_type: PosType,
240 ) -> Option<usize> {
241 match &self.cached_cursor {
242 Some(c) if c.leaf == cursor.leaf => {}
243 _ => return None,
244 }
245 let leaf_start = self.get_cache_leaf_start_index(pos_type)?;
246 if cursor.offset == 0 {
247 return Some(leaf_start);
248 }
249 let elem = self.tree.get_elem(cursor.leaf)?;
250 Some(leaf_start + entity_offset_to_pos_type_offset(pos_type, elem, cursor.offset))
251 }
252
253 pub(crate) fn check_cache(&self) {
254 #[cfg(debug_assertions)]
255 {
256 if let Some(c) = &self.cached_cursor {
257 for (pos_type, index) in &c.index {
258 let actual = self.get_index_from_cursor(
259 Cursor {
260 leaf: c.leaf,
261 offset: 0,
262 },
263 *pos_type,
264 );
265
266 assert_eq!(actual.unwrap(), *index);
267 }
268 }
269 }
270 }
271 }
272}
273
274pub(crate) use text_chunk::TextChunk;
275mod text_chunk {
276 use std::ops::Range;
277
278 use append_only_bytes::BytesSlice;
279 use loro_common::{IdFull, ID};
280
281 /// Largest text element kept in the state tree (project_note patch).
282 pub(crate) const MAX_CHUNK_BYTES: usize = 2048;
283
284 #[derive(Clone, PartialEq)]
285 pub(crate) struct TextChunk {
286 bytes: BytesSlice,
287 unicode_len: i32,
288 utf16_len: i32,
289 id: IdFull,
290 }
291
292 impl std::fmt::Debug for TextChunk {
293 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
294 f.debug_struct("TextChunk")
295 .field("text", &self.as_str())
296 .field("unicode_len", &self.unicode_len)
297 .field("utf16_len", &self.utf16_len)
298 .field("id", &self.id)
299 .finish()
300 }
301 }
302
303 impl TextChunk {
304 pub fn new(bytes: BytesSlice, id: IdFull) -> Self {
305 // ASCII: every length is the byte length. (project_note patch)
306 if bytes.is_ascii() {
307 let len = bytes.len() as i32;
308 return Self { unicode_len: len, bytes, utf16_len: len, id };
309 }
310 let (unicode_len, utf16_len) = crate::utils::utf16::str_lens(&bytes);
311 Self {
312 unicode_len: unicode_len as i32,
313 bytes,
314 utf16_len: utf16_len as i32,
315 id,
316 }
317 }
318
319 /// Splits into pieces of at most [`MAX_CHUNK_BYTES`] (on char boundaries), so
320 /// that offset conversions inside one tree element stay short. (project_note patch)
321 pub fn into_pieces(self) -> Vec<Self> {
322 if self.bytes.len() <= MAX_CHUNK_BYTES {
323 return vec![self];
324 }
325 let s = self.as_str();
326 let mut out = Vec::with_capacity(s.len() / MAX_CHUNK_BYTES + 1);
327 let mut id = self.id;
328 let mut start = 0;
329 while start < s.len() {
330 let mut end = (start + MAX_CHUNK_BYTES).min(s.len());
331 while !s.is_char_boundary(end) {
332 end -= 1;
333 }
334 let (unicode, utf16) = crate::utils::utf16::str_lens(&s.as_bytes()[start..end]);
335 let (unicode, utf16) = (unicode as i32, utf16 as i32);
336 out.push(Self { bytes: self.bytes.slice_clone(start..end), unicode_len: unicode, utf16_len: utf16, id });
337 id = id.inc(unicode);
338 start = end;
339 }
340 out
341 }
342
343 #[inline]
344 pub fn id(&self) -> ID {
345 self.id.id()
346 }
347
348 #[inline]
349 #[allow(unused)]
350 pub fn id_full(&self) -> IdFull {
351 self.id
352 }
353
354 #[inline]
355 pub fn bytes(&self) -> &BytesSlice {
356 &self.bytes
357 }
358
359 #[inline]
360 pub fn as_str(&self) -> &str {
361 // SAFETY: We know that the text is valid UTF-8
362 unsafe { std::str::from_utf8_unchecked(&self.bytes) }
363 }
364
365 #[inline]
366 pub fn len(&self) -> i32 {
367 self.unicode_len
368 }
369
370 #[inline]
371 pub fn utf8_len(&self) -> i32 {
372 self.bytes.len() as i32
373 }
374
375 #[inline]
376 pub fn unicode_len(&self) -> i32 {
377 self.unicode_len
378 }
379
380 #[inline]
381 pub fn utf16_len(&self) -> i32 {
382 self.utf16_len
383 }
384
385 #[inline]
386 pub fn event_len(&self) -> i32 {
387 if cfg!(feature = "wasm") {
388 self.utf16_len
389 } else {
390 self.unicode_len
391 }
392 }
393
394 /// Convert a unicode index on this text to an event index
395 pub fn convert_unicode_offset_to_event_offset(&self, offset: usize) -> usize {
396 if cfg!(feature = "wasm") {
397 let mut event_offset = 0;
398 for (i, c) in self.as_str().chars().enumerate() {
399 if i == offset {
400 return event_offset;
401 }
402 event_offset += c.len_utf16();
403 }
404 event_offset
405 } else {
406 offset
407 }
408 }
409
410 pub fn new_empty() -> Self {
411 Self {
412 unicode_len: 0,
413 bytes: BytesSlice::empty(),
414 utf16_len: 0,
415 // This is a dummy value.
416 // It's fine because the length is 0. We never actually use this value.
417 id: IdFull::NONE_ID,
418 }
419 }
420
421 /// Whether every char in this chunk is in the Basic Multilingual Plane,
422 /// i.e. each char is a single UTF-16 code unit. When true, UTF-16 offsets
423 /// equal unicode offsets, so conversions are O(1) instead of O(offset).
424 #[inline]
425 fn is_all_bmp(&self) -> bool {
426 self.utf16_len == self.unicode_len
427 }
428
429 /// Whether this chunk is pure ASCII, i.e. each char is a single byte.
430 /// When true, byte offsets equal unicode offsets.
431 #[inline]
432 fn is_all_ascii(&self) -> bool {
433 self.bytes.len() as i32 == self.unicode_len
434 }
435
436 /// Convert a UTF-16 offset within this chunk to a unicode offset.
437 ///
438 /// O(1) when the chunk has no astral-plane characters; otherwise it
439 /// scans up to `utf16_offset` chars. Mirrors [`utf16_to_unicode_index`].
440 pub fn utf16_offset_to_unicode(&self, utf16_offset: usize) -> Result<usize, usize> {
441 if self.is_all_bmp() {
442 return Ok(utf16_offset);
443 }
444 super::utf16_to_unicode_index(self.as_str(), utf16_offset)
445 }
446
447 /// Convert a UTF-8 (byte) offset within this chunk to a unicode offset.
448 /// O(1) when the chunk is pure ASCII.
449 pub fn utf8_offset_to_unicode(&self, utf8_offset: usize) -> Result<usize, usize> {
450 if self.is_all_ascii() {
451 return Ok(utf8_offset);
452 }
453 super::utf8_to_unicode_index(self.as_str(), utf8_offset)
454 }
455
456 /// Convert a unicode offset within this chunk to a UTF-16 offset.
457 /// O(1) when the chunk has no astral-plane characters.
458 pub fn unicode_offset_to_utf16(&self, unicode_offset: usize) -> Option<usize> {
459 if self.is_all_bmp() {
460 return Some(unicode_offset);
461 }
462 super::unicode_to_utf16_index(self.as_str(), unicode_offset)
463 }
464
465 /// Convert a unicode offset within this chunk to a UTF-8 (byte) offset.
466 /// O(1) when the chunk is pure ASCII.
467 pub fn unicode_offset_to_utf8(&self, unicode_offset: usize) -> Option<usize> {
468 if self.is_all_ascii() {
469 return Some(unicode_offset);
470 }
471 super::unicode_to_utf8_index(self.as_str(), unicode_offset)
472 }
473
474 /// Slice this chunk by unicode offsets, returning the substring.
475 /// O(1) byte lookup when the chunk is pure ASCII.
476 pub fn unicode_slice(&self, start: usize, end: usize) -> Result<&str, ()> {
477 if self.is_all_ascii() {
478 return self.as_str().get(start..end).ok_or(());
479 }
480 super::unicode_slice(self.as_str(), start, end)
481 }
482
483 pub(crate) fn delete_by_entity_index(
484 &mut self,
485 unicode_offset: usize,
486 unicode_len: usize,
487 ) -> (Option<Self>, usize) {
488 let s = self.as_str();
489 let mut start_byte = 0;
490 let mut end_byte = self.bytes().len();
491 let start_unicode_index = unicode_offset;
492 let end_unicode_index = unicode_offset + unicode_len;
493 let mut start_utf16_index = 0;
494 let mut current_utf16_index = 0;
495 let mut current_utf8_index = 0;
496 for (current_unicode_index, c) in s.chars().enumerate() {
497 if current_unicode_index == start_unicode_index {
498 start_utf16_index = current_utf16_index;
499 start_byte = current_utf8_index;
500 }
501
502 if current_unicode_index == end_unicode_index {
503 end_byte = current_utf8_index;
504 break;
505 }
506
507 current_utf16_index += c.len_utf16();
508 current_utf8_index += c.len_utf8();
509 }
510
511 self.utf16_len -= (current_utf16_index - start_utf16_index) as i32;
512
513 let event_len = if cfg!(feature = "wasm") {
514 current_utf16_index - start_utf16_index
515 } else {
516 unicode_len
517 };
518
519 self.unicode_len -= unicode_len as i32;
520 let next = match (start_byte == 0, end_byte == self.bytes.len()) {
521 (true, true) => {
522 self.bytes = BytesSlice::empty();
523 None
524 }
525 (true, false) => {
526 self.bytes.slice_(end_byte..);
527 self.id = self.id.inc(end_unicode_index as i32);
528 None
529 }
530 (false, true) => {
531 self.bytes.slice_(..start_byte);
532 None
533 }
534 (false, false) => {
535 let next = self.bytes.slice_clone(end_byte..);
536 let next = Self::new(next, self.id.inc(end_unicode_index as i32));
537 self.unicode_len -= next.unicode_len;
538 self.utf16_len -= next.utf16_len;
539 self.bytes.slice_(..start_byte);
540 Some(next)
541 }
542 };
543
544 self.check();
545 if let Some(next) = next.as_ref() {
546 next.check();
547 }
548 (next, event_len)
549 }
550
551 fn check(&self) {
552 if !cfg!(any(debug_assertions, test)) {
553 return;
554 }
555
556 let bytes_len = self.bytes.len() as i32;
557 if bytes_len == self.unicode_len {
558 assert_eq!(self.utf16_len, self.unicode_len);
559 return;
560 }
561
562 assert_eq!(self.unicode_len, self.as_str().chars().count() as i32);
563 assert_eq!(
564 self.utf16_len,
565 self.as_str().chars().map(|c| c.len_utf16()).sum::<usize>() as i32
566 );
567 }
568
569 pub(crate) fn entity_range_to_event_range(&self, range: Range<usize>) -> Range<usize> {
570 if cfg!(feature = "wasm") {
571 assert!(range.start <= range.end);
572 if range.start == 0 && range.end == self.unicode_len as usize {
573 return 0..self.utf16_len as usize;
574 }
575
576 let mut start = 0;
577 let mut end = 0;
578 let mut utf16_index = 0;
579 for (unicode_index, c) in self.as_str().chars().enumerate() {
580 if unicode_index == range.start {
581 start = utf16_index;
582 }
583 if unicode_index == range.end {
584 end = utf16_index;
585 break;
586 }
587
588 utf16_index += c.len_utf16();
589 }
590
591 if end == 0 {
592 end = utf16_index;
593 }
594
595 start..end
596 } else {
597 range
598 }
599 }
600 }
601
602 impl generic_btree::rle::HasLength for TextChunk {
603 fn rle_len(&self) -> usize {
604 self.unicode_len as usize
605 }
606 }
607
608 impl generic_btree::rle::Sliceable for TextChunk {
609 fn _slice(&self, range: Range<usize>) -> Self {
610 assert!(range.start < range.end);
611 let total_unicode_len = self.unicode_len as usize;
612 if range.start == 0 && range.end == total_unicode_len {
613 return self.clone();
614 }
615
616 // Fast path for ASCII text: unicode index == byte index, and utf16 index == unicode index.
617 if self.is_all_ascii() {
618 let ans = Self {
619 unicode_len: range.len() as i32,
620 bytes: self.bytes.slice_clone(range.start..range.end),
621 utf16_len: range.len() as i32,
622 id: self.id.inc(range.start as i32),
623 };
624 ans.check();
625 return ans;
626 }
627
628 // Fast path for slicing a suffix/prefix to avoid scanning the whole chunk.
629 if range.end == total_unicode_len {
630 let mut utf16_offset = 0;
631 let mut start_byte = self.bytes.len();
632 for (unicode_index, (byte_index, c)) in self.as_str().char_indices().enumerate() {
633 if unicode_index == range.start {
634 start_byte = byte_index;
635 break;
636 }
637 utf16_offset += c.len_utf16();
638 }
639
640 let ans = Self {
641 unicode_len: (total_unicode_len - range.start) as i32,
642 bytes: self.bytes.slice_clone(start_byte..),
643 utf16_len: self.utf16_len - utf16_offset as i32,
644 id: self.id.inc(range.start as i32),
645 };
646 ans.check();
647 return ans;
648 }
649
650 if range.start == 0 {
651 let mut utf16_len = 0;
652 let mut end_byte = self.bytes.len();
653 for (unicode_index, (byte_index, c)) in self.as_str().char_indices().enumerate() {
654 if unicode_index == range.end {
655 end_byte = byte_index;
656 break;
657 }
658 utf16_len += c.len_utf16();
659 }
660
661 let ans = Self {
662 unicode_len: range.end as i32,
663 bytes: self.bytes.slice_clone(..end_byte),
664 utf16_len: utf16_len as i32,
665 id: self.id,
666 };
667 ans.check();
668 return ans;
669 }
670
671 // General middle slice.
672 let mut utf16_len = 0;
673 let mut start = 0;
674 let mut end = 0;
675 let mut started = false;
676 let mut last_unicode_index = 0;
677 for (unicode_index, (i, c)) in self.as_str().char_indices().enumerate() {
678 if unicode_index == range.start {
679 start = i;
680 started = true;
681 }
682
683 if unicode_index == range.end {
684 end = i;
685 break;
686 }
687 if started {
688 utf16_len += c.len_utf16();
689 }
690
691 last_unicode_index = unicode_index;
692 }
693
694 assert!(started);
695 if end == 0 {
696 assert_eq!(last_unicode_index + 1, range.end);
697 end = self.bytes.len();
698 }
699
700 let ans = Self {
701 unicode_len: range.len() as i32,
702 bytes: self.bytes.slice_clone(start..end),
703 utf16_len: utf16_len as i32,
704 id: self.id.inc(range.start as i32),
705 };
706 ans.check();
707 ans
708 }
709
710 fn split(&mut self, pos: usize) -> Self {
711 let mut utf16_len = 0;
712 let mut byte_offset = 0;
713 for (unicode_index, (i, c)) in self.as_str().char_indices().enumerate() {
714 if unicode_index == pos {
715 byte_offset = i;
716 break;
717 }
718
719 utf16_len += c.len_utf16();
720 }
721 let right = Self {
722 unicode_len: self.unicode_len - pos as i32,
723 bytes: self.bytes.slice_clone(byte_offset..),
724 utf16_len: self.utf16_len - utf16_len as i32,
725 id: self.id.inc(pos as i32),
726 };
727
728 self.unicode_len = pos as i32;
729 self.utf16_len = utf16_len as i32;
730 self.bytes.slice_(..byte_offset);
731 right.check();
732 self.check();
733 right
734 }
735 }
736
737 impl generic_btree::rle::Mergeable for TextChunk {
738 fn can_merge(&self, rhs: &Self) -> bool {
739 self.bytes.can_merge(&rhs.bytes)
740 && self.id.inc(self.unicode_len) == rhs.id
741 && self.bytes.len() + rhs.bytes.len() <= MAX_CHUNK_BYTES
742 }
743
744 fn merge_right(&mut self, rhs: &Self) {
745 self.bytes.try_merge(&rhs.bytes).unwrap();
746 self.utf16_len += rhs.utf16_len;
747 self.unicode_len += rhs.unicode_len;
748 self.check();
749 }
750
751 fn merge_left(&mut self, left: &Self) {
752 let mut new = left.bytes.clone();
753 new.try_merge(&self.bytes).unwrap();
754 self.bytes = new;
755 self.utf16_len += left.utf16_len;
756 self.unicode_len += left.unicode_len;
757 self.id = left.id;
758 self.check();
759 }
760 }
761}
762
763// TODO: change visibility back to crate after #116 is done
764#[derive(Clone, Debug, PartialEq)]
765pub(crate) enum RichtextStateChunk {
766 Text(TextChunk),
767 Style {
768 style: Arc<StyleOp>,
769 anchor_type: AnchorType,
770 },
771}
772
773impl Default for RichtextStateChunk {
774 fn default() -> Self {
775 Self::new_empty()
776 }
777}
778
779impl RichtextStateChunk {
780 pub fn new_text(s: BytesSlice, id: IdFull) -> Self {
781 Self::Text(TextChunk::new(s, id))
782 }
783
784 /// Splits an oversized text element; other elements come back as they are.
785 pub(crate) fn into_pieces(self) -> Vec<Self> {
786 match self {
787 Self::Text(t) => t.into_pieces().into_iter().map(Self::Text).collect(),
788 s => vec![s],
789 }
790 }
791
792 pub fn new_empty() -> Self {
793 Self::Text(TextChunk::new_empty())
794 }
795
796 pub fn new_style(style: Arc<StyleOp>, anchor_type: AnchorType) -> Self {
797 Self::Style { style, anchor_type }
798 }
799
800 pub(crate) fn get_id_span(&self) -> IdSpan {
801 match self {
802 RichtextStateChunk::Text(t) => {
803 let id = t.id();
804 IdSpan::new(id.peer, id.counter, id.counter + t.unicode_len() as Counter)
805 }
806 RichtextStateChunk::Style { style, anchor_type } => match anchor_type {
807 AnchorType::Start => style.id().into(),
808 AnchorType::End => {
809 let id = style.id();
810 id.to_span(1)
811 }
812 },
813 }
814 }
815
816 pub(crate) fn counter(&self) -> Counter {
817 match self {
818 RichtextStateChunk::Text(t) => t.id().counter,
819 RichtextStateChunk::Style { style, anchor_type } => match anchor_type {
820 AnchorType::Start => style.id().counter,
821 AnchorType::End => {
822 let id = style.id();
823 id.counter + 1
824 }
825 },
826 }
827 }
828
829 pub fn entity_range_to_event_range(&self, range: Range<usize>) -> Range<usize> {
830 match self {
831 RichtextStateChunk::Text(t) => t.entity_range_to_event_range(range),
832 RichtextStateChunk::Style { .. } => {
833 assert_eq!(range.start, 0);
834 assert_eq!(range.end, 1);
835 0..1
836 }
837 }
838 }
839
840 pub fn len_with(&self, pos_type: PosType) -> usize {
841 match self {
842 RichtextStateChunk::Text(t) => match pos_type {
843 PosType::Bytes => t.utf8_len() as usize,
844 PosType::Utf16 => t.utf16_len() as usize,
845 PosType::Event if cfg!(feature = "wasm") => t.utf16_len() as usize,
846 PosType::Event => t.unicode_len() as usize,
847 PosType::Entity => t.unicode_len() as usize,
848 PosType::Unicode => t.unicode_len() as usize,
849 },
850 RichtextStateChunk::Style { .. } => {
851 if let PosType::Entity = pos_type {
852 1
853 } else {
854 0
855 }
856 }
857 }
858 }
859}
860
861impl loro_delta::delta_trait::DeltaValue for RichtextStateChunk {}
862
863impl DeltaValue for RichtextStateChunk {
864 fn value_extend(&mut self, other: Self) -> Result<(), Self> {
865 Err(other)
866 }
867
868 fn take(&mut self, length: usize) -> Self {
869 let mut right = self.split(length);
870 std::mem::swap(self, &mut right);
871 right
872 }
873
874 fn length(&self) -> usize {
875 self.rle_len()
876 }
877}
878
879impl Serialize for RichtextStateChunk {
880 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
881 where
882 S: serde::Serializer,
883 {
884 match self {
885 RichtextStateChunk::Text(text) => {
886 let mut state = serializer.serialize_struct("RichtextStateChunk", 3)?;
887 state.serialize_field("type", "Text")?;
888 state.serialize_field("unicode_len", &text.unicode_len())?;
889 state.serialize_field("text", text.as_str())?;
890 state.end()
891 }
892 RichtextStateChunk::Style { style, anchor_type } => {
893 let mut state = serializer.serialize_struct("RichtextStateChunk", 3)?;
894 state.serialize_field("type", "Style")?;
895 state.serialize_field("style", &style.key)?;
896 state.serialize_field("anchor_type", anchor_type)?;
897 state.end()
898 }
899 }
900 }
901}
902
903impl RichtextStateChunk {
904 pub fn try_new(s: BytesSlice, id: IdFull) -> Result<Self, Utf8Error> {
905 std::str::from_utf8(&s)?;
906 Ok(RichtextStateChunk::Text(TextChunk::new(s, id)))
907 }
908
909 pub fn from_style(style: Arc<StyleOp>, anchor_type: AnchorType) -> Self {
910 Self::Style { style, anchor_type }
911 }
912
913 pub fn as_str(&self) -> Option<&str> {
914 match self {
915 RichtextStateChunk::Text(text) => Some(text.as_str()),
916 _ => None,
917 }
918 }
919}
920
921impl HasLength for RichtextStateChunk {
922 fn rle_len(&self) -> usize {
923 match self {
924 RichtextStateChunk::Text(s) => s.rle_len(),
925 RichtextStateChunk::Style { .. } => 1,
926 }
927 }
928}
929
930impl Mergeable for RichtextStateChunk {
931 fn can_merge(&self, rhs: &Self) -> bool {
932 match (self, rhs) {
933 (RichtextStateChunk::Text(l), RichtextStateChunk::Text(r)) => l.can_merge(r),
934 _ => false,
935 }
936 }
937
938 fn merge_right(&mut self, rhs: &Self) {
939 match (self, rhs) {
940 (RichtextStateChunk::Text(l), RichtextStateChunk::Text(r)) => l.merge_right(r),
941 _ => unreachable!(),
942 }
943 }
944
945 fn merge_left(&mut self, left: &Self) {
946 match (self, left) {
947 (RichtextStateChunk::Text(this), RichtextStateChunk::Text(left)) => {
948 this.merge_left(left)
949 }
950 _ => unreachable!(),
951 }
952 }
953}
954
955impl Sliceable for RichtextStateChunk {
956 fn _slice(&self, range: Range<usize>) -> Self {
957 match self {
958 RichtextStateChunk::Text(s) => RichtextStateChunk::Text(s._slice(range)),
959 RichtextStateChunk::Style { style, anchor_type } => {
960 assert_eq!(range.start, 0);
961 assert_eq!(range.end, 1);
962 RichtextStateChunk::Style {
963 style: style.clone(),
964 anchor_type: *anchor_type,
965 }
966 }
967 }
968 }
969
970 fn split(&mut self, pos: usize) -> Self {
971 match self {
972 RichtextStateChunk::Text(s) => RichtextStateChunk::Text(s.split(pos)),
973 RichtextStateChunk::Style { .. } => {
974 unreachable!()
975 }
976 }
977 }
978}
979
980impl TryInsert for RichtextStateChunk {
981 fn try_insert(&mut self, _pos: usize, elem: Self) -> Result<(), Self>
982 where
983 Self: Sized,
984 {
985 Err(elem)
986 }
987}
988
989impl CanRemove for RichtextStateChunk {
990 fn can_remove(&self) -> bool {
991 self.rle_len() == 0
992 }
993}
994
995//TODO: start/end can be scanned in one loop, but now it takes twice the time
996fn unicode_slice(s: &str, start_index: usize, end_index: usize) -> Result<&str, ()> {
997 let (Some(start), Some(end)) = (
998 unicode_to_utf8_index(s, start_index),
999 unicode_to_utf8_index(s, end_index),
1000 ) else {
1001 return Err(());
1002 };
1003 Ok(&s[start..end])
1004}
1005
1006pub(crate) fn unicode_to_utf8_index(s: &str, unicode_index: usize) -> Option<usize> {
1007 if unicode_index <= s.len() && s.as_bytes()[..unicode_index].is_ascii() {
1008 return Some(unicode_index);
1009 }
1010 let mut current_unicode_index = 0;
1011 for (byte_index, _) in s.char_indices() {
1012 if current_unicode_index == unicode_index {
1013 return Some(byte_index);
1014 }
1015 current_unicode_index += 1;
1016 }
1017
1018 if current_unicode_index == unicode_index {
1019 return Some(s.len());
1020 }
1021
1022 None
1023}
1024
1025pub(crate) fn unicode_to_utf16_index(s: &str, unicode_index: usize) -> Option<usize> {
1026 if unicode_index <= s.len() && s.as_bytes()[..unicode_index].is_ascii() {
1027 return Some(unicode_index);
1028 }
1029 if unicode_index == 0 {
1030 return Some(0);
1031 }
1032
1033 let mut current_unicode_index = 0;
1034 let mut current_utf16_index = 0;
1035 for c in s.chars() {
1036 let len = c.len_utf16();
1037 current_unicode_index += 1;
1038 current_utf16_index += len;
1039 if current_unicode_index == unicode_index {
1040 return Some(current_utf16_index);
1041 }
1042 }
1043
1044 None
1045}
1046
1047pub(crate) fn utf16_to_utf8_index(s: &str, utf16_index: usize) -> Option<usize> {
1048 if utf16_index <= s.len() && s.as_bytes()[..utf16_index].is_ascii() {
1049 return Some(utf16_index);
1050 }
1051 if utf16_index == 0 {
1052 return Some(0);
1053 }
1054
1055 let mut current_utf16_index = 0;
1056 for (byte_index, c) in s.char_indices() {
1057 let len = c.len_utf16();
1058 current_utf16_index += len;
1059 if current_utf16_index == utf16_index {
1060 return Some(byte_index + c.len_utf8());
1061 }
1062 }
1063
1064 if current_utf16_index == utf16_index {
1065 return Some(s.len());
1066 }
1067
1068 None
1069}
1070
1071/// Returns the unicode index of the character at the given utf16 index.
1072///
1073/// If the given utf16 index is not at the correct boundary, returns the unicode index of the
1074/// character before the given utf16 index.
1075pub(crate) fn utf16_to_unicode_index(s: &str, utf16_index: usize) -> Result<usize, usize> {
1076 if utf16_index <= s.len() && s.as_bytes()[..utf16_index].is_ascii() {
1077 return Ok(utf16_index);
1078 }
1079 if utf16_index == 0 {
1080 return Ok(0);
1081 }
1082
1083 let mut current_utf16_index = 0;
1084 let mut current_unicode_index = 0;
1085 for (i, c) in s.chars().enumerate() {
1086 current_utf16_index += c.len_utf16();
1087 if current_utf16_index == utf16_index {
1088 return Ok(i + 1);
1089 }
1090 if current_utf16_index > utf16_index {
1091 loro_common::info!("WARNING: UTF16 MISMATCHED!");
1092 return Err(i);
1093 }
1094 current_unicode_index = i + 1;
1095 }
1096
1097 loro_common::info!("WARNING: UTF16 MISMATCHED!");
1098 Err(current_unicode_index)
1099}
1100
1101pub(crate) fn utf8_to_unicode_index(s: &str, utf8_index: usize) -> Result<usize, usize> {
1102 if utf8_index <= s.len() && s.as_bytes()[..utf8_index].is_ascii() {
1103 return Ok(utf8_index);
1104 }
1105 if utf8_index == 0 {
1106 return Ok(0);
1107 }
1108
1109 let mut current_utf8_index = 0;
1110 let mut current_unicode_index = 0;
1111 for (i, c) in s.chars().enumerate() {
1112 let char_start = current_utf8_index;
1113 current_utf8_index += c.len_utf8();
1114
1115 if utf8_index == char_start {
1116 return Ok(i);
1117 }
1118
1119 if utf8_index < current_utf8_index {
1120 loro_common::info!("WARNING: UTF-8 index is in the middle of a codepoint!");
1121 return Err(i);
1122 }
1123 current_unicode_index = i + 1;
1124 }
1125
1126 if current_utf8_index == utf8_index {
1127 Ok(current_unicode_index)
1128 } else {
1129 Err(current_unicode_index)
1130 }
1131}
1132
1133#[derive(Clone, Debug, Copy, PartialEq, Eq, Default)]
1134pub(crate) struct PosCache {
1135 pub(super) unicode_len: i32,
1136 pub(super) bytes: i32,
1137 pub(super) utf16_len: i32,
1138 pub(crate) entity_len: i32,
1139}
1140
1141impl PosCache {
1142 pub(crate) fn event_len(&self) -> i32 {
1143 if cfg!(feature = "wasm") {
1144 self.utf16_len
1145 } else {
1146 self.unicode_len
1147 }
1148 }
1149
1150 #[allow(unused)]
1151 fn get_len(&self, pos_type: PosType) -> i32 {
1152 match pos_type {
1153 PosType::Bytes => self.bytes,
1154 PosType::Unicode => self.unicode_len,
1155 PosType::Utf16 => self.utf16_len,
1156 PosType::Entity => self.entity_len,
1157 PosType::Event => self.event_len(),
1158 }
1159 }
1160}
1161
1162impl AddAssign for PosCache {
1163 fn add_assign(&mut self, rhs: Self) {
1164 self.unicode_len += rhs.unicode_len;
1165 self.bytes += rhs.bytes;
1166 self.utf16_len += rhs.utf16_len;
1167 self.entity_len += rhs.entity_len;
1168 }
1169}
1170
1171impl Add for PosCache {
1172 type Output = Self;
1173
1174 fn add(self, rhs: Self) -> Self::Output {
1175 Self {
1176 bytes: self.bytes + rhs.bytes,
1177 unicode_len: self.unicode_len + rhs.unicode_len,
1178 utf16_len: self.utf16_len + rhs.utf16_len,
1179 entity_len: self.entity_len + rhs.entity_len,
1180 }
1181 }
1182}
1183
1184impl Sub for PosCache {
1185 type Output = Self;
1186
1187 fn sub(self, rhs: Self) -> Self::Output {
1188 Self {
1189 bytes: self.bytes - rhs.bytes,
1190 unicode_len: self.unicode_len - rhs.unicode_len,
1191 utf16_len: self.utf16_len - rhs.utf16_len,
1192 entity_len: self.entity_len - rhs.entity_len,
1193 }
1194 }
1195}
1196
1197impl CanRemove for PosCache {
1198 fn can_remove(&self) -> bool {
1199 self.bytes == 0
1200 }
1201}
1202
1203pub(crate) struct RichtextTreeTrait;
1204
1205#[derive(Debug)]
1206pub(crate) struct EntityRangeInfo {
1207 pub id_start: ID,
1208 pub entity_start: usize,
1209 pub entity_end: usize,
1210 pub event_len: usize,
1211}
1212
1213/// Entity ranges produced by a single text query. Inline storage avoids a heap
1214/// allocation on the per-op delete hot path, where a contiguous delete is
1215/// usually a single merged range.
1216pub(crate) type EntityRanges = SmallVec<[EntityRangeInfo; 2]>;
1217
1218impl EntityRangeInfo {
1219 pub fn entity_len(&self) -> usize {
1220 self.entity_end - self.entity_start
1221 }
1222}
1223
1224impl BTreeTrait for RichtextTreeTrait {
1225 type Elem = RichtextStateChunk;
1226
1227 type Cache = PosCache;
1228
1229 type CacheDiff = PosCache;
1230
1231 fn calc_cache_internal(
1232 cache: &mut Self::Cache,
1233 caches: &[generic_btree::Child<Self>],
1234 ) -> Self::CacheDiff {
1235 let mut new_cache = PosCache::default();
1236 for child in caches {
1237 new_cache += child.cache;
1238 }
1239
1240 let diff = new_cache - *cache;
1241 *cache = new_cache;
1242 diff
1243 }
1244
1245 #[inline(always)]
1246 fn merge_cache_diff(diff1: &mut Self::CacheDiff, diff2: &Self::CacheDiff) {
1247 *diff1 += *diff2;
1248 }
1249
1250 #[inline(always)]
1251 fn apply_cache_diff(cache: &mut Self::Cache, diff: &Self::CacheDiff) {
1252 *cache += *diff;
1253 }
1254
1255 #[inline]
1256 fn get_elem_cache(elem: &Self::Elem) -> Self::Cache {
1257 match elem {
1258 RichtextStateChunk::Text(s) => PosCache {
1259 bytes: s.bytes().len() as i32,
1260 unicode_len: s.unicode_len(),
1261 utf16_len: s.utf16_len(),
1262 entity_len: s.unicode_len(),
1263 },
1264 RichtextStateChunk::Style { .. } => PosCache {
1265 bytes: 0,
1266 unicode_len: 0,
1267 utf16_len: 0,
1268 entity_len: 1,
1269 },
1270 }
1271 }
1272
1273 #[inline(always)]
1274 fn new_cache_to_diff(cache: &Self::Cache) -> Self::CacheDiff {
1275 *cache
1276 }
1277
1278 #[inline(always)]
1279 fn sub_cache(cache_lhs: &Self::Cache, cache_rhs: &Self::Cache) -> Self::CacheDiff {
1280 PosCache {
1281 bytes: cache_lhs.bytes - cache_rhs.bytes,
1282 unicode_len: cache_lhs.unicode_len - cache_rhs.unicode_len,
1283 utf16_len: cache_lhs.utf16_len - cache_rhs.utf16_len,
1284 entity_len: cache_lhs.entity_len - cache_rhs.entity_len,
1285 }
1286 }
1287}
1288
1289// This query implementation will prefer right element when both left element and right element are valid.
1290mod query {
1291 use crate::utils::query_by_len::{IndexQuery, QueryByLen};
1292
1293 use super::*;
1294
1295 pub(super) type EndQuery<T> = IndexQuery<T, RichtextTreeTrait, true>;
1296
1297 #[cfg(not(feature = "wasm"))]
1298 pub(super) type EventIndexQuery = UnicodeQuery;
1299 #[cfg(feature = "wasm")]
1300 pub(super) type EventIndexQuery = Utf16Query;
1301
1302 #[cfg(not(feature = "wasm"))]
1303 pub(super) type EventIndexQueryT = UnicodeQueryT;
1304 #[cfg(feature = "wasm")]
1305 pub(super) type EventIndexQueryT = Utf16QueryT;
1306
1307 pub(super) struct UnicodeQueryT;
1308 pub(super) type UnicodeQuery = IndexQuery<UnicodeQueryT, RichtextTreeTrait>;
1309
1310 impl QueryByLen<RichtextTreeTrait> for UnicodeQueryT {
1311 fn get_cache_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize {
1312 cache.unicode_len as usize
1313 }
1314
1315 fn get_elem_len(elem: &<RichtextTreeTrait as BTreeTrait>::Elem) -> usize {
1316 match elem {
1317 RichtextStateChunk::Text(s) => s.rle_len(),
1318 RichtextStateChunk::Style { .. } => 0,
1319 }
1320 }
1321
1322 fn get_offset_and_found(
1323 left: usize,
1324 elem: &<RichtextTreeTrait as BTreeTrait>::Elem,
1325 ) -> (usize, bool) {
1326 match elem {
1327 RichtextStateChunk::Text(s) => {
1328 if s.rle_len() >= left {
1329 return (left, true);
1330 }
1331
1332 (left, false)
1333 }
1334 RichtextStateChunk::Style { .. } => (1, false),
1335 }
1336 }
1337
1338 fn get_cache_entity_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize {
1339 cache.entity_len as usize
1340 }
1341 }
1342
1343 pub(crate) struct Utf16QueryT;
1344 pub(crate) type Utf16Query = IndexQuery<Utf16QueryT, RichtextTreeTrait>;
1345
1346 impl QueryByLen<RichtextTreeTrait> for Utf16QueryT {
1347 fn get_cache_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize {
1348 cache.utf16_len as usize
1349 }
1350
1351 fn get_elem_len(elem: &<RichtextTreeTrait as BTreeTrait>::Elem) -> usize {
1352 match elem {
1353 RichtextStateChunk::Text(s) => s.utf16_len() as usize,
1354 RichtextStateChunk::Style { .. } => 0,
1355 }
1356 }
1357
1358 fn get_offset_and_found(
1359 left: usize,
1360 elem: &<RichtextTreeTrait as BTreeTrait>::Elem,
1361 ) -> (usize, bool) {
1362 match elem {
1363 RichtextStateChunk::Text(s) => {
1364 if left == 0 {
1365 return (0, true);
1366 }
1367
1368 // Allow left to not at the correct utf16 boundary. If so fallback to the last position.
1369 // TODO: if we remove the use of query(pos-1), we won't need this fallback behavior
1370 // WARNING: Unable to report error!!!
1371 let offset = s.utf16_offset_to_unicode(left).unwrap_or_else(|e| e);
1372 (offset, true)
1373 }
1374 RichtextStateChunk::Style { .. } => (1, false),
1375 }
1376 }
1377
1378 fn get_cache_entity_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize {
1379 cache.entity_len as usize
1380 }
1381 }
1382
1383 pub(super) struct EntityQueryT;
1384 pub(super) type EntityQuery = IndexQuery<EntityQueryT, RichtextTreeTrait>;
1385
1386 impl QueryByLen<RichtextTreeTrait> for EntityQueryT {
1387 fn get_cache_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize {
1388 cache.entity_len as usize
1389 }
1390
1391 fn get_elem_len(elem: &<RichtextTreeTrait as BTreeTrait>::Elem) -> usize {
1392 match elem {
1393 RichtextStateChunk::Text(s) => s.rle_len(),
1394 RichtextStateChunk::Style { .. } => 1,
1395 }
1396 }
1397
1398 fn get_offset_and_found(
1399 left: usize,
1400 elem: &<RichtextTreeTrait as BTreeTrait>::Elem,
1401 ) -> (usize, bool) {
1402 match elem {
1403 RichtextStateChunk::Text(s) => {
1404 if s.rle_len() >= left {
1405 return (left, true);
1406 }
1407
1408 (left, false)
1409 }
1410 RichtextStateChunk::Style { .. } => {
1411 if left == 0 {
1412 return (0, true);
1413 }
1414
1415 (left, false)
1416 }
1417 }
1418 }
1419
1420 fn get_cache_entity_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize {
1421 cache.entity_len as usize
1422 }
1423 }
1424
1425 pub(super) struct ByteQueryT;
1426 pub(super) type ByteQuery = IndexQuery<ByteQueryT, RichtextTreeTrait>;
1427 impl QueryByLen<RichtextTreeTrait> for ByteQueryT {
1428 fn get_cache_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize {
1429 cache.bytes as usize
1430 }
1431 fn get_elem_len(elem: &<RichtextTreeTrait as BTreeTrait>::Elem) -> usize {
1432 match elem {
1433 RichtextStateChunk::Text(s) => s.utf8_len() as usize,
1434 RichtextStateChunk::Style { .. } => 0,
1435 }
1436 }
1437
1438 fn get_offset_and_found(
1439 left: usize,
1440 elem: &<RichtextTreeTrait as BTreeTrait>::Elem,
1441 ) -> (usize, bool) {
1442 match elem {
1443 RichtextStateChunk::Text(s) => {
1444 if left == 0 {
1445 return (0, true);
1446 }
1447
1448 // Allow left to not at the correct utf16 boundary. If so fallback to the last position.
1449 // TODO: if we remove the use of query(pos-1), we won't need this fallback behavior
1450 // WARNING: Unable to report error!!!
1451 let offset = s.utf8_offset_to_unicode(left).unwrap_or_else(|e| e);
1452 (offset, true)
1453 }
1454 RichtextStateChunk::Style { .. } => (1, false),
1455 }
1456 }
1457
1458 fn get_cache_entity_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize {
1459 cache.entity_len as usize
1460 }
1461 }
1462}
1463
1464/// Whether new text inserted right in front of this anchor stays in front of
1465/// it: the start of an unmark (case 1 of `find_best_insert_pos`), or an anchor
1466/// that prefers inserts before it (case 2).
1467fn insert_stays_before_anchor(style: &StyleOp, anchor_type: AnchorType) -> bool {
1468 (anchor_type == AnchorType::Start && (style.value.is_null() || style.value.is_false()))
1469 || style.info.prefer_insert_before(anchor_type)
1470}
1471
1472impl RichtextState {
1473 pub(crate) fn from_chunks<I: Iterator<Item = impl Into<RichtextStateChunk>>>(i: I) -> Self {
1474 Self {
1475 tree: i.collect(),
1476 style_ranges: Default::default(),
1477 cached_cursor: None,
1478 }
1479 }
1480
1481 pub(crate) fn get_entity_index_for_text_insert(
1482 &mut self,
1483 pos: usize,
1484 pos_type: PosType,
1485 ) -> Result<(usize, Option<Cursor>), LoroError> {
1486 self.check_cache();
1487 let result = {
1488 if self.tree.is_empty() {
1489 return Ok((0, None));
1490 }
1491
1492 // A cached cursor next to a style anchor would skip the anchor
1493 // rules of `find_best_insert_pos`.
1494 let cached = self
1495 .try_get_cache_or_clean(pos, pos_type)
1496 .filter(|c| !self.has_styles() || !self.anchor_rules_may_move_insert(*c));
1497 if let Some(c) = cached {
1498 let entity_index = self.get_cache_entity_index().unwrap();
1499 Ok((entity_index + c.offset, Some(c)))
1500 } else {
1501 let (c, entity_index) = match pos_type {
1502 PosType::Bytes => self.find_best_insert_pos::<ByteQueryT>(pos),
1503 PosType::Unicode => self.find_best_insert_pos::<UnicodeQueryT>(pos),
1504 PosType::Utf16 => self.find_best_insert_pos::<Utf16QueryT>(pos),
1505 PosType::Entity => self.find_best_insert_pos::<EntityQueryT>(pos),
1506 PosType::Event => self.find_best_insert_pos::<EventIndexQueryT>(pos),
1507 };
1508
1509 if let Some(c) = c {
1510 debug_assert_eq!(
1511 self.get_index_from_cursor(c, PosType::Entity).unwrap(),
1512 entity_index
1513 );
1514 self.record_cache(
1515 c.leaf,
1516 entity_index,
1517 PosType::Entity,
1518 c.offset,
1519 Some(entity_index),
1520 );
1521 }
1522 Ok((entity_index, c))
1523 }
1524 };
1525 self.check_cache();
1526 result
1527 }
1528
1529 /// Whether the anchor rules of `find_best_insert_pos` could put an insert
1530 /// somewhere other than `cursor`. They cannot inside a text chunk, between
1531 /// two text chunks, or at the end of a text chunk followed by an anchor
1532 /// that new text stays in front of (the rules stop at that anchor).
1533 fn anchor_rules_may_move_insert(&self, cursor: Cursor) -> bool {
1534 let Some(elem) = self.tree.get_elem(cursor.leaf) else {
1535 return true;
1536 };
1537 if !matches!(elem, RichtextStateChunk::Text { .. }) {
1538 return true;
1539 }
1540 if cursor.offset == 0 {
1541 return self.tree.prev_elem(cursor).is_some_and(|prev| {
1542 matches!(
1543 self.tree.get_elem(prev.leaf),
1544 Some(RichtextStateChunk::Style { .. })
1545 )
1546 });
1547 }
1548 if cursor.offset < elem.rle_len() {
1549 return false;
1550 }
1551 match self
1552 .tree
1553 .next_elem(cursor)
1554 .and_then(|next| self.tree.get_elem(next.leaf))
1555 {
1556 Some(RichtextStateChunk::Style { style, anchor_type }) => {
1557 !insert_stays_before_anchor(style, *anchor_type)
1558 }
1559 _ => false,
1560 }
1561 }
1562
1563 pub(crate) fn has_styles(&self) -> bool {
1564 self.style_ranges
1565 .as_ref()
1566 .map(|x| x.has_style())
1567 .unwrap_or(false)
1568 }
1569
1570 pub(crate) fn range_has_style_key(&mut self, range: Range<usize>, key: &StyleKey) -> bool {
1571 self.check_cache();
1572 let result = match self.style_ranges.as_ref() {
1573 Some(s) => s.range_contains_key(range, key),
1574 None => false,
1575 };
1576 self.check_cache();
1577 result
1578 }
1579
1580 /// Whether every position in the entity range already resolves `key` to
1581 /// `value`, in which case a mark with that key and value can be skipped.
1582 pub(crate) fn range_has_style_key_value(
1583 &mut self,
1584 range: Range<usize>,
1585 key: &str,
1586 value: &LoroValue,
1587 ) -> bool {
1588 self.check_cache();
1589 let result = match self.style_ranges.as_ref() {
1590 Some(s) => s.range_has_key_value(range, key, value),
1591 None => false,
1592 };
1593 self.check_cache();
1594 result
1595 }
1596
1597 /// Return the entity range and text styles at the given range.
1598 /// If in the target range the leaves are not in the same span, the returned styles would be None
1599 pub(crate) fn get_entity_range_and_text_styles_at_range(
1600 &mut self,
1601 range: Range<usize>,
1602 pos_type: PosType,
1603 ) -> (Range<usize>, Option<&Styles>) {
1604 self.check_cache();
1605 let result = {
1606 if self.tree.is_empty() {
1607 return (0..0, None);
1608 }
1609
1610 let (start, _) = self
1611 .get_entity_index_for_text_insert(range.start, pos_type)
1612 .unwrap();
1613 let (end, _) = self
1614 .get_entity_index_for_text_insert(range.end, pos_type)
1615 .unwrap();
1616 if self.has_styles() {
1617 (
1618 start..end,
1619 self.style_ranges
1620 .as_ref()
1621 .unwrap()
1622 .get_styles_of_range(start..end),
1623 )
1624 } else {
1625 (start..end, None)
1626 }
1627 };
1628 self.check_cache();
1629 result
1630 }
1631
1632 /// Get the insert text styles at the given entity index if we insert text at that position
1633 ///
1634 // TODO: PERF we can avoid this calculation by getting it when inserting new text
1635 // but that requires a lot of changes
1636 pub(crate) fn get_styles_at_entity_index_for_insert(
1637 &mut self,
1638 entity_index: usize,
1639 ) -> StyleMeta {
1640 self.check_cache();
1641 let result = {
1642 if !self.has_styles() {
1643 return Default::default();
1644 }
1645
1646 self.style_ranges
1647 .as_mut()
1648 .unwrap()
1649 .get_styles_for_insert(entity_index)
1650 };
1651 self.check_cache();
1652 result
1653 }
1654
1655 /// This is used to accept changes from DiffCalculator
1656 pub(crate) fn insert_at_entity_index(
1657 &mut self,
1658 entity_index: usize,
1659 text: BytesSlice,
1660 id: IdFull,
1661 ) -> Cursor {
1662 if text.len() > text_chunk::MAX_CHUNK_BYTES {
1663 // Insert the pieces back to front at the same index; they end up in order.
1664 let pieces = RichtextStateChunk::try_new(text, id).unwrap().into_pieces();
1665 let mut last = None;
1666 for p in pieces.into_iter().rev() {
1667 let RichtextStateChunk::Text(t) = p else { unreachable!() };
1668 last = Some(self.insert_at_entity_index(entity_index, t.bytes().clone(), t.id_full()));
1669 }
1670 return last.unwrap();
1671 }
1672 self.check_cache();
1673 let result = {
1674 let elem = RichtextStateChunk::try_new(text, id).unwrap();
1675 self.style_ranges
1676 .as_mut()
1677 .map(|x| x.insert(entity_index, elem.rle_len()));
1678 let q = &entity_index;
1679 if let Some(c) = self.try_get_cache_or_clean(entity_index, PosType::Entity) {
1680 let p = self.tree.prefer_left(c).unwrap_or(c);
1681 self.tree.insert_by_path(p, elem).0
1682 } else {
1683 match self.tree.query::<EntityQuery>(q) {
1684 Some(result) => {
1685 let p = self
1686 .tree
1687 .prefer_left(result.cursor)
1688 .unwrap_or(result.cursor);
1689 self.tree.insert_by_path(p, elem).0
1690 }
1691 None => self.tree.push(elem),
1692 }
1693 }
1694 };
1695 self.record_cache(
1696 result.leaf,
1697 entity_index,
1698 PosType::Entity,
1699 result.offset,
1700 None,
1701 );
1702 self.check_cache();
1703 result
1704 }
1705
1706 /// This is used to accept changes from DiffCalculator.
1707 ///
1708 /// Return (event_index, styles)
1709 pub(crate) fn insert_elem_at_entity_index(
1710 &mut self,
1711 entity_index: usize,
1712 elem: RichtextStateChunk,
1713 ) -> (usize, &Styles) {
1714 let mut pieces = elem.into_pieces();
1715 let elem = pieces.remove(0);
1716 for p in pieces.into_iter().rev() {
1717 self.insert_elem_at_entity_index(entity_index, p);
1718 }
1719 self.clear_cache();
1720 let result = {
1721 debug_assert!(
1722 entity_index <= self.len_entity(),
1723 "entity_index={} len={} self={:#?}",
1724 entity_index,
1725 self.len_entity(),
1726 &self
1727 );
1728
1729 let (c, f) = self
1730 .tree
1731 .query_with_finder_return::<EntityIndexQueryWithEventIndex>(&entity_index);
1732 let cursor = c.map(|x| x.cursor);
1733 let event_index = f.event_index;
1734 self.clear_cache();
1735
1736 match cursor {
1737 Some(cursor) => {
1738 let styles = self
1739 .style_ranges
1740 .as_mut()
1741 .map(|x| x.insert(entity_index, elem.rle_len()))
1742 .unwrap_or(&EMPTY_STYLES);
1743 self.tree.insert_by_path(cursor, elem);
1744 (event_index, styles)
1745 }
1746 None => {
1747 let styles = self
1748 .style_ranges
1749 .as_mut()
1750 .map(|x| x.insert(entity_index, elem.rle_len()))
1751 .unwrap_or(&EMPTY_STYLES);
1752 self.tree.push(elem);
1753 (0, styles)
1754 }
1755 }
1756 };
1757 result
1758 }
1759
1760 /// Convert cursor position to event index:
1761 ///
1762 /// - If feature="wasm", index is utf16 index,
1763 /// - If feature!="wasm", index is unicode index,
1764 pub(crate) fn cursor_to_event_index(&self, cursor: Cursor) -> usize {
1765 self.check_cache();
1766 let result = self.get_index_from_cursor(cursor, PosType::Event).unwrap();
1767 self.check_cache();
1768 result
1769 }
1770
1771 /// Cache-aware (`&mut`) variant of [`Self::cursor_to_event_index`] for the
1772 /// per-op insert hot path. When the cursor lands in the currently cached
1773 /// leaf, this reuses the memoized event-index start instead of doing a fresh
1774 /// `visit_previous_caches` walk on every insert.
1775 pub(crate) fn cursor_to_event_index_cached(&mut self, cursor: Cursor) -> usize {
1776 self.check_cache();
1777 let ans = match self.cursor_index_via_cache(cursor, PosType::Event) {
1778 Some(i) => {
1779 debug_assert_eq!(
1780 i,
1781 self.get_index_from_cursor(cursor, PosType::Event).unwrap()
1782 );
1783 i
1784 }
1785 None => self.get_index_from_cursor(cursor, PosType::Event).unwrap(),
1786 };
1787 self.check_cache();
1788 ans
1789 }
1790
1791 pub(crate) fn cursor_to_unicode_index(&self, cursor: Cursor) -> usize {
1792 self.check_cache();
1793 let result = self
1794 .get_index_from_cursor(cursor, PosType::Unicode)
1795 .unwrap();
1796 self.check_cache();
1797 result
1798 }
1799
1800 /// This method only updates `style_ranges`.
1801 /// When this method is called, the style start anchor and the style end anchor should already have been inserted.
1802 pub(crate) fn annotate_style_range(&mut self, range: Range<usize>, style: Arc<StyleOp>) {
1803 self.check_cache();
1804 self.clear_cache();
1805 self.ensure_style_ranges_mut().annotate(range, style, None);
1806 self.check_cache();
1807 }
1808
1809 /// This method only updates `style_ranges`.
1810 /// When this method is called, the style start anchor and the style end anchor should already have been inserted.
1811 ///
1812 /// This method will return the event of this annotation in event length
1813 pub(crate) fn annotate_style_range_with_event(
1814 &mut self,
1815 range: Range<usize>,
1816 style: Arc<StyleOp>,
1817 ) -> impl Iterator<Item = (StyleMeta, usize)> + '_ {
1818 self.check_cache();
1819 self.clear_cache();
1820 let mut ranges_in_entity_index: Vec<(StyleMeta, Range<usize>)> = Vec::new();
1821 let mut start = range.start;
1822 let end = range.end;
1823 self.ensure_style_ranges_mut().annotate(
1824 range,
1825 style,
1826 Some(&mut |s, len| {
1827 let range = start..start + len;
1828 start += len;
1829 ranges_in_entity_index.push((s.into(), range));
1830 }),
1831 );
1832
1833 assert_eq!(ranges_in_entity_index.last().unwrap().1.end, end);
1834 let mut converter = ContinuousIndexConverter::new(self);
1835 let result = ranges_in_entity_index
1836 .into_iter()
1837 .filter_map(move |(meta, range)| {
1838 let start = converter.convert_entity_index_to_event_index(range.start);
1839 let end = converter.convert_entity_index_to_event_index(range.end);
1840 if end == start {
1841 return None;
1842 }
1843
1844 Some((meta, end - start))
1845 });
1846 self.check_cache();
1847 result
1848 }
1849
1850 /// init style ranges if not initialized
1851 fn ensure_style_ranges_mut(&mut self) -> &mut StyleRangeMap {
1852 self.clear_cache();
1853 let result = {
1854 if self.style_ranges.is_none() {
1855 self.style_ranges = Some(Box::default());
1856 }
1857
1858 self.style_ranges.as_mut().unwrap()
1859 };
1860 result
1861 }
1862
1863 pub(crate) fn get_char_by_event_index(&self, pos: usize) -> Result<char, ()> {
1864 self.check_cache();
1865 let result = {
1866 let cursor = self.tree.query::<EventIndexQuery>(&pos).unwrap().cursor;
1867 let Some(str) = &self.tree.get_elem(cursor.leaf) else {
1868 return Err(());
1869 };
1870 if cfg!(not(feature = "wasm")) {
1871 let mut char_iter = str.as_str().unwrap().chars();
1872 match &mut char_iter.nth(cursor.offset) {
1873 Some(c) => Ok(*c),
1874 None => Err(()),
1875 }
1876 } else {
1877 let s = str.as_str().unwrap();
1878 let utf16offset = unicode_to_utf16_index(s, cursor.offset).unwrap();
1879 // Convert utf16 offset to actual character by finding the character at that position
1880 let char_iter = s.chars();
1881 let mut current_utf16_offset = 0;
1882
1883 for c in char_iter {
1884 if current_utf16_offset == utf16offset {
1885 return Ok(c);
1886 }
1887 current_utf16_offset += c.len_utf16();
1888 if current_utf16_offset > utf16offset {
1889 return Err(());
1890 }
1891 }
1892 Err(())
1893 }
1894 };
1895 self.check_cache();
1896 result
1897 }
1898
1899 /// Find the best insert position based on the rich-text CRDT algorithm.
1900 ///
1901 /// The result is only different from `query` when there are style anchors around the insert pos.
1902 /// Returns the right neighbor of the insert pos and the entity index.
1903 ///
1904 /// 1. Insertions occur before style anchors that contain the beginning of new marks.
1905 /// 2. Insertions occur before style anchors that contain the end of bold-like marks
1906 /// 3. Insertions occur after style anchors that contain the end of link-like marks
1907 ///
1908 /// Rule 1 should be satisfied before rules 2 and 3 to avoid creating a new style out of nowhere
1909 ///
1910 /// The current method will scan forward to find the last position that satisfies 1 and 2.
1911 /// Then it scans backward to find the first position that satisfies 3.
1912 fn find_best_insert_pos<Q: QueryByLen<RichtextTreeTrait>>(
1913 &self,
1914 pos: usize,
1915 ) -> (Option<generic_btree::Cursor>, usize) {
1916 type Query<Q> = IndexQueryWithEntityIndex<Q, RichtextTreeTrait>;
1917 if self.tree.is_empty() {
1918 return (None, 0);
1919 }
1920
1921 // There are a range of elements may share the same unicode index
1922 // because style anchors' lengths are zero in unicode index.
1923
1924 // Find the start and the end of the range, and entity index of left cursor
1925 let (left, right, mut entity_index) = if pos == 0 {
1926 let left = self.tree.start_cursor().unwrap();
1927 let mut right = left;
1928 let mut elem = self.tree.get_elem(right.leaf).unwrap();
1929 let entity_index = 0;
1930 if matches!(elem, RichtextStateChunk::Text { .. }) {
1931 return (Some(right), 0);
1932 } else {
1933 while Q::get_elem_len(elem) == 0 {
1934 match self.tree.next_elem(right) {
1935 Some(r) => {
1936 right = r;
1937 elem = self.tree.get_elem(right.leaf).unwrap();
1938 }
1939 None => {
1940 right.offset = elem.rle_len();
1941 break;
1942 }
1943 }
1944 }
1945
1946 (left, right, entity_index)
1947 }
1948 } else {
1949 // The query prefers right when there are empty elements (style anchors)
1950 // So the nodes between (pos-1) and pos are all style anchors.
1951 let (q, f) = self.tree.query_with_finder_return::<Query<Q>>(&(pos - 1));
1952 let q = q.unwrap();
1953 let mut entity_index = f.entity_index();
1954
1955 let elem = self.tree.get_elem(q.leaf()).unwrap();
1956 let mut right = q.cursor;
1957 right.offset += 1;
1958 entity_index += 1;
1959 if elem.rle_len() > right.offset {
1960 // The cursor is in the middle of a style anchor
1961 return (Some(right), entity_index);
1962 }
1963
1964 match self.tree.next_elem(q.cursor) {
1965 // If next is None, we know the range is empty, return directly
1966 None => return (self.tree.end_cursor(), entity_index),
1967 Some(x) => {
1968 assert_eq!(right.offset, elem.rle_len());
1969 right = x;
1970 let mut elem = self.tree.get_elem(right.leaf).unwrap();
1971 if matches!(elem, RichtextStateChunk::Text { .. }) {
1972 return (Some(right), entity_index);
1973 }
1974
1975 let left = x;
1976 while matches!(elem, RichtextStateChunk::Style { .. }) {
1977 match self.tree.next_elem(right) {
1978 Some(r) => {
1979 right = r;
1980 elem = self.tree.get_elem(right.leaf).unwrap();
1981 }
1982 None => {
1983 // this is last element
1984 right.offset = 1;
1985 break;
1986 }
1987 }
1988 }
1989
1990 (left, right, entity_index)
1991 }
1992 }
1993 };
1994
1995 let mut iter = left;
1996
1997 // need to scan from left to right
1998 let mut visited = Vec::new();
1999 while iter != right {
2000 let Some(elem) = self.tree.get_elem(iter.leaf) else {
2001 break;
2002 };
2003
2004 let (style, anchor_type) = match elem {
2005 RichtextStateChunk::Text { .. } => unreachable!(),
2006 RichtextStateChunk::Style { style, anchor_type } => (style, *anchor_type),
2007 };
2008
2009 visited.push((style, anchor_type, iter, entity_index));
2010 if insert_stays_before_anchor(style, anchor_type) {
2011 // case 1 or 2.
2012 break;
2013 }
2014
2015 iter = match self.tree.next_elem(iter) {
2016 Some(x) => x,
2017 None => self.tree.end_cursor().unwrap(),
2018 };
2019 entity_index += 1;
2020 }
2021
2022 while let Some((style, anchor_type, top_elem, top_entity_index)) = visited.pop() {
2023 if !style.info.prefer_insert_before(anchor_type) {
2024 // case 3.
2025 break;
2026 }
2027
2028 iter = top_elem;
2029 entity_index = top_entity_index;
2030 }
2031
2032 (Some(iter), entity_index)
2033 }
2034
2035 fn get_entity_index_from_path(&self, right: generic_btree::Cursor) -> usize {
2036 self.get_index_from_cursor(right, PosType::Entity).unwrap()
2037 }
2038
2039 pub fn get_index_from_cursor(
2040 &self,
2041 cursor: generic_btree::Cursor,
2042 pos_type: PosType,
2043 ) -> Option<usize> {
2044 let mut index = 0;
2045 self.tree
2046 .visit_previous_caches(cursor, |cache| match cache {
2047 generic_btree::PreviousCache::NodeCache(c) => {
2048 index += c.get_len(pos_type) as usize;
2049 }
2050 generic_btree::PreviousCache::PrevSiblingElem(c) => {
2051 index += c.len_with(pos_type);
2052 }
2053 generic_btree::PreviousCache::ThisElemAndOffset { elem, offset } => {
2054 if offset != 0 {
2055 index += entity_offset_to_pos_type_offset(pos_type, elem, offset)
2056 }
2057 }
2058 });
2059
2060 Some(index)
2061 }
2062
2063 pub(crate) fn get_text_entity_ranges(
2064 &self,
2065 pos: usize,
2066 len: usize,
2067 pos_type: PosType,
2068 ) -> LoroResult<EntityRanges> {
2069 self.check_cache();
2070 let result = {
2071 if self.tree.is_empty() {
2072 return Ok(EntityRanges::new());
2073 }
2074
2075 if len == 0 {
2076 return Ok(EntityRanges::new());
2077 }
2078
2079 if pos + len > self.len(pos_type) {
2080 return Ok(EntityRanges::new());
2081 }
2082
2083 let mut ans: EntityRanges = SmallVec::new();
2084 let (start, end) = match pos_type {
2085 PosType::Bytes => (
2086 self.tree.query::<ByteQuery>(&pos).unwrap().cursor,
2087 self.tree.query::<ByteQuery>(&(pos + len)).unwrap().cursor,
2088 ),
2089 PosType::Unicode => (
2090 self.tree.query::<UnicodeQuery>(&pos).unwrap().cursor,
2091 self.tree
2092 .query::<UnicodeQuery>(&(pos + len))
2093 .unwrap()
2094 .cursor,
2095 ),
2096 PosType::Utf16 => (
2097 self.tree.query::<Utf16Query>(&pos).unwrap().cursor,
2098 self.tree.query::<Utf16Query>(&(pos + len)).unwrap().cursor,
2099 ),
2100 PosType::Entity => (
2101 self.tree.query::<EntityQuery>(&pos).unwrap().cursor,
2102 self.tree.query::<EntityQuery>(&(pos + len)).unwrap().cursor,
2103 ),
2104 PosType::Event => (
2105 self.tree.query::<EventIndexQuery>(&pos).unwrap().cursor,
2106 self.tree
2107 .query::<EventIndexQuery>(&(pos + len))
2108 .unwrap()
2109 .cursor,
2110 ),
2111 };
2112
2113 // TODO: assert end cursor is valid
2114 let mut entity_index = self.get_entity_index_from_path(start);
2115 for span in self.tree.iter_range(start..end) {
2116 let start = span.start.unwrap_or(0);
2117 let end = span.end.unwrap_or(span.elem.rle_len());
2118 if end == 0 {
2119 break;
2120 }
2121
2122 let len = end - start;
2123 match span.elem {
2124 RichtextStateChunk::Text(s) => {
2125 let event_len = s.entity_range_to_event_range(start..end).len();
2126 let id = s.id().inc(start as i32);
2127 match ans.last_mut() {
2128 // Every entity of a range is text, so its IDs advance by
2129 // the entity length (not the UTF-16 event length).
2130 Some(last)
2131 if last.entity_end == entity_index
2132 && last.id_start.inc(last.entity_len() as i32) == id =>
2133 {
2134 last.entity_end += len;
2135 last.event_len += event_len;
2136 }
2137 _ => {
2138 ans.push(EntityRangeInfo {
2139 id_start: id,
2140 entity_start: entity_index,
2141 entity_end: entity_index + len,
2142 event_len,
2143 });
2144 }
2145 }
2146 entity_index += len;
2147 }
2148 RichtextStateChunk::Style { .. } => {
2149 entity_index += 1;
2150 }
2151 }
2152 }
2153
2154 Ok(ans)
2155 };
2156 self.check_cache();
2157 result
2158 }
2159
2160 pub(crate) fn get_text_slice_by_event_index(
2161 &self,
2162 pos: usize,
2163 len: usize,
2164 ) -> LoroResult<String> {
2165 self.check_cache();
2166 let result = {
2167 if self.tree.is_empty() {
2168 return Ok(String::new());
2169 }
2170
2171 if len == 0 {
2172 return Ok(String::new());
2173 }
2174
2175 if pos + len > self.len_event() {
2176 return Err(LoroError::OutOfBound {
2177 pos: pos + len,
2178 len: self.len_event(),
2179 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
2180 });
2181 }
2182
2183 let mut ans = String::new();
2184 let (start, end) = (
2185 self.tree.query::<EventIndexQuery>(&pos).unwrap().cursor,
2186 self.tree
2187 .query::<query::EndQuery<EventIndexQueryT>>(&(pos + len))
2188 .unwrap()
2189 .cursor,
2190 );
2191
2192 for span in self.tree.iter_range(start..end) {
2193 let start = span.start.unwrap_or(0);
2194 let end = span.end.unwrap_or(span.elem.rle_len());
2195 if end == 0 {
2196 break;
2197 }
2198
2199 if let RichtextStateChunk::Text(s) = span.elem {
2200 match s.unicode_slice(start, end) {
2201 Ok(x) => ans.push_str(x),
2202 Err(()) => {
2203 return Err(LoroError::UTF16InUnicodeCodePoint { pos: pos + len })
2204 }
2205 }
2206 }
2207 }
2208
2209 Ok(ans)
2210 };
2211 self.check_cache();
2212 result
2213 }
2214
2215 pub(crate) fn slice_delta(
2216 &self,
2217 start_index: usize,
2218 end_index: usize,
2219 pos_type: PosType,
2220 ) -> LoroResult<Vec<(String, StyleMeta)>> {
2221 if end_index < start_index {
2222 return Err(LoroError::EndIndexLessThanStartIndex {
2223 start: start_index,
2224 end: end_index,
2225 });
2226 }
2227
2228 if end_index == start_index {
2229 return Ok(Vec::new());
2230 }
2231
2232 self.check_cache();
2233 let result = {
2234 // 1. Convert start/end pos to cursors
2235 let (start_query, end_query) = match pos_type {
2236 PosType::Event => (
2237 self.tree.query::<EventIndexQuery>(&start_index),
2238 self.tree
2239 .query::<query::EndQuery<EventIndexQueryT>>(&end_index),
2240 ),
2241 PosType::Bytes => (
2242 self.tree.query::<ByteQuery>(&start_index),
2243 self.tree.query::<query::EndQuery<ByteQueryT>>(&end_index),
2244 ),
2245 PosType::Unicode => (
2246 self.tree.query::<UnicodeQuery>(&start_index),
2247 self.tree
2248 .query::<query::EndQuery<UnicodeQueryT>>(&end_index),
2249 ),
2250 PosType::Utf16 => (
2251 self.tree.query::<Utf16Query>(&start_index),
2252 self.tree.query::<query::EndQuery<Utf16QueryT>>(&end_index),
2253 ),
2254 PosType::Entity => (
2255 self.tree.query::<EntityQuery>(&start_index),
2256 self.tree.query::<EntityQuery>(&end_index),
2257 ),
2258 };
2259
2260 let start_cursor = start_query
2261 .ok_or(LoroError::OutOfBound {
2262 pos: start_index,
2263 len: self.len(pos_type),
2264 info: "".into(),
2265 })?
2266 .cursor;
2267 let end_cursor = end_query
2268 .ok_or(LoroError::OutOfBound {
2269 pos: end_index,
2270 len: self.len(pos_type),
2271 info: "".into(),
2272 })?
2273 .cursor;
2274
2275 // 2. Get start entity index
2276 let mut current_entity_index = self
2277 .get_index_from_cursor(start_cursor, PosType::Entity)
2278 .unwrap();
2279 // We need end entity index for style iterator
2280 let end_entity_index = self
2281 .get_index_from_cursor(end_cursor, PosType::Entity)
2282 .unwrap();
2283
2284 // 3. Setup style iterator
2285 let mut style_range_iter: Box<dyn Iterator<Item = (Range<usize>, &Styles)>> =
2286 match &self.style_ranges {
2287 Some(s) => {
2288 let mut idx = current_entity_index;
2289 Box::new(s.iter_range(current_entity_index..end_entity_index).map(
2290 move |elem_slice| {
2291 let len = elem_slice.end.unwrap_or(elem_slice.elem.len)
2292 - elem_slice.start.unwrap_or(0);
2293 let range = idx..idx + len;
2294 idx += len;
2295 (range, &elem_slice.elem.styles)
2296 },
2297 ))
2298 }
2299 None => Box::new(Some((0..usize::MAX / 2, &*EMPTY_STYLES)).into_iter()),
2300 };
2301
2302 let mut cur_style_range = style_range_iter.next();
2303 let mut cur_styles: Option<StyleMeta> =
2304 cur_style_range.as_ref().map(|x| StyleMeta::from(x.1));
2305
2306 let mut ans: Vec<(String, StyleMeta)> = Vec::new();
2307
2308 // 4. Iterate tree range
2309 for span in self.tree.iter_range(start_cursor..end_cursor) {
2310 match &span.elem {
2311 RichtextStateChunk::Text(t) => {
2312 let chunk_len =
2313 span.end.unwrap_or(span.elem.rle_len()) - span.start.unwrap_or(0); // length in rle_len (unicode_len)
2314 let mut processed_len = 0;
2315
2316 while processed_len < chunk_len {
2317 while let Some((inner_cur_range, _)) = cur_style_range.as_ref() {
2318 if current_entity_index >= inner_cur_range.end {
2319 cur_style_range = style_range_iter.next();
2320 cur_styles =
2321 cur_style_range.as_ref().map(|x| StyleMeta::from(x.1));
2322 } else {
2323 break;
2324 }
2325 }
2326
2327 if cur_style_range.is_none() {
2328 cur_styles = Some(StyleMeta::default());
2329 cur_style_range =
2330 Some((current_entity_index..usize::MAX, &*EMPTY_STYLES));
2331 }
2332
2333 let (inner_cur_range, _) = cur_style_range.as_ref().unwrap();
2334
2335 let remaining_text = chunk_len - processed_len;
2336 let remaining_style = inner_cur_range.end - current_entity_index;
2337 let take_len = remaining_text.min(remaining_style);
2338
2339 let slice_start = span.start.unwrap_or(0) + processed_len;
2340 let slice_end = slice_start + take_len;
2341
2342 let text_content =
2343 t.unicode_slice(slice_start, slice_end).map_err(|_| {
2344 LoroError::OutOfBound {
2345 pos: slice_end,
2346 len: t.unicode_len() as usize,
2347 info: "Slice delta out of bound".into(),
2348 }
2349 })?;
2350
2351 let styles = cur_styles.as_ref().unwrap();
2352 if let Some(last) = ans.last_mut() {
2353 if &last.1 == styles {
2354 last.0.push_str(text_content);
2355 processed_len += take_len;
2356 current_entity_index += take_len;
2357 continue;
2358 }
2359 }
2360
2361 ans.push((text_content.to_string(), styles.clone()));
2362
2363 processed_len += take_len;
2364 current_entity_index += take_len;
2365 }
2366 }
2367 RichtextStateChunk::Style { .. } => {
2368 current_entity_index += 1;
2369 }
2370 }
2371 }
2372
2373 Ok(ans)
2374 };
2375 self.check_cache();
2376 result
2377 }
2378
2379 // PERF: can be splitted into two methods. One is without cursor_to_event_index
2380 // PERF: can be speed up a lot by detecting whether the range is in a single leaf first
2381 /// This is used to accept changes from DiffCalculator
2382 #[instrument(skip(self, f))]
2383 pub(crate) fn drain_by_entity_index(
2384 &mut self,
2385 pos: usize,
2386 len: usize,
2387 mut f: Option<&mut dyn FnMut(RichtextStateChunk)>,
2388 ) -> DrainInfo {
2389 let result = {
2390 assert!(
2391 pos + len <= self.len_entity(),
2392 "pos: {}, len: {}, self.len(): {}",
2393 pos,
2394 len,
2395 &self.len_entity(),
2396 );
2397
2398 self.clear_cache();
2399 // PERF: may use cache to speed up
2400 let range = pos..pos + len;
2401 let (start, start_f) = self
2402 .tree
2403 .query_with_finder_return::<EntityIndexQueryWithEventIndex>(&range.start);
2404 let start_cursor = start.unwrap().cursor();
2405 let elem = self.tree.get_elem(start_cursor.leaf).unwrap();
2406
2407 /// This struct remove the corresponding style ranges if the start style anchor is removed
2408 struct StyleRangeUpdater<'a> {
2409 style_ranges: Option<&'a mut StyleRangeMap>,
2410 current_index: usize,
2411 start: usize,
2412 end: usize,
2413 }
2414
2415 impl<'a> StyleRangeUpdater<'a> {
2416 fn update(&mut self, elem: &RichtextStateChunk) {
2417 match &elem {
2418 RichtextStateChunk::Text(t) => {
2419 self.current_index += t.unicode_len() as usize;
2420 }
2421 RichtextStateChunk::Style { style, anchor_type } => {
2422 if matches!(anchor_type, AnchorType::End) {
2423 self.end = self.end.max(self.current_index);
2424 if let Some(s) = self.style_ranges.as_mut() {
2425 let start =
2426 s.remove_style_scanning_backward(style, self.current_index);
2427 self.start = self.start.min(start);
2428 }
2429 }
2430
2431 self.current_index += 1;
2432 }
2433 }
2434 }
2435
2436 fn new(
2437 style_ranges: Option<&'a mut Box<StyleRangeMap>>,
2438 start_index: usize,
2439 ) -> Self {
2440 Self {
2441 style_ranges: style_ranges.map(|x| &mut **x),
2442 current_index: start_index,
2443 end: 0,
2444 start: usize::MAX,
2445 }
2446 }
2447
2448 fn get_affected_range(&self, pos: usize) -> Option<Range<usize>> {
2449 if self.start == usize::MAX {
2450 None
2451 } else {
2452 let start = self.start.min(pos);
2453 let end = self.end.min(pos);
2454 if start == end {
2455 None
2456 } else {
2457 Some(start..end)
2458 }
2459 }
2460 }
2461 }
2462
2463 if elem.rle_len() >= start_cursor.offset + len {
2464 // drop in place
2465 let mut event_len = 0;
2466 let mut updater = StyleRangeUpdater::new(self.style_ranges.as_mut(), pos);
2467 self.tree.update_leaf(start_cursor.leaf, |elem| {
2468 updater.update(&*elem);
2469 match elem {
2470 RichtextStateChunk::Text(text) => {
2471 if let Some(f) = f {
2472 let span =
2473 text.slice(start_cursor.offset..start_cursor.offset + len);
2474 f(RichtextStateChunk::Text(span));
2475 }
2476 let (next, event_len_) =
2477 text.delete_by_entity_index(start_cursor.offset, len);
2478 event_len = event_len_;
2479 (true, next.map(RichtextStateChunk::Text), None)
2480 }
2481 RichtextStateChunk::Style { .. } => {
2482 if let Some(f) = f {
2483 let v = std::mem::replace(
2484 elem,
2485 RichtextStateChunk::Text(TextChunk::new_empty()),
2486 );
2487 f(v);
2488 } else {
2489 *elem = RichtextStateChunk::Text(TextChunk::new_empty());
2490 }
2491 (true, None, None)
2492 }
2493 }
2494 });
2495
2496 let affected_range = updater.get_affected_range(pos);
2497 if let Some(s) = self.style_ranges.as_mut() {
2498 s.delete(pos..pos + len);
2499 }
2500
2501 DrainInfo {
2502 start_event_index: start_f.event_index,
2503 end_event_index: (start_f.event_index + event_len),
2504 affected_style_range: affected_range.map(|entity_range| {
2505 (
2506 entity_range.clone(),
2507 self.entity_index_to_event_index(entity_range.start)
2508 ..self.entity_index_to_event_index(entity_range.end),
2509 )
2510 }),
2511 }
2512 } else {
2513 let (end, end_f) = self
2514 .tree
2515 .query_with_finder_return::<EntityIndexQueryWithEventIndex>(&range.end);
2516 let mut updater = StyleRangeUpdater::new(self.style_ranges.as_mut(), pos);
2517 for iter in generic_btree::iter::Drain::new(&mut self.tree, start, end) {
2518 updater.update(&iter);
2519 if let Some(f) = f.as_mut() {
2520 f(iter)
2521 }
2522 }
2523
2524 let affected_range = updater.get_affected_range(pos);
2525 if let Some(s) = self.style_ranges.as_mut() {
2526 s.delete(pos..pos + len);
2527 }
2528
2529 DrainInfo {
2530 start_event_index: start_f.event_index,
2531 end_event_index: end_f.event_index,
2532 affected_style_range: affected_range.map(|entity_range| {
2533 (
2534 entity_range.clone(),
2535 self.entity_index_to_event_index(entity_range.start)
2536 ..self.entity_index_to_event_index(entity_range.end),
2537 )
2538 }),
2539 }
2540 }
2541 };
2542 result
2543 }
2544
2545 pub fn entity_index_to_event_index(&self, index: usize) -> usize {
2546 if index == 0 {
2547 // the tree maybe empty
2548 return 0;
2549 }
2550 let cursor = self.tree.query::<EntityQuery>(&index).unwrap();
2551 self.cursor_to_event_index(cursor.cursor)
2552 }
2553
2554 pub fn index_to_event_index(&self, index: usize, pos_type: PosType) -> usize {
2555 if self.tree.is_empty() {
2556 return 0;
2557 }
2558
2559 let cursor = match pos_type {
2560 PosType::Entity => self.tree.query::<EntityQuery>(&index).unwrap(),
2561 PosType::Utf16 => self.tree.query::<Utf16Query>(&index).unwrap(),
2562 PosType::Bytes => self.tree.query::<ByteQuery>(&index).unwrap(),
2563 PosType::Event => return index,
2564 PosType::Unicode => self.tree.query::<UnicodeQuery>(&index).unwrap(),
2565 };
2566
2567 self.cursor_to_event_index(cursor.cursor)
2568 }
2569
2570 pub fn event_index_to_unicode_index(&self, index: usize) -> usize {
2571 if !cfg!(feature = "wasm") {
2572 return index;
2573 }
2574
2575 let Some(cursor) = self.tree.query::<EventIndexQuery>(&index) else {
2576 return 0;
2577 };
2578
2579 self.cursor_to_unicode_index(cursor.cursor)
2580 }
2581
2582 /// Convert an event-index position into the index of `pos_type`.
2583 ///
2584 /// This runs in O(log n) by querying the tree once and reading the prefix
2585 /// caches from the resulting cursor, instead of materializing the whole
2586 /// prefix string.
2587 pub fn event_index_to_index(&self, event_index: usize, pos_type: PosType) -> usize {
2588 if self.tree.is_empty() {
2589 return 0;
2590 }
2591
2592 let cursor = self.tree.query::<EventIndexQuery>(&event_index).unwrap();
2593 self.get_index_from_cursor(cursor.cursor, pos_type).unwrap()
2594 }
2595
2596 #[allow(unused)]
2597 pub(crate) fn check(&self) {
2598 if !cfg!(any(debug_assertions, test)) {
2599 return;
2600 }
2601
2602 self.tree.check();
2603 self.check_consistency_between_content_and_style_ranges();
2604 self.check_style_anchors_appear_in_pairs();
2605 }
2606
2607 pub(crate) fn mark_with_entity_index(&mut self, range: Range<usize>, style: Arc<StyleOp>) {
2608 self.check_cache();
2609 self.clear_cache();
2610 if self.tree.is_empty() {
2611 panic!("Cannot mark an empty tree");
2612 }
2613
2614 self.insert_elem_at_entity_index(
2615 range.end,
2616 RichtextStateChunk::from_style(style.clone(), AnchorType::End),
2617 );
2618 self.insert_elem_at_entity_index(
2619 range.start,
2620 RichtextStateChunk::from_style(style.clone(), AnchorType::Start),
2621 );
2622 // end_entity_index + 2, because
2623 // 1. We inserted a start anchor before end_entity_index, so we need to +1
2624 // 2. We need to include the end anchor in the range, so we need to +1
2625 self.ensure_style_ranges_mut()
2626 .annotate(range.start..range.end + 2, style, None);
2627 self.check_cache();
2628 }
2629
2630 pub fn iter(&self) -> impl Iterator<Item = RichtextSpan> + '_ {
2631 let mut entity_index = 0;
2632 let mut style_range_iter: Box<dyn Iterator<Item = (Range<usize>, &Styles)>> =
2633 match &self.style_ranges {
2634 Some(s) => Box::new(s.iter()),
2635 None => Box::new(Some((0..usize::MAX / 2, &*EMPTY_STYLES)).into_iter()),
2636 };
2637 let mut cur_style_range = style_range_iter.next();
2638 let mut cur_styles: Option<StyleMeta> =
2639 cur_style_range.as_ref().map(|x| StyleMeta::from(x.1));
2640
2641 self.tree.iter().filter_map(move |x| match x {
2642 RichtextStateChunk::Text(s) => {
2643 let mut styles = Default::default();
2644 while let Some((inner_cur_range, _)) = cur_style_range.as_ref() {
2645 if entity_index < inner_cur_range.start {
2646 break;
2647 }
2648
2649 if entity_index < inner_cur_range.end {
2650 styles = cur_styles.as_ref().unwrap().clone();
2651 break;
2652 } else {
2653 cur_style_range = style_range_iter.next();
2654 cur_styles = cur_style_range.as_ref().map(|x| StyleMeta::from(x.1));
2655 }
2656 }
2657
2658 entity_index += s.rle_len();
2659 Some(RichtextSpan {
2660 text: s.bytes().clone().into(),
2661 attributes: styles,
2662 })
2663 }
2664 RichtextStateChunk::Style { .. } => {
2665 entity_index += 1;
2666 None
2667 }
2668 })
2669 }
2670
2671 #[inline]
2672 pub fn iter_chunk(&self) -> impl Iterator<Item = &RichtextStateChunk> {
2673 self.tree.iter()
2674 }
2675
2676 pub fn get_richtext_value(&self) -> LoroValue {
2677 self.check_cache();
2678 let result = {
2679 let mut ans: Vec<LoroValue> = Vec::new();
2680 let mut last_attributes: Option<LoroValue> = None;
2681 for span in self.iter() {
2682 let attributes: LoroValue = span.attributes.to_value();
2683 if let Some(last) = last_attributes.as_ref() {
2684 if &attributes == last {
2685 let hash_map = ans.last_mut().unwrap().as_map_mut().unwrap();
2686 let s = hash_map
2687 .make_mut()
2688 .get_mut("insert")
2689 .unwrap()
2690 .as_string_mut()
2691 .unwrap();
2692 s.make_mut().push_str(span.text.as_str());
2693 continue;
2694 }
2695 }
2696
2697 let mut value = FxHashMap::default();
2698 value.insert(
2699 "insert".into(),
2700 LoroValue::String(span.text.as_str().into()),
2701 );
2702
2703 if !attributes.as_map().unwrap().is_empty() {
2704 value.insert("attributes".into(), attributes.clone());
2705 }
2706
2707 ans.push(LoroValue::Map(value.into()));
2708 last_attributes = Some(attributes);
2709 }
2710
2711 LoroValue::List(ans.into())
2712 };
2713 self.check_cache();
2714 result
2715 }
2716
2717 #[allow(unused)]
2718 pub fn to_vec(&self) -> Vec<RichtextSpan> {
2719 self.iter().collect()
2720 }
2721
2722 #[cfg(test)]
2723 #[allow(unused)]
2724 pub(crate) fn debug(&self) {
2725 dbg!(&self.tree);
2726 dbg!(&self.style_ranges);
2727 }
2728
2729 #[inline(always)]
2730 pub fn len_unicode(&self) -> usize {
2731 self.tree.root_cache().unicode_len as usize
2732 }
2733
2734 #[inline(always)]
2735 pub fn len_utf16(&self) -> usize {
2736 self.tree.root_cache().utf16_len as usize
2737 }
2738
2739 #[inline(always)]
2740 pub fn len_utf8(&self) -> usize {
2741 self.tree.root_cache().bytes as usize
2742 }
2743
2744 #[inline(always)]
2745 pub fn is_empty(&self) -> bool {
2746 self.tree.root_cache().entity_len == 0
2747 }
2748
2749 #[inline(always)]
2750 pub fn len_entity(&self) -> usize {
2751 self.tree.root_cache().entity_len as usize
2752 }
2753
2754 #[inline(always)]
2755 pub(crate) fn content_node_len(&self) -> usize {
2756 self.tree.node_len()
2757 }
2758
2759 pub fn diagnose(&self) {
2760 println!(
2761 "rope_nodes: {}, style_nodes: {}, text_len: {}",
2762 self.tree.node_len(),
2763 self.style_ranges
2764 .as_ref()
2765 .map(|x| x.tree.node_len())
2766 .unwrap_or(0),
2767 self.tree.root_cache().bytes
2768 );
2769 }
2770
2771 /// Check if the content and style ranges are consistent.
2772 ///
2773 /// Panic if inconsistent.
2774 pub(crate) fn check_consistency_between_content_and_style_ranges(&self) {
2775 if !cfg!(debug_assertions) {
2776 return;
2777 }
2778
2779 // A start anchor whose end is not in the state (a version that holds a
2780 // mark's `StyleStart` but not its `StyleEnd`, loro-dev/loro#1165) styles
2781 // nothing, so it has no style range.
2782 let closed: FxHashSet<&Arc<StyleOp>> = self
2783 .iter_chunk()
2784 .filter_map(|c| match c {
2785 RichtextStateChunk::Style {
2786 style,
2787 anchor_type: AnchorType::End,
2788 } => Some(style),
2789 _ => None,
2790 })
2791 .collect();
2792 let mut entity_index_to_style_anchor: FxHashMap<usize, &RichtextStateChunk> =
2793 FxHashMap::default();
2794 let mut index = 0;
2795 for c in self.iter_chunk() {
2796 if let RichtextStateChunk::Style { style, .. } = c {
2797 if closed.contains(style) {
2798 entity_index_to_style_anchor.insert(index, c);
2799 }
2800 }
2801
2802 index += c.length()
2803 }
2804
2805 if let Some(s) = &self.style_ranges {
2806 for IterAnchorItem {
2807 index,
2808 op,
2809 anchor_type: iter_anchor_type,
2810 } in s.iter_anchors()
2811 {
2812 let c = entity_index_to_style_anchor
2813 .remove(&index)
2814 .unwrap_or_else(|| {
2815 panic!(
2816 "Inconsistency found {} {:?} {:?}",
2817 index, iter_anchor_type, &op
2818 );
2819 });
2820
2821 match c {
2822 RichtextStateChunk::Text(_) => {
2823 unreachable!()
2824 }
2825 RichtextStateChunk::Style { style, anchor_type } => {
2826 assert_eq!(style, &op);
2827 assert_eq!(&iter_anchor_type, anchor_type);
2828 }
2829 }
2830 }
2831 }
2832
2833 assert!(
2834 entity_index_to_style_anchor.is_empty(),
2835 "Inconsistency found. Some anchors are not reflected in style ranges {:#?}",
2836 &entity_index_to_style_anchor
2837 );
2838 }
2839
2840 /// Every end anchor must follow its start anchor. A start anchor may lack its end.
2841 pub(crate) fn check_style_anchors_appear_in_pairs(&self) {
2842 if !cfg!(any(debug_assertions, test)) {
2843 return;
2844 }
2845
2846 let mut start_ops: FxHashSet<&Arc<StyleOp>> = Default::default();
2847 for item in self.iter_chunk() {
2848 match item {
2849 RichtextStateChunk::Text(_) => {}
2850 RichtextStateChunk::Style { style, anchor_type } => match anchor_type {
2851 AnchorType::Start => {
2852 start_ops.insert(style);
2853 }
2854 AnchorType::End => {
2855 assert!(start_ops.remove(style), "End anchor without start anchor");
2856 }
2857 },
2858 }
2859 }
2860 // A start anchor without its end is allowed: a version can hold a mark's
2861 // `StyleStart` op but not its `StyleEnd` op (loro-dev/loro#1165).
2862 let _ = start_ops;
2863 }
2864
2865 /// Iter style ranges in the given range in entity index
2866 pub(crate) fn iter_range(
2867 &self,
2868 range: impl RangeBounds<usize>,
2869 ) -> impl Iterator<Item = IterRangeItem<'_>> + '_ {
2870 self.check_cache();
2871 let result = {
2872 let start = match range.start_bound() {
2873 Bound::Included(x) => *x,
2874 Bound::Excluded(x) => x + 1,
2875 Bound::Unbounded => 0,
2876 };
2877 let end = match range.end_bound() {
2878 Bound::Included(x) => x + 1,
2879 Bound::Excluded(x) => *x,
2880 Bound::Unbounded => self.len_entity(),
2881 };
2882 assert!(end > start);
2883 assert!(end <= self.len_entity());
2884
2885 let mut style_iter = self
2886 .style_ranges
2887 .as_ref()
2888 .map(|x| x.iter_range(range))
2889 .into_iter()
2890 .flatten();
2891
2892 let start = self.tree.query::<EntityQuery>(&start).unwrap();
2893 let end = self.tree.query::<EntityQuery>(&end).unwrap();
2894 let mut content_iter = self.tree.iter_range(start.cursor..end.cursor);
2895 let mut style_left_len = usize::MAX;
2896 let mut cur_style = style_iter
2897 .next()
2898 .map(|x| {
2899 style_left_len = x.elem.len - x.start.unwrap_or(0);
2900 &x.elem.styles
2901 })
2902 .unwrap_or(&*EMPTY_STYLES);
2903 let mut chunk = content_iter.next();
2904 let mut offset = 0;
2905 let mut chunk_left_len = chunk
2906 .as_ref()
2907 .map(|x| {
2908 let len = x.elem.rle_len();
2909 offset = x.start.unwrap_or(0);
2910 x.end.map(|v| v.min(len)).unwrap_or(len) - offset
2911 })
2912 .unwrap_or(0);
2913 std::iter::from_fn(move || {
2914 if chunk_left_len == 0 {
2915 chunk = content_iter.next();
2916 chunk_left_len = chunk
2917 .as_ref()
2918 .map(|x| {
2919 let len = x.elem.rle_len();
2920 x.end.map(|v| v.min(len)).unwrap_or(len)
2921 })
2922 .unwrap_or(0);
2923 offset = 0;
2924 }
2925
2926 let iter_chunk = chunk.as_ref()?;
2927
2928 let styles = cur_style;
2929 let iter_len;
2930 let event_range;
2931 if chunk_left_len >= style_left_len {
2932 iter_len = style_left_len;
2933 event_range = iter_chunk
2934 .elem
2935 .entity_range_to_event_range(offset..offset + iter_len);
2936 chunk_left_len -= style_left_len;
2937 offset += style_left_len;
2938 style_left_len = 0;
2939 } else {
2940 iter_len = chunk_left_len;
2941 event_range = iter_chunk
2942 .elem
2943 .entity_range_to_event_range(offset..offset + iter_len);
2944 style_left_len -= chunk_left_len;
2945 chunk_left_len = 0;
2946 }
2947
2948 if style_left_len == 0 {
2949 cur_style = style_iter
2950 .next()
2951 .map(|x| {
2952 style_left_len = x.elem.len;
2953 &x.elem.styles
2954 })
2955 .unwrap_or(&*EMPTY_STYLES);
2956 }
2957
2958 Some(IterRangeItem {
2959 chunk: iter_chunk.elem,
2960 styles,
2961 entity_len: iter_len,
2962 event_len: event_range.len(),
2963 })
2964 })
2965 };
2966 self.check_cache();
2967 result
2968 }
2969
2970 pub(crate) fn get_stable_position_at_event_index(
2971 &self,
2972 pos: usize,
2973 kind: PosType,
2974 ) -> Option<ID> {
2975 self.check_cache();
2976 let result = {
2977 if pos >= self.len(kind) {
2978 return None;
2979 }
2980
2981 let cursor = match kind {
2982 PosType::Event => self.tree.query::<EventIndexQuery>(&pos)?,
2983 PosType::Unicode => self.tree.query::<UnicodeQuery>(&pos)?,
2984 _ => unreachable!("stable text positions use event or Unicode indices"),
2985 };
2986
2987 // A WASM event index is a UTF-16 offset. The tree query rounds an
2988 // offset inside a surrogate pair down to the scalar's start, so
2989 // compare it back to reject non-boundaries before selecting an ID.
2990 if self.get_index_from_cursor(cursor.cursor, kind)? != pos {
2991 return None;
2992 }
2993
2994 let range_len = if kind == PosType::Event && cfg!(feature = "wasm") {
2995 self.get_char_by_event_index(pos).ok()?.len_utf16()
2996 } else {
2997 1
2998 };
2999 let v = &self.get_text_entity_ranges(pos, range_len, kind).unwrap();
3000 let a = v.first()?;
3001 Some(a.id_start)
3002 };
3003 self.check_cache();
3004 result
3005 }
3006
3007 pub(crate) fn len_event(&self) -> usize {
3008 self.check_cache();
3009 let result = {
3010 if cfg!(feature = "wasm") {
3011 self.len_utf16()
3012 } else {
3013 self.len_unicode()
3014 }
3015 };
3016 self.check_cache();
3017 result
3018 }
3019
3020 pub(crate) fn len(&self, pos_type: PosType) -> usize {
3021 self.check_cache();
3022 let result = {
3023 match pos_type {
3024 PosType::Unicode => self.len_unicode(),
3025 PosType::Utf16 => self.len_utf16(),
3026 PosType::Entity => self.len_entity(),
3027 PosType::Event => self.len_event(),
3028 PosType::Bytes => self.len_utf8(),
3029 }
3030 };
3031 self.check_cache();
3032 result
3033 }
3034}
3035
3036fn entity_offset_to_pos_type_offset(
3037 pos_type: PosType,
3038 elem: &RichtextStateChunk,
3039 offset: usize,
3040) -> usize {
3041 match pos_type {
3042 PosType::Bytes => match elem {
3043 RichtextStateChunk::Text(t) => t.unicode_offset_to_utf8(offset).unwrap(),
3044 RichtextStateChunk::Style { .. } => 0,
3045 },
3046 PosType::Unicode => match elem {
3047 RichtextStateChunk::Text(_) => offset,
3048 RichtextStateChunk::Style { .. } => 0,
3049 },
3050 PosType::Utf16 => match elem {
3051 RichtextStateChunk::Text(t) => t.unicode_offset_to_utf16(offset).unwrap(),
3052 RichtextStateChunk::Style { .. } => 0,
3053 },
3054 PosType::Entity => offset,
3055 PosType::Event => match elem {
3056 RichtextStateChunk::Text(t) => {
3057 if cfg!(feature = "wasm") {
3058 t.unicode_offset_to_utf16(offset).unwrap()
3059 } else {
3060 offset
3061 }
3062 }
3063 RichtextStateChunk::Style { .. } => 0,
3064 },
3065 }
3066}
3067
3068fn pos_type_offset_to_entity_offset(
3069 pos_type: PosType,
3070 elem: &RichtextStateChunk,
3071 offset: usize,
3072) -> Option<usize> {
3073 match pos_type {
3074 PosType::Bytes => match elem {
3075 RichtextStateChunk::Text(t) => t.utf8_offset_to_unicode(offset).ok(),
3076 RichtextStateChunk::Style { .. } => {
3077 if offset > 0 {
3078 None
3079 } else {
3080 Some(0)
3081 }
3082 }
3083 },
3084 PosType::Unicode => Some(offset),
3085 PosType::Utf16 => match elem {
3086 RichtextStateChunk::Text(t) => t.utf16_offset_to_unicode(offset).ok(),
3087 RichtextStateChunk::Style { .. } => {
3088 if offset > 0 {
3089 None
3090 } else {
3091 Some(0)
3092 }
3093 }
3094 },
3095 PosType::Entity => {
3096 if offset > elem.rle_len() {
3097 None
3098 } else {
3099 Some(offset)
3100 }
3101 }
3102 PosType::Event => match elem {
3103 RichtextStateChunk::Text(t) => {
3104 if cfg!(feature = "wasm") {
3105 t.utf16_offset_to_unicode(offset).ok()
3106 } else if offset < t.unicode_len() as usize {
3107 Some(offset)
3108 } else {
3109 None
3110 }
3111 }
3112 RichtextStateChunk::Style { .. } => {
3113 if offset > 0 {
3114 None
3115 } else {
3116 Some(0)
3117 }
3118 }
3119 },
3120 }
3121}
3122
3123pub(crate) struct DrainInfo {
3124 pub start_event_index: usize,
3125 pub end_event_index: usize,
3126 // entity range, event range
3127 pub affected_style_range: Option<(Range<usize>, Range<usize>)>,
3128}
3129
3130pub(crate) struct IterRangeItem<'a> {
3131 pub(crate) chunk: &'a RichtextStateChunk,
3132 pub(crate) styles: &'a Styles,
3133 pub(crate) entity_len: usize,
3134 pub(crate) event_len: usize,
3135}
3136
3137use converter::ContinuousIndexConverter;
3138mod converter {
3139 use generic_btree::{rle::HasLength, Cursor};
3140
3141 use super::{query::EntityQuery, RichtextState};
3142
3143 /// Convert entity index into event index.
3144 /// It assumes the entity_index are in ascending order
3145 pub(super) struct ContinuousIndexConverter<'a> {
3146 state: &'a RichtextState,
3147 last_entity_index_cache: Option<ConverterCache>,
3148 }
3149
3150 struct ConverterCache {
3151 entity_index: usize,
3152 cursor: Cursor,
3153 event_index: usize,
3154 cursor_elem_len: usize,
3155 }
3156
3157 impl<'a> ContinuousIndexConverter<'a> {
3158 pub fn new(state: &'a RichtextState) -> Self {
3159 Self {
3160 state,
3161 last_entity_index_cache: None,
3162 }
3163 }
3164
3165 pub fn convert_entity_index_to_event_index(&mut self, entity_index: usize) -> usize {
3166 self.state.check_cache();
3167 let result = {
3168 if let Some(last) = self.last_entity_index_cache.as_ref() {
3169 if last.entity_index == entity_index {
3170 return last.event_index;
3171 }
3172
3173 assert!(entity_index > last.entity_index);
3174 if last.cursor.offset + entity_index - last.entity_index < last.cursor_elem_len
3175 {
3176 // in the same cursor
3177 return self.state.cursor_to_event_index(Cursor {
3178 leaf: last.cursor.leaf,
3179 offset: last.cursor.offset + entity_index - last.entity_index,
3180 });
3181 }
3182 }
3183
3184 let cursor = self
3185 .state
3186 .tree
3187 .query::<EntityQuery>(&entity_index)
3188 .unwrap()
3189 .cursor;
3190 let ans = self.state.cursor_to_event_index(cursor);
3191 let len = self.state.tree.get_elem(cursor.leaf).unwrap().rle_len();
3192 self.last_entity_index_cache = Some(ConverterCache {
3193 entity_index,
3194 cursor,
3195 event_index: ans,
3196 cursor_elem_len: len,
3197 });
3198 ans
3199 };
3200 self.state.check_cache();
3201 result
3202 }
3203 }
3204}
3205
3206#[cfg(test)]
3207mod insert_pos_cache_test;
3208
3209#[cfg(test)]
3210mod test {
3211 use append_only_bytes::AppendOnlyBytes;
3212 use serde_json::json;
3213
3214 use crate::{container::richtext::TextStyleInfoFlag, ToJson};
3215
3216 use super::*;
3217
3218 #[derive(Debug, Default, Clone)]
3219 struct SimpleWrapper {
3220 state: RichtextState,
3221 bytes: AppendOnlyBytes,
3222 }
3223
3224 impl SimpleWrapper {
3225 fn insert(&mut self, pos: usize, text: &str) {
3226 let start = self.bytes.len();
3227 self.bytes.push_str(text);
3228 {
3229 let state = &mut self.state;
3230 let text = self.bytes.slice(start..);
3231 let (entity_index, _) = state
3232 .get_entity_index_for_text_insert(pos, PosType::Unicode)
3233 .unwrap();
3234 state.insert_at_entity_index(entity_index, text, IdFull::new(0, 0, 0));
3235 };
3236 }
3237
3238 fn delete(&mut self, pos: usize, len: usize) {
3239 let ranges = self
3240 .state
3241 .get_text_entity_ranges(pos, len, PosType::Unicode)
3242 .unwrap();
3243 for range in ranges.into_iter().rev() {
3244 self.state.drain_by_entity_index(
3245 range.entity_start,
3246 range.entity_end - range.entity_start,
3247 None,
3248 );
3249 }
3250 }
3251
3252 fn mark(&mut self, range: Range<usize>, style: Arc<StyleOp>) {
3253 let (start, _) = self
3254 .state
3255 .get_entity_index_for_text_insert(range.start, PosType::Unicode)
3256 .unwrap();
3257 let (end, _) = self
3258 .state
3259 .get_entity_index_for_text_insert(range.end, PosType::Unicode)
3260 .unwrap();
3261 self.state.mark_with_entity_index(start..end, style);
3262 }
3263 }
3264
3265 fn bold(n: isize) -> Arc<StyleOp> {
3266 Arc::new(StyleOp::new_for_test(
3267 n,
3268 "bold",
3269 true.into(),
3270 TextStyleInfoFlag::BOLD,
3271 ))
3272 }
3273
3274 fn comment(n: isize) -> Arc<StyleOp> {
3275 Arc::new(StyleOp::new_for_test(
3276 n,
3277 &format!("comment:{}", n),
3278 "comment".into(),
3279 TextStyleInfoFlag::COMMENT,
3280 ))
3281 }
3282
3283 fn unbold(n: isize) -> Arc<StyleOp> {
3284 Arc::new(StyleOp::new_for_test(
3285 n,
3286 "bold",
3287 LoroValue::Null,
3288 TextStyleInfoFlag::BOLD.to_delete(),
3289 ))
3290 }
3291
3292 fn link(n: isize) -> Arc<StyleOp> {
3293 Arc::new(StyleOp::new_for_test(
3294 n,
3295 "link",
3296 true.into(),
3297 TextStyleInfoFlag::LINK,
3298 ))
3299 }
3300
3301 #[test]
3302 fn test() {
3303 let mut wrapper = SimpleWrapper::default();
3304 wrapper.insert(0, "Hello World!");
3305 wrapper.mark(0..5, bold(0));
3306 assert_eq!(
3307 wrapper.state.get_richtext_value().to_json_value(),
3308 json!([
3309 {
3310 "insert": "Hello",
3311 "attributes": {
3312 "bold": true
3313 }
3314 },
3315 {
3316 "insert": " World!"
3317 }
3318 ])
3319 );
3320 wrapper.mark(2..7, link(1));
3321 assert_eq!(
3322 wrapper.state.get_richtext_value().to_json_value(),
3323 json!([
3324 {
3325 "insert": "He",
3326 "attributes": {
3327 "bold": true
3328 }
3329 },
3330 {
3331 "insert": "llo",
3332 "attributes": {
3333 "bold": true,
3334 "link": true
3335 }
3336 },
3337 {
3338 "insert": " W",
3339 "attributes": {
3340 "link": true
3341 }
3342 },
3343 {
3344 "insert": "orld!"
3345 }
3346
3347 ])
3348 );
3349 }
3350
3351 #[test]
3352 fn delete_text() {
3353 let mut wrapper = SimpleWrapper::default();
3354 wrapper.insert(0, "Hello World!");
3355 assert_eq!(wrapper.state.len_unicode(), 12);
3356 assert_eq!(wrapper.state.len_entity(), 12);
3357 wrapper.delete(0, 5);
3358 assert_eq!(
3359 wrapper.state.get_richtext_value().to_json_value(),
3360 json!([
3361 {
3362 "insert": " World!"
3363 }
3364 ])
3365 );
3366
3367 assert_eq!(wrapper.state.len_unicode(), 7);
3368 assert_eq!(wrapper.state.len_entity(), 7);
3369 wrapper.delete(1, 1);
3370
3371 assert_eq!(wrapper.state.len_unicode(), 6);
3372 assert_eq!(wrapper.state.len_entity(), 6);
3373 assert_eq!(
3374 wrapper.state.get_richtext_value().to_json_value(),
3375 json!([
3376 {
3377 "insert": " orld!"
3378 }
3379 ])
3380 );
3381
3382 wrapper.delete(5, 1);
3383 assert_eq!(wrapper.state.len_unicode(), 5);
3384 assert_eq!(wrapper.state.len_entity(), 5);
3385 assert_eq!(
3386 wrapper.state.get_richtext_value().to_json_value(),
3387 json!([
3388 {
3389 "insert": " orld"
3390 }
3391 ])
3392 );
3393
3394 wrapper.delete(0, 5);
3395 assert_eq!(wrapper.state.len_unicode(), 0);
3396 assert_eq!(
3397 wrapper.state.get_richtext_value().to_json_value(),
3398 json!([])
3399 );
3400 }
3401
3402 #[test]
3403 #[ignore]
3404 fn insert_cache_hit() {
3405 let mut wrapper = SimpleWrapper::default();
3406 wrapper.insert(0, "H");
3407 wrapper.insert(1, "H");
3408 dbg!(&wrapper);
3409 wrapper.insert(2, "e");
3410 dbg!(&wrapper);
3411 wrapper.insert(3, "k");
3412 wrapper.state.diagnose();
3413 }
3414
3415 #[test]
3416 fn bold_should_expand() {
3417 let mut wrapper = SimpleWrapper::default();
3418 wrapper.insert(0, "Hello World!");
3419 wrapper.mark(0..5, bold(0));
3420 wrapper.insert(5, " Test");
3421 assert_eq!(
3422 wrapper.state.get_richtext_value().to_json_value(),
3423 json!([
3424 {
3425 "insert": "Hello Test",
3426 "attributes": {
3427 "bold": true
3428 }
3429 },
3430 {
3431 "insert": " World!"
3432 }
3433 ])
3434 );
3435 }
3436
3437 #[test]
3438 fn link_should_not_expand() {
3439 let mut wrapper = SimpleWrapper::default();
3440 wrapper.insert(0, "Hello World!");
3441 wrapper.mark(0..5, link(0));
3442 wrapper.insert(5, " Test");
3443 assert_eq!(
3444 wrapper.state.get_richtext_value().to_json_value(),
3445 json!([
3446 {
3447 "insert": "Hello",
3448 "attributes": {
3449 "link": true
3450 }
3451 },
3452 {
3453 "insert": " Test World!"
3454 },
3455 ])
3456 );
3457 }
3458
3459 #[test]
3460 fn continuous_text_insert_should_be_merged() {
3461 let mut wrapper = SimpleWrapper::default();
3462 wrapper.insert(0, "Hello");
3463 wrapper.insert(5, " World!");
3464 assert_eq!(
3465 wrapper.state.get_richtext_value().to_json_value(),
3466 json!([
3467 {
3468 "insert": "Hello World!"
3469 },
3470 ])
3471 );
3472 }
3473
3474 #[test]
3475 fn continuous_text_insert_should_be_merged_and_have_bold() {
3476 let mut wrapper = SimpleWrapper::default();
3477 wrapper.insert(0, "Hello");
3478 wrapper.mark(0..5, bold(0));
3479 wrapper.insert(5, " World!");
3480 dbg!(&wrapper.state);
3481 assert_eq!(
3482 wrapper.state.get_richtext_value().to_json_value(),
3483 json!([
3484 {
3485 "insert": "Hello World!",
3486 "attributes": {
3487 "bold": true
3488 }
3489 },
3490 ])
3491 );
3492 }
3493
3494 #[test]
3495 fn continuous_text_insert_should_not_be_merged_when_prev_is_link() {
3496 let mut wrapper = SimpleWrapper::default();
3497 wrapper.insert(0, "Hello");
3498 wrapper.mark(0..5, link(0));
3499 wrapper.insert(5, " World!");
3500 assert_eq!(
3501 wrapper.state.get_richtext_value().to_json_value(),
3502 json!([
3503 {
3504 "insert": "Hello",
3505 "attributes": {
3506 "link": true
3507 }
3508 },
3509 {
3510
3511 "insert": " World!",
3512 }
3513 ])
3514 );
3515 }
3516
3517 #[test]
3518 fn delete_bold() {
3519 let mut wrapper = SimpleWrapper::default();
3520 wrapper.insert(0, "Hello World!");
3521 wrapper.mark(0..12, bold(0));
3522 wrapper.mark(5..12, unbold(1));
3523 assert_eq!(
3524 wrapper.state.get_richtext_value().to_json_value(),
3525 json!([
3526 {
3527 "insert": "Hello",
3528 "attributes": {
3529 "bold": true
3530 }
3531 },
3532 {
3533 "insert": " World!"
3534 }
3535 ])
3536 );
3537 wrapper.insert(5, "A");
3538 assert_eq!(
3539 wrapper.state.get_richtext_value().to_json_value(),
3540 json!([
3541 {
3542 "insert": "HelloA",
3543 "attributes": {
3544 "bold": true
3545 }
3546 },
3547 {
3548 "insert": " World!",
3549 }
3550 ])
3551 );
3552
3553 wrapper.insert(0, "A");
3554 assert_eq!(
3555 wrapper.state.get_richtext_value().to_json_value(),
3556 json!([
3557 {
3558 "insert": "A",
3559 },
3560 {
3561 "insert": "HelloA",
3562 "attributes": {
3563 "bold": true
3564 }
3565 },
3566 {
3567 "insert": " World!",
3568 }
3569 ])
3570 );
3571 }
3572
3573 #[test]
3574 fn bold_and_link_at_the_same_place() {
3575 let mut wrapper = SimpleWrapper::default();
3576 wrapper.insert(0, "Hello");
3577 wrapper.mark(0..5, link(0));
3578 wrapper.mark(0..5, bold(1));
3579 wrapper.insert(5, "A");
3580 assert_eq!(
3581 wrapper.state.get_richtext_value().to_json_value(),
3582 json!([
3583 {
3584 "insert": "Hello",
3585 "attributes": {
3586 "bold": true,
3587 "link": true
3588 }
3589 },
3590 {
3591 "insert": "A",
3592 "attributes": {
3593 "bold": true,
3594 }
3595 },
3596 ])
3597 );
3598 }
3599
3600 #[test]
3601 fn test_comments() {
3602 let mut wrapper = SimpleWrapper::default();
3603 wrapper.insert(0, "Hello World!");
3604 wrapper.mark(0..5, comment(0));
3605 wrapper.mark(1..6, comment(1));
3606 assert_eq!(
3607 wrapper.state.get_richtext_value().to_json_value(),
3608 json!([
3609 {
3610 "insert": "H",
3611 "attributes": {
3612 "comment:0": "comment",
3613 },
3614 },
3615 {
3616 "insert": "ello",
3617 "attributes": {
3618 "comment:0": "comment",
3619 "comment:1": "comment",
3620 },
3621 },
3622
3623 {
3624 "insert": " ",
3625 "attributes": {
3626 "comment:1": "comment",
3627 },
3628 },
3629 {
3630 "insert": "World!",
3631 }
3632 ])
3633 );
3634 }
3635
3636 #[test]
3637 fn remove_style_anchors_should_also_delete_style() {
3638 let mut wrapper = SimpleWrapper::default();
3639 wrapper.insert(0, "Hello World!");
3640 wrapper.mark(0..5, bold(0));
3641 let mut count = 0;
3642 wrapper.state.drain_by_entity_index(
3643 0,
3644 7,
3645 Some(&mut |span| {
3646 if matches!(span, RichtextStateChunk::Style { .. }) {
3647 count += 1;
3648 }
3649 }),
3650 );
3651
3652 assert_eq!(count, 2);
3653 assert_eq!(
3654 wrapper.state.get_richtext_value().to_json_value(),
3655 json!([{
3656 "insert": " World!"
3657 }])
3658 );
3659 }
3660
3661 #[test]
3662 fn remove_start_anchor_should_remove_style() {
3663 let mut wrapper = SimpleWrapper::default();
3664 wrapper.insert(0, "Hello World!");
3665 wrapper.mark(0..5, bold(0));
3666 wrapper.state.drain_by_entity_index(6, 1, None);
3667 wrapper.state.drain_by_entity_index(0, 1, None);
3668 assert_eq!(
3669 wrapper.state.get_richtext_value().to_json_value(),
3670 json!([{
3671 "insert": "Hello World!"
3672 }])
3673 );
3674 }
3675
3676 #[test]
3677 fn remove_start_anchor_in_the_middle_should_remove_style() {
3678 let mut wrapper = SimpleWrapper::default();
3679 wrapper.insert(0, "Hello World!");
3680 wrapper.mark(2..5, bold(0));
3681 wrapper.state.drain_by_entity_index(6, 1, None);
3682 wrapper.state.drain_by_entity_index(1, 2, None);
3683 assert_eq!(
3684 wrapper.state.get_richtext_value().to_json_value(),
3685 json!([{
3686 "insert": "Hllo World!"
3687 }])
3688 );
3689 }
3690}