1#![allow(unsafe_code)]
47
48use std::borrow::Borrow;
49use std::cmp::Ordering;
50use std::fmt::{Debug, Error, Formatter};
51use std::hash::{Hash, Hasher};
52use std::iter::Sum;
53use std::iter::{FromIterator, FusedIterator};
54use std::mem::{replace, swap};
55use std::ops::{Add, Index, IndexMut, RangeBounds};
56
57use archery::{SharedPointer, SharedPointerKind};
58use imbl_sized_chunks::InlineArray;
59
60use crate::nodes::chunk::{Chunk, CHUNK_SIZE};
61use crate::nodes::rrb::{Node, PopResult, PushResult, SplitResult};
62use crate::shared_ptr::DefaultSharedPtr;
63use crate::sort;
64use crate::util::{clone_ref, to_range, Side};
65
66use self::VectorInner::{Full, Inline, Single};
67
68mod focus;
69
70pub use self::focus::{Focus, FocusMut};
71
72#[cfg(any(test, feature = "rayon"))]
73pub mod rayon;
74
75#[macro_export]
90macro_rules! vector {
91 () => { $crate::vector::Vector::new() };
92
93 ( $($x:expr),* ) => {{
94 let mut l = $crate::vector::Vector::new();
95 $(
96 l.push_back($x);
97 )*
98 l
99 }};
100
101 ( $($x:expr ,)* ) => {{
102 let mut l = $crate::vector::Vector::new();
103 $(
104 l.push_back($x);
105 )*
106 l
107 }};
108}
109
110pub type Vector<A> = GenericVector<A, DefaultSharedPtr>;
115
116pub struct GenericVector<A, P: SharedPointerKind> {
153 vector: VectorInner<A, P>,
154}
155
156enum VectorInner<A, P: SharedPointerKind> {
157 Inline(InlineArray<A, RRB<A, P>>),
158 Single(SharedPointer<Chunk<A>, P>),
159 Full(RRB<A, P>),
160}
161
162#[doc(hidden)]
163pub struct RRB<A, P: SharedPointerKind> {
164 length: usize,
165 middle_level: usize,
166 outer_f: SharedPointer<Chunk<A>, P>,
167 inner_f: SharedPointer<Chunk<A>, P>,
168 middle: SharedPointer<Node<A, P>, P>,
169 inner_b: SharedPointer<Chunk<A>, P>,
170 outer_b: SharedPointer<Chunk<A>, P>,
171}
172
173impl<A, P: SharedPointerKind> Clone for RRB<A, P> {
174 fn clone(&self) -> Self {
175 RRB {
176 length: self.length,
177 middle_level: self.middle_level,
178 outer_f: self.outer_f.clone(),
179 inner_f: self.inner_f.clone(),
180 middle: self.middle.clone(),
181 inner_b: self.inner_b.clone(),
182 outer_b: self.outer_b.clone(),
183 }
184 }
185}
186
187impl<A, P: SharedPointerKind> GenericVector<A, P> {
188 fn needs_promotion(&self) -> bool {
191 match &self.vector {
192 Inline(chunk) => chunk.is_full() || chunk.len() + 1 >= CHUNK_SIZE,
197 Single(chunk) => chunk.is_full(),
198 _ => false,
199 }
200 }
201
202 fn promote_inline(&mut self) {
204 if let Inline(chunk) = &mut self.vector {
205 self.vector = Single(SharedPointer::new(chunk.into()));
206 }
207 }
208
209 fn promote_front(&mut self) {
212 self.vector = match &mut self.vector {
213 Inline(chunk) => Single(SharedPointer::new(chunk.into())),
214 Single(chunk) => {
215 let chunk = chunk.clone();
216 Full(RRB {
217 length: chunk.len(),
218 middle_level: 0,
219 outer_f: SharedPointer::default(),
220 inner_f: chunk,
221 middle: SharedPointer::new(Node::new()),
222 inner_b: SharedPointer::default(),
223 outer_b: SharedPointer::default(),
224 })
225 }
226 Full(_) => return,
227 }
228 }
229
230 fn promote_back(&mut self) {
233 self.vector = match &mut self.vector {
234 Inline(chunk) => Single(SharedPointer::new(chunk.into())),
235 Single(chunk) => {
236 let chunk = chunk.clone();
237 Full(RRB {
238 length: chunk.len(),
239 middle_level: 0,
240 outer_f: SharedPointer::default(),
241 inner_f: SharedPointer::default(),
242 middle: SharedPointer::new(Node::new()),
243 inner_b: chunk,
244 outer_b: SharedPointer::default(),
245 })
246 }
247 Full(_) => return,
248 }
249 }
250
251 #[must_use]
253 pub fn new() -> Self {
254 Self {
255 vector: Inline(InlineArray::new()),
256 }
257 }
258
259 #[inline]
272 #[must_use]
273 pub fn len(&self) -> usize {
274 match &self.vector {
275 Inline(chunk) => chunk.len(),
276 Single(chunk) => chunk.len(),
277 Full(tree) => tree.length,
278 }
279 }
280
281 #[inline]
295 #[must_use]
296 pub fn is_empty(&self) -> bool {
297 self.len() == 0
298 }
299
300 #[inline]
316 #[must_use]
317 pub fn is_inline(&self) -> bool {
318 matches!(self.vector, Inline(_))
319 }
320
321 #[must_use]
336 pub fn ptr_eq(&self, other: &Self) -> bool {
337 fn cmp_chunk<A, P: SharedPointerKind>(
338 left: &SharedPointer<Chunk<A>, P>,
339 right: &SharedPointer<Chunk<A>, P>,
340 ) -> bool {
341 (left.is_empty() && right.is_empty()) || SharedPointer::ptr_eq(left, right)
342 }
343
344 if std::ptr::eq(self, other) {
345 return true;
346 }
347
348 match (&self.vector, &other.vector) {
349 (Single(left), Single(right)) => cmp_chunk(left, right),
350 (Full(left), Full(right)) => {
351 cmp_chunk(&left.outer_f, &right.outer_f)
352 && cmp_chunk(&left.inner_f, &right.inner_f)
353 && cmp_chunk(&left.inner_b, &right.inner_b)
354 && cmp_chunk(&left.outer_b, &right.outer_b)
355 && ((left.middle.is_empty() && right.middle.is_empty())
356 || SharedPointer::ptr_eq(&left.middle, &right.middle))
357 }
358 _ => false,
359 }
360 }
361
362 #[inline]
366 #[must_use]
367 pub fn iter(&self) -> Iter<'_, A, P> {
368 Iter::new(self)
369 }
370
371 #[inline]
381 #[must_use]
382 pub fn leaves(&self) -> Chunks<'_, A, P> {
383 Chunks::new(self)
384 }
385
386 #[inline]
392 #[must_use]
393 pub fn focus(&self) -> Focus<'_, A, P> {
394 Focus::new(self)
395 }
396
397 #[must_use]
412 pub fn get(&self, index: usize) -> Option<&A> {
413 if index >= self.len() {
414 return None;
415 }
416
417 match &self.vector {
418 Inline(chunk) => chunk.get(index),
419 Single(chunk) => chunk.get(index),
420 Full(tree) => {
421 let mut local_index = index;
422
423 if local_index < tree.outer_f.len() {
424 return Some(&tree.outer_f[local_index]);
425 }
426 local_index -= tree.outer_f.len();
427
428 if local_index < tree.inner_f.len() {
429 return Some(&tree.inner_f[local_index]);
430 }
431 local_index -= tree.inner_f.len();
432
433 if local_index < tree.middle.len() {
434 return Some(tree.middle.index(tree.middle_level, local_index));
435 }
436 local_index -= tree.middle.len();
437
438 if local_index < tree.inner_b.len() {
439 return Some(&tree.inner_b[local_index]);
440 }
441 local_index -= tree.inner_b.len();
442
443 Some(&tree.outer_b[local_index])
444 }
445 }
446 }
447
448 #[inline]
454 #[must_use]
455 pub fn front(&self) -> Option<&A> {
456 self.get(0)
457 }
458
459 #[inline]
469 #[must_use]
470 pub fn head(&self) -> Option<&A> {
471 self.get(0)
472 }
473
474 #[must_use]
480 pub fn back(&self) -> Option<&A> {
481 if self.is_empty() {
482 None
483 } else {
484 self.get(self.len() - 1)
485 }
486 }
487
488 #[inline]
498 #[must_use]
499 pub fn last(&self) -> Option<&A> {
500 self.back()
501 }
502
503 #[must_use]
520 pub fn index_of(&self, value: &A) -> Option<usize>
521 where
522 A: PartialEq,
523 {
524 for (index, item) in self.iter().enumerate() {
525 if value == item {
526 return Some(index);
527 }
528 }
529 None
530 }
531
532 #[inline]
549 #[must_use]
550 pub fn contains(&self, value: &A) -> bool
551 where
552 A: PartialEq,
553 {
554 self.index_of(value).is_some()
555 }
556
557 pub fn clear(&mut self) {
564 if !self.is_empty() {
565 self.vector = Inline(InlineArray::new());
566 }
567 }
568
569 pub fn binary_search_by<F>(&self, mut f: F) -> Result<usize, usize>
584 where
585 F: FnMut(&A) -> Ordering,
586 {
587 let mut size = self.len();
588 if size == 0 {
589 return Err(0);
590 }
591 let mut base = 0;
592 while size > 1 {
593 let half = size / 2;
594 let mid = base + half;
595 base = match f(&self[mid]) {
596 Ordering::Greater => base,
597 _ => mid,
598 };
599 size -= half;
600 }
601 match f(&self[base]) {
602 Ordering::Equal => Ok(base),
603 Ordering::Greater => Err(base),
604 Ordering::Less => Err(base + 1),
605 }
606 }
607
608 pub fn binary_search(&self, value: &A) -> Result<usize, usize>
617 where
618 A: Ord,
619 {
620 self.binary_search_by(|e| e.cmp(value))
621 }
622
623 pub fn binary_search_by_key<B, F>(&self, b: &B, mut f: F) -> Result<usize, usize>
638 where
639 F: FnMut(&A) -> B,
640 B: Ord,
641 {
642 self.binary_search_by(|k| f(k).cmp(b))
643 }
644
645 #[inline]
660 #[must_use]
661 pub fn unit(a: A) -> Self {
662 if InlineArray::<A, RRB<A, P>>::CAPACITY > 0 {
663 let mut array = InlineArray::new();
664 array.push(a);
665 Self {
666 vector: Inline(array),
667 }
668 } else {
669 let chunk = SharedPointer::new(Chunk::unit(a));
670 Self {
671 vector: Single(chunk),
672 }
673 }
674 }
675
676 #[cfg(any(test, feature = "debug"))]
680 pub fn dot<W: std::io::Write>(&self, write: W) -> std::io::Result<()> {
681 if let Full(ref tree) = self.vector {
682 tree.middle.dot(write)
683 } else {
684 Ok(())
685 }
686 }
687
688 #[cfg(any(test, feature = "debug"))]
696 pub fn assert_invariants(&self) {
697 if let Full(ref tree) = self.vector {
698 tree.assert_invariants();
699 }
700 }
701}
702
703impl<A: Clone, P: SharedPointerKind> GenericVector<A, P> {
704 #[must_use]
724 pub fn get_mut(&mut self, index: usize) -> Option<&mut A> {
725 if index >= self.len() {
726 return None;
727 }
728
729 match &mut self.vector {
730 Inline(chunk) => chunk.get_mut(index),
731 Single(chunk) => SharedPointer::make_mut(chunk).get_mut(index),
732 Full(tree) => {
733 let mut local_index = index;
734
735 if local_index < tree.outer_f.len() {
736 let outer_f = SharedPointer::make_mut(&mut tree.outer_f);
737 return Some(&mut outer_f[local_index]);
738 }
739 local_index -= tree.outer_f.len();
740
741 if local_index < tree.inner_f.len() {
742 let inner_f = SharedPointer::make_mut(&mut tree.inner_f);
743 return Some(&mut inner_f[local_index]);
744 }
745 local_index -= tree.inner_f.len();
746
747 if local_index < tree.middle.len() {
748 let middle = SharedPointer::make_mut(&mut tree.middle);
749 return Some(middle.index_mut(tree.middle_level, local_index));
750 }
751 local_index -= tree.middle.len();
752
753 if local_index < tree.inner_b.len() {
754 let inner_b = SharedPointer::make_mut(&mut tree.inner_b);
755 return Some(&mut inner_b[local_index]);
756 }
757 local_index -= tree.inner_b.len();
758
759 let outer_b = SharedPointer::make_mut(&mut tree.outer_b);
760 Some(&mut outer_b[local_index])
761 }
762 }
763 }
764
765 #[inline]
771 #[must_use]
772 pub fn front_mut(&mut self) -> Option<&mut A> {
773 self.get_mut(0)
774 }
775
776 #[must_use]
782 pub fn back_mut(&mut self) -> Option<&mut A> {
783 if self.is_empty() {
784 None
785 } else {
786 let len = self.len();
787 self.get_mut(len - 1)
788 }
789 }
790
791 #[inline]
797 #[must_use]
798 pub fn focus_mut(&mut self) -> FocusMut<'_, A, P> {
799 FocusMut::new(self)
800 }
801
802 #[inline]
806 #[must_use]
807 pub fn iter_mut(&mut self) -> IterMut<'_, A, P> {
808 IterMut::new(self)
809 }
810
811 #[inline]
821 #[must_use]
822 pub fn leaves_mut(&mut self) -> ChunksMut<'_, A, P> {
823 ChunksMut::new(self)
824 }
825
826 #[must_use]
840 pub fn update(&self, index: usize, value: A) -> Self {
841 let mut out = self.clone();
842 out[index] = value;
843 out
844 }
845
846 #[inline]
854 pub fn set(&mut self, index: usize, value: A) -> A {
855 replace(&mut self[index], value)
856 }
857
858 pub fn swap(&mut self, i: usize, j: usize) {
862 if i != j {
863 let a: *mut A = &mut self[i];
864 let b: *mut A = &mut self[j];
865
866 unsafe {
869 std::ptr::swap(a, b);
870 }
871 }
872 }
873
874 pub fn push_front(&mut self, value: A) {
887 if self.needs_promotion() {
888 self.promote_back();
889 }
890 match &mut self.vector {
891 Inline(chunk) => {
892 chunk.insert(0, value);
893 }
894 Single(chunk) => SharedPointer::make_mut(chunk).push_front(value),
895 Full(tree) => tree.push_front(value),
896 }
897 }
898
899 pub fn push_back(&mut self, value: A) {
912 if self.needs_promotion() {
913 self.promote_front();
914 }
915 match &mut self.vector {
916 Inline(chunk) => {
917 chunk.push(value);
918 }
919 Single(chunk) => SharedPointer::make_mut(chunk).push_back(value),
920 Full(tree) => tree.push_back(value),
921 }
922 }
923
924 pub fn pop_front(&mut self) -> Option<A> {
937 if self.is_empty() {
938 None
939 } else {
940 match &mut self.vector {
941 Inline(chunk) => chunk.remove(0),
942 Single(chunk) => Some(SharedPointer::make_mut(chunk).pop_front()),
943 Full(tree) => tree.pop_front(),
944 }
945 }
946 }
947
948 pub fn pop_back(&mut self) -> Option<A> {
962 if self.is_empty() {
963 None
964 } else {
965 match &mut self.vector {
966 Inline(chunk) => chunk.pop(),
967 Single(chunk) => Some(SharedPointer::make_mut(chunk).pop_back()),
968 Full(tree) => tree.pop_back(),
969 }
970 }
971 }
972
973 pub fn append(&mut self, mut other: Self) {
986 if other.is_empty() {
987 return;
988 }
989
990 if self.is_empty() {
991 *self = other;
992 return;
993 }
994
995 self.promote_inline();
996 other.promote_inline();
997
998 let total_length = self
999 .len()
1000 .checked_add(other.len())
1001 .expect("Vector length overflow");
1002
1003 match &mut self.vector {
1004 Inline(_) => unreachable!("inline vecs should have been promoted"),
1005 Single(left) => {
1006 match &mut other.vector {
1007 Inline(_) => unreachable!("inline vecs should have been promoted"),
1008 Single(ref mut right) if total_length <= CHUNK_SIZE => {
1011 SharedPointer::make_mut(left).append(SharedPointer::make_mut(right));
1012 return;
1013 }
1014 _ if total_length <= CHUNK_SIZE => {
1017 while let Some(value) = other.pop_front() {
1018 SharedPointer::make_mut(left).push_back(value);
1019 }
1020 return;
1021 }
1022 _ => {}
1023 }
1024 }
1025 Full(left) => {
1026 if let Full(mut right) = other.vector {
1027 if left.middle.is_empty()
1031 && right.middle.is_empty()
1032 && left.outer_b.is_empty()
1033 && left.inner_b.is_empty()
1034 && right.outer_f.is_empty()
1035 && right.inner_f.is_empty()
1036 {
1037 left.inner_b = right.inner_b;
1038 left.outer_b = right.outer_b;
1039 left.length = total_length;
1040 return;
1041 }
1042 if left.middle.is_empty()
1045 && right.middle.is_empty()
1046 && total_length <= CHUNK_SIZE * 4
1047 {
1048 while let Some(value) = right.pop_front() {
1049 left.push_back(value);
1050 }
1051 return;
1052 }
1053 let inner_b1 = left.inner_b.clone();
1055 left.push_middle(Side::Right, inner_b1);
1056 let outer_b1 = left.outer_b.clone();
1057 left.push_middle(Side::Right, outer_b1);
1058 let inner_f2 = right.inner_f.clone();
1059 right.push_middle(Side::Left, inner_f2);
1060 let outer_f2 = right.outer_f.clone();
1061 right.push_middle(Side::Left, outer_f2);
1062
1063 let mut middle1 =
1064 clone_ref(replace(&mut left.middle, SharedPointer::new(Node::new())));
1065 let mut middle2 = clone_ref(right.middle);
1066 let normalised_middle = match left.middle_level.cmp(&right.middle_level) {
1067 Ordering::Greater => {
1068 middle2 = middle2.elevate(left.middle_level - right.middle_level);
1069 left.middle_level
1070 }
1071 Ordering::Less => {
1072 middle1 = middle1.elevate(right.middle_level - left.middle_level);
1073 right.middle_level
1074 }
1075 Ordering::Equal => left.middle_level,
1076 };
1077 left.middle =
1078 SharedPointer::new(Node::merge(middle1, middle2, normalised_middle));
1079 left.middle_level = normalised_middle + 1;
1080
1081 left.inner_b = right.inner_b;
1082 left.outer_b = right.outer_b;
1083 left.length = total_length;
1084 left.prune();
1085 return;
1086 }
1087 }
1088 }
1089 self.promote_front();
1092 other.promote_back();
1093 self.append(other)
1094 }
1095
1096 pub fn retain<F>(&mut self, mut f: F)
1103 where
1104 F: FnMut(&A) -> bool,
1105 {
1106 let len = self.len();
1107 let mut del = 0;
1108 {
1109 let mut focus = self.focus_mut();
1110 for i in 0..len {
1111 if !f(focus.index(i)) {
1112 del += 1;
1113 } else if del > 0 {
1114 focus.swap(i - del, i);
1115 }
1116 }
1117 }
1118 if del > 0 {
1119 let _ = self.split_off(len - del);
1120 }
1121 }
1122
1123 pub fn split_at(mut self, index: usize) -> (Self, Self) {
1141 let right = self.split_off(index);
1142 (self, right)
1143 }
1144
1145 #[must_use]
1163 pub fn split_off(&mut self, index: usize) -> Self {
1164 assert!(index <= self.len());
1165
1166 match &mut self.vector {
1167 Inline(chunk) => Self {
1168 vector: Inline(chunk.split_off(index)),
1169 },
1170 Single(chunk) => Self {
1171 vector: Single(SharedPointer::new(
1172 SharedPointer::make_mut(chunk).split_off(index),
1173 )),
1174 },
1175 Full(tree) => {
1176 let mut local_index = index;
1177
1178 if local_index < tree.outer_f.len() {
1179 let of2 = SharedPointer::make_mut(&mut tree.outer_f).split_off(local_index);
1180 let right = RRB {
1181 length: tree.length - index,
1182 middle_level: tree.middle_level,
1183 outer_f: SharedPointer::new(of2),
1184 inner_f: replace_shared_pointer(&mut tree.inner_f),
1185 middle: std::mem::take(&mut tree.middle),
1186 inner_b: replace_shared_pointer(&mut tree.inner_b),
1187 outer_b: replace_shared_pointer(&mut tree.outer_b),
1188 };
1189 tree.length = index;
1190 tree.middle_level = 0;
1191 return Self {
1192 vector: Full(right),
1193 };
1194 }
1195
1196 local_index -= tree.outer_f.len();
1197
1198 if local_index < tree.inner_f.len() {
1199 let if2 = SharedPointer::make_mut(&mut tree.inner_f).split_off(local_index);
1200 let right = RRB {
1201 length: tree.length - index,
1202 middle_level: tree.middle_level,
1203 outer_f: SharedPointer::new(if2),
1204 inner_f: SharedPointer::default(),
1205 middle: std::mem::take(&mut tree.middle),
1206 inner_b: replace_shared_pointer(&mut tree.inner_b),
1207 outer_b: replace_shared_pointer(&mut tree.outer_b),
1208 };
1209 tree.length = index;
1210 tree.middle_level = 0;
1211 swap(&mut tree.outer_b, &mut tree.inner_f);
1212 return Self {
1213 vector: Full(right),
1214 };
1215 }
1216
1217 local_index -= tree.inner_f.len();
1218
1219 if local_index < tree.middle.len() {
1220 let mut right_middle = tree.middle.clone();
1221 let (c1, c2) = {
1222 let m1 = SharedPointer::make_mut(&mut tree.middle);
1223 let m2 = SharedPointer::make_mut(&mut right_middle);
1224 match m1.split(tree.middle_level, Side::Right, local_index) {
1225 SplitResult::Dropped(_) => (),
1226 SplitResult::OutOfBounds => unreachable!(),
1227 };
1228 match m2.split(tree.middle_level, Side::Left, local_index) {
1229 SplitResult::Dropped(_) => (),
1230 SplitResult::OutOfBounds => unreachable!(),
1231 };
1232 let c1 = match m1.pop_chunk(tree.middle_level, Side::Right) {
1233 PopResult::Empty => SharedPointer::default(),
1234 PopResult::Done(chunk) => chunk,
1235 PopResult::Drained(chunk) => {
1236 m1.clear_node();
1237 chunk
1238 }
1239 };
1240 let c2 = match m2.pop_chunk(tree.middle_level, Side::Left) {
1241 PopResult::Empty => SharedPointer::default(),
1242 PopResult::Done(chunk) => chunk,
1243 PopResult::Drained(chunk) => {
1244 m2.clear_node();
1245 chunk
1246 }
1247 };
1248 (c1, c2)
1249 };
1250 let mut right = RRB {
1251 length: tree.length - index,
1252 middle_level: tree.middle_level,
1253 outer_f: c2,
1254 inner_f: SharedPointer::default(),
1255 middle: right_middle,
1256 inner_b: replace_shared_pointer(&mut tree.inner_b),
1257 outer_b: replace(&mut tree.outer_b, c1),
1258 };
1259 tree.length = index;
1260 tree.prune();
1261 right.prune();
1262 return Self {
1263 vector: Full(right),
1264 };
1265 }
1266
1267 local_index -= tree.middle.len();
1268
1269 if local_index < tree.inner_b.len() {
1270 let ib2 = SharedPointer::make_mut(&mut tree.inner_b).split_off(local_index);
1271 let right = RRB {
1272 length: tree.length - index,
1273 outer_b: replace_shared_pointer(&mut tree.outer_b),
1274 outer_f: SharedPointer::new(ib2),
1275 ..RRB::new()
1276 };
1277 tree.length = index;
1278 swap(&mut tree.outer_b, &mut tree.inner_b);
1279 return Self {
1280 vector: Full(right),
1281 };
1282 }
1283
1284 local_index -= tree.inner_b.len();
1285
1286 let ob2 = SharedPointer::make_mut(&mut tree.outer_b).split_off(local_index);
1287 tree.length = index;
1288 Self {
1289 vector: Single(SharedPointer::new(ob2)),
1290 }
1291 }
1292 }
1293 }
1294
1295 #[must_use]
1300 pub fn skip(&self, count: usize) -> Self {
1301 match count {
1302 0 => self.clone(),
1303 count if count >= self.len() => Self::new(),
1304 count => {
1305 self.clone().split_off(count)
1307 }
1308 }
1309 }
1310
1311 #[must_use]
1316 pub fn take(&self, count: usize) -> Self {
1317 let mut left = self.clone();
1319 let _ = left.split_off(count);
1320 left
1321 }
1322
1323 pub fn truncate(&mut self, len: usize) {
1330 if len < self.len() {
1331 let _ = self.split_off(len);
1333 }
1334 }
1335
1336 #[must_use]
1344 pub fn slice<R>(&mut self, range: R) -> Self
1345 where
1346 R: RangeBounds<usize>,
1347 {
1348 let r = to_range(&range, self.len());
1349 if r.start >= r.end || r.start >= self.len() {
1350 return GenericVector::new();
1351 }
1352 let mut middle = self.split_off(r.start);
1353 let right = middle.split_off(r.end - r.start);
1354 self.append(right);
1355 middle
1356 }
1357
1358 pub fn insert(&mut self, index: usize, value: A) {
1376 if index == 0 {
1377 return self.push_front(value);
1378 }
1379 if index == self.len() {
1380 return self.push_back(value);
1381 }
1382 assert!(index < self.len());
1383 if matches!(&self.vector, Inline(_)) && self.needs_promotion() {
1384 self.promote_inline();
1385 }
1386 match &mut self.vector {
1387 Inline(chunk) => {
1388 chunk.insert(index, value);
1389 }
1390 Single(chunk) if chunk.len() < CHUNK_SIZE => {
1391 SharedPointer::make_mut(chunk).insert(index, value)
1392 }
1393 _ => {
1395 let right = self.split_off(index);
1396 self.push_back(value);
1397 self.append(right);
1398 }
1399 }
1400 }
1401
1402 pub fn remove(&mut self, index: usize) -> A {
1419 assert!(index < self.len());
1420 match &mut self.vector {
1421 Inline(chunk) => chunk.remove(index).unwrap(),
1422 Single(chunk) => SharedPointer::make_mut(chunk).remove(index),
1423 _ => {
1424 if index == 0 {
1425 return self.pop_front().unwrap();
1426 }
1427 if index == self.len() - 1 {
1428 return self.pop_back().unwrap();
1429 }
1430 let mut right = self.split_off(index);
1432 let value = right.pop_front().unwrap();
1433 self.append(right);
1434 value
1435 }
1436 }
1437 }
1438
1439 pub fn insert_ord(&mut self, item: A)
1455 where
1456 A: Ord,
1457 {
1458 match self.binary_search(&item) {
1459 Ok(index) => self.insert(index, item),
1460 Err(index) => self.insert(index, item),
1461 }
1462 }
1463
1464 pub fn insert_ord_by<F>(&mut self, item: A, mut f: F)
1491 where
1492 A: Ord,
1493 F: FnMut(&A, &A) -> Ordering,
1494 {
1495 match self.binary_search_by(|scan_item| f(scan_item, &item)) {
1496 Ok(idx) | Err(idx) => self.insert(idx, item),
1497 }
1498 }
1499
1500 pub fn insert_ord_by_key<B, F>(&mut self, item: A, mut f: F)
1536 where
1537 B: Ord,
1538 F: FnMut(&A) -> B,
1539 {
1540 match self.binary_search_by_key(&f(&item), |scan_item| f(scan_item)) {
1541 Ok(idx) | Err(idx) => self.insert(idx, item),
1542 }
1543 }
1544
1545 pub fn sort(&mut self)
1558 where
1559 A: Ord,
1560 {
1561 self.sort_by(Ord::cmp)
1562 }
1563
1564 pub fn sort_by<F>(&mut self, cmp: F)
1577 where
1578 F: Fn(&A, &A) -> Ordering,
1579 {
1580 let len = self.len();
1581 if len > 1 {
1582 sort::quicksort(self.focus_mut(), &cmp);
1583 }
1584 }
1585}
1586
1587impl<A, P: SharedPointerKind> RRB<A, P> {
1590 fn new() -> Self {
1591 RRB {
1592 length: 0,
1593 middle_level: 0,
1594 outer_f: SharedPointer::default(),
1595 inner_f: SharedPointer::default(),
1596 middle: SharedPointer::new(Node::new()),
1597 inner_b: SharedPointer::default(),
1598 outer_b: SharedPointer::default(),
1599 }
1600 }
1601
1602 #[cfg(any(test, feature = "debug"))]
1603 fn assert_invariants(&self) {
1604 let ml = self.middle.assert_invariants(self.middle_level);
1605 assert_eq!(
1606 self.length,
1607 self.outer_f.len() + self.inner_f.len() + ml + self.inner_b.len() + self.outer_b.len()
1608 );
1609 }
1610}
1611
1612impl<A: Clone, P: SharedPointerKind> RRB<A, P> {
1613 fn prune(&mut self) {
1614 if self.middle.is_empty() {
1615 self.middle = SharedPointer::new(Node::new());
1616 self.middle_level = 0;
1617 } else {
1618 while self.middle_level > 0 && self.middle.is_single() {
1619 self.middle = SharedPointer::new(self.middle.first_child().clone());
1621 self.middle_level -= 1;
1622 }
1623 }
1624 }
1625
1626 fn pop_front(&mut self) -> Option<A> {
1627 if self.length == 0 {
1628 return None;
1629 }
1630 if self.outer_f.is_empty() {
1631 if self.inner_f.is_empty() {
1632 if self.middle.is_empty() {
1633 if self.inner_b.is_empty() {
1634 swap(&mut self.outer_f, &mut self.outer_b);
1635 } else {
1636 swap(&mut self.outer_f, &mut self.inner_b);
1637 }
1638 } else {
1639 self.outer_f = self.pop_middle(Side::Left).unwrap();
1640 }
1641 } else {
1642 swap(&mut self.outer_f, &mut self.inner_f);
1643 }
1644 }
1645 self.length -= 1;
1646 let outer_f = SharedPointer::make_mut(&mut self.outer_f);
1647 Some(outer_f.pop_front())
1648 }
1649
1650 fn pop_back(&mut self) -> Option<A> {
1651 if self.length == 0 {
1652 return None;
1653 }
1654 if self.outer_b.is_empty() {
1655 if self.inner_b.is_empty() {
1656 if self.middle.is_empty() {
1657 if self.inner_f.is_empty() {
1658 swap(&mut self.outer_b, &mut self.outer_f);
1659 } else {
1660 swap(&mut self.outer_b, &mut self.inner_f);
1661 }
1662 } else {
1663 self.outer_b = self.pop_middle(Side::Right).unwrap();
1664 }
1665 } else {
1666 swap(&mut self.outer_b, &mut self.inner_b);
1667 }
1668 }
1669 self.length -= 1;
1670 let outer_b = SharedPointer::make_mut(&mut self.outer_b);
1671 Some(outer_b.pop_back())
1672 }
1673
1674 fn push_front(&mut self, value: A) {
1675 if self.outer_f.is_full() {
1676 swap(&mut self.outer_f, &mut self.inner_f);
1677 if !self.outer_f.is_empty() {
1678 let mut chunk = SharedPointer::new(Chunk::new());
1679 swap(&mut chunk, &mut self.outer_f);
1680 self.push_middle(Side::Left, chunk);
1681 }
1682 }
1683 self.length = self.length.checked_add(1).expect("Vector length overflow");
1684 let outer_f = SharedPointer::make_mut(&mut self.outer_f);
1685 outer_f.push_front(value)
1686 }
1687
1688 fn push_back(&mut self, value: A) {
1689 if self.outer_b.is_full() {
1690 swap(&mut self.outer_b, &mut self.inner_b);
1691 if !self.outer_b.is_empty() {
1692 let mut chunk = SharedPointer::new(Chunk::new());
1693 swap(&mut chunk, &mut self.outer_b);
1694 self.push_middle(Side::Right, chunk);
1695 }
1696 }
1697 self.length = self.length.checked_add(1).expect("Vector length overflow");
1698 let outer_b = SharedPointer::make_mut(&mut self.outer_b);
1699 outer_b.push_back(value)
1700 }
1701
1702 fn push_middle(&mut self, side: Side, chunk: SharedPointer<Chunk<A>, P>) {
1703 if chunk.is_empty() {
1704 return;
1705 }
1706 let new_middle = {
1707 let middle = SharedPointer::make_mut(&mut self.middle);
1708 match middle.push_chunk(self.middle_level, side, chunk) {
1709 PushResult::Done => return,
1710 PushResult::Full(chunk, _num_drained) => SharedPointer::new({
1711 match side {
1712 Side::Left => Node::from_chunk(self.middle_level, chunk)
1713 .join_branches(middle.clone(), self.middle_level),
1714 Side::Right => middle.clone().join_branches(
1715 Node::from_chunk(self.middle_level, chunk),
1716 self.middle_level,
1717 ),
1718 }
1719 }),
1720 }
1721 };
1722 self.middle_level += 1;
1723 self.middle = new_middle;
1724 }
1725
1726 fn pop_middle(&mut self, side: Side) -> Option<SharedPointer<Chunk<A>, P>> {
1727 let chunk = {
1728 let middle = SharedPointer::make_mut(&mut self.middle);
1729 match middle.pop_chunk(self.middle_level, side) {
1730 PopResult::Empty => return None,
1731 PopResult::Done(chunk) => chunk,
1732 PopResult::Drained(chunk) => {
1733 middle.clear_node();
1734 self.middle_level = 0;
1735 chunk
1736 }
1737 }
1738 };
1739 Some(chunk)
1740 }
1741}
1742
1743#[inline]
1744fn replace_shared_pointer<A: Default, P: SharedPointerKind>(
1745 dest: &mut SharedPointer<A, P>,
1746) -> SharedPointer<A, P> {
1747 std::mem::take(dest)
1748}
1749
1750impl<A, P: SharedPointerKind> Default for GenericVector<A, P> {
1753 fn default() -> Self {
1754 Self::new()
1755 }
1756}
1757
1758impl<A: Clone, P: SharedPointerKind> Clone for GenericVector<A, P> {
1759 fn clone(&self) -> Self {
1763 Self {
1764 vector: match &self.vector {
1765 Inline(chunk) => Inline(chunk.clone()),
1766 Single(chunk) => Single(chunk.clone()),
1767 Full(tree) => Full(tree.clone()),
1768 },
1769 }
1770 }
1771}
1772
1773impl<A: Debug, P: SharedPointerKind> Debug for GenericVector<A, P> {
1774 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
1775 f.debug_list().entries(self.iter()).finish()
1776 }
1785}
1786
1787impl<A: PartialEq, P: SharedPointerKind> PartialEq for GenericVector<A, P> {
1788 fn eq(&self, other: &Self) -> bool {
1789 self.len() == other.len() && self.iter().eq(other.iter())
1790 }
1791}
1792
1793impl<A: Eq, P: SharedPointerKind> Eq for GenericVector<A, P> {}
1794
1795impl<A: PartialOrd, P: SharedPointerKind> PartialOrd for GenericVector<A, P> {
1796 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1797 self.iter().partial_cmp(other.iter())
1798 }
1799}
1800
1801impl<A: Ord, P: SharedPointerKind> Ord for GenericVector<A, P> {
1802 fn cmp(&self, other: &Self) -> Ordering {
1803 self.iter().cmp(other.iter())
1804 }
1805}
1806
1807impl<A: Hash, P: SharedPointerKind> Hash for GenericVector<A, P> {
1808 fn hash<H: Hasher>(&self, state: &mut H) {
1809 for i in self {
1810 i.hash(state)
1811 }
1812 }
1813}
1814
1815impl<A: Clone, P: SharedPointerKind> Sum for GenericVector<A, P> {
1816 fn sum<I>(it: I) -> Self
1817 where
1818 I: Iterator<Item = Self>,
1819 {
1820 it.fold(Self::new(), |a, b| a + b)
1821 }
1822}
1823
1824impl<A: Clone, P: SharedPointerKind> Add for GenericVector<A, P> {
1825 type Output = GenericVector<A, P>;
1826
1827 fn add(mut self, other: Self) -> Self::Output {
1831 self.append(other);
1832 self
1833 }
1834}
1835
1836impl<'a, A: Clone, P: SharedPointerKind> Add for &'a GenericVector<A, P> {
1837 type Output = GenericVector<A, P>;
1838
1839 fn add(self, other: Self) -> Self::Output {
1843 let mut out = self.clone();
1844 out.append(other.clone());
1845 out
1846 }
1847}
1848
1849impl<A: Clone, P: SharedPointerKind> Extend<A> for GenericVector<A, P> {
1850 fn extend<I>(&mut self, iter: I)
1854 where
1855 I: IntoIterator<Item = A>,
1856 {
1857 for item in iter {
1858 self.push_back(item)
1859 }
1860 }
1861}
1862
1863impl<A, P: SharedPointerKind> Index<usize> for GenericVector<A, P> {
1864 type Output = A;
1865 fn index(&self, index: usize) -> &Self::Output {
1869 match self.get(index) {
1870 Some(value) => value,
1871 None => panic!(
1872 "Vector::index: index out of bounds: {} < {}",
1873 index,
1874 self.len()
1875 ),
1876 }
1877 }
1878}
1879
1880impl<A: Clone, P: SharedPointerKind> IndexMut<usize> for GenericVector<A, P> {
1881 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1886 match self.get_mut(index) {
1887 Some(value) => value,
1888 None => panic!("Vector::index_mut: index out of bounds"),
1889 }
1890 }
1891}
1892
1893impl<'a, A, P: SharedPointerKind> IntoIterator for &'a GenericVector<A, P> {
1896 type Item = &'a A;
1897 type IntoIter = Iter<'a, A, P>;
1898 fn into_iter(self) -> Self::IntoIter {
1899 self.iter()
1900 }
1901}
1902
1903impl<'a, A: Clone, P: SharedPointerKind> IntoIterator for &'a mut GenericVector<A, P> {
1904 type Item = &'a mut A;
1905 type IntoIter = IterMut<'a, A, P>;
1906 fn into_iter(self) -> Self::IntoIter {
1907 self.iter_mut()
1908 }
1909}
1910
1911impl<A: Clone, P: SharedPointerKind> IntoIterator for GenericVector<A, P> {
1912 type Item = A;
1913 type IntoIter = ConsumingIter<A, P>;
1914 fn into_iter(self) -> Self::IntoIter {
1915 ConsumingIter::new(self)
1916 }
1917}
1918
1919impl<A: Clone, P: SharedPointerKind> FromIterator<A> for GenericVector<A, P> {
1920 fn from_iter<I>(iter: I) -> Self
1924 where
1925 I: IntoIterator<Item = A>,
1926 {
1927 let mut seq = Self::new();
1928 for item in iter {
1929 seq.push_back(item)
1930 }
1931 seq
1932 }
1933}
1934
1935impl<'s, 'a, A, OA, P1, P2> From<&'s GenericVector<&'a A, P2>> for GenericVector<OA, P1>
1936where
1937 A: ToOwned<Owned = OA>,
1938 OA: Borrow<A> + Clone,
1939 P1: SharedPointerKind,
1940 P2: SharedPointerKind,
1941{
1942 fn from(vec: &GenericVector<&A, P2>) -> Self {
1943 vec.iter().map(|a| (*a).to_owned()).collect()
1944 }
1945}
1946
1947impl<A, const N: usize, P: SharedPointerKind> From<[A; N]> for GenericVector<A, P>
1948where
1949 A: Clone,
1950{
1951 fn from(arr: [A; N]) -> Self {
1952 IntoIterator::into_iter(arr).collect()
1953 }
1954}
1955
1956impl<'a, A: Clone, P: SharedPointerKind> From<&'a [A]> for GenericVector<A, P> {
1957 fn from(slice: &[A]) -> Self {
1958 slice.iter().cloned().collect()
1959 }
1960}
1961
1962impl<A: Clone, P: SharedPointerKind> From<Vec<A>> for GenericVector<A, P> {
1963 fn from(vec: Vec<A>) -> Self {
1969 vec.into_iter().collect()
1970 }
1971}
1972
1973impl<'a, A: Clone, P: SharedPointerKind> From<&'a Vec<A>> for GenericVector<A, P> {
1974 fn from(vec: &Vec<A>) -> Self {
1980 vec.iter().cloned().collect()
1981 }
1982}
1983
1984#[derive(Clone)]
1994pub struct Iter<'a, A, P: SharedPointerKind> {
1995 focus: Focus<'a, A, P>,
1996 front_index: usize,
1997 back_index: usize,
1998}
1999
2000impl<'a, A, P: SharedPointerKind> Iter<'a, A, P> {
2001 fn new(seq: &'a GenericVector<A, P>) -> Self {
2002 Iter {
2003 focus: seq.focus(),
2004 front_index: 0,
2005 back_index: seq.len(),
2006 }
2007 }
2008
2009 fn from_focus(focus: Focus<'a, A, P>) -> Self {
2010 Iter {
2011 front_index: 0,
2012 back_index: focus.len(),
2013 focus,
2014 }
2015 }
2016}
2017
2018impl<'a, A, P: SharedPointerKind + 'a> Iterator for Iter<'a, A, P> {
2019 type Item = &'a A;
2020
2021 fn next(&mut self) -> Option<Self::Item> {
2025 if self.front_index >= self.back_index {
2026 return None;
2027 }
2028 let focus: &'a mut Focus<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2029 let value = focus.get(self.front_index);
2030 self.front_index += 1;
2031 value
2032 }
2033
2034 fn size_hint(&self) -> (usize, Option<usize>) {
2035 let remaining = self.back_index - self.front_index;
2036 (remaining, Some(remaining))
2037 }
2038}
2039
2040impl<'a, A, P: SharedPointerKind + 'a> DoubleEndedIterator for Iter<'a, A, P> {
2041 fn next_back(&mut self) -> Option<Self::Item> {
2045 if self.front_index >= self.back_index {
2046 return None;
2047 }
2048 self.back_index -= 1;
2049 let focus: &'a mut Focus<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2050 focus.get(self.back_index)
2051 }
2052}
2053
2054impl<'a, A, P: SharedPointerKind + 'a> ExactSizeIterator for Iter<'a, A, P> {}
2055
2056impl<'a, A, P: SharedPointerKind + 'a> FusedIterator for Iter<'a, A, P> {}
2057
2058pub struct IterMut<'a, A, P: SharedPointerKind> {
2064 focus: FocusMut<'a, A, P>,
2065 front_index: usize,
2066 back_index: usize,
2067}
2068
2069impl<'a, A, P: SharedPointerKind> IterMut<'a, A, P> {
2070 fn from_focus(focus: FocusMut<'a, A, P>) -> Self {
2071 IterMut {
2072 front_index: 0,
2073 back_index: focus.len(),
2074 focus,
2075 }
2076 }
2077}
2078
2079impl<'a, A: Clone, P: SharedPointerKind> IterMut<'a, A, P> {
2080 fn new(seq: &'a mut GenericVector<A, P>) -> Self {
2081 let focus = seq.focus_mut();
2082 let len = focus.len();
2083 IterMut {
2084 focus,
2085 front_index: 0,
2086 back_index: len,
2087 }
2088 }
2089}
2090
2091impl<'a, A, P: SharedPointerKind> Iterator for IterMut<'a, A, P>
2092where
2093 A: 'a + Clone,
2094{
2095 type Item = &'a mut A;
2096
2097 fn next(&mut self) -> Option<Self::Item> {
2101 if self.front_index >= self.back_index {
2102 return None;
2103 }
2104 let focus: &'a mut FocusMut<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2105 let value = focus.get_mut(self.front_index);
2106 self.front_index += 1;
2107 value
2108 }
2109
2110 fn size_hint(&self) -> (usize, Option<usize>) {
2111 let remaining = self.back_index - self.front_index;
2112 (remaining, Some(remaining))
2113 }
2114}
2115
2116impl<'a, A, P: SharedPointerKind> DoubleEndedIterator for IterMut<'a, A, P>
2117where
2118 A: 'a + Clone,
2119{
2120 fn next_back(&mut self) -> Option<Self::Item> {
2124 if self.front_index >= self.back_index {
2125 return None;
2126 }
2127 self.back_index -= 1;
2128 let focus: &'a mut FocusMut<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2129 focus.get_mut(self.back_index)
2130 }
2131}
2132
2133impl<'a, A: Clone, P: SharedPointerKind> ExactSizeIterator for IterMut<'a, A, P> {}
2134
2135impl<'a, A: Clone, P: SharedPointerKind> FusedIterator for IterMut<'a, A, P> {}
2136
2137pub struct ConsumingIter<A, P: SharedPointerKind> {
2139 vector: GenericVector<A, P>,
2140}
2141
2142impl<A, P: SharedPointerKind> ConsumingIter<A, P> {
2143 fn new(vector: GenericVector<A, P>) -> Self {
2144 Self { vector }
2145 }
2146}
2147
2148impl<A: Clone, P: SharedPointerKind> Iterator for ConsumingIter<A, P> {
2149 type Item = A;
2150
2151 fn next(&mut self) -> Option<Self::Item> {
2155 self.vector.pop_front()
2156 }
2157
2158 fn size_hint(&self) -> (usize, Option<usize>) {
2159 let len = self.vector.len();
2160 (len, Some(len))
2161 }
2162}
2163
2164impl<A: Clone, P: SharedPointerKind> DoubleEndedIterator for ConsumingIter<A, P> {
2165 fn next_back(&mut self) -> Option<Self::Item> {
2169 self.vector.pop_back()
2170 }
2171}
2172
2173impl<A: Clone, P: SharedPointerKind> ExactSizeIterator for ConsumingIter<A, P> {}
2174
2175impl<A: Clone, P: SharedPointerKind> FusedIterator for ConsumingIter<A, P> {}
2176
2177pub struct Chunks<'a, A, P: SharedPointerKind> {
2183 focus: Focus<'a, A, P>,
2184 front_index: usize,
2185 back_index: usize,
2186}
2187
2188impl<'a, A, P: SharedPointerKind> Chunks<'a, A, P> {
2189 fn new(seq: &'a GenericVector<A, P>) -> Self {
2190 Chunks {
2191 focus: seq.focus(),
2192 front_index: 0,
2193 back_index: seq.len(),
2194 }
2195 }
2196}
2197
2198impl<'a, A, P: SharedPointerKind + 'a> Iterator for Chunks<'a, A, P> {
2199 type Item = &'a [A];
2200
2201 fn next(&mut self) -> Option<Self::Item> {
2205 if self.front_index >= self.back_index {
2206 return None;
2207 }
2208 let focus: &'a mut Focus<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2209 let (range, value) = focus.chunk_at(self.front_index);
2210 self.front_index = range.end;
2211 Some(value)
2212 }
2213}
2214
2215impl<'a, A, P: SharedPointerKind + 'a> DoubleEndedIterator for Chunks<'a, A, P> {
2216 fn next_back(&mut self) -> Option<Self::Item> {
2220 if self.front_index >= self.back_index {
2221 return None;
2222 }
2223 self.back_index -= 1;
2224 let focus: &'a mut Focus<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2225 let (range, value) = focus.chunk_at(self.back_index);
2226 self.back_index = range.start;
2227 Some(value)
2228 }
2229}
2230
2231impl<'a, A, P: SharedPointerKind + 'a> FusedIterator for Chunks<'a, A, P> {}
2232
2233pub struct ChunksMut<'a, A, P: SharedPointerKind> {
2239 focus: FocusMut<'a, A, P>,
2240 front_index: usize,
2241 back_index: usize,
2242}
2243
2244impl<'a, A: Clone, P: SharedPointerKind> ChunksMut<'a, A, P> {
2245 fn new(seq: &'a mut GenericVector<A, P>) -> Self {
2246 let len = seq.len();
2247 ChunksMut {
2248 focus: seq.focus_mut(),
2249 front_index: 0,
2250 back_index: len,
2251 }
2252 }
2253}
2254
2255impl<'a, A: Clone, P: SharedPointerKind> Iterator for ChunksMut<'a, A, P> {
2256 type Item = &'a mut [A];
2257
2258 fn next(&mut self) -> Option<Self::Item> {
2262 if self.front_index >= self.back_index {
2263 return None;
2264 }
2265 let focus: &'a mut FocusMut<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2266 let (range, value) = focus.chunk_at(self.front_index);
2267 self.front_index = range.end;
2268 Some(value)
2269 }
2270}
2271
2272impl<'a, A: Clone, P: SharedPointerKind> DoubleEndedIterator for ChunksMut<'a, A, P> {
2273 fn next_back(&mut self) -> Option<Self::Item> {
2277 if self.front_index >= self.back_index {
2278 return None;
2279 }
2280 self.back_index -= 1;
2281 let focus: &'a mut FocusMut<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2282 let (range, value) = focus.chunk_at(self.back_index);
2283 self.back_index = range.start;
2284 Some(value)
2285 }
2286}
2287
2288impl<'a, A: Clone, P: SharedPointerKind> FusedIterator for ChunksMut<'a, A, P> {}
2289
2290#[cfg(any(test, feature = "proptest"))]
2292#[doc(hidden)]
2293pub mod proptest {
2294 #[deprecated(
2295 since = "14.3.0",
2296 note = "proptest strategies have moved to imbl::proptest"
2297 )]
2298 pub use crate::proptest::vector;
2299}
2300
2301#[cfg(test)]
2304mod test {
2305 use super::*;
2306 use crate::proptest::vector;
2307 use ::proptest::collection::vec;
2308 use ::proptest::num::{i32, usize};
2309 use ::proptest::proptest;
2310 use static_assertions::{assert_impl_all, assert_not_impl_any};
2311
2312 assert_impl_all!(Vector<i32>: Send, Sync);
2313 assert_not_impl_any!(Vector<*const i32>: Send, Sync);
2314 assert_covariant!(Vector<T> in T);
2315
2316 #[test]
2317 fn macro_allows_trailing_comma() {
2318 let vec1 = vector![1, 2, 3];
2319 let vec2 = vector![1, 2, 3,];
2320 assert_eq!(vec1, vec2);
2321 }
2322
2323 #[test]
2324 fn indexing() {
2325 let mut vec: Vector<_> = vector![0, 1, 2, 3, 4, 5];
2326 vec.push_front(0);
2327 assert_eq!(0, *vec.get(0).unwrap());
2328 assert_eq!(0, vec[0]);
2329 }
2330
2331 #[test]
2332 fn test_vector_focus_split_at() {
2333 for (data, split_points) in [
2334 (0..0, vec![0]),
2335 (0..3, vec![0, 1, 2, 3]),
2336 (0..128, vec![0, 1, 64, 127, 128]),
2337 #[cfg(not(miri))]
2338 (0..100_000, vec![0, 1, 50_000, 99_999, 100_000]),
2339 ] {
2340 let imbl_vec = Vector::from_iter(data.clone());
2341 let vec = Vec::from_iter(data);
2342 let focus = imbl_vec.focus();
2343 for split_point in split_points {
2344 let (left, right) = focus.clone().split_at(split_point);
2345 let (expected_left, expected_right) = vec.split_at(split_point);
2346 assert_eq!(
2347 left.clone().into_iter().copied().collect::<Vec<_>>(),
2348 expected_left
2349 );
2350 assert_eq!(
2351 right.clone().into_iter().copied().collect::<Vec<_>>(),
2352 expected_right
2353 );
2354 }
2355 }
2356 }
2357
2358 #[test]
2359 #[should_panic(expected = "range out of bounds")]
2360 fn test_vector_focus_narrow_out_of_range() {
2361 let vec = Vector::from_iter(0..100);
2362 _ = vec.focus().narrow(..1000);
2363 }
2364
2365 #[test]
2366 fn test_vector_focus_narrow() {
2367 macro_rules! testcase {
2368 ($data:expr, $range:expr) => {{
2369 let imbl_vector = Vector::<_>::from_iter($data);
2370 let vec = Vec::from_iter($data);
2371 let focus = imbl_vector.focus();
2372 assert_eq!(
2373 focus
2374 .narrow($range)
2375 .into_iter()
2376 .copied()
2377 .collect::<Vec<_>>(),
2378 vec[$range]
2379 );
2380 }};
2381 }
2382 for len in 0..=3 {
2384 testcase!(0..len, ..);
2385 for start in 0..=len {
2386 testcase!(0..len, start..);
2387 testcase!(0..len, ..start);
2388 for end in start..=len {
2389 testcase!(0..len, start..end);
2390 }
2391 }
2392 }
2393 }
2394
2395 #[cfg_attr(miri, ignore)]
2396 #[test]
2397 fn large_vector_focus() {
2398 let input = Vector::from_iter(0..100_000);
2399 let vec = input.clone();
2400 let mut sum: i64 = 0;
2401 let mut focus = vec.focus();
2402 for i in 0..input.len() {
2403 sum += *focus.index(i);
2404 }
2405 let expected: i64 = (0..100_000).sum();
2406 assert_eq!(expected, sum);
2407 }
2408
2409 #[cfg_attr(miri, ignore)]
2410 #[test]
2411 fn large_vector_focus_mut() {
2412 let input = Vector::from_iter(0..100_000);
2413 let mut vec = input.clone();
2414 {
2415 let mut focus = vec.focus_mut();
2416 for i in 0..input.len() {
2417 let p = focus.index_mut(i);
2418 *p += 1;
2419 }
2420 }
2421 let expected: Vector<_> = input.into_iter().map(|i| i + 1).collect();
2422 assert_eq!(expected, vec);
2423 }
2424
2425 #[cfg_attr(miri, ignore)]
2426 #[test]
2427 fn issue_55_fwd() {
2428 let mut l = Vector::new();
2429 for i in 0..4098 {
2430 l.append(GenericVector::unit(i));
2431 }
2432 l.append(GenericVector::unit(4098));
2433 assert_eq!(Some(&4097), l.get(4097));
2434 assert_eq!(Some(&4096), l.get(4096));
2435 }
2436
2437 #[cfg_attr(miri, ignore)]
2438 #[test]
2439 fn issue_55_back() {
2440 let mut l = Vector::unit(0);
2441 for i in 0..4099 {
2442 let mut tmp = GenericVector::unit(i + 1);
2443 tmp.append(l);
2444 l = tmp;
2445 }
2446 assert_eq!(Some(&4098), l.get(1));
2447 assert_eq!(Some(&4097), l.get(2));
2448 let len = l.len();
2449 let _ = l.slice(2..len);
2450 }
2451
2452 #[test]
2453 fn issue_55_append() {
2454 let mut vec1 = Vector::from_iter(0..92);
2455 let vec2 = GenericVector::from_iter(0..165);
2456 vec1.append(vec2);
2457 }
2458
2459 #[test]
2460 fn issue_70() {
2461 if CHUNK_SIZE != 64 {
2463 return;
2464 }
2465 let mut x = Vector::new();
2466 for _ in 0..262 {
2467 x.push_back(0);
2468 }
2469 for _ in 0..97 {
2470 x.pop_front();
2471 }
2472 for &offset in &[160, 163, 160] {
2473 x.remove(offset);
2474 }
2475 for _ in 0..64 {
2476 x.push_back(0);
2477 }
2478 match x.vector {
2482 VectorInner::Full(ref tree) => {
2483 assert_eq!(129, tree.middle.len());
2484 assert_eq!(3, tree.middle.number_of_children());
2485 }
2486 _ => unreachable!(),
2487 }
2488 x.push_back(0);
2489 match x.vector {
2490 VectorInner::Full(ref tree) => {
2491 assert_eq!(131, tree.middle.len());
2492 assert_eq!(3, tree.middle.number_of_children())
2493 }
2494 _ => unreachable!(),
2495 }
2496 for _ in 0..64 {
2497 x.push_back(0);
2498 }
2499 for _ in x.iter() {}
2500 }
2501
2502 #[cfg_attr(miri, ignore)]
2503 #[test]
2504 fn issue_67() {
2505 let mut l = Vector::unit(4100);
2506 for i in (0..4099).rev() {
2507 let mut tmp = GenericVector::unit(i);
2508 tmp.append(l);
2509 l = tmp;
2510 }
2511 assert_eq!(4100, l.len());
2512 let len = l.len();
2513 let tail = l.slice(1..len);
2514 assert_eq!(1, l.len());
2515 assert_eq!(4099, tail.len());
2516 assert_eq!(Some(&0), l.get(0));
2517 assert_eq!(Some(&1), tail.get(0));
2518 }
2519
2520 #[test]
2521 fn issue_74_simple_size() {
2522 use crate::nodes::rrb::NODE_SIZE;
2523 let mut x = Vector::new();
2524 for _ in 0..(CHUNK_SIZE
2525 * (
2526 1 + (2 * NODE_SIZE) + 1 + 1
2530 ))
2532 {
2533 x.push_back(0u32);
2534 }
2535 let middle_first_node_start = CHUNK_SIZE;
2536 let middle_second_node_start = middle_first_node_start + NODE_SIZE * CHUNK_SIZE;
2537 x.remove(middle_second_node_start);
2539 x.push_back(0u32);
2543 match x.vector {
2544 VectorInner::Full(tree) => {
2545 if CHUNK_SIZE == 64 {
2546 assert_eq!(3, tree.middle.number_of_children());
2547 }
2548 assert_eq!(
2549 2 * NODE_SIZE * CHUNK_SIZE + CHUNK_SIZE - 1,
2550 tree.middle.len()
2551 );
2552 }
2553 _ => unreachable!(),
2554 }
2555 }
2556
2557 #[test]
2558 fn issue_77() {
2559 let mut x = Vector::new();
2560 for _ in 0..44 {
2561 x.push_back(0);
2562 }
2563 for _ in 0..20 {
2564 x.insert(0, 0);
2565 }
2566 x.insert(1, 0);
2567 for _ in 0..441 {
2568 x.push_back(0);
2569 }
2570 for _ in 0..58 {
2571 x.insert(0, 0);
2572 }
2573 x.insert(514, 0);
2574 for _ in 0..73 {
2575 x.push_back(0);
2576 }
2577 for _ in 0..10 {
2578 x.insert(0, 0);
2579 }
2580 x.insert(514, 0);
2581 }
2582
2583 #[cfg_attr(miri, ignore)]
2584 #[test]
2585 fn issue_105() {
2586 let mut v = Vector::<_>::new();
2587
2588 for i in 0..270_000 {
2589 v.push_front(i);
2590 }
2591
2592 while !v.is_empty() {
2593 v = v.take(v.len() - 1);
2594 }
2595 }
2596
2597 #[cfg_attr(miri, ignore)]
2598 #[test]
2599 fn issue_107_split_off_causes_overflow() {
2600 let mut vec = Vector::from_iter(0..4289);
2601 let mut control = Vec::from_iter(0..4289);
2602 let chunk = 64;
2603
2604 while vec.len() >= chunk {
2605 vec = vec.split_off(chunk);
2606 control = control.split_off(chunk);
2607 assert_eq!(vec.len(), control.len());
2608 assert_eq!(control, vec.iter().cloned().collect::<Vec<_>>());
2609 }
2610 }
2611
2612 #[cfg_attr(miri, ignore)]
2613 #[test]
2614 fn collect_crash() {
2615 let _vector: Vector<i32> = (0..5953).collect();
2616 }
2618
2619 #[test]
2620 fn issue_116() {
2621 let vec = Vector::from_iter(0..300);
2622 let rev_vec: Vector<_> = vec.clone().into_iter().rev().collect();
2623 assert_eq!(vec.len(), rev_vec.len());
2624 }
2625
2626 #[test]
2627 fn issue_131() {
2628 let smol = std::iter::repeat(42).take(64).collect::<Vector<_>>();
2629 let mut smol2 = smol.clone();
2630 assert!(smol.ptr_eq(&smol2));
2631 smol2.set(63, 420);
2632 assert!(!smol.ptr_eq(&smol2));
2633
2634 let huge = std::iter::repeat(42).take(65).collect::<Vector<_>>();
2635 let mut huge2 = huge.clone();
2636 assert!(huge.ptr_eq(&huge2));
2637 huge2.set(63, 420);
2638 assert!(!huge.ptr_eq(&huge2));
2639 }
2640
2641 #[test]
2642 fn ptr_eq() {
2643 const MAX: usize = if cfg!(miri) { 64 } else { 256 };
2644 for len in 32..MAX {
2645 let input = std::iter::repeat(42).take(len).collect::<Vector<_>>();
2646 let mut inp2 = input.clone();
2647 assert!(input.ptr_eq(&inp2));
2648 inp2.set(len - 1, 98);
2649 assert_ne!(inp2.get(len - 1), input.get(len - 1));
2650 assert!(!input.ptr_eq(&inp2));
2651 }
2652 }
2653
2654 #[test]
2655 fn full_retain() {
2656 let mut a = Vector::from_iter(0..128);
2657 let b = Vector::from_iter(128..256);
2658 a.append(b);
2659 assert!(matches!(a.vector, Full(_)));
2660 a.retain(|i| *i % 2 == 0);
2661 assert_eq!(a.len(), 128);
2662 }
2663
2664 proptest! {
2665 #[cfg_attr(miri, ignore)]
2669 #[test]
2670 fn iter(ref vec in vec(i32::ANY, 0..1000)) {
2671 let seq = Vector::from_iter(vec.iter().cloned());
2672 for (index, item) in seq.iter().enumerate() {
2673 assert_eq!(&vec[index], item);
2674 }
2675 assert_eq!(vec.len(), seq.len());
2676 }
2677
2678 #[cfg_attr(miri, ignore)]
2679 #[test]
2680 fn push_front_mut(ref input in vec(i32::ANY, 0..1000)) {
2681 let mut vector = Vector::new();
2682 for (count, value) in input.iter().cloned().enumerate() {
2683 assert_eq!(count, vector.len());
2684 vector.push_front(value);
2685 assert_eq!(count + 1, vector.len());
2686 }
2687 let input2 = Vec::from_iter(input.iter().rev().cloned());
2688 assert_eq!(input2, Vec::from_iter(vector.iter().cloned()));
2689 }
2690
2691 #[cfg_attr(miri, ignore)]
2692 #[test]
2693 fn push_back_mut(ref input in vec(i32::ANY, 0..1000)) {
2694 let mut vector = Vector::new();
2695 for (count, value) in input.iter().cloned().enumerate() {
2696 assert_eq!(count, vector.len());
2697 vector.push_back(value);
2698 assert_eq!(count + 1, vector.len());
2699 }
2700 assert_eq!(input, &Vec::from_iter(vector.iter().cloned()));
2701 }
2702
2703 #[cfg_attr(miri, ignore)]
2704 #[test]
2705 fn pop_back_mut(ref input in vec(i32::ANY, 0..1000)) {
2706 let mut vector = Vector::from_iter(input.iter().cloned());
2707 assert_eq!(input.len(), vector.len());
2708 for (index, value) in input.iter().cloned().enumerate().rev() {
2709 match vector.pop_back() {
2710 None => panic!("vector emptied unexpectedly"),
2711 Some(item) => {
2712 assert_eq!(index, vector.len());
2713 assert_eq!(value, item);
2714 }
2715 }
2716 }
2717 assert_eq!(0, vector.len());
2718 }
2719
2720 #[cfg_attr(miri, ignore)]
2721 #[test]
2722 fn pop_front_mut(ref input in vec(i32::ANY, 0..1000)) {
2723 let mut vector = Vector::from_iter(input.iter().cloned());
2724 assert_eq!(input.len(), vector.len());
2725 for (index, value) in input.iter().cloned().rev().enumerate().rev() {
2726 match vector.pop_front() {
2727 None => panic!("vector emptied unexpectedly"),
2728 Some(item) => {
2729 assert_eq!(index, vector.len());
2730 assert_eq!(value, item);
2731 }
2732 }
2733 }
2734 assert_eq!(0, vector.len());
2735 }
2736
2737 #[cfg_attr(miri, ignore)]
2758 #[test]
2759 fn skip(ref vec in vec(i32::ANY, 1..2000), count in usize::ANY) {
2760 let count = count % (vec.len() + 1);
2761 let old = Vector::from_iter(vec.iter().cloned());
2762 let new = old.skip(count);
2763 assert_eq!(old.len(), vec.len());
2764 assert_eq!(new.len(), vec.len() - count);
2765 for (index, item) in old.iter().enumerate() {
2766 assert_eq!(& vec[index], item);
2767 }
2768 for (index, item) in new.iter().enumerate() {
2769 assert_eq!(&vec[count + index], item);
2770 }
2771 }
2772
2773 #[cfg_attr(miri, ignore)]
2774 #[test]
2775 fn split_off(ref vec in vec(i32::ANY, 1..2000), split_pos in usize::ANY) {
2776 let split_index = split_pos % (vec.len() + 1);
2777 let mut left = Vector::from_iter(vec.iter().cloned());
2778 let right = left.split_off(split_index);
2779 assert_eq!(left.len(), split_index);
2780 assert_eq!(right.len(), vec.len() - split_index);
2781 for (index, item) in left.iter().enumerate() {
2782 assert_eq!(& vec[index], item);
2783 }
2784 for (index, item) in right.iter().enumerate() {
2785 assert_eq!(&vec[split_index + index], item);
2786 }
2787 }
2788
2789 #[cfg_attr(miri, ignore)]
2790 #[test]
2791 fn append(ref vec1 in vec(i32::ANY, 0..1000), ref vec2 in vec(i32::ANY, 0..1000)) {
2792 let mut seq1 = Vector::from_iter(vec1.iter().cloned());
2793 let seq2 = Vector::from_iter(vec2.iter().cloned());
2794 assert_eq!(seq1.len(), vec1.len());
2795 assert_eq!(seq2.len(), vec2.len());
2796 seq1.append(seq2);
2797 let mut vec = vec1.clone();
2798 vec.extend(vec2);
2799 assert_eq!(seq1.len(), vec.len());
2800 for (index, item) in seq1.into_iter().enumerate() {
2801 assert_eq!(vec[index], item);
2802 }
2803 }
2804
2805 #[cfg_attr(miri, ignore)]
2806 #[test]
2807 fn iter_mut(ref input in vector(i32::ANY, 0..10000)) {
2808 let mut vec = input.clone();
2809 {
2810 for p in vec.iter_mut() {
2811 *p = p.overflowing_add(1).0;
2812 }
2813 }
2814 let expected: Vector<i32> = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect();
2815 assert_eq!(expected, vec);
2816 }
2817
2818 #[cfg_attr(miri, ignore)]
2819 #[test]
2820 fn focus(ref input in vector(i32::ANY, 0..10000)) {
2821 let mut vec = input.clone();
2822 {
2823 let mut focus = vec.focus_mut();
2824 for i in 0..input.len() {
2825 let p = focus.index_mut(i);
2826 *p = p.overflowing_add(1).0;
2827 }
2828 }
2829 let expected: Vector<i32> = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect();
2830 assert_eq!(expected, vec);
2831 }
2832
2833 #[cfg_attr(miri, ignore)]
2834 #[test]
2835 fn focus_mut_split(ref input in vector(i32::ANY, 0..10000)) {
2836 let mut vec = input.clone();
2837
2838 fn split_down(focus: FocusMut<'_, i32, DefaultSharedPtr>) {
2839 let len = focus.len();
2840 if len < 8 {
2841 for p in focus {
2842 *p = p.overflowing_add(1).0;
2843 }
2844 } else {
2845 let (left, right) = focus.split_at(len / 2);
2846 split_down(left);
2847 split_down(right);
2848 }
2849 }
2850
2851 split_down(vec.focus_mut());
2852
2853 let expected: Vector<_> = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect();
2854 assert_eq!(expected, vec);
2855 }
2856
2857 #[cfg_attr(miri, ignore)]
2858 #[test]
2859 fn chunks(ref input in vector(i32::ANY, 0..10000)) {
2860 let output: Vector<_> = input.leaves().flatten().cloned().collect();
2861 assert_eq!(input, &output);
2862 let rev_in: Vector<_> = input.iter().rev().cloned().collect();
2863 let rev_out: Vector<_> = input.leaves().rev().flat_map(|c| c.iter().rev()).cloned().collect();
2864 assert_eq!(rev_in, rev_out);
2865 }
2866
2867 #[cfg_attr(miri, ignore)]
2868 #[test]
2869 fn chunks_mut(ref mut input_src in vector(i32::ANY, 0..10000)) {
2870 let mut input = input_src.clone();
2871 #[allow(clippy::map_clone)]
2872 let output: Vector<_> = input.leaves_mut().flatten().map(|v| *v).collect();
2873 assert_eq!(input, output);
2874 let rev_in: Vector<_> = input.iter().rev().cloned().collect();
2875 let rev_out: Vector<_> = input.leaves_mut().rev().flat_map(|c| c.iter().rev()).cloned().collect();
2876 assert_eq!(rev_in, rev_out);
2877 }
2878
2879 }
2908}