oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1use crate::branch::{Branch, BranchPtr};
2use crate::doc::{DocAddr, OffsetKind};
3use crate::encoding::read::Error;
4use crate::error::UpdateError;
5use crate::gc::GCCollector;
6use crate::moving::Move;
7use crate::slice::{BlockSlice, GCSlice, ItemSlice};
8use crate::store::Store;
9use crate::transaction::TransactionMut;
10use crate::types::text::update_current_attributes;
11use crate::types::{Attrs, TypePtr, TypeRef};
12use crate::undo::UndoStack;
13use crate::updates::decoder::{Decode, Decoder};
14use crate::updates::encoder::{Encode, Encoder};
15use crate::utils::OptionExt;
16use crate::{Any, DeleteSet, Doc, Options, Out, Transact};
17use serde::{Deserialize, Serialize};
18use smallstr::SmallString;
19use std::collections::HashSet;
20use std::convert::TryFrom;
21use std::fmt::Formatter;
22use std::hash::Hash;
23use std::ops::{Deref, DerefMut};
24use std::panic;
25use std::ptr::NonNull;
26use std::sync::Arc;
27
28/// Bit flag used to identify [Item::GC].
29pub const BLOCK_GC_REF_NUMBER: u8 = 0;
30
31/// Bit flag used to identify items with content of type [ItemContent::Deleted].
32pub const BLOCK_ITEM_DELETED_REF_NUMBER: u8 = 1;
33
34/// Bit flag used to identify items with content of type [ItemContent::JSON].
35pub const BLOCK_ITEM_JSON_REF_NUMBER: u8 = 2;
36
37/// Bit flag used to identify items with content of type [ItemContent::Binary].
38pub const BLOCK_ITEM_BINARY_REF_NUMBER: u8 = 3;
39
40/// Bit flag used to identify items with content of type [ItemContent::String].
41pub const BLOCK_ITEM_STRING_REF_NUMBER: u8 = 4;
42
43/// Bit flag used to identify items with content of type [ItemContent::Embed].
44pub const BLOCK_ITEM_EMBED_REF_NUMBER: u8 = 5;
45
46/// Bit flag used to identify items with content of type [ItemContent::Format].
47pub const BLOCK_ITEM_FORMAT_REF_NUMBER: u8 = 6;
48
49/// Bit flag used to identify items with content of type [ItemContent::Number].
50pub const BLOCK_ITEM_TYPE_REF_NUMBER: u8 = 7;
51
52/// Bit flag used to identify items with content of type [ItemContent::Any].
53pub const BLOCK_ITEM_ANY_REF_NUMBER: u8 = 8;
54
55/// Bit flag used to identify items with content of type [ItemContent::Doc].
56pub const BLOCK_ITEM_DOC_REF_NUMBER: u8 = 9;
57
58/// Bit flag used to identify [Item::Skip].
59pub const BLOCK_SKIP_REF_NUMBER: u8 = 10;
60
61/// Bit flag used to identify items with content of type [ItemContent::Move].
62pub const BLOCK_ITEM_MOVE_REF_NUMBER: u8 = 11;
63
64/// Bit flag used to tell if encoded item has right origin defined.
65pub const HAS_RIGHT_ORIGIN: u8 = 0b01000000;
66
67/// Bit flag used to tell if encoded item has left origin defined.
68pub const HAS_ORIGIN: u8 = 0b10000000;
69
70/// Bit flag used to tell if encoded item has a parent subtitle defined. Subtitles are used only
71/// for blocks which act as map-like types entries.
72pub const HAS_PARENT_SUB: u8 = 0b00100000;
73
74/// Globally unique client identifier. No two active peers are allowed to share the same [ClientID].
75/// If that happens, following updates may cause document store to be corrupted and desync in a result.
76pub type ClientID = u64;
77
78/// Block identifier, which allows to uniquely identify any element insertion in a global scope
79/// (across different replicas of the same document). It consists of client ID (which is a unique
80/// document replica identifier) and monotonically incrementing clock value.
81///
82/// [ID] corresponds to a [Lamport timestamp](https://en.wikipedia.org/wiki/Lamport_timestamp) in
83/// terms of its properties and guarantees.
84#[derive(Debug, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Serialize, Deserialize)]
85pub struct ID {
86 /// Unique identifier of a client.
87 pub client: ClientID,
88
89 /// Monotonically incrementing sequence number, which informs about order of inserted item
90 /// operation in a scope of a given `client`. This value doesn't have to increase by 1, but
91 /// instead is increased by number of countable elements which make a content of an inserted
92 /// block.
93 pub clock: u32,
94}
95
96impl ID {
97 pub fn new(client: ClientID, clock: u32) -> Self {
98 ID { client, clock }
99 }
100}
101
102pub(crate) enum BlockCell {
103 GC(GC),
104 Block(Box<Item>),
105}
106
107impl PartialEq for BlockCell {
108 fn eq(&self, other: &Self) -> bool {
109 match (self, other) {
110 (BlockCell::GC(a), BlockCell::GC(b)) => a == b,
111 (BlockCell::Block(a), BlockCell::Block(b)) => a.id == b.id,
112 _ => false,
113 }
114 }
115}
116
117impl std::fmt::Debug for BlockCell {
118 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
119 match self {
120 BlockCell::GC(gc) => write!(f, "gc({}..={})", gc.start, gc.end),
121 BlockCell::Block(item) => item.fmt(f),
122 }
123 }
124}
125
126impl BlockCell {
127 /// Returns the first clock sequence number of a current block.
128 pub fn clock_start(&self) -> u32 {
129 match self {
130 BlockCell::GC(gc) => gc.start,
131 BlockCell::Block(item) => item.id.clock,
132 }
133 }
134
135 /// Returns the last clock sequence number of a current block.
136 pub fn clock_end(&self) -> u32 {
137 match self {
138 BlockCell::GC(gc) => gc.end,
139 BlockCell::Block(item) => item.id.clock + item.len - 1,
140 }
141 }
142
143 /// Returns a range of first and the last clock sequence numbers that belong to a current block.
144 #[inline]
145 pub fn clock_range(&self) -> (u32, u32) {
146 match self {
147 BlockCell::GC(gc) => (gc.start, gc.end),
148 BlockCell::Block(block) => block.clock_range(),
149 }
150 }
151
152 pub fn is_deleted(&self) -> bool {
153 match self {
154 BlockCell::GC(_) => true,
155 BlockCell::Block(item) => item.is_deleted(),
156 }
157 }
158
159 pub fn len(&self) -> u32 {
160 match self {
161 BlockCell::GC(gc) => gc.end - gc.start + 1,
162 BlockCell::Block(block) => block.len(),
163 }
164 }
165
166 pub fn as_slice(&self) -> BlockSlice {
167 match self {
168 BlockCell::GC(gc) => BlockSlice::GC(GCSlice::from(gc.clone())),
169 BlockCell::Block(item) => {
170 let ptr = ItemPtr::from(item);
171 BlockSlice::Item(ItemSlice::from(ptr))
172 }
173 }
174 }
175
176 pub fn as_item(&self) -> Option<ItemPtr> {
177 if let BlockCell::Block(item) = self {
178 Some(ItemPtr::from(item))
179 } else {
180 None
181 }
182 }
183}
184
185impl From<Box<Item>> for BlockCell {
186 fn from(value: Box<Item>) -> Self {
187 BlockCell::Block(value)
188 }
189}
190
191impl From<GC> for BlockCell {
192 fn from(gc: GC) -> Self {
193 BlockCell::GC(gc)
194 }
195}
196
197#[derive(Debug, Copy, Clone, PartialEq)]
198pub(crate) struct GC {
199 pub start: u32,
200 pub end: u32,
201}
202
203impl GC {
204 #[inline]
205 pub fn new(start: u32, end: u32) -> Self {
206 GC { start, end }
207 }
208
209 pub fn len(&self) -> u32 {
210 self.end - self.start + 1
211 }
212}
213
214impl From<BlockRange> for GC {
215 fn from(value: BlockRange) -> Self {
216 let start = value.id.clock;
217 let end = start + value.len - 1;
218 GC { start, end }
219 }
220}
221
222impl Encode for GC {
223 fn encode<E: Encoder>(&self, encoder: &mut E) {
224 encoder.write_info(BLOCK_GC_REF_NUMBER);
225 encoder.write_len(self.len());
226 }
227}
228
229/// A raw [Item] pointer. As the underlying block doesn't move it's in-memory location, [ItemPtr]
230/// can be considered a pinned object.
231#[repr(transparent)]
232#[derive(Clone, Copy, Hash)]
233pub struct ItemPtr(NonNull<Item>);
234
235unsafe impl Send for ItemPtr {}
236unsafe impl Sync for ItemPtr {}
237
238impl ItemPtr {
239 pub(crate) fn redo<M>(
240 &mut self,
241 txn: &mut TransactionMut,
242 redo_items: &HashSet<ItemPtr>,
243 items_to_delete: &DeleteSet,
244 s1: &UndoStack<M>,
245 s2: &UndoStack<M>,
246 ) -> Option<ItemPtr> {
247 let self_ptr = self.clone();
248 let item = self.deref_mut();
249 if let Some(redone) = item.redone.as_ref() {
250 let slice = txn.store.blocks.get_item_clean_start(redone)?;
251 return Some(txn.store.materialize(slice));
252 }
253
254 let mut parent_block = item.parent.as_branch().and_then(|b| b.item);
255 // make sure that parent is redone
256 if let Some(mut parent) = parent_block.clone() {
257 if parent.is_deleted() {
258 // try to undo parent if it will be undone anyway
259 if parent.redone.is_none()
260 && (!redo_items.contains(&parent)
261 || parent
262 .redo(txn, redo_items, items_to_delete, s1, s2)
263 .is_none())
264 {
265 return None;
266 }
267 let mut redone = parent.redone;
268 while let Some(id) = redone.as_ref() {
269 parent_block = txn
270 .store
271 .blocks
272 .get_item_clean_start(id)
273 .map(|slice| txn.store.materialize(slice));
274 redone = parent_block.and_then(|ptr| ptr.redone);
275 }
276 }
277 }
278 let parent_branch = BranchPtr::from(if let Some(item) = parent_block.as_deref() {
279 if let ItemContent::Type(b) = &item.content {
280 b.as_ref()
281 } else {
282 item.parent.as_branch().unwrap()
283 }
284 } else {
285 item.parent.as_branch().unwrap()
286 });
287
288 let mut left = None;
289 let mut right = None;
290 if let Some(sub) = item.parent_sub.as_ref() {
291 if item.right.is_some() {
292 left = Some(self_ptr);
293 // Iterate right while is in itemsToDelete
294 // If it is intended to delete right while item is redone,
295 // we can expect that item should replace right.
296 while let Some(left_item) = left.as_deref() {
297 if let Some(left_right) = left_item.right {
298 let id = left_right.id();
299 if left_right.redone.is_some()
300 || items_to_delete.is_deleted(id)
301 || s1.is_deleted(id)
302 || s2.is_deleted(id)
303 {
304 // follow redone
305 left = Some(left_right);
306 while let Some(item) = left.as_deref() {
307 if let Some(id) = item.redone.as_ref() {
308 left = match txn.store.blocks.get_item_clean_start(id) {
309 None => break,
310 Some(slice) => {
311 let ptr = txn.store.materialize(slice);
312 txn.merge_blocks.push(ptr.id().clone());
313 Some(ptr)
314 }
315 };
316 } else {
317 break;
318 }
319 }
320 continue;
321 }
322 }
323 break;
324 }
325
326 if let Some(left_item) = left.as_deref() {
327 if left_item.right.is_some() {
328 // It is not possible to redo this item because it conflicts with a
329 // change from another client
330 return None;
331 }
332 }
333 } else {
334 left = parent_branch.map.get(sub).cloned();
335 }
336 } else {
337 // Is an array item. Insert at the old position
338 left = item.left;
339 right = Some(self_ptr);
340 // find next cloned_redo items
341 while let Some(left_item) = left.clone().as_deref() {
342 let mut left_trace = left;
343 while let Some(trace) = left_trace.as_deref() {
344 let p = trace.parent.as_branch().and_then(|p| p.item);
345 if parent_block != p {
346 left_trace = if let Some(redone) = trace.redone.as_ref() {
347 let slice = txn.store.blocks.get_item_clean_start(redone);
348 slice.map(|s| txn.store.materialize(s))
349 } else {
350 None
351 };
352 } else {
353 break;
354 }
355 }
356 if let Some(trace) = left_trace.as_deref() {
357 let p = trace.parent.as_branch().and_then(|p| p.item);
358 if parent_block == p {
359 left = left_trace;
360 break;
361 }
362 }
363 left = left_item.left.clone();
364 }
365
366 while let Some(right_item) = right.clone().as_deref() {
367 let mut right_trace = right;
368 // trace redone until parent matches
369 while let Some(trace) = right_trace.as_deref() {
370 let p = trace.parent.as_branch().and_then(|p| p.item);
371 if parent_block != p {
372 right_trace = if let Some(redone) = trace.redone.as_ref() {
373 let slice = txn.store.blocks.get_item_clean_start(redone);
374 slice.map(|s| txn.store.materialize(s))
375 } else {
376 None
377 };
378 } else {
379 break;
380 }
381 }
382 if let Some(trace) = right_trace.as_deref() {
383 let p = trace.parent.as_branch().and_then(|p| p.item);
384 if parent_block == p {
385 right = right_trace;
386 break;
387 }
388 }
389 right = right_item.right.clone();
390 }
391 }
392
393 // Local patch (see PATCHES.md, "Redo origins"): tracing `redone` chains
394 // can land `right` on or before `left` (an item restored earlier to the
395 // left; here, `right` = `left`). Integrated locally the item goes right
396 // after `left`, but a receiver resolves those origins elsewhere: `right`
397 // inside `left`'s merged block splits it, so the item lands before it.
398 // Name the item actually after `left` as `right`, so every replica puts
399 // it where this one does.
400 if let (Some(l), Some(r)) = (left, right) {
401 let mut next = l.right;
402 while let Some(n) = next {
403 if n == r {
404 break;
405 }
406 next = n.right;
407 }
408 if next.is_none() {
409 right = l.right;
410 }
411 }
412
413 let next_clock = txn.store.get_local_state();
414 let next_id = ID::new(txn.store.client_id, next_clock);
415 let mut redone_item = Item::new(
416 next_id,
417 left,
418 left.map(|p| p.last_id()),
419 right,
420 right.map(|p| *p.id()),
421 TypePtr::Branch(parent_branch),
422 item.parent_sub.clone(),
423 item.content.clone(),
424 )?;
425 item.redone = Some(*redone_item.id());
426 redone_item.info.set_keep();
427 let mut block_ptr = ItemPtr::from(&mut redone_item);
428
429 // Local patch (see PATCHES.md, "Local inserts into a deleted parent"):
430 // integrate answers true when the parent is deleted (a restored parent a
431 // peer has since deleted). Yjs's Item.integrate and every peer receiving
432 // this item delete it then; dropping the answer left it live here alone.
433 // Deleted after it is stored, as Update::integrate does.
434 let should_delete = block_ptr.integrate(txn, 0);
435
436 txn.store_mut().blocks.push_block(redone_item);
437 if should_delete {
438 txn.delete(block_ptr);
439 }
440 Some(block_ptr)
441 }
442
443 pub(crate) fn keep(&self, keep: bool) {
444 let mut curr = Some(*self);
445 while let Some(item) = curr.as_deref_mut() {
446 if item.info.is_keep() == keep {
447 break;
448 } else {
449 if keep {
450 item.info.set_keep();
451 } else {
452 item.info.clear_keep();
453 }
454 curr = item.parent.as_branch().and_then(|b| b.item);
455 }
456 }
457 }
458
459 pub(crate) fn delete_as_cleanup(&self, txn: &mut TransactionMut, is_local: bool) {
460 txn.delete(*self);
461 if is_local {
462 txn.delete_set.insert(*self.id(), self.len());
463 }
464 }
465
466 pub(crate) fn splice(&mut self, offset: u32, encoding: OffsetKind) -> Option<Box<Item>> {
467 let self_ptr = self.clone();
468 if offset == 0 {
469 None
470 } else {
471 let item = self.deref_mut();
472 let client = item.id.client;
473 let clock = item.id.clock;
474 let content = item.content.splice(offset as usize, encoding).unwrap();
475 item.len = offset;
476 let mut new = Box::new(Item {
477 id: ID::new(client, clock + offset),
478 len: content.len(OffsetKind::Utf16),
479 left: Some(self_ptr),
480 right: item.right.clone(),
481 origin: Some(ID::new(client, clock + offset - 1)),
482 right_origin: item.right_origin.clone(),
483 content,
484 parent: item.parent.clone(),
485 moved: item.moved.clone(),
486 parent_sub: item.parent_sub.clone(),
487 info: item.info.clone(),
488 redone: item.redone.map(|id| ID::new(id.client, id.clock + offset)),
489 });
490 let new_ptr = ItemPtr::from(&mut new);
491
492 if let Some(right) = item.right.as_deref_mut() {
493 right.left = Some(new_ptr);
494 }
495
496 if let Some(parent_sub) = item.parent_sub.as_ref() {
497 if item.right.is_none() {
498 // update parent.map
499 if let TypePtr::Branch(mut branch) = item.parent {
500 branch.map.insert(parent_sub.clone(), new_ptr);
501 }
502 }
503 }
504
505 item.right = Some(new_ptr);
506
507 Some(new)
508 }
509 }
510
511 /// Integrates current block into block store.
512 /// If it returns true, it means that the block should be deleted after being added to a block store.
513 pub(crate) fn integrate(&mut self, txn: &mut TransactionMut, offset: u32) -> bool {
514 let self_ptr = self.clone();
515 let this = self.deref_mut();
516 let store = txn.store_mut();
517 let encoding = store.offset_kind;
518 if offset > 0 {
519 // offset could be > 0 only in context of Update::integrate,
520 // is such case offset kind in use always means Yjs-compatible offset (utf-16)
521 this.id.clock += offset;
522 this.left = store
523 .blocks
524 .get_item_clean_end(&ID::new(this.id.client, this.id.clock - 1))
525 .map(|slice| store.materialize(slice));
526 this.origin = this.left.as_deref().map(|b: &Item| b.last_id());
527 this.content = this
528 .content
529 .splice(offset as usize, OffsetKind::Utf16)
530 .unwrap();
531 this.len -= offset;
532 }
533
534 let parent = match &this.parent {
535 TypePtr::Branch(branch) => Some(*branch),
536 TypePtr::Named(name) => {
537 let branch = store.get_or_create_type(name.clone(), TypeRef::Undefined);
538 this.parent = TypePtr::Branch(branch);
539 Some(branch)
540 }
541 TypePtr::ID(id) => {
542 if let Some(item) = store.blocks.get_item(id) {
543 if let Some(branch) = item.as_branch() {
544 this.parent = TypePtr::Branch(branch);
545 Some(branch)
546 } else {
547 None
548 }
549 } else {
550 None
551 }
552 }
553 TypePtr::Unknown => return true,
554 };
555
556 let left: Option<&Item> = this.left.as_deref();
557 let right: Option<&Item> = this.right.as_deref();
558
559 let right_is_null_or_has_left = match right {
560 None => true,
561 Some(i) => i.left.is_some(),
562 };
563 let left_has_other_right_than_self = match left {
564 Some(i) => i.right != this.right,
565 _ => false,
566 };
567
568 if let Some(mut parent_ref) = parent {
569 if (left.is_none() && right_is_null_or_has_left) || left_has_other_right_than_self {
570 // set the first conflicting item
571 let mut o = if let Some(left) = left {
572 left.right
573 } else if let Some(sub) = &this.parent_sub {
574 let mut o = parent_ref.map.get(sub).cloned();
575 while let Some(item) = o.as_deref() {
576 if item.left.is_some() {
577 o = item.left.clone();
578 continue;
579 }
580 break;
581 }
582 o.clone()
583 } else {
584 parent_ref.start
585 };
586
587 let mut left = this.left.clone();
588 let mut conflicting_items = HashSet::new();
589 let mut items_before_origin = HashSet::new();
590
591 // Let c in conflicting_items, b in items_before_origin
592 // ***{origin}bbbb{this}{c,b}{c,b}{o}***
593 // Note that conflicting_items is a subset of items_before_origin
594 while let Some(item) = o {
595 if Some(item) == this.right {
596 break;
597 }
598
599 items_before_origin.insert(item);
600 conflicting_items.insert(item);
601 if this.origin == item.origin {
602 // case 1
603 if item.id.client < this.id.client {
604 left = Some(item.clone());
605 conflicting_items.clear();
606 } else if this.right_origin == item.right_origin {
607 // `self` and `item` are conflicting and point to the same integration
608 // points. The id decides which item comes first. Since `self` is to
609 // the left of `item`, we can break here.
610 break;
611 }
612 } else {
613 if let Some(origin_ptr) = item
614 .origin
615 .as_ref()
616 .and_then(|id| store.blocks.get_item(id))
617 {
618 if items_before_origin.contains(&origin_ptr) {
619 if !conflicting_items.contains(&origin_ptr) {
620 left = Some(item.clone());
621 conflicting_items.clear();
622 }
623 } else {
624 break;
625 }
626 } else {
627 break;
628 }
629 }
630 o = item.right.clone();
631 }
632 this.left = left;
633 }
634
635 if this.parent_sub.is_none() {
636 if let Some(item) = this.left.as_deref() {
637 if item.parent_sub.is_some() {
638 this.parent_sub = item.parent_sub.clone();
639 } else if let Some(item) = this.right.as_deref() {
640 this.parent_sub = item.parent_sub.clone();
641 }
642 }
643 }
644
645 // reconnect left/right
646 if let Some(left) = this.left.as_deref_mut() {
647 this.right = left.right.replace(self_ptr);
648 } else {
649 let r = if let Some(parent_sub) = &this.parent_sub {
650 // update parent map/start if necessary
651 let mut r = parent_ref.map.get(parent_sub).cloned();
652 while let Some(item) = r {
653 if item.left.is_some() {
654 r = item.left;
655 } else {
656 break;
657 }
658 }
659 r
660 } else {
661 let start = parent_ref.start.replace(self_ptr);
662 start
663 };
664 this.right = r;
665 }
666
667 if let Some(right) = this.right.as_deref_mut() {
668 right.left = Some(self_ptr);
669 } else if let Some(parent_sub) = &this.parent_sub {
670 // set as current parent value if right === null and this is parentSub
671 parent_ref.map.insert(parent_sub.clone(), self_ptr);
672 if let Some(mut left) = this.left {
673 #[cfg(feature = "weak")]
674 {
675 if left.info.is_linked() {
676 // inherit links from the block we're overriding
677 left.info.clear_linked();
678 this.info.set_linked();
679 let all_links = &mut txn.store.linked_by;
680 if let Some(linked_by) = all_links.remove(&left) {
681 all_links.insert(self_ptr, linked_by);
682 // since left is being deleted, it will remove
683 // its links from store.linkedBy anyway
684 }
685 }
686 }
687 // this is the current attribute value of parent. delete right
688 txn.delete(left);
689 }
690 }
691
692 // adjust length of parent
693 if this.parent_sub.is_none() && !this.is_deleted() {
694 if this.is_countable() {
695 // adjust length of parent
696 parent_ref.block_len += this.len;
697 parent_ref.content_len += this.content_len(encoding);
698 }
699 #[cfg(feature = "weak")]
700 match (this.left, this.right) {
701 (Some(l), Some(r)) if l.info.is_linked() || r.info.is_linked() => {
702 crate::types::weak::join_linked_range(self_ptr, txn)
703 }
704 _ => {}
705 }
706 }
707
708 // check if this item is in a moved range
709 let left_moved = this.left.and_then(|i| i.moved);
710 let right_moved = this.right.and_then(|i| i.moved);
711 if left_moved.is_some() || right_moved.is_some() {
712 if left_moved == right_moved {
713 this.moved = left_moved;
714 } else {
715 #[inline]
716 fn try_integrate(mut item: ItemPtr, txn: &mut TransactionMut) {
717 let ptr = item.clone();
718 if let ItemContent::Move(m) = &mut item.content {
719 if !m.is_collapsed() {
720 m.integrate_block(txn, ptr);
721 }
722 }
723 }
724
725 if let Some(ptr) = left_moved {
726 try_integrate(ptr, txn);
727 }
728
729 if let Some(ptr) = right_moved {
730 try_integrate(ptr, txn);
731 }
732 }
733 }
734
735 match &mut this.content {
736 ItemContent::Deleted(len) => {
737 txn.delete_set.insert(this.id, *len);
738 this.mark_as_deleted();
739 }
740 ItemContent::Move(m) => m.integrate_block(txn, self_ptr),
741 ItemContent::Doc(parent_doc, doc) => {
742 *parent_doc = Some(txn.doc().clone());
743 {
744 let mut child_txn = doc.transact_mut();
745 child_txn.store.parent = Some(self_ptr);
746 }
747 let subdocs = txn.subdocs.get_or_init();
748 subdocs.added.insert(DocAddr::new(doc), doc.clone());
749 if doc.should_load() {
750 subdocs.loaded.insert(doc.addr(), doc.clone());
751 }
752 }
753 ItemContent::Format(_, _) => {
754 // @todo searchmarker are currently unsupported for rich text documents
755 // /** @type {AbstractType<any>} */ (item.parent)._searchMarker = null
756 }
757 ItemContent::Type(branch) => {
758 let ptr = BranchPtr::from(branch);
759 #[cfg(feature = "weak")]
760 if let TypeRef::WeakLink(source) = &ptr.type_ref {
761 source.materialize(txn, ptr);
762 }
763 }
764 _ => {
765 // other types don't define integration-specific actions
766 }
767 }
768 txn.add_changed_type(parent_ref, this.parent_sub.clone());
769 if this.info.is_linked() {
770 if let Some(links) = txn.store.linked_by.get(&self_ptr).cloned() {
771 // notify links about changes
772 for link in links.iter() {
773 txn.add_changed_type(*link, this.parent_sub.clone());
774 }
775 }
776 }
777 let parent_deleted = if let TypePtr::Branch(ptr) = &this.parent {
778 if let Some(block) = ptr.item {
779 block.is_deleted()
780 } else {
781 false
782 }
783 } else {
784 false
785 };
786 if parent_deleted || (this.parent_sub.is_some() && this.right.is_some()) {
787 // delete if parent is deleted or if this is not the current attribute value of parent
788 true
789 } else {
790 false
791 }
792 } else {
793 true
794 }
795 }
796
797 /// Squashes two blocks together. Returns true if it succeeded. Squashing is possible only if
798 /// blocks are of the same type, their contents are of the same type, they belong to the same
799 /// parent data structure, their IDs are sequenced directly one after another and they point to
800 /// each other as their left/right neighbors respectively.
801 pub(crate) fn try_squash(&mut self, other: ItemPtr) -> bool {
802 if self.id.client == other.id.client
803 && self.id.clock + self.len() == other.id.clock
804 && other.origin == Some(self.last_id())
805 && self.right_origin == other.right_origin
806 && self.right == Some(other)
807 && self.is_deleted() == other.is_deleted()
808 && (self.redone.is_none() && other.redone.is_none())
809 && (!self.info.is_linked() && !other.info.is_linked()) // linked items cannot be merged
810 && self.moved == other.moved
811 && self.content.try_squash(&other.content)
812 {
813 self.len = self.content.len(OffsetKind::Utf16);
814 if let Some(mut right_right) = other.right {
815 right_right.left = Some(*self);
816 }
817 if other.info.is_keep() {
818 self.info.set_keep();
819 }
820 self.right = other.right;
821 true
822 } else {
823 false
824 }
825 }
826
827 pub(crate) fn as_branch(self) -> Option<BranchPtr> {
828 if let ItemContent::Type(branch) = &self.content {
829 Some(BranchPtr::from(branch))
830 } else {
831 None
832 }
833 }
834}
835
836impl Deref for ItemPtr {
837 type Target = Item;
838
839 fn deref(&self) -> &Self::Target {
840 unsafe { self.0.as_ref() }
841 }
842}
843
844impl DerefMut for ItemPtr {
845 fn deref_mut(&mut self) -> &mut Self::Target {
846 unsafe { self.0.as_mut() }
847 }
848}
849
850impl<'a> From<&'a mut Box<Item>> for ItemPtr {
851 fn from(block: &'a mut Box<Item>) -> Self {
852 ItemPtr(NonNull::from(block.as_mut()))
853 }
854}
855
856impl<'a> From<&'a Box<Item>> for ItemPtr {
857 fn from(block: &'a Box<Item>) -> Self {
858 ItemPtr(unsafe { NonNull::new_unchecked(block.as_ref() as *const Item as *mut Item) })
859 }
860}
861
862impl Eq for ItemPtr {}
863
864impl PartialEq for ItemPtr {
865 fn eq(&self, other: &Self) -> bool {
866 // BlockPtr.pivot may differ, but logically it doesn't affect block equality
867 self.id() == other.id()
868 }
869}
870
871impl TryFrom<ItemPtr> for Any {
872 type Error = ItemPtr;
873
874 fn try_from(item: ItemPtr) -> Result<Self, Self::Error> {
875 match &item.content {
876 ItemContent::Any(v) => Ok(v[0].clone()),
877 ItemContent::Embed(v) => Ok(v.clone()),
878 ItemContent::Binary(v) => Ok(v.clone().into()),
879 ItemContent::JSON(v) => Ok(v[0].clone().into()),
880 ItemContent::String(v) => Ok(v.to_string().into()),
881 _ => Err(item),
882 }
883 }
884}
885
886impl Item {
887 #[inline]
888 pub(crate) fn clock_range(&self) -> (u32, u32) {
889 let start = self.id.clock;
890 let end = start + self.len - 1;
891 (start, end)
892 }
893
894 pub fn encode<E: Encoder>(&self, encoder: &mut E) {
895 let info = self.info();
896 let cant_copy_parent_info = info & (HAS_ORIGIN | HAS_RIGHT_ORIGIN) == 0;
897 encoder.write_info(info);
898 if let Some(origin_id) = self.origin.as_ref() {
899 encoder.write_left_id(origin_id);
900 }
901 if let Some(right_origin_id) = self.right_origin.as_ref() {
902 encoder.write_right_id(right_origin_id);
903 }
904 if cant_copy_parent_info {
905 match &self.parent {
906 TypePtr::Branch(branch) => {
907 if let Some(block) = branch.item {
908 encoder.write_parent_info(false);
909 encoder.write_left_id(block.id());
910 } else if let Some(name) = branch.name.as_deref() {
911 encoder.write_parent_info(true);
912 encoder.write_string(name);
913 } else {
914 unreachable!("Could not get parent branch info for item")
915 }
916 }
917 TypePtr::Named(name) => {
918 encoder.write_parent_info(true);
919 encoder.write_string(name);
920 }
921 TypePtr::ID(id) => {
922 encoder.write_parent_info(false);
923 encoder.write_left_id(id);
924 }
925 TypePtr::Unknown => {
926 panic!("Couldn't get item's parent")
927 }
928 }
929 if let Some(parent_sub) = self.parent_sub.as_ref() {
930 encoder.write_string(parent_sub.as_ref());
931 }
932 }
933 self.content.encode(encoder);
934 }
935
936 /// Returns a unique identifier of a first update contained by a current [Item].
937 pub fn id(&self) -> &ID {
938 &self.id
939 }
940}
941
942/// A helper structure that's used to precisely describe a location of an [Item] to be inserted in
943/// relation to its neighbors and parent.
944#[derive(Debug)]
945pub(crate) struct ItemPosition {
946 pub parent: TypePtr,
947 pub left: Option<ItemPtr>,
948 pub right: Option<ItemPtr>,
949 pub index: u32,
950 pub current_attrs: Option<Box<Attrs>>,
951}
952
953impl ItemPosition {
954 pub fn forward(&mut self) -> bool {
955 if let Some(right) = self.right.as_deref() {
956 if !right.is_deleted() {
957 match &right.content {
958 ItemContent::String(_) | ItemContent::Embed(_) => {
959 self.index += right.len();
960 }
961 ItemContent::Format(key, value) => {
962 let attrs = self.current_attrs.get_or_init();
963 update_current_attributes(attrs, key, value.as_ref());
964 }
965 _ => {}
966 }
967 }
968
969 let new = right.right.clone();
970 self.left = self.right.take();
971 self.right = new;
972
973 return true;
974 }
975 false
976 }
977
978 /// If current `attributes` don't confirm the same keys as the formatting wrapping
979 /// current insert position, they should be unset.
980 pub fn unset_missing(&self, attributes: &mut Attrs) {
981 if let Some(attrs) = self.current_attrs.as_ref() {
982 // if current `attributes` don't confirm the same keys as the formatting wrapping
983 // current insert position, they should be unset
984 for (k, _) in attrs.iter() {
985 if !attributes.contains_key(k) {
986 attributes.insert(k.clone(), Any::Null);
987 }
988 }
989 }
990 }
991}
992
993/// Bit flag (9st bit) for item that is linked by Weak Link references
994const ITEM_FLAG_LINKED: u16 = 0b0001_0000_0000;
995
996/// Bit flag (4th bit) for a marked item - not used atm.
997const ITEM_FLAG_MARKED: u16 = 0b0000_1000;
998
999/// Bit flag (3rd bit) for a tombstoned (deleted) item.
1000const ITEM_FLAG_DELETED: u16 = 0b0000_0100;
1001
1002/// Bit flag (2nd bit) for an item, which contents are considered countable.
1003const ITEM_FLAG_COUNTABLE: u16 = 0b0000_0010;
1004
1005/// Bit flag (1st bit) used for an item which should be kept - not used atm.
1006const ITEM_FLAG_KEEP: u16 = 0b0000_0001;
1007
1008/// Collection of flags attached to an [Item] - most of them are serializable and define specific
1009/// properties of an associated [Item], like:
1010///
1011/// - Has item been deleted?
1012/// - Is item countable (should its content add to the length/offset calculation of containing collection)?
1013/// - Should item be kept untouched eg. because it's being tracked by [UndoManager].
1014#[repr(transparent)]
1015#[derive(Debug, Copy, Clone, PartialEq, Eq)]
1016pub struct ItemFlags(u16);
1017
1018impl ItemFlags {
1019 pub fn new(source: u16) -> Self {
1020 ItemFlags(source)
1021 }
1022
1023 #[inline]
1024 fn set(&mut self, value: u16) {
1025 self.0 |= value
1026 }
1027
1028 #[inline]
1029 fn clear(&mut self, value: u16) {
1030 self.0 &= !value
1031 }
1032
1033 #[inline]
1034 fn check(&self, value: u16) -> bool {
1035 self.0 & value == value
1036 }
1037
1038 #[inline]
1039 pub fn is_keep(&self) -> bool {
1040 self.check(ITEM_FLAG_KEEP)
1041 }
1042
1043 #[inline]
1044 pub fn set_keep(&mut self) {
1045 self.set(ITEM_FLAG_KEEP)
1046 }
1047
1048 #[inline]
1049 pub fn clear_keep(&mut self) {
1050 self.clear(ITEM_FLAG_KEEP)
1051 }
1052
1053 #[inline]
1054 pub fn set_countable(&mut self) {
1055 self.set(ITEM_FLAG_COUNTABLE)
1056 }
1057
1058 #[inline]
1059 pub fn clear_countable(&mut self) {
1060 self.clear(ITEM_FLAG_COUNTABLE)
1061 }
1062
1063 #[inline]
1064 pub fn is_countable(&self) -> bool {
1065 self.check(ITEM_FLAG_COUNTABLE)
1066 }
1067
1068 #[inline]
1069 pub fn set_deleted(&mut self) {
1070 self.set(ITEM_FLAG_DELETED)
1071 }
1072
1073 #[inline]
1074 pub fn is_deleted(&self) -> bool {
1075 self.check(ITEM_FLAG_DELETED)
1076 }
1077
1078 #[inline]
1079 pub fn is_marked(&self) -> bool {
1080 self.check(ITEM_FLAG_MARKED)
1081 }
1082
1083 #[inline]
1084 pub fn is_linked(&self) -> bool {
1085 self.check(ITEM_FLAG_LINKED)
1086 }
1087
1088 #[inline]
1089 pub fn set_linked(&mut self) {
1090 self.set(ITEM_FLAG_LINKED)
1091 }
1092
1093 #[inline]
1094 pub fn clear_linked(&mut self) {
1095 self.clear(ITEM_FLAG_LINKED)
1096 }
1097}
1098
1099impl Into<u16> for ItemFlags {
1100 #[inline]
1101 fn into(self) -> u16 {
1102 self.0
1103 }
1104}
1105
1106/// Block defines a range of consecutive updates performed by the same peer. While individual
1107/// updates are always uniquely defined by their corresponding [ID]s, they may contain a lot of
1108/// additional metadata. Block representation here is crucial, since it optimizes memory usage,
1109/// available when multiple updates have been performed one after another (eg. *when user is writing
1110/// a sentence, individual key strokes are independent updates but they can be compresses into a
1111/// single block containing an entire sentence for as long as another piece of data is not being
1112/// inserted in the middle it*).
1113#[derive(PartialEq)]
1114pub struct Item {
1115 /// Unique identifier of the first update described by the current [Item].
1116 pub(crate) id: ID,
1117
1118 /// A number of splittable updates within a current [Item].
1119 pub(crate) len: u32,
1120
1121 /// Pointer to left neighbor of this item. Used in sequenced collections.
1122 /// If `None`, then current item is the first one on its [parent](Item::parent) collection.
1123 pub(crate) left: Option<ItemPtr>,
1124
1125 /// Pointer to right neighbor of this item. Used in sequenced collections.
1126 /// If `None`, then current item is the last one on its [parent](Item::parent) collection.
1127 ///
1128 /// For map-like CRDTs if this field is `None`, it means that a current item also contains
1129 /// the most recent update for an individual key-value entry.
1130 pub(crate) right: Option<ItemPtr>,
1131
1132 /// Used for concurrent insert conflict resolution. An ID of a left-side neighbor at the moment
1133 /// of insertion of current block.
1134 pub(crate) origin: Option<ID>,
1135
1136 /// Used for concurrent insert conflict resolution. An ID of a right-side neighbor at the moment
1137 /// of insertion of current block.
1138 pub(crate) right_origin: Option<ID>,
1139
1140 /// A user data stored inside of a current item.
1141 pub(crate) content: ItemContent,
1142
1143 /// Pointer to a parent collection containing current item.
1144 pub(crate) parent: TypePtr,
1145
1146 /// Used by [UndoManager] to track another block that reverts the effects of deletion of current
1147 /// item.
1148 pub(crate) redone: Option<ID>,
1149
1150 /// Used only when current item is used by map-like types. In such case this item works as a
1151 /// key-value entry of a map, and this field contains a key used by map.
1152 pub(crate) parent_sub: Option<Arc<str>>,
1153
1154 /// This property is reused by the moved prop. In this case this property refers to an Item.
1155 pub(crate) moved: Option<ItemPtr>,
1156
1157 /// Bit flag field which contains information about specifics of this item.
1158 pub(crate) info: ItemFlags,
1159}
1160
1161/// Describes a consecutive range of updates (identified by their [ID]s).
1162#[derive(PartialEq, Eq, Clone)]
1163pub struct BlockRange {
1164 /// [ID] of the first update stored within current [BlockRange] bounds.
1165 pub id: ID,
1166 /// Number of splittable updates stored within this [BlockRange].
1167 pub len: u32,
1168}
1169
1170impl BlockRange {
1171 pub fn new(id: ID, len: u32) -> Self {
1172 BlockRange { id, len }
1173 }
1174
1175 /// Returns an [ID] of the last update fitting into the bounds of current [BlockRange]
1176 pub fn last_id(&self) -> ID {
1177 ID::new(self.id.client, self.id.clock + self.len)
1178 }
1179
1180 /// Returns a slice of a current [BlockRange], which starts at a given offset (relative to
1181 /// current range).
1182 ///
1183 /// # Example:
1184 ///
1185 /// ```rust
1186 /// use yrs::block::BlockRange;
1187 /// use yrs::ID;
1188 /// let a = BlockRange::new(ID::new(1, 2), 8); // range of clocks [2..10)
1189 /// let b = a.slice(3); // range of clocks [5..10)
1190 ///
1191 /// assert_eq!(b.id, ID::new(1, 5));
1192 /// assert_eq!(b.last_id(), ID::new(1, 10));
1193 /// ```
1194 pub fn slice(&self, offset: u32) -> Self {
1195 let mut next = self.clone();
1196 next.id.clock += offset;
1197 next.len -= offset;
1198 next
1199 }
1200
1201 pub(crate) fn integrate(&mut self, pivot: u32) -> bool {
1202 if pivot > 0 {
1203 self.id.clock += pivot;
1204 self.len -= pivot;
1205 }
1206
1207 false
1208 }
1209
1210 #[inline]
1211 pub(crate) fn merge(&mut self, other: &Self) {
1212 self.len += other.len;
1213 }
1214
1215 /// Checks if provided `id` fits inside of boundaries defined by current [BlockRange].
1216 pub fn contains(&self, id: &ID) -> bool {
1217 self.id.client == id.client
1218 && id.clock >= self.id.clock
1219 && id.clock < self.id.clock + self.len
1220 }
1221}
1222
1223impl std::fmt::Debug for BlockRange {
1224 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1225 std::fmt::Display::fmt(self, f)
1226 }
1227}
1228
1229impl std::fmt::Display for BlockRange {
1230 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1231 write!(f, "({}-{})", self.id, self.len)
1232 }
1233}
1234
1235impl Item {
1236 pub(crate) fn new(
1237 id: ID,
1238 left: Option<ItemPtr>,
1239 origin: Option<ID>,
1240 right: Option<ItemPtr>,
1241 right_origin: Option<ID>,
1242 parent: TypePtr,
1243 parent_sub: Option<Arc<str>>,
1244 content: ItemContent,
1245 ) -> Option<Box<Item>> {
1246 let info = ItemFlags::new(if content.is_countable() {
1247 ITEM_FLAG_COUNTABLE
1248 } else {
1249 0
1250 });
1251 let len = content.len(OffsetKind::Utf16);
1252 if len == 0 {
1253 return None;
1254 }
1255 let root_name = if let TypePtr::Named(root) = &parent {
1256 Some(root.clone())
1257 } else {
1258 None
1259 };
1260 let mut item = Box::new(Item {
1261 id,
1262 len,
1263 left,
1264 right,
1265 origin,
1266 right_origin,
1267 content,
1268 parent,
1269 parent_sub,
1270 info,
1271 moved: None,
1272 redone: None,
1273 });
1274 let item_ptr = ItemPtr::from(&mut item);
1275 if let ItemContent::Type(branch) = &mut item.content {
1276 branch.item = Some(item_ptr);
1277 if branch.name.is_none() {
1278 branch.name = root_name;
1279 }
1280 }
1281 Some(item)
1282 }
1283
1284 /// Checks if provided `id` fits inside of updates defined within bounds of current [Item].
1285 pub fn contains(&self, id: &ID) -> bool {
1286 self.id.client == id.client
1287 && id.clock >= self.id.clock
1288 && id.clock < self.id.clock + self.len()
1289 }
1290
1291 /// Checks if current item is marked as deleted (tombstoned).
1292 /// Yrs uses soft item deletion mechanism, which means that deleted values are not physically
1293 /// erased from memory, but just marked as deleted.
1294 pub fn is_deleted(&self) -> bool {
1295 self.info.is_deleted()
1296 }
1297
1298 /// Checks if item content can be considered countable. Countable elements can be split
1299 /// and joined together.
1300 pub fn is_countable(&self) -> bool {
1301 self.info.is_countable()
1302 }
1303
1304 pub(crate) fn mark_as_deleted(&mut self) {
1305 self.info.set_deleted()
1306 }
1307
1308 /// Assign left/right neighbors of the block. This may require for origin/right_origin
1309 /// blocks to be already present in block store - which may not be the case during block
1310 /// decoding. We decode entire update first, and apply individual blocks second, hence
1311 /// repair function is called before applying the block rather than on decode.
1312 pub(crate) fn repair(&mut self, store: &mut Store) -> Result<(), UpdateError> {
1313 if let Some(origin) = self.origin.as_ref() {
1314 self.left = store
1315 .blocks
1316 .get_item_clean_end(origin)
1317 .map(|slice| store.materialize(slice));
1318 }
1319
1320 if let Some(origin) = self.right_origin.as_ref() {
1321 self.right = store
1322 .blocks
1323 .get_item_clean_start(origin)
1324 .map(|slice| store.materialize(slice));
1325 }
1326
1327 // We have all missing ids, now find the items
1328
1329 // In the original Y.js algorithm we decoded items as we go and attached them to client
1330 // block list. During that process if we had right origin but no left, we made a lookup for
1331 // right origin's parent and attach it as a parent of current block.
1332 //
1333 // Here since we decode all blocks first, then apply them, we might not find them in
1334 // the block store during decoding. Therefore we retroactively reattach it here.
1335
1336 self.parent = match &self.parent {
1337 TypePtr::Branch(branch_ptr) => TypePtr::Branch(*branch_ptr),
1338 TypePtr::Unknown => match (self.left, self.right) {
1339 (Some(item), _) if item.parent != TypePtr::Unknown => {
1340 self.parent_sub = item.parent_sub.clone();
1341 item.parent.clone()
1342 }
1343 (_, Some(item)) if item.parent != TypePtr::Unknown => {
1344 self.parent_sub = item.parent_sub.clone();
1345 item.parent.clone()
1346 }
1347 _ => TypePtr::Unknown,
1348 },
1349 TypePtr::Named(name) => {
1350 let branch = store.get_or_create_type(name.clone(), TypeRef::Undefined);
1351 TypePtr::Branch(branch)
1352 }
1353 TypePtr::ID(id) => {
1354 let ptr = store.blocks.get_item(id);
1355 if let Some(item) = ptr {
1356 match &item.content {
1357 ItemContent::Type(branch) => {
1358 TypePtr::Branch(BranchPtr::from(branch.as_ref()))
1359 }
1360 ItemContent::Deleted(_) => TypePtr::Unknown,
1361 other => {
1362 return Err(UpdateError::InvalidParent(
1363 id.clone(),
1364 other.get_ref_number(),
1365 ))
1366 }
1367 }
1368 } else {
1369 TypePtr::Unknown
1370 }
1371 }
1372 };
1373
1374 Ok(())
1375 }
1376
1377 /// Returns a length of a block. For most situation it works like [Item::content_len] with a
1378 /// difference to a [Text]/[XmlText] contents - in order to achieve compatibility with
1379 /// Yjs we need to calculate string length in terms of UTF-16 character encoding.
1380 /// However depending on used [Encoding] scheme we may calculate string length/offsets
1381 /// differently.
1382 pub fn len(&self) -> u32 {
1383 self.len
1384 }
1385
1386 pub fn content_len(&self, kind: OffsetKind) -> u32 {
1387 self.content.len(kind)
1388 }
1389
1390 /// Returns an ID of the last element that can be considered a part of this item.
1391 pub fn last_id(&self) -> ID {
1392 ID::new(self.id.client, self.id.clock + self.len() - 1)
1393 }
1394
1395 pub fn info(&self) -> u8 {
1396 let info = if self.origin.is_some() { HAS_ORIGIN } else { 0 } // is left null
1397 | if self.right_origin.is_some() { HAS_RIGHT_ORIGIN } else { 0 } // is right null
1398 | if self.parent_sub.is_some() { HAS_PARENT_SUB } else { 0 }
1399 | (self.content.get_ref_number() & 0b1111);
1400 info
1401 }
1402
1403 pub(crate) fn gc(&mut self, collector: &mut GCCollector, parent_gc: bool) {
1404 // Backport of y-crdt 0e5df00 (see PATCHES.md): the keep flag is checked by
1405 // the collector for top-level candidates only. Children of a collected
1406 // type go with it whatever their flag, as in Yjs (ContentType.gc); a kept
1407 // child left behind would point into its parent's freed branch.
1408 if self.is_deleted() {
1409 self.content.gc(collector);
1410 let len = self.len();
1411 if parent_gc {
1412 collector.mark(&self.id);
1413 } else {
1414 self.content = ItemContent::Deleted(len);
1415 self.info.clear_countable();
1416 }
1417 }
1418 }
1419}
1420
1421#[derive(PartialEq, PartialOrd, Eq, Ord, Debug, Clone)]
1422pub struct SplittableString {
1423 content: SmallString<[u8; 8]>,
1424}
1425
1426impl SplittableString {
1427 pub fn len(&self, kind: OffsetKind) -> usize {
1428 let len = self.content.len();
1429 if len == 1 {
1430 len // quite often strings are single-letter, so we don't care about OffsetKind
1431 } else {
1432 match kind {
1433 OffsetKind::Bytes => len,
1434 OffsetKind::Utf16 => self.utf16_len(),
1435 }
1436 }
1437 }
1438
1439 #[inline(always)]
1440 pub fn as_str(&self) -> &str {
1441 self.content.as_str()
1442 }
1443
1444 #[inline(always)]
1445 pub fn utf16_len(&self) -> usize {
1446 self.encode_utf16().count()
1447 }
1448
1449 /// Maps given offset onto block offset. This means, that given an `offset` provided
1450 /// in given `encoding` we want the output as a UTF-16 compatible offset (required
1451 /// by Yjs for compatibility reasons).
1452 pub(crate) fn block_offset(&self, offset: u32, kind: OffsetKind) -> u32 {
1453 match kind {
1454 OffsetKind::Utf16 => offset,
1455 OffsetKind::Bytes => {
1456 let mut remaining = offset;
1457 let mut i = 0;
1458 // since this offset is used to splitting later on - and we can only split entire
1459 // characters - we're computing by characters
1460 for c in self.content.chars() {
1461 if remaining == 0 {
1462 break;
1463 }
1464 remaining -= c.len_utf8() as u32;
1465 i += c.len_utf16() as u32;
1466 }
1467 i
1468 }
1469 }
1470 }
1471
1472 pub fn push_str(&mut self, str: &str) {
1473 self.content.push_str(str);
1474 }
1475}
1476
1477impl std::fmt::Display for SplittableString {
1478 #[inline(always)]
1479 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1480 self.content.fmt(f)
1481 }
1482}
1483
1484impl Into<SmallString<[u8; 8]>> for SplittableString {
1485 #[inline(always)]
1486 fn into(self) -> SmallString<[u8; 8]> {
1487 self.content
1488 }
1489}
1490
1491impl Into<Box<str>> for SplittableString {
1492 #[inline(always)]
1493 fn into(self) -> Box<str> {
1494 self.content.into_string().into_boxed_str()
1495 }
1496}
1497
1498impl From<SmallString<[u8; 8]>> for SplittableString {
1499 fn from(content: SmallString<[u8; 8]>) -> Self {
1500 SplittableString { content }
1501 }
1502}
1503
1504impl<'a> From<&'a str> for SplittableString {
1505 fn from(str: &'a str) -> Self {
1506 Self::from(SmallString::from_str(str))
1507 }
1508}
1509
1510impl Deref for SplittableString {
1511 type Target = str;
1512
1513 #[inline(always)]
1514 fn deref(&self) -> &Self::Target {
1515 &self.content
1516 }
1517}
1518
1519pub(crate) fn split_str(str: &str, offset: usize, kind: OffsetKind) -> (&str, &str) {
1520 fn map_utf16_offset(str: &str, offset: u32) -> u32 {
1521 let mut off = 0;
1522 let mut i = 0;
1523 for c in str.chars() {
1524 if i >= offset {
1525 break;
1526 }
1527 off += c.len_utf8() as u32;
1528 i += c.len_utf16() as u32;
1529 }
1530 off
1531 }
1532
1533 let off = match kind {
1534 OffsetKind::Bytes => offset,
1535 OffsetKind::Utf16 => map_utf16_offset(str, offset as u32) as usize,
1536 };
1537 str.split_at(off)
1538}
1539
1540/// An enum describing the type of a user data content stored as part of one or more
1541/// (if items were squashed) insert operations.
1542#[derive(Debug, PartialEq)]
1543pub enum ItemContent {
1544 /// Collection of consecutively inserted JSON-like primitive values.
1545 Any(Vec<Any>),
1546
1547 /// A BLOB data eg. images. Binaries are treated as a single objects (they are not subjects to splits).
1548 Binary(Vec<u8>),
1549
1550 /// A marker for delete item data, which describes a number of deleted elements.
1551 /// Deleted elements also don't contribute to an overall length of containing collection type.
1552 Deleted(u32),
1553
1554 /// Sub-document container. Contains weak reference to a parent document and a child document.
1555 Doc(Option<Doc>, Doc),
1556
1557 /// Obsolete: collection of consecutively inserted stringified JSON values.
1558 JSON(Vec<String>),
1559
1560 /// A single embedded JSON-like primitive value.
1561 Embed(Any),
1562
1563 /// Formatting attribute entry. Format attributes are not considered countable and don't
1564 /// contribute to an overall length of a collection they are applied to.
1565 Format(Arc<str>, Box<Any>),
1566
1567 /// A chunk of text, usually applied by collaborative text insertion.
1568 String(SplittableString),
1569
1570 /// A reference of a branch node. Branch nodes define a complex collection types, such as
1571 /// arrays, maps or XML elements.
1572 Type(Box<Branch>),
1573
1574 /// Marker for destination location of move operation. Move is used to change position of
1575 /// previously inserted element in a sequence with respect to other operations that may happen
1576 /// concurrently on other peers.
1577 Move(Box<Move>),
1578}
1579
1580impl ItemContent {
1581 /// Returns a reference number used to determine a content type.
1582 /// It's used during encoding/decoding of a containing block.
1583 pub fn get_ref_number(&self) -> u8 {
1584 match self {
1585 ItemContent::Any(_) => BLOCK_ITEM_ANY_REF_NUMBER,
1586 ItemContent::Binary(_) => BLOCK_ITEM_BINARY_REF_NUMBER,
1587 ItemContent::Deleted(_) => BLOCK_ITEM_DELETED_REF_NUMBER,
1588 ItemContent::Doc(_, _) => BLOCK_ITEM_DOC_REF_NUMBER,
1589 ItemContent::JSON(_) => BLOCK_ITEM_JSON_REF_NUMBER,
1590 ItemContent::Embed(_) => BLOCK_ITEM_EMBED_REF_NUMBER,
1591 ItemContent::Format(_, _) => BLOCK_ITEM_FORMAT_REF_NUMBER,
1592 ItemContent::String(_) => BLOCK_ITEM_STRING_REF_NUMBER,
1593 ItemContent::Type(_) => BLOCK_ITEM_TYPE_REF_NUMBER,
1594 ItemContent::Move(_) => BLOCK_ITEM_MOVE_REF_NUMBER,
1595 }
1596 }
1597
1598 /// Checks if item content can be considered countable. Countable elements contribute to
1599 /// a length of the block they are contained by. Most of the item content variants are countable
1600 /// with exception for [ItemContent::Deleted] (which length describes number of removed
1601 /// elements) and [ItemContent::Format] (which is used for storing text formatting tags).
1602 pub fn is_countable(&self) -> bool {
1603 match self {
1604 ItemContent::Any(_) => true,
1605 ItemContent::Binary(_) => true,
1606 ItemContent::Doc(_, _) => true,
1607 ItemContent::JSON(_) => true,
1608 ItemContent::Embed(_) => true,
1609 ItemContent::String(_) => true,
1610 ItemContent::Type(_) => true,
1611 ItemContent::Deleted(_) => false,
1612 ItemContent::Format(_, _) => false,
1613 ItemContent::Move(_) => false,
1614 }
1615 }
1616
1617 /// Returns a number of separate elements contained within current item content struct.
1618 ///
1619 /// Separate elements can be split in order to put another block in between them. Definition of
1620 /// separation depends on a item content kin, eg. [ItemContent::String], [ItemContent::Any],
1621 /// [ItemContent::JSON] and [ItemContent::Deleted] can have variable length as they may be split
1622 /// by other insert operations. Other variants (eg. [ItemContent::Binary]) are considered as
1623 /// a single element and therefore their length is always 1 and are not considered as subject of
1624 /// splitting.
1625 ///
1626 /// In cases of counting number of visible elements, `len` method should be used together with
1627 /// [ItemContent::is_countable].
1628 pub fn len(&self, kind: OffsetKind) -> u32 {
1629 match self {
1630 ItemContent::Deleted(deleted) => *deleted,
1631 ItemContent::String(str) => str.len(kind) as u32,
1632 ItemContent::Any(v) => v.len() as u32,
1633 ItemContent::JSON(v) => v.len() as u32,
1634 _ => 1,
1635 }
1636 }
1637
1638 /// Reads a contents of current [ItemContent] into a given `buf`, starting from provided
1639 /// `offset`. Returns a number of elements read this way (it cannot be longer than `buf`'s len.
1640 pub fn read(&self, offset: usize, buf: &mut [Out]) -> usize {
1641 if buf.is_empty() {
1642 0
1643 } else {
1644 match self {
1645 ItemContent::Any(values) => {
1646 let mut i = offset;
1647 let mut j = 0;
1648 while i < values.len() && j < buf.len() {
1649 let any = &values[i];
1650 buf[j] = Out::Any(any.clone());
1651 i += 1;
1652 j += 1;
1653 }
1654 j
1655 }
1656 ItemContent::String(v) => {
1657 let chars = v.chars().skip(offset).take(buf.len());
1658 let mut j = 0;
1659 for c in chars {
1660 buf[j] = Out::Any(Any::from(c.to_string()));
1661 j += 1;
1662 }
1663 j
1664 }
1665 ItemContent::JSON(elements) => {
1666 let mut i = offset;
1667 let mut j = 0;
1668 while i < elements.len() && j < buf.len() {
1669 let elem = elements[i].as_str();
1670 buf[j] = Out::Any(Any::from(elem));
1671 i += 1;
1672 j += 1;
1673 }
1674 j
1675 }
1676 ItemContent::Binary(v) => {
1677 buf[0] = Out::Any(Any::from(v.deref()));
1678 1
1679 }
1680 ItemContent::Doc(_, doc) => {
1681 buf[0] = Out::YDoc(doc.clone());
1682 1
1683 }
1684 ItemContent::Type(c) => {
1685 let branch_ref = BranchPtr::from(c);
1686 buf[0] = branch_ref.into();
1687 1
1688 }
1689 ItemContent::Embed(v) => {
1690 buf[0] = Out::Any(v.clone());
1691 1
1692 }
1693 ItemContent::Move(_) => 0,
1694 ItemContent::Deleted(_) => 0,
1695 ItemContent::Format(_, _) => 0,
1696 }
1697 }
1698 }
1699
1700 /// Reads all contents stored in this item and returns them. Use [ItemContent::read] if you need
1701 /// to read only slice of elements from the corresponding item.
1702 pub fn get_content(&self) -> Vec<Out> {
1703 let len = self.len(OffsetKind::Utf16) as usize;
1704 let mut values = vec![Out::default(); len];
1705 let read = self.read(0, &mut values);
1706 if read == len {
1707 values
1708 } else {
1709 Vec::default()
1710 }
1711 }
1712
1713 /// Returns a first value stored in a corresponding item.
1714 pub fn get_first(&self) -> Option<Out> {
1715 match self {
1716 ItemContent::Any(v) => v.first().map(|a| Out::Any(a.clone())),
1717 ItemContent::Binary(v) => Some(Out::Any(Any::from(v.deref()))),
1718 ItemContent::Deleted(_) => None,
1719 ItemContent::Move(_) => None,
1720 ItemContent::Doc(_, v) => Some(Out::YDoc(v.clone())),
1721 ItemContent::JSON(v) => v.first().map(|v| Out::Any(Any::from(v.deref()))),
1722 ItemContent::Embed(v) => Some(Out::Any(v.clone())),
1723 ItemContent::Format(_, _) => None,
1724 ItemContent::String(v) => Some(Out::Any(Any::from(v.clone().as_str()))),
1725 ItemContent::Type(c) => Some(BranchPtr::from(c).into()),
1726 }
1727 }
1728
1729 /// Returns a last value stored in a corresponding item.
1730 pub fn get_last(&self) -> Option<Out> {
1731 match self {
1732 ItemContent::Any(v) => v.last().map(|a| Out::Any(a.clone())),
1733 ItemContent::Binary(v) => Some(Out::Any(Any::from(v.deref()))),
1734 ItemContent::Deleted(_) => None,
1735 ItemContent::Move(_) => None,
1736 ItemContent::Doc(_, v) => Some(Out::YDoc(v.clone())),
1737 ItemContent::JSON(v) => v.last().map(|v| Out::Any(Any::from(v.as_str()))),
1738 ItemContent::Embed(v) => Some(Out::Any(v.clone())),
1739 ItemContent::Format(_, _) => None,
1740 ItemContent::String(v) => Some(Out::Any(Any::from(v.as_str()))),
1741 ItemContent::Type(c) => Some(BranchPtr::from(c).into()),
1742 }
1743 }
1744
1745 /// Encodes a slice of a current [ItemContent] within an index bounds of (start..=end) - both
1746 /// sides inclusive.
1747 pub fn encode_slice<E: Encoder>(&self, encoder: &mut E, start: u32, end: u32) {
1748 match self {
1749 ItemContent::Deleted(_) => encoder.write_len(end - start + 1),
1750 ItemContent::Binary(buf) => encoder.write_buf(buf),
1751 ItemContent::String(s) => {
1752 let slice = if start != 0 {
1753 let (_, right) = split_str(&s, start as usize, OffsetKind::Utf16);
1754 right
1755 } else {
1756 &s
1757 };
1758 let slice = if end != 0 {
1759 let (left, _) =
1760 split_str(&slice, (end - start + 1) as usize, OffsetKind::Utf16);
1761 left
1762 } else {
1763 slice
1764 };
1765 encoder.write_string(slice)
1766 }
1767 ItemContent::Embed(s) => encoder.write_json(s),
1768 ItemContent::JSON(s) => {
1769 encoder.write_len(end - start + 1);
1770 for i in start..=end {
1771 encoder.write_string(s[i as usize].as_str())
1772 }
1773 }
1774 ItemContent::Format(k, v) => {
1775 encoder.write_key(k.as_ref());
1776 encoder.write_json(v.as_ref());
1777 }
1778 ItemContent::Type(inner) => {
1779 inner.type_ref.encode(encoder);
1780 }
1781 ItemContent::Any(any) => {
1782 encoder.write_len(end - start + 1);
1783 for i in start..=end {
1784 encoder.write_any(&any[i as usize]);
1785 }
1786 }
1787 ItemContent::Doc(_, doc) => doc.store().options().encode(encoder),
1788 ItemContent::Move(m) => m.encode(encoder),
1789 }
1790 }
1791
1792 pub fn encode<E: Encoder>(&self, encoder: &mut E) {
1793 match self {
1794 ItemContent::Deleted(len) => encoder.write_len(*len),
1795 ItemContent::Binary(buf) => encoder.write_buf(buf),
1796 ItemContent::String(s) => encoder.write_string(s.as_str()),
1797 ItemContent::Embed(s) => encoder.write_json(s),
1798 ItemContent::JSON(s) => {
1799 encoder.write_len(s.len() as u32);
1800 for json in s.iter() {
1801 encoder.write_string(json.as_str())
1802 }
1803 }
1804 ItemContent::Format(k, v) => {
1805 encoder.write_key(k.as_ref());
1806 encoder.write_json(v.as_ref());
1807 }
1808 ItemContent::Type(inner) => {
1809 inner.type_ref.encode(encoder);
1810 }
1811 ItemContent::Any(any) => {
1812 encoder.write_len(any.len() as u32);
1813 for a in any.iter() {
1814 encoder.write_any(a);
1815 }
1816 }
1817 ItemContent::Doc(_, doc) => doc.store().options().encode(encoder),
1818 ItemContent::Move(m) => m.encode(encoder),
1819 }
1820 }
1821
1822 pub fn decode<D: Decoder>(decoder: &mut D, ref_num: u8) -> Result<Self, Error> {
1823 match ref_num & 0b1111 {
1824 BLOCK_ITEM_DELETED_REF_NUMBER => Ok(ItemContent::Deleted(decoder.read_len()?)),
1825 BLOCK_ITEM_JSON_REF_NUMBER => {
1826 let mut remaining = decoder.read_len()? as i32;
1827 let mut buf = Vec::new();
1828 buf.try_reserve(remaining as usize)?;
1829
1830 while remaining >= 0 {
1831 buf.push(decoder.read_string()?.to_owned());
1832 remaining -= 1;
1833 }
1834 Ok(ItemContent::JSON(buf))
1835 }
1836 BLOCK_ITEM_BINARY_REF_NUMBER => Ok(ItemContent::Binary(decoder.read_buf()?.to_owned())),
1837 BLOCK_ITEM_STRING_REF_NUMBER => Ok(ItemContent::String(decoder.read_string()?.into())),
1838 BLOCK_ITEM_EMBED_REF_NUMBER => Ok(ItemContent::Embed(decoder.read_json()?.into())),
1839 BLOCK_ITEM_FORMAT_REF_NUMBER => Ok(ItemContent::Format(
1840 decoder.read_key()?,
1841 decoder.read_json()?.into(),
1842 )),
1843 BLOCK_ITEM_TYPE_REF_NUMBER => {
1844 let type_ref = TypeRef::decode(decoder)?;
1845 let inner = Branch::new(type_ref);
1846 Ok(ItemContent::Type(inner))
1847 }
1848 BLOCK_ITEM_ANY_REF_NUMBER => {
1849 let len = decoder.read_len()? as usize;
1850 let mut values = Vec::new();
1851 values.try_reserve(len)?;
1852
1853 let mut i = 0;
1854 while i < len {
1855 values.push(decoder.read_any()?);
1856 i += 1;
1857 }
1858 Ok(ItemContent::Any(values))
1859 }
1860 BLOCK_ITEM_MOVE_REF_NUMBER => {
1861 let m = Move::decode(decoder)?;
1862 Ok(ItemContent::Move(Box::new(m)))
1863 }
1864 BLOCK_ITEM_DOC_REF_NUMBER => {
1865 let mut options = Options::decode(decoder)?;
1866 options.should_load = options.should_load || options.auto_load;
1867 Ok(ItemContent::Doc(None, Doc::with_options(options)))
1868 }
1869 _ => Err(Error::UnexpectedValue),
1870 }
1871 }
1872
1873 pub(crate) fn splice(&mut self, offset: usize, encoding: OffsetKind) -> Option<ItemContent> {
1874 match self {
1875 ItemContent::Any(value) => {
1876 let (left, right) = value.split_at(offset);
1877 let left = left.to_vec();
1878 let right = right.to_vec();
1879 *self = ItemContent::Any(left);
1880 Some(ItemContent::Any(right))
1881 }
1882 ItemContent::String(string) => {
1883 // compute offset given in unicode code points into byte position
1884 let (left, right) = split_str(&string, offset, encoding);
1885 let left: SplittableString = left.into();
1886 let right: SplittableString = right.into();
1887
1888 //TODO: do we need that in Rust?
1889 //let split_point = left.chars().last().unwrap();
1890 //if split_point >= 0xD800 as char && split_point <= 0xDBFF as char {
1891 // // Last character of the left split is the start of a surrogate utf16/ucs2 pair.
1892 // // We don't support splitting of surrogate pairs because this may lead to invalid documents.
1893 // // Replace the invalid character with a unicode replacement character (� / U+FFFD)
1894 // left.replace_range((offset-1)..offset, "�");
1895 // right.replace_range(0..1, "�");
1896 //}
1897 *self = ItemContent::String(left);
1898
1899 Some(ItemContent::String(right))
1900 }
1901 ItemContent::Deleted(len) => {
1902 let right = ItemContent::Deleted(*len - offset as u32);
1903 *len = offset as u32;
1904 Some(right)
1905 }
1906 ItemContent::JSON(value) => {
1907 let (left, right) = value.split_at(offset);
1908 let left = left.to_vec();
1909 let right = right.to_vec();
1910 *self = ItemContent::JSON(left);
1911 Some(ItemContent::JSON(right))
1912 }
1913 _ => None,
1914 }
1915 }
1916
1917 /// Tries to squash two item content structures together.
1918 /// Returns `true` if this method had any effect on current [ItemContent] (modified it).
1919 /// Otherwise returns `false`.
1920 pub fn try_squash(&mut self, other: &Self) -> bool {
1921 //TODO: change `other` to Self (not ref) and return type to Option<Self> (none if merge suceeded)
1922 match (self, other) {
1923 (ItemContent::Any(v1), ItemContent::Any(v2)) => {
1924 v1.append(&mut v2.clone());
1925 true
1926 }
1927 (ItemContent::Deleted(v1), ItemContent::Deleted(v2)) => {
1928 *v1 = *v1 + *v2;
1929 true
1930 }
1931 (ItemContent::JSON(v1), ItemContent::JSON(v2)) => {
1932 v1.append(&mut v2.clone());
1933 true
1934 }
1935 (ItemContent::String(v1), ItemContent::String(v2)) => {
1936 v1.push_str(v2.as_str());
1937 true
1938 }
1939 _ => false,
1940 }
1941 }
1942
1943 pub(crate) fn gc(&mut self, collector: &mut GCCollector) {
1944 match self {
1945 ItemContent::Type(branch) => {
1946 let mut curr = branch.start.take();
1947 while let Some(mut item) = curr {
1948 curr = item.right.clone();
1949 item.gc(collector, true);
1950 }
1951
1952 for (_, ptr) in branch.map.drain() {
1953 curr = Some(ptr);
1954 while let Some(mut item) = curr {
1955 curr = item.left.clone();
1956 item.gc(collector, true);
1957 continue;
1958 }
1959 }
1960 }
1961 _ => {}
1962 }
1963 }
1964}
1965
1966impl Clone for ItemContent {
1967 fn clone(&self) -> Self {
1968 match self {
1969 ItemContent::Any(array) => ItemContent::Any(array.clone()),
1970 ItemContent::Binary(bytes) => ItemContent::Binary(bytes.clone()),
1971 ItemContent::Deleted(len) => ItemContent::Deleted(*len),
1972 ItemContent::Doc(store, doc) => ItemContent::Doc(store.clone(), doc.clone()),
1973 ItemContent::JSON(array) => ItemContent::JSON(array.clone()),
1974 ItemContent::Embed(json) => ItemContent::Embed(json.clone()),
1975 ItemContent::Format(key, value) => ItemContent::Format(key.clone(), value.clone()),
1976 ItemContent::String(chunk) => ItemContent::String(chunk.clone()),
1977 ItemContent::Type(branch) => ItemContent::Type(Branch::new(branch.type_ref.clone())),
1978 ItemContent::Move(range) => ItemContent::Move(range.clone()),
1979 }
1980 }
1981}
1982
1983impl std::fmt::Debug for Item {
1984 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1985 std::fmt::Display::fmt(self, f)
1986 }
1987}
1988
1989impl std::fmt::Display for Item {
1990 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1991 write!(f, "({}, len: {}", self.id, self.len)?;
1992 match &self.parent {
1993 TypePtr::Unknown => {}
1994 TypePtr::Branch(b) => {
1995 if let Some(ptr) = b.item.as_ref() {
1996 write!(f, ", parent: {}", ptr.id())?;
1997 } else {
1998 write!(f, ", parent: <root>")?;
1999 }
2000 }
2001 other => {
2002 write!(f, ", parent: {}", other)?;
2003 }
2004 }
2005 if let Some(m) = self.moved {
2006 write!(f, ", moved-to: {}", m)?;
2007 }
2008 if let Some(id) = self.redone.as_ref() {
2009 write!(f, ", redone: {}", id)?;
2010 }
2011 if let Some(origin) = self.origin.as_ref() {
2012 write!(f, ", origin-l: {}", origin)?;
2013 }
2014 if let Some(origin) = self.right_origin.as_ref() {
2015 write!(f, ", origin-r: {}", origin)?;
2016 }
2017 if let Some(left) = self.left.as_ref() {
2018 write!(f, ", left: {}", left.id())?;
2019 }
2020 if let Some(right) = self.right.as_ref() {
2021 write!(f, ", right: {}", right.id())?;
2022 }
2023 if let Some(key) = self.parent_sub.as_ref() {
2024 write!(f, ", '{}' =>", key)?;
2025 } else {
2026 write!(f, ":")?;
2027 }
2028 if self.is_deleted() {
2029 write!(f, " ~{}~", &self.content)?;
2030 } else {
2031 write!(f, " {}", &self.content)?;
2032 }
2033 if self.info.is_linked() {
2034 write!(f, "|linked")?;
2035 }
2036 write!(f, ")")
2037 }
2038}
2039
2040impl std::fmt::Display for ItemContent {
2041 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2042 match self {
2043 ItemContent::String(s) => write!(f, "'{}'", s),
2044 ItemContent::Any(s) => {
2045 write!(f, "[")?;
2046 let mut iter = s.iter();
2047 if let Some(a) = iter.next() {
2048 write!(f, "{}", a.to_string())?;
2049 }
2050 while let Some(a) = iter.next() {
2051 write!(f, ", {}", a.to_string())?;
2052 }
2053 write!(f, "]")
2054 }
2055 ItemContent::JSON(s) => {
2056 write!(f, "{{")?;
2057 let mut iter = s.iter();
2058 if let Some(a) = iter.next() {
2059 write!(f, "{}", a)?;
2060 }
2061 while let Some(a) = iter.next() {
2062 write!(f, ", {}", a)?;
2063 }
2064 write!(f, "}}")
2065 }
2066 ItemContent::Format(k, v) => write!(f, "<{}={}>", k, v),
2067 ItemContent::Deleted(s) => write!(f, "deleted({})", s),
2068 ItemContent::Binary(s) => write!(f, "{:?}", s),
2069 ItemContent::Type(inner) => match &inner.type_ref {
2070 TypeRef::Array => {
2071 if let Some(ptr) = inner.start {
2072 write!(f, "<array(head: {})>", ptr)
2073 } else {
2074 write!(f, "<array>")
2075 }
2076 }
2077 TypeRef::Map => {
2078 write!(f, "<map({{")?;
2079 let mut iter = inner.map.iter();
2080 if let Some((k, ptr)) = iter.next() {
2081 write!(f, "'{}': {}", k, ptr)?;
2082 }
2083 while let Some((k, ptr)) = iter.next() {
2084 write!(f, ", '{}': {}", k, ptr)?;
2085 }
2086 write!(f, "}})>")
2087 }
2088 TypeRef::Text => {
2089 if let Some(start) = inner.start {
2090 write!(f, "<text(head: {})>", start)
2091 } else {
2092 write!(f, "<text>")
2093 }
2094 }
2095 TypeRef::XmlElement(name) => {
2096 write!(f, "<xml element: {}>", name)
2097 }
2098 TypeRef::XmlFragment => write!(f, "<xml fragment>"),
2099 TypeRef::XmlHook => write!(f, "<xml hook>"),
2100 TypeRef::XmlText => write!(f, "<xml text>"),
2101 #[cfg(feature = "weak")]
2102 TypeRef::WeakLink(s) => write!(f, "<weak({}..{})>", s.quote_start, s.quote_end),
2103 _ => write!(f, "<undefined type ref>"),
2104 },
2105 ItemContent::Move(m) => std::fmt::Display::fmt(m.as_ref(), f),
2106 ItemContent::Doc(_, doc) => std::fmt::Display::fmt(doc, f),
2107 _ => Ok(()),
2108 }
2109 }
2110}
2111
2112impl std::fmt::Display for ItemPosition {
2113 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2114 write!(f, "(index: {}", self.index)?;
2115 if let Some(l) = self.left.as_ref() {
2116 write!(f, ", left: {}", l)?;
2117 }
2118 if let Some(r) = self.right.as_ref() {
2119 write!(f, ", right: {}", r)?;
2120 }
2121 write!(f, ")")
2122 }
2123}
2124
2125/// A trait used for preliminary types, that can be inserted into shared Yrs collections.
2126pub trait Prelim: Sized {
2127 /// Type of a value to be returned as a result of inserting this [Prelim] type instance.
2128 /// Use [Unused] if none is necessary.
2129 type Return: TryFrom<ItemPtr>;
2130
2131 /// This method is used to create initial content required in order to create a block item.
2132 /// A supplied `ptr` can be used to identify block that is about to be created to store
2133 /// the returned content.
2134 ///
2135 /// Since this method may decide to consume `self` or not, a second optional return parameter
2136 /// is used when `self` was not consumed - which is the case for complex types creation such as
2137 /// YMap or YArray. In such case it will be passed later on to [Self::integrate] method.
2138 fn into_content(self, txn: &mut TransactionMut) -> (ItemContent, Option<Self>);
2139
2140 /// Method called once an original item filled with content from [Self::into_content] has been
2141 /// added to block store. This method is used by complex types such as maps or arrays to append
2142 /// the original contents of prelim struct into YMap, YArray etc.
2143 fn integrate(self, txn: &mut TransactionMut, inner_ref: BranchPtr);
2144}
2145
2146impl<T> Prelim for T
2147where
2148 T: Into<Any>,
2149{
2150 type Return = Unused;
2151
2152 fn into_content(self, _txn: &mut TransactionMut) -> (ItemContent, Option<Self>) {
2153 let value: Any = self.into();
2154 (ItemContent::Any(vec![value]), None)
2155 }
2156
2157 fn integrate(self, _txn: &mut TransactionMut, _inner_ref: BranchPtr) {}
2158}
2159
2160#[derive(Debug)]
2161pub(crate) struct PrelimString(pub SmallString<[u8; 8]>);
2162
2163impl Prelim for PrelimString {
2164 type Return = Unused;
2165
2166 fn into_content(self, _txn: &mut TransactionMut) -> (ItemContent, Option<Self>) {
2167 (ItemContent::String(self.0.into()), None)
2168 }
2169
2170 fn integrate(self, _txn: &mut TransactionMut, _inner_ref: BranchPtr) {}
2171}
2172
2173/// Empty type marker, which can be used by a [Prelim] trait implementations when no integrated
2174/// value should be returned after prelim type has been integrated as a result of insertion.
2175#[repr(transparent)]
2176pub struct Unused;
2177
2178impl TryFrom<ItemPtr> for Unused {
2179 type Error = ItemPtr;
2180
2181 #[inline(always)]
2182 fn try_from(_: ItemPtr) -> Result<Self, Self::Error> {
2183 Ok(Unused)
2184 }
2185}
2186
2187/// Prelim container for types passed over to [Text::insert_embed] and [Text::insert_embed_with_attributes] methods.
2188#[derive(Debug)]
2189pub enum EmbedPrelim<T> {
2190 Primitive(Any),
2191 Shared(T),
2192}
2193
2194impl<T> Prelim for EmbedPrelim<T>
2195where
2196 T: Prelim,
2197{
2198 type Return = T::Return;
2199
2200 fn into_content(self, txn: &mut TransactionMut) -> (ItemContent, Option<Self>) {
2201 match self {
2202 EmbedPrelim::Primitive(any) => (ItemContent::Embed(any), None),
2203 EmbedPrelim::Shared(prelim) => {
2204 let (branch, content) = prelim.into_content(txn);
2205 let carrier = if let Some(carrier) = content {
2206 Some(EmbedPrelim::Shared(carrier))
2207 } else {
2208 None
2209 };
2210 (branch, carrier)
2211 }
2212 }
2213 }
2214
2215 fn integrate(self, txn: &mut TransactionMut, inner_ref: BranchPtr) {
2216 if let EmbedPrelim::Shared(carrier) = self {
2217 carrier.integrate(txn, inner_ref)
2218 }
2219 }
2220}
2221
2222impl<T> From<T> for EmbedPrelim<T>
2223where
2224 T: Into<Any>,
2225{
2226 fn from(value: T) -> Self {
2227 EmbedPrelim::Primitive(value.into())
2228 }
2229}
2230
2231impl std::fmt::Display for ID {
2232 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2233 write!(f, "<{}#{}>", self.client, self.clock)
2234 }
2235}
2236
2237impl std::fmt::Debug for ItemPtr {
2238 #[inline]
2239 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2240 std::fmt::Display::fmt(self, f)
2241 }
2242}
2243
2244impl std::fmt::Display for ItemPtr {
2245 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2246 write!(f, "({})", self.id())
2247 }
2248}
2249
2250#[cfg(test)]
2251mod test {
2252 use crate::block::{split_str, SplittableString};
2253 use crate::doc::OffsetKind;
2254 use std::ops::Deref;
2255
2256 #[test]
2257 fn splittable_string_len() {
2258 let s: SplittableString = "Zażółć gęślą jaźń😀 女".into();
2259
2260 assert_eq!(s.len(OffsetKind::Bytes), 34, "wrong byte length");
2261 assert_eq!(s.len(OffsetKind::Utf16), 21, "wrong UTF-16 length");
2262 }
2263
2264 #[test]
2265 fn splittable_string_push_str() {
2266 let mut s: SplittableString = "Zażółć gęślą jaźń😀".into();
2267 s.push_str("ありがとうございます");
2268
2269 assert_eq!(
2270 s.deref(),
2271 &"Zażółć gęślą jaźń😀ありがとうございます".to_string()
2272 );
2273
2274 assert_eq!(s.len(OffsetKind::Bytes), 60, "wrong byte length");
2275 assert_eq!(s.len(OffsetKind::Utf16), 29, "wrong UTF-16 length");
2276 }
2277
2278 #[test]
2279 fn splittable_string_split_str() {
2280 let s: SplittableString = "Zażółć gęślą jaźń😀ありがとうございます".into();
2281
2282 let (a, b) = split_str(&s, 19, OffsetKind::Utf16);
2283 assert_eq!(a, "Zażółć gęślą jaźń😀");
2284 assert_eq!(b, "ありがとうございます");
2285
2286 let (a, b) = split_str(&s, 30, OffsetKind::Bytes);
2287 assert_eq!(a, "Zażółć gęślą jaźń😀");
2288 assert_eq!(b, "ありがとうございます");
2289 }
2290}
2291