1use std::{mem, ptr};
2use std::hint::unreachable_unchecked;
3use std::pin::Pin;
4use std::ptr::NonNull;
5
6use smallvec::SmallVec;
7
8use super::*;
9use rle::AppendRle;
10
11impl<E: ContentTraits, I: TreeMetrics<E>, const IE: usize, const LE: usize> ContentTreeRaw<E, I, IE, LE> {
14 unsafe fn insert_internal<F>(mut items: &[E], cursor: &mut UnsafeCursor<E, I, IE, LE>, flush_marker: &mut I::Update, notify: &mut F)
22 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
23 {
24 if items.is_empty() { return; }
25 assert!(items.len() <= 3);
26
27 let mut node = &mut *cursor.node.as_ptr();
29
30 let remainder = if cursor.offset == usize::MAX {
31 debug_assert_eq!(cursor.idx, 0);
32 debug_assert_eq!(node.num_entries, 0);
33 cursor.offset = 0;
36 None
37 } else if cursor.offset == 0 && cursor.idx > 0 {
38 cursor.idx -= 1;
40 cursor.offset = node.data[cursor.idx].len(); None
42 } else {
43 if cursor.offset == node.data[cursor.idx].len() || cursor.offset == 0 {
48 None
49 } else {
50 let entry: &mut E = &mut node.data[cursor.idx];
52 let remainder = entry.truncate(cursor.offset);
53 I::decrement_marker(flush_marker, &remainder);
54 Some(remainder)
58 }
59 };
60
61 let mut trailing_offset = 0;
64
65 if cursor.offset != 0 {
66 debug_assert_eq!(cursor.offset, node.data[cursor.idx].len());
68 let mut items_idx = 0;
70 let cur_entry: &mut E = &mut node.data[cursor.idx];
71 while items_idx < items.len() { let next = items[items_idx];
73 if cur_entry.can_append(&next) {
74 I::increment_marker(flush_marker, &next);
75 notify(next, cursor.node);
77 cur_entry.append(next);
78
79 cursor.offset = cur_entry.len();
80 items_idx += 1;
81 } else { break; }
82 }
83 if items_idx == items.len() && remainder.is_none() {
84 return; }
86 items = &items[items_idx..];
87 cursor.offset = 0;
90 cursor.idx += 1; if remainder.is_none() && !items.is_empty() && cursor.idx < node.len_entries() {
93 let mut end_idx = items.len() - 1;
105 let cur_entry = &mut node.data[cursor.idx];
106 loop {
107 let next = items[end_idx];
108 if next.can_append(cur_entry) {
109 I::increment_marker(flush_marker, &next);
110 notify(next, cursor.node);
111 trailing_offset += next.len();
112 cur_entry.prepend(next);
113 } else { break; }
114
115 if end_idx == 0 {
116 cursor.offset = trailing_offset;
117 return; } else { end_idx -= 1; }
119 }
120 items = &items[..=end_idx];
121 }
122 }
123
124 debug_assert_eq!(cursor.offset, 0);
125
126 let space_needed = items.len() + remainder.is_some() as usize;
130 let num_filled = node.len_entries();
131 debug_assert!(space_needed > 0);
132 assert!(space_needed <= LE / 2);
133
134 let remainder_moved = if num_filled + space_needed > LE {
135 node.flush_metric_update(flush_marker);
142
143 if cursor.idx < LE / 2 {
144 node.split_at(cursor.idx, 0, notify);
146 node.num_entries += space_needed as u8;
147 false
148 } else {
149 let new_node_ptr = node.split_at(cursor.idx, space_needed, notify);
151 cursor.node = new_node_ptr;
152 cursor.idx = 0;
153 node = &mut *cursor.node.as_ptr();
154 true
155 }
156 } else {
157 if num_filled > cursor.idx {
159 node.data[..].copy_within(cursor.idx..num_filled, cursor.idx + space_needed);
160 }
161 node.num_entries += space_needed as u8;
162 false
163 };
164
165 let remainder_idx = cursor.idx + items.len();
168
169 if !items.is_empty() {
170 for e in items {
171 I::increment_marker(flush_marker, e);
172 notify(*e, cursor.node);
174 }
175 node.data[cursor.idx..cursor.idx + items.len()].copy_from_slice(items);
176
177 cursor.idx += items.len() - 1;
179 cursor.offset = items[items.len() - 1].len();
180
181 if trailing_offset > 0 {
182 cursor.move_forward_by_offset(trailing_offset, Some(flush_marker));
183 }
184 }
185
186 if let Some(e) = remainder {
188 I::increment_marker(flush_marker, &e);
189 if remainder_moved {
190 notify(e, cursor.node);
191 }
192 node.data[remainder_idx] = e;
193 }
194 }
195
196 pub unsafe fn unsafe_insert_notify<F>(cursor: &mut UnsafeCursor<E, I, IE, LE>, new_entry: E, mut notify: F)
197 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>) {
198 let mut marker = I::Update::default();
199 Self::insert_internal(&[new_entry], cursor, &mut marker, &mut notify);
200
201 cursor.get_node_mut().flush_metric_update(&mut marker);
202 }
204
205 #[inline(always)]
206 pub fn insert_at_start_notify<F>(self: &mut Pin<Box<Self>>, new_entry: E, notify: F)
207 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
208 {
209 unsafe { Self::unsafe_insert_notify(&mut self.unsafe_cursor_at_start(), new_entry, notify) }
210 }
211
212 #[inline(always)]
213 pub fn insert_at_start(self: &mut Pin<Box<Self>>, new_entry: E) {
214 self.insert_at_start_notify(new_entry, null_notify);
215 }
216
217 #[inline(always)]
218 pub fn push_notify<F>(self: &mut Pin<Box<Self>>, new_entry: E, notify: F)
219 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
220 {
221 unsafe { Self::unsafe_insert_notify(&mut self.unsafe_cursor_at_end(), new_entry, notify) }
222 }
223
224 #[inline(always)]
227 pub fn push(self: &mut Pin<Box<Self>>, new_entry: E)
228 {
229 self.push_notify(new_entry, null_notify);
230 }
231
232 #[allow(clippy::len_zero)]
237 unsafe fn replace_entry<F>(cursor: &mut UnsafeCursor<E, I, IE, LE>, items: &[E], flush_marker: &mut I::Update, notify: &mut F)
238 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>) {
239 assert!(items.len() >= 1 && items.len() <= 3);
240
241 let mut items_idx = 0;
253 let node = cursor.node.as_mut();
254 debug_assert!(cursor.idx < node.len_entries());
255
256 if cursor.idx >= 1 {
257 let elem = &mut node.data[cursor.idx - 1];
258 loop { let item = &items[items_idx];
260 if elem.can_append(item) {
261 I::increment_marker(flush_marker, item);
262 elem.append(*item);
263 items_idx += 1;
264 if items_idx >= items.len() { break; }
265 } else { break; }
266 }
267 }
268
269 let entry = &mut node.data[cursor.idx];
271 I::decrement_marker(flush_marker, entry);
272
273 if items_idx >= items.len() {
274 node.splice_out(cursor.idx);
276 if cursor.idx >= node.len_entries() {
277 debug_assert!(node.len_entries() >= 1);
279 cursor.idx -= 1;
280 cursor.offset = node.data[cursor.idx].len();
281 } else {
282 cursor.offset = 0;
283 }
284 } else {
285 *entry = items[items_idx];
287 I::increment_marker(flush_marker, entry);
288
289 cursor.offset = entry.len();
290 Self::insert_internal(&items[items_idx + 1..], cursor, flush_marker, notify);
294 }
295
296 if cfg!(debug_assertions) {
297 let node = cursor.get_node_mut();
299 debug_assert!(cursor.idx < node.len_entries());
300 }
301 }
302
303 pub unsafe fn unsafe_replace_entry_notify<N>(cursor: &mut UnsafeCursor<E, I, IE, LE>, items: &[E], mut notify: N)
306 where N: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>) {
307
308 let mut flush_marker = I::Update::default();
309 Self::replace_entry(cursor, items, &mut flush_marker, &mut notify);
310 cursor.get_node_mut().flush_metric_update(&mut flush_marker);
311 }
312
313 #[inline]
314 unsafe fn replace_entry_simple<F>(cursor: &mut UnsafeCursor<E, I, IE, LE>, new_item: E, flush_marker: &mut I::Update, notify: &mut F)
315 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>) {
316 notify(new_item, cursor.node);
317 cursor.offset = new_item.len();
318 let entry = cursor.get_raw_entry_mut();
319 I::decrement_marker(flush_marker, entry);
320 *entry = new_item;
321 I::increment_marker(flush_marker, entry);
322 }
323
324 pub unsafe fn unsafe_replace_entry_simple_notify<N>(cursor: &mut UnsafeCursor<E, I, IE, LE>, new_item: E, mut notify: N)
325 where N: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>) {
326
327 let mut flush_marker = I::Update::default();
328 Self::replace_entry_simple(cursor, new_item, &mut flush_marker, &mut notify);
329 cursor.get_node_mut().flush_metric_update(&mut flush_marker);
330 }
331
332
333 unsafe fn unsafe_mutate_entry_internal<MapFn, N, R>(
335 map_fn: MapFn,
336 cursor: &mut UnsafeCursor<E, I, IE, LE>,
337 replace_max: usize,
338 flush_marker: &mut I::Update,
339 notify: &mut N
340 ) -> (usize, R)
341 where N: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>), MapFn: FnOnce(&mut E) -> R
342 {
343 let node = cursor.get_node_mut();
344 debug_assert!(cursor.idx < node.len_entries());
345 let mut entry: E = node.data[cursor.idx];
346 let mut entry_len = entry.len();
347
348 assert!(cursor.offset < entry_len);
349
350 let a = if cursor.offset > 0 {
354 entry_len -= cursor.offset;
355 Some(entry.truncate_keeping_right(cursor.offset))
356 } else { None };
357
358 let (c, replaced_here) = if replace_max < entry_len {
360 (Some(entry.truncate(replace_max)), replace_max)
361 } else { (None, entry_len) };
362
363 let return_val = map_fn(&mut entry);
364
365 match (a, c) {
366 (Some(a), Some(c)) => {
367 let c_len = c.len();
368 Self::replace_entry(cursor, &[a, entry, c], flush_marker, notify);
369 cursor.move_back_by_offset(c_len, Some(flush_marker));
370 },
371 (Some(a), None) => {
372 Self::replace_entry(cursor, &[a, entry], flush_marker, notify);
373 },
374 (None, Some(c)) => {
375 let c_len = c.len();
376 Self::replace_entry(cursor, &[entry, c], flush_marker, notify);
377 cursor.move_back_by_offset(c_len, Some(flush_marker));
378 },
379 (None, None) => {
380 I::decrement_marker(flush_marker, &node.data[cursor.idx]);
386 node.data[cursor.idx] = entry;
387 cursor.offset = replaced_here;
388 I::increment_marker(flush_marker, &entry);
389 notify(entry, cursor.node);
390 }
391 }
392
393 (replaced_here, return_val)
394 }
395
396 pub unsafe fn unsafe_mutate_single_entry_notify<MapFn, R, N>(
397 map_fn: MapFn,
398 cursor: &mut UnsafeCursor<E, I, IE, LE>,
399 replace_max: usize,
400 mut notify: N
401 ) -> (usize, R)
402 where N: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>), MapFn: FnOnce(&mut E) -> R {
403 let mut flush_marker = I::Update::default();
404 let (amt_modified, ret) = Self::unsafe_mutate_entry_internal(map_fn, cursor, replace_max, &mut flush_marker, &mut notify);
405
406 cursor.get_node_mut().flush_metric_update(&mut flush_marker);
407 (amt_modified, ret)
408 }
409
410 pub unsafe fn unsafe_mutate_entries_notify<MapFn, N>(
411 map_fn: MapFn,
412 cursor: &mut UnsafeCursor<E, I, IE, LE>,
413 replace_len: usize,
414 mut notify: N
415 )
416 where N: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>), MapFn: Fn(&mut E) {
417 let mut flush_marker = I::Update::default();
418 let mut remaining = replace_len;
419 while remaining > 0 {
420 cursor.roll_to_next_entry_marker(&mut flush_marker);
421 let (consumed_here, _) = Self::unsafe_mutate_entry_internal(&map_fn, cursor, remaining, &mut flush_marker, &mut notify);
422 assert!(consumed_here > 0, "Could not mutate past end of list");
423 remaining -= consumed_here;
424 }
426
427 cursor.get_node_mut().flush_metric_update(&mut flush_marker);
428 }
429
430 pub unsafe fn unsafe_replace_range_notify<N>(cursor: &mut UnsafeCursor<E, I, IE, LE>, new_entry: E, notify: N)
432 where N: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>) {
433
434 let mut flush_marker = I::Update::default();
435 Self::replace_range_internal(cursor, new_entry.len(), new_entry, &mut flush_marker, notify);
436 cursor.get_node_mut().flush_metric_update(&mut flush_marker);
437 }
439
440 unsafe fn replace_range_internal<N>(cursor: &mut UnsafeCursor<E, I, IE, LE>, mut replaced_len: usize, new_entry: E, flush_marker: &mut I::Update, mut notify: N)
441 where N: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>) {
442
443 let node = cursor.node.as_mut();
444
445 if cursor.idx >= node.len_entries() {
446 cursor.roll_to_next_entry();
448 Self::insert_internal(&[new_entry], cursor, flush_marker, &mut notify);
449 return;
450 }
451
452 let entry = &mut node.data[cursor.idx];
460 let entry_len = entry.len();
461
462 if cursor.offset == entry_len && entry.can_append(&new_entry) {
466 assert!(cursor.offset > 0);
467 notify(new_entry, cursor.node);
468 I::increment_marker(flush_marker, &new_entry);
469 entry.append(new_entry);
470 cursor.offset += new_entry.len();
471
472 Self::delete_internal(cursor, replaced_len, flush_marker, &mut notify);
473 return;
474 }
475
476 if !cursor.roll_to_next_entry() { debug_assert_eq!(*flush_marker, I::Update::default());
478
479 Self::insert_internal(&[new_entry], cursor, flush_marker, &mut notify);
481 return;
482 }
483
484 let mut node = cursor.node.as_mut();
485 let mut entry = &mut node.data[cursor.idx];
486 let mut entry_len = entry.len();
487
488 if cursor.offset > 0 {
489 if cursor.offset + replaced_len < entry_len {
490 let mut a = *entry;
492 a.truncate(cursor.offset);
493
494 let mut c = *entry;
495 c.truncate_keeping_right(cursor.offset + replaced_len);
496 let c_len = c.len();
497
498 Self::replace_entry(cursor, &[a, new_entry, c], flush_marker, &mut notify);
500
501 cursor.move_back_by_offset(c_len, Some(flush_marker));
503 return;
504 } else {
505 let removed = entry.truncate(cursor.offset);
507 I::decrement_marker(flush_marker, &removed);
508 replaced_len -= entry_len - cursor.offset;
509 debug_assert_eq!(entry_len - cursor.offset, removed.len());
510
511 if replaced_len == 0 || !cursor.next_entry_marker(Some(flush_marker)) {
512 Self::insert_internal(&[new_entry], cursor, flush_marker, &mut notify);
514 return;
515 }
516
517 node = cursor.node.as_mut();
520 entry = &mut node.data[cursor.idx];
521 entry_len = entry.len();
522 }
523 }
524
525 debug_assert_eq!(cursor.offset, 0);
526
527 if replaced_len >= entry_len {
528 I::decrement_marker(flush_marker, entry);
532 I::increment_marker(flush_marker, &new_entry);
533 notify(new_entry, cursor.node);
534 cursor.offset = new_entry.len();
535 *cursor.get_raw_entry_mut() = new_entry;
536
537 if replaced_len > entry_len {
538 cursor.next_entry_marker(Some(flush_marker));
540 Self::delete_internal(cursor, replaced_len - entry_len, flush_marker, &mut notify);
541 } } else { let mut remainder = *entry;
545 let remainder = remainder.truncate(replaced_len);
546 let rem_len = remainder.len();
547 Self::replace_entry(cursor, &[new_entry, remainder], flush_marker, &mut notify);
548 cursor.move_back_by_offset(rem_len, Some(flush_marker));
549 }
550 }
551
552 unsafe fn delete_entry_range(cursor: &mut UnsafeCursor<E, I, IE, LE>, mut del_items: usize, flush_marker: &mut I::Update) -> (bool, usize) {
561 debug_assert_eq!(cursor.offset, 0);
563 debug_assert!(del_items > 0);
564
565 let mut node = cursor.get_node_mut();
566 if cursor.idx >= node.num_entries as usize {
568 node.flush_metric_update(flush_marker);
569 if !cursor.traverse_forward() { return (false, 0); }
571 node = cursor.get_node_mut();
572 }
573
574 if cursor.idx >= LE { unreachable_unchecked(); }
575 let start_range = cursor.idx;
576 let mut end_range = cursor.idx;
577
578 let len_entries = node.len_entries();
580 while end_range < len_entries && del_items > 0 {
582 let entry = node.data[end_range];
583 let entry_len = entry.len();
584 if entry_len <= del_items {
585 I::decrement_marker(flush_marker, &entry);
586 del_items -= entry_len;
587 end_range += 1;
588 } else {
589 break;
590 }
591 }
592
593 if start_range == 0 && end_range == len_entries && !node.has_root_as_parent() {
594 node.flush_metric_update(flush_marker);
596
597 let node = cursor.node;
598 let has_next = cursor.traverse_forward();
599 if !has_next {
600 cursor.traverse_backwards();
611 del_items = 0; }
613
614 NodeLeaf::remove(node);
615 (has_next, del_items)
616 } else if end_range > start_range {
617 let len_entries = node.len_entries();
620 let tail_count = len_entries - end_range;
621 if tail_count > 0 {
622 node.data.copy_within(end_range..len_entries, start_range);
623 }
624 node.num_entries = (start_range + tail_count) as u8;
625
626 debug_assert!(node.num_entries > 0 || node.parent.is_root());
628
629 node.data[start_range + tail_count..].fill(E::default());
633
634 (true, del_items)
636 } else {
637 (false, del_items)
638 }
639 }
640
641 unsafe fn delete_internal<N>(cursor: &mut UnsafeCursor<E, I, IE, LE>, mut del_items: usize, flush_marker: &mut I::Update, notify: &mut N)
642 where N: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>) {
643
644 if del_items == 0 { return; }
645
646 if cursor.offset > 0 {
648 let node = cursor.node.as_mut();
649 let entry = &mut node.data[cursor.idx];
650 let entry_len = entry.len();
651
652 let remaining_len = entry_len - cursor.offset;
653 if remaining_len > 0 {
654 if remaining_len <= del_items {
655 I::decrement_marker(flush_marker, &entry.truncate(cursor.offset));
657 del_items -= remaining_len;
658 if del_items == 0 { return; }
659 } else { let mut remainder = entry.truncate(cursor.offset);
661 I::decrement_marker(flush_marker, &remainder);
662
663 remainder.truncate_keeping_right(del_items);
664
665 let mut c2 = cursor.clone();
673 Self::insert_internal(&[remainder], &mut c2, flush_marker, notify);
674 c2.get_node_mut().flush_metric_update(flush_marker);
675
676 return;
677 }
678 }
679
680 if !cursor.next_entry_marker(Some(flush_marker)) { return; }
682 }
683
684 debug_assert!(del_items > 0);
685 debug_assert_eq!(cursor.offset, 0);
686
687 while del_items > 0 {
690 let (iterate, num) = Self::delete_entry_range(cursor, del_items, flush_marker);
691 del_items = num;
692 if !iterate { break; }
693 }
695
696
697 let node = cursor.node.as_mut();
698 if del_items > 0 {
699 debug_assert!(cursor.idx < node.len_entries());
707 debug_assert!(node.data[cursor.idx].len() > del_items);
708
709 let trimmed = node.data[cursor.idx].truncate_keeping_right(del_items);
710 I::decrement_marker(flush_marker, &trimmed);
711 } else if cursor.idx >= node.len_entries() {
712 debug_assert_eq!(cursor.offset, 0);
713 if cursor.idx == 0 {
714 cursor.offset = usize::MAX;
716 debug_assert!(node.parent.is_root());
717 } else {
718 cursor.idx -= 1;
719 cursor.offset = node.data[cursor.idx].len();
720 }
721 }
722 }
723
724 pub unsafe fn unsafe_delete_notify<F>(cursor: &mut UnsafeCursor<E, I, IE, LE>, del_items: usize, mut notify: F)
727 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
728 {
729 let mut marker = I::Update::default();
730 Self::delete_internal(cursor, del_items, &mut marker, &mut notify);
731 cursor.get_node_mut().flush_metric_update(&mut marker);
732 }
733
734 pub fn delete_at_start_notify<F>(self: &mut Pin<Box<Self>>, del_items: usize, mut notify: F)
735 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
736 {
737 let mut marker = I::Update::default();
738 let mut cursor = self.unsafe_cursor_at_start();
739 unsafe {
740 Self::delete_internal(&mut cursor, del_items, &mut marker, &mut notify);
741 cursor.get_node_mut().flush_metric_update(&mut marker);
742 }
743 }
744
745 pub fn delete_at_start(self: &mut Pin<Box<Self>>, del_items: usize) {
746 self.delete_at_start_notify(del_items, null_notify);
747 }
748}
749
750impl<E: ContentTraits + Toggleable, I: TreeMetrics<E>, const IE: usize, const LE: usize> ContentTreeRaw<E, I, IE, LE> {
751 pub unsafe fn local_deactivate_notify<F>(self: &mut Pin<Box<Self>>, mut cursor: UnsafeCursor<E, I, IE, LE>, deleted_len: usize, mut notify: F) -> DeleteResult<E>
752 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
753 {
754 if cfg!(debug_assertions) {
757 }
761 let mut result: DeleteResult<E> = SmallVec::default();
767 let mut flush_marker = I::Update::default();
768 let mut delete_remaining = deleted_len;
769 cursor.roll_to_next_entry();
770
771 while delete_remaining > 0 {
772 while cursor.get_raw_entry().is_deactivated() {
776 Self::next_entry_or_panic(&mut cursor, &mut flush_marker);
777 }
778
779 delete_remaining -= Self::unsafe_mutate_entry_internal(|e| {
782 result.push_rle(*e);
783 e.mark_deactivated();
784 }, &mut cursor, delete_remaining, &mut flush_marker, &mut notify).0;
785 }
786 cursor.compress_node();
787
788 cursor.get_node_mut().flush_metric_update(&mut flush_marker);
790
791 if cfg!(debug_assertions) {
792 }
798
799 result
800 }
801
802 unsafe fn set_enabled<F>(cursor: &mut UnsafeCursor<E, I, IE, LE>, max_len: usize, want_enabled: bool, notify: F) -> (usize, bool)
803 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>) {
804
805 cursor.roll_to_next_entry();
806 let entry = cursor.get_raw_entry();
807
808 if entry.is_activated() != want_enabled {
809 let (amt_modified, _) = Self::unsafe_mutate_single_entry_notify(|e| {
815 if want_enabled { e.mark_activated(); } else { e.mark_deactivated(); }
816 }, cursor, max_len, notify);
817
818 (amt_modified, true)
819 } else {
820 (max_len.min(entry.len() - cursor.offset), false)
822 }
823 }
824
825 pub unsafe fn unsafe_remote_deactivate_notify<F>(cursor: &mut UnsafeCursor<E, I, IE, LE>, max_deleted_len: usize, notify: F) -> (usize, bool)
841 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
842 {
843 Self::set_enabled(cursor, max_deleted_len, false, notify)
844 }
845
846 pub unsafe fn unsafe_remote_reactivate_notify<F>(cursor: &mut UnsafeCursor<E, I, IE, LE>, max_len: usize, notify: F) -> (usize, bool)
847 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
848 {
849 Self::set_enabled(cursor, max_len, true, notify)
850 }
851}
852
853impl<E: ContentTraits, I: FindOffset<E>, const IE: usize, const LE: usize> ContentTreeRaw<E, I, IE, LE> {
854 pub fn insert_at_offset_notify<F>(self: &mut Pin<Box<Self>>, pos: usize, new_entry: E, notify: F)
856 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
857 {
858 let mut cursor = self.unsafe_cursor_at_offset_pos(pos, true);
859 unsafe { Self::unsafe_insert_notify(&mut cursor, new_entry, notify); }
860 }
861
862 pub fn insert_at_offset(self: &mut Pin<Box<Self>>, pos: usize, new_entry: E) {
863 let mut cursor = self.unsafe_cursor_at_offset_pos(pos, true);
864 unsafe { Self::unsafe_insert_notify(&mut cursor, new_entry, null_notify); }
865 }
866
867 pub fn replace_range_at_offset_notify<N>(self: &mut Pin<Box<Self>>, offset: usize, new_entry: E, notify: N)
868 where N: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
869 {
870 let mut cursor = self.unsafe_cursor_at_offset_pos(offset, true);
871 unsafe { Self::unsafe_replace_range_notify(&mut cursor, new_entry, notify); }
872 }
873
874 pub fn replace_range_at_offset(self: &mut Pin<Box<Self>>, offset: usize, new_entry: E) {
875 let mut cursor = self.unsafe_cursor_at_offset_pos(offset, true);
876 unsafe { Self::unsafe_replace_range_notify(&mut cursor, new_entry, null_notify); }
877 }
878
879 pub fn delete_at_offset_notify<F>(self: &mut Pin<Box<Self>>, pos: usize, del_items: usize, notify: F)
880 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
881 {
882 let mut cursor = self.unsafe_cursor_at_offset_pos(pos, false);
883 unsafe { Self::unsafe_delete_notify(&mut cursor, del_items, notify); }
884 }
885
886 pub fn delete_at_offset(self: &mut Pin<Box<Self>>, pos: usize, del_items: usize) {
887 let mut cursor = self.unsafe_cursor_at_offset_pos(pos, false);
888 unsafe { Self::unsafe_delete_notify(&mut cursor, del_items, null_notify); }
889 }
890}
891
892impl<E: ContentTraits + ContentLength, I: FindContent<E>, const IE: usize, const LE: usize> ContentTreeRaw<E, I, IE, LE> {
893 pub fn insert_at_content_notify<F>(self: &mut Pin<Box<Self>>, pos: usize, new_entry: E, notify: F)
894 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
895 {
896 let mut cursor = self.unsafe_cursor_at_content_pos(pos, true);
897 unsafe { Self::unsafe_insert_notify(&mut cursor, new_entry, notify); }
898 }
899
900 pub fn insert_at_content(self: &mut Pin<Box<Self>>, pos: usize, new_entry: E) {
901 let mut cursor = self.unsafe_cursor_at_content_pos(pos, true);
902 unsafe { Self::unsafe_insert_notify(&mut cursor, new_entry, null_notify); }
903 }
904
905 pub fn replace_range_at_content_notify<N>(self: &mut Pin<Box<Self>>, pos: usize, new_entry: E, notify: N)
906 where N: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
907 {
908 let mut cursor = self.unsafe_cursor_at_content_pos(pos, true);
909 unsafe { Self::unsafe_replace_range_notify(&mut cursor, new_entry, notify); }
910 }
911 pub fn replace_range_at_content(self: &mut Pin<Box<Self>>, pos: usize, new_entry: E) {
912 let mut cursor = self.unsafe_cursor_at_content_pos(pos, true);
913 unsafe { Self::unsafe_replace_range_notify(&mut cursor, new_entry, null_notify); }
914 }
915
916 pub fn delete_at_content_notify<F>(self: &mut Pin<Box<Self>>, pos: usize, del_items: usize, notify: F)
917 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
918 {
919 let mut cursor = self.unsafe_cursor_at_content_pos(pos, false);
920 unsafe { Self::unsafe_delete_notify(&mut cursor, del_items, notify); }
921 }
922 pub fn delete_at_content(self: &mut Pin<Box<Self>>, pos: usize, del_items: usize) {
923 let mut cursor = self.unsafe_cursor_at_content_pos(pos, false);
924 unsafe { Self::unsafe_delete_notify(&mut cursor, del_items, null_notify); }
925 }
926}
927
928impl<E: ContentTraits + ContentLength + Toggleable, I: FindContent<E>, const IE: usize, const LE: usize> ContentTreeRaw<E, I, IE, LE> {
929 pub fn local_deactivate_at_content_notify<F>(self: &mut Pin<Box<Self>>, offset: usize, deleted_len: usize, notify: F) -> DeleteResult<E>
930 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
931 {
932 let cursor = self.unsafe_cursor_at_content_pos(offset, false);
933 unsafe { self.local_deactivate_notify(cursor, deleted_len, notify) }
934 }
935}
936
937impl<E: ContentTraits, I: TreeMetrics<E>, const IE: usize, const LE: usize> NodeLeaf<E, I, IE, LE> {
938
939 fn split_at<F>(&mut self, idx: usize, padding: usize, notify: &mut F) -> NonNull<NodeLeaf<E, I, IE, LE>>
943 where F: FnMut(E, NonNull<NodeLeaf<E, I, IE, LE>>)
944 {
945 unsafe {
947 let mut new_node = Self::new(self.next); let new_filled_len = self.len_entries() - idx;
954 let new_len = new_filled_len + padding;
955 debug_assert!(new_len <= LE);
956
957 if new_filled_len > 0 {
958 ptr::copy_nonoverlapping(&self.data[idx], &mut new_node.data[padding], new_filled_len);
959 }
960
961 new_node.num_entries = new_len as u8; let mut stolen_length = I::Value::default();
966 for e in &mut self.data[idx..self.num_entries as usize] {
968 I::increment_offset(&mut stolen_length, e);
969 *e = E::default();
971 }
972 self.num_entries = idx as u8;
973
974 let mut new_node_boxed = Box::pin(new_node);
977
978 let new_leaf_ptr = NonNull::new_unchecked(new_node_boxed.as_mut().get_unchecked_mut());
980 self.next = Some(new_leaf_ptr);
981
982 for e in &new_node_boxed.as_ref().data[padding..new_len] {
983 notify(*e, new_leaf_ptr);
984 }
985
986 insert_after(self.parent, Node::Leaf(new_node_boxed), NodePtr::Leaf(NonNull::new_unchecked(self)), stolen_length);
987
988 new_leaf_ptr
990 }
991 }
992
993 unsafe fn remove(self_ptr: NonNull<NodeLeaf<E, I, IE, LE>>) {
998 let leaf = self_ptr.as_ref();
1004 debug_assert!(!leaf.has_root_as_parent());
1005
1006 if let Some(mut prev) = leaf.prev_leaf() {
1007 prev.as_mut().next = leaf.next;
1008 }
1009
1010 NodeInternal::remove_leaf(leaf.parent.unwrap_internal(), self_ptr);
1011 }
1012}
1013
1014impl<E: ContentTraits, I: TreeMetrics<E>, const IE: usize, const LE: usize> NodeInternal<E, I, IE, LE> {
1015 unsafe fn slice_out(&mut self, child: NodePtr<E, I, IE, LE>) -> Node<E, I, IE, LE> {
1016 if self.children[1].is_none() {
1017 debug_assert_eq!(self.find_child(child).unwrap(), 0);
1021
1022 self.children[0].take().unwrap()
1023 } else {
1024 let idx = self.find_child(child).unwrap();
1025 let num_children = self.count_children();
1026
1027 let removed = self.children[idx].take().unwrap();
1028
1029 let count = num_children - idx - 1;
1030 if count > 0 {
1031 ptr::copy(
1032 &self.children[idx + 1],
1033 &mut self.children[idx],
1034 count
1035 );
1036
1037 self.metrics.copy_within(idx + 1..num_children, idx);
1038 }
1039
1040 std::mem::forget(self.children[num_children - 1].take());
1042
1043 removed
1044 }
1045 }
1046
1047 unsafe fn remove_leaf(mut self_ptr: NonNull<NodeInternal<E, I, IE, LE>>, child: NonNull<NodeLeaf<E, I, IE, LE>>) {
1048 let spare = self_ptr.as_mut().slice_out(NodePtr::Leaf(child));
1049 Self::ripple_delete(self_ptr, spare);
1050 }
1051
1052 unsafe fn ripple_delete(mut self_ptr: NonNull<NodeInternal<E, I, IE, LE>>, mut spare_leaf: Node<E, I, IE, LE>) {
1053 debug_assert!(spare_leaf.is_leaf());
1054
1055 let self_ref = self_ptr.as_mut();
1056
1057 if self_ref.children[0].is_none() {
1058 match self_ref.parent {
1060 ParentPtr::Root(mut root) => {
1061 let mut root = root.as_mut();
1067 spare_leaf.set_parent(root.to_parent_ptr());
1068 spare_leaf.unwrap_leaf_mut().get_unchecked_mut().clear_all();
1070 root.root = spare_leaf;
1071 }
1072 ParentPtr::Internal(mut parent) => {
1073 parent.as_mut().slice_out(NodePtr::Internal(self_ptr));
1075 Self::ripple_delete(parent, spare_leaf);
1076 }
1077 }
1078 }
1079 }
1080}
1081
1082
1083unsafe fn insert_after<E: ContentTraits, I: TreeMetrics<E>, const INT_ENTRIES: usize, const LEAF_ENTRIES: usize>(
1087 mut parent: ParentPtr<E, I, INT_ENTRIES, LEAF_ENTRIES>,
1088 mut inserted_leaf_node: Node<E, I, INT_ENTRIES, LEAF_ENTRIES>,
1089 mut insert_after: NodePtr<E, I, INT_ENTRIES, LEAF_ENTRIES>,
1090 mut stolen_length: I::Value) {
1091 loop {
1096 if let ParentPtr::Internal(mut n) = parent {
1098 let parent_ref = n.as_ref();
1099 let count = parent_ref.count_children();
1100 if count < INT_ENTRIES {
1101 inserted_leaf_node.set_parent(ParentPtr::Internal(n));
1103
1104 let old_idx = parent_ref.find_child(insert_after).unwrap();
1105 let new_idx = old_idx + 1;
1106
1107 let parent_ref = n.as_mut();
1108 parent_ref.metrics[old_idx] -= stolen_length;
1110 parent_ref.splice_in(new_idx, stolen_length, inserted_leaf_node);
1111
1112 return;
1114 }
1115 }
1116
1117 match parent {
1121 ParentPtr::Root(mut r) => {
1122 let new_root = Node::Internal(NodeInternal::new_with_parent(ParentPtr::Root(r)));
1125 let mut old_root = mem::replace(&mut r.as_mut().root, new_root);
1126
1127 let root = r.as_mut();
1130 let mut count = root.count;
1131 let mut new_internal_root = root.root.unwrap_internal_mut();
1132 let parent_ptr = new_internal_root.as_ref().to_parent_ptr();
1134
1135 old_root.set_parent(parent_ptr);
1137 inserted_leaf_node.set_parent(parent_ptr);
1138
1139 count -= stolen_length;
1140 new_internal_root.as_mut().set_entry(0, count, Some(old_root));
1141 new_internal_root.as_mut().set_entry(1, stolen_length, Some(inserted_leaf_node));
1142
1143 return;
1145 },
1146
1147 ParentPtr::Internal(mut n) => {
1148 let left_sibling = n.as_ref();
1153 parent = left_sibling.parent; debug_assert!(left_sibling.count_children() == INT_ENTRIES);
1155
1156 let mut right_sibling_box = Node::Internal(NodeInternal::new_with_parent(parent));
1158 let mut right_sibling = right_sibling_box.unwrap_internal_mut();
1159 let old_idx = left_sibling.find_child(insert_after).unwrap();
1160
1161 let left_sibling = n.as_mut();
1162 left_sibling.metrics[old_idx] -= stolen_length;
1163 let mut new_stolen_length = I::Value::default();
1164 if old_idx < INT_ENTRIES /2 {
1167 for i in 0..INT_ENTRIES /2 {
1171 let ii = i + INT_ENTRIES /2;
1172 let c = mem::take(&mut left_sibling.metrics[ii]);
1174 let e = mem::take(&mut left_sibling.children[ii]);
1176 if let Some(mut e) = e {
1177 e.set_parent(right_sibling.as_ref().to_parent_ptr());
1178 new_stolen_length += c;
1179 right_sibling.as_mut().set_entry(i, c, Some(e));
1180 }
1181
1182 }
1183
1184 let new_idx = old_idx + 1;
1185 inserted_leaf_node.set_parent(ParentPtr::Internal(NonNull::new_unchecked(left_sibling)));
1186 left_sibling.splice_in(new_idx, stolen_length, inserted_leaf_node);
1187 } else {
1188 let new_idx = old_idx - INT_ENTRIES /2 + 1;
1191
1192 inserted_leaf_node.set_parent(right_sibling.as_ref().to_parent_ptr());
1193 let mut new_entry = (stolen_length, Some(inserted_leaf_node));
1194 new_stolen_length = stolen_length;
1195
1196 let mut src = INT_ENTRIES /2;
1197 for dest in 0..=INT_ENTRIES /2 {
1198 if dest == new_idx {
1199 right_sibling.as_mut().set_entry(dest, mem::take(&mut new_entry.0), mem::take(&mut new_entry.1));
1200 } else {
1201 let c = mem::take(&mut left_sibling.metrics[src]);
1202 let e = mem::take(&mut left_sibling.children[src]);
1203 if let Some(mut e) = e {
1206 e.set_parent(right_sibling.as_ref().to_parent_ptr());
1207 new_stolen_length += c;
1208 right_sibling.as_mut().set_entry(dest, c, Some(e));
1209 src += 1;
1210 } else { break; }
1211 }
1212 }
1213 debug_assert!(new_entry.1.is_none());
1214 }
1215
1216 insert_after = NodePtr::Internal(n);
1217 inserted_leaf_node = right_sibling_box;
1218 stolen_length = new_stolen_length;
1219 },
1221 };
1222 }
1223}
1224
1225#[cfg(test)]
1226mod tests {
1227 use super::*;
1229 use crate::testrange::TestRange;
1230
1231 #[test]
1232 fn splice_insert_test() {
1233 let mut tree = ContentTreeRaw::<TestRange, ContentMetrics, DEFAULT_IE, DEFAULT_LE>::new();
1234 let entry = TestRange {
1235 id: 1000,
1236 len: 100,
1237 is_activated: true
1238 };
1239 tree.insert_at_content(15, entry);
1240 tree.check();
1241
1242 let entry = TestRange {
1243 id: 1100,
1244 len: 20,
1245 is_activated: true
1246 };
1247 tree.insert_at_content(15, entry);
1248 tree.check();
1249
1250 assert_eq!(tree.raw_iter().collect::<Vec<TestRange>>(), vec![
1252 TestRange { id: 1000, len: 15, is_activated: true },
1253 TestRange { id: 1100, len: 20, is_activated: true },
1254 TestRange { id: 1015, len: 85, is_activated: true },
1255 ]);
1256 }
1257
1258 #[test]
1259 fn delete_collapses() {
1260 let mut tree = ContentTreeRaw::<TestRange, ContentMetrics, DEFAULT_IE, DEFAULT_LE>::new();
1261
1262 let entry = TestRange {
1263 id: 1000,
1264 len: 100,
1265 is_activated: true,
1266 };
1267 tree.insert_at_content(0, entry);
1268 assert_eq!(tree.count_entries(), 1);
1269
1270 tree.local_deactivate_at_content_notify(50, 1, null_notify);
1272 assert_eq!(tree.count_entries(), 3);
1273
1274 tree.local_deactivate_at_content_notify(50, 1, null_notify);
1276 assert_eq!(tree.raw_iter().collect::<Vec<TestRange>>(), vec![
1279 TestRange { id: 1000, len: 50, is_activated: true },
1280 TestRange { id: 1050, len: 2, is_activated: false },
1281 TestRange { id: 1052, len: 48, is_activated: true },
1282 ]);
1283 }
1284
1285 #[test]
1286 fn backspace_collapses() {
1287 let mut tree = ContentTreeRaw::<TestRange, ContentMetrics, DEFAULT_IE, DEFAULT_LE>::new();
1288
1289 let entry = TestRange {
1290 id: 1000,
1291 len: 100,
1292 is_activated: true,
1293 };
1294 tree.insert_at_content_notify(0, entry, null_notify);
1295 assert_eq!(tree.count_entries(), 1);
1296
1297 tree.local_deactivate_at_content_notify(99, 1, null_notify);
1300 assert_eq!(tree.count_entries(), 2);
1301
1302 tree.local_deactivate_at_content_notify(98, 1, null_notify);
1303 assert_eq!(tree.count_entries(), 2);
1304
1305 assert_eq!(tree.raw_iter().collect::<Vec<TestRange>>(), vec![
1306 TestRange { id: 1000, len: 98, is_activated: true },
1307 TestRange { id: 1098, len: 2, is_activated: false },
1308 ]);
1309 tree.check();
1310 }
1311
1312 #[test]
1313 fn delete_single_item() {
1314 let mut tree = ContentTreeRaw::<TestRange, ContentMetrics, DEFAULT_IE, DEFAULT_LE>::new();
1315 tree.insert_at_start(TestRange { id: 0, len: 10, is_activated: true });
1316
1317 tree.delete_at_start(10);
1318 assert_eq!(tree.len(), 0);
1319 tree.check();
1320 }
1321
1322 #[test]
1323 fn delete_all_items() {
1324 let mut tree = ContentTreeRaw::<TestRange, ContentMetrics, DEFAULT_IE, DEFAULT_LE>::new();
1325 let num = DEFAULT_LE + 1;
1326 for i in 0..num {
1327 tree.insert_at_start_notify(TestRange { id: i as _, len: 10, is_activated: true }, null_notify);
1328 }
1329 assert!(!tree.root.is_leaf());
1331
1332 tree.delete_at_start_notify(10 * num, null_notify);
1333 assert_eq!(tree.len(), 0);
1334 tree.check();
1335 }
1336
1337 #[test]
1338 fn delete_past_end() {
1339 let mut tree = ContentTreeRaw::<TestRange, ContentMetrics, DEFAULT_IE, DEFAULT_LE>::new();
1340 tree.insert_at_start_notify(TestRange { id: 10 as _, len: 10, is_activated: true }, null_notify);
1341 tree.delete_at_content_notify(10, 100, null_notify);
1342
1343 assert_eq!(tree.raw_iter().collect::<Vec<TestRange>>(), vec![
1344 TestRange { id: 10, len: 10, is_activated: true },
1345 ]);
1346 }
1347
1348 #[test]
1349 fn push_into_empty() {
1350 let mut tree = ContentTreeRaw::<TestRange, ContentMetrics, DEFAULT_IE, DEFAULT_LE>::new();
1351 tree.push(TestRange { id: 0, len: 10, is_activated: true });
1352 }
1353
1354 #[test]
1355 fn mutation_wrappers() {
1356 let mut tree = ContentTreeRaw::<TestRange, FullMetricsU32, DEFAULT_IE, DEFAULT_LE>::new();
1357 tree.insert_at_content(0, TestRange { id: 0, len: 10, is_activated: true });
1358 assert_eq!(tree.offset_len(), 10);
1359 assert_eq!(tree.content_len(), 10);
1360
1361 tree.replace_range_at_content(3, TestRange { id: 100, len: 3, is_activated: false });
1362 assert_eq!(tree.offset_len(), 10);
1363 assert_eq!(tree.content_len(), 7);
1364
1365 assert_eq!(tree.at_content(4), Some((7, true)));
1366 assert_eq!(tree.at_offset(4), Some((101, false)));
1367
1368 tree.delete_at_offset(5, 3);
1370 assert_eq!(tree.offset_len(), 7);
1371 assert_eq!(tree.content_len(), 5);
1372
1373 tree.delete_at_content(0, 1);
1374 assert_eq!(tree.offset_len(), 6);
1375 assert_eq!(tree.content_len(), 4);
1376 }
1377
1378 #[test]
1379 fn mutate_range() {
1380 let mut tree = ContentTreeRaw::<TestRange, FullMetricsU32, DEFAULT_IE, DEFAULT_LE>::new();
1381 tree.push(TestRange { id: 0, len: 10, is_activated: true });
1382
1383 unsafe {
1384 let mut cursor = tree.unsafe_cursor_at_offset_pos(5, false);
1385 ContentTreeRaw::unsafe_mutate_entries_notify(|r| {
1386 assert_eq!(r, &TestRange { id: 5, len: 2, is_activated: true });
1387
1388 r.len = 1;
1389 }, &mut cursor, 2, null_notify);
1390 }
1391 unsafe {
1394 let mut cursor = tree.unsafe_cursor_at_offset_pos(5, false);
1395 ContentTreeRaw::unsafe_mutate_entries_notify(|r| {
1396 assert_eq!(r.len, 1);
1398 assert!(r.id == 5 || r.id == 7);
1399 r.len += 1;
1400 }, &mut cursor, 2, null_notify);
1401 }
1402
1403 assert_eq!(tree.raw_iter().collect::<Vec<TestRange>>(), vec![
1405 TestRange { id: 0, len: 9, is_activated: true },
1406 TestRange { id: 8, len: 2, is_activated: true },
1407 ]);
1408 }
1410}