forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

handler.rs6099 lines, 213.5 KiBHistoryRawDownload
1use super::{state::DocState, txn::Transaction};
2use crate::sync::Mutex;
3use crate::{
4 container::{
5 idx::ContainerIdx,
6 list::list_op::{DeleteSpan, DeleteSpanWithId, ListOp},
7 richtext::{richtext_state::PosType, RichtextState, StyleKey, StyleOp, TextStyleInfoFlag},
8 },
9 cursor::{Cursor, Side},
10 delta::{DeltaItem, Meta, StyleMeta, TreeExternalDiff},
11 diff::{diff, diff_impl::UpdateTimeoutError, OperateProxy},
12 event::{Diff, TextDiff, TextDiffItem, TextMeta},
13 op::ListSlice,
14 state::{IndexType, State, TreeParentId},
15 txn::EventHint,
16 utils::{string_slice::StringSlice, utf16::count_utf16_len},
17 LoroDoc, LoroDocInner,
18};
19use append_only_bytes::BytesSlice;
20use enum_as_inner::EnumAsInner;
21use generic_btree::rle::HasLength;
22use loro_common::{
23 ContainerID, ContainerType, IdFull, InternalString, LoroError, LoroResult, LoroValue, PeerID,
24 TreeID, ID,
25};
26use rustc_hash::{FxHashMap, FxHashSet};
27use serde::{Deserialize, Serialize};
28use std::{borrow::Cow, fmt::Debug, ops::Deref, sync::Arc};
29use tracing::{error, instrument};
30
31pub use crate::diff::diff_impl::UpdateOptions;
32pub use tree::TreeHandler;
33mod full_state;
34mod movable_list_apply_delta;
35pub(crate) use full_state::align_full_state;
36mod tree;
37
38const REGULAR_CONTAINER_VALUE_ARG_ERROR: &str =
39 "Cannot use a LoroValue::Container as a regular value. To create a child container, use insert_container/set_container, or ensure_mergeable_* on maps for mergeable children";
40
41mod text_update;
42
43fn ensure_no_regular_container_value(value: &LoroValue) -> LoroResult<()> {
44 // Fast path: scalar values can never transitively hold a container, so we
45 // skip the heap allocation + traversal below. This is the common case on
46 // the per-op insert hot path (inserting numbers/strings/bools), where the
47 // previous unconditional `vec![value]` allocation showed up as a measurable
48 // regression.
49 if !matches!(
50 value,
51 LoroValue::Container(_) | LoroValue::List(_) | LoroValue::Map(_)
52 ) {
53 return Ok(());
54 }
55
56 let mut stack = vec![value];
57 while let Some(value) = stack.pop() {
58 match value {
59 LoroValue::Container(_) => {
60 return Err(LoroError::ArgErr(
61 REGULAR_CONTAINER_VALUE_ARG_ERROR
62 .to_string()
63 .into_boxed_str(),
64 ));
65 }
66 LoroValue::List(list) => {
67 stack.extend(list.iter());
68 }
69 LoroValue::Map(map) => {
70 stack.extend(map.values());
71 }
72 LoroValue::Null
73 | LoroValue::Bool(_)
74 | LoroValue::Double(_)
75 | LoroValue::I64(_)
76 | LoroValue::Binary(_)
77 | LoroValue::String(_) => {}
78 }
79 }
80
81 Ok(())
82}
83
84fn checked_range_end(
85 pos: usize,
86 len: usize,
87 container_len: usize,
88 // Lazily built: this is on the per-op edit hot path, so the position-context
89 // string must only be allocated when a bound check actually fails.
90 info: impl Fn() -> Box<str>,
91) -> LoroResult<usize> {
92 let end = pos.checked_add(len).ok_or_else(|| LoroError::OutOfBound {
93 pos: usize::MAX,
94 len: container_len,
95 info: info(),
96 })?;
97 if end > container_len {
98 return Err(LoroError::OutOfBound {
99 pos: end,
100 len: container_len,
101 info: info(),
102 });
103 }
104
105 Ok(end)
106}
107
108fn checked_delta_index_end(pos: usize, len: usize, container_len: usize) -> LoroResult<usize> {
109 pos.checked_add(len).ok_or_else(|| LoroError::OutOfBound {
110 pos: usize::MAX,
111 len: container_len,
112 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
113 })
114}
115
116pub trait HandlerTrait: Clone + Sized {
117 fn is_attached(&self) -> bool;
118 fn attached_handler(&self) -> Option<&BasicHandler>;
119 fn get_value(&self) -> LoroValue;
120 fn get_deep_value(&self) -> LoroValue;
121 fn kind(&self) -> ContainerType;
122 fn to_handler(&self) -> Handler;
123 fn from_handler(h: Handler) -> Option<Self>;
124 fn doc(&self) -> Option<LoroDoc>;
125 /// This method returns an attached handler.
126 fn attach(
127 &self,
128 txn: &mut Transaction,
129 parent: &BasicHandler,
130 self_id: ContainerID,
131 ) -> LoroResult<Self>;
132 /// If a detached container is attached, this method will return its corresponding attached handler.
133 fn get_attached(&self) -> Option<Self>;
134
135 fn parent(&self) -> Option<Handler> {
136 self.attached_handler().and_then(|x| x.parent())
137 }
138
139 fn idx(&self) -> ContainerIdx {
140 self.attached_handler()
141 .map(|x| x.container_idx)
142 .unwrap_or_else(|| {
143 ContainerIdx::from_index_and_type(ContainerIdx::INDEX_MASK, self.kind())
144 })
145 }
146
147 fn id(&self) -> ContainerID {
148 self.attached_handler()
149 .map(|x| x.id.clone())
150 .unwrap_or_else(|| ContainerID::new_normal(ID::NONE_ID, self.kind()))
151 }
152
153 fn with_state<R>(&self, f: impl FnOnce(&mut State) -> LoroResult<R>) -> LoroResult<R> {
154 let inner = self
155 .attached_handler()
156 .ok_or(LoroError::MisuseDetachedContainer {
157 method: "with_state",
158 })?;
159 let state = inner.doc.state.clone();
160 let mut guard = state.lock();
161 guard.with_state_mut(inner.container_idx, f)
162 }
163}
164
165fn create_handler(inner: &BasicHandler, id: ContainerID) -> Handler {
166 Handler::new_attached(id, inner.doc.clone())
167}
168
169fn value_to_value_or_handler(inner: &BasicHandler, value: LoroValue) -> ValueOrHandler {
170 match value {
171 LoroValue::Container(container_id) => {
172 ValueOrHandler::Handler(create_handler(inner, container_id))
173 }
174 value => ValueOrHandler::Value(value),
175 }
176}
177
178/// Reject inserting a container that is attached to another doc, either directly
179/// or nested inside a detached container, or a copy that would need to create an
180/// unknown container.
181///
182/// Attaching copies an attached container through its own doc, so a foreign
183/// child would mix the source doc's arena with the target doc's transaction.
184/// Callers must run this before applying any op so the target doc is untouched.
185fn ensure_not_attached_to_other_doc<H: HandlerTrait>(child: &H, doc: &LoroDoc) -> LoroResult<()> {
186 ensure_handler_not_attached_to_other_doc(&child.to_handler(), doc)
187}
188
189fn ensure_handler_not_attached_to_other_doc(handler: &Handler, doc: &LoroDoc) -> LoroResult<()> {
190 if let Some(a) = handler.attached_handler() {
191 if Arc::ptr_eq(&a.doc.inner, &doc.inner) {
192 // Attaching a container of the same doc copies it
193 return ensure_no_unknown_container_in_attached(handler);
194 }
195
196 return Err(LoroError::ArgErr(
197 "Cannot insert a container attached to another LoroDoc".into(),
198 ));
199 }
200
201 let check_values = |values: &mut dyn Iterator<Item = &ValueOrHandler>| {
202 for v in values {
203 if let ValueOrHandler::Handler(h) = v {
204 ensure_handler_not_attached_to_other_doc(h, doc)?;
205 }
206 }
207 Ok(())
208 };
209
210 match handler {
211 Handler::Map(m) => match &m.inner {
212 MaybeDetached::Detached(d) => check_values(&mut d.lock().value.values()),
213 MaybeDetached::Attached(_) => Ok(()),
214 },
215 Handler::List(l) => match &l.inner {
216 MaybeDetached::Detached(d) => check_values(&mut d.lock().value.iter()),
217 MaybeDetached::Attached(_) => Ok(()),
218 },
219 Handler::MovableList(l) => match &l.inner {
220 MaybeDetached::Detached(d) => check_values(&mut d.lock().value.iter()),
221 MaybeDetached::Attached(_) => Ok(()),
222 },
223 Handler::Tree(t) => {
224 for meta in t.detached_meta_maps() {
225 ensure_handler_not_attached_to_other_doc(&Handler::Map(meta), doc)?;
226 }
227 Ok(())
228 }
229 Handler::Text(_) | Handler::Unknown(_) => Ok(()),
230 #[cfg(feature = "counter")]
231 Handler::Counter(_) => Ok(()),
232 }
233}
234
235const UNKNOWN_CONTAINER_CREATION_ERR_SUFFIX: &str = ": the type is unknown to this version of Loro";
236
237/// The error for operations that would create a container of a type this
238/// version doesn't know ([ContainerType::Unknown], written by a newer Loro).
239pub(crate) fn unknown_container_creation_err(kind: ContainerType) -> LoroError {
240 LoroError::ArgErr(
241 format!("Cannot create a container of type {kind}{UNKNOWN_CONTAINER_CREATION_ERR_SUFFIX}")
242 .into_boxed_str(),
243 )
244}
245
246/// Whether `e` is [`unknown_container_creation_err`].
247pub(crate) fn is_unknown_container_creation_err(e: &LoroError) -> bool {
248 matches!(e, LoroError::ArgErr(msg) if msg.ends_with(UNKNOWN_CONTAINER_CREATION_ERR_SUFFIX))
249}
250
251/// Attaching an attached container copies its content, which is impossible for
252/// a container whose type this version doesn't know (created by a newer Loro).
253fn ensure_no_unknown_container_in_attached(handler: &Handler) -> LoroResult<()> {
254 let check_children = |value: LoroValue| -> LoroResult<()> {
255 let children: Vec<ContainerID> = match value {
256 LoroValue::Map(m) => m
257 .values()
258 .filter_map(|v| v.as_container().cloned())
259 .collect(),
260 LoroValue::List(l) => l.iter().filter_map(|v| v.as_container().cloned()).collect(),
261 _ => Vec::new(),
262 };
263 let Some(doc) = handler.attached_handler().map(|a| a.doc()) else {
264 return Ok(());
265 };
266 for id in children {
267 ensure_no_unknown_container_in_attached(&Handler::new_attached(id, doc.clone()))?;
268 }
269 Ok(())
270 };
271
272 match handler {
273 Handler::Unknown(u) => Err(unknown_container_creation_err(u.kind())),
274 Handler::Map(m) => check_children(m.get_value()),
275 Handler::List(l) => check_children(l.get_value()),
276 Handler::MovableList(l) => check_children(l.get_value()),
277 Handler::Tree(t) => {
278 let mut pending = t.get_all_hierarchy_nodes_under(TreeParentId::Root);
279 pending.reverse();
280 while let Some(mut node) = pending.pop() {
281 ensure_no_unknown_container_in_attached(&Handler::Map(t.get_meta(node.id)?))?;
282 pending.extend(std::mem::take(&mut node.children).into_iter().rev());
283 }
284 Ok(())
285 }
286 Handler::Text(_) => Ok(()),
287 #[cfg(feature = "counter")]
288 Handler::Counter(_) => Ok(()),
289 }
290}
291
292/// Flatten attributes that allow overlap
293#[derive(Clone, Debug)]
294pub struct BasicHandler {
295 id: ContainerID,
296 container_idx: ContainerIdx,
297 doc: LoroDoc,
298}
299
300struct DetachedInner<T> {
301 value: T,
302 /// If the handler attached later, this field will be filled.
303 attached: Option<BasicHandler>,
304}
305
306impl<T> DetachedInner<T> {
307 fn new(v: T) -> Self {
308 Self {
309 value: v,
310 attached: None,
311 }
312 }
313}
314
315enum MaybeDetached<T> {
316 Detached(Arc<Mutex<DetachedInner<T>>>),
317 Attached(BasicHandler),
318}
319
320impl<T> Clone for MaybeDetached<T> {
321 fn clone(&self) -> Self {
322 match self {
323 MaybeDetached::Detached(a) => MaybeDetached::Detached(Arc::clone(a)),
324 MaybeDetached::Attached(a) => MaybeDetached::Attached(a.clone()),
325 }
326 }
327}
328
329impl<T> MaybeDetached<T> {
330 fn new_detached(v: T) -> Self {
331 MaybeDetached::Detached(Arc::new(Mutex::new(DetachedInner::new(v))))
332 }
333
334 fn is_attached(&self) -> bool {
335 match self {
336 MaybeDetached::Detached(_) => false,
337 MaybeDetached::Attached(_) => true,
338 }
339 }
340
341 fn attached_handler(&self) -> Option<&BasicHandler> {
342 match self {
343 MaybeDetached::Detached(_) => None,
344 MaybeDetached::Attached(a) => Some(a),
345 }
346 }
347
348 fn try_attached_state(&self) -> LoroResult<&BasicHandler> {
349 match self {
350 MaybeDetached::Detached(_) => Err(LoroError::MisuseDetachedContainer {
351 method: "inner_state",
352 }),
353 MaybeDetached::Attached(a) => Ok(a),
354 }
355 }
356}
357
358impl<T> From<BasicHandler> for MaybeDetached<T> {
359 fn from(a: BasicHandler) -> Self {
360 MaybeDetached::Attached(a)
361 }
362}
363
364impl BasicHandler {
365 pub(crate) fn doc(&self) -> LoroDoc {
366 self.doc.clone()
367 }
368
369 #[inline]
370 fn with_doc_state<R>(&self, f: impl FnOnce(&mut DocState) -> R) -> R {
371 let state = self.doc.state.clone();
372 let mut guard = state.lock();
373 f(&mut guard)
374 }
375
376 fn with_txn<R>(
377 &self,
378 f: impl FnOnce(&mut Transaction) -> Result<R, LoroError>,
379 ) -> Result<R, LoroError> {
380 with_txn(&self.doc, f)
381 }
382
383 fn get_parent(&self) -> Option<Handler> {
384 let parent_idx = self.doc.arena.get_parent(self.container_idx)?;
385 let parent_id = self.doc.arena.get_container_id(parent_idx).unwrap();
386 {
387 let kind = parent_id.container_type();
388 let handler = BasicHandler {
389 container_idx: parent_idx,
390 id: parent_id,
391 doc: self.doc.clone(),
392 };
393
394 Some(match kind {
395 ContainerType::Map => Handler::Map(MapHandler {
396 inner: handler.into(),
397 }),
398 ContainerType::List => Handler::List(ListHandler {
399 inner: handler.into(),
400 }),
401 ContainerType::Tree => Handler::Tree(TreeHandler {
402 inner: handler.into(),
403 }),
404 ContainerType::Text => Handler::Text(TextHandler {
405 inner: handler.into(),
406 }),
407 ContainerType::MovableList => Handler::MovableList(MovableListHandler {
408 inner: handler.into(),
409 }),
410 #[cfg(feature = "counter")]
411 ContainerType::Counter => Handler::Counter(counter::CounterHandler {
412 inner: handler.into(),
413 }),
414 // Snapshots from a newer Loro may store children of an unknown container
415 ContainerType::Unknown(_) => Handler::Unknown(UnknownHandler { inner: handler }),
416 })
417 }
418 }
419
420 pub fn get_value(&self) -> LoroValue {
421 self.doc.state.lock().get_value_by_idx(self.container_idx)
422 }
423
424 pub fn get_deep_value(&self) -> LoroValue {
425 self.doc
426 .state
427 .lock()
428 .get_container_deep_value(self.container_idx)
429 }
430
431 fn with_state<R>(&self, f: impl FnOnce(&mut State) -> R) -> R {
432 let mut guard = self.doc.state.lock();
433 guard.with_state_mut(self.container_idx, f)
434 }
435
436 pub fn parent(&self) -> Option<Handler> {
437 self.get_parent()
438 }
439
440 fn is_deleted(&self) -> bool {
441 self.doc.state.lock().is_deleted(self.container_idx)
442 }
443
444 fn has_decoded_state(&self) -> bool {
445 self.with_doc_state(|state| state.has_decoded_container_state(self.container_idx))
446 }
447}
448
449/// Flatten attributes that allow overlap
450#[derive(Clone)]
451pub struct TextHandler {
452 inner: MaybeDetached<RichtextState>,
453}
454
455impl HandlerTrait for TextHandler {
456 fn to_handler(&self) -> Handler {
457 Handler::Text(self.clone())
458 }
459
460 fn attach(
461 &self,
462 txn: &mut Transaction,
463 parent: &BasicHandler,
464 self_id: ContainerID,
465 ) -> LoroResult<Self> {
466 match &self.inner {
467 MaybeDetached::Detached(t) => {
468 let mut t = t.lock();
469 let inner = create_handler(parent, self_id);
470 let text = inner.into_text().unwrap();
471 let mut delta: Vec<TextDelta> = Vec::new();
472 for span in t.value.iter() {
473 delta.push(TextDelta::Insert {
474 insert: span.text.to_string(),
475 attributes: span.attributes.to_option_map(),
476 });
477 }
478
479 text.apply_delta_with_txn(txn, &delta)?;
480 t.attached = text.attached_handler().cloned();
481 Ok(text)
482 }
483 MaybeDetached::Attached(a) => {
484 let new_inner = create_handler(a, self_id);
485 let ans = new_inner.into_text().unwrap();
486
487 let delta = self.get_delta();
488 ans.apply_delta_with_txn(txn, &delta)?;
489 Ok(ans)
490 }
491 }
492 }
493
494 fn attached_handler(&self) -> Option<&BasicHandler> {
495 self.inner.attached_handler()
496 }
497
498 fn get_value(&self) -> LoroValue {
499 match &self.inner {
500 MaybeDetached::Detached(t) => {
501 let t = t.lock();
502 LoroValue::String((t.value.to_string()).into())
503 }
504 MaybeDetached::Attached(a) => a.get_value(),
505 }
506 }
507
508 fn get_deep_value(&self) -> LoroValue {
509 self.get_value()
510 }
511
512 fn is_attached(&self) -> bool {
513 matches!(&self.inner, MaybeDetached::Attached(..))
514 }
515
516 fn kind(&self) -> ContainerType {
517 ContainerType::Text
518 }
519
520 fn get_attached(&self) -> Option<Self> {
521 match &self.inner {
522 MaybeDetached::Detached(d) => d.lock().attached.clone().map(|x| Self {
523 inner: MaybeDetached::Attached(x),
524 }),
525 MaybeDetached::Attached(_a) => Some(self.clone()),
526 }
527 }
528
529 fn from_handler(h: Handler) -> Option<Self> {
530 match h {
531 Handler::Text(x) => Some(x),
532 _ => None,
533 }
534 }
535
536 fn doc(&self) -> Option<LoroDoc> {
537 match &self.inner {
538 MaybeDetached::Detached(_) => None,
539 MaybeDetached::Attached(a) => Some(a.doc()),
540 }
541 }
542}
543
544impl std::fmt::Debug for TextHandler {
545 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
546 match &self.inner {
547 MaybeDetached::Detached(_) => {
548 write!(f, "TextHandler(Unattached)")
549 }
550 MaybeDetached::Attached(a) => {
551 write!(f, "TextHandler({:?})", &a.id)
552 }
553 }
554 }
555}
556
557#[derive(Debug, Clone, EnumAsInner, Deserialize, Serialize, PartialEq)]
558#[serde(untagged)]
559pub enum TextDelta {
560 Retain {
561 retain: usize,
562 attributes: Option<FxHashMap<String, LoroValue>>,
563 },
564 Insert {
565 insert: String,
566 attributes: Option<FxHashMap<String, LoroValue>>,
567 },
568 Delete {
569 delete: usize,
570 },
571}
572
573impl TextDelta {
574 pub fn from_text_diff<'a>(diff: impl Iterator<Item = &'a TextDiffItem>) -> Vec<TextDelta> {
575 let mut ans = Vec::with_capacity(diff.size_hint().0);
576 for iter in diff {
577 match iter {
578 loro_delta::DeltaItem::Retain { len, attr } => {
579 ans.push(TextDelta::Retain {
580 retain: *len,
581 attributes: if attr.0.is_empty() {
582 None
583 } else {
584 Some(attr.0.clone())
585 },
586 });
587 }
588 loro_delta::DeltaItem::Replace {
589 value,
590 attr,
591 delete,
592 } => {
593 if value.rle_len() > 0 {
594 ans.push(TextDelta::Insert {
595 insert: value.to_string(),
596 attributes: if attr.0.is_empty() {
597 None
598 } else {
599 Some(attr.0.clone())
600 },
601 });
602 }
603 if *delete > 0 {
604 ans.push(TextDelta::Delete { delete: *delete });
605 }
606 }
607 }
608 }
609
610 ans
611 }
612
613 pub fn into_text_diff(vec: impl Iterator<Item = Self>) -> TextDiff {
614 let mut delta = TextDiff::new();
615 for item in vec {
616 match item {
617 TextDelta::Retain { retain, attributes } => {
618 delta.push_retain(retain, TextMeta(attributes.unwrap_or_default().clone()));
619 }
620 TextDelta::Insert { insert, attributes } => {
621 delta.push_insert(
622 StringSlice::from(insert.as_str()),
623 TextMeta(attributes.unwrap_or_default()),
624 );
625 }
626 TextDelta::Delete { delete } => {
627 delta.push_delete(delete);
628 }
629 }
630 }
631
632 delta
633 }
634}
635
636impl From<&DeltaItem<StringSlice, StyleMeta>> for TextDelta {
637 fn from(value: &DeltaItem<StringSlice, StyleMeta>) -> Self {
638 match value {
639 crate::delta::DeltaItem::Retain { retain, attributes } => TextDelta::Retain {
640 retain: *retain,
641 attributes: attributes.to_option_map(),
642 },
643 crate::delta::DeltaItem::Insert { insert, attributes } => TextDelta::Insert {
644 insert: insert.to_string(),
645 attributes: attributes.to_option_map(),
646 },
647 crate::delta::DeltaItem::Delete {
648 delete,
649 attributes: _,
650 } => TextDelta::Delete { delete: *delete },
651 }
652 }
653}
654
655#[derive(Clone)]
656pub struct MapHandler {
657 inner: MaybeDetached<FxHashMap<String, ValueOrHandler>>,
658}
659
660impl HandlerTrait for MapHandler {
661 fn is_attached(&self) -> bool {
662 matches!(&self.inner, MaybeDetached::Attached(..))
663 }
664
665 fn attached_handler(&self) -> Option<&BasicHandler> {
666 match &self.inner {
667 MaybeDetached::Detached(_) => None,
668 MaybeDetached::Attached(a) => Some(a),
669 }
670 }
671
672 fn get_value(&self) -> LoroValue {
673 match &self.inner {
674 MaybeDetached::Detached(m) => {
675 let m = m.lock();
676 let mut map = FxHashMap::default();
677 for (k, v) in m.value.iter() {
678 map.insert(k.to_string(), v.to_value());
679 }
680 LoroValue::Map(map.into())
681 }
682 MaybeDetached::Attached(a) => a.get_value(),
683 }
684 }
685
686 fn get_deep_value(&self) -> LoroValue {
687 match &self.inner {
688 MaybeDetached::Detached(m) => {
689 let m = m.lock();
690 let mut map = FxHashMap::default();
691 for (k, v) in m.value.iter() {
692 map.insert(k.to_string(), v.to_deep_value());
693 }
694 LoroValue::Map(map.into())
695 }
696 MaybeDetached::Attached(a) => a.get_deep_value(),
697 }
698 }
699
700 fn kind(&self) -> ContainerType {
701 ContainerType::Map
702 }
703
704 fn to_handler(&self) -> Handler {
705 Handler::Map(self.clone())
706 }
707
708 fn attach(
709 &self,
710 txn: &mut Transaction,
711 parent: &BasicHandler,
712 self_id: ContainerID,
713 ) -> LoroResult<Self> {
714 match &self.inner {
715 MaybeDetached::Detached(m) => {
716 let mut m = m.lock();
717 let inner = create_handler(parent, self_id);
718 let map = inner.into_map().unwrap();
719 for (k, v) in m.value.iter() {
720 match v {
721 ValueOrHandler::Value(v) => {
722 map.insert_with_txn(txn, k, v.clone())?;
723 }
724 ValueOrHandler::Handler(h) => {
725 map.insert_container_with_txn(txn, k, h.clone())?;
726 }
727 }
728 }
729 m.attached = map.attached_handler().cloned();
730 Ok(map)
731 }
732 MaybeDetached::Attached(a) => {
733 let new_inner = create_handler(a, self_id);
734 let ans = new_inner.into_map().unwrap();
735
736 for (k, v) in self.get_value().into_map().unwrap().iter() {
737 if let LoroValue::Container(id) = v {
738 ans.insert_container_with_txn(txn, k, create_handler(a, id.clone()))?;
739 } else {
740 ans.insert_with_txn(txn, k, v.clone())?;
741 }
742 }
743
744 Ok(ans)
745 }
746 }
747 }
748
749 fn get_attached(&self) -> Option<Self> {
750 match &self.inner {
751 MaybeDetached::Detached(d) => d.lock().attached.clone().map(|x| Self {
752 inner: MaybeDetached::Attached(x),
753 }),
754 MaybeDetached::Attached(_a) => Some(self.clone()),
755 }
756 }
757
758 fn from_handler(h: Handler) -> Option<Self> {
759 match h {
760 Handler::Map(x) => Some(x),
761 _ => None,
762 }
763 }
764
765 fn doc(&self) -> Option<LoroDoc> {
766 match &self.inner {
767 MaybeDetached::Detached(_) => None,
768 MaybeDetached::Attached(a) => Some(a.doc()),
769 }
770 }
771}
772
773impl std::fmt::Debug for MapHandler {
774 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
775 match &self.inner {
776 MaybeDetached::Detached(_) => write!(f, "MapHandler Detached"),
777 MaybeDetached::Attached(a) => write!(f, "MapHandler {}", a.id),
778 }
779 }
780}
781
782#[derive(Clone)]
783pub struct ListHandler {
784 inner: MaybeDetached<Vec<ValueOrHandler>>,
785}
786
787#[derive(Clone)]
788pub struct MovableListHandler {
789 inner: MaybeDetached<Vec<ValueOrHandler>>,
790}
791
792impl HandlerTrait for MovableListHandler {
793 fn is_attached(&self) -> bool {
794 matches!(&self.inner, MaybeDetached::Attached(..))
795 }
796
797 fn attached_handler(&self) -> Option<&BasicHandler> {
798 match &self.inner {
799 MaybeDetached::Detached(_) => None,
800 MaybeDetached::Attached(a) => Some(a),
801 }
802 }
803
804 fn get_value(&self) -> LoroValue {
805 match &self.inner {
806 MaybeDetached::Detached(a) => {
807 let a = a.lock();
808 LoroValue::List(a.value.iter().map(|v| v.to_value()).collect())
809 }
810 MaybeDetached::Attached(a) => a.get_value(),
811 }
812 }
813
814 fn get_deep_value(&self) -> LoroValue {
815 match &self.inner {
816 MaybeDetached::Detached(a) => {
817 let a = a.lock();
818 LoroValue::List(a.value.iter().map(|v| v.to_deep_value()).collect())
819 }
820 MaybeDetached::Attached(a) => a.get_deep_value(),
821 }
822 }
823
824 fn kind(&self) -> ContainerType {
825 ContainerType::MovableList
826 }
827
828 fn to_handler(&self) -> Handler {
829 Handler::MovableList(self.clone())
830 }
831
832 fn from_handler(h: Handler) -> Option<Self> {
833 match h {
834 Handler::MovableList(x) => Some(x),
835 _ => None,
836 }
837 }
838
839 fn attach(
840 &self,
841 txn: &mut Transaction,
842 parent: &BasicHandler,
843 self_id: ContainerID,
844 ) -> LoroResult<Self> {
845 match &self.inner {
846 MaybeDetached::Detached(l) => {
847 let mut l = l.lock();
848 let inner = create_handler(parent, self_id);
849 let list = inner.into_movable_list().unwrap();
850 for (index, v) in l.value.iter().enumerate() {
851 match v {
852 ValueOrHandler::Value(v) => {
853 list.insert_with_txn(txn, index, v.clone())?;
854 }
855 ValueOrHandler::Handler(h) => {
856 list.insert_container_with_txn(txn, index, h.clone())?;
857 }
858 }
859 }
860 l.attached = list.attached_handler().cloned();
861 Ok(list)
862 }
863 MaybeDetached::Attached(a) => {
864 let new_inner = create_handler(a, self_id);
865 let ans = new_inner.into_movable_list().unwrap();
866
867 for (i, v) in self.get_value().into_list().unwrap().iter().enumerate() {
868 if let LoroValue::Container(id) = v {
869 ans.insert_container_with_txn(txn, i, create_handler(a, id.clone()))?;
870 } else {
871 ans.insert_with_txn(txn, i, v.clone())?;
872 }
873 }
874
875 Ok(ans)
876 }
877 }
878 }
879
880 fn get_attached(&self) -> Option<Self> {
881 match &self.inner {
882 MaybeDetached::Detached(d) => d.lock().attached.clone().map(|x| Self {
883 inner: MaybeDetached::Attached(x),
884 }),
885 MaybeDetached::Attached(_a) => Some(self.clone()),
886 }
887 }
888
889 fn doc(&self) -> Option<LoroDoc> {
890 match &self.inner {
891 MaybeDetached::Detached(_) => None,
892 MaybeDetached::Attached(a) => Some(a.doc()),
893 }
894 }
895}
896
897impl std::fmt::Debug for MovableListHandler {
898 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
899 write!(f, "MovableListHandler {}", self.id())
900 }
901}
902
903impl std::fmt::Debug for ListHandler {
904 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
905 match &self.inner {
906 MaybeDetached::Detached(_) => write!(f, "ListHandler Detached"),
907 MaybeDetached::Attached(a) => write!(f, "ListHandler {}", a.id),
908 }
909 }
910}
911
912impl HandlerTrait for ListHandler {
913 fn is_attached(&self) -> bool {
914 self.inner.is_attached()
915 }
916
917 fn attached_handler(&self) -> Option<&BasicHandler> {
918 self.inner.attached_handler()
919 }
920
921 fn get_value(&self) -> LoroValue {
922 match &self.inner {
923 MaybeDetached::Detached(a) => {
924 let a = a.lock();
925 LoroValue::List(a.value.iter().map(|v| v.to_value()).collect())
926 }
927 MaybeDetached::Attached(a) => a.get_value(),
928 }
929 }
930
931 fn get_deep_value(&self) -> LoroValue {
932 match &self.inner {
933 MaybeDetached::Detached(a) => {
934 let a = a.lock();
935 LoroValue::List(a.value.iter().map(|v| v.to_deep_value()).collect())
936 }
937 MaybeDetached::Attached(a) => a.get_deep_value(),
938 }
939 }
940
941 fn kind(&self) -> ContainerType {
942 ContainerType::List
943 }
944
945 fn to_handler(&self) -> Handler {
946 Handler::List(self.clone())
947 }
948
949 fn attach(
950 &self,
951 txn: &mut Transaction,
952 parent: &BasicHandler,
953 self_id: ContainerID,
954 ) -> LoroResult<Self> {
955 match &self.inner {
956 MaybeDetached::Detached(l) => {
957 let mut l = l.lock();
958 let inner = create_handler(parent, self_id);
959 let list = inner.into_list().unwrap();
960 for (index, v) in l.value.iter().enumerate() {
961 match v {
962 ValueOrHandler::Value(v) => {
963 list.insert_with_txn(txn, index, v.clone())?;
964 }
965 ValueOrHandler::Handler(h) => {
966 list.insert_container_with_txn(txn, index, h.clone())?;
967 }
968 }
969 }
970 l.attached = list.attached_handler().cloned();
971 Ok(list)
972 }
973 MaybeDetached::Attached(a) => {
974 let new_inner = create_handler(a, self_id);
975 let ans = new_inner.into_list().unwrap();
976
977 for (i, v) in self.get_value().into_list().unwrap().iter().enumerate() {
978 if let LoroValue::Container(id) = v {
979 ans.insert_container_with_txn(txn, i, create_handler(a, id.clone()))?;
980 } else {
981 ans.insert_with_txn(txn, i, v.clone())?;
982 }
983 }
984
985 Ok(ans)
986 }
987 }
988 }
989
990 fn get_attached(&self) -> Option<Self> {
991 match &self.inner {
992 MaybeDetached::Detached(d) => d.lock().attached.clone().map(|x| Self {
993 inner: MaybeDetached::Attached(x),
994 }),
995 MaybeDetached::Attached(_a) => Some(self.clone()),
996 }
997 }
998
999 fn from_handler(h: Handler) -> Option<Self> {
1000 match h {
1001 Handler::List(x) => Some(x),
1002 _ => None,
1003 }
1004 }
1005
1006 fn doc(&self) -> Option<LoroDoc> {
1007 match &self.inner {
1008 MaybeDetached::Detached(_) => None,
1009 MaybeDetached::Attached(a) => Some(a.doc()),
1010 }
1011 }
1012}
1013
1014#[derive(Clone)]
1015pub struct UnknownHandler {
1016 inner: BasicHandler,
1017}
1018
1019impl Debug for UnknownHandler {
1020 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1021 write!(f, "UnknownHandler")
1022 }
1023}
1024
1025impl UnknownHandler {
1026 pub fn is_deleted(&self) -> bool {
1027 self.inner.is_deleted()
1028 }
1029}
1030
1031impl HandlerTrait for UnknownHandler {
1032 fn is_attached(&self) -> bool {
1033 true
1034 }
1035
1036 fn attached_handler(&self) -> Option<&BasicHandler> {
1037 Some(&self.inner)
1038 }
1039
1040 fn get_value(&self) -> LoroValue {
1041 // The payload of an unknown container is opaque to this version of
1042 // Loro; expose it as `Null`, matching the public API convention in
1043 // `ValueOrContainer::get_deep_value` (crates/loro/src/lib.rs).
1044 LoroValue::Null
1045 }
1046
1047 fn get_deep_value(&self) -> LoroValue {
1048 LoroValue::Null
1049 }
1050
1051 fn kind(&self) -> ContainerType {
1052 self.inner.id.container_type()
1053 }
1054
1055 fn to_handler(&self) -> Handler {
1056 Handler::Unknown(self.clone())
1057 }
1058
1059 fn from_handler(h: Handler) -> Option<Self> {
1060 match h {
1061 Handler::Unknown(x) => Some(x),
1062 _ => None,
1063 }
1064 }
1065
1066 fn attach(
1067 &self,
1068 _txn: &mut Transaction,
1069 _parent: &BasicHandler,
1070 self_id: ContainerID,
1071 ) -> LoroResult<Self> {
1072 let new_inner = create_handler(&self.inner, self_id);
1073 let ans = new_inner.into_unknown().unwrap();
1074 Ok(ans)
1075 }
1076
1077 fn get_attached(&self) -> Option<Self> {
1078 Some(self.clone())
1079 }
1080
1081 fn doc(&self) -> Option<LoroDoc> {
1082 Some(self.inner.doc())
1083 }
1084}
1085
1086#[derive(Clone, EnumAsInner, Debug)]
1087pub enum Handler {
1088 Text(TextHandler),
1089 Map(MapHandler),
1090 List(ListHandler),
1091 MovableList(MovableListHandler),
1092 Tree(TreeHandler),
1093 #[cfg(feature = "counter")]
1094 Counter(counter::CounterHandler),
1095 Unknown(UnknownHandler),
1096}
1097
1098impl HandlerTrait for Handler {
1099 fn is_attached(&self) -> bool {
1100 match self {
1101 Self::Text(x) => x.is_attached(),
1102 Self::Map(x) => x.is_attached(),
1103 Self::List(x) => x.is_attached(),
1104 Self::Tree(x) => x.is_attached(),
1105 Self::MovableList(x) => x.is_attached(),
1106 #[cfg(feature = "counter")]
1107 Self::Counter(x) => x.is_attached(),
1108 Self::Unknown(x) => x.is_attached(),
1109 }
1110 }
1111
1112 fn attached_handler(&self) -> Option<&BasicHandler> {
1113 match self {
1114 Self::Text(x) => x.attached_handler(),
1115 Self::Map(x) => x.attached_handler(),
1116 Self::List(x) => x.attached_handler(),
1117 Self::MovableList(x) => x.attached_handler(),
1118 Self::Tree(x) => x.attached_handler(),
1119 #[cfg(feature = "counter")]
1120 Self::Counter(x) => x.attached_handler(),
1121 Self::Unknown(x) => x.attached_handler(),
1122 }
1123 }
1124
1125 fn get_value(&self) -> LoroValue {
1126 match self {
1127 Self::Text(x) => x.get_value(),
1128 Self::Map(x) => x.get_value(),
1129 Self::List(x) => x.get_value(),
1130 Self::MovableList(x) => x.get_value(),
1131 Self::Tree(x) => x.get_value(),
1132 #[cfg(feature = "counter")]
1133 Self::Counter(x) => x.get_value(),
1134 Self::Unknown(x) => x.get_value(),
1135 }
1136 }
1137
1138 fn get_deep_value(&self) -> LoroValue {
1139 match self {
1140 Self::Text(x) => x.get_deep_value(),
1141 Self::Map(x) => x.get_deep_value(),
1142 Self::List(x) => x.get_deep_value(),
1143 Self::MovableList(x) => x.get_deep_value(),
1144 Self::Tree(x) => x.get_deep_value(),
1145 #[cfg(feature = "counter")]
1146 Self::Counter(x) => x.get_deep_value(),
1147 Self::Unknown(x) => x.get_deep_value(),
1148 }
1149 }
1150
1151 fn kind(&self) -> ContainerType {
1152 match self {
1153 Self::Text(x) => x.kind(),
1154 Self::Map(x) => x.kind(),
1155 Self::List(x) => x.kind(),
1156 Self::MovableList(x) => x.kind(),
1157 Self::Tree(x) => x.kind(),
1158 #[cfg(feature = "counter")]
1159 Self::Counter(x) => x.kind(),
1160 Self::Unknown(x) => x.kind(),
1161 }
1162 }
1163
1164 fn to_handler(&self) -> Handler {
1165 match self {
1166 Self::Text(x) => x.to_handler(),
1167 Self::Map(x) => x.to_handler(),
1168 Self::List(x) => x.to_handler(),
1169 Self::MovableList(x) => x.to_handler(),
1170 Self::Tree(x) => x.to_handler(),
1171 #[cfg(feature = "counter")]
1172 Self::Counter(x) => x.to_handler(),
1173 Self::Unknown(x) => x.to_handler(),
1174 }
1175 }
1176
1177 fn attach(
1178 &self,
1179 txn: &mut Transaction,
1180 parent: &BasicHandler,
1181 self_id: ContainerID,
1182 ) -> LoroResult<Self> {
1183 match self {
1184 Self::Text(x) => Ok(Handler::Text(x.attach(txn, parent, self_id)?)),
1185 Self::Map(x) => Ok(Handler::Map(x.attach(txn, parent, self_id)?)),
1186 Self::List(x) => Ok(Handler::List(x.attach(txn, parent, self_id)?)),
1187 Self::MovableList(x) => Ok(Handler::MovableList(x.attach(txn, parent, self_id)?)),
1188 Self::Tree(x) => Ok(Handler::Tree(x.attach(txn, parent, self_id)?)),
1189 #[cfg(feature = "counter")]
1190 Self::Counter(x) => Ok(Handler::Counter(x.attach(txn, parent, self_id)?)),
1191 Self::Unknown(x) => Ok(Handler::Unknown(x.attach(txn, parent, self_id)?)),
1192 }
1193 }
1194
1195 fn get_attached(&self) -> Option<Self> {
1196 match self {
1197 Self::Text(x) => x.get_attached().map(Handler::Text),
1198 Self::Map(x) => x.get_attached().map(Handler::Map),
1199 Self::List(x) => x.get_attached().map(Handler::List),
1200 Self::MovableList(x) => x.get_attached().map(Handler::MovableList),
1201 Self::Tree(x) => x.get_attached().map(Handler::Tree),
1202 #[cfg(feature = "counter")]
1203 Self::Counter(x) => x.get_attached().map(Handler::Counter),
1204 Self::Unknown(x) => x.get_attached().map(Handler::Unknown),
1205 }
1206 }
1207
1208 fn from_handler(h: Handler) -> Option<Self> {
1209 Some(h)
1210 }
1211
1212 fn doc(&self) -> Option<LoroDoc> {
1213 match self {
1214 Self::Text(x) => x.doc(),
1215 Self::Map(x) => x.doc(),
1216 Self::List(x) => x.doc(),
1217 Self::MovableList(x) => x.doc(),
1218 Self::Tree(x) => x.doc(),
1219 #[cfg(feature = "counter")]
1220 Self::Counter(x) => x.doc(),
1221 Self::Unknown(x) => x.doc(),
1222 }
1223 }
1224}
1225
1226impl Handler {
1227 fn apply_map_container_diff_value(
1228 map: &MapHandler,
1229 key: &str,
1230 old_id: ContainerID,
1231 on_container_remap: &mut dyn FnMut(ContainerID, ContainerID),
1232 full_state_targets: &mut FxHashSet<ContainerID>,
1233 ) -> LoroResult<()> {
1234 if old_id.is_mergeable() {
1235 let parent_id = map.id();
1236 let kind = old_id.container_type();
1237 let new_id = ContainerID::new_mergeable(&parent_id, key, kind);
1238 let marker = loro_common::mergeable_marker(&parent_id, key, kind);
1239 map.insert_without_skipping(key, marker)?;
1240 // The deterministic cid may still hold hidden state, while the child's diff in
1241 // this batch is its full target state. Reconcile instead of appending.
1242 full_state_targets.insert(new_id.clone());
1243 on_container_remap(old_id, new_id);
1244 return Ok(());
1245 }
1246
1247 let new_h = map.insert_container(key, Handler::new_unattached(old_id.container_type())?)?;
1248 let new_id = new_h.id();
1249 on_container_remap(old_id, new_id);
1250 Ok(())
1251 }
1252
1253 pub(crate) fn new_attached(id: ContainerID, doc: LoroDoc) -> Self {
1254 let kind = id.container_type();
1255 let handler = BasicHandler {
1256 container_idx: doc.arena.register_container(&id),
1257 id,
1258 doc,
1259 };
1260
1261 match kind {
1262 ContainerType::Map => Self::Map(MapHandler {
1263 inner: handler.into(),
1264 }),
1265 ContainerType::List => Self::List(ListHandler {
1266 inner: handler.into(),
1267 }),
1268 ContainerType::Tree => Self::Tree(TreeHandler {
1269 inner: handler.into(),
1270 }),
1271 ContainerType::Text => Self::Text(TextHandler {
1272 inner: handler.into(),
1273 }),
1274 ContainerType::MovableList => Self::MovableList(MovableListHandler {
1275 inner: handler.into(),
1276 }),
1277 #[cfg(feature = "counter")]
1278 ContainerType::Counter => Self::Counter(counter::CounterHandler {
1279 inner: handler.into(),
1280 }),
1281 ContainerType::Unknown(_) => Self::Unknown(UnknownHandler { inner: handler }),
1282 }
1283 }
1284
1285 /// Errors on [ContainerType::Unknown]: this version cannot create a
1286 /// container of a type it doesn't know.
1287 pub(crate) fn new_unattached(kind: ContainerType) -> LoroResult<Self> {
1288 Ok(match kind {
1289 ContainerType::Text => Self::Text(TextHandler::new_detached()),
1290 ContainerType::Map => Self::Map(MapHandler::new_detached()),
1291 ContainerType::List => Self::List(ListHandler::new_detached()),
1292 ContainerType::Tree => Self::Tree(TreeHandler::new_detached()),
1293 ContainerType::MovableList => Self::MovableList(MovableListHandler::new_detached()),
1294 #[cfg(feature = "counter")]
1295 ContainerType::Counter => Self::Counter(counter::CounterHandler::new_detached()),
1296 ContainerType::Unknown(_) => return Err(unknown_container_creation_err(kind)),
1297 })
1298 }
1299
1300 pub fn id(&self) -> ContainerID {
1301 match self {
1302 Self::Map(x) => x.id(),
1303 Self::List(x) => x.id(),
1304 Self::Text(x) => x.id(),
1305 Self::Tree(x) => x.id(),
1306 Self::MovableList(x) => x.id(),
1307 #[cfg(feature = "counter")]
1308 Self::Counter(x) => x.id(),
1309 Self::Unknown(x) => x.id(),
1310 }
1311 }
1312
1313 pub(crate) fn container_idx(&self) -> ContainerIdx {
1314 match self {
1315 Self::Map(x) => x.idx(),
1316 Self::List(x) => x.idx(),
1317 Self::Text(x) => x.idx(),
1318 Self::Tree(x) => x.idx(),
1319 Self::MovableList(x) => x.idx(),
1320 #[cfg(feature = "counter")]
1321 Self::Counter(x) => x.idx(),
1322 Self::Unknown(x) => x.idx(),
1323 }
1324 }
1325
1326 pub fn c_type(&self) -> ContainerType {
1327 match self {
1328 Self::Map(_) => ContainerType::Map,
1329 Self::List(_) => ContainerType::List,
1330 Self::Text(_) => ContainerType::Text,
1331 Self::Tree(_) => ContainerType::Tree,
1332 Self::MovableList(_) => ContainerType::MovableList,
1333 #[cfg(feature = "counter")]
1334 Self::Counter(_) => ContainerType::Counter,
1335 Self::Unknown(x) => x.id().container_type(),
1336 }
1337 }
1338
1339 fn get_deep_value(&self) -> LoroValue {
1340 match self {
1341 Self::Map(x) => x.get_deep_value(),
1342 Self::List(x) => x.get_deep_value(),
1343 Self::MovableList(x) => x.get_deep_value(),
1344 Self::Text(x) => x.get_deep_value(),
1345 Self::Tree(x) => x.get_deep_value(),
1346 #[cfg(feature = "counter")]
1347 Self::Counter(x) => x.get_deep_value(),
1348 Self::Unknown(x) => x.get_deep_value(),
1349 }
1350 }
1351
1352 pub(crate) fn apply_diff(
1353 &self,
1354 diff: Diff,
1355 container_remap: &mut FxHashMap<ContainerID, ContainerID>,
1356 full_state_targets: &mut FxHashSet<ContainerID>,
1357 ) -> LoroResult<()> {
1358 // In this method we will not clone the values of the containers if
1359 // they are remapped. It's the caller's duty to do so
1360 let on_container_remap = &mut |old_id, new_id| {
1361 if old_id != new_id {
1362 container_remap.insert(old_id, new_id);
1363 }
1364 };
1365 match self {
1366 Self::Map(x) => {
1367 let diff = match diff {
1368 crate::event::Diff::Map(d) => d,
1369 _ => {
1370 return Err(LoroError::DecodeError(
1371 "Invalid diff type for map container".into(),
1372 ));
1373 }
1374 };
1375 for (key, value) in diff.updated.into_iter() {
1376 match value.value {
1377 Some(ValueOrHandler::Handler(h)) => {
1378 Self::apply_map_container_diff_value(
1379 x,
1380 &key,
1381 h.id(),
1382 on_container_remap,
1383 full_state_targets,
1384 )?;
1385 }
1386 Some(ValueOrHandler::Value(LoroValue::Container(old_id))) => {
1387 Self::apply_map_container_diff_value(
1388 x,
1389 &key,
1390 old_id,
1391 on_container_remap,
1392 full_state_targets,
1393 )?;
1394 }
1395 Some(ValueOrHandler::Value(v)) => {
1396 x.insert_without_skipping(&key, v)?;
1397 }
1398 None => {
1399 x.delete(&key)?;
1400 }
1401 }
1402 }
1403 }
1404 Self::Text(x) => {
1405 let delta = match diff {
1406 crate::event::Diff::Text(d) => d,
1407 _ => {
1408 return Err(LoroError::DecodeError(
1409 "Invalid diff type for text container".into(),
1410 ));
1411 }
1412 };
1413 x.apply_delta(&TextDelta::from_text_diff(delta.iter()))?;
1414 }
1415 Self::List(x) => {
1416 let delta = match diff {
1417 crate::event::Diff::List(d) => d,
1418 _ => {
1419 return Err(LoroError::DecodeError(
1420 "Invalid diff type for list container".into(),
1421 ));
1422 }
1423 };
1424 x.apply_delta(delta, on_container_remap)?;
1425 }
1426 Self::MovableList(x) => {
1427 let delta = match diff {
1428 crate::event::Diff::List(d) => d,
1429 _ => {
1430 return Err(LoroError::DecodeError(
1431 "Invalid diff type for movable list container".into(),
1432 ));
1433 }
1434 };
1435 x.apply_delta(delta, container_remap)?;
1436 }
1437 Self::Tree(x) => {
1438 fn remap_tree_id(
1439 id: &mut TreeID,
1440 container_remap: &FxHashMap<ContainerID, ContainerID>,
1441 ) {
1442 let mut remapped = false;
1443 let mut map_id = id.associated_meta_container();
1444 while let Some(rid) = container_remap.get(&map_id) {
1445 remapped = true;
1446 map_id = rid.clone();
1447 }
1448 if remapped {
1449 *id = TreeID::new(
1450 *map_id.as_normal().unwrap().0,
1451 *map_id.as_normal().unwrap().1,
1452 )
1453 }
1454 }
1455 let tree_diff = match diff {
1456 crate::event::Diff::Tree(d) => d,
1457 _ => {
1458 return Err(LoroError::DecodeError(
1459 "Invalid diff type for tree container".into(),
1460 ));
1461 }
1462 };
1463 for diff in tree_diff.diff {
1464 let mut target = diff.target;
1465 match diff.action {
1466 TreeExternalDiff::Create {
1467 mut parent,
1468 index: _,
1469 position,
1470 } => {
1471 if let TreeParentId::Node(p) = &mut parent {
1472 remap_tree_id(p, container_remap)
1473 }
1474 remap_tree_id(&mut target, container_remap);
1475 if !x.is_node_unexist(&target) && !x.is_node_deleted(&target)? {
1476 // 1@0 is the parent of 2@1
1477 // ┌────┐ ┌───────────────┐
1478 // │xxxx│◀───│Move 2@1 to 0@0◀┐
1479 // └────┘ └───────────────┘│
1480 // ┌───────┐ │ ┌────────┐
1481 // │Del 1@0│◀─────────────────┴─│Meta 2@1│ ◀─── undo 2 ops redo 2 ops
1482 // └───────┘ └────────┘
1483 //
1484 // When we undo the delete operation, we should not create a new tree node and its child.
1485 // However, the concurrent operation has moved the child to another parent. It's still alive.
1486 // So when we redo the delete operation, we should check if the target is still alive.
1487 // If it's alive, we should move it back instead of creating new one.
1488 x.move_at_with_target_for_apply_diff(parent, position, target)?;
1489 } else {
1490 let new_target = x.__internal__next_tree_id();
1491 if x.create_at_with_target_for_apply_diff(
1492 parent, position, new_target,
1493 )? {
1494 container_remap.insert(
1495 target.associated_meta_container(),
1496 new_target.associated_meta_container(),
1497 );
1498 }
1499 }
1500 }
1501 TreeExternalDiff::Move {
1502 mut parent,
1503 index: _,
1504 position,
1505 old_parent: _,
1506 old_index: _,
1507 } => {
1508 if let TreeParentId::Node(p) = &mut parent {
1509 remap_tree_id(p, container_remap)
1510 }
1511 remap_tree_id(&mut target, container_remap);
1512 // determine if the target is deleted
1513 if x.is_node_unexist(&target) || x.is_node_deleted(&target)? {
1514 // create the target node, we should use the new target id
1515 let new_target = x.__internal__next_tree_id();
1516 if x.create_at_with_target_for_apply_diff(
1517 parent, position, new_target,
1518 )? {
1519 container_remap.insert(
1520 target.associated_meta_container(),
1521 new_target.associated_meta_container(),
1522 );
1523 }
1524 } else {
1525 x.move_at_with_target_for_apply_diff(parent, position, target)?;
1526 }
1527 }
1528 TreeExternalDiff::Delete { .. } => {
1529 remap_tree_id(&mut target, container_remap);
1530 if !x.is_node_deleted(&target)? {
1531 x.delete(target)?;
1532 }
1533 }
1534 }
1535 }
1536 }
1537 #[cfg(feature = "counter")]
1538 Self::Counter(x) => {
1539 let delta = match diff {
1540 crate::event::Diff::Counter(d) => d,
1541 _ => {
1542 return Err(LoroError::DecodeError(
1543 "Invalid diff type for counter container".into(),
1544 ));
1545 }
1546 };
1547 x.increment(delta)?;
1548 }
1549 Self::Unknown(_) => {
1550 // do nothing
1551 }
1552 }
1553
1554 Ok(())
1555 }
1556
1557 pub fn clear(&self) -> LoroResult<()> {
1558 match self {
1559 Handler::Text(text_handler) => text_handler.clear(),
1560 Handler::Map(map_handler) => map_handler.clear(),
1561 Handler::List(list_handler) => list_handler.clear(),
1562 Handler::MovableList(movable_list_handler) => movable_list_handler.clear(),
1563 Handler::Tree(tree_handler) => tree_handler.clear(),
1564 #[cfg(feature = "counter")]
1565 Handler::Counter(counter_handler) => counter_handler.clear(),
1566 Handler::Unknown(_unknown_handler) => Ok(()),
1567 }
1568 }
1569}
1570
1571#[derive(Clone, EnumAsInner, Debug)]
1572pub enum ValueOrHandler {
1573 Value(LoroValue),
1574 Handler(Handler),
1575}
1576
1577impl ValueOrHandler {
1578 pub(crate) fn from_value(value: LoroValue, doc: &Arc<LoroDocInner>) -> Self {
1579 if let LoroValue::Container(c) = value {
1580 ValueOrHandler::Handler(Handler::new_attached(c, LoroDoc::from_inner(doc.clone())))
1581 } else {
1582 ValueOrHandler::Value(value)
1583 }
1584 }
1585
1586 pub(crate) fn to_value(&self) -> LoroValue {
1587 match self {
1588 Self::Value(v) => v.clone(),
1589 Self::Handler(h) => LoroValue::Container(h.id().clone()),
1590 }
1591 }
1592
1593 pub(crate) fn to_deep_value(&self) -> LoroValue {
1594 match self {
1595 Self::Value(v) => v.clone(),
1596 Self::Handler(h) => h.get_deep_value(),
1597 }
1598 }
1599}
1600
1601impl From<LoroValue> for ValueOrHandler {
1602 fn from(value: LoroValue) -> Self {
1603 ValueOrHandler::Value(value)
1604 }
1605}
1606
1607impl TextHandler {
1608 /// Create a new container that is detached from the document.
1609 ///
1610 /// The edits on a detached container will not be persisted.
1611 /// To attach the container to the document, please insert it into an attached container.
1612 pub fn new_detached() -> Self {
1613 Self {
1614 inner: MaybeDetached::new_detached(RichtextState::default()),
1615 }
1616 }
1617
1618 /// Get the version id of the richtext
1619 ///
1620 /// This can be used to detect whether the richtext is changed
1621 pub fn version_id(&self) -> Option<usize> {
1622 match &self.inner {
1623 MaybeDetached::Detached(_) => None,
1624 MaybeDetached::Attached(a) => {
1625 Some(a.with_state(|state| state.as_richtext_state_mut().unwrap().get_version_id()))
1626 }
1627 }
1628 }
1629
1630 pub fn get_richtext_value(&self) -> LoroValue {
1631 match &self.inner {
1632 MaybeDetached::Detached(t) => {
1633 let t = t.lock();
1634 t.value.get_richtext_value()
1635 }
1636 MaybeDetached::Attached(a) => {
1637 a.with_state(|state| state.as_richtext_state_mut().unwrap().get_richtext_value())
1638 }
1639 }
1640 }
1641
1642 pub fn is_empty(&self) -> bool {
1643 match &self.inner {
1644 MaybeDetached::Detached(t) => t.lock().value.is_empty(),
1645 MaybeDetached::Attached(a) if a.has_decoded_state() => {
1646 a.with_state(|state| state.as_richtext_state_mut().unwrap().is_empty())
1647 }
1648 MaybeDetached::Attached(a) => a.get_value().as_string().unwrap().is_empty(),
1649 }
1650 }
1651
1652 pub fn len_utf8(&self) -> usize {
1653 match &self.inner {
1654 MaybeDetached::Detached(t) => {
1655 let t = t.lock();
1656 t.value.len_utf8()
1657 }
1658 MaybeDetached::Attached(a) => {
1659 a.with_doc_state(|state| state.get_text_len(a.container_idx, PosType::Bytes))
1660 }
1661 }
1662 }
1663
1664 pub fn len_utf16(&self) -> usize {
1665 match &self.inner {
1666 MaybeDetached::Detached(t) => {
1667 let t = t.lock();
1668 t.value.len_utf16()
1669 }
1670 MaybeDetached::Attached(a) => {
1671 a.with_doc_state(|state| state.get_text_len(a.container_idx, PosType::Utf16))
1672 }
1673 }
1674 }
1675
1676 pub fn len_unicode(&self) -> usize {
1677 match &self.inner {
1678 MaybeDetached::Detached(t) => {
1679 let t = t.lock();
1680 t.value.len_unicode()
1681 }
1682 MaybeDetached::Attached(a) => {
1683 a.with_doc_state(|state| state.get_text_len(a.container_idx, PosType::Unicode))
1684 }
1685 }
1686 }
1687
1688 /// if `wasm` feature is enabled, it is a UTF-16 length
1689 /// otherwise, it is a Unicode length
1690 pub fn len_event(&self) -> usize {
1691 if cfg!(feature = "wasm") {
1692 self.len_utf16()
1693 } else {
1694 self.len_unicode()
1695 }
1696 }
1697
1698 fn len(&self, pos_type: PosType) -> usize {
1699 match &self.inner {
1700 MaybeDetached::Detached(t) => t.lock().value.len(pos_type),
1701 MaybeDetached::Attached(a) => {
1702 a.with_doc_state(|state| state.get_text_len(a.container_idx, pos_type))
1703 }
1704 }
1705 }
1706
1707 fn validate_text_boundary(&self, pos: usize, pos_type: PosType) -> LoroResult<()> {
1708 let err = match pos_type {
1709 PosType::Bytes => Some(LoroError::UTF8InUnicodeCodePoint { pos }),
1710 PosType::Utf16 => Some(LoroError::UTF16InUnicodeCodePoint { pos }),
1711 PosType::Event if cfg!(feature = "wasm") => {
1712 Some(LoroError::UTF16InUnicodeCodePoint { pos })
1713 }
1714 _ => None,
1715 };
1716
1717 let Some(err) = err else {
1718 return Ok(());
1719 };
1720
1721 let len = self.len(pos_type);
1722 if pos > len {
1723 return Ok(());
1724 }
1725
1726 if self.all_text_positions_are_boundaries(pos_type, len) {
1727 return Ok(());
1728 }
1729
1730 let Some(unicode_pos) = self.convert_pos(pos, pos_type, PosType::Unicode) else {
1731 return Err(err);
1732 };
1733 if self.convert_pos(unicode_pos, PosType::Unicode, pos_type) != Some(pos) {
1734 return Err(err);
1735 }
1736
1737 Ok(())
1738 }
1739
1740 fn all_text_positions_are_boundaries(&self, pos_type: PosType, len: usize) -> bool {
1741 match pos_type {
1742 PosType::Bytes => len == self.len_unicode(),
1743 PosType::Utf16 => len == self.len_unicode(),
1744 PosType::Event if cfg!(feature = "wasm") => len == self.len_unicode(),
1745 _ => false,
1746 }
1747 }
1748
1749 pub fn diagnose(&self) {
1750 match &self.inner {
1751 MaybeDetached::Detached(t) => {
1752 let t = t.lock();
1753 t.value.diagnose();
1754 }
1755 MaybeDetached::Attached(a) => {
1756 a.with_state(|state| state.as_richtext_state_mut().unwrap().diagnose());
1757 }
1758 }
1759 }
1760
1761 pub fn iter(&self, mut callback: impl FnMut(&str) -> bool) {
1762 // Do not call user callbacks while holding the state lock; callbacks may re-enter Loro.
1763 let spans: Vec<String> = match &self.inner {
1764 MaybeDetached::Detached(t) => {
1765 let t = t.lock();
1766 t.value
1767 .iter()
1768 .map(|span| span.text.as_str().to_owned())
1769 .collect()
1770 }
1771 MaybeDetached::Attached(a) => a.with_state(|state| {
1772 let mut spans = Vec::new();
1773 state.as_richtext_state_mut().unwrap().iter(|span| {
1774 spans.push(span.to_owned());
1775 true
1776 });
1777 spans
1778 }),
1779 };
1780
1781 for span in spans {
1782 if !callback(span.as_str()) {
1783 return;
1784 }
1785 }
1786 }
1787
1788 /// Get a character at `pos` in the coordinate system specified by `pos_type`.
1789 pub fn char_at(&self, pos: usize, pos_type: PosType) -> LoroResult<char> {
1790 let len = self.len(pos_type);
1791 if pos >= len {
1792 return Err(LoroError::OutOfBound {
1793 pos,
1794 len,
1795 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
1796 });
1797 }
1798 if let Ok(c) = match &self.inner {
1799 MaybeDetached::Detached(t) => {
1800 let t = t.lock();
1801 let event_pos = match pos_type {
1802 PosType::Event => pos,
1803 _ => t.value.index_to_event_index(pos, pos_type),
1804 };
1805 t.value.get_char_by_event_index(event_pos)
1806 }
1807 MaybeDetached::Attached(a) if a.has_decoded_state() || pos_type == PosType::Entity => a
1808 .with_state(|state| {
1809 let state = state.as_richtext_state_mut().unwrap();
1810 let event_pos = match pos_type {
1811 PosType::Event => pos,
1812 _ => state.index_to_event_index(pos, pos_type),
1813 };
1814 state.get_char_by_event_index(event_pos)
1815 }),
1816 MaybeDetached::Attached(a) => {
1817 return text_char_at(a.get_value().as_string().unwrap(), pos, pos_type);
1818 }
1819 } {
1820 Ok(c)
1821 } else {
1822 Err(LoroError::OutOfBound {
1823 pos,
1824 len,
1825 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
1826 })
1827 }
1828 }
1829
1830 /// `start_index` and `end_index` are Event Index:
1831 ///
1832 /// - if feature="wasm", pos is a UTF-16 index
1833 /// - if feature!="wasm", pos is a Unicode index
1834 ///
1835 pub fn slice(
1836 &self,
1837 start_index: usize,
1838 end_index: usize,
1839 pos_type: PosType,
1840 ) -> LoroResult<String> {
1841 self.slice_with_pos_type(start_index, end_index, pos_type)
1842 }
1843
1844 pub fn slice_utf16(&self, start_index: usize, end_index: usize) -> LoroResult<String> {
1845 self.slice(start_index, end_index, PosType::Utf16)
1846 }
1847
1848 fn slice_with_pos_type(
1849 &self,
1850 start_index: usize,
1851 end_index: usize,
1852 pos_type: PosType,
1853 ) -> LoroResult<String> {
1854 if end_index < start_index {
1855 return Err(LoroError::EndIndexLessThanStartIndex {
1856 start: start_index,
1857 end: end_index,
1858 });
1859 }
1860 if start_index == end_index {
1861 return Ok(String::new());
1862 }
1863
1864 let info = || format!("Position: {}:{}", file!(), line!()).into_boxed_str();
1865 match &self.inner {
1866 MaybeDetached::Detached(t) => {
1867 let t = t.lock();
1868 let len = t.value.len(pos_type);
1869 if end_index > len {
1870 return Err(LoroError::OutOfBound {
1871 pos: end_index,
1872 len,
1873 info: info(),
1874 });
1875 }
1876 let (start, end) = match pos_type {
1877 PosType::Event => (start_index, end_index),
1878 _ => (
1879 t.value.index_to_event_index(start_index, pos_type),
1880 t.value.index_to_event_index(end_index, pos_type),
1881 ),
1882 };
1883 t.value.get_text_slice_by_event_index(start, end - start)
1884 }
1885 MaybeDetached::Attached(a) if a.has_decoded_state() || pos_type == PosType::Entity => a
1886 .with_state(|state| {
1887 let state = state.as_richtext_state_mut().unwrap();
1888 let len = state.len(pos_type);
1889 if end_index > len {
1890 return Err(LoroError::OutOfBound {
1891 pos: end_index,
1892 len,
1893 info: info(),
1894 });
1895 }
1896 let (start, end) = match pos_type {
1897 PosType::Event => (start_index, end_index),
1898 _ => (
1899 state.index_to_event_index(start_index, pos_type),
1900 state.index_to_event_index(end_index, pos_type),
1901 ),
1902 };
1903 state.get_text_slice_by_event_index(start, end - start)
1904 }),
1905 MaybeDetached::Attached(a) => text_slice(
1906 a.get_value().as_string().unwrap(),
1907 start_index,
1908 end_index,
1909 pos_type,
1910 )
1911 .map_err(|err| match err {
1912 LoroError::OutOfBound { pos, len, .. } => LoroError::OutOfBound {
1913 pos,
1914 len,
1915 info: info(),
1916 },
1917 err => err,
1918 }),
1919 }
1920 }
1921
1922 pub fn slice_delta(
1923 &self,
1924 start_index: usize,
1925 end_index: usize,
1926 pos_type: PosType,
1927 ) -> LoroResult<Vec<TextDelta>> {
1928 if end_index < start_index {
1929 return Err(LoroError::EndIndexLessThanStartIndex {
1930 start: start_index,
1931 end: end_index,
1932 });
1933 }
1934 if start_index == end_index {
1935 return Ok(Vec::new());
1936 }
1937
1938 let len = self.len(pos_type);
1939 if end_index > len {
1940 return Err(LoroError::OutOfBound {
1941 pos: end_index,
1942 len,
1943 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
1944 });
1945 }
1946 self.validate_text_boundary(start_index, pos_type)?;
1947 self.validate_text_boundary(end_index, pos_type)?;
1948
1949 match &self.inner {
1950 MaybeDetached::Detached(t) => {
1951 let t = t.lock();
1952 let ans = t.value.slice_delta(start_index, end_index, pos_type)?;
1953 Ok(ans
1954 .into_iter()
1955 .map(|(s, a)| TextDelta::Insert {
1956 insert: s,
1957 attributes: a.to_option_map_without_null_value(),
1958 })
1959 .collect())
1960 }
1961 MaybeDetached::Attached(a) => a.with_state(|state| {
1962 let ans = state.as_richtext_state_mut().unwrap().slice_delta(
1963 start_index,
1964 end_index,
1965 pos_type,
1966 )?;
1967 Ok(ans
1968 .into_iter()
1969 .map(|(s, a)| TextDelta::Insert {
1970 insert: s,
1971 attributes: a.to_option_map_without_null_value(),
1972 })
1973 .collect())
1974 }),
1975 }
1976 }
1977
1978 /// `pos` is a Event Index:
1979 ///
1980 /// - if feature="wasm", pos is a UTF-16 index
1981 /// - if feature!="wasm", pos is a Unicode index
1982 ///
1983 /// This method requires auto_commit to be enabled.
1984 pub fn splice(&self, pos: usize, len: usize, s: &str, pos_type: PosType) -> LoroResult<String> {
1985 let end = checked_range_end(pos, len, self.len(pos_type), || {
1986 format!("Position: {}:{}", file!(), line!()).into_boxed_str()
1987 })?;
1988 let x = self.slice(pos, end, pos_type)?;
1989 self.delete(pos, len, pos_type)?;
1990 self.insert(pos, s, pos_type)?;
1991 Ok(x)
1992 }
1993
1994 pub fn splice_utf8(&self, pos: usize, len: usize, s: &str) -> LoroResult<()> {
1995 // let x = self.slice(pos, pos + len)?;
1996 self.delete_utf8(pos, len)?;
1997 self.insert_utf8(pos, s)?;
1998 Ok(())
1999 }
2000
2001 pub fn splice_utf16(&self, pos: usize, len: usize, s: &str) -> LoroResult<()> {
2002 self.delete(pos, len, PosType::Utf16)?;
2003 self.insert(pos, s, PosType::Utf16)?;
2004 Ok(())
2005 }
2006
2007 /// Insert text at `pos` using the given `pos_type` coordinate system.
2008 ///
2009 /// This method requires auto_commit to be enabled.
2010 pub fn insert(&self, pos: usize, s: &str, pos_type: PosType) -> LoroResult<()> {
2011 match &self.inner {
2012 MaybeDetached::Detached(t) => {
2013 let len = self.len(pos_type);
2014 if pos > len {
2015 return Err(LoroError::OutOfBound {
2016 pos,
2017 len,
2018 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
2019 });
2020 }
2021 self.validate_text_boundary(pos, pos_type)?;
2022
2023 let mut t = t.lock();
2024 let (index, _) = t
2025 .value
2026 .get_entity_index_for_text_insert(pos, pos_type)
2027 .unwrap();
2028 t.value.insert_at_entity_index(
2029 index,
2030 BytesSlice::from_bytes(s.as_bytes()),
2031 IdFull::NONE_ID,
2032 );
2033 Ok(())
2034 }
2035 MaybeDetached::Attached(a) => {
2036 if s.is_empty() {
2037 let len = self.len(pos_type);
2038 if pos > len {
2039 return Err(LoroError::OutOfBound {
2040 pos,
2041 len,
2042 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
2043 });
2044 }
2045 self.validate_text_boundary(pos, pos_type)?;
2046 return Ok(());
2047 }
2048
2049 a.with_txn(|txn| self.insert_with_txn(txn, pos, s, pos_type))
2050 }
2051 }
2052 }
2053
2054 pub fn insert_utf8(&self, pos: usize, s: &str) -> LoroResult<()> {
2055 self.insert(pos, s, PosType::Bytes)
2056 }
2057
2058 pub fn insert_utf16(&self, pos: usize, s: &str) -> LoroResult<()> {
2059 self.insert(pos, s, PosType::Utf16)
2060 }
2061
2062 pub fn insert_unicode(&self, pos: usize, s: &str) -> LoroResult<()> {
2063 self.insert(pos, s, PosType::Unicode)
2064 }
2065
2066 /// Insert text within an existing transaction using the provided `pos_type`.
2067 pub fn insert_with_txn(
2068 &self,
2069 txn: &mut Transaction,
2070 pos: usize,
2071 s: &str,
2072 pos_type: PosType,
2073 ) -> LoroResult<()> {
2074 self.insert_with_txn_and_attr(txn, pos, s, None, pos_type)?;
2075 Ok(())
2076 }
2077
2078 pub fn insert_with_txn_utf8(
2079 &self,
2080 txn: &mut Transaction,
2081 pos: usize,
2082 s: &str,
2083 ) -> LoroResult<()> {
2084 self.insert_with_txn(txn, pos, s, PosType::Bytes)
2085 }
2086
2087 /// Delete a span using the coordinate system described by `pos_type`.
2088 ///
2089 /// This method requires auto_commit to be enabled.
2090 pub fn delete(&self, pos: usize, len: usize, pos_type: PosType) -> LoroResult<()> {
2091 if len == 0 {
2092 return Ok(());
2093 }
2094
2095 let text_len = self.len(pos_type);
2096 let end = checked_range_end(pos, len, text_len, || {
2097 format!("Position: {}:{}", file!(), line!()).into_boxed_str()
2098 })?;
2099 self.validate_text_boundary(pos, pos_type)?;
2100 self.validate_text_boundary(end, pos_type)?;
2101
2102 match &self.inner {
2103 MaybeDetached::Detached(t) => {
2104 let mut t = t.lock();
2105 let ranges = t.value.get_text_entity_ranges(pos, len, pos_type)?;
2106 for range in ranges.iter().rev() {
2107 t.value
2108 .drain_by_entity_index(range.entity_start, range.entity_len(), None);
2109 }
2110 Ok(())
2111 }
2112 MaybeDetached::Attached(a) => {
2113 a.with_txn(|txn| self.delete_with_txn(txn, pos, len, pos_type))
2114 }
2115 }
2116 }
2117
2118 pub fn delete_utf8(&self, pos: usize, len: usize) -> LoroResult<()> {
2119 self.delete(pos, len, PosType::Bytes)
2120 }
2121
2122 pub fn delete_utf16(&self, pos: usize, len: usize) -> LoroResult<()> {
2123 self.delete(pos, len, PosType::Utf16)
2124 }
2125
2126 pub fn delete_unicode(&self, pos: usize, len: usize) -> LoroResult<()> {
2127 self.delete(pos, len, PosType::Unicode)
2128 }
2129
2130 /// If attr is specified, it will be used as the attribute of the inserted text.
2131 /// It will override the existing attribute of the text.
2132 fn insert_with_txn_and_attr(
2133 &self,
2134 txn: &mut Transaction,
2135 pos: usize,
2136 s: &str,
2137 attr: Option<&FxHashMap<String, LoroValue>>,
2138 pos_type: PosType,
2139 ) -> Result<Vec<(InternalString, LoroValue)>, LoroError> {
2140 if s.is_empty() {
2141 return Ok(Vec::new());
2142 }
2143
2144 // Fast path: plain-text insert into a style-free document (non-wasm).
2145 // With no style anchors, entity_index == unicode pos and the event index
2146 // equals the unicode index, so bounds + no-styles are checked in a single
2147 // state access and the entire read phase (cursor location + two
2148 // visit_previous_caches walks + styles lookup) is skipped; apply_local_op
2149 // then locates the cursor exactly once.
2150 #[cfg(not(feature = "wasm"))]
2151 if attr.is_none() && pos_type == PosType::Unicode {
2152 let inner = self.inner.try_attached_state()?;
2153 let fast = inner.with_state(|state| {
2154 let rt = state.as_richtext_state_mut().unwrap();
2155 if rt.has_styles() {
2156 return Ok(false);
2157 }
2158 let len = rt.len_unicode();
2159 if pos > len {
2160 return Err(LoroError::OutOfBound {
2161 pos,
2162 len,
2163 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
2164 });
2165 }
2166 Ok(true)
2167 })?;
2168 if fast {
2169 let unicode_len = s.chars().count();
2170 txn.apply_local_op(
2171 inner.container_idx,
2172 crate::op::RawOpContent::List(
2173 crate::container::list::list_op::ListOp::Insert {
2174 slice: ListSlice::RawStr {
2175 str: Cow::Borrowed(s),
2176 unicode_len,
2177 },
2178 // entity_index == unicode pos (no style anchors)
2179 pos,
2180 },
2181 ),
2182 EventHint::InsertText {
2183 // event index == unicode index (non-wasm)
2184 pos: pos as u32,
2185 styles: StyleMeta::empty(),
2186 unicode_len: unicode_len as u32,
2187 event_len: unicode_len as u32,
2188 },
2189 &inner.doc,
2190 )?;
2191 return Ok(Vec::new());
2192 }
2193 }
2194
2195 match pos_type {
2196 PosType::Event => {
2197 if pos > self.len_event() {
2198 return Err(LoroError::OutOfBound {
2199 pos,
2200 len: self.len_event(),
2201 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
2202 });
2203 }
2204 }
2205 PosType::Bytes => {
2206 if pos > self.len_utf8() {
2207 return Err(LoroError::OutOfBound {
2208 pos,
2209 len: self.len_utf8(),
2210 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
2211 });
2212 }
2213 }
2214 PosType::Unicode => {
2215 if pos > self.len_unicode() {
2216 return Err(LoroError::OutOfBound {
2217 pos,
2218 len: self.len_unicode(),
2219 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
2220 });
2221 }
2222 }
2223 PosType::Entity => {}
2224 PosType::Utf16 => {
2225 if pos > self.len_utf16() {
2226 return Err(LoroError::OutOfBound {
2227 pos,
2228 len: self.len_utf16(),
2229 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
2230 });
2231 }
2232 }
2233 }
2234 self.validate_text_boundary(pos, pos_type)?;
2235
2236 let inner = self.inner.try_attached_state()?;
2237 let (entity_index, event_index, styles) = inner.with_state(|state| {
2238 let richtext_state = state.as_richtext_state_mut().unwrap();
2239 let ret = richtext_state.get_entity_index_for_text_insert(pos, pos_type);
2240 let (entity_index, cursor) = match ret {
2241 Err(_) => match pos_type {
2242 PosType::Bytes => {
2243 return (
2244 Err(LoroError::UTF8InUnicodeCodePoint { pos }),
2245 0,
2246 StyleMeta::empty(),
2247 );
2248 }
2249 PosType::Utf16 | PosType::Event => {
2250 return (
2251 Err(LoroError::UTF16InUnicodeCodePoint { pos }),
2252 0,
2253 StyleMeta::empty(),
2254 );
2255 }
2256 _ => unreachable!(),
2257 },
2258 Ok(x) => x,
2259 };
2260 let event_index = if let Some(cursor) = cursor {
2261 if pos_type == PosType::Event {
2262 debug_assert_eq!(
2263 richtext_state.get_event_index_by_cursor(cursor),
2264 pos,
2265 "pos={} cursor={:?} state={:#?}",
2266 pos,
2267 cursor,
2268 &richtext_state
2269 );
2270 pos
2271 } else {
2272 richtext_state.get_event_index_by_cursor(cursor)
2273 }
2274 } else {
2275 assert_eq!(entity_index, 0);
2276 0
2277 };
2278 let styles = richtext_state.get_styles_at_entity_index(entity_index);
2279 (Ok(entity_index), event_index, styles)
2280 });
2281
2282 let entity_index = match entity_index {
2283 Err(x) => return Err(x),
2284 _ => entity_index.unwrap(),
2285 };
2286
2287 let mut override_styles = Vec::new();
2288 if let Some(attr) = attr {
2289 // current styles
2290 let map: FxHashMap<_, _> = styles.iter().map(|x| (x.0.clone(), x.1.data)).collect();
2291 for (key, style) in map.iter() {
2292 match attr.get(key.deref()) {
2293 Some(v) if v == style => {}
2294 new_style_value => {
2295 // need to override
2296 let new_style_value = new_style_value.cloned().unwrap_or(LoroValue::Null);
2297 override_styles.push((key.clone(), new_style_value));
2298 }
2299 }
2300 }
2301
2302 for (key, style) in attr.iter() {
2303 let key = key.as_str().into();
2304 if !map.contains_key(&key) {
2305 override_styles.push((key, style.clone()));
2306 }
2307 }
2308 }
2309
2310 let unicode_len = s.chars().count();
2311 let event_len = if cfg!(feature = "wasm") {
2312 count_utf16_len(s.as_bytes())
2313 } else {
2314 unicode_len
2315 };
2316
2317 txn.apply_local_op(
2318 inner.container_idx,
2319 crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Insert {
2320 slice: ListSlice::RawStr {
2321 str: Cow::Borrowed(s),
2322 unicode_len,
2323 },
2324 pos: entity_index,
2325 }),
2326 EventHint::InsertText {
2327 pos: event_index as u32,
2328 styles,
2329 unicode_len: unicode_len as u32,
2330 event_len: event_len as u32,
2331 },
2332 &inner.doc,
2333 )?;
2334
2335 Ok(override_styles)
2336 }
2337
2338 /// Delete text within a transaction using the specified `pos_type`.
2339 pub fn delete_with_txn(
2340 &self,
2341 txn: &mut Transaction,
2342 pos: usize,
2343 len: usize,
2344 pos_type: PosType,
2345 ) -> LoroResult<()> {
2346 self.delete_with_txn_inline(txn, pos, len, pos_type)
2347 }
2348
2349 fn delete_with_txn_inline(
2350 &self,
2351 txn: &mut Transaction,
2352 pos: usize,
2353 len: usize,
2354 pos_type: PosType,
2355 ) -> LoroResult<()> {
2356 if len == 0 {
2357 return Ok(());
2358 }
2359
2360 let text_len = self.len(pos_type);
2361 let end = checked_range_end(pos, len, text_len, || {
2362 format!("Position: {}:{}", file!(), line!()).into_boxed_str()
2363 })
2364 .inspect_err(|_| error!("pos={} len={} len={}", pos, len, text_len))?;
2365 self.validate_text_boundary(pos, pos_type)?;
2366 self.validate_text_boundary(end, pos_type)?;
2367
2368 let inner = self.inner.try_attached_state()?;
2369 let s = tracing::span!(tracing::Level::INFO, "delete", "pos={} len={}", pos, len);
2370 let _e = s.enter();
2371 let mut event_pos = 0;
2372 let mut event_len = 0;
2373 let ranges = inner.with_state(|state| {
2374 let richtext_state = state.as_richtext_state_mut().unwrap();
2375 // Fast path: with no style anchors (non-wasm), the event index equals
2376 // the unicode index, so the two index_to_event_index walks collapse to
2377 // identity.
2378 let fast = cfg!(not(feature = "wasm"))
2379 && pos_type == PosType::Unicode
2380 && !richtext_state.has_styles();
2381 if fast {
2382 event_pos = pos;
2383 event_len = len;
2384 } else {
2385 event_pos = richtext_state.index_to_event_index(pos, pos_type);
2386 let event_end = richtext_state.index_to_event_index(end, pos_type);
2387 event_len = event_end - event_pos;
2388 }
2389
2390 richtext_state.get_text_entity_ranges_in_event_index_range(event_pos, event_len)
2391 })?;
2392
2393 //debug_assert_eq!(ranges.iter().map(|x| x.event_len).sum::<usize>(), len);
2394 let pos = event_pos as isize;
2395 let len = event_len as isize;
2396 let mut event_end = pos + len;
2397 for range in ranges.iter().rev() {
2398 let event_start = event_end - range.event_len as isize;
2399 txn.apply_local_op(
2400 inner.container_idx,
2401 crate::op::RawOpContent::List(ListOp::Delete(DeleteSpanWithId::new(
2402 range.id_start,
2403 range.entity_start as isize,
2404 range.entity_len() as isize,
2405 ))),
2406 EventHint::DeleteText {
2407 span: DeleteSpan {
2408 pos: event_start,
2409 signed_len: range.event_len as isize,
2410 },
2411 unicode_len: range.entity_len(),
2412 },
2413 &inner.doc,
2414 )?;
2415 event_end = event_start;
2416 }
2417
2418 Ok(())
2419 }
2420
2421 /// `start` and `end` are interpreted using `pos_type`.
2422 ///
2423 /// This method requires auto_commit to be enabled.
2424 pub fn mark(
2425 &self,
2426 start: usize,
2427 end: usize,
2428 key: impl Into<InternalString>,
2429 value: LoroValue,
2430 pos_type: PosType,
2431 ) -> LoroResult<()> {
2432 match &self.inner {
2433 MaybeDetached::Detached(t) => {
2434 let mut g = t.lock();
2435 self.mark_for_detached(&mut g.value, key, &value, start, end, pos_type)
2436 }
2437 MaybeDetached::Attached(a) => {
2438 a.with_txn(|txn| self.mark_with_txn(txn, start, end, key, value, pos_type))
2439 }
2440 }
2441 }
2442
2443 fn mark_for_detached(
2444 &self,
2445 state: &mut RichtextState,
2446 key: impl Into<InternalString>,
2447 value: &LoroValue,
2448 start: usize,
2449 end: usize,
2450 pos_type: PosType,
2451 ) -> Result<(), LoroError> {
2452 let key: InternalString = key.into();
2453 let is_delete = matches!(value, &LoroValue::Null);
2454 if start >= end {
2455 return Err(loro_common::LoroError::ArgErr(
2456 "Start must be less than end".to_string().into_boxed_str(),
2457 ));
2458 }
2459 ensure_no_regular_container_value(value)?;
2460
2461 let len = state.len(pos_type);
2462 if end > len {
2463 return Err(LoroError::OutOfBound {
2464 pos: end,
2465 len,
2466 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
2467 });
2468 }
2469 let (entity_range, styles) =
2470 state.get_entity_range_and_text_styles_at_range(start..end, pos_type);
2471 // `styles` is None when the range spans multiple style ranges; fall
2472 // back to scanning them so redundant marks are still skipped instead
2473 // of accumulating style anchors.
2474 let already_applied = styles.map(|styles| styles.has_key_value(&key, value));
2475 let already_applied = match already_applied {
2476 Some(applied) => applied,
2477 None => state.range_has_style_key_value(entity_range.clone(), &key, value),
2478 };
2479 if already_applied {
2480 return Ok(());
2481 }
2482
2483 let has_target_style =
2484 state.range_has_style_key(entity_range.clone(), &StyleKey::Key(key.clone()));
2485 let missing_style_key = is_delete && !has_target_style;
2486
2487 if missing_style_key {
2488 return Ok(());
2489 }
2490
2491 let style_op = Arc::new(StyleOp {
2492 lamport: 0,
2493 peer: 0,
2494 cnt: 0,
2495 key,
2496 value: value.clone(),
2497 // TODO: describe this behavior in the document
2498 info: if is_delete {
2499 TextStyleInfoFlag::BOLD.to_delete()
2500 } else {
2501 TextStyleInfoFlag::BOLD
2502 },
2503 });
2504 state.mark_with_entity_index(entity_range, style_op);
2505 Ok(())
2506 }
2507
2508 /// `start` and `end` are interpreted using `pos_type`.
2509 pub fn unmark(
2510 &self,
2511 start: usize,
2512 end: usize,
2513 key: impl Into<InternalString>,
2514 pos_type: PosType,
2515 ) -> LoroResult<()> {
2516 match &self.inner {
2517 MaybeDetached::Detached(t) => self.mark_for_detached(
2518 &mut t.lock().value,
2519 key,
2520 &LoroValue::Null,
2521 start,
2522 end,
2523 pos_type,
2524 ),
2525 MaybeDetached::Attached(a) => a.with_txn(|txn| {
2526 self.mark_with_txn(txn, start, end, key, LoroValue::Null, pos_type)
2527 }),
2528 }
2529 }
2530
2531 /// `start` and `end` are interpreted using `pos_type`.
2532 pub fn mark_with_txn(
2533 &self,
2534 txn: &mut Transaction,
2535 start: usize,
2536 end: usize,
2537 key: impl Into<InternalString>,
2538 value: LoroValue,
2539 pos_type: PosType,
2540 ) -> LoroResult<()> {
2541 if start >= end {
2542 return Err(loro_common::LoroError::ArgErr(
2543 "Start must be less than end".to_string().into_boxed_str(),
2544 ));
2545 }
2546 ensure_no_regular_container_value(&value)?;
2547
2548 let inner = self.inner.try_attached_state()?;
2549 let key: InternalString = key.into();
2550 let is_delete = matches!(&value, &LoroValue::Null);
2551
2552 let mut doc_state = inner.doc.state.lock();
2553 let len = doc_state.with_state_mut(inner.container_idx, |state| {
2554 state.as_richtext_state_mut().unwrap().len(pos_type)
2555 });
2556
2557 if end > len {
2558 return Err(LoroError::OutOfBound {
2559 pos: end,
2560 len,
2561 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
2562 });
2563 }
2564
2565 let (entity_range, skip, missing_style_key, event_start, event_end) = doc_state
2566 .with_state_mut(inner.container_idx, |state| {
2567 let state = state.as_richtext_state_mut().unwrap();
2568 let event_start = state.index_to_event_index(start, pos_type);
2569 let event_end = state.index_to_event_index(end, pos_type);
2570 let (entity_range, styles) =
2571 state.get_entity_range_and_styles_at_range(start..end, pos_type);
2572
2573 // `styles` is None when the range spans multiple style
2574 // ranges; fall back to scanning them so redundant marks are
2575 // still skipped instead of accumulating style anchors.
2576 let skip = match styles
2577 .as_ref()
2578 .map(|styles| styles.has_key_value(&key, &value))
2579 {
2580 Some(skip) => skip,
2581 None => state.has_style_key_value_in_entity_range(
2582 entity_range.clone(),
2583 &key,
2584 &value,
2585 ),
2586 };
2587 let has_target_style = state.has_style_key_in_entity_range(
2588 entity_range.clone(),
2589 &StyleKey::Key(key.clone()),
2590 );
2591 let missing_style_key = is_delete && !has_target_style;
2592
2593 (
2594 entity_range,
2595 skip,
2596 missing_style_key,
2597 event_start,
2598 event_end,
2599 )
2600 });
2601
2602 if skip || missing_style_key {
2603 return Ok(());
2604 }
2605
2606 let entity_start = entity_range.start;
2607 let entity_end = entity_range.end;
2608 let style_config = doc_state.config.text_style_config.read();
2609 let flag = if is_delete {
2610 style_config
2611 .get_style_flag_for_unmark(&key)
2612 .ok_or_else(|| LoroError::StyleConfigMissing(key.clone()))?
2613 } else {
2614 style_config
2615 .get_style_flag(&key)
2616 .ok_or_else(|| LoroError::StyleConfigMissing(key.clone()))?
2617 };
2618
2619 drop(style_config);
2620 drop(doc_state);
2621 txn.apply_local_op(
2622 inner.container_idx,
2623 crate::op::RawOpContent::List(ListOp::StyleStart {
2624 start: entity_start as u32,
2625 end: entity_end as u32,
2626 key: key.clone(),
2627 value: value.clone(),
2628 info: flag,
2629 }),
2630 EventHint::Mark {
2631 start: event_start as u32,
2632 end: event_end as u32,
2633 style: crate::container::richtext::Style { key, data: value },
2634 },
2635 &inner.doc,
2636 )?;
2637
2638 txn.apply_local_op(
2639 inner.container_idx,
2640 crate::op::RawOpContent::List(ListOp::StyleEnd),
2641 EventHint::MarkEnd,
2642 &inner.doc,
2643 )?;
2644
2645 Ok(())
2646 }
2647
2648 pub fn check(&self) {
2649 match &self.inner {
2650 MaybeDetached::Detached(t) => {
2651 let t = t.lock();
2652 t.value.check_consistency_between_content_and_style_ranges();
2653 }
2654 MaybeDetached::Attached(a) => a.with_state(|state| {
2655 state
2656 .as_richtext_state_mut()
2657 .unwrap()
2658 .check_consistency_between_content_and_style_ranges();
2659 }),
2660 }
2661 }
2662
2663 pub fn apply_delta(&self, delta: &[TextDelta]) -> LoroResult<()> {
2664 match &self.inner {
2665 MaybeDetached::Detached(t) => {
2666 let _t = t.lock();
2667 // TODO: implement
2668 Err(LoroError::NotImplemented(
2669 "`apply_delta` on a detached text container",
2670 ))
2671 }
2672 MaybeDetached::Attached(a) => a.with_txn(|txn| self.apply_delta_with_txn(txn, delta)),
2673 }
2674 }
2675
2676 pub fn apply_delta_with_txn(
2677 &self,
2678 txn: &mut Transaction,
2679 delta: &[TextDelta],
2680 ) -> LoroResult<()> {
2681 let mut index = 0;
2682 struct PendingMark {
2683 start: usize,
2684 end: usize,
2685 attributes: FxHashMap<InternalString, LoroValue>,
2686 }
2687 let mut marks: Vec<PendingMark> = Vec::new();
2688 for d in delta {
2689 match d {
2690 TextDelta::Insert { insert, attributes } => {
2691 let insert_len = event_len(insert.as_str());
2692 if insert_len == 0 {
2693 continue;
2694 }
2695
2696 let mut empty_attr = None;
2697 let attr_ref = attributes.as_ref().unwrap_or_else(|| {
2698 empty_attr = Some(FxHashMap::default());
2699 empty_attr.as_ref().unwrap()
2700 });
2701
2702 let end = checked_delta_index_end(index, insert_len, self.len_event())?;
2703 let override_styles = self.insert_with_txn_and_attr(
2704 txn,
2705 index,
2706 insert.as_str(),
2707 Some(attr_ref),
2708 PosType::Event,
2709 )?;
2710
2711 let mut pending_mark = PendingMark {
2712 start: index,
2713 end,
2714 attributes: FxHashMap::default(),
2715 };
2716 for (key, value) in override_styles {
2717 pending_mark.attributes.insert(key, value);
2718 }
2719 marks.push(pending_mark);
2720 index = end;
2721 }
2722 TextDelta::Delete { delete } => {
2723 self.delete_with_txn(txn, index, *delete, PosType::Event)?;
2724 }
2725 TextDelta::Retain { attributes, retain } => {
2726 let end = checked_delta_index_end(index, *retain, self.len_event())?;
2727 match attributes {
2728 Some(attr) if !attr.is_empty() => {
2729 let mut pending_mark = PendingMark {
2730 start: index,
2731 end,
2732 attributes: FxHashMap::default(),
2733 };
2734 for (key, value) in attr {
2735 pending_mark
2736 .attributes
2737 .insert(key.deref().into(), value.clone());
2738 }
2739 marks.push(pending_mark);
2740 }
2741 _ => {}
2742 }
2743 index = end;
2744 }
2745 }
2746 }
2747
2748 let mut len = match &self.inner {
2749 MaybeDetached::Detached(_) => self.len_event(),
2750 MaybeDetached::Attached(a) => {
2751 a.with_state(|state| state.as_richtext_state_mut().unwrap().len(PosType::Event))
2752 }
2753 };
2754 for pending_mark in marks {
2755 if pending_mark.start >= len {
2756 self.insert_with_txn(
2757 txn,
2758 len,
2759 &"\n".repeat(pending_mark.start - len + 1),
2760 PosType::Event,
2761 )?;
2762 len = pending_mark.start;
2763 }
2764
2765 for (key, value) in pending_mark.attributes {
2766 self.mark_with_txn(
2767 txn,
2768 pending_mark.start,
2769 pending_mark.end,
2770 key.deref(),
2771 value,
2772 PosType::Event,
2773 )?;
2774 }
2775 }
2776
2777 Ok(())
2778 }
2779
2780 pub fn update(&self, text: &str, options: UpdateOptions) -> Result<(), UpdateTimeoutError> {
2781 let old_str = self.to_string();
2782 let new = text.chars().map(|x| x as u32).collect::<Vec<u32>>();
2783 let old = old_str.chars().map(|x| x as u32).collect::<Vec<u32>>();
2784 diff(
2785 &mut OperateProxy::new(text_update::DiffHook::new(self, &new)),
2786 options,
2787 &old,
2788 &new,
2789 )?;
2790 Ok(())
2791 }
2792
2793 pub fn update_by_line(
2794 &self,
2795 text: &str,
2796 options: UpdateOptions,
2797 ) -> Result<(), UpdateTimeoutError> {
2798 let hook = text_update::DiffHookForLine::new(self, text);
2799 let old_lines = hook.get_old_arr().to_vec();
2800 let new_lines = hook.get_new_arr().to_vec();
2801 diff(
2802 &mut OperateProxy::new(hook),
2803 options,
2804 &old_lines,
2805 &new_lines,
2806 )
2807 }
2808
2809 #[allow(clippy::inherent_to_string)]
2810 pub fn to_string(&self) -> String {
2811 match &self.inner {
2812 MaybeDetached::Detached(t) => t.lock().value.to_string(),
2813 MaybeDetached::Attached(a) => a.get_value().into_string().unwrap().unwrap(),
2814 }
2815 }
2816
2817 /// Get the deep value of the text with its container id, as a
2818 /// `{ cid, value }` map where `value` is the text content.
2819 pub fn get_deep_value_with_id(&self) -> LoroResult<LoroValue> {
2820 let inner = self.inner.try_attached_state()?;
2821 Ok(inner.with_doc_state(|state| {
2822 state.get_container_deep_value_with_id(inner.container_idx, None)
2823 }))
2824 }
2825
2826 pub fn get_cursor(&self, event_index: usize, side: Side) -> Option<Cursor> {
2827 self.get_cursor_internal(event_index, side, true)
2828 }
2829
2830 /// Get the stable position representation for the target pos
2831 pub(crate) fn get_cursor_internal(
2832 &self,
2833 index: usize,
2834 side: Side,
2835 get_by_event_index: bool,
2836 ) -> Option<Cursor> {
2837 match &self.inner {
2838 MaybeDetached::Detached(_) => None,
2839 MaybeDetached::Attached(a) => {
2840 let (id, len, origin_pos) = a.with_state(|s| {
2841 let s = s.as_richtext_state_mut().unwrap();
2842 (
2843 s.get_stable_position(index, get_by_event_index),
2844 if get_by_event_index {
2845 s.len_event()
2846 } else {
2847 s.len_unicode()
2848 },
2849 if get_by_event_index {
2850 s.event_index_to_unicode_index(index)
2851 } else {
2852 index
2853 },
2854 )
2855 });
2856
2857 if len == 0 {
2858 return Some(Cursor {
2859 id: None,
2860 container: self.id(),
2861 side: if side == Side::Middle {
2862 Side::Left
2863 } else {
2864 side
2865 },
2866 origin_pos: 0,
2867 });
2868 }
2869
2870 if len <= index {
2871 return Some(Cursor {
2872 id: None,
2873 container: self.id(),
2874 side: Side::Right,
2875 origin_pos: len,
2876 });
2877 }
2878
2879 let id = id?;
2880 Some(Cursor {
2881 id: Some(id),
2882 container: self.id(),
2883 side,
2884 origin_pos,
2885 })
2886 }
2887 }
2888 }
2889
2890 pub(crate) fn convert_entity_index_to_event_index(&self, entity_index: usize) -> usize {
2891 match &self.inner {
2892 MaybeDetached::Detached(s) => s.lock().value.entity_index_to_event_index(entity_index),
2893 MaybeDetached::Attached(a) => {
2894 let mut pos = 0;
2895 a.with_state(|s| {
2896 let s = s.as_richtext_state_mut().unwrap();
2897 pos = s.entity_index_to_event_index(entity_index);
2898 });
2899 pos
2900 }
2901 }
2902 }
2903
2904 pub fn get_delta(&self) -> Vec<TextDelta> {
2905 match &self.inner {
2906 MaybeDetached::Detached(s) => {
2907 let mut delta = Vec::new();
2908 for span in s.lock().value.iter() {
2909 if span.text.as_str().is_empty() {
2910 continue;
2911 }
2912
2913 let next_attr = span.attributes.to_option_map();
2914 match delta.last_mut() {
2915 Some(TextDelta::Insert { insert, attributes })
2916 if &next_attr == attributes =>
2917 {
2918 insert.push_str(span.text.as_str());
2919 continue;
2920 }
2921 _ => {}
2922 }
2923
2924 delta.push(TextDelta::Insert {
2925 insert: span.text.as_str().to_string(),
2926 attributes: next_attr,
2927 })
2928 }
2929 delta
2930 }
2931 MaybeDetached::Attached(_a) => self
2932 .with_state(|state| {
2933 let state = state.as_richtext_state_mut().unwrap();
2934 Ok(state.get_delta())
2935 })
2936 .unwrap(),
2937 }
2938 }
2939
2940 pub fn is_deleted(&self) -> bool {
2941 match &self.inner {
2942 MaybeDetached::Detached(_) => false,
2943 MaybeDetached::Attached(a) => a.is_deleted(),
2944 }
2945 }
2946
2947 pub fn push_str(&self, s: &str) -> LoroResult<()> {
2948 self.insert_utf8(self.len_utf8(), s)
2949 }
2950
2951 pub fn clear(&self) -> LoroResult<()> {
2952 match &self.inner {
2953 MaybeDetached::Detached(mutex) => {
2954 let mut t = mutex.lock();
2955 let len = t.value.len_unicode();
2956 let ranges = t.value.get_text_entity_ranges(0, len, PosType::Unicode)?;
2957 for range in ranges.iter().rev() {
2958 t.value
2959 .drain_by_entity_index(range.entity_start, range.entity_len(), None);
2960 }
2961 Ok(())
2962 }
2963 MaybeDetached::Attached(a) => a.with_txn(|txn| {
2964 let len = a.with_state(|s| s.as_richtext_state_mut().unwrap().len_unicode());
2965 self.delete_with_txn_inline(txn, 0, len, PosType::Unicode)
2966 }),
2967 }
2968 }
2969
2970 /// Convert a position `index` from one coordinate system to another.
2971 ///
2972 /// Supported `PosType` conversions: `Event`, `Unicode`, `Utf16`, and `Bytes`.
2973 /// Returns `None` if the index is out of bounds or the conversion is unsupported.
2974 pub fn convert_pos(&self, index: usize, from: PosType, to: PosType) -> Option<usize> {
2975 if from == to {
2976 return Some(index);
2977 }
2978
2979 if matches!(from, PosType::Entity) || matches!(to, PosType::Entity) {
2980 return None;
2981 }
2982
2983 // Normalize to event + unicode indices for the given position.
2984 let (event_index, unicode_index) = match &self.inner {
2985 MaybeDetached::Detached(t) => {
2986 let t = t.lock();
2987 if index > t.value.len(from) {
2988 return None;
2989 }
2990 let event_index = if from == PosType::Event {
2991 index
2992 } else {
2993 t.value.index_to_event_index(index, from)
2994 };
2995 let unicode_index = if from == PosType::Unicode {
2996 index
2997 } else {
2998 t.value.event_index_to_unicode_index(event_index)
2999 };
3000 (event_index, unicode_index)
3001 }
3002 MaybeDetached::Attached(a) if a.has_decoded_state() => {
3003 let res: Option<(usize, usize)> = a.with_state(|state| {
3004 let state = state.as_richtext_state_mut().unwrap();
3005 if index > state.len(from) {
3006 return None;
3007 }
3008
3009 let event_index = if from == PosType::Event {
3010 index
3011 } else {
3012 state.index_to_event_index(index, from)
3013 };
3014 let unicode_index = if from == PosType::Unicode {
3015 index
3016 } else {
3017 state.event_index_to_unicode_index(event_index)
3018 };
3019 Some((event_index, unicode_index))
3020 });
3021
3022 res?
3023 }
3024 MaybeDetached::Attached(a) => {
3025 let value = a.get_value();
3026 let s = value.as_string().unwrap();
3027 let unicode_index = text_pos_to_unicode(s, index, from)?;
3028 let event_index = unicode_to_text_pos(s, unicode_index, PosType::Event)?;
3029 (event_index, unicode_index)
3030 }
3031 };
3032
3033 let result = match to {
3034 PosType::Unicode => Some(unicode_index),
3035 PosType::Event => Some(event_index),
3036 PosType::Bytes | PosType::Utf16 => {
3037 // Map the event-index position onto the target coordinate via the
3038 // rope's prefix caches. This is O(log n); materializing the prefix
3039 // string would be O(n) and makes repeated edits O(n^2).
3040 match &self.inner {
3041 MaybeDetached::Detached(t) => {
3042 let t = t.lock();
3043 if event_index > t.value.len_event() {
3044 return None;
3045 }
3046 Some(t.value.event_index_to_index(event_index, to))
3047 }
3048 MaybeDetached::Attached(a) if a.has_decoded_state() => a.with_state(|state| {
3049 let state = state.as_richtext_state_mut().unwrap();
3050 if event_index > state.len_event() {
3051 return None;
3052 }
3053 Some(state.event_index_to_index(event_index, to))
3054 }),
3055 MaybeDetached::Attached(a) => {
3056 let value = a.get_value();
3057 let s = value.as_string().unwrap();
3058 unicode_to_text_pos(s, unicode_index, to)
3059 }
3060 }
3061 }
3062 PosType::Entity => None,
3063 };
3064 result
3065 }
3066}
3067
3068fn event_len(s: &str) -> usize {
3069 if cfg!(feature = "wasm") {
3070 count_utf16_len(s.as_bytes())
3071 } else {
3072 s.chars().count()
3073 }
3074}
3075
3076fn text_len(s: &str, pos_type: PosType) -> Option<usize> {
3077 Some(match pos_type {
3078 PosType::Bytes => s.len(),
3079 PosType::Unicode => s.chars().count(),
3080 PosType::Utf16 => count_utf16_len(s.as_bytes()),
3081 PosType::Event => event_len(s),
3082 PosType::Entity => return None,
3083 })
3084}
3085
3086fn text_pos_to_unicode(s: &str, index: usize, pos_type: PosType) -> Option<usize> {
3087 match pos_type {
3088 PosType::Unicode => (index <= s.chars().count()).then_some(index),
3089 PosType::Bytes => {
3090 if index > s.len() {
3091 None
3092 } else {
3093 Some(
3094 s.char_indices()
3095 .take_while(|(pos, c)| *pos + c.len_utf8() <= index)
3096 .count(),
3097 )
3098 }
3099 }
3100 PosType::Utf16 => utf16_to_unicode_pos(s, index),
3101 PosType::Event if cfg!(feature = "wasm") => utf16_to_unicode_pos(s, index),
3102 PosType::Event => (index <= s.chars().count()).then_some(index),
3103 PosType::Entity => None,
3104 }
3105}
3106
3107fn unicode_to_text_pos(s: &str, index: usize, pos_type: PosType) -> Option<usize> {
3108 match pos_type {
3109 PosType::Unicode => (index <= s.chars().count()).then_some(index),
3110 PosType::Bytes => unicode_to_byte_pos(s, index),
3111 PosType::Utf16 => unicode_to_utf16_pos(s, index),
3112 PosType::Event if cfg!(feature = "wasm") => unicode_to_utf16_pos(s, index),
3113 PosType::Event => (index <= s.chars().count()).then_some(index),
3114 PosType::Entity => None,
3115 }
3116}
3117
3118fn unicode_to_byte_pos(s: &str, index: usize) -> Option<usize> {
3119 if index == 0 {
3120 return Some(0);
3121 }
3122
3123 let mut unicode_pos = 0;
3124 for (byte_pos, _) in s.char_indices() {
3125 if unicode_pos == index {
3126 return Some(byte_pos);
3127 }
3128 unicode_pos += 1;
3129 }
3130
3131 (unicode_pos == index).then_some(s.len())
3132}
3133
3134fn unicode_to_utf16_pos(s: &str, index: usize) -> Option<usize> {
3135 let mut unicode_pos = 0;
3136 let mut utf16_pos = 0;
3137 if index == 0 {
3138 return Some(0);
3139 }
3140
3141 for c in s.chars() {
3142 unicode_pos += 1;
3143 utf16_pos += c.len_utf16();
3144 if unicode_pos == index {
3145 return Some(utf16_pos);
3146 }
3147 }
3148
3149 (unicode_pos == index).then_some(utf16_pos)
3150}
3151
3152fn utf16_to_unicode_pos(s: &str, index: usize) -> Option<usize> {
3153 let mut unicode_pos = 0;
3154 let mut utf16_pos = 0;
3155 if index == 0 {
3156 return Some(0);
3157 }
3158
3159 for c in s.chars() {
3160 let next_utf16_pos = utf16_pos + c.len_utf16();
3161 if index < next_utf16_pos {
3162 return Some(unicode_pos);
3163 }
3164 if index == next_utf16_pos {
3165 return Some(unicode_pos + 1);
3166 }
3167 utf16_pos = next_utf16_pos;
3168 unicode_pos += 1;
3169 }
3170
3171 (index == utf16_pos).then_some(unicode_pos)
3172}
3173
3174fn text_boundary_error(pos: usize, pos_type: PosType) -> LoroError {
3175 match pos_type {
3176 PosType::Bytes => LoroError::UTF8InUnicodeCodePoint { pos },
3177 PosType::Utf16 => LoroError::UTF16InUnicodeCodePoint { pos },
3178 PosType::Event if cfg!(feature = "wasm") => LoroError::UTF16InUnicodeCodePoint { pos },
3179 _ => LoroError::OutOfBound {
3180 pos,
3181 len: 0,
3182 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3183 },
3184 }
3185}
3186
3187fn text_char_at(s: &str, pos: usize, pos_type: PosType) -> LoroResult<char> {
3188 let len = text_len(s, pos_type).unwrap_or(0);
3189 if pos >= len {
3190 return Err(LoroError::OutOfBound {
3191 pos,
3192 len,
3193 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3194 });
3195 }
3196
3197 let unicode_pos =
3198 text_pos_to_unicode(s, pos, pos_type).ok_or_else(|| text_boundary_error(pos, pos_type))?;
3199 s.chars().nth(unicode_pos).ok_or(LoroError::OutOfBound {
3200 pos,
3201 len,
3202 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3203 })
3204}
3205
3206fn text_slice(s: &str, start: usize, end: usize, pos_type: PosType) -> LoroResult<String> {
3207 if end < start {
3208 return Err(LoroError::EndIndexLessThanStartIndex { start, end });
3209 }
3210 if start == end {
3211 return Ok(String::new());
3212 }
3213
3214 let len = text_len(s, pos_type).unwrap_or(0);
3215 if end > len {
3216 return Err(LoroError::OutOfBound {
3217 pos: end,
3218 len,
3219 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3220 });
3221 }
3222
3223 let start = text_pos_to_unicode(s, start, pos_type)
3224 .ok_or_else(|| text_boundary_error(start, pos_type))?;
3225 let end =
3226 text_pos_to_unicode(s, end, pos_type).ok_or_else(|| text_boundary_error(end, pos_type))?;
3227 let start = unicode_to_byte_pos(s, start).expect("unicode index must map to a byte boundary");
3228 let end = unicode_to_byte_pos(s, end).expect("unicode index must map to a byte boundary");
3229 Ok(s[start..end].to_string())
3230}
3231
3232impl ListHandler {
3233 /// Create a new container that is detached from the document.
3234 /// The edits on a detached container will not be persisted.
3235 /// To attach the container to the document, please insert it into an attached container.
3236 pub fn new_detached() -> Self {
3237 Self {
3238 inner: MaybeDetached::new_detached(Vec::new()),
3239 }
3240 }
3241
3242 pub fn insert(&self, pos: usize, v: impl Into<LoroValue>) -> LoroResult<()> {
3243 match &self.inner {
3244 MaybeDetached::Detached(l) => {
3245 let mut list = l.lock();
3246 let len = list.value.len();
3247 if pos > len {
3248 return Err(LoroError::OutOfBound {
3249 pos,
3250 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3251 len,
3252 });
3253 }
3254 let value = v.into();
3255 ensure_no_regular_container_value(&value)?;
3256 list.value.insert(pos, ValueOrHandler::Value(value));
3257 Ok(())
3258 }
3259 MaybeDetached::Attached(a) => {
3260 a.with_txn(|txn| self.insert_with_txn(txn, pos, v.into()))
3261 }
3262 }
3263 }
3264
3265 pub fn insert_with_txn(
3266 &self,
3267 txn: &mut Transaction,
3268 pos: usize,
3269 v: LoroValue,
3270 ) -> LoroResult<()> {
3271 if pos > self.len() {
3272 return Err(LoroError::OutOfBound {
3273 pos,
3274 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3275 len: self.len(),
3276 });
3277 }
3278
3279 let inner = self.inner.try_attached_state()?;
3280 ensure_no_regular_container_value(&v)?;
3281
3282 txn.apply_local_op(
3283 inner.container_idx,
3284 crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Insert {
3285 slice: ListSlice::RawData(Cow::Owned(vec![v.clone()])),
3286 pos,
3287 }),
3288 EventHint::InsertList { len: 1, pos },
3289 &inner.doc,
3290 )
3291 }
3292
3293 pub fn push(&self, v: impl Into<LoroValue>) -> LoroResult<()> {
3294 match &self.inner {
3295 MaybeDetached::Detached(l) => {
3296 let mut list = l.lock();
3297 let value = v.into();
3298 ensure_no_regular_container_value(&value)?;
3299 list.value.push(ValueOrHandler::Value(value));
3300 Ok(())
3301 }
3302 MaybeDetached::Attached(a) => a.with_txn(|txn| self.push_with_txn(txn, v.into())),
3303 }
3304 }
3305
3306 pub fn push_with_txn(&self, txn: &mut Transaction, v: LoroValue) -> LoroResult<()> {
3307 let pos = self.len();
3308 self.insert_with_txn(txn, pos, v)
3309 }
3310
3311 pub fn pop(&self) -> LoroResult<Option<LoroValue>> {
3312 match &self.inner {
3313 MaybeDetached::Detached(l) => {
3314 let mut list = l.lock();
3315 Ok(list.value.pop().map(|v| v.to_value()))
3316 }
3317 MaybeDetached::Attached(a) => a.with_txn(|txn| self.pop_with_txn(txn)),
3318 }
3319 }
3320
3321 pub fn pop_with_txn(&self, txn: &mut Transaction) -> LoroResult<Option<LoroValue>> {
3322 let len = self.len();
3323 if len == 0 {
3324 return Ok(None);
3325 }
3326
3327 let v = self.get(len - 1);
3328 self.delete_with_txn(txn, len - 1, 1)?;
3329 Ok(v)
3330 }
3331
3332 pub fn insert_container<H: HandlerTrait>(&self, pos: usize, child: H) -> LoroResult<H> {
3333 match &self.inner {
3334 MaybeDetached::Detached(l) => {
3335 let mut list = l.lock();
3336 if pos > list.value.len() {
3337 return Err(LoroError::OutOfBound {
3338 pos,
3339 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3340 len: list.value.len(),
3341 });
3342 }
3343 list.value
3344 .insert(pos, ValueOrHandler::Handler(child.to_handler()));
3345 Ok(child)
3346 }
3347 MaybeDetached::Attached(a) => {
3348 a.with_txn(|txn| self.insert_container_with_txn(txn, pos, child))
3349 }
3350 }
3351 }
3352
3353 pub fn push_container<H: HandlerTrait>(&self, child: H) -> LoroResult<H> {
3354 self.insert_container(self.len(), child)
3355 }
3356
3357 pub fn insert_container_with_txn<H: HandlerTrait>(
3358 &self,
3359 txn: &mut Transaction,
3360 pos: usize,
3361 child: H,
3362 ) -> LoroResult<H> {
3363 if pos > self.len() {
3364 return Err(LoroError::OutOfBound {
3365 pos,
3366 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3367 len: self.len(),
3368 });
3369 }
3370
3371 let inner = self.inner.try_attached_state()?;
3372 ensure_not_attached_to_other_doc(&child, &inner.doc)?;
3373 let id = txn.next_id();
3374 let container_id = ContainerID::new_normal(id, child.kind());
3375 let v = LoroValue::Container(container_id.clone());
3376 txn.apply_local_op(
3377 inner.container_idx,
3378 crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Insert {
3379 slice: ListSlice::RawData(Cow::Owned(vec![v.clone()])),
3380 pos,
3381 }),
3382 EventHint::InsertList { len: 1, pos },
3383 &inner.doc,
3384 )?;
3385 let ans = child.attach(txn, inner, container_id)?;
3386 Ok(ans)
3387 }
3388
3389 pub fn delete(&self, pos: usize, len: usize) -> LoroResult<()> {
3390 match &self.inner {
3391 MaybeDetached::Detached(l) => {
3392 let mut list = l.lock();
3393 let end = checked_range_end(pos, len, list.value.len(), || {
3394 format!("Position: {}:{}", file!(), line!()).into_boxed_str()
3395 })?;
3396 list.value.drain(pos..end);
3397 Ok(())
3398 }
3399 MaybeDetached::Attached(a) => a.with_txn(|txn| self.delete_with_txn(txn, pos, len)),
3400 }
3401 }
3402
3403 pub fn delete_with_txn(&self, txn: &mut Transaction, pos: usize, len: usize) -> LoroResult<()> {
3404 if len == 0 {
3405 return Ok(());
3406 }
3407
3408 let list_len = self.len();
3409 let end = checked_range_end(pos, len, list_len, || {
3410 format!("Position: {}:{}", file!(), line!()).into_boxed_str()
3411 })?;
3412
3413 let inner = self.inner.try_attached_state()?;
3414 let ids: Vec<_> = inner.with_state(|state| {
3415 let list = state.as_list_state().unwrap();
3416 (pos..end).map(|i| list.get_id_at(i).unwrap()).collect()
3417 });
3418
3419 for id in ids.into_iter() {
3420 txn.apply_local_op(
3421 inner.container_idx,
3422 crate::op::RawOpContent::List(ListOp::Delete(DeleteSpanWithId::new(
3423 id.id(),
3424 pos as isize,
3425 1,
3426 ))),
3427 EventHint::DeleteList(DeleteSpan::new(pos as isize, 1)),
3428 &inner.doc,
3429 )?;
3430 }
3431
3432 Ok(())
3433 }
3434
3435 pub fn get_child_handler(&self, index: usize) -> LoroResult<Handler> {
3436 match &self.inner {
3437 MaybeDetached::Detached(l) => {
3438 let list = l.lock();
3439 let value = list.value.get(index).ok_or(LoroError::OutOfBound {
3440 pos: index,
3441 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3442 len: list.value.len(),
3443 })?;
3444 match value {
3445 ValueOrHandler::Handler(h) => Ok(h.clone()),
3446 _ => Err(LoroError::ArgErr(
3447 format!(
3448 "Expected container at index {}, but found {:?}",
3449 index, value
3450 )
3451 .into_boxed_str(),
3452 )),
3453 }
3454 }
3455 MaybeDetached::Attached(_) => {
3456 let Some(value) = self.get_(index) else {
3457 return Err(LoroError::OutOfBound {
3458 pos: index,
3459 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3460 len: self.len(),
3461 });
3462 };
3463 match value {
3464 ValueOrHandler::Handler(handler) => Ok(handler),
3465 ValueOrHandler::Value(value) => Err(LoroError::ArgErr(
3466 format!(
3467 "Expected container at index {}, but found {:?}",
3468 index, value
3469 )
3470 .into_boxed_str(),
3471 )),
3472 }
3473 }
3474 }
3475 }
3476
3477 pub fn len(&self) -> usize {
3478 match &self.inner {
3479 MaybeDetached::Detached(l) => l.lock().value.len(),
3480 MaybeDetached::Attached(a) => {
3481 a.with_doc_state(|state| state.get_list_len(a.container_idx))
3482 }
3483 }
3484 }
3485
3486 pub fn is_empty(&self) -> bool {
3487 self.len() == 0
3488 }
3489
3490 pub fn get_deep_value_with_id(&self) -> LoroResult<LoroValue> {
3491 let inner = self.inner.try_attached_state()?;
3492 Ok(inner.with_doc_state(|state| {
3493 state.get_container_deep_value_with_id(inner.container_idx, None)
3494 }))
3495 }
3496
3497 /// Get the deep value of the elements in the range `[start, end)`.
3498 ///
3499 /// Child containers in the range are recursively resolved to `{ cid, value }`
3500 /// nodes. Out-of-range bounds are clamped to the list length; an empty or
3501 /// inverted range returns an empty list.
3502 pub fn get_slice_deep_value_with_id(&self, start: usize, end: usize) -> LoroResult<LoroValue> {
3503 let inner = self.inner.try_attached_state()?;
3504 Ok(inner.with_doc_state(|state| {
3505 state.get_list_range_deep_value(inner.container_idx, start, end, true)
3506 }))
3507 }
3508
3509 /// Get the deep value of the elements in the range `[start, end)`.
3510 ///
3511 /// Child containers in the range are recursively resolved to their deep value.
3512 /// Out-of-range bounds are clamped to the list length; an empty or inverted
3513 /// range returns an empty list.
3514 pub fn get_slice_deep_value(&self, start: usize, end: usize) -> LoroResult<LoroValue> {
3515 let inner = self.inner.try_attached_state()?;
3516 Ok(inner.with_doc_state(|state| {
3517 state.get_list_range_deep_value(inner.container_idx, start, end, false)
3518 }))
3519 }
3520
3521 pub fn get(&self, index: usize) -> Option<LoroValue> {
3522 match &self.inner {
3523 MaybeDetached::Detached(l) => l.lock().value.get(index).map(|x| x.to_value()),
3524 MaybeDetached::Attached(a) => {
3525 a.with_doc_state(|state| state.get_list_value_at(a.container_idx, index))
3526 }
3527 }
3528 }
3529
3530 /// Get value at given index, if it's a container, return a handler to the container
3531 pub fn get_(&self, index: usize) -> Option<ValueOrHandler> {
3532 match &self.inner {
3533 MaybeDetached::Detached(l) => {
3534 let l = l.lock();
3535 l.value.get(index).cloned()
3536 }
3537 MaybeDetached::Attached(inner) => {
3538 let value = inner
3539 .with_doc_state(|state| state.get_list_value_at(inner.container_idx, index));
3540 value.map(|value| value_to_value_or_handler(inner, value))
3541 }
3542 }
3543 }
3544
3545 pub fn for_each<I>(&self, mut f: I)
3546 where
3547 I: FnMut(ValueOrHandler),
3548 {
3549 match &self.inner {
3550 MaybeDetached::Detached(l) => {
3551 let l = l.lock();
3552 for v in l.value.iter() {
3553 f(v.clone())
3554 }
3555 }
3556 MaybeDetached::Attached(inner) => {
3557 let temp = inner.with_doc_state(|state| {
3558 state
3559 .get_list_values(inner.container_idx)
3560 .into_iter()
3561 .map(|value| value_to_value_or_handler(inner, value))
3562 .collect::<Vec<_>>()
3563 });
3564 for v in temp.into_iter() {
3565 f(v);
3566 }
3567 }
3568 }
3569 }
3570
3571 pub fn get_cursor(&self, pos: usize, side: Side) -> Option<Cursor> {
3572 match &self.inner {
3573 MaybeDetached::Detached(_) => None,
3574 MaybeDetached::Attached(a) => {
3575 let (id, len) = a.with_state(|s| {
3576 let l = s.as_list_state().unwrap();
3577 (l.get_id_at(pos), l.len())
3578 });
3579
3580 if len == 0 {
3581 return Some(Cursor {
3582 id: None,
3583 container: self.id(),
3584 side: if side == Side::Middle {
3585 Side::Left
3586 } else {
3587 side
3588 },
3589 origin_pos: 0,
3590 });
3591 }
3592
3593 if len <= pos {
3594 return Some(Cursor {
3595 id: None,
3596 container: self.id(),
3597 side: Side::Right,
3598 origin_pos: len,
3599 });
3600 }
3601
3602 let id = id?;
3603 Some(Cursor {
3604 id: Some(id.id()),
3605 container: self.id(),
3606 side,
3607 origin_pos: pos,
3608 })
3609 }
3610 }
3611 }
3612
3613 fn apply_delta(
3614 &self,
3615 delta: loro_delta::DeltaRope<
3616 loro_delta::array_vec::ArrayVec<ValueOrHandler, 8>,
3617 crate::event::ListDeltaMeta,
3618 >,
3619 on_container_remap: &mut dyn FnMut(ContainerID, ContainerID),
3620 ) -> LoroResult<()> {
3621 match &self.inner {
3622 MaybeDetached::Detached(_) => unimplemented!(),
3623 MaybeDetached::Attached(_) => {
3624 let mut index = 0;
3625 for item in delta.iter() {
3626 match item {
3627 loro_delta::DeltaItem::Retain { len, .. } => {
3628 index += len;
3629 }
3630 loro_delta::DeltaItem::Replace { value, delete, .. } => {
3631 if *delete > 0 {
3632 self.delete(index, *delete)?;
3633 }
3634
3635 for v in value.iter() {
3636 match v {
3637 ValueOrHandler::Value(LoroValue::Container(old_id)) => {
3638 let new_h = self.insert_container(
3639 index,
3640 Handler::new_unattached(old_id.container_type())?,
3641 )?;
3642 let new_id = new_h.id();
3643 on_container_remap(old_id.clone(), new_id);
3644 }
3645 ValueOrHandler::Handler(h) => {
3646 let old_id = h.id();
3647 let new_h = self.insert_container(
3648 index,
3649 Handler::new_unattached(old_id.container_type())?,
3650 )?;
3651 let new_id = new_h.id();
3652 on_container_remap(old_id, new_id);
3653 }
3654 ValueOrHandler::Value(v) => {
3655 self.insert(index, v.clone())?;
3656 }
3657 }
3658
3659 index += 1;
3660 }
3661 }
3662 }
3663 }
3664 }
3665 }
3666
3667 Ok(())
3668 }
3669
3670 pub fn is_deleted(&self) -> bool {
3671 match &self.inner {
3672 MaybeDetached::Detached(_) => false,
3673 MaybeDetached::Attached(a) => a.is_deleted(),
3674 }
3675 }
3676
3677 pub fn clear(&self) -> LoroResult<()> {
3678 match &self.inner {
3679 MaybeDetached::Detached(l) => {
3680 let mut l = l.lock();
3681 l.value.clear();
3682 Ok(())
3683 }
3684 MaybeDetached::Attached(a) => a.with_txn(|txn| self.clear_with_txn(txn)),
3685 }
3686 }
3687
3688 pub fn clear_with_txn(&self, txn: &mut Transaction) -> LoroResult<()> {
3689 self.delete_with_txn(txn, 0, self.len())
3690 }
3691
3692 pub fn get_id_at(&self, pos: usize) -> Option<ID> {
3693 match &self.inner {
3694 MaybeDetached::Detached(_) => None,
3695 MaybeDetached::Attached(a) => a.with_state(|state| {
3696 state
3697 .as_list_state()
3698 .unwrap()
3699 .get_id_at(pos)
3700 .map(|x| x.id())
3701 }),
3702 }
3703 }
3704}
3705
3706impl MovableListHandler {
3707 pub fn insert(&self, pos: usize, v: impl Into<LoroValue>) -> LoroResult<()> {
3708 match &self.inner {
3709 MaybeDetached::Detached(d) => {
3710 let mut d = d.lock();
3711 if pos > d.value.len() {
3712 return Err(LoroError::OutOfBound {
3713 pos,
3714 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3715 len: d.value.len(),
3716 });
3717 }
3718 let value = v.into();
3719 ensure_no_regular_container_value(&value)?;
3720 d.value.insert(pos, ValueOrHandler::Value(value));
3721 Ok(())
3722 }
3723 MaybeDetached::Attached(a) => {
3724 a.with_txn(|txn| self.insert_with_txn(txn, pos, v.into()))
3725 }
3726 }
3727 }
3728
3729 #[instrument(skip_all)]
3730 pub fn insert_with_txn(
3731 &self,
3732 txn: &mut Transaction,
3733 pos: usize,
3734 v: LoroValue,
3735 ) -> LoroResult<()> {
3736 if pos > self.len() {
3737 return Err(LoroError::OutOfBound {
3738 pos,
3739 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3740 len: self.len(),
3741 });
3742 }
3743
3744 ensure_no_regular_container_value(&v)?;
3745
3746 let op_index = self.with_state(|state| {
3747 let list = state.as_movable_list_state().unwrap();
3748 Ok(list
3749 .convert_index(pos, IndexType::ForUser, IndexType::ForOp)
3750 .unwrap())
3751 })?;
3752
3753 let inner = self.inner.try_attached_state()?;
3754 txn.apply_local_op(
3755 inner.container_idx,
3756 crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Insert {
3757 slice: ListSlice::RawData(Cow::Owned(vec![v.clone()])),
3758 pos: op_index,
3759 }),
3760 EventHint::InsertList { len: 1, pos },
3761 &inner.doc,
3762 )
3763 }
3764
3765 #[inline]
3766 pub fn mov(&self, from: usize, to: usize) -> LoroResult<()> {
3767 match &self.inner {
3768 MaybeDetached::Detached(d) => {
3769 let mut d = d.lock();
3770 if from >= d.value.len() {
3771 return Err(LoroError::OutOfBound {
3772 pos: from,
3773 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3774 len: d.value.len(),
3775 });
3776 }
3777 if to >= d.value.len() {
3778 return Err(LoroError::OutOfBound {
3779 pos: to,
3780 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3781 len: d.value.len(),
3782 });
3783 }
3784 let v = d.value.remove(from);
3785 d.value.insert(to, v);
3786 Ok(())
3787 }
3788 MaybeDetached::Attached(a) => a.with_txn(|txn| self.move_with_txn(txn, from, to)),
3789 }
3790 }
3791
3792 /// Move element from `from` to `to`. After this op, elem will be at pos `to`.
3793 #[instrument(skip_all)]
3794 pub fn move_with_txn(&self, txn: &mut Transaction, from: usize, to: usize) -> LoroResult<()> {
3795 if from == to {
3796 return Ok(());
3797 }
3798
3799 if from >= self.len() {
3800 return Err(LoroError::OutOfBound {
3801 pos: from,
3802 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3803 len: self.len(),
3804 });
3805 }
3806
3807 if to >= self.len() {
3808 return Err(LoroError::OutOfBound {
3809 pos: to,
3810 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3811 len: self.len(),
3812 });
3813 }
3814
3815 let (op_from, op_to, elem_id, value) = self.with_state(|state| {
3816 let list = state.as_movable_list_state().unwrap();
3817 let (elem_id, elem) = list
3818 .get_elem_at_given_pos(from, IndexType::ForUser)
3819 .unwrap();
3820 Ok((
3821 list.convert_index(from, IndexType::ForUser, IndexType::ForOp)
3822 .unwrap(),
3823 list.convert_index(to, IndexType::ForUser, IndexType::ForOp)
3824 .unwrap(),
3825 elem_id,
3826 elem.value().clone(),
3827 ))
3828 })?;
3829
3830 let inner = self.inner.try_attached_state()?;
3831 txn.apply_local_op(
3832 inner.container_idx,
3833 crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Move {
3834 from: op_from as u32,
3835 to: op_to as u32,
3836 elem_id: elem_id.to_id(),
3837 }),
3838 EventHint::Move {
3839 value,
3840 from: from as u32,
3841 to: to as u32,
3842 },
3843 &inner.doc,
3844 )
3845 }
3846
3847 pub fn push(&self, v: LoroValue) -> LoroResult<()> {
3848 match &self.inner {
3849 MaybeDetached::Detached(d) => {
3850 let mut d = d.lock();
3851 d.value.push(v.into());
3852 Ok(())
3853 }
3854 MaybeDetached::Attached(a) => a.with_txn(|txn| self.push_with_txn(txn, v)),
3855 }
3856 }
3857
3858 pub fn push_with_txn(&self, txn: &mut Transaction, v: LoroValue) -> LoroResult<()> {
3859 let pos = self.len();
3860 self.insert_with_txn(txn, pos, v)
3861 }
3862
3863 pub fn pop_(&self) -> LoroResult<Option<ValueOrHandler>> {
3864 match &self.inner {
3865 MaybeDetached::Detached(d) => {
3866 let mut d = d.lock();
3867 Ok(d.value.pop())
3868 }
3869 MaybeDetached::Attached(a) => {
3870 if self.is_empty() {
3871 return Ok(None);
3872 }
3873 let last = self.len() - 1;
3874 let ans = self.get_(last);
3875 a.with_txn(|txn| self.pop_with_txn(txn))?;
3876 Ok(ans)
3877 }
3878 }
3879 }
3880
3881 pub fn pop(&self) -> LoroResult<Option<LoroValue>> {
3882 match &self.inner {
3883 MaybeDetached::Detached(a) => {
3884 let mut a = a.lock();
3885 Ok(a.value.pop().map(|x| x.to_value()))
3886 }
3887 MaybeDetached::Attached(a) => a.with_txn(|txn| self.pop_with_txn(txn)),
3888 }
3889 }
3890
3891 pub fn pop_with_txn(&self, txn: &mut Transaction) -> LoroResult<Option<LoroValue>> {
3892 let len = self.len();
3893 if len == 0 {
3894 return Ok(None);
3895 }
3896
3897 let v = self.get(len - 1);
3898 self.delete_with_txn(txn, len - 1, 1)?;
3899 Ok(v)
3900 }
3901
3902 pub fn insert_container<H: HandlerTrait>(&self, pos: usize, child: H) -> LoroResult<H> {
3903 match &self.inner {
3904 MaybeDetached::Detached(d) => {
3905 let mut d = d.lock();
3906 if pos > d.value.len() {
3907 return Err(LoroError::OutOfBound {
3908 pos,
3909 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3910 len: d.value.len(),
3911 });
3912 }
3913 d.value
3914 .insert(pos, ValueOrHandler::Handler(child.to_handler()));
3915 Ok(child)
3916 }
3917 MaybeDetached::Attached(a) => {
3918 a.with_txn(|txn| self.insert_container_with_txn(txn, pos, child))
3919 }
3920 }
3921 }
3922
3923 pub fn push_container<H: HandlerTrait>(&self, child: H) -> LoroResult<H> {
3924 self.insert_container(self.len(), child)
3925 }
3926
3927 pub fn insert_container_with_txn<H: HandlerTrait>(
3928 &self,
3929 txn: &mut Transaction,
3930 pos: usize,
3931 child: H,
3932 ) -> LoroResult<H> {
3933 if pos > self.len() {
3934 return Err(LoroError::OutOfBound {
3935 pos,
3936 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3937 len: self.len(),
3938 });
3939 }
3940
3941 let op_index = self.with_state(|state| {
3942 let list = state.as_movable_list_state().unwrap();
3943 Ok(list
3944 .convert_index(pos, IndexType::ForUser, IndexType::ForOp)
3945 .unwrap())
3946 })?;
3947
3948 let inner = self.inner.try_attached_state()?;
3949 ensure_not_attached_to_other_doc(&child, &inner.doc)?;
3950 let id = txn.next_id();
3951 let container_id = ContainerID::new_normal(id, child.kind());
3952 let v = LoroValue::Container(container_id.clone());
3953 txn.apply_local_op(
3954 inner.container_idx,
3955 crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Insert {
3956 slice: ListSlice::RawData(Cow::Owned(vec![v.clone()])),
3957 pos: op_index,
3958 }),
3959 EventHint::InsertList { len: 1, pos },
3960 &inner.doc,
3961 )?;
3962 child.attach(txn, inner, container_id)
3963 }
3964
3965 pub fn set(&self, index: usize, value: impl Into<LoroValue>) -> LoroResult<()> {
3966 match &self.inner {
3967 MaybeDetached::Detached(d) => {
3968 let mut d = d.lock();
3969 if index >= d.value.len() {
3970 return Err(LoroError::OutOfBound {
3971 pos: index,
3972 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3973 len: d.value.len(),
3974 });
3975 }
3976 let value = value.into();
3977 ensure_no_regular_container_value(&value)?;
3978 d.value[index] = ValueOrHandler::Value(value);
3979 Ok(())
3980 }
3981 MaybeDetached::Attached(a) => {
3982 a.with_txn(|txn| self.set_with_txn(txn, index, value.into()))
3983 }
3984 }
3985 }
3986
3987 pub fn set_with_txn(
3988 &self,
3989 txn: &mut Transaction,
3990 index: usize,
3991 value: LoroValue,
3992 ) -> LoroResult<()> {
3993 if index >= self.len() {
3994 return Err(LoroError::OutOfBound {
3995 pos: index,
3996 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
3997 len: self.len(),
3998 });
3999 }
4000
4001 let inner = self.inner.try_attached_state()?;
4002 let Some(elem_id) = self.with_state(|state| {
4003 let list = state.as_movable_list_state().unwrap();
4004 Ok(list.get_elem_id_at(index, IndexType::ForUser))
4005 })?
4006 else {
4007 unreachable!()
4008 };
4009 ensure_no_regular_container_value(&value)?;
4010
4011 let op = crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Set {
4012 elem_id: elem_id.to_id(),
4013 value: value.clone(),
4014 });
4015
4016 let hint = EventHint::SetList { index, value };
4017 txn.apply_local_op(inner.container_idx, op, hint, &inner.doc)
4018 }
4019
4020 pub fn set_container<H: HandlerTrait>(&self, pos: usize, child: H) -> LoroResult<H> {
4021 match &self.inner {
4022 MaybeDetached::Detached(d) => {
4023 let mut d = d.lock();
4024 if pos >= d.value.len() {
4025 return Err(LoroError::OutOfBound {
4026 pos,
4027 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
4028 len: d.value.len(),
4029 });
4030 }
4031 d.value[pos] = ValueOrHandler::Handler(child.to_handler());
4032 Ok(child)
4033 }
4034 MaybeDetached::Attached(a) => {
4035 a.with_txn(|txn| self.set_container_with_txn(txn, pos, child))
4036 }
4037 }
4038 }
4039
4040 pub fn set_container_with_txn<H: HandlerTrait>(
4041 &self,
4042 txn: &mut Transaction,
4043 pos: usize,
4044 child: H,
4045 ) -> LoroResult<H> {
4046 let inner = self.inner.try_attached_state()?;
4047 ensure_not_attached_to_other_doc(&child, &inner.doc)?;
4048 let id = txn.next_id();
4049 let container_id = ContainerID::new_normal(id, child.kind());
4050 let v = LoroValue::Container(container_id.clone());
4051 let Some(elem_id) = self.with_state(|state| {
4052 let list = state.as_movable_list_state().unwrap();
4053 Ok(list.get_elem_id_at(pos, IndexType::ForUser))
4054 })?
4055 else {
4056 let len = self.len();
4057 if pos >= len {
4058 return Err(LoroError::OutOfBound {
4059 pos,
4060 len,
4061 info: "".into(),
4062 });
4063 } else {
4064 unreachable!()
4065 }
4066 };
4067 txn.apply_local_op(
4068 inner.container_idx,
4069 crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Set {
4070 elem_id: elem_id.to_id(),
4071 value: v.clone(),
4072 }),
4073 EventHint::SetList {
4074 index: pos,
4075 value: v,
4076 },
4077 &inner.doc,
4078 )?;
4079
4080 child.attach(txn, inner, container_id)
4081 }
4082
4083 pub fn delete(&self, pos: usize, len: usize) -> LoroResult<()> {
4084 match &self.inner {
4085 MaybeDetached::Detached(d) => {
4086 let mut d = d.lock();
4087 let end = checked_range_end(pos, len, d.value.len(), || {
4088 format!("Position: {}:{}", file!(), line!()).into_boxed_str()
4089 })?;
4090 d.value.drain(pos..end);
4091 Ok(())
4092 }
4093 MaybeDetached::Attached(a) => a.with_txn(|txn| self.delete_with_txn(txn, pos, len)),
4094 }
4095 }
4096
4097 #[instrument(skip_all)]
4098 pub fn delete_with_txn(&self, txn: &mut Transaction, pos: usize, len: usize) -> LoroResult<()> {
4099 if len == 0 {
4100 return Ok(());
4101 }
4102
4103 let list_len = self.len();
4104 let end = checked_range_end(pos, len, list_len, || {
4105 format!("Position: {}:{}", file!(), line!()).into_boxed_str()
4106 })?;
4107
4108 let (ids, new_poses) = self.with_state(|state| {
4109 let list = state.as_movable_list_state().unwrap();
4110 let ids: Vec<_> = (pos..end)
4111 .map(|i| list.get_list_id_at(i, IndexType::ForUser).unwrap())
4112 .collect();
4113 let poses: Vec<_> = (pos..end)
4114 // need to -i because we delete the previous ones
4115 .map(|user_index| {
4116 let op_index = list
4117 .convert_index(user_index, IndexType::ForUser, IndexType::ForOp)
4118 .unwrap();
4119 assert!(op_index >= user_index);
4120 op_index - (user_index - pos)
4121 })
4122 .collect();
4123 Ok((ids, poses))
4124 })?;
4125
4126 loro_common::info!(?pos, ?len, ?ids, ?new_poses, "delete_with_txn");
4127 let user_pos = pos;
4128 let inner = self.inner.try_attached_state()?;
4129 for (id, op_pos) in ids.into_iter().zip(new_poses.into_iter()) {
4130 txn.apply_local_op(
4131 inner.container_idx,
4132 crate::op::RawOpContent::List(ListOp::Delete(DeleteSpanWithId::new(
4133 id,
4134 op_pos as isize,
4135 1,
4136 ))),
4137 EventHint::DeleteList(DeleteSpan::new(user_pos as isize, 1)),
4138 &inner.doc,
4139 )?;
4140 }
4141
4142 Ok(())
4143 }
4144
4145 pub fn get_child_handler(&self, index: usize) -> LoroResult<Handler> {
4146 match &self.inner {
4147 MaybeDetached::Detached(l) => {
4148 let list = l.lock();
4149 let value = list.value.get(index).ok_or(LoroError::OutOfBound {
4150 pos: index,
4151 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
4152 len: list.value.len(),
4153 })?;
4154 match value {
4155 ValueOrHandler::Handler(h) => Ok(h.clone()),
4156 _ => Err(LoroError::ArgErr(
4157 format!(
4158 "Expected container at index {}, but found {:?}",
4159 index, value
4160 )
4161 .into_boxed_str(),
4162 )),
4163 }
4164 }
4165 MaybeDetached::Attached(_) => {
4166 let Some(value) = self.get_(index) else {
4167 return Err(LoroError::OutOfBound {
4168 pos: index,
4169 info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(),
4170 len: self.len(),
4171 });
4172 };
4173 match value {
4174 ValueOrHandler::Handler(handler) => Ok(handler),
4175 ValueOrHandler::Value(value) => Err(LoroError::ArgErr(
4176 format!(
4177 "Expected container at index {}, but found {:?}",
4178 index, value
4179 )
4180 .into_boxed_str(),
4181 )),
4182 }
4183 }
4184 }
4185 }
4186
4187 pub fn len(&self) -> usize {
4188 match &self.inner {
4189 MaybeDetached::Detached(d) => {
4190 let d = d.lock();
4191 d.value.len()
4192 }
4193 MaybeDetached::Attached(a) => {
4194 a.with_doc_state(|state| state.get_list_len(a.container_idx))
4195 }
4196 }
4197 }
4198
4199 pub fn is_empty(&self) -> bool {
4200 self.len() == 0
4201 }
4202
4203 pub fn get_deep_value_with_id(&self) -> LoroResult<LoroValue> {
4204 let inner = self.inner.try_attached_state()?;
4205 Ok(inner.with_doc_state(|state| {
4206 state.get_container_deep_value_with_id(inner.container_idx, None)
4207 }))
4208 }
4209
4210 /// Get the deep value of the elements in the range `[start, end)`.
4211 ///
4212 /// Child containers in the range are recursively resolved to `{ cid, value }`
4213 /// nodes. Out-of-range bounds are clamped to the list length; an empty or
4214 /// inverted range returns an empty list.
4215 pub fn get_slice_deep_value_with_id(&self, start: usize, end: usize) -> LoroResult<LoroValue> {
4216 let inner = self.inner.try_attached_state()?;
4217 Ok(inner.with_doc_state(|state| {
4218 state.get_list_range_deep_value(inner.container_idx, start, end, true)
4219 }))
4220 }
4221
4222 /// Get the deep value of the elements in the range `[start, end)`.
4223 ///
4224 /// Child containers in the range are recursively resolved to their deep value.
4225 /// Out-of-range bounds are clamped to the list length; an empty or inverted
4226 /// range returns an empty list.
4227 pub fn get_slice_deep_value(&self, start: usize, end: usize) -> LoroResult<LoroValue> {
4228 let inner = self.inner.try_attached_state()?;
4229 Ok(inner.with_doc_state(|state| {
4230 state.get_list_range_deep_value(inner.container_idx, start, end, false)
4231 }))
4232 }
4233
4234 pub fn get(&self, index: usize) -> Option<LoroValue> {
4235 match &self.inner {
4236 MaybeDetached::Detached(d) => {
4237 let d = d.lock();
4238 d.value.get(index).map(|v| v.to_value())
4239 }
4240 MaybeDetached::Attached(a) => {
4241 a.with_doc_state(|state| state.get_list_value_at(a.container_idx, index))
4242 }
4243 }
4244 }
4245
4246 /// Get value at given index, if it's a container, return a handler to the container
4247 pub fn get_(&self, index: usize) -> Option<ValueOrHandler> {
4248 match &self.inner {
4249 MaybeDetached::Detached(d) => {
4250 let d = d.lock();
4251 d.value.get(index).cloned()
4252 }
4253 MaybeDetached::Attached(m) => {
4254 let value =
4255 m.with_doc_state(|state| state.get_list_value_at(m.container_idx, index));
4256 value.map(|value| value_to_value_or_handler(m, value))
4257 }
4258 }
4259 }
4260
4261 pub fn for_each<I>(&self, mut f: I)
4262 where
4263 I: FnMut(ValueOrHandler),
4264 {
4265 match &self.inner {
4266 MaybeDetached::Detached(d) => {
4267 let d = d.lock();
4268 for v in d.value.iter() {
4269 f(v.clone());
4270 }
4271 }
4272 MaybeDetached::Attached(m) => {
4273 let temp = m.with_doc_state(|state| {
4274 state
4275 .get_list_values(m.container_idx)
4276 .into_iter()
4277 .map(|value| value_to_value_or_handler(m, value))
4278 .collect::<Vec<_>>()
4279 });
4280
4281 for v in temp.into_iter() {
4282 f(v);
4283 }
4284 }
4285 }
4286 }
4287
4288 pub fn log_internal_state(&self) -> String {
4289 match &self.inner {
4290 MaybeDetached::Detached(d) => {
4291 let d = d.lock();
4292 format!("{:#?}", &d.value)
4293 }
4294 MaybeDetached::Attached(a) => a.with_state(|state| {
4295 let a = state.as_movable_list_state().unwrap();
4296 format!("{a:#?}")
4297 }),
4298 }
4299 }
4300
4301 pub fn new_detached() -> MovableListHandler {
4302 MovableListHandler {
4303 inner: MaybeDetached::new_detached(Default::default()),
4304 }
4305 }
4306
4307 pub fn get_cursor(&self, pos: usize, side: Side) -> Option<Cursor> {
4308 match &self.inner {
4309 MaybeDetached::Detached(_) => None,
4310 MaybeDetached::Attached(inner) => {
4311 let (id, len) = inner.with_state(|s| {
4312 let l = s.as_movable_list_state().unwrap();
4313 (l.get_list_item_id_at(pos), l.len())
4314 });
4315
4316 if len == 0 {
4317 return Some(Cursor {
4318 id: None,
4319 container: self.id(),
4320 side: if side == Side::Middle {
4321 Side::Left
4322 } else {
4323 side
4324 },
4325 origin_pos: 0,
4326 });
4327 }
4328
4329 if len <= pos {
4330 return Some(Cursor {
4331 id: None,
4332 container: self.id(),
4333 side: Side::Right,
4334 origin_pos: len,
4335 });
4336 }
4337
4338 let id = id?;
4339 Some(Cursor {
4340 id: Some(id.id()),
4341 container: self.id(),
4342 side,
4343 origin_pos: pos,
4344 })
4345 }
4346 }
4347 }
4348
4349 pub(crate) fn op_pos_to_user_pos(&self, new_pos: usize) -> usize {
4350 match &self.inner {
4351 MaybeDetached::Detached(_) => new_pos,
4352 MaybeDetached::Attached(inner) => {
4353 let mut pos = new_pos;
4354 inner.with_state(|s| {
4355 let l = s.as_movable_list_state().unwrap();
4356 pos = l
4357 .convert_index(new_pos, IndexType::ForOp, IndexType::ForUser)
4358 .unwrap_or(l.len());
4359 });
4360 pos
4361 }
4362 }
4363 }
4364
4365 pub fn is_deleted(&self) -> bool {
4366 match &self.inner {
4367 MaybeDetached::Detached(_) => false,
4368 MaybeDetached::Attached(a) => a.is_deleted(),
4369 }
4370 }
4371
4372 pub fn clear(&self) -> LoroResult<()> {
4373 match &self.inner {
4374 MaybeDetached::Detached(d) => {
4375 let mut d = d.lock();
4376 d.value.clear();
4377 Ok(())
4378 }
4379 MaybeDetached::Attached(a) => a.with_txn(|txn| self.clear_with_txn(txn)),
4380 }
4381 }
4382
4383 pub fn clear_with_txn(&self, txn: &mut Transaction) -> LoroResult<()> {
4384 self.delete_with_txn(txn, 0, self.len())
4385 }
4386
4387 pub fn get_creator_at(&self, pos: usize) -> Option<PeerID> {
4388 match &self.inner {
4389 MaybeDetached::Detached(_) => None,
4390 MaybeDetached::Attached(a) => {
4391 a.with_state(|state| state.as_movable_list_state().unwrap().get_creator_at(pos))
4392 }
4393 }
4394 }
4395
4396 pub fn get_last_mover_at(&self, pos: usize) -> Option<PeerID> {
4397 match &self.inner {
4398 MaybeDetached::Detached(_) => None,
4399 MaybeDetached::Attached(a) => a.with_state(|state| {
4400 state
4401 .as_movable_list_state()
4402 .unwrap()
4403 .get_last_mover_at(pos)
4404 }),
4405 }
4406 }
4407
4408 pub fn get_last_editor_at(&self, pos: usize) -> Option<PeerID> {
4409 match &self.inner {
4410 MaybeDetached::Detached(_) => None,
4411 MaybeDetached::Attached(a) => a.with_state(|state| {
4412 state
4413 .as_movable_list_state()
4414 .unwrap()
4415 .get_last_editor_at(pos)
4416 }),
4417 }
4418 }
4419}
4420
4421impl MapHandler {
4422 /// Create a new container that is detached from the document.
4423 /// The edits on a detached container will not be persisted.
4424 /// To attach the container to the document, please insert it into an attached container.
4425 pub fn new_detached() -> Self {
4426 Self {
4427 inner: MaybeDetached::new_detached(Default::default()),
4428 }
4429 }
4430
4431 pub fn insert(&self, key: &str, value: impl Into<LoroValue>) -> LoroResult<()> {
4432 match &self.inner {
4433 MaybeDetached::Detached(m) => {
4434 let mut m = m.lock();
4435 let value = value.into();
4436 ensure_no_regular_container_value(&value)?;
4437 m.value.insert(key.into(), ValueOrHandler::Value(value));
4438 Ok(())
4439 }
4440 MaybeDetached::Attached(a) => {
4441 a.with_txn(|txn| self.insert_with_txn(txn, key, value.into()))
4442 }
4443 }
4444 }
4445
4446 /// This method will insert the value even if the same value is already in the given entry.
4447 fn insert_without_skipping(&self, key: &str, value: impl Into<LoroValue>) -> LoroResult<()> {
4448 match &self.inner {
4449 MaybeDetached::Detached(m) => {
4450 let mut m = m.lock();
4451 let value = value.into();
4452 ensure_no_regular_container_value(&value)?;
4453 m.value.insert(key.into(), ValueOrHandler::Value(value));
4454 Ok(())
4455 }
4456 MaybeDetached::Attached(a) => a.with_txn(|txn| {
4457 let this = &self;
4458 let value = value.into();
4459 ensure_no_regular_container_value(&value)?;
4460
4461 let inner = this.inner.try_attached_state()?;
4462 txn.apply_local_op(
4463 inner.container_idx,
4464 crate::op::RawOpContent::Map(crate::container::map::MapSet {
4465 key: key.into(),
4466 value: Some(value.clone()),
4467 }),
4468 EventHint::Map {
4469 key: key.into(),
4470 value: Some(value.clone()),
4471 },
4472 &inner.doc,
4473 )
4474 }),
4475 }
4476 }
4477
4478 pub fn insert_with_txn(
4479 &self,
4480 txn: &mut Transaction,
4481 key: &str,
4482 value: LoroValue,
4483 ) -> LoroResult<()> {
4484 ensure_no_regular_container_value(&value)?;
4485
4486 if self.get(key).map(|x| x == value).unwrap_or(false) {
4487 // skip if the value is already set
4488 return Ok(());
4489 }
4490
4491 let inner = self.inner.try_attached_state()?;
4492 txn.apply_local_op(
4493 inner.container_idx,
4494 crate::op::RawOpContent::Map(crate::container::map::MapSet {
4495 key: key.into(),
4496 value: Some(value.clone()),
4497 }),
4498 EventHint::Map {
4499 key: key.into(),
4500 value: Some(value.clone()),
4501 },
4502 &inner.doc,
4503 )
4504 }
4505
4506 pub fn insert_container<T: HandlerTrait>(&self, key: &str, handler: T) -> LoroResult<T> {
4507 match &self.inner {
4508 MaybeDetached::Detached(m) => {
4509 let mut m = m.lock();
4510 let to_insert = handler.to_handler();
4511 m.value
4512 .insert(key.into(), ValueOrHandler::Handler(to_insert.clone()));
4513 Ok(handler)
4514 }
4515 MaybeDetached::Attached(a) => {
4516 a.with_txn(|txn| self.insert_container_with_txn(txn, key, handler))
4517 }
4518 }
4519 }
4520
4521 pub fn insert_container_with_txn<H: HandlerTrait>(
4522 &self,
4523 txn: &mut Transaction,
4524 key: &str,
4525 child: H,
4526 ) -> LoroResult<H> {
4527 let inner = self.inner.try_attached_state()?;
4528 ensure_not_attached_to_other_doc(&child, &inner.doc)?;
4529 let id = txn.next_id();
4530 let container_id = ContainerID::new_normal(id, child.kind());
4531 txn.apply_local_op(
4532 inner.container_idx,
4533 crate::op::RawOpContent::Map(crate::container::map::MapSet {
4534 key: key.into(),
4535 value: Some(LoroValue::Container(container_id.clone())),
4536 }),
4537 EventHint::Map {
4538 key: key.into(),
4539 value: Some(LoroValue::Container(container_id.clone())),
4540 },
4541 &inner.doc,
4542 )?;
4543
4544 child.attach(txn, inner, container_id)
4545 }
4546
4547 pub fn delete(&self, key: &str) -> LoroResult<()> {
4548 match &self.inner {
4549 MaybeDetached::Detached(m) => {
4550 let mut m = m.lock();
4551 m.value.remove(key);
4552 Ok(())
4553 }
4554 MaybeDetached::Attached(a) => a.with_txn(|txn| self.delete_with_txn(txn, key)),
4555 }
4556 }
4557
4558 pub fn delete_with_txn(&self, txn: &mut Transaction, key: &str) -> LoroResult<()> {
4559 let inner = self.inner.try_attached_state()?;
4560 txn.apply_local_op(
4561 inner.container_idx,
4562 crate::op::RawOpContent::Map(crate::container::map::MapSet {
4563 key: key.into(),
4564 value: None,
4565 }),
4566 EventHint::Map {
4567 key: key.into(),
4568 value: None,
4569 },
4570 &inner.doc,
4571 )
4572 }
4573
4574 pub fn for_each<I>(&self, mut f: I)
4575 where
4576 I: FnMut(&str, ValueOrHandler),
4577 {
4578 match &self.inner {
4579 MaybeDetached::Detached(m) => {
4580 let m = m.lock();
4581 for (k, v) in m.value.iter() {
4582 f(k, v.clone());
4583 }
4584 }
4585 MaybeDetached::Attached(inner) => {
4586 let temp = inner.with_doc_state(|state| {
4587 state
4588 .get_map_entries(inner.container_idx)
4589 .into_iter()
4590 .map(|(key, value)| {
4591 let translated = loro_common::translate_mergeable_marker_value(
4592 &inner.id,
4593 key.as_ref(),
4594 value,
4595 );
4596 (
4597 key.to_string(),
4598 value_to_value_or_handler(inner, translated),
4599 )
4600 })
4601 .collect::<Vec<_>>()
4602 });
4603
4604 for (k, v) in temp.into_iter() {
4605 f(&k, v.clone());
4606 }
4607 }
4608 }
4609 }
4610
4611 pub fn get_child_handler(&self, key: &str) -> LoroResult<Handler> {
4612 match &self.inner {
4613 MaybeDetached::Detached(m) => {
4614 let m = m.lock();
4615 let value = m.value.get(key).unwrap();
4616 match value {
4617 ValueOrHandler::Value(v) => Err(LoroError::ArgErr(
4618 format!("Expected Handler but found {:?}", v).into_boxed_str(),
4619 )),
4620 ValueOrHandler::Handler(h) => Ok(h.clone()),
4621 }
4622 }
4623 MaybeDetached::Attached(_) => {
4624 let Some(value) = self.get_(key) else {
4625 return Err(LoroError::ArgErr(
4626 format!("Key {key} does not exist").into_boxed_str(),
4627 ));
4628 };
4629 match value {
4630 ValueOrHandler::Handler(handler) => Ok(handler),
4631 ValueOrHandler::Value(value) => Err(LoroError::ArgErr(
4632 format!("Expected Handler but found {:?}", value).into_boxed_str(),
4633 )),
4634 }
4635 }
4636 }
4637 }
4638
4639 pub fn get_deep_value_with_id(&self) -> LoroResult<LoroValue> {
4640 match &self.inner {
4641 MaybeDetached::Detached(_) => Err(LoroError::MisuseDetachedContainer {
4642 method: "get_deep_value_with_id",
4643 }),
4644 MaybeDetached::Attached(inner) => Ok(inner.with_doc_state(|state| {
4645 state.get_container_deep_value_with_id(inner.container_idx, None)
4646 })),
4647 }
4648 }
4649
4650 pub fn get(&self, key: &str) -> Option<LoroValue> {
4651 match &self.inner {
4652 MaybeDetached::Detached(m) => {
4653 let m = m.lock();
4654 m.value.get(key).map(|v| v.to_value())
4655 }
4656 MaybeDetached::Attached(inner) => {
4657 let value = inner
4658 .with_doc_state(|state| state.get_map_value_by_key(inner.container_idx, key))?;
4659 Some(loro_common::translate_mergeable_marker_value(
4660 &inner.id, key, value,
4661 ))
4662 }
4663 }
4664 }
4665
4666 /// Get the value at given key, if value is a container, return a handler to the container
4667 pub fn get_(&self, key: &str) -> Option<ValueOrHandler> {
4668 match &self.inner {
4669 MaybeDetached::Detached(m) => {
4670 let m = m.lock();
4671 m.value.get(key).cloned()
4672 }
4673 MaybeDetached::Attached(inner) => {
4674 let value = inner
4675 .with_doc_state(|state| state.get_map_value_by_key(inner.container_idx, key))?;
4676 let value = loro_common::translate_mergeable_marker_value(&inner.id, key, value);
4677 Some(value_to_value_or_handler(inner, value))
4678 }
4679 }
4680 }
4681
4682 /// Get or create a regular child container at `key`.
4683 ///
4684 /// This legacy method creates regular op-id child containers when the key is empty or `null`.
4685 /// It is not mergeable: concurrent first creation at the same map key can fork child state and
4686 /// leave one branch hidden by map conflict resolution. Prefer `ensure_mergeable_*` for lazy
4687 /// map-key child creation.
4688 #[deprecated(
4689 note = "use ensure_mergeable_map/list/movable_list/text/tree/counter for lazy map-key child creation; this method creates regular op-id children"
4690 )]
4691 pub fn get_or_create_container<C: HandlerTrait>(&self, key: &str, child: C) -> LoroResult<C> {
4692 if let Some(ans) = self.get_(key) {
4693 if let ValueOrHandler::Handler(h) = ans {
4694 let kind = h.kind();
4695 return C::from_handler(h).ok_or_else(move || {
4696 LoroError::ArgErr(
4697 format!("Expected value type {} but found {:?}", child.kind(), kind)
4698 .into_boxed_str(),
4699 )
4700 });
4701 } else if let ValueOrHandler::Value(LoroValue::Null) = ans {
4702 // do nothing
4703 } else {
4704 return Err(LoroError::ArgErr(
4705 format!("Expected value type {} but found {:?}", child.kind(), ans)
4706 .into_boxed_str(),
4707 ));
4708 }
4709 }
4710
4711 self.insert_container(key, child)
4712 }
4713
4714 /// Shared implementation for all `ensure_mergeable_*` methods.
4715 ///
4716 /// Computes a deterministic [`ContainerID::Root`] in the mergeable namespace from
4717 /// `(parent.id, key, child.kind())` and constructs the handler from it. Two peers calling this
4718 /// with the same `(parent, key, kind)` receive handlers with identical container ids, which is
4719 /// what makes the child container mergeable on concurrent first-write.
4720 ///
4721 /// # Errors
4722 ///
4723 /// Returns [`LoroError::MisuseDetachedContainer`] when called on a detached handler. The
4724 /// deterministic cid is computed from the parent's cid, which a detached parent does not have
4725 /// yet; falling back to a non-deterministic regular child would silently drop the mergeable
4726 /// guarantee at attach time. Detached callers must attach the parent first.
4727 ///
4728 /// Returns [`LoroError::ArgErr`] if the parent slot already holds a non-mergeable value, or if
4729 /// `C::from_handler` rejects the handler built from the deterministic cid (unreachable by
4730 /// construction; guards against future drift between `from_handler` and `kind`).
4731 fn ensure_mergeable_container<C: HandlerTrait>(&self, key: &str, child: C) -> LoroResult<C> {
4732 let MaybeDetached::Attached(parent) = &self.inner else {
4733 return Err(LoroError::MisuseDetachedContainer {
4734 method: "ensure_mergeable_container",
4735 });
4736 };
4737
4738 // Compare against the raw marker bytes (skipping `MapHandler::get`'s user-facing
4739 // marker → Container translation) so the non-mergeable-occupant guard sees the real
4740 // slot value and the same-kind idempotent-skip can match.
4741 let existing_raw =
4742 parent.with_doc_state(|state| state.get_map_value_by_key(parent.container_idx, key));
4743
4744 // A non-mergeable occupant (scalar, arbitrary binary, regular child container) would be
4745 // silently clobbered by the marker write, so reject rather than overwrite under a
4746 // `get_`-named API. Only the exact binary marker for this `(parent, key, kind)` is
4747 // accepted as an existing mergeable occupant.
4748 if let Some(existing) = &existing_raw {
4749 if !matches!(existing, LoroValue::Null)
4750 && loro_common::parse_mergeable_marker(&parent.id, key, existing).is_none()
4751 {
4752 return Err(LoroError::ArgErr(
4753 format!(
4754 "Cannot create a mergeable {} at key {key:?}: the key already holds a non-mergeable value",
4755 child.kind()
4756 )
4757 .into_boxed_str(),
4758 ));
4759 }
4760 }
4761
4762 let cid = ContainerID::new_mergeable(&parent.id, key, child.kind());
4763 let marker = loro_common::mergeable_marker(&parent.id, key, child.kind());
4764
4765 // Idempotent-skip on same marker: `MapHandler::get` translates markers to Container, so
4766 // `insert_with_txn`'s equality check can't see this collision — do it directly.
4767 // A different-kind marker is a deliberate kind change; let the insert through.
4768 if existing_raw.as_ref() != Some(&marker) {
4769 self.insert(key, marker)?;
4770 }
4771
4772 C::from_handler(create_handler(parent, cid.clone())).ok_or_else(|| {
4773 LoroError::ArgErr(
4774 format!(
4775 "Expected value type {} but found {}",
4776 child.kind(),
4777 cid.container_type()
4778 )
4779 .into_boxed_str(),
4780 )
4781 })
4782 }
4783
4784 #[cfg(feature = "counter")]
4785 /// Ensure a mergeable Counter child exists under `key` and return its handler.
4786 ///
4787 /// Returns [`LoroError::MisuseDetachedContainer`] when called on a detached map.
4788 /// Returns [`LoroError::ArgErr`] if the parent slot already holds a non-mergeable value.
4789 /// Repeated same-kind calls are idempotent; different mergeable kinds deliberately rewrite
4790 /// the active marker while preserving each mergeable child's deterministic state.
4791 pub fn ensure_mergeable_counter(&self, key: &str) -> LoroResult<counter::CounterHandler> {
4792 self.ensure_mergeable_container(key, counter::CounterHandler::new_detached())
4793 }
4794
4795 /// Ensure a mergeable Map child exists under `key` and return its handler.
4796 ///
4797 /// Returns [`LoroError::MisuseDetachedContainer`] when called on a detached map.
4798 /// Returns [`LoroError::ArgErr`] if the parent slot already holds a non-mergeable value.
4799 /// Repeated same-kind calls are idempotent; different mergeable kinds deliberately rewrite
4800 /// the active marker while preserving each mergeable child's deterministic state.
4801 ///
4802 /// Prefer to avoid very deep mergeable-map chains: mergeable cids encode their flattened
4803 /// logical path, so cid size still grows with depth and rides through every op/snapshot
4804 /// reference to it. See [`MERGEABLE_NAMESPACE_PREFIX`](loro_common::MERGEABLE_NAMESPACE_PREFIX).
4805 pub fn ensure_mergeable_map(&self, key: &str) -> LoroResult<MapHandler> {
4806 self.ensure_mergeable_container(key, MapHandler::new_detached())
4807 }
4808
4809 /// Ensure a mergeable List child exists under `key` and return its handler.
4810 ///
4811 /// Returns [`LoroError::MisuseDetachedContainer`] when called on a detached map.
4812 /// Returns [`LoroError::ArgErr`] if the parent slot already holds a non-mergeable value.
4813 /// Repeated same-kind calls are idempotent; different mergeable kinds deliberately rewrite
4814 /// the active marker while preserving each mergeable child's deterministic state.
4815 pub fn ensure_mergeable_list(&self, key: &str) -> LoroResult<ListHandler> {
4816 self.ensure_mergeable_container(key, ListHandler::new_detached())
4817 }
4818
4819 /// Ensure a mergeable MovableList child exists under `key` and return its handler.
4820 ///
4821 /// Returns [`LoroError::MisuseDetachedContainer`] when called on a detached map.
4822 /// Returns [`LoroError::ArgErr`] if the parent slot already holds a non-mergeable value.
4823 /// Repeated same-kind calls are idempotent; different mergeable kinds deliberately rewrite
4824 /// the active marker while preserving each mergeable child's deterministic state.
4825 pub fn ensure_mergeable_movable_list(&self, key: &str) -> LoroResult<MovableListHandler> {
4826 self.ensure_mergeable_container(key, MovableListHandler::new_detached())
4827 }
4828
4829 /// Ensure a mergeable Text child exists under `key` and return its handler.
4830 ///
4831 /// Returns [`LoroError::MisuseDetachedContainer`] when called on a detached map.
4832 /// Returns [`LoroError::ArgErr`] if the parent slot already holds a non-mergeable value.
4833 /// Repeated same-kind calls are idempotent; different mergeable kinds deliberately rewrite
4834 /// the active marker while preserving each mergeable child's deterministic state.
4835 pub fn ensure_mergeable_text(&self, key: &str) -> LoroResult<TextHandler> {
4836 self.ensure_mergeable_container(key, TextHandler::new_detached())
4837 }
4838
4839 /// Ensure a mergeable Tree child exists under `key` and return its handler.
4840 ///
4841 /// Returns [`LoroError::MisuseDetachedContainer`] when called on a detached map.
4842 /// Returns [`LoroError::ArgErr`] if the parent slot already holds a non-mergeable value.
4843 /// Repeated same-kind calls are idempotent; different mergeable kinds deliberately rewrite
4844 /// the active marker while preserving each mergeable child's deterministic state.
4845 pub fn ensure_mergeable_tree(&self, key: &str) -> LoroResult<TreeHandler> {
4846 self.ensure_mergeable_container(key, TreeHandler::new_detached())
4847 }
4848
4849 pub fn contains_key(&self, key: &str) -> bool {
4850 self.get(key).is_some()
4851 }
4852
4853 pub fn len(&self) -> usize {
4854 match &self.inner {
4855 MaybeDetached::Detached(m) => m.lock().value.len(),
4856 MaybeDetached::Attached(a) => {
4857 a.with_doc_state(|state| state.get_map_len(a.container_idx))
4858 }
4859 }
4860 }
4861
4862 pub fn is_empty(&self) -> bool {
4863 self.len() == 0
4864 }
4865
4866 pub fn is_deleted(&self) -> bool {
4867 match &self.inner {
4868 MaybeDetached::Detached(_) => false,
4869 MaybeDetached::Attached(a) => a.is_deleted(),
4870 }
4871 }
4872
4873 pub fn clear(&self) -> LoroResult<()> {
4874 match &self.inner {
4875 MaybeDetached::Detached(m) => {
4876 let mut m = m.lock();
4877 m.value.clear();
4878 Ok(())
4879 }
4880 MaybeDetached::Attached(a) => a.with_txn(|txn| self.clear_with_txn(txn)),
4881 }
4882 }
4883
4884 pub fn clear_with_txn(&self, txn: &mut Transaction) -> LoroResult<()> {
4885 let keys: Vec<InternalString> = self.inner.try_attached_state()?.with_state(|state| {
4886 state
4887 .as_map_state()
4888 .unwrap()
4889 .iter()
4890 .map(|(k, _)| k.clone())
4891 .collect()
4892 });
4893
4894 for key in keys {
4895 self.delete_with_txn(txn, &key)?;
4896 }
4897
4898 Ok(())
4899 }
4900
4901 pub fn keys(&self) -> impl Iterator<Item = InternalString> + '_ {
4902 let keys: Vec<InternalString> = match &self.inner {
4903 MaybeDetached::Detached(m) => {
4904 let m = m.lock();
4905 m.value.keys().map(|x| x.as_str().into()).collect()
4906 }
4907 MaybeDetached::Attached(a) => {
4908 a.with_doc_state(|state| state.get_map_keys(a.container_idx))
4909 }
4910 };
4911
4912 keys.into_iter()
4913 }
4914
4915 pub fn values(&self) -> impl Iterator<Item = ValueOrHandler> + '_ {
4916 let values: Vec<ValueOrHandler> = match &self.inner {
4917 MaybeDetached::Detached(m) => {
4918 let m = m.lock();
4919 m.value.values().cloned().collect()
4920 }
4921 MaybeDetached::Attached(a) => a.with_doc_state(|state| {
4922 // A mergeable child's marker lives in the parent map's value table; iterate
4923 // entries (key + value) so the user-boundary translation can resolve each marker
4924 // to the deterministic child cid before wrapping into a handler.
4925 state
4926 .get_map_entries(a.container_idx)
4927 .into_iter()
4928 .map(|(key, value)| {
4929 let translated = loro_common::translate_mergeable_marker_value(
4930 &a.id,
4931 key.as_ref(),
4932 value,
4933 );
4934 value_to_value_or_handler(a, translated)
4935 })
4936 .collect()
4937 }),
4938 };
4939
4940 values.into_iter()
4941 }
4942
4943 pub fn get_last_editor(&self, key: &str) -> Option<PeerID> {
4944 match &self.inner {
4945 MaybeDetached::Detached(_) => None,
4946 MaybeDetached::Attached(a) => a.with_state(|state| {
4947 let m = state.as_map_state().unwrap();
4948 m.get_last_edit_peer(key)
4949 }),
4950 }
4951 }
4952}
4953
4954fn with_txn<R>(doc: &LoroDoc, f: impl FnOnce(&mut Transaction) -> LoroResult<R>) -> LoroResult<R> {
4955 let txn = &doc.txn;
4956 let mut txn = txn.lock();
4957 loop {
4958 if let Some(txn) = &mut *txn {
4959 return f(txn);
4960 } else if cfg!(target_arch = "wasm32") || !doc.can_edit() {
4961 return Err(LoroError::AutoCommitNotStarted);
4962 } else {
4963 drop(txn);
4964 #[cfg(loom)]
4965 loom::thread::yield_now();
4966 doc.start_auto_commit();
4967 txn = doc.txn.lock();
4968 }
4969 }
4970}
4971
4972#[cfg(feature = "counter")]
4973pub mod counter {
4974
4975 use loro_common::LoroResult;
4976
4977 use crate::{
4978 txn::{EventHint, Transaction},
4979 HandlerTrait,
4980 };
4981
4982 use super::{create_handler, Handler, MaybeDetached};
4983
4984 #[derive(Clone)]
4985 pub struct CounterHandler {
4986 pub(super) inner: MaybeDetached<f64>,
4987 }
4988
4989 impl CounterHandler {
4990 pub fn new_detached() -> Self {
4991 Self {
4992 inner: MaybeDetached::new_detached(0.),
4993 }
4994 }
4995
4996 pub fn increment(&self, n: f64) -> LoroResult<()> {
4997 match &self.inner {
4998 MaybeDetached::Detached(d) => {
4999 let d = &mut d.lock().value;
5000 *d += n;
5001 Ok(())
5002 }
5003 MaybeDetached::Attached(a) => a.with_txn(|txn| self.increment_with_txn(txn, n)),
5004 }
5005 }
5006
5007 pub fn decrement(&self, n: f64) -> LoroResult<()> {
5008 match &self.inner {
5009 MaybeDetached::Detached(d) => {
5010 let d = &mut d.lock().value;
5011 *d -= n;
5012 Ok(())
5013 }
5014 MaybeDetached::Attached(a) => a.with_txn(|txn| self.increment_with_txn(txn, -n)),
5015 }
5016 }
5017
5018 fn increment_with_txn(&self, txn: &mut Transaction, n: f64) -> LoroResult<()> {
5019 let inner = self.inner.try_attached_state()?;
5020 txn.apply_local_op(
5021 inner.container_idx,
5022 crate::op::RawOpContent::Counter(n),
5023 EventHint::Counter(n),
5024 &inner.doc,
5025 )
5026 }
5027
5028 pub fn is_deleted(&self) -> bool {
5029 match &self.inner {
5030 MaybeDetached::Detached(_) => false,
5031 MaybeDetached::Attached(a) => a.is_deleted(),
5032 }
5033 }
5034
5035 pub fn clear(&self) -> LoroResult<()> {
5036 self.decrement(self.get_value().into_double().unwrap())
5037 }
5038 }
5039
5040 impl std::fmt::Debug for CounterHandler {
5041 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5042 match &self.inner {
5043 MaybeDetached::Detached(_) => write!(f, "CounterHandler Detached"),
5044 MaybeDetached::Attached(a) => write!(f, "CounterHandler {}", a.id),
5045 }
5046 }
5047 }
5048
5049 impl HandlerTrait for CounterHandler {
5050 fn is_attached(&self) -> bool {
5051 matches!(&self.inner, MaybeDetached::Attached(..))
5052 }
5053
5054 fn attached_handler(&self) -> Option<&crate::BasicHandler> {
5055 self.inner.attached_handler()
5056 }
5057
5058 fn get_value(&self) -> loro_common::LoroValue {
5059 match &self.inner {
5060 MaybeDetached::Detached(t) => {
5061 let t = t.lock();
5062 t.value.into()
5063 }
5064 MaybeDetached::Attached(a) => a.get_value(),
5065 }
5066 }
5067
5068 fn get_deep_value(&self) -> loro_common::LoroValue {
5069 self.get_value()
5070 }
5071
5072 fn kind(&self) -> loro_common::ContainerType {
5073 loro_common::ContainerType::Counter
5074 }
5075
5076 fn to_handler(&self) -> super::Handler {
5077 Handler::Counter(self.clone())
5078 }
5079
5080 fn from_handler(h: super::Handler) -> Option<Self> {
5081 match h {
5082 Handler::Counter(x) => Some(x),
5083 _ => None,
5084 }
5085 }
5086
5087 fn attach(
5088 &self,
5089 txn: &mut crate::txn::Transaction,
5090 parent: &crate::BasicHandler,
5091 self_id: loro_common::ContainerID,
5092 ) -> loro_common::LoroResult<Self> {
5093 match &self.inner {
5094 MaybeDetached::Detached(v) => {
5095 let mut v = v.lock();
5096 let inner = create_handler(parent, self_id);
5097 let c = inner.into_counter().unwrap();
5098
5099 c.increment_with_txn(txn, v.value)?;
5100
5101 v.attached = c.attached_handler().cloned();
5102 Ok(c)
5103 }
5104 MaybeDetached::Attached(a) => {
5105 let new_inner = create_handler(a, self_id);
5106 let ans = new_inner.into_counter().unwrap();
5107 let delta = *self.get_value().as_double().unwrap();
5108 ans.increment_with_txn(txn, delta)?;
5109 Ok(ans)
5110 }
5111 }
5112 }
5113
5114 fn get_attached(&self) -> Option<Self> {
5115 match &self.inner {
5116 MaybeDetached::Attached(a) => Some(Self {
5117 inner: MaybeDetached::Attached(a.clone()),
5118 }),
5119 MaybeDetached::Detached(v) => v.lock().attached.clone().map(|x| Self {
5120 inner: MaybeDetached::Attached(x),
5121 }),
5122 }
5123 }
5124
5125 fn doc(&self) -> Option<crate::LoroDoc> {
5126 match &self.inner {
5127 MaybeDetached::Detached(_) => None,
5128 MaybeDetached::Attached(a) => Some(a.doc()),
5129 }
5130 }
5131 }
5132}
5133
5134#[cfg(test)]
5135mod test {
5136 use std::borrow::Cow;
5137
5138 use super::{
5139 Handler, HandlerTrait, ListHandler, MapHandler, MovableListHandler, TextDelta, TextHandler,
5140 ValueOrHandler,
5141 };
5142 use crate::container::list::list_op::ListOp;
5143 use crate::cursor::PosType;
5144 use crate::loro::ExportMode;
5145 use crate::op::ListSlice;
5146 use crate::state::TreeParentId;
5147 use crate::txn::EventHint;
5148 use crate::version::Frontiers;
5149 use crate::LoroDoc;
5150 use crate::{fx_map, ToJson};
5151 use loro_common::{ContainerID, ContainerType, LoroError, LoroValue, ID};
5152 use serde_json::json;
5153
5154 fn recheck_fast_blob(mut bytes: Vec<u8>) -> Vec<u8> {
5155 let checksum = xxhash_rust::xxh32::xxh32(&bytes[20..], u32::from_le_bytes(*b"LORO"));
5156 bytes[16..20].copy_from_slice(&checksum.to_le_bytes());
5157 bytes
5158 }
5159
5160 fn replace_fast_snapshot_state_bytes(mut snapshot: Vec<u8>, state_bytes: &[u8]) -> Vec<u8> {
5161 let mut body = &snapshot[22..];
5162 let oplog_len = u32::from_le_bytes(body[..4].try_into().unwrap()) as usize;
5163 body = &body[4 + oplog_len..];
5164 let old_state_len = u32::from_le_bytes(body[..4].try_into().unwrap()) as usize;
5165 let state_len_pos = 22 + 4 + oplog_len;
5166 let state_start = state_len_pos + 4;
5167 let state_end = state_start + old_state_len;
5168 snapshot[state_len_pos..state_start]
5169 .copy_from_slice(&(state_bytes.len() as u32).to_le_bytes());
5170 snapshot.splice(state_start..state_end, state_bytes.iter().copied());
5171 recheck_fast_blob(snapshot)
5172 }
5173
5174 fn insert_many_with_single_list_op(
5175 txn: &mut crate::txn::Transaction,
5176 list: &crate::handler::ListHandler,
5177 pos: usize,
5178 values: Vec<LoroValue>,
5179 ) {
5180 let len = values.len();
5181 let inner = list.inner.try_attached_state().unwrap();
5182 txn.apply_local_op(
5183 inner.container_idx,
5184 crate::op::RawOpContent::List(ListOp::Insert {
5185 slice: ListSlice::RawData(Cow::Owned(values)),
5186 pos,
5187 }),
5188 EventHint::InsertList {
5189 len: len as u32,
5190 pos,
5191 },
5192 &inner.doc,
5193 )
5194 .unwrap();
5195 }
5196
5197 #[test]
5198 fn richtext_handler() {
5199 let loro = LoroDoc::new();
5200 loro.set_peer_id(1).unwrap();
5201 let loro2 = LoroDoc::new();
5202 loro2.set_peer_id(2).unwrap();
5203
5204 let mut txn = loro.txn().unwrap();
5205 let text = txn.get_text("hello");
5206 text.insert_with_txn(&mut txn, 0, "hello", PosType::Unicode)
5207 .unwrap();
5208 txn.commit().unwrap();
5209 let exported = loro.export(ExportMode::all_updates()).unwrap();
5210
5211 loro2.import(&exported).unwrap();
5212 let mut txn = loro2.txn().unwrap();
5213 let text = txn.get_text("hello");
5214 assert_eq!(&**text.get_value().as_string().unwrap(), "hello");
5215 text.insert_with_txn(&mut txn, 5, " world", PosType::Unicode)
5216 .unwrap();
5217 assert_eq!(&**text.get_value().as_string().unwrap(), "hello world");
5218 txn.commit().unwrap();
5219
5220 loro.import(&loro2.export(ExportMode::all_updates()).unwrap())
5221 .unwrap();
5222 let txn = loro.txn().unwrap();
5223 let text = txn.get_text("hello");
5224 assert_eq!(&**text.get_value().as_string().unwrap(), "hello world");
5225 txn.commit().unwrap();
5226
5227 // test checkout
5228 loro.checkout(&Frontiers::from_id(ID::new(2, 1))).unwrap();
5229 assert_eq!(&**text.get_value().as_string().unwrap(), "hello w");
5230 }
5231
5232 #[test]
5233 fn richtext_handler_concurrent() {
5234 let loro = LoroDoc::new();
5235 let mut txn = loro.txn().unwrap();
5236 let handler = loro.get_text("richtext");
5237 handler
5238 .insert_with_txn(&mut txn, 0, "hello", PosType::Unicode)
5239 .unwrap();
5240 txn.commit().unwrap();
5241 for i in 0..100 {
5242 let new_loro = LoroDoc::new();
5243 new_loro
5244 .import(&loro.export(ExportMode::all_updates()).unwrap())
5245 .unwrap();
5246 let mut txn = new_loro.txn().unwrap();
5247 let handler = new_loro.get_text("richtext");
5248 handler
5249 .insert_with_txn(&mut txn, i % 5, &i.to_string(), PosType::Unicode)
5250 .unwrap();
5251 txn.commit().unwrap();
5252 loro.import(
5253 &new_loro
5254 .export(ExportMode::updates(&loro.oplog_vv()))
5255 .unwrap(),
5256 )
5257 .unwrap();
5258 }
5259 }
5260
5261 #[test]
5262 fn cross_doc_txn_is_rejected() {
5263 // `insert_with_txn`/`delete_with_txn` are public API, so a transaction
5264 // from one document can be fed to another document's handler. That must
5265 // be rejected with `UnmatchedContext` rather than silently stamping the
5266 // target doc's state/oplog with the wrong peer+counter. Regression test
5267 // for the always-on (release included) context check in
5268 // `Transaction::apply_local_op`.
5269 let doc_a = LoroDoc::new();
5270 doc_a.set_peer_id(1).unwrap();
5271 let doc_b = LoroDoc::new();
5272 doc_b.set_peer_id(2).unwrap();
5273
5274 // Seed doc_b so it has real state we can prove stays untouched.
5275 {
5276 let mut txn_b = doc_b.txn().unwrap();
5277 doc_b
5278 .get_text("text")
5279 .insert_with_txn(&mut txn_b, 0, "ok", PosType::Unicode)
5280 .unwrap();
5281 txn_b.commit().unwrap();
5282 }
5283 let vv_before = doc_b.oplog_vv();
5284
5285 // Feed doc_a's transaction to doc_b's handler.
5286 let mut txn_a = doc_a.txn().unwrap();
5287 let text_b = doc_b.get_text("text");
5288 let insert_err = text_b
5289 .insert_with_txn(&mut txn_a, 0, "x", PosType::Unicode)
5290 .unwrap_err();
5291 assert!(matches!(insert_err, LoroError::UnmatchedContext { .. }));
5292 let delete_err = text_b
5293 .delete_with_txn(&mut txn_a, 0, 1, PosType::Unicode)
5294 .unwrap_err();
5295 assert!(matches!(delete_err, LoroError::UnmatchedContext { .. }));
5296 txn_a.commit().unwrap();
5297
5298 // doc_b is unchanged: content and version vector identical.
5299 assert_eq!(&**text_b.get_value().as_string().unwrap(), "ok");
5300 assert_eq!(doc_b.oplog_vv(), vv_before);
5301 }
5302
5303 #[test]
5304 fn list_import_batch_stays_consistent_after_repeated_tail_splits() {
5305 let doc_a = LoroDoc::new();
5306 doc_a.set_peer_id(1).unwrap();
5307 let mut txn = doc_a.txn().unwrap();
5308 let list_a = txn.get_list("list");
5309 insert_many_with_single_list_op(
5310 &mut txn,
5311 &list_a,
5312 0,
5313 (0..300).map(|i| LoroValue::I64(i)).collect(),
5314 );
5315 txn.commit().unwrap();
5316
5317 let doc_b = LoroDoc::new();
5318 doc_b.set_peer_id(2).unwrap();
5319 doc_b
5320 .import(&doc_a.export(ExportMode::all_updates()).unwrap())
5321 .unwrap();
5322
5323 let list_b = doc_b.get_list("list");
5324 let mut vv = doc_a.oplog_vv();
5325 let mut updates = Vec::new();
5326 for (i, pos) in [100, 201, 252, 278].into_iter().enumerate() {
5327 list_b.insert(pos, 1000 + i as i64).unwrap();
5328 updates.push(doc_b.export(ExportMode::updates(&vv)).unwrap());
5329 vv = doc_b.oplog_vv();
5330 }
5331
5332 doc_a.import_batch(&updates).unwrap();
5333 doc_a.check_state_diff_calc_consistency_slow();
5334 doc_b.check_state_diff_calc_consistency_slow();
5335 assert_eq!(doc_a.get_deep_value(), doc_b.get_deep_value());
5336 }
5337
5338 #[test]
5339 fn richtext_handler_mark() {
5340 let loro = LoroDoc::new_auto_commit();
5341 let handler = loro.get_text("richtext");
5342 handler.insert(0, "hello world", PosType::Unicode).unwrap();
5343 handler
5344 .mark(0, 5, "bold", true.into(), PosType::Event)
5345 .unwrap();
5346 loro.commit_then_renew();
5347
5348 // assert has bold
5349 let value = handler.get_richtext_value();
5350 assert_eq!(value[0]["insert"], "hello".into());
5351 let meta = value[0]["attributes"].as_map().unwrap();
5352 assert_eq!(meta.len(), 1);
5353 meta.get("bold").unwrap();
5354
5355 let loro2 = LoroDoc::new_auto_commit();
5356 loro2
5357 .import(&loro.export(ExportMode::all_updates()).unwrap())
5358 .unwrap();
5359 let handler2 = loro2.get_text("richtext");
5360 assert_eq!(&**handler2.get_value().as_string().unwrap(), "hello world");
5361
5362 // assert has bold
5363 let value = handler2.get_richtext_value();
5364 assert_eq!(value[0]["insert"], "hello".into());
5365 let meta = value[0]["attributes"].as_map().unwrap();
5366 assert_eq!(meta.len(), 1);
5367 meta.get("bold").unwrap();
5368
5369 // insert after bold should be bold
5370 {
5371 handler2.insert(5, " new", PosType::Unicode).unwrap();
5372 let value = handler2.get_richtext_value();
5373 assert_eq!(
5374 value.to_json_value(),
5375 serde_json::json!([
5376 {"insert": "hello new", "attributes": {"bold": true}},
5377 {"insert": " world"}
5378 ])
5379 );
5380 }
5381 }
5382
5383 #[test]
5384 fn richtext_snapshot() {
5385 let loro = LoroDoc::new();
5386 let mut txn = loro.txn().unwrap();
5387 let handler = loro.get_text("richtext");
5388 handler
5389 .insert_with_txn(&mut txn, 0, "hello world", PosType::Unicode)
5390 .unwrap();
5391 handler
5392 .mark_with_txn(&mut txn, 0, 5, "bold", true.into(), PosType::Event)
5393 .unwrap();
5394 txn.commit().unwrap();
5395
5396 let loro2 = LoroDoc::new();
5397 loro2
5398 .import(&loro.export(ExportMode::snapshot()).unwrap())
5399 .unwrap();
5400 let handler2 = loro2.get_text("richtext");
5401 assert_eq!(
5402 handler2.get_richtext_value().to_json_value(),
5403 serde_json::json!([
5404 {"insert": "hello", "attributes": {"bold": true}},
5405 {"insert": " world"}
5406 ])
5407 );
5408 }
5409
5410 #[test]
5411 fn text_snapshot_string_queries_do_not_decode_state() {
5412 let loro = LoroDoc::new_auto_commit();
5413 let text = loro.get_text("text");
5414 text.insert(0, "a😀文", PosType::Unicode).unwrap();
5415 text.mark(1, 3, "bold", true.into(), PosType::Unicode)
5416 .unwrap();
5417
5418 let restored = LoroDoc::new();
5419 restored
5420 .import(&loro.export(ExportMode::snapshot()).unwrap())
5421 .unwrap();
5422 let text = restored.get_text("text");
5423 assert!(!text.attached_handler().unwrap().has_decoded_state());
5424
5425 assert_eq!(text.len_unicode(), 3);
5426 assert_eq!(text.len_utf16(), 4);
5427 assert_eq!(text.len_utf8(), "a😀文".len());
5428 assert_eq!(text.char_at(1, PosType::Unicode).unwrap(), '😀');
5429 assert_eq!(text.slice(1, 3, PosType::Unicode).unwrap(), "😀文");
5430 assert_eq!(
5431 text.convert_pos(2, PosType::Unicode, PosType::Utf16),
5432 Some(3)
5433 );
5434 assert!(matches!(
5435 text.delete_utf16(2, 1),
5436 Err(LoroError::UTF16InUnicodeCodePoint { pos: 2 })
5437 ));
5438 assert!(matches!(
5439 text.delete_utf8(2, 1),
5440 Err(LoroError::UTF8InUnicodeCodePoint { pos: 2 })
5441 ));
5442 assert!(matches!(
5443 text.slice_delta(2, 3, PosType::Utf16),
5444 Err(LoroError::UTF16InUnicodeCodePoint { pos: 2 })
5445 ));
5446 assert!(matches!(
5447 text.slice_delta(2, 3, PosType::Bytes),
5448 Err(LoroError::UTF8InUnicodeCodePoint { pos: 2 })
5449 ));
5450 assert!(!text.attached_handler().unwrap().has_decoded_state());
5451
5452 assert_eq!(text.get_delta().len(), 2);
5453 assert!(text.attached_handler().unwrap().has_decoded_state());
5454 }
5455
5456 #[test]
5457 fn text_lazy_event_queries_match_decoded_state() {
5458 let loro = LoroDoc::new_auto_commit();
5459 let text = loro.get_text("text");
5460 text.insert(0, "ab😀cd", PosType::Unicode).unwrap();
5461 text.mark(1, 4, "bold", true.into(), PosType::Unicode)
5462 .unwrap();
5463 text.mark(2, 3, "link", "x".into(), PosType::Unicode)
5464 .unwrap();
5465
5466 let lazy_doc = LoroDoc::new();
5467 lazy_doc
5468 .import(&loro.export(ExportMode::snapshot()).unwrap())
5469 .unwrap();
5470 let lazy_text = lazy_doc.get_text("text");
5471
5472 let decoded_doc = LoroDoc::new();
5473 decoded_doc
5474 .import(&loro.export(ExportMode::snapshot()).unwrap())
5475 .unwrap();
5476 let decoded_text = decoded_doc.get_text("text");
5477 decoded_text.get_delta();
5478
5479 assert!(!lazy_text.attached_handler().unwrap().has_decoded_state());
5480 assert!(decoded_text.attached_handler().unwrap().has_decoded_state());
5481
5482 for pos_type in [
5483 PosType::Event,
5484 PosType::Unicode,
5485 PosType::Utf16,
5486 PosType::Bytes,
5487 ] {
5488 assert_eq!(lazy_text.len(pos_type), decoded_text.len(pos_type));
5489 for pos in 0..=decoded_text.len(pos_type) {
5490 assert_eq!(
5491 lazy_text.convert_pos(pos, pos_type, PosType::Unicode),
5492 decoded_text.convert_pos(pos, pos_type, PosType::Unicode),
5493 "convert {pos_type:?} pos {pos} to unicode"
5494 );
5495 assert_eq!(
5496 lazy_text.convert_pos(pos, pos_type, PosType::Event),
5497 decoded_text.convert_pos(pos, pos_type, PosType::Event),
5498 "convert {pos_type:?} pos {pos} to event"
5499 );
5500 if pos < decoded_text.len(pos_type) {
5501 assert_eq!(
5502 lazy_text.char_at(pos, pos_type),
5503 decoded_text.char_at(pos, pos_type),
5504 "char_at {pos_type:?} pos {pos}"
5505 );
5506 }
5507 for end in pos..=decoded_text.len(pos_type) {
5508 assert_eq!(
5509 lazy_text.slice(pos, end, pos_type),
5510 decoded_text.slice(pos, end, pos_type),
5511 "slice {pos_type:?} {pos}..{end}"
5512 );
5513 }
5514 }
5515 }
5516 }
5517
5518 #[test]
5519 fn deep_value_with_id_uses_lazy_values_for_snapshot_roots() {
5520 let loro = LoroDoc::new_auto_commit();
5521 let text = loro.get_text("text");
5522 text.insert(0, "hello", PosType::Unicode).unwrap();
5523 let map = loro.get_map("map");
5524 map.insert("key", "value").unwrap();
5525 let list = loro.get_list("list");
5526 list.push("item").unwrap();
5527
5528 let restored = LoroDoc::new();
5529 restored
5530 .import(&loro.export(ExportMode::snapshot()).unwrap())
5531 .unwrap();
5532 let text = restored.get_text("text");
5533 let map = restored.get_map("map");
5534 let list = restored.get_list("list");
5535
5536 let value = restored.get_deep_value_with_id();
5537 assert_eq!(value["text"]["value"], "hello".into());
5538 assert_eq!(value["map"]["value"]["key"], "value".into());
5539 assert_eq!(value["list"]["value"][0], "item".into());
5540 assert!(!text.attached_handler().unwrap().has_decoded_state());
5541 assert!(!map.attached_handler().unwrap().has_decoded_state());
5542 assert!(!list.attached_handler().unwrap().has_decoded_state());
5543 }
5544
5545 #[test]
5546 fn lazy_value_reads_do_not_write_stale_snapshot_after_mutation() {
5547 let loro = LoroDoc::new_auto_commit();
5548 let map = loro.get_map("map");
5549 map.insert("key", "old").unwrap();
5550 let child = map
5551 .insert_container("child", MapHandler::new_detached())
5552 .unwrap();
5553 child.insert("nested", "old").unwrap();
5554 let list = loro.get_list("list");
5555 list.push("old").unwrap();
5556 let child_list = list.push_container(ListHandler::new_detached()).unwrap();
5557 child_list.push("nested-old").unwrap();
5558
5559 let restored = LoroDoc::new();
5560 restored
5561 .import(&loro.export(ExportMode::snapshot()).unwrap())
5562 .unwrap();
5563 let map = restored.get_map("map");
5564 let list = restored.get_list("list");
5565
5566 assert_eq!(map.get("key").unwrap(), "old".into());
5567 assert_eq!(list.get(0).unwrap(), "old".into());
5568 let child = match map.get_("child").unwrap() {
5569 ValueOrHandler::Handler(handler) => handler.into_map().unwrap(),
5570 ValueOrHandler::Value(value) => panic!("expected child map, got {value:?}"),
5571 };
5572 let child_list = match list.get_(1).unwrap() {
5573 ValueOrHandler::Handler(handler) => handler.into_list().unwrap(),
5574 ValueOrHandler::Value(value) => panic!("expected child list, got {value:?}"),
5575 };
5576
5577 map.insert("key", "new").unwrap();
5578 child.insert("nested", "new").unwrap();
5579 list.delete(0, 1).unwrap();
5580 list.insert(0, "new").unwrap();
5581 child_list.delete(0, 1).unwrap();
5582 child_list.insert(0, "nested-new").unwrap();
5583 restored.commit_then_renew();
5584
5585 let roundtrip = LoroDoc::new();
5586 roundtrip
5587 .import(&restored.export(ExportMode::snapshot()).unwrap())
5588 .unwrap();
5589 assert_eq!(
5590 roundtrip.get_deep_value().to_json_value(),
5591 serde_json::json!({
5592 "map": { "key": "new", "child": { "nested": "new" } },
5593 "list": ["new", ["nested-new"]]
5594 })
5595 );
5596 }
5597
5598 #[test]
5599 fn fast_snapshot_with_trailing_bytes_is_rejected_on_import() {
5600 let loro = LoroDoc::new_auto_commit();
5601 let map = loro.get_map("map");
5602 map.insert("key", "value").unwrap();
5603 let mut snapshot = loro.export(ExportMode::snapshot()).unwrap();
5604 snapshot.push(0xff);
5605 let corrupted = recheck_fast_blob(snapshot);
5606
5607 let doc = LoroDoc::new();
5608 assert!(doc.import(&corrupted).is_err());
5609 }
5610
5611 #[test]
5612 fn fast_snapshot_with_trailing_bytes_is_rejected_by_meta_decoder() {
5613 let loro = LoroDoc::new_auto_commit();
5614 let map = loro.get_map("map");
5615 map.insert("key", "value").unwrap();
5616 let mut snapshot = loro.export(ExportMode::snapshot()).unwrap();
5617 snapshot.push(0xff);
5618 let corrupted = recheck_fast_blob(snapshot);
5619
5620 assert!(LoroDoc::decode_import_blob_meta(&corrupted, true).is_err());
5621 }
5622
5623 #[test]
5624 fn fast_snapshot_empty_sstable_meta_is_rejected_on_import() {
5625 let loro = LoroDoc::new_auto_commit();
5626 let map = loro.get_map("map");
5627 map.insert("key", "value").unwrap();
5628 let snapshot = loro.export(ExportMode::snapshot()).unwrap();
5629
5630 let mut malformed_state = Vec::new();
5631 malformed_state.extend_from_slice(b"LORO");
5632 malformed_state.push(0);
5633 malformed_state.extend_from_slice(&0u32.to_le_bytes());
5634 let checksum = xxhash_rust::xxh32::xxh32(&[], u32::from_le_bytes(*b"LORO"));
5635 malformed_state.extend_from_slice(&checksum.to_le_bytes());
5636 malformed_state.extend_from_slice(&5u32.to_le_bytes());
5637 let corrupted = replace_fast_snapshot_state_bytes(snapshot, &malformed_state);
5638
5639 let doc = LoroDoc::new();
5640 assert!(doc.import(&corrupted).is_err());
5641 }
5642
5643 #[test]
5644 fn tree_meta() {
5645 let loro = LoroDoc::new_auto_commit();
5646 loro.set_peer_id(1).unwrap();
5647 let tree = loro.get_tree("root");
5648 let id = tree.create(TreeParentId::Root).unwrap();
5649 let meta = tree.get_meta(id).unwrap();
5650 meta.insert("a", 123).unwrap();
5651 loro.commit_then_renew();
5652 let meta = tree.get_meta(id).unwrap();
5653 assert_eq!(meta.get("a").unwrap(), 123.into());
5654 assert_eq!(
5655 json!([{"parent":null,"meta":{"a":123},"id":"0@1","index":0,"children":[],"fractional_index":"80"}]),
5656 tree.get_deep_value().to_json_value()
5657 );
5658 let bytes = loro.export(ExportMode::snapshot()).unwrap();
5659 let loro2 = LoroDoc::new();
5660 loro2.import(&bytes).unwrap();
5661 }
5662
5663 #[test]
5664 fn tree_meta_event() {
5665 use std::sync::Arc;
5666 let loro = LoroDoc::new_auto_commit();
5667 let tree = loro.get_tree("root");
5668 let text = loro.get_text("text");
5669
5670 let id = tree.create(TreeParentId::Root).unwrap();
5671 let meta = tree.get_meta(id).unwrap();
5672 meta.insert("a", 1).unwrap();
5673 text.insert(0, "abc", PosType::Unicode).unwrap();
5674 let _id2 = tree.create(TreeParentId::Root).unwrap();
5675 meta.insert("b", 2).unwrap();
5676
5677 let loro2 = LoroDoc::new_auto_commit();
5678 let _g = loro2.subscribe_root(Arc::new(|e| {
5679 println!("{} {:?} ", e.event_meta.by, e.event_meta.diff)
5680 }));
5681 loro2
5682 .import(&loro.export(ExportMode::all_updates()).unwrap())
5683 .unwrap();
5684 assert_eq!(loro.get_deep_value(), loro2.get_deep_value());
5685 }
5686
5687 #[test]
5688 fn richtext_apply_delta() {
5689 let loro = LoroDoc::new_auto_commit();
5690 let text = loro.get_text("text");
5691 text.apply_delta(&[TextDelta::Insert {
5692 insert: "Hello World!".into(),
5693 attributes: None,
5694 }])
5695 .unwrap();
5696 dbg!(text.get_richtext_value());
5697 text.apply_delta(&[
5698 TextDelta::Retain {
5699 retain: 6,
5700 attributes: Some(fx_map!("italic".into() => loro_common::LoroValue::Bool(true))),
5701 },
5702 TextDelta::Insert {
5703 insert: "New ".into(),
5704 attributes: Some(fx_map!("bold".into() => loro_common::LoroValue::Bool(true))),
5705 },
5706 ])
5707 .unwrap();
5708 dbg!(text.get_richtext_value());
5709 loro.commit_then_renew();
5710 assert_eq!(
5711 text.get_richtext_value().to_json_value(),
5712 json!([
5713 {"insert": "Hello ", "attributes": {"italic": true}},
5714 {"insert": "New ", "attributes": {"bold": true}},
5715 {"insert": "World!"}
5716
5717 ])
5718 )
5719 }
5720
5721 #[test]
5722 fn richtext_apply_delta_marks_without_growth() {
5723 let loro = LoroDoc::new_auto_commit();
5724 let text = loro.get_text("text");
5725 text.insert(0, "abc", PosType::Unicode).unwrap();
5726
5727 text.apply_delta(&[TextDelta::Retain {
5728 retain: 3,
5729 attributes: Some(fx_map!("bold".into() => LoroValue::Bool(true))),
5730 }])
5731 .unwrap();
5732 loro.commit_then_renew();
5733
5734 assert_eq!(text.to_string(), "abc");
5735 assert_eq!(
5736 text.get_richtext_value().to_json_value(),
5737 json!([{"insert": "abc", "attributes": {"bold": true}}])
5738 );
5739 }
5740
5741 #[test]
5742 fn richtext_apply_delta_grows_for_mark_gap() {
5743 let loro = LoroDoc::new_auto_commit();
5744 let text = loro.get_text("text");
5745
5746 text.apply_delta(&[TextDelta::Retain {
5747 retain: 1,
5748 attributes: Some(fx_map!("bold".into() => LoroValue::Bool(true))),
5749 }])
5750 .unwrap();
5751 loro.commit_then_renew();
5752
5753 assert_eq!(text.to_string(), "\n");
5754 assert_eq!(
5755 text.get_richtext_value().to_json_value(),
5756 json!([{"insert": "\n", "attributes": {"bold": true}}])
5757 );
5758 }
5759
5760 #[test]
5761 fn richtext_apply_delta_ignores_empty_inserts() {
5762 let loro = LoroDoc::new_auto_commit();
5763 let text = loro.get_text("text");
5764 text.insert(0, "seed", PosType::Unicode).unwrap();
5765
5766 text.apply_delta(&[TextDelta::Insert {
5767 insert: "".into(),
5768 attributes: Some(fx_map!("bold".into() => LoroValue::Bool(true))),
5769 }])
5770 .unwrap();
5771 loro.commit_then_renew();
5772
5773 assert_eq!(text.to_string(), "seed");
5774 assert_eq!(
5775 text.get_richtext_value().to_json_value(),
5776 json!([{"insert": "seed"}])
5777 );
5778 }
5779
5780 #[test]
5781 fn handler_trait_dispatch_reports_attached_container_identity() {
5782 let loro = LoroDoc::new_auto_commit();
5783 let handlers = [
5784 (loro.get_text("text").to_handler(), ContainerType::Text),
5785 (loro.get_map("map").to_handler(), ContainerType::Map),
5786 (loro.get_list("list").to_handler(), ContainerType::List),
5787 (
5788 loro.get_movable_list("movable").to_handler(),
5789 ContainerType::MovableList,
5790 ),
5791 (loro.get_tree("tree").to_handler(), ContainerType::Tree),
5792 ];
5793
5794 for (handler, expected_type) in handlers {
5795 assert!(handler.is_attached());
5796 assert!(handler.attached_handler().is_some());
5797 assert!(handler.doc().is_some());
5798 assert!(handler.get_attached().is_some());
5799 assert_eq!(handler.kind(), expected_type);
5800 assert_eq!(handler.c_type(), expected_type);
5801 assert_eq!(handler.id().container_type(), expected_type);
5802 assert_eq!(
5803 Handler::from_handler(handler.clone()).unwrap().c_type(),
5804 expected_type
5805 );
5806
5807 handler.get_value();
5808 handler.get_deep_value();
5809 handler.clear().unwrap();
5810 }
5811 }
5812
5813 #[test]
5814 fn handler_trait_dispatch_reports_detached_container_identity() {
5815 let handlers = [
5816 (
5817 Handler::new_unattached(ContainerType::Text).unwrap(),
5818 ContainerType::Text,
5819 ),
5820 (
5821 Handler::new_unattached(ContainerType::Map).unwrap(),
5822 ContainerType::Map,
5823 ),
5824 (
5825 Handler::new_unattached(ContainerType::List).unwrap(),
5826 ContainerType::List,
5827 ),
5828 (
5829 Handler::new_unattached(ContainerType::MovableList).unwrap(),
5830 ContainerType::MovableList,
5831 ),
5832 (
5833 Handler::new_unattached(ContainerType::Tree).unwrap(),
5834 ContainerType::Tree,
5835 ),
5836 ];
5837
5838 for (handler, expected_type) in handlers {
5839 assert!(!handler.is_attached());
5840 assert!(handler.attached_handler().is_none());
5841 assert!(handler.doc().is_none());
5842 assert!(handler.get_attached().is_none());
5843 assert_eq!(handler.kind(), expected_type);
5844 assert_eq!(handler.c_type(), expected_type);
5845 assert_eq!(handler.id().container_type(), expected_type);
5846 assert_eq!(handler.idx().get_type(), expected_type);
5847 assert_eq!(
5848 Handler::from_handler(handler.clone()).unwrap().c_type(),
5849 expected_type
5850 );
5851 }
5852 }
5853
5854 #[test]
5855 fn attaching_detached_handlers_sets_parent_and_attached_back_reference() {
5856 let loro = LoroDoc::new_auto_commit();
5857
5858 let map = loro.get_map("map");
5859 let detached_text = TextHandler::new_detached();
5860 detached_text
5861 .insert(0, "detached", PosType::Unicode)
5862 .unwrap();
5863 let attached_text = map.insert_container("text", detached_text.clone()).unwrap();
5864 assert!(attached_text.is_attached());
5865 assert_eq!(attached_text.to_string(), "detached");
5866 assert_eq!(attached_text.parent().unwrap().c_type(), ContainerType::Map);
5867 assert_eq!(
5868 detached_text.get_attached().unwrap().id(),
5869 attached_text.id()
5870 );
5871
5872 let list = loro.get_list("list");
5873 let detached_map = MapHandler::new_detached();
5874 detached_map.insert("k", 1_i64).unwrap();
5875 let attached_map = list.insert_container(0, detached_map.clone()).unwrap();
5876 assert!(attached_map.is_attached());
5877 assert_eq!(attached_map.parent().unwrap().c_type(), ContainerType::List);
5878 assert_eq!(detached_map.get_attached().unwrap().id(), attached_map.id());
5879
5880 let movable = loro.get_movable_list("movable");
5881 let detached_list = ListHandler::new_detached();
5882 detached_list.push("item").unwrap();
5883 let attached_list = movable.insert_container(0, detached_list.clone()).unwrap();
5884 assert!(attached_list.is_attached());
5885 assert_eq!(
5886 attached_list.parent().unwrap().c_type(),
5887 ContainerType::MovableList
5888 );
5889 assert_eq!(
5890 detached_list.get_attached().unwrap().id(),
5891 attached_list.id()
5892 );
5893
5894 let nested = attached_map
5895 .insert_container("movable", MovableListHandler::new_detached())
5896 .unwrap();
5897 assert_eq!(nested.parent().unwrap().id(), attached_map.id());
5898 }
5899
5900 #[test]
5901 fn unknown_handler_reports_identity_without_materializing_value() {
5902 let loro = LoroDoc::new_auto_commit();
5903 let id = ContainerID::Root {
5904 name: "unknown".into(),
5905 container_type: ContainerType::Unknown(7),
5906 };
5907 let handler = Handler::new_attached(id.clone(), loro.clone());
5908 let unknown = handler.as_unknown().unwrap();
5909
5910 assert!(unknown.is_attached());
5911 assert_eq!(unknown.kind(), ContainerType::Unknown(7));
5912 assert_eq!(unknown.id(), id);
5913 assert_eq!(unknown.to_handler().c_type(), ContainerType::Unknown(7));
5914 assert!(unknown.doc().is_some());
5915 assert!(!unknown.is_deleted());
5916 assert_eq!(format!("{unknown:?}"), "UnknownHandler");
5917 assert!(unknown.get_attached().is_some());
5918 assert!(super::UnknownHandler::from_handler(handler.clone()).is_some());
5919
5920 // This version cannot create or copy a container of an unknown type
5921 assert!(matches!(
5922 Handler::new_unattached(ContainerType::Unknown(7)),
5923 Err(LoroError::ArgErr(_))
5924 ));
5925 let map = loro.get_map("map");
5926 assert!(matches!(
5927 map.insert_container("k", handler),
5928 Err(LoroError::ArgErr(_))
5929 ));
5930 assert!(map.is_empty());
5931 }
5932
5933 #[test]
5934 fn deep_value_with_id_cid_matches_container_id_string() {
5935 let loro = LoroDoc::new_auto_commit();
5936 let map = loro.get_map("map");
5937 map.insert("key", "value").unwrap();
5938 let child = map
5939 .insert_container("child", ListHandler::new_detached())
5940 .unwrap();
5941 child.push("item").unwrap();
5942
5943 let value = loro.get_deep_value_with_id();
5944 assert_eq!(
5945 value["map"]["cid"].to_json_value(),
5946 json!(map.id().to_string())
5947 );
5948 assert_eq!(
5949 value["map"]["cid"].to_json_value(),
5950 json!("cid:root-map:Map")
5951 );
5952 let child_cid = value["map"]["value"]["child"]["cid"].to_json_value();
5953 assert_eq!(child_cid, json!(child.id().to_string()));
5954 let child_cid = child_cid.as_str().unwrap();
5955 assert!(child_cid.starts_with("cid:"), "unexpected cid: {child_cid}");
5956 assert!(!child_cid.contains("idx:"), "unexpected cid: {child_cid}");
5957
5958 // The per-container handler API emits the same node shape
5959 let map_value = map.get_deep_value_with_id().unwrap();
5960 assert_eq!(
5961 map_value["cid"].to_json_value(),
5962 json!(map.id().to_string())
5963 );
5964 assert_eq!(
5965 map_value["value"]["child"]["cid"].to_json_value(),
5966 json!(child.id().to_string())
5967 );
5968 assert_eq!(
5969 map_value["value"]["child"]["value"][0].to_json_value(),
5970 json!("item")
5971 );
5972 }
5973
5974 #[test]
5975 fn text_and_tree_deep_value_with_id() {
5976 let loro = LoroDoc::new_auto_commit();
5977 let text = loro.get_text("text");
5978 text.insert(0, "hello", PosType::Unicode).unwrap();
5979 let text_value = text.get_deep_value_with_id().unwrap();
5980 assert_eq!(
5981 text_value.to_json_value(),
5982 json!({"cid": text.id().to_string(), "value": "hello"})
5983 );
5984
5985 let tree = loro.get_tree("tree");
5986 let node = tree.create(TreeParentId::Root).unwrap();
5987 tree.get_meta(node).unwrap().insert("name", "root").unwrap();
5988 let tree_value = tree.get_deep_value_with_id().unwrap();
5989 assert_eq!(
5990 tree_value["cid"].to_json_value(),
5991 json!(tree.id().to_string())
5992 );
5993 assert_eq!(
5994 tree_value["value"][0]["meta"]["name"].to_json_value(),
5995 json!("root")
5996 );
5997
5998 // Detached containers must error rather than panic
5999 let detached_text = TextHandler::new_detached();
6000 assert!(matches!(
6001 detached_text.get_deep_value_with_id(),
6002 Err(LoroError::MisuseDetachedContainer { .. })
6003 ));
6004 let detached_tree = crate::handler::TreeHandler::new_detached();
6005 assert!(matches!(
6006 detached_tree.get_deep_value_with_id(),
6007 Err(LoroError::MisuseDetachedContainer { .. })
6008 ));
6009 }
6010
6011 #[test]
6012 fn list_slice_deep_value() {
6013 let loro = LoroDoc::new_auto_commit();
6014 let list = loro.get_list("list");
6015 list.push("a").unwrap();
6016 list.push("b").unwrap();
6017 let child = list.push_container(MapHandler::new_detached()).unwrap();
6018 child.insert("k", "v").unwrap();
6019 list.push("d").unwrap();
6020
6021 // Full range with ids: containers become { cid, value } nodes
6022 let all = list.get_slice_deep_value_with_id(0, 4).unwrap();
6023 assert_eq!(all[0].to_json_value(), json!("a"));
6024 assert_eq!(
6025 all[2].to_json_value(),
6026 json!({"cid": child.id().to_string(), "value": {"k": "v"}})
6027 );
6028
6029 // Sub-range without ids: containers become their plain deep value
6030 let mid = list.get_slice_deep_value(1, 3).unwrap();
6031 assert_eq!(mid.to_json_value(), json!(["b", {"k": "v"}]));
6032
6033 // Bounds are clamped to the list length
6034 let clamped = list.get_slice_deep_value_with_id(2, 100).unwrap();
6035 assert_eq!(clamped.to_json_value().as_array().unwrap().len(), 2);
6036 let clamped_start = list.get_slice_deep_value_with_id(100, 200).unwrap();
6037 assert_eq!(clamped_start.to_json_value(), json!([]));
6038
6039 // Empty and inverted ranges return an empty list
6040 assert_eq!(
6041 list.get_slice_deep_value(2, 2).unwrap().to_json_value(),
6042 json!([])
6043 );
6044 assert_eq!(
6045 list.get_slice_deep_value(3, 1).unwrap().to_json_value(),
6046 json!([])
6047 );
6048
6049 // Detached lists must error rather than panic
6050 let detached = ListHandler::new_detached();
6051 assert!(matches!(
6052 detached.get_slice_deep_value_with_id(0, 1),
6053 Err(LoroError::MisuseDetachedContainer { .. })
6054 ));
6055 assert!(matches!(
6056 detached.get_slice_deep_value(0, 1),
6057 Err(LoroError::MisuseDetachedContainer { .. })
6058 ));
6059 }
6060
6061 #[test]
6062 fn movable_list_slice_deep_value() {
6063 let loro = LoroDoc::new_auto_commit();
6064 let list = loro.get_movable_list("list");
6065 list.push("a".into()).unwrap();
6066 let child = list.push_container(ListHandler::new_detached()).unwrap();
6067 child.push("x").unwrap();
6068 list.push("b".into()).unwrap();
6069
6070 let all = list.get_slice_deep_value_with_id(0, 3).unwrap();
6071 assert_eq!(
6072 all[1].to_json_value(),
6073 json!({"cid": child.id().to_string(), "value": ["x"]})
6074 );
6075
6076 let plain = list.get_slice_deep_value(0, 2).unwrap();
6077 assert_eq!(plain.to_json_value(), json!(["a", ["x"]]));
6078
6079 // Whole-container deep value with id errors on detached containers
6080 let attached = list.get_deep_value_with_id().unwrap();
6081 assert_eq!(
6082 attached["cid"].to_json_value(),
6083 json!(list.id().to_string())
6084 );
6085 let detached = MovableListHandler::new_detached();
6086 assert!(matches!(
6087 detached.get_deep_value_with_id(),
6088 Err(LoroError::MisuseDetachedContainer { .. })
6089 ));
6090 assert!(matches!(
6091 detached.get_slice_deep_value_with_id(0, 1),
6092 Err(LoroError::MisuseDetachedContainer { .. })
6093 ));
6094 assert!(matches!(
6095 detached.get_slice_deep_value(0, 1),
6096 Err(LoroError::MisuseDetachedContainer { .. })
6097 ));
6098 }
6099}