forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

op.rs749 lines, 21.3 KiBHistoryRawDownload
1use crate::{
2 change::{Change, Lamport, Timestamp},
3 container::{idx::ContainerIdx, ContainerID},
4 estimated_size::EstimatedSize,
5 id::{Counter, PeerID, ID},
6 oplog::BlockChangeRef,
7 span::{HasCounter, HasId, HasLamport},
8};
9use crate::{delta::DeltaValue, LoroValue};
10use either::Either;
11use enum_as_inner::EnumAsInner;
12use loro_common::{CompactIdLp, ContainerType, CounterSpan, IdFull, IdLp, IdSpan};
13use rle::{HasIndex, HasLength, Mergable, Sliceable};
14use serde::{Deserialize, Serialize};
15use std::{borrow::Cow, sync::Arc};
16
17mod content;
18pub use content::*;
19
20/// Operation is a unit of change.
21///
22/// A Op may have multiple atomic operations, since Op can be merged.
23#[derive(Debug, Clone)]
24pub struct Op {
25 pub(crate) counter: Counter,
26 pub(crate) container: ContainerIdx,
27 pub(crate) content: InnerContent,
28}
29
30impl EstimatedSize for Op {
31 fn estimate_storage_size(&self) -> usize {
32 // TODO: use benchmark to get the optimal estimated size for each container type
33 self.content
34 .estimate_storage_size(self.container.get_type())
35 }
36}
37
38#[derive(Debug, Clone)]
39pub(crate) struct OpWithId {
40 pub peer: PeerID,
41 pub op: Op,
42}
43
44impl OpWithId {
45 #[allow(unused)]
46 pub fn id_span(&self) -> IdSpan {
47 IdSpan::new(
48 self.peer,
49 self.op.counter,
50 self.op.counter + self.op.atom_len() as Counter,
51 )
52 }
53}
54
55#[derive(Debug, Clone, PartialEq)]
56#[cfg_attr(feature = "wasm", derive(Serialize, Deserialize))]
57pub struct RemoteOp<'a> {
58 pub(crate) counter: Counter,
59 pub(crate) container: ContainerID,
60 pub(crate) content: RawOpContent<'a>,
61}
62
63/// This is used to propagate messages between inner module.
64/// It's a temporary struct, and will be converted to Op when it's persisted.
65#[derive(Debug, Clone)]
66pub struct RawOp<'a> {
67 pub id: ID,
68 pub lamport: Lamport,
69 pub container: ContainerIdx,
70 pub content: RawOpContent<'a>,
71}
72
73impl RawOp<'_> {
74 pub(crate) fn id_full(&self) -> loro_common::IdFull {
75 IdFull::new(self.id.peer, self.id.counter, self.lamport)
76 }
77
78 pub(crate) fn idlp(&self) -> loro_common::IdLp {
79 IdLp::new(self.id.peer, self.lamport)
80 }
81}
82
83/// RichOp includes lamport and timestamp info, which is used for conflict resolution.
84#[derive(Debug, Clone)]
85pub struct RichOp<'a> {
86 op: Cow<'a, Op>,
87 pub peer: PeerID,
88 lamport: Lamport,
89 pub timestamp: Timestamp,
90 pub start: usize,
91 pub end: usize,
92}
93
94impl Op {
95 #[inline]
96 #[allow(unused)]
97 pub(crate) fn new(id: ID, content: InnerContent, container: ContainerIdx) -> Self {
98 Op {
99 counter: id.counter,
100 content,
101 container,
102 }
103 }
104
105 /// If the estimated storage size of the content is greater than the given size,
106 /// return the length of the content that makes the estimated storage size equal to the given size.
107 /// Otherwise, return None.
108 pub(crate) fn check_whether_slice_content_to_fit_in_size(&self, size: usize) -> Option<usize> {
109 if self.estimate_storage_size() <= size {
110 return None;
111 }
112
113 match &self.content {
114 InnerContent::List(l) => match l {
115 crate::container::list::list_op::InnerListOp::Insert { .. } => {
116 if matches!(self.container.get_type(), ContainerType::Text) {
117 Some(size.min(self.atom_len()))
118 } else {
119 Some((size / 4).min(self.atom_len()))
120 }
121 }
122 crate::container::list::list_op::InnerListOp::InsertText { .. } => {
123 Some(size.min(self.atom_len()))
124 }
125 _ => unreachable!(),
126 },
127 _ => unreachable!(),
128 }
129 }
130}
131
132impl RemoteOp<'_> {
133 #[allow(unused)]
134 pub(crate) fn into_static(self) -> RemoteOp<'static> {
135 RemoteOp {
136 counter: self.counter,
137 container: self.container,
138 content: self.content.to_static(),
139 }
140 }
141}
142
143impl Mergable for Op {
144 fn is_mergable(&self, other: &Self, cfg: &()) -> bool {
145 self.counter + self.content_len() as Counter == other.counter
146 && self.container == other.container
147 && self.content.is_mergable(&other.content, cfg)
148 }
149
150 fn merge(&mut self, other: &Self, cfg: &()) {
151 self.content.merge(&other.content, cfg)
152 }
153}
154
155impl HasLength for Op {
156 fn content_len(&self) -> usize {
157 self.content.content_len()
158 }
159}
160
161impl Sliceable for Op {
162 fn slice(&self, from: usize, to: usize) -> Self {
163 assert!(to > from, "{to} should be greater than {from}");
164 assert!(to <= self.atom_len());
165 let content: InnerContent = self.content.slice(from, to);
166 Op {
167 counter: (self.counter + from as Counter),
168 content,
169 container: self.container,
170 }
171 }
172}
173
174impl Mergable for RemoteOp<'_> {
175 fn is_mergable(&self, _other: &Self, _cfg: &()) -> bool {
176 // don't merge remote op, because it's already merged.
177 false
178 }
179
180 fn merge(&mut self, _other: &Self, _: &()) {
181 unreachable!()
182 }
183}
184
185impl HasLength for RemoteOp<'_> {
186 fn content_len(&self) -> usize {
187 self.content.atom_len()
188 }
189}
190
191impl HasIndex for Op {
192 type Int = Counter;
193
194 fn get_start_index(&self) -> Self::Int {
195 self.counter
196 }
197}
198
199impl HasIndex for RemoteOp<'_> {
200 type Int = Counter;
201
202 fn get_start_index(&self) -> Self::Int {
203 self.counter
204 }
205}
206
207impl HasCounter for Op {
208 fn ctr_start(&self) -> Counter {
209 self.counter
210 }
211}
212
213impl HasCounter for RemoteOp<'_> {
214 fn ctr_start(&self) -> Counter {
215 self.counter
216 }
217}
218
219impl HasId for RichOp<'_> {
220 fn id_start(&self) -> ID {
221 ID {
222 peer: self.peer,
223 counter: self.op.counter + self.start as Counter,
224 }
225 }
226}
227
228impl HasLength for RichOp<'_> {
229 fn content_len(&self) -> usize {
230 self.end - self.start
231 }
232}
233
234impl HasLamport for RichOp<'_> {
235 fn lamport(&self) -> Lamport {
236 self.lamport + self.start as Lamport
237 }
238}
239
240impl<'a> RichOp<'a> {
241 pub fn new_by_change(change: &Change<Op>, op: &'a Op) -> Self {
242 let diff = op.counter - change.id.counter;
243 RichOp {
244 op: Cow::Borrowed(op),
245 peer: change.id.peer,
246 lamport: change.lamport + diff as Lamport,
247 timestamp: change.timestamp,
248 start: 0,
249 end: op.atom_len(),
250 }
251 }
252
253 /// we want the overlap part of the op and change[start..end]
254 ///
255 /// op is contained in the change, but it's not necessary overlap with change[start..end]
256 pub fn new_by_slice_on_change(change: &Change<Op>, start: i32, end: i32, op: &'a Op) -> Self {
257 debug_assert!(end > start);
258 let op_index_in_change = op.counter - change.id.counter;
259 let op_slice_start = (start - op_index_in_change).clamp(0, op.atom_len() as i32);
260 let op_slice_end = (end - op_index_in_change).clamp(0, op.atom_len() as i32);
261 RichOp {
262 op: Cow::Borrowed(op),
263 peer: change.id.peer,
264 lamport: change.lamport + op_index_in_change as Lamport,
265 timestamp: change.timestamp,
266 start: op_slice_start as usize,
267 end: op_slice_end as usize,
268 }
269 }
270
271 pub fn new_by_cnt_range(change: &Change<Op>, span: CounterSpan, op: &'a Op) -> Option<Self> {
272 let op_index_in_change = op.counter - change.id.counter;
273 let op_slice_start = (span.start - op.counter).clamp(0, op.atom_len() as i32);
274 let op_slice_end = (span.end - op.counter).clamp(0, op.atom_len() as i32);
275 if op_slice_start == op_slice_end {
276 return None;
277 }
278 Some(RichOp {
279 op: Cow::Borrowed(op),
280 peer: change.id.peer,
281 lamport: change.lamport + op_index_in_change as Lamport,
282 timestamp: change.timestamp,
283 start: op_slice_start as usize,
284 end: op_slice_end as usize,
285 })
286 }
287
288 pub(crate) fn new_iter_by_cnt_range(
289 change: BlockChangeRef,
290 span: CounterSpan,
291 ) -> RichOpBlockIter {
292 // Start at the first op that reaches into `span`.
293 let op_index = change
294 .ops
295 .vec()
296 .partition_point(|op| op.counter + op.atom_len() as Counter <= span.start);
297 RichOpBlockIter {
298 change,
299 span,
300 op_index,
301 }
302 }
303
304 pub fn op(&self) -> Cow<'_, Op> {
305 if self.start == 0 && self.end == self.op.content_len() {
306 self.op.clone()
307 } else {
308 Cow::Owned(self.op.slice(self.start, self.end))
309 }
310 }
311
312 pub fn raw_op(&self) -> &Op {
313 &self.op
314 }
315
316 pub fn client_id(&self) -> u64 {
317 self.peer
318 }
319
320 pub fn container(&self) -> ContainerIdx {
321 self.op.container
322 }
323
324 pub fn timestamp(&self) -> i64 {
325 self.timestamp
326 }
327
328 pub fn start(&self) -> usize {
329 self.start
330 }
331
332 pub fn end(&self) -> usize {
333 self.end
334 }
335
336 pub fn counter(&self) -> Counter {
337 self.op.counter + self.start as Counter
338 }
339
340 #[allow(unused)]
341 pub(crate) fn id(&self) -> ID {
342 ID {
343 peer: self.peer,
344 counter: self.op.counter + self.start as Counter,
345 }
346 }
347
348 pub(crate) fn id_full(&self) -> IdFull {
349 IdFull::new(
350 self.peer,
351 self.op.counter + self.start as Counter,
352 self.lamport + self.start as Lamport,
353 )
354 }
355
356 pub fn idlp(&self) -> IdLp {
357 IdLp {
358 lamport: self.lamport + self.start as Lamport,
359 peer: self.peer,
360 }
361 }
362}
363
364pub(crate) struct RichOpBlockIter {
365 change: BlockChangeRef,
366 span: CounterSpan,
367 op_index: usize,
368}
369
370impl Iterator for RichOpBlockIter {
371 type Item = RichOp<'static>;
372
373 fn next(&mut self) -> Option<Self::Item> {
374 // Clone only the ops that are returned: cloning a list insert clones its
375 // values' handle.
376 let (op, op_slice_start, op_slice_end) = loop {
377 let op = self.change.ops.get(self.op_index)?;
378 self.op_index += 1;
379 let op_slice_start = (self.span.start - op.counter).clamp(0, op.atom_len() as i32);
380 let op_slice_end = (self.span.end - op.counter).clamp(0, op.atom_len() as i32);
381 if op_slice_start != op_slice_end {
382 break (op.clone(), op_slice_start, op_slice_end);
383 }
384 };
385 let op_offset_in_change = op.counter - self.change.id.counter;
386
387 Some(RichOp {
388 op: Cow::Owned(op),
389 peer: self.change.id.peer,
390 lamport: self.change.lamport + op_offset_in_change as Lamport,
391 timestamp: self.change.timestamp,
392 start: op_slice_start as usize,
393 end: op_slice_end as usize,
394 })
395 }
396}
397
398// Note: It will be encoded into binary format, so the order of its fields should not be changed.
399#[derive(PartialEq, Debug, EnumAsInner, Clone, Serialize, Deserialize)]
400pub enum ListSlice<'a> {
401 RawData(Cow<'a, [LoroValue]>),
402 RawStr {
403 str: Cow<'a, str>,
404 unicode_len: usize,
405 },
406}
407
408impl<'a> ListSlice<'a> {
409 pub fn from_borrowed_str(str: &'a str) -> Self {
410 Self::RawStr {
411 str: Cow::Borrowed(str),
412 unicode_len: str.chars().count(),
413 }
414 }
415}
416
417/// The values of a list insert op.
418///
419/// The op owns them. They used to be a range in the doc-wide values arena,
420/// which never frees, so every parse of a change block appended its values to it
421/// again (`context/text-arena-growth.md`).
422#[derive(Clone)]
423pub struct ValueSlice(Repr);
424
425#[derive(Clone)]
426enum Repr {
427 /// A single value, as most local inserts have. It needs no allocation.
428 One(LoroValue),
429 Shared {
430 values: Arc<Vec<LoroValue>>,
431 start: u32,
432 end: u32,
433 },
434}
435
436impl ValueSlice {
437 pub fn new(mut values: Vec<LoroValue>) -> Self {
438 if values.len() == 1 {
439 return Self::one(values.pop().unwrap());
440 }
441
442 let end = u32::try_from(values.len()).expect("too many values in one list op");
443 Self(Repr::Shared {
444 values: Arc::new(values),
445 start: 0,
446 end,
447 })
448 }
449
450 pub(crate) fn one(value: LoroValue) -> Self {
451 Self(Repr::One(value))
452 }
453
454 /// A slice of `buffer` that is not filled yet. See
455 /// `DecodedBlockBuffers::push_values`.
456 pub(crate) fn pending(buffer: &Arc<Vec<LoroValue>>, range: std::ops::Range<usize>) -> Self {
457 let end = u32::try_from(range.end).expect("too many values in one change block");
458 Self(Repr::Shared {
459 values: buffer.clone(),
460 start: range.start as u32,
461 end,
462 })
463 }
464
465 /// Points this slice at `to` if it points at `from`.
466 pub(crate) fn replace_buffer(&mut self, from: &Arc<Vec<LoroValue>>, to: &Arc<Vec<LoroValue>>) {
467 if let Repr::Shared { values, .. } = &mut self.0 {
468 if Arc::ptr_eq(values, from) {
469 *values = to.clone();
470 }
471 }
472 }
473
474 #[inline]
475 pub fn as_slice(&self) -> &[LoroValue] {
476 match &self.0 {
477 Repr::One(value) => std::slice::from_ref(value),
478 Repr::Shared { values, start, end } => &values[*start as usize..*end as usize],
479 }
480 }
481
482 #[inline]
483 pub fn len(&self) -> usize {
484 match &self.0 {
485 Repr::One(_) => 1,
486 Repr::Shared { start, end, .. } => (end - start) as usize,
487 }
488 }
489
490 #[inline]
491 pub fn is_empty(&self) -> bool {
492 self.len() == 0
493 }
494
495 /// Whether `other` follows this slice in the same buffer.
496 fn is_followed_by(&self, other: &Self) -> bool {
497 matches!(
498 (&self.0, &other.0),
499 (
500 Repr::Shared { values, end, .. },
501 Repr::Shared { values: other_values, start, .. },
502 ) if Arc::ptr_eq(values, other_values) && end == start
503 )
504 }
505
506 /// Extends this slice by `other` if it follows this slice in the same buffer.
507 pub(crate) fn extend_if_adjacent(&mut self, other: &Self) -> bool {
508 if !self.is_followed_by(other) {
509 return false;
510 }
511 if let (Repr::Shared { end, .. }, Repr::Shared { end: other_end, .. }) =
512 (&mut self.0, &other.0)
513 {
514 *end = *other_end;
515 }
516 true
517 }
518
519 /// Whether this slice ends its buffer and is the buffer's only owner.
520 fn can_append(&self) -> bool {
521 match &self.0 {
522 Repr::One(_) => false,
523 Repr::Shared { values, end, .. } => {
524 *end as usize == values.len()
525 && Arc::strong_count(values) == 1
526 && Arc::weak_count(values) == 0
527 }
528 }
529 }
530}
531
532impl PartialEq for ValueSlice {
533 fn eq(&self, other: &Self) -> bool {
534 self.as_slice() == other.as_slice()
535 }
536}
537
538impl Eq for ValueSlice {}
539
540impl std::fmt::Debug for ValueSlice {
541 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
542 match &self.0 {
543 // A slice from `DecodedBlockBuffers::push_values` before `finish`:
544 // its values are not decoded yet. Decoding formats ops in errors
545 // (`check_positions`), so this must not read them.
546 Repr::Shared { values, start, end } if *end as usize > values.len() => f
547 .debug_struct("ValueSlice")
548 .field("pending", &(*start..*end))
549 .finish(),
550 _ => f.debug_tuple("ValueSlice").field(&self.as_slice()).finish(),
551 }
552 }
553}
554
555impl HasLength for ValueSlice {
556 fn content_len(&self) -> usize {
557 self.len()
558 }
559}
560
561impl Sliceable for ValueSlice {
562 fn slice(&self, from: usize, to: usize) -> Self {
563 assert!(from <= to && to <= self.len());
564 match &self.0 {
565 Repr::One(_) if from == 0 && to == 1 => self.clone(),
566 Repr::One(_) => Self::new(Vec::new()),
567 Repr::Shared { values, start, .. } => Self(Repr::Shared {
568 values: values.clone(),
569 start: start + from as u32,
570 end: start + to as u32,
571 }),
572 }
573 }
574}
575
576impl Mergable for ValueSlice {
577 fn merge(&mut self, other: &Self, _: &()) {
578 if self.extend_if_adjacent(other) {
579 return;
580 }
581
582 if self.can_append() {
583 let Repr::Shared { values, end, .. } = &mut self.0 else {
584 unreachable!()
585 };
586 let values = Arc::get_mut(values).unwrap();
587 values.extend_from_slice(other.as_slice());
588 *end = u32::try_from(values.len()).expect("too many values in one list op");
589 return;
590 }
591
592 // Copy only this slice, not the whole shared buffer. The merged slice
593 // owns its buffer, so later merges append to it.
594 let mut values = Vec::with_capacity((self.len() + other.len()).max(4));
595 values.extend_from_slice(self.as_slice());
596 values.extend_from_slice(other.as_slice());
597 *self = Self::new(values);
598 }
599
600 /// Mergeable when the merge never copies this slice's shared buffer:
601 /// `other` follows it in one buffer (nothing is copied), this slice owns
602 /// the end of its buffer (`other` is appended to it), or this slice is a
603 /// single value (it and `other` are copied into a new buffer, which later
604 /// merges append to). Each value is copied once per op it is merged into.
605 fn is_mergable(&self, other: &Self, _conf: &()) -> bool
606 where
607 Self: Sized,
608 {
609 self.is_followed_by(other) || self.can_append() || matches!(self.0, Repr::One(_))
610 }
611}
612
613impl ListSlice<'_> {
614 pub fn to_static(&self) -> ListSlice<'static> {
615 match self {
616 ListSlice::RawData(x) => ListSlice::RawData(Cow::Owned(x.to_vec())),
617 ListSlice::RawStr { str, unicode_len } => ListSlice::RawStr {
618 str: Cow::Owned(str.to_string()),
619 unicode_len: *unicode_len,
620 },
621 }
622 }
623}
624
625impl HasLength for ListSlice<'_> {
626 fn content_len(&self) -> usize {
627 match self {
628 ListSlice::RawStr { unicode_len, .. } => *unicode_len,
629 ListSlice::RawData(x) => x.len(),
630 }
631 }
632}
633
634impl Sliceable for ListSlice<'_> {
635 fn slice(&self, from: usize, to: usize) -> Self {
636 match self {
637 ListSlice::RawStr {
638 str,
639 unicode_len: _,
640 } => {
641 let ans = str.chars().skip(from).take(to - from).collect::<String>();
642 ListSlice::RawStr {
643 str: Cow::Owned(ans),
644 unicode_len: to - from,
645 }
646 }
647 ListSlice::RawData(x) => match x {
648 Cow::Borrowed(x) => ListSlice::RawData(Cow::Borrowed(&x[from..to])),
649 Cow::Owned(x) => ListSlice::RawData(Cow::Owned(x[from..to].into())),
650 },
651 }
652 }
653}
654
655impl Mergable for ListSlice<'_> {
656 fn is_mergable(&self, _other: &Self, _: &()) -> bool {
657 false
658 }
659}
660
661#[derive(Debug, Clone)]
662pub struct SliceWithId {
663 pub values: Either<ValueSlice, LoroValue>,
664 /// This field is no-none when diff calculating movable list that need to handle_unknown
665 pub elem_id: Option<CompactIdLp>,
666 pub id: IdFull,
667}
668
669impl DeltaValue for SliceWithId {
670 fn value_extend(&mut self, other: Self) -> Result<(), Self> {
671 if self.id.peer != other.id.peer {
672 return Err(other);
673 }
674
675 if self.id.counter + self.length() as Counter != other.id.counter {
676 return Err(other);
677 }
678
679 if self.id.lamport + self.length() as Lamport != other.id.lamport {
680 return Err(other);
681 }
682
683 match (&mut self.values, &other.values) {
684 (Either::Left(left), Either::Left(right)) => {
685 if left.extend_if_adjacent(right) {
686 Ok(())
687 } else {
688 Err(other)
689 }
690 }
691 _ => {
692 // Values in different buffers, or a ValueSlice and a LoroValue
693 Err(other)
694 }
695 }
696 }
697
698 fn take(&mut self, target_len: usize) -> Self {
699 match &mut self.values {
700 Either::Left(range) => {
701 let ans = range.slice(0, target_len);
702 let this = range.slice(target_len, range.atom_len());
703 *range = this;
704 let old_id = self.id;
705 self.id = self.id.inc(target_len as i32);
706 Self {
707 id: old_id,
708 values: Either::Left(ans),
709 elem_id: None,
710 }
711 }
712 Either::Right(_) => unimplemented!(),
713 }
714 }
715
716 fn length(&self) -> usize {
717 match &self.values {
718 Either::Left(r) => r.atom_len(),
719 Either::Right(_) => 1,
720 }
721 }
722}
723
724#[cfg(test)]
725mod test {
726 use crate::LoroValue;
727
728 use super::ListSlice;
729
730 #[test]
731 fn fix_fields_order() {
732 let list_slice = vec![
733 ListSlice::RawData(vec![LoroValue::Bool(true)].into()),
734 ListSlice::RawStr {
735 str: "".into(),
736 unicode_len: 0,
737 },
738 ];
739 let list_slice_buf = vec![2, 0, 1, 1, 1, 1, 0, 0];
740 assert_eq!(
741 &postcard::to_allocvec(&list_slice).unwrap(),
742 &list_slice_buf
743 );
744 assert_eq!(
745 postcard::from_bytes::<Vec<ListSlice>>(&list_slice_buf).unwrap(),
746 list_slice
747 );
748 }
749}