loro-internal 1.12.0

Loro internal library. Do not use it directly as it's not stable.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
use generic_btree::{rle::HasLength, rle::Sliceable as _, Cursor};
use loro_common::{ContainerID, InternalString, LoroError, LoroResult, LoroValue, ID};
use loro_delta::DeltaRopeBuilder;
use rustc_hash::{FxHashMap, FxHashSet};
use std::ops::Range;
use std::sync::{Arc, Weak};

use crate::{
    container::{
        idx::ContainerIdx,
        list::list_op,
        richtext::{
            config::StyleConfigMap,
            richtext_state::{
                DrainInfo, EntityRangeInfo, IterRangeItem, PosType, RichtextStateChunk,
            },
            AnchorType, RichtextState as InnerState, StyleKey, StyleOp, Styles,
        },
    },
    delta::{StyleMeta, StyleMetaItem},
    event::{Diff, Index, InternalDiff, TextDiff},
    handler::TextDelta,
    op::{Op, RawOp},
    sync::RwLock,
    utils::{lazy::LazyLoad, string_slice::StringSlice},
    LoroDocInner,
};

use super::{ApplyLocalOpReturn, ContainerState, DiffApplyContext};

#[derive(Debug)]
pub struct RichtextState {
    idx: ContainerIdx,
    config: Arc<RwLock<StyleConfigMap>>,
    state: LazyLoad<RichtextStateLoader, InnerState>,
    /// This is used to indicate whether the richtext state is changed, so the downstream has an easy way to cache
    /// NOTE: We need to ensure the invariance that the version id is always increased when the richtext state is changed
    version_id: usize,
}

struct Pos {
    entity_index: usize,
    event_index: usize,
}

impl RichtextState {
    #[inline]
    pub fn new(idx: ContainerIdx, config: Arc<RwLock<StyleConfigMap>>) -> Self {
        Self {
            idx,
            config,
            state: LazyLoad::Src(Default::default()),
            version_id: 0,
        }
    }

    #[inline]
    fn update_version(&mut self) {
        self.version_id = self.version_id.wrapping_add(1);
    }

    /// Get the version id of the richtext
    ///
    /// This can be used to detect whether the richtext is changed
    #[inline]
    pub fn get_version_id(&self) -> usize {
        self.version_id
    }

    /// Get the text content of the richtext
    ///
    /// This uses `mut` because we may need to build the state from snapshot
    #[inline]
    pub fn to_string_mut(&mut self) -> String {
        self.state.get_mut().to_string()
    }

    #[allow(unused)]
    #[inline(always)]
    pub(crate) fn is_empty(&self) -> bool {
        match &self.state {
            LazyLoad::Src(s) => s.elements.is_empty(),
            LazyLoad::Dst(d) => d.is_empty(),
        }
    }

    pub(crate) fn diagnose(&self) {
        match &self.state {
            LazyLoad::Src(_) => {}
            LazyLoad::Dst(d) => d.diagnose(),
        }
    }

    pub(crate) fn get_text_slice_by_event_index(
        &mut self,
        pos: usize,
        len: usize,
    ) -> LoroResult<String> {
        self.state.get_mut().get_text_slice_by_event_index(pos, len)
    }

    pub(crate) fn slice_delta(
        &mut self,
        start_index: usize,
        end_index: usize,
        pos_type: PosType,
    ) -> LoroResult<Vec<(String, StyleMeta)>> {
        self.state
            .get_mut()
            .slice_delta(start_index, end_index, pos_type)
    }

    pub(crate) fn get_char_by_event_index(&mut self, pos: usize) -> Result<char, ()> {
        self.state.get_mut().get_char_by_event_index(pos)
    }

    pub(crate) fn iter(&mut self, mut callback: impl FnMut(&str) -> bool) {
        for span in self.state.get_mut().iter_chunk() {
            match span {
                RichtextStateChunk::Text(text_chunk) => {
                    if !callback(text_chunk.as_str()) {
                        return;
                    }
                }
                RichtextStateChunk::Style { .. } => {}
            }
        }
    }

    pub(crate) fn iter_raw(&self, callback: &mut dyn FnMut(&RichtextStateChunk)) {
        let iter: &mut dyn Iterator<Item = &RichtextStateChunk>;
        let mut a;
        let mut b;
        match &self.state {
            LazyLoad::Src(s) => {
                a = Some(s.elements.iter());
                iter = &mut *a.as_mut().unwrap();
            }
            LazyLoad::Dst(s) => {
                b = Some(s.iter_chunk());
                iter = &mut *b.as_mut().unwrap();
            }
        }

        for c in iter {
            callback(c);
        }
    }

    fn get_style_start(
        &mut self,
        style_starts: &mut FxHashMap<Arc<StyleOp>, Pos>,
        style: &Arc<StyleOp>,
    ) -> Pos {
        self.update_version();
        match style_starts.remove(style) {
            Some(x) => x,
            None => {
                // this should happen rarely, so it should be fine to scan
                let mut pos = Pos {
                    entity_index: 0,
                    event_index: 0,
                };

                for c in self.state.get_mut().iter_chunk() {
                    match c {
                        RichtextStateChunk::Style {
                            style: s,
                            anchor_type: AnchorType::Start,
                        } if style == s => {
                            break;
                        }
                        RichtextStateChunk::Text(t) => {
                            pos.entity_index += t.unicode_len() as usize;
                            pos.event_index += t.event_len() as usize;
                        }
                        RichtextStateChunk::Style { .. } => {
                            pos.entity_index += 1;
                        }
                    }
                }
                pos
            }
        }
    }

    pub fn get_index_of_id(&self, id: ID) -> Option<usize> {
        let iter: &mut dyn Iterator<Item = &RichtextStateChunk>;
        let mut a;
        let mut b;
        match &self.state {
            LazyLoad::Src(s) => {
                a = Some(s.elements.iter());
                iter = &mut *a.as_mut().unwrap();
            }
            LazyLoad::Dst(s) => {
                b = Some(s.iter_chunk());
                iter = &mut *b.as_mut().unwrap();
            }
        }

        let mut index = 0;
        for elem in iter {
            let span = elem.get_id_span();
            if span.contains(id) {
                return Some(index + (id.counter - span.counter.start) as usize);
            }

            index += elem.rle_len();
        }

        None
    }

    pub fn get_text_index_of_id(&self, id: ID, use_event_index: bool) -> Option<usize> {
        let iter: &mut dyn Iterator<Item = &RichtextStateChunk>;
        let mut a;
        let mut b;
        match &self.state {
            LazyLoad::Src(s) => {
                a = Some(s.elements.iter());
                iter = &mut *a.as_mut().unwrap();
            }
            LazyLoad::Dst(s) => {
                b = Some(s.iter_chunk());
                iter = &mut *b.as_mut().unwrap();
            }
        }

        let mut index = 0;
        for elem in iter {
            let span = elem.get_id_span();
            if span.contains(id) {
                match elem {
                    RichtextStateChunk::Text(t) => {
                        if use_event_index {
                            let event_offset = t.convert_unicode_offset_to_event_offset(
                                (id.counter - span.counter.start) as usize,
                            );
                            return Some(index + event_offset);
                        } else {
                            return Some(index + (id.counter - span.counter.start) as usize);
                        }
                    }
                    RichtextStateChunk::Style { .. } => {
                        return Some(index);
                    }
                }
            }

            index += match elem {
                RichtextStateChunk::Text(t) => {
                    if use_event_index {
                        t.event_len() as usize
                    } else {
                        t.unicode_len() as usize
                    }
                }
                RichtextStateChunk::Style { .. } => 0,
            };
        }

        None
    }

    pub(crate) fn get_delta(&mut self) -> Vec<TextDelta> {
        let mut delta = Vec::new();
        for span in self.state.get_mut().iter() {
            let next_attr = span.attributes.to_option_map();
            match delta.last_mut() {
                Some(TextDelta::Insert { insert, attributes }) if &next_attr == attributes => {
                    insert.push_str(span.text.as_str());
                    continue;
                }
                _ => {}
            }
            delta.push(TextDelta::Insert {
                insert: span.text.as_str().to_string(),
                attributes: next_attr,
            })
        }
        delta
    }
}

#[cfg(test)]
mod tests {
    use crate::{container::richtext::StyleKey, cursor::PosType, handler::HandlerTrait, LoroDoc};

    #[test]
    fn has_style_key_in_entity_range_basic() {
        let loro = LoroDoc::new_auto_commit();
        let text = loro.get_text("text");
        text.insert(0, "abcdef", PosType::Unicode).unwrap();
        text.mark(1, 3, "bold", true.into(), PosType::Unicode)
            .unwrap();

        let bold_key = StyleKey::Key("bold".into());
        let has_style = text
            .with_state(|state| {
                let st = state.as_richtext_state_mut().unwrap();
                let (entity_range, _) =
                    st.get_entity_range_and_styles_at_range(1..3, PosType::Unicode);
                Ok(st.has_style_key_in_entity_range(entity_range, &bold_key))
            })
            .unwrap();
        assert!(has_style);

        let missing = text
            .with_state(|state| {
                let st = state.as_richtext_state_mut().unwrap();
                let (entity_range, _) =
                    st.get_entity_range_and_styles_at_range(4..5, PosType::Unicode);
                Ok(st.has_style_key_in_entity_range(entity_range, &bold_key))
            })
            .unwrap();
        assert!(!missing);
    }

    #[test]
    fn has_style_key_in_entity_range_spans_elements() {
        let loro = LoroDoc::new_auto_commit();
        let text = loro.get_text("text");
        text.insert(0, "abcdefgh", PosType::Unicode).unwrap();
        text.mark(0, 2, "bold", true.into(), PosType::Unicode)
            .unwrap();
        text.mark(3, 5, "bold", true.into(), PosType::Unicode)
            .unwrap();

        let bold_key = StyleKey::Key("bold".into());

        let has_style_across_segments = text
            .with_state(|state| {
                let st = state.as_richtext_state_mut().unwrap();
                let (entity_range, _) =
                    st.get_entity_range_and_styles_at_range(0..5, PosType::Unicode);
                Ok(st.has_style_key_in_entity_range(entity_range, &bold_key))
            })
            .unwrap();
        assert!(has_style_across_segments);

        let gap_has_style = text
            .with_state(|state| {
                let st = state.as_richtext_state_mut().unwrap();
                let (entity_range, _) =
                    st.get_entity_range_and_styles_at_range(6..7, PosType::Unicode);
                Ok(st.has_style_key_in_entity_range(entity_range, &bold_key))
            })
            .unwrap();
        assert!(!gap_has_style);
    }
}

impl Clone for RichtextState {
    fn clone(&self) -> Self {
        Self {
            idx: self.idx,
            config: self.config.clone(),
            state: self.state.clone(),
            version_id: self.version_id,
        }
    }
}

impl ContainerState for RichtextState {
    fn container_idx(&self) -> ContainerIdx {
        self.idx
    }

    fn is_state_empty(&self) -> bool {
        match &self.state {
            LazyLoad::Src(s) => s.is_empty(),
            LazyLoad::Dst(s) => s.is_empty(),
        }
    }

    // TODO: refactor
    fn apply_diff_and_convert(&mut self, diff: InternalDiff, _ctx: DiffApplyContext) -> Diff {
        self.update_version();
        let InternalDiff::RichtextRaw(richtext) = diff else {
            unreachable!()
        };

        // tracing::info!("Self state = {:#?}", &self);
        // PERF: compose delta
        let mut ans: TextDiff = TextDiff::new();
        let mut style_delta: TextDiff = TextDiff::new();
        let mut style_starts: FxHashMap<Arc<StyleOp>, Pos> = FxHashMap::default();
        let mut entity_index = 0;
        let mut event_index = 0;
        let mut new_style_deltas: Vec<TextDiff> = Vec::new();
        for span in richtext.iter() {
            match span {
                loro_delta::DeltaItem::Retain { len, .. } => {
                    entity_index += len;
                }
                loro_delta::DeltaItem::Replace { value, delete, .. } => {
                    if *delete > 0 {
                        // Deletions
                        let mut deleted_style_keys: FxHashSet<InternalString> =
                            FxHashSet::default();
                        let DrainInfo {
                            start_event_index: start,
                            end_event_index: end,
                            affected_style_range,
                        } = self.state.get_mut().drain_by_entity_index(
                            entity_index,
                            *delete,
                            Some(&mut |c| match c {
                                RichtextStateChunk::Style {
                                    style,
                                    anchor_type: AnchorType::Start,
                                } => {
                                    deleted_style_keys.insert(style.key.clone());
                                }
                                RichtextStateChunk::Style {
                                    style,
                                    anchor_type: AnchorType::End,
                                } => {
                                    deleted_style_keys.insert(style.key.clone());
                                }
                                _ => {}
                            }),
                        );

                        if start > event_index {
                            ans.push_retain(start - event_index, Default::default());
                            event_index = start;
                        }

                        if let Some((entity_range, event_range)) = affected_style_range {
                            let mut delta: TextDiff = DeltaRopeBuilder::new()
                                .retain(event_range.start, Default::default())
                                .build();
                            let mut entity_len_sum = 0;
                            let expected_sum = entity_range.len();

                            for IterRangeItem {
                                event_len,
                                chunk,
                                styles,
                                entity_len,
                                ..
                            } in self.state.get_mut().iter_range(entity_range)
                            {
                                entity_len_sum += entity_len;
                                match chunk {
                                    RichtextStateChunk::Text(_) => {
                                        let mut style_meta: StyleMeta = styles.into();
                                        for key in deleted_style_keys.iter() {
                                            if !style_meta.contains_key(key) {
                                                style_meta.insert(
                                                    key.clone(),
                                                    StyleMetaItem {
                                                        lamport: 0,
                                                        peer: 0,
                                                        value: LoroValue::Null,
                                                    },
                                                )
                                            }
                                        }
                                        delta.push_retain(
                                            event_len,
                                            style_meta.to_option_map().unwrap_or_default().into(),
                                        );
                                    }
                                    RichtextStateChunk::Style { .. } => {}
                                }
                            }

                            debug_assert_eq!(entity_len_sum, expected_sum);
                            delta.chop();
                            style_delta.compose(&delta);
                        }

                        ans.push_delete(end - start);
                    }

                    if value.rle_len() > 0 {
                        // Insertions
                        match value {
                            RichtextStateChunk::Text(s) => {
                                let (pos, styles) =
                                    self.state.get_mut().insert_elem_at_entity_index(
                                        entity_index,
                                        RichtextStateChunk::Text(s.clone()),
                                    );
                                // PERF: this can be optimized
                                let insert_styles = Into::<StyleMeta>::into(styles.clone())
                                    .to_option_map()
                                    .unwrap_or_default();

                                if pos > event_index {
                                    ans.push_retain(pos - event_index, Default::default());
                                }
                                event_index = pos + s.event_len() as usize;
                                ans.push_insert(
                                    StringSlice::from(s.bytes().clone()),
                                    insert_styles.into(),
                                );
                            }
                            RichtextStateChunk::Style { anchor_type, style } => {
                                let (new_event_index, _) =
                                    self.state.get_mut().insert_elem_at_entity_index(
                                        entity_index,
                                        RichtextStateChunk::Style {
                                            style: style.clone(),
                                            anchor_type: *anchor_type,
                                        },
                                    );

                                if new_event_index > event_index {
                                    ans.push_retain(
                                        new_event_index - event_index,
                                        Default::default(),
                                    );
                                    // inserting style anchor will not affect event_index's positions
                                    event_index = new_event_index;
                                }

                                match anchor_type {
                                    AnchorType::Start => {
                                        style_starts.insert(
                                            style.clone(),
                                            Pos {
                                                entity_index,
                                                event_index: new_event_index,
                                            },
                                        );
                                    }
                                    AnchorType::End => {
                                        // get the pair of style anchor. now we can annotate the range
                                        let Pos {
                                            entity_index: start_entity_index,
                                            event_index: start_event_index,
                                        } = self.get_style_start(&mut style_starts, style);
                                        let mut delta: TextDiff = DeltaRopeBuilder::new()
                                            .retain(start_event_index, Default::default())
                                            .build();
                                        // we need to + 1 because we also need to annotate the end anchor
                                        let event =
                                            self.state.get_mut().annotate_style_range_with_event(
                                                start_entity_index..entity_index + 1,
                                                style.clone(),
                                            );
                                        for (s, l) in event {
                                            delta.push_retain(
                                                l,
                                                s.to_option_map().unwrap_or_default().into(),
                                            );
                                        }

                                        delta.chop();
                                        new_style_deltas.push(delta);
                                    }
                                }
                            }
                        }

                        entity_index += value.rle_len();
                    }
                }
            }
        }

        for s in new_style_deltas {
            style_delta.compose(&s);
        }
        // self.check_consistency_between_content_and_style_ranges();
        ans.compose(&style_delta);
        Diff::Text(ans)
    }

    fn apply_diff(&mut self, diff: InternalDiff, _ctx: DiffApplyContext) -> LoroResult<()> {
        self.update_version();
        let InternalDiff::RichtextRaw(richtext) = diff else {
            unreachable!()
        };

        // Fast path for plain-text deltas (no style anchors / style ranges).
        //
        // Rebuilding avoids repeated BTree queries and mutations when the delta is very "choppy"
        // (many small edit spans), but it allocates and clones chunks, so it can be slower for
        // small deltas. Use a cheap cost model to enable it only when it's likely beneficial.
        let should_fast_apply = {
            #[inline]
            fn ilog2_ceil(x: usize) -> usize {
                debug_assert!(x > 0);
                (usize::BITS - (x - 1).leading_zeros()) as usize
            }

            let state = self.state.get_mut();
            if state.has_styles() {
                false
            } else {
                // `edit_actions` approximates how many BTree mutations the incremental path will do:
                // each Replace with delete>0 becomes a drain, and each Replace with value>0 becomes an insert.
                let mut edit_actions: usize = 0;
                let mut is_plain_text_delta = true;
                for span in richtext.iter() {
                    match span {
                        loro_delta::DeltaItem::Retain { .. } => {}
                        loro_delta::DeltaItem::Replace { value, delete, .. } => {
                            if *delete > 0 {
                                edit_actions += 1;
                            }
                            if value.rle_len() > 0 {
                                if !matches!(value, RichtextStateChunk::Text(_)) {
                                    is_plain_text_delta = false;
                                    break;
                                }
                                edit_actions += 1;
                            }
                        }
                    }
                }

                if !is_plain_text_delta || edit_actions == 0 {
                    false
                } else {
                    let content_nodes = state.content_node_len().max(1);
                    let log_n = ilog2_ceil(content_nodes + 1).max(1);
                    let incremental_score = edit_actions.saturating_mul(log_n);
                    let rebuild_score = content_nodes.saturating_add(edit_actions);

                    let old_len = richtext.old_len().max(1);
                    let avg_action_span = old_len / edit_actions;
                    // A very rough proxy for "choppiness": many edit actions with small average span.
                    // The thresholds are intentionally conservative to avoid rebuilding for small or
                    // localized deltas.
                    let is_choppy = edit_actions >= 256 && avg_action_span <= 32;

                    is_choppy && incremental_score >= rebuild_score.saturating_mul(4)
                }
            }
        };

        if should_fast_apply {
            let new_state = {
                let state = self.state.get_mut();
                let mut chunks: Vec<RichtextStateChunk> = Vec::new();

                let mut src_iter = state.iter_chunk();
                let mut cur = src_iter.next();
                let mut cur_offset: usize = 0;

                for span in richtext.iter() {
                    match span {
                        loro_delta::DeltaItem::Retain { len, .. } => {
                            let mut left = *len;
                            while left > 0 {
                                let chunk = cur.expect("Delta retain exceeds source length");
                                let chunk_len = chunk.rle_len();
                                if chunk_len == 0 {
                                    cur = src_iter.next();
                                    cur_offset = 0;
                                    continue;
                                }
                                let available = chunk_len - cur_offset;
                                let take = left.min(available);
                                if take == chunk_len && cur_offset == 0 {
                                    chunks.push(chunk.clone());
                                } else {
                                    chunks.push(chunk.slice(cur_offset..cur_offset + take));
                                }

                                left -= take;
                                cur_offset += take;
                                if cur_offset == chunk_len {
                                    cur = src_iter.next();
                                    cur_offset = 0;
                                }
                            }
                        }
                        loro_delta::DeltaItem::Replace { value, delete, .. } => {
                            let mut left = *delete;
                            while left > 0 {
                                let chunk = cur.expect("Delta delete exceeds source length");
                                let chunk_len = chunk.rle_len();
                                if chunk_len == 0 {
                                    cur = src_iter.next();
                                    cur_offset = 0;
                                    continue;
                                }
                                let available = chunk_len - cur_offset;
                                let take = left.min(available);
                                left -= take;
                                cur_offset += take;
                                if cur_offset == chunk_len {
                                    cur = src_iter.next();
                                    cur_offset = 0;
                                }
                            }

                            if value.rle_len() > 0 {
                                chunks.push(value.clone());
                            }
                        }
                    }
                }

                if let Some(chunk) = cur {
                    let chunk_len = chunk.rle_len();
                    if cur_offset < chunk_len {
                        if cur_offset == 0 {
                            chunks.push(chunk.clone());
                        } else {
                            chunks.push(chunk.slice(cur_offset..chunk_len));
                        }
                    }
                }
                for chunk in src_iter {
                    chunks.push(chunk.clone());
                }

                InnerState::from_chunks(chunks.into_iter())
            };

            *self.state.get_mut() = new_state;
            return Ok(());
        }

        let mut style_starts: FxHashMap<Arc<StyleOp>, usize> = FxHashMap::default();
        let mut entity_index = 0;
        for span in richtext.iter() {
            match span {
                loro_delta::DeltaItem::Retain { len, .. } => {
                    entity_index += len;
                }
                loro_delta::DeltaItem::Replace { value, delete, .. } => {
                    if *delete > 0 {
                        // Deletions
                        self.state
                            .get_mut()
                            .drain_by_entity_index(entity_index, *delete, None);
                    }
                    if value.rle_len() > 0 {
                        // Insertions
                        match value {
                            RichtextStateChunk::Text(s) => {
                                self.state.get_mut().insert_elem_at_entity_index(
                                    entity_index,
                                    RichtextStateChunk::Text(s.clone()),
                                );
                            }
                            RichtextStateChunk::Style { style, anchor_type } => {
                                self.state.get_mut().insert_elem_at_entity_index(
                                    entity_index,
                                    RichtextStateChunk::Style {
                                        style: style.clone(),
                                        anchor_type: *anchor_type,
                                    },
                                );

                                if *anchor_type == AnchorType::Start {
                                    style_starts.insert(style.clone(), entity_index);
                                } else {
                                    let start_pos = match style_starts.get(style) {
                                        Some(x) => *x,
                                        None => {
                                            // This should be rare, so it should be fine to scan
                                            let mut start_entity_index = 0;
                                            for c in self.state.get_mut().iter_chunk() {
                                                match c {
                                                    RichtextStateChunk::Style {
                                                        style: s,
                                                        anchor_type: AnchorType::Start,
                                                    } if style == s => {
                                                        break;
                                                    }
                                                    RichtextStateChunk::Text(t) => {
                                                        start_entity_index +=
                                                            t.unicode_len() as usize;
                                                    }
                                                    RichtextStateChunk::Style { .. } => {
                                                        start_entity_index += 1;
                                                    }
                                                }
                                            }
                                            start_entity_index
                                        }
                                    };
                                    // we need to + 1 because we also need to annotate the end anchor
                                    self.state.get_mut().annotate_style_range(
                                        start_pos..entity_index + 1,
                                        style.clone(),
                                    );
                                }
                            }
                        }
                        entity_index += value.rle_len();
                    }
                }
            }
        }

        // self.check_consistency_between_content_and_style_ranges()
        Ok(())
    }

    fn apply_local_op(&mut self, r_op: &RawOp, op: &Op) -> LoroResult<ApplyLocalOpReturn> {
        self.update_version();
        match &op.content {
            crate::op::InnerContent::List(l) => match l {
                list_op::InnerListOp::Insert { slice: _, pos: _ } => {
                    unreachable!()
                }
                list_op::InnerListOp::InsertText {
                    slice,
                    unicode_len: _,
                    unicode_start: _,
                    pos,
                } => {
                    self.state.get_mut().insert_at_entity_index(
                        *pos as usize,
                        slice.clone(),
                        r_op.id_full(),
                    );
                }
                list_op::InnerListOp::Delete(del) => {
                    self.state.get_mut().drain_by_entity_index(
                        del.start() as usize,
                        rle::HasLength::atom_len(&del),
                        None,
                    );
                }
                list_op::InnerListOp::StyleStart {
                    start,
                    end,
                    key,
                    value,
                    info,
                } => {
                    // Behavior here is a little different from apply_diff.
                    //
                    // When apply_diff, we only do the mark when we have included both
                    // StyleStart and StyleEnd.
                    //
                    // When applying local op, we can do the mark when we have StyleStart.
                    // We can assume StyleStart and StyleEnd are always appear in a pair
                    // for apply_local_op. (Because for local behavior, when we mark,
                    // we always create a pair of style ops.)
                    self.state.get_mut().mark_with_entity_index(
                        *start as usize..*end as usize,
                        Arc::new(StyleOp {
                            lamport: r_op.lamport,
                            peer: r_op.id.peer,
                            cnt: r_op.id.counter,
                            key: key.clone(),
                            value: value.clone(),
                            info: *info,
                        }),
                    );
                }
                list_op::InnerListOp::Set { .. } => {}
                list_op::InnerListOp::StyleEnd => {}
                list_op::InnerListOp::Move { .. } => unreachable!(),
            },
            _ => unreachable!(),
        }

        // self.check_consistency_between_content_and_style_ranges();
        Ok(Default::default())
    }

    fn to_diff(&mut self, _doc: &Weak<LoroDocInner>) -> Diff {
        let mut delta = TextDiff::new();
        for span in self.state.get_mut().iter() {
            delta.push_insert(
                span.text,
                span.attributes.to_option_map().unwrap_or_default().into(),
            );
        }

        Diff::Text(delta)
    }

    // value is a list
    fn get_value(&mut self) -> LoroValue {
        self.state.get_mut().to_string().into()
    }

    #[doc = r" Get the index of the child container"]
    #[allow(unused)]
    fn get_child_index(&self, id: &ContainerID) -> Option<Index> {
        None
    }

    #[allow(unused)]
    fn get_child_containers(&self) -> Vec<ContainerID> {
        Vec::new()
    }

    fn contains_child(&self, _id: &ContainerID) -> bool {
        false
    }

    fn fork(&self, config: &crate::configure::Configure) -> Self {
        Self {
            idx: self.idx,
            config: config.text_style_config.clone(),
            state: self.state.clone(),
            version_id: 0,
        }
    }
}

impl RichtextState {
    #[inline(always)]
    pub fn len_utf8(&mut self) -> usize {
        self.state.get_mut().len_utf8()
    }

    #[inline(always)]
    pub fn len(&mut self, pos_type: PosType) -> usize {
        self.state.get_mut().len(pos_type)
    }

    #[inline(always)]
    pub fn len_utf16(&mut self) -> usize {
        self.state.get_mut().len_utf16()
    }

    #[inline(always)]
    pub fn len_entity(&self) -> usize {
        match &self.state {
            LazyLoad::Src(s) => s.entity_index,
            LazyLoad::Dst(d) => d.len_entity(),
        }
    }

    pub fn len_event(&mut self) -> usize {
        if cfg!(feature = "wasm") {
            self.len_utf16()
        } else {
            self.len_unicode()
        }
    }

    #[inline]
    pub(crate) fn has_styles(&mut self) -> bool {
        self.state.get_mut().has_styles()
    }

    pub(crate) fn has_style_key_in_entity_range(
        &mut self,
        range: Range<usize>,
        key: &StyleKey,
    ) -> bool {
        self.state.get_mut().range_has_style_key(range, key)
    }

    /// Check if the content and style ranges are consistent.
    ///
    /// Panic if inconsistent.
    #[allow(unused)]
    pub(crate) fn check_consistency_between_content_and_style_ranges(&mut self) {
        if !cfg!(debug_assertions) {
            return;
        }

        self.state
            .get_mut()
            .check_consistency_between_content_and_style_ranges();
    }

    #[inline]
    pub fn len_unicode(&mut self) -> usize {
        self.state.get_mut().len_unicode()
    }

    #[inline]
    pub(crate) fn get_entity_index_for_text_insert(
        &mut self,
        index: usize,
        pos_type: PosType,
    ) -> Result<(usize, Option<Cursor>), LoroError> {
        self.state
            .get_mut()
            .get_entity_index_for_text_insert(index, pos_type)
    }

    #[inline]
    pub(crate) fn get_event_index_by_cursor(&mut self, cursor: Cursor) -> usize {
        self.state
            .get_mut()
            .get_index_from_cursor(cursor, PosType::Event)
            .unwrap()
    }

    pub(crate) fn get_entity_range_and_styles_at_range(
        &mut self,
        range: Range<usize>,
        pos_type: PosType,
    ) -> (Range<usize>, Option<&Styles>) {
        self.state
            .get_mut()
            .get_entity_range_and_text_styles_at_range(range, pos_type)
    }

    #[inline]
    pub(crate) fn get_styles_at_entity_index(&mut self, entity_index: usize) -> StyleMeta {
        self.state
            .get_mut()
            .get_styles_at_entity_index_for_insert(entity_index)
    }

    #[inline]
    pub(crate) fn get_text_entity_ranges_in_event_index_range(
        &mut self,
        pos: usize,
        len: usize,
    ) -> LoroResult<Vec<EntityRangeInfo>> {
        self.state
            .get_mut()
            .get_text_entity_ranges(pos, len, PosType::Event)
    }

    #[inline]
    pub fn get_richtext_value(&mut self) -> LoroValue {
        self.state.get_mut().get_richtext_value()
    }

    #[inline]
    pub(crate) fn get_stable_position(
        &mut self,
        event_index: usize,
        get_by_event_index: bool,
    ) -> Option<ID> {
        self.state.get_mut().get_stable_position_at_event_index(
            event_index,
            if get_by_event_index {
                PosType::Event
            } else {
                PosType::Unicode
            },
        )
    }

    pub(crate) fn entity_index_to_event_index(&mut self, entity_index: usize) -> usize {
        self.state
            .get_mut()
            .entity_index_to_event_index(entity_index)
    }

    pub(crate) fn index_to_event_index(&mut self, index: usize, pos_type: PosType) -> usize {
        self.state.get_mut().index_to_event_index(index, pos_type)
    }

    pub(crate) fn event_index_to_unicode_index(&mut self, event_index: usize) -> usize {
        self.state
            .get_mut()
            .event_index_to_unicode_index(event_index)
    }
}

#[derive(Debug, Default, Clone)]
pub(crate) struct RichtextStateLoader {
    start_anchor_pos: FxHashMap<ID, usize>,
    elements: Vec<RichtextStateChunk>,
    style_ranges: Vec<(Arc<StyleOp>, Range<usize>)>,
    entity_index: usize,
}

impl From<RichtextStateLoader> for InnerState {
    fn from(value: RichtextStateLoader) -> Self {
        value.into_state()
    }
}

impl RichtextStateLoader {
    pub fn push(&mut self, elem: RichtextStateChunk) {
        if let RichtextStateChunk::Style { style, anchor_type } = &elem {
            if *anchor_type == AnchorType::Start {
                self.start_anchor_pos
                    .insert(ID::new(style.peer, style.cnt), self.entity_index);
            } else {
                let start_pos = self
                    .start_anchor_pos
                    .remove(&ID::new(style.peer, style.cnt))
                    .expect("Style start not found");

                // we need to + 1 because we also need to annotate the end anchor
                self.style_ranges
                    .push((style.clone(), start_pos..self.entity_index + 1));
            }
        }

        self.entity_index += elem.rle_len();
        self.elements.push(elem);
    }

    pub fn into_state(self) -> InnerState {
        let mut state = InnerState::from_chunks(self.elements.into_iter());
        for (style, range) in self.style_ranges {
            state.annotate_style_range(range, style);
        }

        if cfg!(debug_assertions) {
            state.check();
        }

        state
    }

    fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }
}

mod snapshot {
    use loro_common::{IdFull, InternalString, LoroValue, PeerID};
    use rustc_hash::FxHashMap;
    use serde_columnar::columnar;
    use std::{io::Read, sync::Arc};

    use crate::{
        container::richtext::{
            self, richtext_state::RichtextStateChunk, str_slice::StrSlice, StyleOp,
            TextStyleInfoFlag,
        },
        encoding::value_register::ValueRegister,
        state::{ContainerCreationContext, ContainerState, FastStateSnapshot},
        utils::lazy::LazyLoad,
    };

    use super::{RichtextState, RichtextStateLoader};

    #[columnar(vec, ser, de, iterable)]
    #[derive(Debug, Clone)]
    struct EncodedTextSpan {
        #[columnar(strategy = "DeltaRle")]
        peer_idx: usize,
        #[columnar(strategy = "DeltaRle")]
        counter: i32,
        #[columnar(strategy = "DeltaRle")]
        lamport_sub_counter: i32,
        /// positive for text
        /// 0 for mark start
        /// -1 for mark end
        #[columnar(strategy = "DeltaRle")]
        len: i32,
    }

    #[columnar(vec, ser, de, iterable)]
    #[derive(Debug, Clone)]
    struct EncodedMark {
        key_idx: usize,
        value: LoroValue,
        info: u8,
    }

    #[columnar(ser, de)]
    struct EncodedText {
        #[columnar(class = "vec", iter = "EncodedTextSpan")]
        spans: Vec<EncodedTextSpan>,
        keys: Vec<InternalString>,
        marks: Vec<EncodedMark>,
    }

    impl FastStateSnapshot for RichtextState {
        /// Encodes the RichtextState into a compact binary format for fast snapshot storage and retrieval.
        ///
        /// The encoding format consists of:
        /// 1. The full text content as a string, encoded using postcard serialization.
        /// 2. A series of EncodedTextSpan structs representing text chunks and style markers:
        ///    - peer_idx: Index of the peer ID in a value register (delta-RLE encoded)
        ///    - counter: Operation counter (delta-RLE encoded)
        ///    - lamport_sub_counter: Lamport timestamp - counter (delta-RLE encoded)
        ///    - len: Length of text chunk or marker type (-1 for end, 0 for start, positive for text)
        /// 3. A list of unique style keys as InternalString.
        /// 4. A series of EncodedMark structs for style information:
        ///    - key_idx: Index of the style key in the keys list
        ///    - value: The style value
        ///    - info: Additional style information as a byte
        fn encode_snapshot_fast<W: std::io::prelude::Write>(&mut self, mut w: W) {
            let value = self.get_value().into_string().unwrap();
            postcard::to_io(&*value, &mut w).unwrap();
            let mut spans = Vec::new();
            let mut marks = Vec::new();

            let mut peers: ValueRegister<PeerID> = ValueRegister::new();
            let iter: &mut dyn Iterator<Item = &RichtextStateChunk>;
            let mut a;
            let mut b;
            match &self.state {
                LazyLoad::Src(s) => {
                    a = Some(s.elements.iter());
                    iter = &mut *a.as_mut().unwrap();
                }
                LazyLoad::Dst(s) => {
                    b = Some(s.iter_chunk());
                    iter = &mut *b.as_mut().unwrap();
                }
            }

            let mut keys: ValueRegister<InternalString> = ValueRegister::new();

            for chunk in iter {
                match chunk {
                    RichtextStateChunk::Text(t) => {
                        let id = t.id_full();
                        assert!(t.unicode_len() > 0);
                        spans.push(EncodedTextSpan {
                            peer_idx: peers.register(&id.peer),
                            counter: id.counter,
                            lamport_sub_counter: id.lamport as i32 - id.counter,
                            len: t.unicode_len(),
                        })
                    }
                    RichtextStateChunk::Style { style, anchor_type } => match anchor_type {
                        richtext::AnchorType::Start => {
                            let id = style.id_full();
                            spans.push(EncodedTextSpan {
                                peer_idx: peers.register(&id.peer),
                                counter: id.counter,
                                lamport_sub_counter: id.lamport as i32 - id.counter,
                                len: 0,
                            });
                            marks.push(EncodedMark {
                                key_idx: keys.register(&style.key),
                                value: style.value.clone(),
                                info: style.info.to_byte(),
                            })
                        }
                        richtext::AnchorType::End => {
                            let id = style.id_full();
                            spans.push(EncodedTextSpan {
                                peer_idx: peers.register(&id.peer),
                                counter: id.counter + 1,
                                lamport_sub_counter: id.lamport as i32 - id.counter,
                                len: -1,
                            })
                        }
                    },
                }
            }

            let peers = peers.unwrap_vec();
            leb128::write::unsigned(&mut w, peers.len() as u64).unwrap();
            for peer in peers {
                w.write_all(&peer.to_le_bytes()).unwrap();
            }

            let bytes = serde_columnar::to_vec(&EncodedText {
                spans,
                keys: keys.unwrap_vec(),
                marks,
            })
            .unwrap();
            w.write_all(&bytes).unwrap();
        }

        fn decode_value(bytes: &[u8]) -> loro_common::LoroResult<(loro_common::LoroValue, &[u8])> {
            let (value, bytes) = postcard::take_from_bytes(bytes).map_err(|_| {
                loro_common::LoroError::DecodeError(
                    "Decode list value failed".to_string().into_boxed_str(),
                )
            })?;
            let s: String = value;
            Ok((LoroValue::String(s.into()), bytes))
        }

        fn decode_snapshot_fast(
            idx: crate::container::idx::ContainerIdx,
            (string, mut bytes): (loro_common::LoroValue, &[u8]),
            ctx: ContainerCreationContext,
        ) -> loro_common::LoroResult<Self>
        where
            Self: Sized,
        {
            let mut text = RichtextState::new(idx, ctx.configure.text_style_config.clone());
            let mut loader = RichtextStateLoader::default();
            let peer_num = leb128::read::unsigned(&mut bytes).unwrap() as usize;
            let mut peers = Vec::with_capacity(peer_num);
            for _ in 0..peer_num {
                let mut buf = [0u8; 8];
                bytes.read_exact(&mut buf).unwrap();
                peers.push(PeerID::from_le_bytes(buf));
            }

            let string = string.into_string().unwrap();
            let mut s = StrSlice::new_from_str(&string);
            let iters = serde_columnar::from_bytes::<EncodedText>(bytes).unwrap();
            let keys = iters.keys;
            let span_iter = iters.spans.into_iter();
            let mut mark_iter = iters.marks.into_iter();
            let mut id_to_style = FxHashMap::default();
            for span in span_iter {
                let EncodedTextSpan {
                    peer_idx,
                    counter,
                    lamport_sub_counter,
                    len,
                } = span;
                let id_full = IdFull::new(
                    peers[peer_idx],
                    counter,
                    (lamport_sub_counter + counter) as u32,
                );
                let chunk = match len {
                    0 => {
                        // Style Start
                        let EncodedMark {
                            key_idx,
                            value,
                            info,
                        } = mark_iter.next().unwrap();
                        let style_op = Arc::new(StyleOp {
                            lamport: (lamport_sub_counter + counter) as u32,
                            peer: id_full.peer,
                            cnt: id_full.counter,
                            key: keys[key_idx].clone(),
                            value,
                            info: TextStyleInfoFlag::from_byte(info),
                        });
                        id_to_style.insert(id_full.id(), style_op.clone());
                        RichtextStateChunk::new_style(style_op, richtext::AnchorType::Start)
                    }
                    -1 => {
                        // Style End
                        let style = id_to_style.remove(&id_full.id().inc(-1)).unwrap();
                        RichtextStateChunk::new_style(style, richtext::AnchorType::End)
                    }
                    len => {
                        // Text
                        let (new, rest) = s.split_at_unicode_pos(len as usize);
                        s = rest;
                        RichtextStateChunk::new_text(new.bytes().clone(), id_full)
                    }
                };

                loader.push(chunk);
            }
            text.state = LazyLoad::Src(loader);
            // NOTE: We need to ensure the invariance that the version id is always increased when the richtext state is changed
            // This is used to avoid the version_id to be the same as the previous zero version
            text.version_id = 1;
            Ok(text)
        }
    }
}