-
Notifications
You must be signed in to change notification settings - Fork 71
/
block.rs
1712 lines (1544 loc) · 64.1 KB
/
block.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::doc::OffsetKind;
use crate::store::Store;
use crate::types::{
Attrs, Branch, BranchPtr, TypePtr, Value, TYPE_REFS_ARRAY, TYPE_REFS_MAP, TYPE_REFS_TEXT,
TYPE_REFS_UNDEFINED, TYPE_REFS_XML_ELEMENT, TYPE_REFS_XML_FRAGMENT, TYPE_REFS_XML_HOOK,
TYPE_REFS_XML_TEXT,
};
use crate::updates::decoder::Decoder;
use crate::updates::encoder::Encoder;
use crate::*;
use lib0::any::Any;
use smallstr::SmallString;
use std::collections::HashSet;
use std::hash::Hash;
use std::ops::{Deref, DerefMut};
use std::panic;
use std::ptr::NonNull;
use std::rc::Rc;
/// Bit flag used to identify [Block::GC].
pub const BLOCK_GC_REF_NUMBER: u8 = 0;
/// Bit flag used to identify items with content of type [ItemContent::Deleted].
pub const BLOCK_ITEM_DELETED_REF_NUMBER: u8 = 1;
/// Bit flag used to identify items with content of type [ItemContent::JSON].
pub const BLOCK_ITEM_JSON_REF_NUMBER: u8 = 2;
/// Bit flag used to identify items with content of type [ItemContent::Binary].
pub const BLOCK_ITEM_BINARY_REF_NUMBER: u8 = 3;
/// Bit flag used to identify items with content of type [ItemContent::String].
pub const BLOCK_ITEM_STRING_REF_NUMBER: u8 = 4;
/// Bit flag used to identify items with content of type [ItemContent::Embed].
pub const BLOCK_ITEM_EMBED_REF_NUMBER: u8 = 5;
/// Bit flag used to identify items with content of type [ItemContent::Format].
pub const BLOCK_ITEM_FORMAT_REF_NUMBER: u8 = 6;
/// Bit flag used to identify items with content of type [ItemContent::Number].
pub const BLOCK_ITEM_TYPE_REF_NUMBER: u8 = 7;
/// Bit flag used to identify items with content of type [ItemContent::Any].
pub const BLOCK_ITEM_ANY_REF_NUMBER: u8 = 8;
/// Bit flag used to identify items with content of type [ItemContent::Doc].
pub const BLOCK_ITEM_DOC_REF_NUMBER: u8 = 9;
/// Bit flag used to identify [Block::Skip].
pub const BLOCK_SKIP_REF_NUMBER: u8 = 10;
/// Bit flag used to tell if encoded item has right origin defined.
pub const HAS_RIGHT_ORIGIN: u8 = 0b01000000;
/// Bit flag used to tell if encoded item has left origin defined.
pub const HAS_ORIGIN: u8 = 0b10000000;
/// Bit flag used to tell if encoded item has a parent subtitle defined. Subtitles are used only
/// for blocks which act as map-like types entries.
pub const HAS_PARENT_SUB: u8 = 0b00100000;
/// Block identifier, which allows to uniquely identify any element insertion in a global scope
/// (across different replicas of the same document). It consists of client ID (which is unique
/// document replica identifier) and monotonically incrementing clock value.
///
/// [ID] corresponds to a [Lamport timestamp](https://en.wikipedia.org/wiki/Lamport_timestamp) in
/// terms of its properties and guarantees.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct ID {
/// Unique identifier of a client, which inserted corresponding item.
pub client: u64,
/// Monotonically incrementing sequence number, which informs about order of inserted item
/// operation in a scope of a given `client`. This value doesn't have to increase by 1, but
/// instead is increased by number of countable elements which make a content of an inserted
/// block.
pub clock: u32,
}
impl ID {
pub fn new(client: u64, clock: u32) -> Self {
ID { client, clock }
}
}
/// A logical block pointer. It contains a unique block [ID], but also contains a helper metadata
/// which allows to faster locate block it points to within a block store.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, Hash)]
pub(crate) struct BlockPtr(NonNull<Block>);
impl BlockPtr {
pub(crate) fn splice(&mut self, offset: u32) -> Option<Box<Block>> {
let self_ptr = self.clone();
if offset == 0 {
None
} else {
match self.deref_mut() {
Block::Item(item) => {
let client = item.id.client;
let clock = item.id.clock;
let content = item.content.splice(offset as usize).unwrap();
item.len = offset;
let mut new = Box::new(Block::Item(Item {
id: ID::new(client, clock + offset),
len: content.len(OffsetKind::Utf16),
left: Some(self_ptr),
right: item.right.clone(),
origin: Some(ID::new(client, clock + offset - 1)),
right_origin: item.right_origin.clone(),
content,
parent: item.parent.clone(),
parent_sub: item.parent_sub.clone(),
info: item.info.clone(),
}));
let new_ptr = BlockPtr::from(&mut new);
if let Some(Block::Item(right)) = item.right.as_deref_mut() {
right.left = Some(new_ptr);
}
item.right = Some(new_ptr);
Some(new)
}
Block::GC(gc) => Some(Box::new(Block::GC(gc.slice(offset)))),
}
}
}
/// Integrates current block into block store.
/// If it returns true, it means that the block should be deleted after being added to a block store.
pub fn integrate(&mut self, txn: &mut Transaction, offset: u32) -> bool {
let self_ptr = self.clone();
match self.deref_mut() {
Block::GC(this) => this.integrate(offset),
Block::Item(this) => {
let store = txn.store_mut();
let encoding = store.options.offset_kind;
if offset > 0 {
this.id.clock += offset;
this.left = store
.blocks
.get_item_clean_end(&ID::new(this.id.client, this.id.clock - 1));
this.origin = this.left.as_deref().map(|b: &Block| b.last_id());
this.content.splice(offset as usize);
this.len -= offset;
}
let parent = match &this.parent {
TypePtr::Branch(branch) => Some(*branch),
TypePtr::Named(name) => {
let branch =
store.get_or_create_type(name.clone(), None, TYPE_REFS_UNDEFINED);
this.parent = TypePtr::Branch(branch);
Some(branch)
}
TypePtr::ID(id) => {
if let Some(block) = store.blocks.get_block(id) {
if let Some(branch) = block.as_branch() {
this.parent = TypePtr::Branch(branch);
Some(branch)
} else {
None
}
} else {
None
}
}
_ => None,
};
let left: Option<&Block> = this.left.as_deref();
let right: Option<&Block> = this.right.as_deref();
let right_is_null_or_has_left = match right {
None => true,
Some(Block::Item(i)) => i.left.is_some(),
_ => false,
};
let left_has_other_right_than_self = match left {
Some(Block::Item(i)) => i.right != this.right,
_ => false,
};
if let Some(mut parent_ref) = parent {
if (left.is_none() && right_is_null_or_has_left)
|| left_has_other_right_than_self
{
// set the first conflicting item
let mut o = if let Some(Block::Item(left)) = left {
left.right
} else if let Some(sub) = &this.parent_sub {
let mut o = parent_ref.map.get(sub).cloned();
while let Some(Block::Item(item)) = o.as_deref() {
if item.left.is_some() {
o = item.left.clone();
continue;
}
break;
}
o.clone()
} else {
parent_ref.start
};
let mut left = this.left.clone();
let mut conflicting_items = HashSet::new();
let mut items_before_origin = HashSet::new();
// Let c in conflicting_items, b in items_before_origin
// ***{origin}bbbb{this}{c,b}{c,b}{o}***
// Note that conflicting_items is a subset of items_before_origin
while let Some(ptr) = o {
if Some(ptr) == this.right {
break;
}
items_before_origin.insert(ptr.id().clone());
conflicting_items.insert(ptr.id().clone());
if let Block::Item(item) = ptr.deref() {
if this.origin == item.origin {
// case 1
if item.id.client < this.id.client {
left = Some(ptr.clone());
conflicting_items.clear();
} else if this.right_origin == item.right_origin {
// `self` and `item` are conflicting and point to the same integration
// points. The id decides which item comes first. Since `self` is to
// the left of `item`, we can break here.
break;
}
} else {
if let Some(item_origin) = item.origin {
if items_before_origin.contains(&item_origin) {
if !conflicting_items.contains(&item_origin) {
left = Some(ptr.clone());
conflicting_items.clear();
}
} else {
break;
}
} else {
break;
}
}
o = item.right.clone();
} else {
break;
}
}
this.left = left;
}
if this.parent_sub.is_none() {
if let Some(Block::Item(item)) = this.left.as_deref() {
if item.parent_sub.is_some() {
this.parent_sub = item.parent_sub.clone();
} else if let Some(Block::Item(item)) = this.right.as_deref() {
this.parent_sub = item.parent_sub.clone();
}
}
}
// reconnect left/right
if let Some(Block::Item(left)) = this.left.as_deref_mut() {
this.right = left.right.replace(self_ptr);
} else {
let r = if let Some(parent_sub) = &this.parent_sub {
let start = parent_ref.map.get(parent_sub).cloned();
let mut r = start;
while let Some(ptr) = r {
if let Block::Item(item) = ptr.deref() {
if item.left.is_some() {
r = item.left;
continue;
}
}
break;
}
r
} else {
let start = parent_ref.start.replace(self_ptr);
start
};
this.right = r;
}
if let Some(Block::Item(right)) = this.right.as_deref_mut() {
right.left = Some(self_ptr);
} else if let Some(parent_sub) = &this.parent_sub {
// set as current parent value if right === null and this is parentSub
parent_ref.map.insert(parent_sub.clone(), self_ptr);
if let Some(left) = this.left {
// this is the current attribute value of parent. delete right
txn.delete(left);
}
}
if this.parent_sub.is_none() && this.is_countable() && !this.is_deleted() {
parent_ref.block_len += this.len;
parent_ref.content_len += this.content_len(encoding);
}
this.integrate_content(txn, &mut *parent_ref);
txn.add_changed_type(parent_ref, this.parent_sub.clone());
let parent_deleted = if let TypePtr::Branch(ptr) = &this.parent {
if let Some(block) = ptr.item {
block.is_deleted()
} else {
false
}
} else {
false
};
if parent_deleted || (this.parent_sub.is_some() && this.right.is_some()) {
// delete if parent is deleted or if this is not the current attribute value of parent
true
} else {
false
}
} else {
panic!("Defect: item has no parent")
}
}
}
}
pub(crate) fn gc(&mut self, parent_gced: bool) {
if let Block::Item(item) = self.deref_mut() {
if item.is_deleted() {
item.content.gc();
let len = item.len();
if parent_gced {
unsafe {
let gc = Block::GC(BlockRange::new(item.id, len));
let self_mut = self.0.as_mut();
std::mem::replace(self_mut, gc);
}
} else {
item.content = ItemContent::Deleted(len);
item.info = item.info & !ITEM_FLAG_COUNTABLE;
}
}
}
}
/// Squashes two blocks together. Returns true if it succeeded. Squashing is possible only if
/// blocks are of the same type, their contents are of the same type, they belong to the same
/// parent data structure, their IDs are sequenced directly one after another and they point to
/// each other as their left/right neighbors respectively.
pub fn try_squash(&mut self, mut other: BlockPtr) -> bool {
let self_ptr = self.clone();
let other_ptr = other.clone();
match (self.deref_mut(), other.deref_mut()) {
(Block::Item(v1), Block::Item(v2)) => {
if v1.id.client == v2.id.client
&& v1.id.clock + v1.len() == v2.id.clock
&& v2.origin == Some(v1.last_id())
&& v1.right_origin == v2.right_origin
&& v1.right == Some(other_ptr)
&& v1.is_deleted() == v2.is_deleted()
&& v1.content.try_squash(&v2.content)
{
v1.len = v1.content.len(OffsetKind::Utf16);
if let Some(Block::Item(right_right)) = v2.right.as_deref_mut() {
right_right.left = Some(self_ptr);
}
v1.right = v2.right;
true
} else {
false
}
}
(Block::GC(v1), Block::GC(v2)) => {
v1.merge(v2);
true
}
_ => false,
}
}
pub(crate) fn as_branch(self) -> Option<BranchPtr> {
let item = self.as_item()?;
if let ItemContent::Type(branch) = &item.content {
Some(BranchPtr::from(branch))
} else {
None
}
}
}
impl Deref for BlockPtr {
type Target = Block;
fn deref(&self) -> &Self::Target {
unsafe { self.0.as_ref() }
}
}
impl DerefMut for BlockPtr {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { self.0.as_mut() }
}
}
impl<'a> From<&'a mut Box<Block>> for BlockPtr {
fn from(block: &'a mut Box<Block>) -> Self {
BlockPtr(NonNull::from(block.as_mut()))
}
}
impl<'a> From<&'a Box<Block>> for BlockPtr {
fn from(block: &'a Box<Block>) -> Self {
BlockPtr(unsafe { NonNull::new_unchecked(block.as_ref() as *const Block as *mut Block) })
}
}
impl Eq for BlockPtr {}
impl PartialEq for BlockPtr {
fn eq(&self, other: &Self) -> bool {
// BlockPtr.pivot may differ, but logically it doesn't affect block equality
self.id() == other.id()
}
}
/// An enum containing all supported block variants.
#[derive(Debug, PartialEq)]
pub(crate) enum Block {
/// An active block containing user data.
Item(Item),
/// Block, which is a subject of garbage collection after an [Item] has been deleted and its
/// safe for the transaction to remove it.
GC(BlockRange),
}
impl Block {
/// Since [Block] can span over multiple elements, this method returns an unique ID of the last
/// element contained within current block.
pub fn last_id(&self) -> ID {
match self {
Block::Item(item) => item.last_id(),
Block::GC(gc) => gc.last_id(),
}
}
/// Tries to cast this [Block] into an immutable [Item] reference, returning `None` if block was
/// in fact not an item.
pub fn as_item(&self) -> Option<&Item> {
match self {
Block::Item(item) => Some(item),
_ => None,
}
}
/// Tries to cast this [Block] into a mutable [Item] reference, returning `None` if block was in
/// fact not an item.
pub fn as_item_mut(&mut self) -> Option<&mut Item> {
match self {
Block::Item(item) => Some(item),
_ => None,
}
}
/// Checks if current block has been deleted. Yrs uses soft deletion (a.k.a. tombstoning) for
/// marking deleted blocks.
pub fn is_deleted(&self) -> bool {
match self {
Block::Item(item) => item.is_deleted(),
Block::GC(_) => true,
}
}
pub fn encode_with_offset<E: Encoder>(
&self,
store: Option<&Store>,
encoder: &mut E,
offset: u32,
) {
match self {
Block::Item(item) => {
let origin = if offset > 0 {
Some(ID::new(item.id.client, item.id.clock + offset - 1))
} else {
item.origin
};
let info = item.info();
let cant_copy_parent_info = info & (HAS_ORIGIN | HAS_RIGHT_ORIGIN) == 0;
encoder.write_info(info);
if let Some(origin_id) = origin {
encoder.write_left_id(&origin_id);
}
if let Some(right_origin_id) = item.right_origin.as_ref() {
encoder.write_right_id(right_origin_id);
}
if cant_copy_parent_info {
match &item.parent {
TypePtr::Branch(branch) => {
if let Some(block) = branch.item {
encoder.write_parent_info(false);
encoder.write_left_id(block.id());
} else if let Some(store) = store {
let name = store.get_type_key(*branch).unwrap();
encoder.write_parent_info(true);
encoder.write_string(name);
}
}
TypePtr::Named(name) => {
encoder.write_parent_info(true);
encoder.write_string(name);
}
TypePtr::ID(id) => {
encoder.write_parent_info(false);
encoder.write_left_id(id);
}
TypePtr::Unknown => {
panic!("Couldn't get item's parent")
}
}
if let Some(parent_sub) = item.parent_sub.as_ref() {
encoder.write_string(parent_sub.as_ref());
}
}
item.content.encode_with_offset(encoder, offset);
}
Block::GC(gc) => {
encoder.write_info(BLOCK_GC_REF_NUMBER);
encoder.write_len(gc.len - offset);
}
}
}
pub fn encode<E: Encoder>(&self, store: Option<&Store>, encoder: &mut E) {
match self {
Block::Item(item) => {
let info = item.info();
let cant_copy_parent_info = info & (HAS_ORIGIN | HAS_RIGHT_ORIGIN) == 0;
encoder.write_info(info);
if let Some(origin_id) = item.origin.as_ref() {
encoder.write_left_id(origin_id);
}
if let Some(right_origin_id) = item.right_origin.as_ref() {
encoder.write_right_id(right_origin_id);
}
if cant_copy_parent_info {
match &item.parent {
TypePtr::Branch(branch) => {
if let Some(block) = branch.item {
encoder.write_parent_info(false);
encoder.write_left_id(block.id());
} else if let Some(store) = store {
let name = store.get_type_key(*branch).unwrap();
encoder.write_parent_info(true);
encoder.write_string(name);
}
}
TypePtr::Named(name) => {
encoder.write_parent_info(true);
encoder.write_string(name);
}
TypePtr::ID(id) => {
encoder.write_parent_info(false);
encoder.write_left_id(id);
}
TypePtr::Unknown => {
panic!("Couldn't get item's parent")
}
}
if let Some(parent_sub) = item.parent_sub.as_ref() {
encoder.write_string(parent_sub.as_ref());
}
}
item.content.encode(encoder);
}
Block::GC(gc) => {
encoder.write_info(BLOCK_GC_REF_NUMBER);
encoder.write_len(gc.len);
}
}
}
/// Returns a unique identifier of a current block.
pub fn id(&self) -> &ID {
match self {
Block::Item(item) => &item.id,
Block::GC(gc) => &gc.id,
}
}
/// Returns a length of a block. For most situation it works like [Block::content_len] with a
/// difference to a [Text]/[XmlText] contents - in order to achieve compatibility with
/// Yjs we need to calculate string length in terms of UTF-16 character encoding.
/// However depending on used [Encoding] scheme we may calculate string length/offsets
/// differently.
pub fn len(&self) -> u32 {
match self {
Block::Item(item) => item.len(),
Block::GC(gc) => gc.len,
}
}
/// Returns a last clock value of a current block. This is exclusive value meaning, that
/// using it with current block's client ID will point to the beginning of a next block.
pub fn clock_end(&self) -> u32 {
match self {
Block::Item(item) => item.id.clock + item.len(),
Block::GC(gc) => gc.id.clock + gc.len,
}
}
/// Checks if two blocks are of the same type.
pub fn same_type(&self, other: &Self) -> bool {
match (self, other) {
(Block::Item(_), Block::Item(_)) | (Block::GC(_), Block::GC(_)) => true,
_ => false,
}
}
pub fn is_gc(&self) -> bool {
if let Block::GC(_) = self {
true
} else {
false
}
}
pub fn is_item(&self) -> bool {
if let Block::Item(_) = self {
true
} else {
false
}
}
pub fn contains(&self, id: &ID) -> bool {
match self {
Block::Item(v) => v.contains(id),
Block::GC(v) => v.contains(id),
}
}
}
/// A helper structure that's used to precisely describe a location of an [Item] to be inserted in
/// relation to its neighbors and parent.
#[derive(Debug)]
pub(crate) struct ItemPosition {
pub parent: types::TypePtr,
pub left: Option<BlockPtr>,
pub right: Option<BlockPtr>,
pub index: u32,
pub current_attrs: Option<Box<Attrs>>,
}
impl ItemPosition {
pub fn forward(&mut self) -> bool {
if let Some(Block::Item(right)) = self.right.as_deref() {
if !right.is_deleted() {
match &right.content {
ItemContent::String(_) | ItemContent::Embed(_) => {
self.index += right.len();
}
ItemContent::Format(key, value) => {
let attrs = self
.current_attrs
.get_or_insert_with(|| Box::new(Attrs::new()));
Text::update_current_attributes(attrs.as_mut(), key, value.as_ref());
}
_ => {}
}
}
let new = right.right.clone();
self.left = self.right.take();
self.right = new;
return true;
}
false
}
/// If current `attributes` don't confirm the same keys as the formatting wrapping
/// current insert position, they should be unset.
pub fn unset_missing(&self, attributes: &mut Attrs) {
if let Some(attrs) = self.current_attrs.as_ref() {
// if current `attributes` don't confirm the same keys as the formatting wrapping
// current insert position, they should be unset
for (k, _) in attrs.iter() {
if !attributes.contains_key(k) {
attributes.insert(k.clone(), Any::Null);
}
}
}
}
}
/// Bit flag (4th bit) for a marked item - not used atm.
const ITEM_FLAG_MARKED: u8 = 0b1000;
/// Bit flag (3rd bit) for a tombstoned (deleted) item.
const ITEM_FLAG_DELETED: u8 = 0b0100;
/// Bit flag (2nd bit) for an item, which contents are considered countable.
const ITEM_FLAG_COUNTABLE: u8 = 0b0010;
/// Bit flag (1st bit) used for an item which should be kept - not used atm.
const ITEM_FLAG_KEEP: u8 = 0b0001;
/// An item is basic unit of work in Yrs. It contains user data reinforced with all metadata
/// required for a potential conflict resolution as well as extra fields used for joining blocks
/// together as a part of indexed sequences or maps.
#[derive(Debug, PartialEq)]
pub(crate) struct Item {
/// Unique identifier of current item.
pub id: ID,
pub len: u32,
/// Pointer to left neighbor of this item. Used in sequenced collections.
/// If `None` current item is a first one on it's `parent` collection.
pub left: Option<BlockPtr>,
/// Pointer to right neighbor of this item. Used in sequenced collections.
/// If `None` current item is the last one on it's `parent` collection.
pub right: Option<BlockPtr>,
/// Used for concurrent insert conflict resolution. An ID of a left-side neighbor at the moment
/// of insertion of current block.
pub origin: Option<ID>,
/// Used for concurrent insert conflict resolution. An ID of a right-side neighbor at the moment
/// of insertion of current block.
pub right_origin: Option<ID>,
/// A user data stored inside of a current item.
pub content: ItemContent,
/// Pointer to a parent collection containing current item.
pub parent: types::TypePtr,
/// Used only when current item is used by map-like types. In such case this item works as a
/// key-value entry of a map, and this field contains a key used by map.
pub parent_sub: Option<Rc<str>>, //TODO: Rc since it's already used in Branch.map component
/// Bit flag field which contains information about specifics of this item.
pub info: u8,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct BlockRange {
pub id: ID,
pub len: u32,
}
impl BlockRange {
pub fn new(id: ID, len: u32) -> Self {
BlockRange { id, len }
}
pub fn last_id(&self) -> ID {
ID::new(self.id.client, self.id.clock + self.len)
}
pub fn slice(&mut self, offset: u32) -> Self {
let mut next = self.clone();
next.id.clock += offset;
next.len -= offset;
next
}
pub fn integrate(&mut self, pivot: u32) -> bool {
if pivot > 0 {
self.id.clock += pivot;
self.len -= pivot;
}
false
}
#[inline]
pub fn merge(&mut self, other: &Self) {
self.len += other.len;
}
pub fn contains(&self, id: &ID) -> bool {
self.id.client == id.client
&& id.clock >= self.id.clock
&& id.clock < self.id.clock + self.len
}
}
impl Item {
pub(crate) fn new(
id: ID,
left: Option<BlockPtr>,
origin: Option<ID>,
right: Option<BlockPtr>,
right_origin: Option<ID>,
parent: TypePtr,
parent_sub: Option<Rc<str>>,
content: ItemContent,
) -> Box<Block> {
let info = if content.is_countable() {
ITEM_FLAG_COUNTABLE
} else {
0
};
let len = content.len(OffsetKind::Utf16);
let mut item = Box::new(Block::Item(Item {
id,
len,
left,
right,
origin,
right_origin,
content,
parent,
parent_sub,
info,
}));
let item_ptr = BlockPtr::from(&mut item);
if let ItemContent::Type(branch) = &mut item.as_item_mut().unwrap().content {
branch.item = Some(item_ptr);
}
item
}
pub fn contains(&self, id: &ID) -> bool {
self.id.client == id.client
&& id.clock >= self.id.clock
&& id.clock < self.id.clock + self.len()
}
//TODO: not used yet
pub fn marked(&self) -> bool {
self.info & ITEM_FLAG_MARKED == ITEM_FLAG_MARKED
}
//TODO: not used yet
pub fn keep(&self) -> bool {
self.info & ITEM_FLAG_KEEP == ITEM_FLAG_KEEP
}
/// Checks if current item is marked as deleted (tombstoned). Yrs uses soft item deletion
/// mechanism.
pub fn is_deleted(&self) -> bool {
self.info & ITEM_FLAG_DELETED == ITEM_FLAG_DELETED
}
/// Checks if item content can be considered countable. Countable elements can be split
/// and joined together.
pub fn is_countable(&self) -> bool {
self.info & ITEM_FLAG_COUNTABLE == ITEM_FLAG_COUNTABLE
}
pub(crate) fn mark_as_deleted(&mut self) {
self.info |= ITEM_FLAG_DELETED;
}
/// Assign left/right neighbors of the block. This may require for origin/right_origin
/// blocks to be already present in block store - which may not be the case during block
/// decoding. We decode entire update first, and apply individual blocks second, hence
/// repair function is called before applying the block rather than on decode.
pub(crate) fn repair(&mut self, store: &mut Store) {
if let Some(origin) = self.origin.as_ref() {
self.left = store.blocks.get_item_clean_end(origin);
}
if let Some(origin) = self.right_origin.as_ref() {
self.right = store.blocks.get_item_clean_start(origin);
}
// We have all missing ids, now find the items
// In the original Y.js algorithm we decoded items as we go and attached them to client
// block list. During that process if we had right origin but no left, we made a lookup for
// right origin's parent and attach it as a parent of current block.
//
// Here since we decode all blocks first, then apply them, we might not find them in
// the block store during decoding. Therefore we retroactively reattach it here.
match &self.parent {
TypePtr::Unknown => {
if let Some(Block::Item(item)) = self.left.as_deref() {
if let TypePtr::Unknown = item.parent {
if let Some(Block::Item(item)) = self.right.as_deref() {
self.parent = item.parent.clone();
self.parent_sub = item.parent_sub.clone();
}
} else {
self.parent = item.parent.clone();
self.parent_sub = item.parent_sub.clone();
}
} else if let Some(Block::Item(item)) = self.right.as_deref() {
self.parent = item.parent.clone();
self.parent_sub = item.parent_sub.clone();
}
}
TypePtr::Named(name) => {
let branch = store.get_or_create_type(name.clone(), None, TYPE_REFS_UNDEFINED);
self.parent = branch.into();
}
TypePtr::ID(id) => {
let ptr = store.blocks.get_block(id).unwrap();
let item = ptr.as_item().unwrap();
if let ItemContent::Type(branch) = &item.content {
self.parent = TypePtr::Branch(BranchPtr::from(branch));
} else {
panic!("Defect: parent points to a block which is not a shared type");
}
}
_ => {}
}
}
/// Returns a number of elements stored within this item. These elements don't have to exists
/// in reality ie. when item has been deleted, corresponding content no longer exists but `len`
/// still refers to a number of elements current block used to represent.
pub fn len(&self) -> u32 {
self.len
}
pub fn content_len(&self, kind: OffsetKind) -> u32 {
self.content.len(kind)
}
/// Returns an ID of the last element that can be considered a part of this item.
pub fn last_id(&self) -> ID {
ID::new(self.id.client, self.id.clock + self.len() - 1)
}
fn info(&self) -> u8 {
let info = if self.origin.is_some() { HAS_ORIGIN } else { 0 } // is left null
| if self.right_origin.is_some() { HAS_RIGHT_ORIGIN } else { 0 } // is right null
| if self.parent_sub.is_some() { HAS_PARENT_SUB } else { 0 }
| (self.content.get_ref_number() & 0b1111);
info
}
fn integrate_content(&mut self, txn: &mut Transaction, _parent: &mut Branch) {
match &mut self.content {
ItemContent::Deleted(len) => {
txn.delete_set.insert(self.id, *len);
self.mark_as_deleted();
}
ItemContent::Doc(_, _) => {
//// this needs to be reflected in doc.destroy as well
//this.doc._item = item
//transaction.subdocsAdded.add(this.doc)
//if (this.doc.shouldLoad) {
// transaction.subdocsLoaded.add(this.doc)
//}
todo!()
}
ItemContent::Format(_, _) => {
// @todo searchmarker are currently unsupported for rich text documents
// /** @type {AbstractType<any>} */ (item.parent)._searchMarker = null
}
ItemContent::Type(_inner) => {
// this.type._integrate(transaction.doc, item)
}
_ => {
// other types don't define integration-specific actions
}
}
}
}
#[derive(PartialEq, PartialOrd, Eq, Ord, Debug, Clone)]
pub struct SplittableString {
content: SmallString<[u8; 8]>,
}
impl SplittableString {
pub fn len(&self, kind: OffsetKind) -> usize {
let len = self.content.len();
if len == 1 {
len // quite often strings are single-letter, so we don't care about OffsetKind
} else {
match kind {
OffsetKind::Bytes => len,
OffsetKind::Utf16 => self.utf16_len(),
OffsetKind::Utf32 => self.unicode_len(),
}
}
}
#[inline(always)]
pub fn as_str(&self) -> &str {
self.content.as_str()
}
#[inline(always)]
pub fn utf16_len(&self) -> usize {
self.encode_utf16().count()
}
pub fn unicode_len(&self) -> usize {