forked from bodil/im-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector.rs
1819 lines (1666 loc) · 54.6 KB
/
vector.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 vector.
//!
//! This is an implementation of [bitmapped vector tries][bmvt], which
//! offers highly efficient (amortised linear time) index lookups as
//! well as appending elements to, or popping elements off, either
//! side of the vector.
//!
//! This is generally the best data structure if you're looking for
//! something list like. If you don't need lookups or updates by
//! index, but do need fast concatenation of whole lists, you should
//! use the [`CatList`][CatList] instead.
//!
//! If you're familiar with the Clojure variant, this improves on it
//! by being efficiently extensible at the front as well as the back.
//! If you're familiar with [Immutable.js][immutablejs], this is
//! essentially the same, but with easier mutability because Rust has
//! the advantage of direct access to the garbage collector (which in
//! our case is just [`Arc`][Arc]).
//!
//! [bmvt]: https://hypirion.com/musings/understanding-persistent-vector-pt-1
//! [immutablejs]: https://facebook.github.io/immutable-js/
//! [Vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html
//! [Arc]: https://doc.rust-lang.org/std/sync/struct.Arc.html
//! [CatList]: ../catlist/struct.CatList.html
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::fmt::{Debug, Error, Formatter};
use std::hash::{Hash, Hasher};
use std::iter::{FromIterator, Sum};
use std::ops::{Add, Index, IndexMut};
use std::sync::Arc;
use bits::{HASH_BITS, HASH_MASK, HASH_SIZE};
use shared::Shared;
use nodes::vector::{Entry, Node};
/// 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 result = $crate::vector::Vector::new();
$(
result.push_back_mut($x);
)*
result
}};
}
#[derive(Clone, Copy)]
struct Meta {
origin: usize,
capacity: usize,
level: usize,
reverse: bool,
}
impl Default for Meta {
fn default() -> Self {
Meta {
origin: 0,
capacity: 0,
level: HASH_BITS,
reverse: false,
}
}
}
/// A persistent vector of elements of type `A`.
///
/// This is an implementation of [bitmapped vector tries][bmvt], which
/// offers highly efficient index lookups as well as appending
/// elements to, or popping elements off, either side of the vector.
///
/// This is generally the best data structure if you're looking for
/// something list like. If you don't need lookups or updates by
/// index, but do need fast concatenation of whole lists, you should
/// use the [`CatList`][CatList] instead.
///
/// If you're familiar with the Clojure variant, this improves on it
/// by being efficiently extensible at the front as well as the back.
/// If you're familiar with [Immutable.js][immutablejs], this is
/// essentially the same, but with easier mutability because Rust has
/// the advantage of direct access to the garbage collector (which in
/// our case is just [`Arc`][Arc]).
///
/// [bmvt]: https://hypirion.com/musings/understanding-persistent-vector-pt-1
/// [immutablejs]: https://facebook.github.io/immutable-js/
/// [Vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html
/// [Arc]: https://doc.rust-lang.org/std/sync/struct.Arc.html
/// [CatList]: ../catlist/struct.CatList.html
pub struct Vector<A> {
meta: Meta,
root: Arc<Node<A>>,
tail: Arc<Node<A>>,
}
impl<A> Vector<A> {
/// Construct an empty vector.
pub fn new() -> Self {
Vector {
meta: Default::default(),
root: Default::default(),
tail: Default::default(),
}
}
/// Construct a vector with a single value.
pub fn singleton(a: A) -> Self {
let mut tail = Node::new();
tail.push(Entry::Value(a));
Vector {
meta: Default::default(),
root: Default::default(),
tail: Arc::new(tail),
}
}
/// Get the length of a vector.
///
/// Time: O(1)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # fn main() {
/// assert_eq!(5, vector![1, 2, 3, 4, 5].len());
/// # }
/// ```
#[inline]
pub fn len(&self) -> usize {
self.meta.capacity - self.meta.origin
}
/// Test whether a list is empty.
///
/// Time: O(1)
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Get an by-reference iterator over a vector.
///
/// Time: O(log n) per [`next()`][next] call
///
/// [next]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next
#[inline]
pub fn iter(&self) -> Iter<A> {
self.into_iter()
}
/// Get the first element of a vector.
///
/// If the vector is empty, `None` is returned.
///
/// Time: O(log n)
#[inline]
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)
pub fn last(&self) -> Option<&A> {
if self.is_empty() {
None
} else {
self.get(self.len() - 1)
}
}
/// 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)
pub fn get(&self, index: usize) -> Option<&A> {
let i = self.map_index(index)?;
let node = self.node_for(i);
match node.get(i & HASH_MASK as usize) {
Some(&Entry::Value(ref value)) => Some(value),
Some(&Entry::Node(_)) => panic!("Vector::get_ref: encountered node, expected value"),
Some(&Entry::Empty) => panic!("Vector::get_ref: encountered null, expected value"),
None => panic!("Vector::get_ref: unhandled index out of bounds situation!"),
}
}
/// Get the value at index `index` in a vector, directly.
///
/// Panics if the index is out of bounds.
///
/// Time: O(log n)
pub fn get_unwrapped(&self, index: usize) -> &A {
self.get(index).expect("get_unwrapped index out of bounds")
}
}
impl<A: Clone> Vector<A> {
/// Get the vector without the first element.
///
/// If the vector is empty, `None` is returned.
///
/// Time: O(log n)
pub fn tail(&self) -> Option<Vector<A>> {
if self.is_empty() {
None
} else {
let mut v = self.clone();
v.resize(1, self.len() as isize);
Some(v)
}
}
/// Get the vector without the last element.
///
/// If the vector is empty, `None` is returned.
///
/// Time: O(log n)
pub fn init(&self) -> Option<Vector<A>> {
if self.is_empty() {
None
} else {
let mut v = self.clone();
v.resize(0, (self.len() - 1) as isize);
Some(v)
}
}
/// Create a new vector with the value at index `index` updated.
///
/// Panics if the index is out of bounds.
///
/// Time: O(log n)
pub fn set(&self, index: usize, value: A) -> Self {
let i = match self.map_index(index) {
None => panic!("index out of bounds: {} < {}", index, self.len()),
Some(i) => i,
};
if i >= tail_offset(self.meta.capacity) {
let mut tail = (*self.tail).clone();
tail.set(i & HASH_MASK as usize, Entry::Value(value));
self.update_tail(tail)
} else {
self.update_root(
self.root
.set_in(self.meta.level, i, Entry::Value(value)),
)
}
}
/// Update the value at index `index` in a vector.
///
/// Panics if the index is out of bounds.
///
/// This is a copy-on-write operation, so that the parts of the
/// vector's structure which are shared with other vectors will be
/// safely copied before mutating.
///
/// Time: O(log n)
pub fn set_mut(&mut self, index: usize, value: A) {
let i = match self.map_index(index) {
None => panic!("index out of bounds: {} < {}", index, self.len()),
Some(i) => i,
};
if i >= tail_offset(self.meta.capacity) {
let tail = Arc::make_mut(&mut self.tail);
tail.set(i & HASH_MASK as usize, Entry::Value(value));
} else {
let root = Arc::make_mut(&mut self.root);
root.set_in_mut(self.meta.level, 0, i, Entry::Value(value))
}
}
/// Construct a vector with a new value prepended to the end of
/// the current vector.
///
/// Time: O(log n)
pub fn push_back(&self, value: A) -> Self {
let len = self.len();
let mut v = self.clone();
v.resize(0, (len + 1) as isize);
v.set_mut(len, value);
v
}
/// Construct a vector with a new value prepended to the end of
/// the current vector.
///
/// `snoc`, for the curious, is [`cons`][cons] spelled backwards,
/// to denote that it works on the back of the list rather than
/// the front. If you don't find that as clever as whoever coined
/// the term no doubt did, this method is also available as
/// [`push_back()`][push_back].
///
/// Time: O(log n)
///
/// [push_back]: #method.push_back
/// [cons]: #method.cons
#[inline]
pub fn snoc(&self, a: A) -> Self {
self.push_back(a)
}
/// Update a vector in place with a new value prepended to the end
/// of it.
///
/// This is a copy-on-write operation, so that the parts of the
/// vector's structure which are shared with other vectors will be
/// safely copied before mutating.
///
/// Time: O(log n)
pub fn push_back_mut(&mut self, value: A) {
let len = self.len();
self.resize(0, (len + 1) as isize);
self.set_mut(len, value);
}
/// Construct a vector with a new value prepended to the front of
/// the current vector.
///
/// Time: O(log n)
pub fn push_front(&self, value: A) -> Self {
let mut v = self.clone();
v.resize(-1, self.len() as isize);
v.set_mut(0, value);
v
}
/// Construct a vector with a new value prepended to the front of
/// the current vector.
///
/// This is an alias for [push_front], for the Lispers in the
/// house.
///
/// Time: O(log n)
///
/// [push_front]: #method.push_front
#[inline]
pub fn cons(&self, a: A) -> Self {
self.push_front(a)
}
/// Update a vector in place with a new value prepended to the
/// front of it.
///
/// This is a copy-on-write operation, so that the parts of the
/// vector's structure which are shared with other vectors will be
/// safely copied before mutating.
///
/// Time: O(log n)
pub fn push_front_mut(&mut self, value: A) {
let len = self.len();
self.resize(-1, len as isize);
self.set_mut(0, value);
}
/// Get a reference to the last element of a vector, as well as the vector with
/// the last element removed.
///
/// If the vector is empty, [`None`][None] is returned.
///
/// Time: O(log n)
///
/// [None]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
pub fn pop_back(&self) -> Option<(&A, Self)> {
if self.is_empty() {
return None;
}
let val = self.get(self.len() - 1).unwrap();
let mut v = self.clone();
v.resize(0, -1 as isize);
Some((val, v))
}
/// Remove the last element of a vector in place and return it.
///
/// This is a copy-on-write operation, so that the parts of the
/// vector's structure which are shared with other vectors will be
/// safely copied before mutating.
///
/// Time: O(log n)
pub fn pop_back_mut(&mut self) -> Option<A> {
if self.is_empty() {
return None;
}
let val = self.get(self.len() - 1).cloned();
self.resize(0, -1);
val
}
/// Get a reference to the first element of a vector, as well as the vector
/// with the first element removed.
///
/// If the vector is empty, [`None`][None] is returned.
///
/// Time: O(log n)
///
/// [None]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
pub fn pop_front(&self) -> Option<(&A, Self)> {
if self.is_empty() {
return None;
}
let val = self.get(0).unwrap();
let mut v = self.clone();
v.resize(1, self.len() as isize);
Some((val, v))
}
/// Get the head and the tail of a vector.
///
/// If the vector is empty, [`None`][None] is returned.
///
/// This is an alias for [`pop_front`][pop_front].
///
/// Time: O(log n)
///
/// [None]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
/// [pop_front]: #method.pop_front
#[inline]
pub fn uncons(&self) -> Option<(&A, Self)> {
self.pop_front()
}
/// Get the last element of a vector, as well as the vector with the
/// last element removed.
///
/// If the vector is empty, [`None`][None] is returned.
///
/// This is an alias for [`pop_back`][pop_back].
///
/// Time: O(1)*
///
/// [None]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
/// [pop_back]: #method.pop_back
#[inline]
pub fn unsnoc(&self) -> Option<(&A, Self)> {
self.pop_back()
}
/// Remove the first element of a vector in place and return it.
///
/// This is a copy-on-write operation, so that the parts of the
/// vector's structure which are shared with other vectors will be
/// safely copied before mutating.
///
/// Time: O(log n)
pub fn pop_front_mut(&mut self) -> Option<A> {
if self.is_empty() {
return None;
}
let len = self.len();
let val = self.get(0).cloned();
self.resize(1, len as isize);
val
}
/// Split a vector at a given index, returning a vector containing
/// every element before of the index and a vector containing
/// every element from the index onward.
///
/// Time: O(log n)
pub fn split_at(&self, index: usize) -> (Self, Self) {
if index >= self.len() {
return (self.clone(), Vector::new());
}
let mut left = self.clone();
left.resize(0, index as isize);
let mut right = self.clone();
right.resize(index as isize, self.len() as isize);
(left, right)
}
/// Construct a vector with `count` elements removed from the
/// start of the current vector.
///
/// Time: O(log n)
pub fn skip(&self, count: usize) -> Self {
let mut v = self.clone();
v.resize(count as isize, self.len() as isize);
v
}
/// Construct a vector of the first `count` elements from the
/// current vector.
///
/// Time: O(log n)
pub fn take(&self, count: usize) -> Self {
let mut v = self.clone();
v.resize(0, count as isize);
v
}
/// Construct a vector with the elements from `start_index`
/// until `end_index` in the current vector.
///
/// Time: O(log n)
pub fn slice(&self, start_index: usize, end_index: usize) -> Self {
if start_index >= end_index || start_index >= self.len() {
return Vector::new();
}
let mut v = self.clone();
v.resize(start_index as isize, end_index as isize);
v
}
/// Append the vector `other` to the end of the current vector.
///
/// Time: O(n) where n = the length of `other`
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::vector::Vector;
/// # fn main() {
/// assert_eq!(
/// vector![1, 2, 3].append(vector![7, 8, 9]),
/// vector![1, 2, 3, 7, 8, 9]
/// );
/// # }
/// ```
pub fn append<R>(&self, other: R) -> Self
where
R: Borrow<Self>,
{
let o = other.borrow();
let mut v = self.clone();
v.resize(0, (self.len() + o.len()) as isize);
v.write(self.len(), o.clone().into_iter());
v
}
/// Write from an iterator into a vector, starting at the given
/// index.
///
/// This will overwrite elements in the vector until the iterator
/// ends or the end of the vector is reached.
///
/// Time: O(n) where n = the length of the iterator
pub fn write<I: IntoIterator<Item=A>>(&mut self, index: usize, iter: I) {
if let Some(raw_index) = self.map_index(index) {
let cap = self.meta.capacity;
let tail_offset = tail_offset(cap);
let mut it = iter.into_iter();
if raw_index >= tail_offset {
let mut tail = Arc::make_mut(&mut self.tail);
let mut i = raw_index - tail_offset;
loop {
match it.next() {
None => return,
Some(value) => {
tail.set(i, Entry::Value(value));
i += 1;
if tail_offset + i >= cap {
return;
}
}
}
}
} else {
let root = Arc::make_mut(&mut self.root);
let mut max_in_root = tail_offset - raw_index;
root.write(self.meta.level, raw_index, &mut it, &mut max_in_root);
let mut tail = Arc::make_mut(&mut self.tail);
let mut i = 0;
loop {
match it.next() {
None => return,
Some(value) => {
tail.set(i, Entry::Value(value));
i += 1;
if tail_offset + i >= cap {
return;
}
}
}
}
}
}
}
}
impl<A> Vector<A> {
/// Construct a vector which is the reverse of the current vector.
///
/// Time: O(1)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::vector::Vector;
/// # fn main() {
/// assert_eq!(
/// vector![1, 2, 3, 4, 5].reverse(),
/// vector![5, 4, 3, 2, 1]
/// );
/// # }
/// ```
///
/// [rev]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.rev
pub fn reverse(&self) -> Self {
let mut v = self.clone();
v.meta.reverse = !v.meta.reverse;
v
}
/// Reverse a vector in place.
///
/// Time: O(1)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::vector::Vector;
/// # fn main() {
/// let mut v = vector![1, 2, 3, 4, 5];
/// v.reverse_mut();
///
/// assert_eq!(
/// v,
/// vector![5, 4, 3, 2, 1]
/// );
/// # }
/// ```
pub fn reverse_mut(&mut self) {
self.meta.reverse = !self.meta.reverse;
}
}
impl<A: Clone> Vector<A> {
/// Sort a vector of ordered elements.
///
/// Time: O(n log n) worst case
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::vector::Vector;
/// # fn main() {
/// assert_eq!(
/// vector![2, 8, 1, 6, 3, 7, 5, 4].sort(),
/// vector![1, 2, 3, 4, 5, 6, 7, 8]
/// );
/// # }
/// ```
pub fn sort(&self) -> Self
where
A: Ord,
{
self.sort_by(Ord::cmp)
}
/// Sort a vector using a comparator function.
///
/// Time: O(n log n) roughly
pub fn sort_by<F>(&self, cmp: F) -> Self
where
F: Fn(&A, &A) -> Ordering,
{
// FIXME: This is a simple in-place quicksort. There are
// probably faster algorithms.
fn swap<A: Clone>(vector: &mut Vector<A>, a: usize, b: usize) {
let aval = vector.get(a).unwrap().clone();
let bval = vector.get(b).unwrap().clone();
vector.set_mut(a, bval);
vector.set_mut(b, aval);
}
// Ported from the Java version at
// http://www.cs.princeton.edu/~rs/talks/QuicksortIsOptimal.pdf
#[cfg_attr(feature = "clippy", allow(many_single_char_names))]
fn quicksort<A, F>(vector: &mut Vector<A>, l: usize, r: usize, cmp: &F)
where
A: Clone,
F: Fn(&A, &A) -> Ordering,
{
if r <= l {
return;
}
let mut i = l;
let mut j = r;
let mut p = i;
let mut q = j;
let v = vector.get(r).unwrap().clone();
loop {
while cmp(&vector.get_unwrapped(i), &v) == Ordering::Less {
i += 1
}
j -= 1;
while cmp(&v, &vector.get_unwrapped(j)) == Ordering::Less {
if j == l {
break;
}
j -= 1;
}
if i >= j {
break;
}
swap(vector, i, j);
if cmp(&vector.get_unwrapped(i), &v) == Ordering::Equal {
p += 1;
swap(vector, p, i);
}
if cmp(&v, &vector.get_unwrapped(j)) == Ordering::Equal {
q -= 1;
swap(vector, j, q);
}
i += 1;
}
swap(vector, i, r);
let mut jp: isize = i as isize - 1;
let mut k = l;
i += 1;
while k < p {
swap(vector, k, jp as usize);
jp -= 1;
k += 1;
}
k = r - 1;
while k > q {
swap(vector, i, k);
k -= 1;
i += 1;
}
if jp >= 0 {
quicksort(vector, l, jp as usize, cmp);
}
quicksort(vector, i, r, cmp);
}
if self.len() < 2 {
self.clone()
} else {
let mut out = self.clone();
quicksort(&mut out, 0, self.len() - 1, &cmp);
out
}
}
/// Insert an item into a sorted vector.
///
/// Constructs a new vector with the new item inserted before the
/// first item in the vector which is larger than the new item, as
/// determined by the `Ord` trait.
///
/// Please note that this is a very inefficient operation; if you
/// want a sorted list, consider if [`OrdSet`][ordset::OrdSet]
/// might be a better choice for you.
///
/// Time: O(n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # fn main() {
/// assert_eq!(
/// vector![2, 4, 5].insert(1).insert(3).insert(6),
/// vector![1, 2, 3, 4, 5, 6]
/// );
/// # }
/// ```
///
/// [ordset::OrdSet]: ../ordset/struct.OrdSet.html
pub fn insert(&self, item: A) -> Self
where
A: Ord,
{
let mut out = Vector::new();
let mut iter = self.iter();
while let Some(next) = iter.next() {
if next < &item {
out.push_back_mut(next.clone());
} else {
out.push_back_mut(item);
out.push_back_mut(next.clone());
out.extend(iter.map(A::clone));
return out;
}
}
out.push_back_mut(item);
out
}
}
// Implementation details
impl<A> Vector<A> {
fn map_index(&self, index: usize) -> Option<usize> {
let len = self.len();
if index >= len {
return None;
}
Some(
self.meta.origin + if self.meta.reverse {
(len - 1) - index
} else {
index
},
)
}
fn node_for(&self, index: usize) -> &Arc<Node<A>> {
if index >= tail_offset(self.meta.capacity) {
&self.tail
} else {
let mut node = &self.root;
let mut level = self.meta.level;
while level > 0 {
node = if let Some(&Entry::Node(ref child_node)) =
node.children.get((index >> level) & HASH_MASK as usize)
{
level -= HASH_BITS;
child_node
} else {
panic!("Vector::node_for: encountered value or null where node was expected")
};
}
node
}
}
fn clear(&mut self) {
self.meta = Default::default();
self.root = Default::default();
self.tail = Default::default();
}
}
impl<A: Clone> Vector<A> {
fn resize(&mut self, mut start: isize, mut end: isize) {
if self.meta.reverse {
let len = self.len() as isize;
let swap = start;
start = if end < 0 { 0 } else { len } - end;
end = len - swap;
}
let mut o0 = self.meta.origin;
let mut c0 = self.meta.capacity;
let mut o = o0 as isize + start;
let mut c = if end < 0 {
c0 as isize + end
} else {
o0 as isize + end
} as usize;
if o == o0 as isize && c == c0 {
return;
}
if o >= c as isize {
self.clear();
return;
}
let mut level = self.meta.level;
// Create higher level roots until origin is positive
let mut origin_shift = 0;
while o + origin_shift < 0 {
if self.root.is_empty() {
self.root = Default::default()
} else {
self.root = Arc::new(Node::from_vec(
Some(1),
vec![Entry::Empty, Entry::Node(self.root.clone())],
));
}
level += HASH_BITS;
origin_shift += 1 << level;
}
if origin_shift > 0 {
o0 += origin_shift as usize;
c0 += origin_shift as usize;
o += origin_shift;
c += origin_shift as usize;
}
// Create higher level roots until size fits
let tail_offset0 = tail_offset(c0);
let tail_offset = tail_offset(c as usize);
while tail_offset >= 1 << (level + HASH_BITS) {
if self.root.is_empty() {
self.root = Default::default()
} else {
self.root = Arc::new(Node::from_vec(
Some(0),
vec![Entry::Node(self.root.clone())],
));
}
level += HASH_BITS;
}
// Merge old tail into tree
if tail_offset > tail_offset0 && (o as usize) < c0 && !self.tail.is_empty() {
let root = Arc::make_mut(&mut self.root);
root.set_in_mut(
level,
HASH_BITS,
tail_offset0,
Entry::Node(self.tail.clone()),
);
}
// Find the new tail
if tail_offset < tail_offset0 {
self.tail = self.node_for(c - 1).clone()
} else if tail_offset > tail_offset0 {
self.tail = Default::default()
}
// Trim new tail if needed
if c < c0 {
let t = Arc::make_mut(&mut self.tail);
t.remove_after(0, c);
}
// If new origin is inside tail, drop the root
if o as usize >= tail_offset {
o -= tail_offset as isize;
c -= tail_offset;
level = HASH_BITS;
self.root = Default::default();
let tail = Arc::make_mut(&mut self.tail);
tail.remove_before(0, o as usize);
} else if o as usize > o0 || tail_offset < tail_offset0 {
// If root has been trimmed, clean it up.
let mut shift = 0;
// Find the top root node inside the old tree.
loop {
let start_index = (o as usize >> level) & HASH_MASK as usize;
if start_index != (tail_offset >> level) & HASH_MASK as usize {
break;
}
if start_index != 0 {
shift += (1 << level) * start_index;
}
level -= HASH_BITS;
self.root = self.root.get(start_index).unwrap().unwrap_node();
}
// Trim the edges of the root.
if o as usize > o0 {
let root = Arc::make_mut(&mut self.root);
root.remove_before(level, o as usize - shift);
}
if tail_offset < tail_offset0 {
let root = Arc::make_mut(&mut self.root);
root.remove_after(level, tail_offset - shift);
}
if shift > 0 {
o -= shift as isize;
c -= shift;
}
}
self.meta.level = level;
self.meta.origin = o as usize;
self.meta.capacity = c;
}
fn update_root<Root: Shared<Node<A>>>(&self, root: Root) -> Self {
Vector {
meta: self.meta,
root: root.shared(),
tail: self.tail.clone(),
}
}