1use alloc::{
47 borrow::{
48 Borrow,
49 ToOwned,
50 },
51 fmt::{
52 Debug,
53 Error,
54 Formatter,
55 },
56 vec::Vec,
57};
58
59use core::{
60 cmp::Ordering,
61 hash::{
62 Hash,
63 Hasher,
64 },
65 iter::{
66 FromIterator,
67 FusedIterator,
68 Sum,
69 },
70 mem::{
71 replace,
72 swap,
73 },
74 ops::{
75 Add,
76 Index,
77 IndexMut,
78 RangeBounds,
79 },
80};
81
82use sp_sized_chunks::InlineArray;
83
84use crate::{
85 nodes::{
86 chunk::{
87 Chunk,
88 CHUNK_SIZE,
89 },
90 rrb::{
91 Node,
92 PopResult,
93 PushResult,
94 SplitResult,
95 },
96 },
97 sort,
98 util::{
99 clone_ref,
100 swap_indices,
101 to_range,
102 Pool,
103 PoolDefault,
104 PoolRef,
105 Ref,
106 Side,
107 },
108};
109
110use self::VectorInner::{
111 Full,
112 Inline,
113 Single,
114};
115
116mod focus;
117
118pub use self::focus::{
119 Focus,
120 FocusMut,
121};
122
123mod pool;
124pub use self::pool::RRBPool;
125
126#[cfg(all(threadsafe, any(test, feature = "rayon")))]
127pub mod rayon;
128
129#[macro_export]
141macro_rules! vector {
142 () => { $crate::vector::Vector::new() };
143
144 ( $($x:expr),* ) => {{
145 let mut l = $crate::vector::Vector::new();
146 $(
147 l.push_back($x);
148 )*
149 l
150 }};
151
152 ( $($x:expr ,)* ) => {{
153 let mut l = $crate::vector::Vector::new();
154 $(
155 l.push_back($x);
156 )*
157 l
158 }};
159}
160
161pub struct Vector<A> {
198 vector: VectorInner<A>,
199}
200
201enum VectorInner<A> {
202 Inline(RRBPool<A>, InlineArray<A, RRB<A>>),
203 Single(RRBPool<A>, PoolRef<Chunk<A>>),
204 Full(RRBPool<A>, RRB<A>),
205}
206
207#[doc(hidden)]
208pub struct RRB<A> {
209 length: usize,
210 middle_level: usize,
211 outer_f: PoolRef<Chunk<A>>,
212 inner_f: PoolRef<Chunk<A>>,
213 middle: Ref<Node<A>>,
214 inner_b: PoolRef<Chunk<A>>,
215 outer_b: PoolRef<Chunk<A>>,
216}
217
218impl<A> Clone for RRB<A> {
219 fn clone(&self) -> Self {
220 RRB {
221 length: self.length,
222 middle_level: self.middle_level,
223 outer_f: self.outer_f.clone(),
224 inner_f: self.inner_f.clone(),
225 middle: self.middle.clone(),
226 inner_b: self.inner_b.clone(),
227 outer_b: self.outer_b.clone(),
228 }
229 }
230}
231
232impl<A: Clone> Vector<A> {
233 #[cfg_attr(not(feature = "pool"), doc = "hidden")]
238 pub fn pool(&self) -> &RRBPool<A> {
239 match self.vector {
240 Inline(ref pool, _) => pool,
241 Single(ref pool, _) => pool,
242 Full(ref pool, _) => pool,
243 }
244 }
245
246 fn needs_promotion(&self) -> bool {
249 match &self.vector {
250 Inline(_, chunk) if chunk.is_full() => true,
251 Single(_, chunk) if chunk.is_full() => true,
252 _ => false,
253 }
254 }
255
256 fn promote_inline(&mut self) {
258 if let Inline(pool, chunk) = &mut self.vector {
259 self.vector =
260 Single(pool.clone(), PoolRef::new(&pool.value_pool, chunk.into()));
261 }
262 }
263
264 fn promote_front(&mut self) {
267 self.vector = match &mut self.vector {
268 Inline(pool, chunk) => {
269 Single(pool.clone(), PoolRef::new(&pool.value_pool, chunk.into()))
270 }
271 Single(pool, chunk) => {
272 let chunk = chunk.clone();
273 Full(pool.clone(), RRB {
274 length: chunk.len(),
275 middle_level: 0,
276 outer_f: PoolRef::default(&pool.value_pool),
277 inner_f: chunk,
278 middle: Ref::new(Node::new()),
279 inner_b: PoolRef::default(&pool.value_pool),
280 outer_b: PoolRef::default(&pool.value_pool),
281 })
282 }
283 Full(..) => return,
284 }
285 }
286
287 fn promote_back(&mut self) {
290 self.vector = match &mut self.vector {
291 Inline(pool, chunk) => {
292 Single(pool.clone(), PoolRef::new(&pool.value_pool, chunk.into()))
293 }
294 Single(pool, chunk) => {
295 let chunk = chunk.clone();
296 Full(pool.clone(), RRB {
297 length: chunk.len(),
298 middle_level: 0,
299 outer_f: PoolRef::default(&pool.value_pool),
300 inner_f: PoolRef::default(&pool.value_pool),
301 middle: Ref::new(Node::new()),
302 inner_b: chunk,
303 outer_b: PoolRef::default(&pool.value_pool),
304 })
305 }
306 Full(..) => return,
307 }
308 }
309
310 #[must_use]
312 pub fn new() -> Self {
313 Self { vector: Inline(RRBPool::default(), InlineArray::new()) }
314 }
315
316 #[cfg(feature = "pool")]
318 #[must_use]
319 pub fn with_pool(pool: &RRBPool<A>) -> Self {
320 Self { vector: Inline(pool.clone(), InlineArray::new()) }
321 }
322
323 #[inline]
334 #[must_use]
335 pub fn len(&self) -> usize {
336 match &self.vector {
337 Inline(_, chunk) => chunk.len(),
338 Single(_, chunk) => chunk.len(),
339 Full(_, tree) => tree.length,
340 }
341 }
342
343 #[inline]
357 #[must_use]
358 pub fn is_empty(&self) -> bool { self.len() == 0 }
359
360 #[inline]
376 #[must_use]
377 pub fn is_inline(&self) -> bool {
378 if let Inline(..) = &self.vector { true } else { false }
379 }
380
381 #[must_use]
398 pub fn ptr_eq(&self, other: &Self) -> bool {
399 fn cmp_chunk<A>(
400 left: &PoolRef<Chunk<A>>,
401 right: &PoolRef<Chunk<A>>,
402 ) -> bool {
403 (left.is_empty() && right.is_empty()) || PoolRef::ptr_eq(left, right)
404 }
405
406 if core::ptr::eq(self, other) {
407 return true;
408 }
409
410 match (&self.vector, &other.vector) {
411 (Single(_, left), Single(_, right)) => cmp_chunk(left, right),
412 (Full(_, left), Full(_, right)) => {
413 cmp_chunk(&left.outer_f, &right.outer_f)
414 && cmp_chunk(&left.inner_f, &right.inner_f)
415 && cmp_chunk(&left.inner_b, &right.inner_b)
416 && cmp_chunk(&left.outer_b, &right.outer_b)
417 && ((left.middle.is_empty() && right.middle.is_empty())
418 || Ref::ptr_eq(&left.middle, &right.middle))
419 }
420 _ => false,
421 }
422 }
423
424 #[inline]
428 #[must_use]
429 pub fn iter(&self) -> Iter<'_, A> { Iter::new(self) }
430
431 #[inline]
435 #[must_use]
436 pub fn iter_mut(&mut self) -> IterMut<'_, A> { IterMut::new(self) }
437
438 #[inline]
448 #[must_use]
449 pub fn leaves(&self) -> Chunks<'_, A> { Chunks::new(self) }
450
451 #[inline]
461 #[must_use]
462 pub fn leaves_mut(&mut self) -> ChunksMut<'_, A> { ChunksMut::new(self) }
463
464 #[inline]
470 #[must_use]
471 pub fn focus(&self) -> Focus<'_, A> { Focus::new(self) }
472
473 #[inline]
479 #[must_use]
480 pub fn focus_mut(&mut self) -> FocusMut<'_, A> { FocusMut::new(self) }
481
482 #[must_use]
498 pub fn get(&self, index: usize) -> Option<&A> {
499 if index >= self.len() {
500 return None;
501 }
502
503 match &self.vector {
504 Inline(_, chunk) => chunk.get(index),
505 Single(_, chunk) => chunk.get(index),
506 Full(_, tree) => {
507 let mut local_index = index;
508
509 if local_index < tree.outer_f.len() {
510 return Some(&tree.outer_f[local_index]);
511 }
512 local_index -= tree.outer_f.len();
513
514 if local_index < tree.inner_f.len() {
515 return Some(&tree.inner_f[local_index]);
516 }
517 local_index -= tree.inner_f.len();
518
519 if local_index < tree.middle.len() {
520 return Some(tree.middle.index(tree.middle_level, local_index));
521 }
522 local_index -= tree.middle.len();
523
524 if local_index < tree.inner_b.len() {
525 return Some(&tree.inner_b[local_index]);
526 }
527 local_index -= tree.inner_b.len();
528
529 Some(&tree.outer_b[local_index])
530 }
531 }
532 }
533
534 #[must_use]
555 pub fn get_mut(&mut self, index: usize) -> Option<&mut A> {
556 if index >= self.len() {
557 return None;
558 }
559
560 match &mut self.vector {
561 Inline(_, chunk) => chunk.get_mut(index),
562 Single(pool, chunk) => {
563 PoolRef::make_mut(&pool.value_pool, chunk).get_mut(index)
564 }
565 Full(pool, tree) => {
566 let mut local_index = index;
567
568 if local_index < tree.outer_f.len() {
569 let outer_f = PoolRef::make_mut(&pool.value_pool, &mut tree.outer_f);
570 return Some(&mut outer_f[local_index]);
571 }
572 local_index -= tree.outer_f.len();
573
574 if local_index < tree.inner_f.len() {
575 let inner_f = PoolRef::make_mut(&pool.value_pool, &mut tree.inner_f);
576 return Some(&mut inner_f[local_index]);
577 }
578 local_index -= tree.inner_f.len();
579
580 if local_index < tree.middle.len() {
581 let middle = Ref::make_mut(&mut tree.middle);
582 return Some(middle.index_mut(pool, tree.middle_level, local_index));
583 }
584 local_index -= tree.middle.len();
585
586 if local_index < tree.inner_b.len() {
587 let inner_b = PoolRef::make_mut(&pool.value_pool, &mut tree.inner_b);
588 return Some(&mut inner_b[local_index]);
589 }
590 local_index -= tree.inner_b.len();
591
592 let outer_b = PoolRef::make_mut(&pool.value_pool, &mut tree.outer_b);
593 Some(&mut outer_b[local_index])
594 }
595 }
596 }
597
598 #[inline]
604 #[must_use]
605 pub fn front(&self) -> Option<&A> { self.get(0) }
606
607 #[inline]
613 #[must_use]
614 pub fn front_mut(&mut self) -> Option<&mut A> { self.get_mut(0) }
615
616 #[inline]
626 #[must_use]
627 pub fn head(&self) -> Option<&A> { self.get(0) }
628
629 #[must_use]
635 pub fn back(&self) -> Option<&A> {
636 if self.is_empty() { None } else { self.get(self.len() - 1) }
637 }
638
639 #[must_use]
645 pub fn back_mut(&mut self) -> Option<&mut A> {
646 if self.is_empty() {
647 None
648 }
649 else {
650 let len = self.len();
651 self.get_mut(len - 1)
652 }
653 }
654
655 #[inline]
665 #[must_use]
666 pub fn last(&self) -> Option<&A> { self.back() }
667
668 #[must_use]
686 pub fn index_of(&self, value: &A) -> Option<usize>
687 where A: PartialEq {
688 for (index, item) in self.iter().enumerate() {
689 if value == item {
690 return Some(index);
691 }
692 }
693 None
694 }
695
696 #[inline]
714 #[must_use]
715 pub fn contains(&self, value: &A) -> bool
716 where A: PartialEq {
717 self.index_of(value).is_some()
718 }
719
720 pub fn clear(&mut self) {
727 if !self.is_empty() {
728 self.vector = Inline(self.pool().clone(), InlineArray::new());
729 }
730 }
731
732 pub fn binary_search_by<F>(&self, mut f: F) -> Result<usize, usize>
747 where F: FnMut(&A) -> Ordering {
748 let mut size = self.len();
749 if size == 0 {
750 return Err(0);
751 }
752 let mut base = 0;
753 while size > 1 {
754 let half = size / 2;
755 let mid = base + half;
756 base = match f(&self[mid]) {
757 Ordering::Greater => base,
758 _ => mid,
759 };
760 size -= half;
761 }
762 match f(&self[base]) {
763 Ordering::Equal => Ok(base),
764 Ordering::Greater => Err(base),
765 Ordering::Less => Err(base + 1),
766 }
767 }
768
769 pub fn binary_search(&self, value: &A) -> Result<usize, usize>
778 where A: Ord {
779 self.binary_search_by(|e| e.cmp(value))
780 }
781
782 pub fn binary_search_by_key<B, F>(
797 &self,
798 b: &B,
799 mut f: F,
800 ) -> Result<usize, usize>
801 where
802 F: FnMut(&A) -> B,
803 B: Ord,
804 {
805 self.binary_search_by(|k| f(k).cmp(b))
806 }
807}
808
809impl<A: Clone> Vector<A> {
810 #[inline]
822 #[must_use]
823 pub fn unit(a: A) -> Self {
824 let pool = RRBPool::default();
825 if InlineArray::<A, RRB<A>>::CAPACITY > 0 {
826 let mut array = InlineArray::new();
827 array.push(a);
828 Self { vector: Inline(pool, array) }
829 }
830 else {
831 let chunk = PoolRef::new(&pool.value_pool, Chunk::unit(a));
832 Self { vector: Single(pool, chunk) }
833 }
834 }
835
836 #[must_use]
851 pub fn update(&self, index: usize, value: A) -> Self {
852 let mut out = self.clone();
853 out[index] = value;
854 out
855 }
856
857 #[inline]
865 pub fn set(&mut self, index: usize, value: A) -> A {
866 replace(&mut self[index], value)
867 }
868
869 pub fn swap(&mut self, i: usize, j: usize) { swap_indices(self, i, j) }
873
874 pub fn push_front(&mut self, value: A) {
888 if self.needs_promotion() {
889 self.promote_back();
890 }
891 match &mut self.vector {
892 Inline(_, chunk) => {
893 chunk.insert(0, value);
894 }
895 Single(pool, chunk) => {
896 PoolRef::make_mut(&pool.value_pool, chunk).push_front(value)
897 }
898 Full(pool, tree) => tree.push_front(pool, value),
899 }
900 }
901
902 pub fn push_back(&mut self, value: A) {
916 if self.needs_promotion() {
917 self.promote_front();
918 }
919 match &mut self.vector {
920 Inline(_, chunk) => {
921 chunk.push(value);
922 }
923 Single(pool, chunk) => {
924 PoolRef::make_mut(&pool.value_pool, chunk).push_back(value)
925 }
926 Full(pool, tree) => tree.push_back(pool, value),
927 }
928 }
929
930 pub fn pop_front(&mut self) -> Option<A> {
944 if self.is_empty() {
945 None
946 }
947 else {
948 match &mut self.vector {
949 Inline(_, chunk) => chunk.remove(0),
950 Single(pool, chunk) => {
951 Some(PoolRef::make_mut(&pool.value_pool, chunk).pop_front())
952 }
953 Full(pool, tree) => tree.pop_front(pool),
954 }
955 }
956 }
957
958 pub fn pop_back(&mut self) -> Option<A> {
972 if self.is_empty() {
973 None
974 }
975 else {
976 match &mut self.vector {
977 Inline(_, chunk) => chunk.pop(),
978 Single(pool, chunk) => {
979 Some(PoolRef::make_mut(&pool.value_pool, chunk).pop_back())
980 }
981 Full(pool, tree) => tree.pop_back(pool),
982 }
983 }
984 }
985
986 pub fn append(&mut self, mut other: Self) {
1000 if other.is_empty() {
1001 return;
1002 }
1003
1004 if self.is_empty() {
1005 *self = other;
1006 return;
1007 }
1008
1009 self.promote_inline();
1010 other.promote_inline();
1011
1012 let total_length =
1013 self.len().checked_add(other.len()).expect("Vector length overflow");
1014
1015 match &mut self.vector {
1016 Inline(..) => unreachable!("inline vecs should have been promoted"),
1017 Single(pool, left) => {
1018 match &mut other.vector {
1019 Inline(..) => unreachable!("inline vecs should have been promoted"),
1020 Single(_, ref mut right) if total_length <= CHUNK_SIZE => {
1023 PoolRef::make_mut(&pool.value_pool, left)
1024 .append(PoolRef::make_mut(&pool.value_pool, right));
1025 return;
1026 }
1027 _ if total_length <= CHUNK_SIZE => {
1030 while let Some(value) = other.pop_front() {
1031 PoolRef::make_mut(&pool.value_pool, left).push_back(value);
1032 }
1033 return;
1034 }
1035 _ => {}
1036 }
1037 }
1038 Full(pool, left) => {
1039 if let Full(_, mut right) = other.vector {
1040 if left.middle.is_empty()
1044 && right.middle.is_empty()
1045 && left.outer_b.is_empty()
1046 && left.inner_b.is_empty()
1047 && right.outer_f.is_empty()
1048 && right.inner_f.is_empty()
1049 {
1050 left.inner_b = right.inner_b;
1051 left.outer_b = right.outer_b;
1052 left.length = total_length;
1053 return;
1054 }
1055 if left.middle.is_empty()
1058 && right.middle.is_empty()
1059 && total_length <= CHUNK_SIZE * 4
1060 {
1061 while let Some(value) = right.pop_front(pool) {
1062 left.push_back(pool, value);
1063 }
1064 return;
1065 }
1066 let inner_b1 = left.inner_b.clone();
1068 left.push_middle(pool, Side::Right, inner_b1);
1069 let outer_b1 = left.outer_b.clone();
1070 left.push_middle(pool, Side::Right, outer_b1);
1071 let inner_f2 = right.inner_f.clone();
1072 right.push_middle(pool, Side::Left, inner_f2);
1073 let outer_f2 = right.outer_f.clone();
1074 right.push_middle(pool, Side::Left, outer_f2);
1075
1076 let mut middle1 =
1077 clone_ref(replace(&mut left.middle, Ref::from(Node::new())));
1078 let mut middle2 = clone_ref(right.middle);
1079 let normalised_middle =
1080 match left.middle_level.cmp(&right.middle_level) {
1081 Ordering::Greater => {
1082 middle2 =
1083 middle2.elevate(pool, left.middle_level - right.middle_level);
1084 left.middle_level
1085 }
1086 Ordering::Less => {
1087 middle1 =
1088 middle1.elevate(pool, right.middle_level - left.middle_level);
1089 right.middle_level
1090 }
1091 Ordering::Equal => left.middle_level,
1092 };
1093 left.middle =
1094 Ref::new(Node::merge(pool, middle1, middle2, normalised_middle));
1095 left.middle_level = normalised_middle + 1;
1096
1097 left.inner_b = right.inner_b;
1098 left.outer_b = right.outer_b;
1099 left.length = total_length;
1100 left.prune();
1101 return;
1102 }
1103 }
1104 }
1105 self.promote_front();
1108 other.promote_back();
1109 self.append(other)
1110 }
1111
1112 pub fn retain<F>(&mut self, mut f: F)
1119 where F: FnMut(&A) -> bool {
1120 let len = self.len();
1121 let mut del = 0;
1122 {
1123 let mut focus = self.focus_mut();
1124 for i in 0..len {
1125 if !f(focus.index(i)) {
1126 del += 1;
1127 }
1128 else if del > 0 {
1129 focus.swap(i - del, i);
1130 }
1131 }
1132 }
1133 if del > 0 {
1134 self.split_off(len - del);
1135 }
1136 }
1137
1138 pub fn split_at(mut self, index: usize) -> (Self, Self) {
1157 let right = self.split_off(index);
1158 (self, right)
1159 }
1160
1161 pub fn split_off(&mut self, index: usize) -> Self {
1180 assert!(index <= self.len());
1181
1182 match &mut self.vector {
1183 Inline(pool, chunk) => {
1184 Self { vector: Inline(pool.clone(), chunk.split_off(index)) }
1185 }
1186 Single(pool, chunk) => Self {
1187 vector: Single(
1188 pool.clone(),
1189 PoolRef::new(
1190 &pool.value_pool,
1191 PoolRef::make_mut(&pool.value_pool, chunk).split_off(index),
1192 ),
1193 ),
1194 },
1195 Full(pool, tree) => {
1196 let mut local_index = index;
1197
1198 if local_index < tree.outer_f.len() {
1199 let of2 = PoolRef::make_mut(&pool.value_pool, &mut tree.outer_f)
1200 .split_off(local_index);
1201 let right = RRB {
1202 length: tree.length - index,
1203 middle_level: tree.middle_level,
1204 outer_f: PoolRef::new(&pool.value_pool, of2),
1205 inner_f: replace_pool_def(&pool.value_pool, &mut tree.inner_f),
1206 middle: core::mem::take(&mut tree.middle),
1207 inner_b: replace_pool_def(&pool.value_pool, &mut tree.inner_b),
1208 outer_b: replace_pool_def(&pool.value_pool, &mut tree.outer_b),
1209 };
1210 tree.length = index;
1211 tree.middle_level = 0;
1212 return Self { vector: Full(pool.clone(), right) };
1213 }
1214
1215 local_index -= tree.outer_f.len();
1216
1217 if local_index < tree.inner_f.len() {
1218 let if2 = PoolRef::make_mut(&pool.value_pool, &mut tree.inner_f)
1219 .split_off(local_index);
1220 let right = RRB {
1221 length: tree.length - index,
1222 middle_level: tree.middle_level,
1223 outer_f: PoolRef::new(&pool.value_pool, if2),
1224 inner_f: PoolRef::<Chunk<A>>::default(&pool.value_pool),
1225 middle: core::mem::take(&mut tree.middle),
1226 inner_b: replace_pool_def(&pool.value_pool, &mut tree.inner_b),
1227 outer_b: replace_pool_def(&pool.value_pool, &mut tree.outer_b),
1228 };
1229 tree.length = index;
1230 tree.middle_level = 0;
1231 swap(&mut tree.outer_b, &mut tree.inner_f);
1232 return Self { vector: Full(pool.clone(), right) };
1233 }
1234
1235 local_index -= tree.inner_f.len();
1236
1237 if local_index < tree.middle.len() {
1238 let mut right_middle = tree.middle.clone();
1239 let (c1, c2) = {
1240 let m1 = Ref::make_mut(&mut tree.middle);
1241 let m2 = Ref::make_mut(&mut right_middle);
1242 match m1.split(pool, tree.middle_level, Side::Right, local_index) {
1243 SplitResult::Dropped(_) => (),
1244 SplitResult::OutOfBounds => unreachable!(),
1245 };
1246 match m2.split(pool, tree.middle_level, Side::Left, local_index) {
1247 SplitResult::Dropped(_) => (),
1248 SplitResult::OutOfBounds => unreachable!(),
1249 };
1250 let c1 = match m1.pop_chunk(pool, tree.middle_level, Side::Right) {
1251 PopResult::Empty => PoolRef::default(&pool.value_pool),
1252 PopResult::Done(chunk) => chunk,
1253 PopResult::Drained(chunk) => {
1254 m1.clear_node();
1255 chunk
1256 }
1257 };
1258 let c2 = match m2.pop_chunk(pool, tree.middle_level, Side::Left) {
1259 PopResult::Empty => PoolRef::default(&pool.value_pool),
1260 PopResult::Done(chunk) => chunk,
1261 PopResult::Drained(chunk) => {
1262 m2.clear_node();
1263 chunk
1264 }
1265 };
1266 (c1, c2)
1267 };
1268 let mut right = RRB {
1269 length: tree.length - index,
1270 middle_level: tree.middle_level,
1271 outer_f: c2,
1272 inner_f: PoolRef::<Chunk<A>>::default(&pool.value_pool),
1273 middle: right_middle,
1274 inner_b: replace_pool_def(&pool.value_pool, &mut tree.inner_b),
1275 outer_b: replace(&mut tree.outer_b, c1),
1276 };
1277 tree.length = index;
1278 tree.prune();
1279 right.prune();
1280 return Self { vector: Full(pool.clone(), right) };
1281 }
1282
1283 local_index -= tree.middle.len();
1284
1285 if local_index < tree.inner_b.len() {
1286 let ib2 = PoolRef::make_mut(&pool.value_pool, &mut tree.inner_b)
1287 .split_off(local_index);
1288 let right = RRB {
1289 length: tree.length - index,
1290 outer_b: replace_pool_def(&pool.value_pool, &mut tree.outer_b),
1291 outer_f: PoolRef::new(&pool.value_pool, ib2),
1292 ..RRB::new(pool)
1293 };
1294 tree.length = index;
1295 swap(&mut tree.outer_b, &mut tree.inner_b);
1296 return Self { vector: Full(pool.clone(), right) };
1297 }
1298
1299 local_index -= tree.inner_b.len();
1300
1301 let ob2 = PoolRef::make_mut(&pool.value_pool, &mut tree.outer_b)
1302 .split_off(local_index);
1303 tree.length = index;
1304 Self {
1305 vector: Single(pool.clone(), PoolRef::new(&pool.value_pool, ob2)),
1306 }
1307 }
1308 }
1309 }
1310
1311 #[must_use]
1316 pub fn skip(&self, count: usize) -> Self {
1317 self.clone().split_off(count)
1320 }
1321
1322 #[must_use]
1327 pub fn take(&self, count: usize) -> Self {
1328 let mut left = self.clone();
1331 left.split_off(count);
1332 left
1333 }
1334
1335 pub fn truncate(&mut self, len: usize) {
1343 self.split_off(len);
1346 }
1347
1348 pub fn slice<R>(&mut self, range: R) -> Self
1356 where R: RangeBounds<usize> {
1357 let r = to_range(&range, self.len());
1358 if r.start >= r.end || r.start >= self.len() {
1359 return Vector::new();
1360 }
1361 let mut middle = self.split_off(r.start);
1362 let right = middle.split_off(r.end - r.start);
1363 self.append(right);
1364 middle
1365 }
1366
1367 pub fn insert(&mut self, index: usize, value: A) {
1385 if index == 0 {
1386 return self.push_front(value);
1387 }
1388 if index == self.len() {
1389 return self.push_back(value);
1390 }
1391 assert!(index < self.len());
1392 if if let Inline(_, chunk) = &self.vector { chunk.is_full() } else { false }
1393 {
1394 self.promote_inline();
1395 }
1396 match &mut self.vector {
1397 Inline(_, chunk) => {
1398 chunk.insert(index, value);
1399 }
1400 Single(pool, chunk) if chunk.len() < CHUNK_SIZE => {
1401 PoolRef::make_mut(&pool.value_pool, chunk).insert(index, value)
1402 }
1403 _ => {
1405 let right = self.split_off(index);
1406 self.push_back(value);
1407 self.append(right);
1408 }
1409 }
1410 }
1411
1412 pub fn remove(&mut self, index: usize) -> A {
1429 assert!(index < self.len());
1430 match &mut self.vector {
1431 Inline(_, chunk) => chunk.remove(index).unwrap(),
1432 Single(pool, chunk) => {
1433 PoolRef::make_mut(&pool.value_pool, chunk).remove(index)
1434 }
1435 _ => {
1436 if index == 0 {
1437 return self.pop_front().unwrap();
1438 }
1439 if index == self.len() - 1 {
1440 return self.pop_back().unwrap();
1441 }
1442 let mut right = self.split_off(index);
1444 let value = right.pop_front().unwrap();
1445 self.append(right);
1446 value
1447 }
1448 }
1449 }
1450
1451 pub fn insert_ord(&mut self, item: A)
1468 where A: Ord {
1469 match self.binary_search(&item) {
1470 Ok(index) => self.insert(index, item),
1471 Err(index) => self.insert(index, item),
1472 }
1473 }
1474
1475 pub fn sort(&mut self)
1489 where A: Ord {
1490 self.sort_by(Ord::cmp)
1491 }
1492
1493 pub fn sort_by<F>(&mut self, cmp: F)
1507 where F: Fn(&A, &A) -> Ordering {
1508 let len = self.len();
1509 if len > 1 {
1510 sort::quicksort(self.focus_mut(), &cmp);
1511 }
1512 }
1513
1514 #[cfg(any(test, feature = "debug"))]
1522 pub fn assert_invariants(&self) {
1523 if let Full(_, ref tree) = self.vector {
1524 tree.assert_invariants();
1525 }
1526 }
1527}
1528
1529impl<A: Clone> RRB<A> {
1532 fn new(pool: &RRBPool<A>) -> Self {
1533 RRB {
1534 length: 0,
1535 middle_level: 0,
1536 outer_f: PoolRef::default(&pool.value_pool),
1537 inner_f: PoolRef::default(&pool.value_pool),
1538 middle: Ref::new(Node::new()),
1539 inner_b: PoolRef::default(&pool.value_pool),
1540 outer_b: PoolRef::default(&pool.value_pool),
1541 }
1542 }
1543
1544 #[cfg(any(test, feature = "debug"))]
1545 fn assert_invariants(&self) {
1546 let ml = self.middle.assert_invariants(self.middle_level);
1547 assert_eq!(
1548 self.length,
1549 self.outer_f.len()
1550 + self.inner_f.len()
1551 + ml
1552 + self.inner_b.len()
1553 + self.outer_b.len()
1554 );
1555 }
1556
1557 fn prune(&mut self) {
1558 if self.middle.is_empty() {
1559 self.middle = Ref::new(Node::new());
1560 self.middle_level = 0;
1561 }
1562 else {
1563 while self.middle_level > 0 && self.middle.is_single() {
1564 self.middle = Ref::new(self.middle.first_child().clone());
1566 self.middle_level -= 1;
1567 }
1568 }
1569 }
1570
1571 fn pop_front(&mut self, pool: &RRBPool<A>) -> Option<A> {
1572 if self.length == 0 {
1573 return None;
1574 }
1575 if self.outer_f.is_empty() {
1576 if self.inner_f.is_empty() {
1577 if self.middle.is_empty() {
1578 if self.inner_b.is_empty() {
1579 swap(&mut self.outer_f, &mut self.outer_b);
1580 }
1581 else {
1582 swap(&mut self.outer_f, &mut self.inner_b);
1583 }
1584 }
1585 else {
1586 self.outer_f = self.pop_middle(pool, Side::Left).unwrap();
1587 }
1588 }
1589 else {
1590 swap(&mut self.outer_f, &mut self.inner_f);
1591 }
1592 }
1593 self.length -= 1;
1594 let outer_f = PoolRef::make_mut(&pool.value_pool, &mut self.outer_f);
1595 Some(outer_f.pop_front())
1596 }
1597
1598 fn pop_back(&mut self, pool: &RRBPool<A>) -> Option<A> {
1599 if self.length == 0 {
1600 return None;
1601 }
1602 if self.outer_b.is_empty() {
1603 if self.inner_b.is_empty() {
1604 if self.middle.is_empty() {
1605 if self.inner_f.is_empty() {
1606 swap(&mut self.outer_b, &mut self.outer_f);
1607 }
1608 else {
1609 swap(&mut self.outer_b, &mut self.inner_f);
1610 }
1611 }
1612 else {
1613 self.outer_b = self.pop_middle(pool, Side::Right).unwrap();
1614 }
1615 }
1616 else {
1617 swap(&mut self.outer_b, &mut self.inner_b);
1618 }
1619 }
1620 self.length -= 1;
1621 let outer_b = PoolRef::make_mut(&pool.value_pool, &mut self.outer_b);
1622 Some(outer_b.pop_back())
1623 }
1624
1625 fn push_front(&mut self, pool: &RRBPool<A>, value: A) {
1626 if self.outer_f.is_full() {
1627 swap(&mut self.outer_f, &mut self.inner_f);
1628 if !self.outer_f.is_empty() {
1629 let mut chunk = PoolRef::new(&pool.value_pool, Chunk::new());
1630 swap(&mut chunk, &mut self.outer_f);
1631 self.push_middle(pool, Side::Left, chunk);
1632 }
1633 }
1634 self.length = self.length.checked_add(1).expect("Vector length overflow");
1635 let outer_f = PoolRef::make_mut(&pool.value_pool, &mut self.outer_f);
1636 outer_f.push_front(value)
1637 }
1638
1639 fn push_back(&mut self, pool: &RRBPool<A>, value: A) {
1640 if self.outer_b.is_full() {
1641 swap(&mut self.outer_b, &mut self.inner_b);
1642 if !self.outer_b.is_empty() {
1643 let mut chunk = PoolRef::new(&pool.value_pool, Chunk::new());
1644 swap(&mut chunk, &mut self.outer_b);
1645 self.push_middle(pool, Side::Right, chunk);
1646 }
1647 }
1648 self.length = self.length.checked_add(1).expect("Vector length overflow");
1649 let outer_b = PoolRef::make_mut(&pool.value_pool, &mut self.outer_b);
1650 outer_b.push_back(value)
1651 }
1652
1653 fn push_middle(
1654 &mut self,
1655 pool: &RRBPool<A>,
1656 side: Side,
1657 chunk: PoolRef<Chunk<A>>,
1658 ) {
1659 if chunk.is_empty() {
1660 return;
1661 }
1662 let new_middle = {
1663 let middle = Ref::make_mut(&mut self.middle);
1664 match middle.push_chunk(pool, self.middle_level, side, chunk) {
1665 PushResult::Done => return,
1666 PushResult::Full(chunk, _num_drained) => Ref::from({
1667 match side {
1668 Side::Left => Node::from_chunk(pool, self.middle_level, chunk)
1669 .join_branches(pool, middle.clone(), self.middle_level),
1670 Side::Right => middle.clone().join_branches(
1671 pool,
1672 Node::from_chunk(pool, self.middle_level, chunk),
1673 self.middle_level,
1674 ),
1675 }
1676 }),
1677 }
1678 };
1679 self.middle_level += 1;
1680 self.middle = new_middle;
1681 }
1682
1683 fn pop_middle(
1684 &mut self,
1685 pool: &RRBPool<A>,
1686 side: Side,
1687 ) -> Option<PoolRef<Chunk<A>>> {
1688 let chunk = {
1689 let middle = Ref::make_mut(&mut self.middle);
1690 match middle.pop_chunk(pool, self.middle_level, side) {
1691 PopResult::Empty => return None,
1692 PopResult::Done(chunk) => chunk,
1693 PopResult::Drained(chunk) => {
1694 middle.clear_node();
1695 self.middle_level = 0;
1696 chunk
1697 }
1698 }
1699 };
1700 Some(chunk)
1701 }
1702}
1703
1704#[inline]
1705fn replace_pool_def<A: PoolDefault>(
1706 pool: &Pool<A>,
1707 dest: &mut PoolRef<A>,
1708) -> PoolRef<A> {
1709 replace(dest, PoolRef::default(pool))
1710}
1711
1712impl<A: Clone> Default for Vector<A> {
1715 fn default() -> Self { Self::new() }
1716}
1717
1718impl<A: Clone> Clone for Vector<A> {
1719 fn clone(&self) -> Self {
1723 Self {
1724 vector: match &self.vector {
1725 Inline(pool, chunk) => Inline(pool.clone(), chunk.clone()),
1726 Single(pool, chunk) => Single(pool.clone(), chunk.clone()),
1727 Full(pool, tree) => Full(pool.clone(), tree.clone()),
1728 },
1729 }
1730 }
1731}
1732
1733impl<A: Clone + Debug> Debug for Vector<A> {
1734 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
1735 f.debug_list().entries(self.iter()).finish()
1736 }
1745}
1746
1747#[cfg(not(has_specialisation))]
1748impl<A: Clone + PartialEq> PartialEq for Vector<A> {
1749 fn eq(&self, other: &Self) -> bool {
1750 self.len() == other.len() && self.iter().eq(other.iter())
1751 }
1752}
1753
1754#[cfg(has_specialisation)]
1755impl<A: Clone + PartialEq> PartialEq for Vector<A> {
1756 default fn eq(&self, other: &Self) -> bool {
1757 self.len() == other.len() && self.iter().eq(other.iter())
1758 }
1759}
1760
1761#[cfg(has_specialisation)]
1762impl<A: Clone + Eq> PartialEq for Vector<A> {
1763 fn eq(&self, other: &Self) -> bool {
1764 fn cmp_chunk<A>(
1765 left: &PoolRef<Chunk<A>>,
1766 right: &PoolRef<Chunk<A>>,
1767 ) -> bool {
1768 (left.is_empty() && right.is_empty()) || PoolRef::ptr_eq(left, right)
1769 }
1770
1771 if core::ptr::eq(self, other) {
1772 return true;
1773 }
1774
1775 match (&self.vector, &other.vector) {
1776 (Single(_, left), Single(_, right)) => {
1777 if cmp_chunk(left, right) {
1778 return true;
1779 }
1780 self.iter().eq(other.iter())
1781 }
1782 (Full(_, left), Full(_, right)) => {
1783 if left.length != right.length {
1784 return false;
1785 }
1786
1787 if cmp_chunk(&left.outer_f, &right.outer_f)
1788 && cmp_chunk(&left.inner_f, &right.inner_f)
1789 && cmp_chunk(&left.inner_b, &right.inner_b)
1790 && cmp_chunk(&left.outer_b, &right.outer_b)
1791 && ((left.middle.is_empty() && right.middle.is_empty())
1792 || Ref::ptr_eq(&left.middle, &right.middle))
1793 {
1794 return true;
1795 }
1796 self.iter().eq(other.iter())
1797 }
1798 _ => self.len() == other.len() && self.iter().eq(other.iter()),
1799 }
1800 }
1801}
1802
1803impl<A: Clone + Eq> Eq for Vector<A> {}
1804
1805impl<A: Clone + PartialOrd> PartialOrd for Vector<A> {
1806 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1807 self.iter().partial_cmp(other.iter())
1808 }
1809}
1810
1811impl<A: Clone + Ord> Ord for Vector<A> {
1812 fn cmp(&self, other: &Self) -> Ordering { self.iter().cmp(other.iter()) }
1813}
1814
1815impl<A: Clone + Hash> Hash for Vector<A> {
1816 fn hash<H: Hasher>(&self, state: &mut H) {
1817 for i in self {
1818 i.hash(state)
1819 }
1820 }
1821}
1822
1823impl<A: Clone> Sum for Vector<A> {
1824 fn sum<I>(it: I) -> Self
1825 where I: Iterator<Item = Self> {
1826 it.fold(Self::new(), |a, b| a + b)
1827 }
1828}
1829
1830impl<A: Clone> Add for Vector<A> {
1831 type Output = Vector<A>;
1832
1833 fn add(mut self, other: Self) -> Self::Output {
1837 self.append(other);
1838 self
1839 }
1840}
1841
1842impl<'a, A: Clone> Add for &'a Vector<A> {
1843 type Output = Vector<A>;
1844
1845 fn add(self, other: Self) -> Self::Output {
1849 let mut out = self.clone();
1850 out.append(other.clone());
1851 out
1852 }
1853}
1854
1855impl<A: Clone> Extend<A> for Vector<A> {
1856 fn extend<I>(&mut self, iter: I)
1860 where I: IntoIterator<Item = A> {
1861 for item in iter {
1862 self.push_back(item)
1863 }
1864 }
1865}
1866
1867impl<A: Clone> Index<usize> for Vector<A> {
1868 type Output = A;
1869
1870 fn index(&self, index: usize) -> &Self::Output {
1874 match self.get(index) {
1875 Some(value) => value,
1876 None => {
1877 panic!("Vector::index: index out of bounds: {} < {}", index, self.len())
1878 }
1879 }
1880 }
1881}
1882
1883impl<A: Clone> IndexMut<usize> for Vector<A> {
1884 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1889 match self.get_mut(index) {
1890 Some(value) => value,
1891 None => panic!("Vector::index_mut: index out of bounds"),
1892 }
1893 }
1894}
1895
1896impl<'a, A: Clone> IntoIterator for &'a Vector<A> {
1899 type IntoIter = Iter<'a, A>;
1900 type Item = &'a A;
1901
1902 fn into_iter(self) -> Self::IntoIter { self.iter() }
1903}
1904
1905impl<A: Clone> IntoIterator for Vector<A> {
1906 type IntoIter = ConsumingIter<A>;
1907 type Item = A;
1908
1909 fn into_iter(self) -> Self::IntoIter { ConsumingIter::new(self) }
1910}
1911
1912impl<A: Clone> FromIterator<A> for Vector<A> {
1913 fn from_iter<I>(iter: I) -> Self
1917 where I: IntoIterator<Item = A> {
1918 let mut seq = Self::new();
1919 for item in iter {
1920 seq.push_back(item)
1921 }
1922 seq
1923 }
1924}
1925
1926impl<'s, 'a, A, OA> From<&'s Vector<&'a A>> for Vector<OA>
1927where
1928 A: ToOwned<Owned = OA>,
1929 OA: Borrow<A> + Clone,
1930{
1931 fn from(vec: &Vector<&A>) -> Self {
1932 vec.iter().map(|a| (*a).to_owned()).collect()
1933 }
1934}
1935
1936impl<'a, A: Clone> From<&'a [A]> for Vector<A> {
1937 fn from(slice: &[A]) -> Self { slice.iter().cloned().collect() }
1938}
1939
1940impl<A: Clone> From<Vec<A>> for Vector<A> {
1941 fn from(vec: Vec<A>) -> Self { vec.into_iter().collect() }
1947}
1948
1949impl<'a, A: Clone> From<&'a Vec<A>> for Vector<A> {
1950 fn from(vec: &Vec<A>) -> Self { vec.iter().cloned().collect() }
1956}
1957
1958pub struct Iter<'a, A> {
1966 focus: Focus<'a, A>,
1967 front_index: usize,
1968 back_index: usize,
1969}
1970
1971impl<'a, A: Clone> Iter<'a, A> {
1972 fn new(seq: &'a Vector<A>) -> Self {
1973 Iter { focus: seq.focus(), front_index: 0, back_index: seq.len() }
1974 }
1975
1976 fn from_focus(focus: Focus<'a, A>) -> Self {
1977 Iter { front_index: 0, back_index: focus.len(), focus }
1978 }
1979}
1980
1981impl<'a, A: Clone> Iterator for Iter<'a, A> {
1982 type Item = &'a A;
1983
1984 fn next(&mut self) -> Option<Self::Item> {
1988 if self.front_index >= self.back_index {
1989 return None;
1990 }
1991 #[allow(unsafe_code)]
1992 let focus: &'a mut Focus<'a, A> =
1993 unsafe { &mut *(&mut self.focus as *mut _) };
1994 let value = focus.get(self.front_index);
1995 self.front_index += 1;
1996 value
1997 }
1998
1999 fn size_hint(&self) -> (usize, Option<usize>) {
2000 let remaining = self.back_index - self.front_index;
2001 (remaining, Some(remaining))
2002 }
2003}
2004
2005impl<'a, A: Clone> DoubleEndedIterator for Iter<'a, A> {
2006 fn next_back(&mut self) -> Option<Self::Item> {
2010 if self.front_index >= self.back_index {
2011 return None;
2012 }
2013 self.back_index -= 1;
2014 #[allow(unsafe_code)]
2015 let focus: &'a mut Focus<'a, A> =
2016 unsafe { &mut *(&mut self.focus as *mut _) };
2017 focus.get(self.back_index)
2018 }
2019}
2020
2021impl<'a, A: Clone> ExactSizeIterator for Iter<'a, A> {}
2022
2023impl<'a, A: Clone> FusedIterator for Iter<'a, A> {}
2024
2025pub struct IterMut<'a, A> {
2031 focus: FocusMut<'a, A>,
2032 front_index: usize,
2033 back_index: usize,
2034}
2035
2036impl<'a, A> IterMut<'a, A>
2037where A: Clone
2038{
2039 fn new(seq: &'a mut Vector<A>) -> Self {
2040 let focus = seq.focus_mut();
2041 let len = focus.len();
2042 IterMut { focus, front_index: 0, back_index: len }
2043 }
2044
2045 fn from_focus(focus: FocusMut<'a, A>) -> Self {
2046 IterMut { front_index: 0, back_index: focus.len(), focus }
2047 }
2048}
2049
2050impl<'a, A> Iterator for IterMut<'a, A>
2051where A: 'a + Clone
2052{
2053 type Item = &'a mut A;
2054
2055 fn next(&mut self) -> Option<Self::Item> {
2059 if self.front_index >= self.back_index {
2060 return None;
2061 }
2062 #[allow(unsafe_code)]
2063 let focus: &'a mut FocusMut<'a, A> =
2064 unsafe { &mut *(&mut self.focus as *mut _) };
2065 let value = focus.get_mut(self.front_index);
2066 self.front_index += 1;
2067 value
2068 }
2069
2070 fn size_hint(&self) -> (usize, Option<usize>) {
2071 let remaining = self.back_index - self.front_index;
2072 (remaining, Some(remaining))
2073 }
2074}
2075
2076impl<'a, A> DoubleEndedIterator for IterMut<'a, A>
2077where A: 'a + Clone
2078{
2079 fn next_back(&mut self) -> Option<Self::Item> {
2083 if self.front_index >= self.back_index {
2084 return None;
2085 }
2086 self.back_index -= 1;
2087 #[allow(unsafe_code)]
2088 let focus: &'a mut FocusMut<'a, A> =
2089 unsafe { &mut *(&mut self.focus as *mut _) };
2090 focus.get_mut(self.back_index)
2091 }
2092}
2093
2094impl<'a, A: Clone> ExactSizeIterator for IterMut<'a, A> {}
2095
2096impl<'a, A: Clone> FusedIterator for IterMut<'a, A> {}
2097
2098pub struct ConsumingIter<A> {
2100 vector: Vector<A>,
2101}
2102
2103impl<A: Clone> ConsumingIter<A> {
2104 fn new(vector: Vector<A>) -> Self { Self { vector } }
2105}
2106
2107impl<A: Clone> Iterator for ConsumingIter<A> {
2108 type Item = A;
2109
2110 fn next(&mut self) -> Option<Self::Item> { self.vector.pop_front() }
2114
2115 fn size_hint(&self) -> (usize, Option<usize>) {
2116 let len = self.vector.len();
2117 (len, Some(len))
2118 }
2119}
2120
2121impl<A: Clone> DoubleEndedIterator for ConsumingIter<A> {
2122 fn next_back(&mut self) -> Option<Self::Item> { self.vector.pop_back() }
2126}
2127
2128impl<A: Clone> ExactSizeIterator for ConsumingIter<A> {}
2129
2130impl<A: Clone> FusedIterator for ConsumingIter<A> {}
2131
2132pub struct Chunks<'a, A> {
2138 focus: Focus<'a, A>,
2139 front_index: usize,
2140 back_index: usize,
2141}
2142
2143impl<'a, A: Clone> Chunks<'a, A> {
2144 fn new(seq: &'a Vector<A>) -> Self {
2145 Chunks { focus: seq.focus(), front_index: 0, back_index: seq.len() }
2146 }
2147}
2148
2149impl<'a, A: Clone> Iterator for Chunks<'a, A> {
2150 type Item = &'a [A];
2151
2152 fn next(&mut self) -> Option<Self::Item> {
2156 if self.front_index >= self.back_index {
2157 return None;
2158 }
2159 #[allow(unsafe_code)]
2160 let focus: &'a mut Focus<'a, A> =
2161 unsafe { &mut *(&mut self.focus as *mut _) };
2162 let (range, value) = focus.chunk_at(self.front_index);
2163 self.front_index = range.end;
2164 Some(value)
2165 }
2166}
2167
2168impl<'a, A: Clone> DoubleEndedIterator for Chunks<'a, A> {
2169 fn next_back(&mut self) -> Option<Self::Item> {
2173 if self.front_index >= self.back_index {
2174 return None;
2175 }
2176 self.back_index -= 1;
2177 #[allow(unsafe_code)]
2178 let focus: &'a mut Focus<'a, A> =
2179 unsafe { &mut *(&mut self.focus as *mut _) };
2180 let (range, value) = focus.chunk_at(self.back_index);
2181 self.back_index = range.start;
2182 Some(value)
2183 }
2184}
2185
2186impl<'a, A: Clone> FusedIterator for Chunks<'a, A> {}
2187
2188pub struct ChunksMut<'a, A> {
2194 focus: FocusMut<'a, A>,
2195 front_index: usize,
2196 back_index: usize,
2197}
2198
2199impl<'a, A: Clone> ChunksMut<'a, A> {
2200 fn new(seq: &'a mut Vector<A>) -> Self {
2201 let len = seq.len();
2202 ChunksMut { focus: seq.focus_mut(), front_index: 0, back_index: len }
2203 }
2204}
2205
2206impl<'a, A: Clone> Iterator for ChunksMut<'a, A> {
2207 type Item = &'a mut [A];
2208
2209 fn next(&mut self) -> Option<Self::Item> {
2213 if self.front_index >= self.back_index {
2214 return None;
2215 }
2216 #[allow(unsafe_code)]
2217 let focus: &'a mut FocusMut<'a, A> =
2218 unsafe { &mut *(&mut self.focus as *mut _) };
2219 let (range, value) = focus.chunk_at(self.front_index);
2220 self.front_index = range.end;
2221 Some(value)
2222 }
2223}
2224
2225impl<'a, A: Clone> DoubleEndedIterator for ChunksMut<'a, A> {
2226 fn next_back(&mut self) -> Option<Self::Item> {
2230 if self.front_index >= self.back_index {
2231 return None;
2232 }
2233 self.back_index -= 1;
2234 #[allow(unsafe_code)]
2235 let focus: &'a mut FocusMut<'a, A> =
2236 unsafe { &mut *(&mut self.focus as *mut _) };
2237 let (range, value) = focus.chunk_at(self.back_index);
2238 self.back_index = range.start;
2239 Some(value)
2240 }
2241}
2242
2243impl<'a, A: Clone> FusedIterator for ChunksMut<'a, A> {}
2244
2245#[cfg(test)]
2259mod test {
2260 use super::*;
2261 #[test]
2272 fn macro_allows_trailing_comma() {
2273 let vec1 = vector![1, 2, 3];
2274 let vec2 = vector![1, 2, 3,];
2275 assert_eq!(vec1, vec2);
2276 }
2277
2278 #[test]
2279 fn indexing() {
2280 let mut vec = vector![0, 1, 2, 3, 4, 5];
2281 vec.push_front(0);
2282 assert_eq!(0, *vec.get(0).unwrap());
2283 assert_eq!(0, vec[0]);
2284 }
2285
2286 #[test]
2287 fn large_vector_focus() {
2288 let input = Vector::from_iter(0..100_000);
2289 let vec = input.clone();
2290 let mut sum: i64 = 0;
2291 let mut focus = vec.focus();
2292 for i in 0..input.len() {
2293 sum += *focus.index(i);
2294 }
2295 let expected: i64 = (0..100_000).sum();
2296 assert_eq!(expected, sum);
2297 }
2298
2299 #[test]
2300 fn large_vector_focus_mut() {
2301 let input = Vector::from_iter(0..100_000);
2302 let mut vec = input.clone();
2303 {
2304 let mut focus = vec.focus_mut();
2305 for i in 0..input.len() {
2306 let p = focus.index_mut(i);
2307 *p += 1;
2308 }
2309 }
2310 let expected: Vector<i32> = input.into_iter().map(|i| i + 1).collect();
2311 assert_eq!(expected, vec);
2312 }
2313
2314 #[test]
2315 fn issue_55_fwd() {
2316 let mut l = Vector::new();
2317 for i in 0..4098 {
2318 l.append(Vector::unit(i));
2319 }
2320 l.append(Vector::unit(4098));
2321 assert_eq!(Some(&4097), l.get(4097));
2322 assert_eq!(Some(&4096), l.get(4096));
2323 }
2324
2325 #[test]
2326 fn issue_55_back() {
2327 let mut l = Vector::unit(0);
2328 for i in 0..4099 {
2329 let mut tmp = Vector::unit(i + 1);
2330 tmp.append(l);
2331 l = tmp;
2332 }
2333 assert_eq!(Some(&4098), l.get(1));
2334 assert_eq!(Some(&4097), l.get(2));
2335 let len = l.len();
2336 l.slice(2..len);
2337 }
2338
2339 #[test]
2340 fn issue_55_append() {
2341 let mut vec1 = Vector::from_iter(0..92);
2342 let vec2 = Vector::from_iter(0..165);
2343 vec1.append(vec2);
2344 }
2345
2346 #[test]
2347 fn issue_70() {
2348 let mut x = Vector::new();
2349 for _ in 0..262 {
2350 x.push_back(0);
2351 }
2352 for _ in 0..97 {
2353 x.pop_front();
2354 }
2355 for &offset in &[160, 163, 160] {
2356 x.remove(offset);
2357 }
2358 for _ in 0..64 {
2359 x.push_back(0);
2360 }
2361 match x.vector {
2365 VectorInner::Full(_, ref tree) => {
2366 assert_eq!(129, tree.middle.len());
2367 assert_eq!(3, tree.middle.number_of_children());
2368 }
2369 _ => unreachable!(),
2370 }
2371 x.push_back(0);
2372 match x.vector {
2373 VectorInner::Full(_, ref tree) => {
2374 assert_eq!(131, tree.middle.len());
2375 assert_eq!(3, tree.middle.number_of_children())
2376 }
2377 _ => unreachable!(),
2378 }
2379 for _ in 0..64 {
2380 x.push_back(0);
2381 }
2382 for _ in x.iter() {}
2383 }
2384
2385 #[test]
2386 fn issue_67() {
2387 let mut l = Vector::unit(4100);
2388 for i in (0..4099).rev() {
2389 let mut tmp = Vector::unit(i);
2390 tmp.append(l);
2391 l = tmp;
2392 }
2393 assert_eq!(4100, l.len());
2394 let len = l.len();
2395 let tail = l.slice(1..len);
2396 assert_eq!(1, l.len());
2397 assert_eq!(4099, tail.len());
2398 assert_eq!(Some(&0), l.get(0));
2399 assert_eq!(Some(&1), tail.get(0));
2400 }
2401
2402 #[test]
2403 fn issue_74_simple_size() {
2404 use crate::nodes::rrb::NODE_SIZE;
2405 let mut x = Vector::new();
2406 for _ in 0..(CHUNK_SIZE
2407 * (
2408 1 + (2 * NODE_SIZE) + 1 + 1
2412 ))
2414 {
2415 x.push_back(0u32);
2416 }
2417 let middle_first_node_start = CHUNK_SIZE;
2418 let middle_second_node_start =
2419 middle_first_node_start + NODE_SIZE * CHUNK_SIZE;
2420 x.remove(middle_second_node_start);
2422 x.push_back(0u32);
2426 match x.vector {
2427 VectorInner::Full(_, tree) => {
2428 assert_eq!(3, tree.middle.number_of_children());
2429 assert_eq!(
2430 2 * NODE_SIZE * CHUNK_SIZE + CHUNK_SIZE - 1,
2431 tree.middle.len()
2432 );
2433 }
2434 _ => unreachable!(),
2435 }
2436 }
2437
2438 #[test]
2439 fn issue_77() {
2440 let mut x = Vector::new();
2441 for _ in 0..44 {
2442 x.push_back(0);
2443 }
2444 for _ in 0..20 {
2445 x.insert(0, 0);
2446 }
2447 x.insert(1, 0);
2448 for _ in 0..441 {
2449 x.push_back(0);
2450 }
2451 for _ in 0..58 {
2452 x.insert(0, 0);
2453 }
2454 x.insert(514, 0);
2455 for _ in 0..73 {
2456 x.push_back(0);
2457 }
2458 for _ in 0..10 {
2459 x.insert(0, 0);
2460 }
2461 x.insert(514, 0);
2462 }
2463
2464 #[test]
2465 fn issue_105() {
2466 let mut v = Vector::new();
2467
2468 for i in 0..270_000 {
2469 v.push_front(i);
2470 }
2471
2472 while !v.is_empty() {
2473 v = v.take(v.len() - 1);
2474 }
2475 }
2476
2477 #[test]
2478 fn issue_107_split_off_causes_overflow() {
2479 let mut vec = Vector::from_iter(0..4289);
2480 let mut control = Vec::from_iter(0..4289);
2481 let chunk = 64;
2482
2483 while vec.len() >= chunk {
2484 vec = vec.split_off(chunk);
2485 control = control.split_off(chunk);
2486 assert_eq!(vec.len(), control.len());
2487 assert_eq!(control, vec.iter().cloned().collect::<Vec<_>>());
2488 }
2489 }
2490
2491 #[test]
2492 fn collect_crash() {
2493 let _vector: Vector<i32> = (0..5953).collect();
2494 }
2496
2497 #[test]
2498 fn issue_116() {
2499 let vec = Vector::from_iter(0..300);
2500 let rev_vec: Vector<u32> = vec.clone().into_iter().rev().collect();
2501 assert_eq!(vec.len(), rev_vec.len());
2502 }
2503
2504 #[test]
2505 fn issue_131() {
2506 let smol = core::iter::repeat(42).take(64).collect::<Vector<_>>();
2507 let mut smol2 = smol.clone();
2508 assert!(smol.ptr_eq(&smol2));
2509 smol2.set(63, 420);
2510 assert!(!smol.ptr_eq(&smol2));
2511
2512 let huge = core::iter::repeat(42).take(65).collect::<Vector<_>>();
2513 let mut huge2 = huge.clone();
2514 assert!(huge.ptr_eq(&huge2));
2515 huge2.set(63, 420);
2516 assert!(!huge.ptr_eq(&huge2));
2517 }
2518
2519 #[test]
2520 fn ptr_eq() {
2521 for len in 32..256 {
2522 let input = core::iter::repeat(42).take(len).collect::<Vector<_>>();
2523 let mut inp2 = input.clone();
2524 assert!(input.ptr_eq(&inp2));
2525 inp2.set(len - 1, 98);
2526 assert_ne!(inp2.get(len - 1), input.get(len - 1));
2527 assert!(!input.ptr_eq(&inp2), "{}", len);
2528 }
2529 }
2530
2531 quickcheck! {
2532 fn iter(vec: Vec<i32>) -> bool {
2533 let seq: Vector<i32> = Vector::from_iter(vec.iter().cloned());
2534 let mut res = true;
2535 for (index, item) in seq.iter().enumerate() {
2536 res = res && &vec[index] == item;
2537 }
2538 res && vec.len() == seq.len()
2539 }
2540
2541 fn push_front_mut(input: Vec<i32>) -> bool {
2542 let mut vector = Vector::new();
2543 let mut res = true;
2544 for (count, value) in input.iter().cloned().enumerate() {
2545 res = res && count == vector.len();
2546 vector.push_front(value);
2547 res = res && count + 1 == vector.len();
2548 }
2549 let input2 = Vec::from_iter(input.iter().rev().cloned());
2550 res && input2 == Vec::from_iter(vector.iter().cloned())
2551 }
2552
2553 fn push_back_mut(input: Vec<i32>) -> bool {
2554 let mut vector = Vector::new();
2555 let mut res = true;
2556 for (count, value) in input.iter().cloned().enumerate() {
2557 res = res && count == vector.len();
2558 vector.push_back(value);
2559 res = res && count + 1 == vector.len();
2560 }
2561 res && input == Vec::from_iter(vector.iter().cloned())
2562 }
2563
2564 fn pop_back_mut(input: Vec<i32>) -> bool {
2565 let mut vector = Vector::from_iter(input.iter().cloned());
2566 let mut res = true;
2567 res = res && input.len() == vector.len();
2568 for (index, value) in input.iter().cloned().enumerate().rev() {
2569 match vector.pop_back() {
2570 None => panic!("vector emptied unexpectedly"),
2571 Some(item) => {
2572 res = res && index == vector.len();
2573 res = res && value == item;
2574 }
2575 }
2576 }
2577 res && 0 == vector.len()
2578 }
2579
2580 fn pop_front_mut(input: Vec<i32>) -> bool {
2581 let mut vector = Vector::from_iter(input.iter().cloned());
2582 let mut res = input.len() == vector.len();
2583 for (index, value) in input.iter().cloned().rev().enumerate().rev() {
2584 match vector.pop_front() {
2585 None => panic!("vector emptied unexpectedly"),
2586 Some(item) => {
2587 res = res && index == vector.len()
2588 && value == item;
2589 }
2590 }
2591 }
2592 res && 0 == vector.len()
2593 }
2594
2595 fn push_and_pop(input: Vec<i32>) -> bool {
2596 let mut vector = Vector::new();
2597 let mut res = true;
2598 for (count, value) in input.iter().cloned().enumerate() {
2599 res = res && count == vector.len();
2600 vector.push_back(value);
2601 res = res && count + 1 == vector.len();
2602 }
2603 for (index, value) in input.iter().cloned().rev().enumerate().rev() {
2604 match vector.pop_front() {
2605 None => panic!("vector emptied unexpectedly"),
2606 Some(item) => {
2607 res = res && index == vector.len();
2608 res = res && value == item;
2609 }
2610 }
2611 }
2612 res && vector.is_empty()
2613 }
2614
2615 fn split(vec: Vec<i32>) -> bool {
2616 let split_index = rand::random::<usize>() % (vec.len() + 1);
2617 let mut left = Vector::from_iter(vec.iter().cloned());
2618 let right = left.split_off(split_index);
2619 let mut res = true;
2620 res = res && left.len() == split_index;
2621 res = res && right.len() == vec.len() - split_index;
2622 for (index, item) in left.iter().enumerate() {
2623 res = res && &vec[index] == item;
2624 }
2625 for (index, item) in right.iter().enumerate() {
2626 res = res && &vec[split_index + index] == item;
2627 }
2628 res
2629 }
2630
2631 fn append(vec1: Vec<i32>, vec2: Vec<i32>) -> bool {
2632 let mut seq1 = Vector::from_iter(vec1.iter().cloned());
2633 let seq2 = Vector::from_iter(vec2.iter().cloned());
2634 let mut res = true;
2635 res = res && seq1.len() == vec1.len();
2636 res = res && seq2.len() == vec2.len();
2637 seq1.append(seq2);
2638 let mut vec = vec1.clone();
2639 vec.extend(vec2);
2640 res = res && seq1.len() == vec.len();
2641 for (index, item) in seq1.into_iter().enumerate() {
2642 res = res && vec[index] == item;
2643 }
2644 res
2645 }
2646
2647 fn iter_mut(input: Vector<i32>) -> bool {
2648 let mut vec = input.clone();
2649 {
2650 for p in vec.iter_mut() {
2651 *p = p.overflowing_add(1).0;
2652 }
2653 }
2654 let expected: Vector<i32> = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect();
2655 expected == vec
2656 }
2657
2658 fn focus(input: Vector<i32>) -> bool {
2659 let mut vec = input.clone();
2660 {
2661 let mut focus = vec.focus_mut();
2662 for i in 0..input.len() {
2663 let p = focus.index_mut(i);
2664 *p = p.overflowing_add(1).0;
2665 }
2666 }
2667 let expected: Vector<i32> = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect();
2668 expected == vec
2669 }
2670
2671 fn focus_mut_split(input: Vector<i32>) -> bool {
2672 let mut vec = input.clone();
2673
2674 fn split_down(focus: FocusMut<'_, i32>) {
2675 let len = focus.len();
2676 if len < 8 {
2677 for p in focus {
2678 *p = p.overflowing_add(1).0;
2679 }
2680 } else {
2681 let (left, right) = focus.split_at(len / 2);
2682 split_down(left);
2683 split_down(right);
2684 }
2685 }
2686
2687 split_down(vec.focus_mut());
2688
2689 let expected: Vector<i32> = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect();
2690 expected == vec
2691 }
2692
2693 fn chunks(input: Vector<i32>) -> bool {
2694 let output: Vector<_> = input.leaves().flatten().cloned().collect();
2695 let mut res = true;
2696 res = res && input == output;
2697 let rev_in: Vector<_> = input.iter().rev().cloned().collect();
2698 let rev_out: Vector<_> = input.leaves().rev().map(|c| c.iter().rev()).flatten().cloned().collect();
2699 res && rev_in == rev_out
2700 }
2701
2702 fn chunks_mut(input_src: Vector<i32>) -> bool {
2703 let mut input = input_src.clone();
2704 let mut res = true;
2705 #[allow(clippy::map_clone)]
2706 let output: Vector<_> = input.leaves_mut().flatten().map(|v| *v).collect();
2707 res = res && input == output;
2708 let rev_in: Vector<_> = input.iter().rev().cloned().collect();
2709 let rev_out: Vector<_> = input.leaves_mut().rev().map(|c| c.iter().rev()).flatten().cloned().collect();
2710 res && rev_in == rev_out
2711 }
2712
2713 }
2742}