-
Notifications
You must be signed in to change notification settings - Fork 111
/
mod.rs
2745 lines (2523 loc) · 85.9 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//! A persistent vector.
//!
//! This is a sequence of elements in insertion order - if you need a
//! list of things, any kind of list of things, this is what you're
//! looking for.
//!
//! It's implemented as an [RRB vector][rrbpaper] with [smart
//! head/tail chunking][chunkedseq]. In performance terms, this means
//! that practically every operation is O(log n), except push/pop on
//! both sides, which will be O(1) amortised, and O(log n) in the
//! worst case. In practice, the push/pop operations will be
//! blindingly fast, nearly on par with the native
//! [`VecDeque`][VecDeque], and other operations will have decent, if
//! not high, performance, but they all have more or less the same
//! O(log n) complexity, so you don't need to keep their performance
//! characteristics in mind - everything, even splitting and merging,
//! is safe to use and never too slow.
//!
//! ## Performance Notes
//!
//! Because of the head/tail chunking technique, until you push a
//! number of items above double the tree's branching factor (that's
//! `self.len()` = 2 × *k* (where *k* = 64) = 128) on either side, the
//! data structure is still just a handful of arrays, not yet an RRB
//! tree, so you'll see performance and memory characteristics fairly
//! close to [`Vec`][Vec] or [`VecDeque`][VecDeque].
//!
//! This means that the structure always preallocates four chunks of
//! size *k* (*k* being the tree's branching factor), equivalent to a
//! [`Vec`][Vec] with an initial capacity of 256. Beyond that, it will
//! allocate tree nodes of capacity *k* as needed.
//!
//! In addition, vectors start out as single chunks, and only expand into the
//! full data structure once you go past the chunk size. This makes them
//! perform identically to [`Vec`][Vec] at small sizes.
//!
//! [rrbpaper]: https://infoscience.epfl.ch/record/213452/files/rrbvector.pdf
//! [chunkedseq]: http://deepsea.inria.fr/pasl/chunkedseq.pdf
//! [Vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html
//! [VecDeque]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::fmt::{Debug, Error, Formatter};
use std::hash::{Hash, Hasher};
use std::iter::Sum;
use std::iter::{FromIterator, FusedIterator};
use std::mem::{replace, swap};
use std::ops::{Add, Index, IndexMut, RangeBounds};
use sized_chunks::InlineArray;
use crate::nodes::chunk::{Chunk, CHUNK_SIZE};
use crate::nodes::rrb::{Node, PopResult, PushResult, SplitResult};
use crate::sort;
use crate::util::{clone_ref, swap_indices, to_range, Pool, PoolDefault, PoolRef, Ref, Side};
use self::VectorInner::{Full, Inline, Single};
mod focus;
pub use self::focus::{Focus, FocusMut};
mod pool;
pub use self::pool::RRBPool;
#[cfg(all(threadsafe, any(test, feature = "rayon")))]
pub mod rayon;
/// Construct a vector from a sequence of elements.
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::vector::Vector;
/// # fn main() {
/// assert_eq!(
/// vector![1, 2, 3],
/// Vector::from(vec![1, 2, 3])
/// );
/// # }
/// ```
#[macro_export]
macro_rules! vector {
() => { $crate::vector::Vector::new() };
( $($x:expr),* ) => {{
let mut l = $crate::vector::Vector::new();
$(
l.push_back($x);
)*
l
}};
( $($x:expr ,)* ) => {{
let mut l = $crate::vector::Vector::new();
$(
l.push_back($x);
)*
l
}};
}
/// A persistent vector.
///
/// This is a sequence of elements in insertion order - if you need a list of
/// things, any kind of list of things, this is what you're looking for.
///
/// It's implemented as an [RRB vector][rrbpaper] with [smart head/tail
/// chunking][chunkedseq]. In performance terms, this means that practically
/// every operation is O(log n), except push/pop on both sides, which will be
/// O(1) amortised, and O(log n) in the worst case. In practice, the push/pop
/// operations will be blindingly fast, nearly on par with the native
/// [`VecDeque`][VecDeque], and other operations will have decent, if not high,
/// performance, but they all have more or less the same O(log n) complexity, so
/// you don't need to keep their performance characteristics in mind -
/// everything, even splitting and merging, is safe to use and never too slow.
///
/// ## Performance Notes
///
/// Because of the head/tail chunking technique, until you push a number of
/// items above double the tree's branching factor (that's `self.len()` = 2 ×
/// *k* (where *k* = 64) = 128) on either side, the data structure is still just
/// a handful of arrays, not yet an RRB tree, so you'll see performance and
/// memory characteristics similar to [`Vec`][Vec] or [`VecDeque`][VecDeque].
///
/// This means that the structure always preallocates four chunks of size *k*
/// (*k* being the tree's branching factor), equivalent to a [`Vec`][Vec] with
/// an initial capacity of 256. Beyond that, it will allocate tree nodes of
/// capacity *k* as needed.
///
/// In addition, vectors start out as single chunks, and only expand into the
/// full data structure once you go past the chunk size. This makes them
/// perform identically to [`Vec`][Vec] at small sizes.
///
/// [rrbpaper]: https://infoscience.epfl.ch/record/213452/files/rrbvector.pdf
/// [chunkedseq]: http://deepsea.inria.fr/pasl/chunkedseq.pdf
/// [Vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html
/// [VecDeque]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html
pub struct Vector<A> {
vector: VectorInner<A>,
}
enum VectorInner<A> {
Inline(RRBPool<A>, InlineArray<A, Rrb<A>>),
Single(RRBPool<A>, PoolRef<Chunk<A>>),
Full(RRBPool<A>, Rrb<A>),
}
#[doc(hidden)]
pub struct Rrb<A> {
length: usize,
middle_level: usize,
outer_f: PoolRef<Chunk<A>>,
inner_f: PoolRef<Chunk<A>>,
middle: Ref<Node<A>>,
inner_b: PoolRef<Chunk<A>>,
outer_b: PoolRef<Chunk<A>>,
}
impl<A> Clone for Rrb<A> {
fn clone(&self) -> Self {
Rrb {
length: self.length,
middle_level: self.middle_level,
outer_f: self.outer_f.clone(),
inner_f: self.inner_f.clone(),
middle: self.middle.clone(),
inner_b: self.inner_b.clone(),
outer_b: self.outer_b.clone(),
}
}
}
impl<A: Clone> Vector<A> {
/// Get a reference to the memory pool this `Vector` is using.
///
/// Note that if you didn't specifically construct it with a pool, you'll
/// get back a reference to a pool of size 0.
#[cfg_attr(not(feature = "pool"), doc(hidden))]
pub fn pool(&self) -> &RRBPool<A> {
match self.vector {
Inline(ref pool, _) => pool,
Single(ref pool, _) => pool,
Full(ref pool, _) => pool,
}
}
/// True if a vector is a full inline or single chunk, ie. must be promoted
/// to grow further.
fn needs_promotion(&self) -> bool {
match &self.vector {
Inline(_, chunk) if chunk.is_full() => true,
Single(_, chunk) if chunk.is_full() => true,
_ => false,
}
}
/// Promote an inline to a single.
fn promote_inline(&mut self) {
if let Inline(pool, chunk) = &mut self.vector {
self.vector = Single(pool.clone(), PoolRef::new(&pool.value_pool, chunk.into()));
}
}
/// Promote a single to a full, with the single chunk becoming inner_f, or
/// promote an inline to a single.
fn promote_front(&mut self) {
self.vector = match &mut self.vector {
Inline(pool, chunk) => {
Single(pool.clone(), PoolRef::new(&pool.value_pool, chunk.into()))
}
Single(pool, chunk) => {
let chunk = chunk.clone();
Full(
pool.clone(),
Rrb {
length: chunk.len(),
middle_level: 0,
outer_f: PoolRef::default(&pool.value_pool),
inner_f: chunk,
middle: Ref::new(Node::new()),
inner_b: PoolRef::default(&pool.value_pool),
outer_b: PoolRef::default(&pool.value_pool),
},
)
}
Full(_, _) => return,
}
}
/// Promote a single to a full, with the single chunk becoming inner_b, or
/// promote an inline to a single.
fn promote_back(&mut self) {
self.vector = match &mut self.vector {
Inline(pool, chunk) => {
Single(pool.clone(), PoolRef::new(&pool.value_pool, chunk.into()))
}
Single(pool, chunk) => {
let chunk = chunk.clone();
Full(
pool.clone(),
Rrb {
length: chunk.len(),
middle_level: 0,
outer_f: PoolRef::default(&pool.value_pool),
inner_f: PoolRef::default(&pool.value_pool),
middle: Ref::new(Node::new()),
inner_b: chunk,
outer_b: PoolRef::default(&pool.value_pool),
},
)
}
Full(_, _) => return,
}
}
/// Construct an empty vector.
#[must_use]
pub fn new() -> Self {
Self {
vector: Inline(RRBPool::default(), InlineArray::new()),
}
}
/// Construct an empty vector using a specific memory pool.
#[cfg(feature = "pool")]
#[must_use]
pub fn with_pool(pool: &RRBPool<A>) -> Self {
Self {
vector: Inline(pool.clone(), InlineArray::new()),
}
}
/// Get the length of a vector.
///
/// Time: O(1)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// assert_eq!(5, vector![1, 2, 3, 4, 5].len());
/// ```
#[inline]
#[must_use]
pub fn len(&self) -> usize {
match &self.vector {
Inline(_, chunk) => chunk.len(),
Single(_, chunk) => chunk.len(),
Full(_, tree) => tree.length,
}
}
/// Test whether a vector is empty.
///
/// Time: O(1)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::Vector;
/// let vec = vector!["Joe", "Mike", "Robert"];
/// assert_eq!(false, vec.is_empty());
/// assert_eq!(true, Vector::<i32>::new().is_empty());
/// ```
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Test whether a vector is currently inlined.
///
/// Vectors small enough that their contents could be stored entirely inside
/// the space of `std::mem::size_of::<Vector<A>>()` bytes are stored inline on
/// the stack instead of allocating any chunks. This method returns `true` if
/// this vector is currently inlined, or `false` if it currently has chunks allocated
/// on the heap.
///
/// This may be useful in conjunction with [`ptr_eq()`][ptr_eq], which checks if
/// two vectors' heap allocations are the same, and thus will never return `true`
/// for inlined vectors.
///
/// Time: O(1)
///
/// [ptr_eq]: #method.ptr_eq
#[inline]
#[must_use]
pub fn is_inline(&self) -> bool {
matches!(&self.vector, Inline(_, _))
}
/// Test whether two vectors refer to the same content in memory.
///
/// This uses the following rules to determine equality:
/// * If the two sides are references to the same vector, return true.
/// * If the two sides are single chunk vectors pointing to the same chunk, return true.
/// * If the two sides are full trees pointing to the same chunks, return true.
///
/// This would return true if you're comparing a vector to itself, or
/// if you're comparing a vector to a fresh clone of itself. The exception to this is
/// if you've cloned an inline array (ie. an array with so few elements they can fit
/// inside the space a `Vector` allocates for its pointers, so there are no heap allocations
/// to compare).
///
/// Time: O(1)
#[must_use]
pub fn ptr_eq(&self, other: &Self) -> bool {
fn cmp_chunk<A>(left: &PoolRef<Chunk<A>>, right: &PoolRef<Chunk<A>>) -> bool {
(left.is_empty() && right.is_empty()) || PoolRef::ptr_eq(left, right)
}
if std::ptr::eq(self, other) {
return true;
}
match (&self.vector, &other.vector) {
(Single(_, left), Single(_, right)) => cmp_chunk(left, right),
(Full(_, left), Full(_, right)) => {
cmp_chunk(&left.outer_f, &right.outer_f)
&& cmp_chunk(&left.inner_f, &right.inner_f)
&& cmp_chunk(&left.inner_b, &right.inner_b)
&& cmp_chunk(&left.outer_b, &right.outer_b)
&& ((left.middle.is_empty() && right.middle.is_empty())
|| Ref::ptr_eq(&left.middle, &right.middle))
}
_ => false,
}
}
/// Get an iterator over a vector.
///
/// Time: O(1)
#[inline]
#[must_use]
pub fn iter(&self) -> Iter<'_, A> {
Iter::new(self)
}
/// Get a mutable iterator over a vector.
///
/// Time: O(1)
#[inline]
#[must_use]
pub fn iter_mut(&mut self) -> IterMut<'_, A> {
IterMut::new(self)
}
/// Get an iterator over the leaf nodes of a vector.
///
/// This returns an iterator over the [`Chunk`s][Chunk] at the leaves of the
/// RRB tree. These are useful for efficient parallelisation of work on
/// the vector, but should not be used for basic iteration.
///
/// Time: O(1)
///
/// [Chunk]: ../chunk/struct.Chunk.html
#[inline]
#[must_use]
pub fn leaves(&self) -> Chunks<'_, A> {
Chunks::new(self)
}
/// Get a mutable iterator over the leaf nodes of a vector.
//
/// This returns an iterator over the [`Chunk`s][Chunk] at the leaves of the
/// RRB tree. These are useful for efficient parallelisation of work on
/// the vector, but should not be used for basic iteration.
///
/// Time: O(1)
///
/// [Chunk]: ../chunk/struct.Chunk.html
#[inline]
#[must_use]
pub fn leaves_mut(&mut self) -> ChunksMut<'_, A> {
ChunksMut::new(self)
}
/// Construct a [`Focus`][Focus] for a vector.
///
/// Time: O(1)
///
/// [Focus]: enum.Focus.html
#[inline]
#[must_use]
pub fn focus(&self) -> Focus<'_, A> {
Focus::new(self)
}
/// Construct a [`FocusMut`][FocusMut] for a vector.
///
/// Time: O(1)
///
/// [FocusMut]: enum.FocusMut.html
#[inline]
#[must_use]
pub fn focus_mut(&mut self) -> FocusMut<'_, A> {
FocusMut::new(self)
}
/// Get a reference to the value at index `index` in a vector.
///
/// Returns `None` if the index is out of bounds.
///
/// Time: O(log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::Vector;
/// let vec = vector!["Joe", "Mike", "Robert"];
/// assert_eq!(Some(&"Robert"), vec.get(2));
/// assert_eq!(None, vec.get(5));
/// ```
#[must_use]
pub fn get(&self, index: usize) -> Option<&A> {
if index >= self.len() {
return None;
}
match &self.vector {
Inline(_, chunk) => chunk.get(index),
Single(_, chunk) => chunk.get(index),
Full(_, tree) => {
let mut local_index = index;
if local_index < tree.outer_f.len() {
return Some(&tree.outer_f[local_index]);
}
local_index -= tree.outer_f.len();
if local_index < tree.inner_f.len() {
return Some(&tree.inner_f[local_index]);
}
local_index -= tree.inner_f.len();
if local_index < tree.middle.len() {
return Some(tree.middle.index(tree.middle_level, local_index));
}
local_index -= tree.middle.len();
if local_index < tree.inner_b.len() {
return Some(&tree.inner_b[local_index]);
}
local_index -= tree.inner_b.len();
Some(&tree.outer_b[local_index])
}
}
}
/// Get a mutable reference to the value at index `index` in a
/// vector.
///
/// Returns `None` if the index is out of bounds.
///
/// Time: O(log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::Vector;
/// let mut vec = vector!["Joe", "Mike", "Robert"];
/// {
/// let robert = vec.get_mut(2).unwrap();
/// assert_eq!(&mut "Robert", robert);
/// *robert = "Bjarne";
/// }
/// assert_eq!(vector!["Joe", "Mike", "Bjarne"], vec);
/// ```
#[must_use]
pub fn get_mut(&mut self, index: usize) -> Option<&mut A> {
if index >= self.len() {
return None;
}
match &mut self.vector {
Inline(_, chunk) => chunk.get_mut(index),
Single(pool, chunk) => PoolRef::make_mut(&pool.value_pool, chunk).get_mut(index),
Full(pool, tree) => {
let mut local_index = index;
if local_index < tree.outer_f.len() {
let outer_f = PoolRef::make_mut(&pool.value_pool, &mut tree.outer_f);
return Some(&mut outer_f[local_index]);
}
local_index -= tree.outer_f.len();
if local_index < tree.inner_f.len() {
let inner_f = PoolRef::make_mut(&pool.value_pool, &mut tree.inner_f);
return Some(&mut inner_f[local_index]);
}
local_index -= tree.inner_f.len();
if local_index < tree.middle.len() {
let middle = Ref::make_mut(&mut tree.middle);
return Some(middle.index_mut(pool, tree.middle_level, local_index));
}
local_index -= tree.middle.len();
if local_index < tree.inner_b.len() {
let inner_b = PoolRef::make_mut(&pool.value_pool, &mut tree.inner_b);
return Some(&mut inner_b[local_index]);
}
local_index -= tree.inner_b.len();
let outer_b = PoolRef::make_mut(&pool.value_pool, &mut tree.outer_b);
Some(&mut outer_b[local_index])
}
}
}
/// Get the first element of a vector.
///
/// If the vector is empty, `None` is returned.
///
/// Time: O(log n)
#[inline]
#[must_use]
pub fn front(&self) -> Option<&A> {
self.get(0)
}
/// Get a mutable reference to the first element of a vector.
///
/// If the vector is empty, `None` is returned.
///
/// Time: O(log n)
#[inline]
#[must_use]
pub fn front_mut(&mut self) -> Option<&mut A> {
self.get_mut(0)
}
/// Get the first element of a vector.
///
/// If the vector is empty, `None` is returned.
///
/// This is an alias for the [`front`][front] method.
///
/// Time: O(log n)
///
/// [front]: #method.front
#[inline]
#[must_use]
pub fn head(&self) -> Option<&A> {
self.get(0)
}
/// Get the last element of a vector.
///
/// If the vector is empty, `None` is returned.
///
/// Time: O(log n)
#[must_use]
pub fn back(&self) -> Option<&A> {
if self.is_empty() {
None
} else {
self.get(self.len() - 1)
}
}
/// Get a mutable reference to the last element of a vector.
///
/// If the vector is empty, `None` is returned.
///
/// Time: O(log n)
#[must_use]
pub fn back_mut(&mut self) -> Option<&mut A> {
if self.is_empty() {
None
} else {
let len = self.len();
self.get_mut(len - 1)
}
}
/// Get the last element of a vector.
///
/// If the vector is empty, `None` is returned.
///
/// This is an alias for the [`back`][back] method.
///
/// Time: O(log n)
///
/// [back]: #method.back
#[inline]
#[must_use]
pub fn last(&self) -> Option<&A> {
self.back()
}
/// Get the index of a given element in the vector.
///
/// Searches the vector for the first occurrence of a given value,
/// and returns the index of the value if it's there. Otherwise,
/// it returns `None`.
///
/// Time: O(n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::Vector;
/// let mut vec = vector![1, 2, 3, 4, 5];
/// assert_eq!(Some(2), vec.index_of(&3));
/// assert_eq!(None, vec.index_of(&31337));
/// ```
#[must_use]
pub fn index_of(&self, value: &A) -> Option<usize>
where
A: PartialEq,
{
for (index, item) in self.iter().enumerate() {
if value == item {
return Some(index);
}
}
None
}
/// Test if a given element is in the vector.
///
/// Searches the vector for the first occurrence of a given value,
/// and returns `true` if it's there. If it's nowhere to be found
/// in the vector, it returns `false`.
///
/// Time: O(n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::Vector;
/// let mut vec = vector![1, 2, 3, 4, 5];
/// assert_eq!(true, vec.contains(&3));
/// assert_eq!(false, vec.contains(&31337));
/// ```
#[inline]
#[must_use]
pub fn contains(&self, value: &A) -> bool
where
A: PartialEq,
{
self.index_of(value).is_some()
}
/// Discard all elements from the vector.
///
/// This leaves you with an empty vector, and all elements that
/// were previously inside it are dropped.
///
/// Time: O(n)
pub fn clear(&mut self) {
if !self.is_empty() {
self.vector = Inline(self.pool().clone(), InlineArray::new());
}
}
/// Binary search a sorted vector for a given element using a comparator
/// function.
///
/// Assumes the vector has already been sorted using the same comparator
/// function, eg. by using [`sort_by`][sort_by].
///
/// If the value is found, it returns `Ok(index)` where `index` is the index
/// of the element. If the value isn't found, it returns `Err(index)` where
/// `index` is the index at which the element would need to be inserted to
/// maintain sorted order.
///
/// Time: O(log n)
///
/// [sort_by]: #method.sort_by
pub fn binary_search_by<F>(&self, mut f: F) -> Result<usize, usize>
where
F: FnMut(&A) -> Ordering,
{
let mut size = self.len();
if size == 0 {
return Err(0);
}
let mut base = 0;
while size > 1 {
let half = size / 2;
let mid = base + half;
base = match f(&self[mid]) {
Ordering::Greater => base,
_ => mid,
};
size -= half;
}
match f(&self[base]) {
Ordering::Equal => Ok(base),
Ordering::Greater => Err(base),
Ordering::Less => Err(base + 1),
}
}
/// Binary search a sorted vector for a given element.
///
/// If the value is found, it returns `Ok(index)` where `index` is the index
/// of the element. If the value isn't found, it returns `Err(index)` where
/// `index` is the index at which the element would need to be inserted to
/// maintain sorted order.
///
/// Time: O(log n)
pub fn binary_search(&self, value: &A) -> Result<usize, usize>
where
A: Ord,
{
self.binary_search_by(|e| e.cmp(value))
}
/// Binary search a sorted vector for a given element with a key extract
/// function.
///
/// Assumes the vector has already been sorted using the same key extract
/// function, eg. by using [`sort_by_key`][sort_by_key].
///
/// If the value is found, it returns `Ok(index)` where `index` is the index
/// of the element. If the value isn't found, it returns `Err(index)` where
/// `index` is the index at which the element would need to be inserted to
/// maintain sorted order.
///
/// Time: O(log n)
///
/// [sort_by_key]: #method.sort_by_key
pub fn binary_search_by_key<B, F>(&self, b: &B, mut f: F) -> Result<usize, usize>
where
F: FnMut(&A) -> B,
B: Ord,
{
self.binary_search_by(|k| f(k).cmp(b))
}
}
impl<A: Clone> Vector<A> {
/// Construct a vector with a single value.
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::vector::Vector;
/// let vec = Vector::unit(1337);
/// assert_eq!(1, vec.len());
/// assert_eq!(
/// vec.get(0),
/// Some(&1337)
/// );
/// ```
#[inline]
#[must_use]
pub fn unit(a: A) -> Self {
let pool = RRBPool::default();
if InlineArray::<A, Rrb<A>>::CAPACITY > 0 {
let mut array = InlineArray::new();
array.push(a);
Self {
vector: Inline(pool, array),
}
} else {
let chunk = PoolRef::new(&pool.value_pool, Chunk::unit(a));
Self {
vector: Single(pool, chunk),
}
}
}
/// Create a new vector with the value at index `index` updated.
///
/// Panics if the index is out of bounds.
///
/// Time: O(log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::Vector;
/// let mut vec = vector![1, 2, 3];
/// assert_eq!(vector![1, 5, 3], vec.update(1, 5));
/// ```
#[must_use]
pub fn update(&self, index: usize, value: A) -> Self {
let mut out = self.clone();
out[index] = value;
out
}
/// Update the value at index `index` in a vector.
///
/// Returns the previous value at the index.
///
/// Panics if the index is out of bounds.
///
/// Time: O(log n)
#[inline]
pub fn set(&mut self, index: usize, value: A) -> A {
replace(&mut self[index], value)
}
/// Swap the elements at indices `i` and `j`.
///
/// Time: O(log n)
pub fn swap(&mut self, i: usize, j: usize) {
swap_indices(self, i, j)
}
/// Push a value to the front of a vector.
///
/// Time: O(1)*
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::Vector;
/// let mut vec = vector![5, 6, 7];
/// vec.push_front(4);
/// assert_eq!(vector![4, 5, 6, 7], vec);
/// ```
pub fn push_front(&mut self, value: A) {
if self.needs_promotion() {
self.promote_back();
}
match &mut self.vector {
Inline(_, chunk) => {
chunk.insert(0, value);
}
Single(pool, chunk) => PoolRef::make_mut(&pool.value_pool, chunk).push_front(value),
Full(pool, tree) => tree.push_front(pool, value),
}
}
/// Push a value to the back of a vector.
///
/// Time: O(1)*
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::Vector;
/// let mut vec = vector![1, 2, 3];
/// vec.push_back(4);
/// assert_eq!(vector![1, 2, 3, 4], vec);
/// ```
pub fn push_back(&mut self, value: A) {
if self.needs_promotion() {
self.promote_front();
}
match &mut self.vector {
Inline(_, chunk) => {
chunk.push(value);
}
Single(pool, chunk) => PoolRef::make_mut(&pool.value_pool, chunk).push_back(value),
Full(pool, tree) => tree.push_back(pool, value),
}
}
/// Remove the first element from a vector and return it.
///
/// Time: O(1)*
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::Vector;
/// let mut vec = vector![1, 2, 3];
/// assert_eq!(Some(1), vec.pop_front());
/// assert_eq!(vector![2, 3], vec);
/// ```
pub fn pop_front(&mut self) -> Option<A> {
if self.is_empty() {
None
} else {
match &mut self.vector {
Inline(_, chunk) => chunk.remove(0),
Single(pool, chunk) => Some(PoolRef::make_mut(&pool.value_pool, chunk).pop_front()),
Full(pool, tree) => tree.pop_front(pool),
}
}
}
/// Remove the last element from a vector and return it.
///
/// Time: O(1)*
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::Vector;
/// let mut vec = vector![1, 2, 3];
/// assert_eq!(Some(3), vec.pop_back());
/// assert_eq!(vector![1, 2], vec);
/// ```
pub fn pop_back(&mut self) -> Option<A> {
if self.is_empty() {
None
} else {
match &mut self.vector {
Inline(_, chunk) => chunk.pop(),
Single(pool, chunk) => Some(PoolRef::make_mut(&pool.value_pool, chunk).pop_back()),
Full(pool, tree) => tree.pop_back(pool),
}
}
}
/// Append the vector `other` to the end of the current vector.
///
/// Time: O(log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::vector::Vector;
/// let mut vec = vector![1, 2, 3];
/// vec.append(vector![7, 8, 9]);
/// assert_eq!(vector![1, 2, 3, 7, 8, 9], vec);
/// ```
pub fn append(&mut self, mut other: Self) {
if other.is_empty() {
return;
}
if self.is_empty() {
*self = other;
return;
}
self.promote_inline();
other.promote_inline();
let total_length = self
.len()
.checked_add(other.len())
.expect("Vector length overflow");
match &mut self.vector {
Inline(_, _) => unreachable!("inline vecs should have been promoted"),
Single(pool, left) => {
match &mut other.vector {
Inline(_, _) => unreachable!("inline vecs should have been promoted"),
// If both are single chunks and left has room for right: directly
// memcpy right into left