forked from senderista/rotated-array-set
/
lib.rs
1802 lines (1702 loc) · 60.7 KB
/
lib.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
//! An ordered set based on a 2-level rotated array.
//!
//! See <a href="https://github.com/senderista/rotated-array-set/blob/master/README.md">the repository README</a> for a detailed discussion of this collection's performance
//! benefits and drawbacks.
#![doc(html_root_url = "https://docs.rs/rotated-array-set/0.1.0/rotated_array_set/")]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/senderista/rotated-array-set/master/img/cells.png"
)]
use std::cmp::Ordering::{self, Equal, Greater, Less};
use std::cmp::{max, min};
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
use std::iter::{DoubleEndedIterator, ExactSizeIterator, FromIterator, FusedIterator, Peekable};
use std::mem;
use std::ops::Bound::{Excluded, Included, Unbounded};
use std::ops::RangeBounds;
// remove when Iterator::is_sorted is stabilized
use is_sorted::IsSorted;
/// An ordered set based on a 2-level rotated array.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// // Type inference lets us omit an explicit type signature (which
/// // would be `RotatedArraySet<i32>` in this example).
/// let mut ints = RotatedArraySet::new();
///
/// // Add some integers.
/// ints.insert(-1);
/// ints.insert(6);
/// ints.insert(1729);
/// ints.insert(24);
///
/// // Check for a specific one.
/// if !ints.contains(&42) {
/// println!("We don't have the answer to Life, the Universe, and Everything :-(");
/// }
///
/// // Remove an integer.
/// ints.remove(&6);
///
/// // Iterate over everything.
/// for int in &ints {
/// println!("{}", int);
/// }
/// ```
#[derive(Debug, Clone)]
pub struct RotatedArraySet<T> {
data: Vec<T>,
min_indexes: Vec<usize>,
min_data: Vec<T>,
}
// Internal encapsulation of container + bounds
#[derive(Debug, Copy, Clone)]
struct Range<'a, T: 'a> {
container: &'a RotatedArraySet<T>,
start_index_inclusive: usize,
end_index_exclusive: usize,
}
impl<'a, T> Range<'a, T>
where
T: Ord + Copy + Default + Debug,
{
fn with_bounds(
container: &'a RotatedArraySet<T>,
start_index_inclusive: usize,
end_index_exclusive: usize,
) -> Range<'a, T> {
assert!(end_index_exclusive >= start_index_inclusive);
assert!(end_index_exclusive <= container.len());
Range {
container,
start_index_inclusive,
end_index_exclusive,
}
}
fn new(container: &'a RotatedArraySet<T>) -> Range<'a, T> {
Range::with_bounds(container, 0, container.len())
}
fn at(&self, index: usize) -> Option<&'a T> {
let container_idx = index + self.start_index_inclusive;
self.container.select(container_idx)
}
fn len(&self) -> usize {
self.end_index_exclusive - self.start_index_inclusive
}
}
/// An iterator over the items of a `RotatedArraySet`.
///
/// This `struct` is created by the [`iter`] method on [`RotatedArraySet`][`RotatedArraySet`].
/// See its documentation for more.
///
/// [`RotatedArraySet`]: struct.RotatedArraySet.html
/// [`iter`]: struct.RotatedArraySet.html#method.iter
#[derive(Debug, Copy, Clone)]
pub struct Iter<'a, T: 'a> {
range: Range<'a, T>,
next_index: usize,
next_rev_index: usize,
}
impl<'a, T> Iter<'a, T>
where
T: Ord + Copy + Default + Debug,
{
fn new(range: Range<'a, T>) -> Iter<'a, T> {
let next_index = 0;
let next_rev_index = if range.len() == 0 { 0 } else { range.len() - 1 };
Iter {
range,
next_index,
next_rev_index,
}
}
#[inline(always)]
fn assert_invariants(&self) -> bool {
assert!(self.next_index <= self.range.len());
assert!(self.next_rev_index <= self.range.len());
if self.next_rev_index < self.next_index {
assert!(self.next_index - self.next_rev_index == 1);
}
true
}
}
/// An owning iterator over the items of a `RotatedArraySet`.
///
/// This `struct` is created by the [`into_iter`] method on [`RotatedArraySet`][`RotatedArraySet`]
/// (provided by the `IntoIterator` trait). See its documentation for more.
///
/// [`RotatedArraySet`]: struct.RotatedArraySet.html
/// [`into_iter`]: struct.RotatedArraySet.html#method.into_iter
#[derive(Debug, Clone)]
pub struct IntoIter<T> {
vec: Vec<T>,
next_index: usize,
}
/// A lazy iterator producing elements in the difference of `RotatedArraySet`s.
///
/// This `struct` is created by the [`difference`] method on [`RotatedArraySet`].
/// See its documentation for more.
///
/// [`RotatedArraySet`]: struct.RotatedArraySet.html
/// [`difference`]: struct.RotatedArraySet.html#method.difference
#[derive(Debug, Clone)]
pub struct Difference<'a, T: 'a> {
self_iter: Iter<'a, T>,
other_set: &'a RotatedArraySet<T>,
}
/// A lazy iterator producing elements in the symmetric difference of `RotatedArraySet`s.
///
/// This `struct` is created by the [`symmetric_difference`] method on
/// [`RotatedArraySet`]. See its documentation for more.
///
/// [`RotatedArraySet`]: struct.RotatedArraySet.html
/// [`symmetric_difference`]: struct.RotatedArraySet.html#method.symmetric_difference
#[derive(Debug, Clone)]
pub struct SymmetricDifference<'a, T: 'a>
where
T: Ord + Copy + Default + Debug,
{
a: Peekable<Iter<'a, T>>,
b: Peekable<Iter<'a, T>>,
}
/// A lazy iterator producing elements in the intersection of `RotatedArraySet`s.
///
/// This `struct` is created by the [`intersection`] method on [`RotatedArraySet`].
/// See its documentation for more.
///
/// [`RotatedArraySet`]: struct.RotatedArraySet.html
/// [`intersection`]: struct.RotatedArraySet.html#method.intersection
#[derive(Debug, Clone)]
pub struct Intersection<'a, T: 'a> {
small_iter: Iter<'a, T>,
large_set: &'a RotatedArraySet<T>,
}
/// A lazy iterator producing elements in the union of `RotatedArraySet`s.
///
/// This `struct` is created by the [`union`] method on [`RotatedArraySet`].
/// See its documentation for more.
///
/// [`RotatedArraySet`]: struct.RotatedArraySet.html
/// [`union`]: struct.RotatedArraySet.html#method.union
#[derive(Debug, Clone)]
pub struct Union<'a, T: 'a>
where
T: Ord + Copy + Default + Debug,
{
a: Peekable<Iter<'a, T>>,
b: Peekable<Iter<'a, T>>,
}
impl<T> RotatedArraySet<T>
where
T: Ord + Copy + Default + Debug,
{
/// Makes a new `RotatedArraySet` without any heap allocations.
///
/// This is a constant-time operation.
///
/// # Examples
///
/// ```
/// # #![allow(unused_mut)]
/// use rotated_array_set::RotatedArraySet;
///
/// let mut set: RotatedArraySet<i32> = RotatedArraySet::new();
/// ```
pub fn new() -> Self {
RotatedArraySet {
data: Vec::new(),
min_indexes: Vec::new(),
min_data: Vec::new(),
}
}
/// Constructs a new, empty `RotatedArraySet<T>` with the specified capacity.
///
/// The set will be able to hold exactly `capacity` elements without
/// reallocating. If `capacity` is 0, the set will not allocate.
///
/// It is important to note that although the returned set has the
/// *capacity* specified, the set will have a zero *length*.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let mut set = RotatedArraySet::with_capacity(10);
///
/// // The set contains no items, even though it has capacity for more
/// assert_eq!(set.len(), 0);
///
/// // These are all done without reallocating...
/// for i in 0..10 {
/// set.insert(i);
/// }
///
/// // ...but this may make the set reallocate
/// set.insert(11);
/// ```
pub fn with_capacity(capacity: usize) -> RotatedArraySet<T> {
let min_indexes_capacity = if capacity > 0 {
Self::get_subarray_idx_from_array_idx(capacity - 1) + 1
} else {
0
};
RotatedArraySet {
data: Vec::with_capacity(capacity),
min_indexes: Vec::with_capacity(min_indexes_capacity),
min_data: Vec::with_capacity(min_indexes_capacity),
}
}
/// Clears the set, removing all values.
///
/// This is a constant-time operation.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let mut v = RotatedArraySet::new();
/// v.insert(1);
/// v.clear();
/// assert!(v.is_empty());
/// ```
pub fn clear(&mut self) {
self.data.clear();
self.min_indexes.clear();
self.min_data.clear();
}
/// Returns `true` if the set contains a value.
///
/// This is an `O(lg n)` operation.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let set: RotatedArraySet<_> = vec![1, 2, 3].into();
/// assert_eq!(set.contains(&1), true);
/// assert_eq!(set.contains(&4), false);
/// ```
pub fn contains(&self, value: &T) -> bool {
self.get(value).is_some()
}
/// Returns `true` if `self` has no elements in common with `other`.
/// This is equivalent to checking for an empty intersection.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let a: RotatedArraySet<_> = vec![1, 2, 3].into();
/// let mut b = RotatedArraySet::new();
///
/// assert_eq!(a.is_disjoint(&b), true);
/// b.insert(4);
/// assert_eq!(a.is_disjoint(&b), true);
/// b.insert(1);
/// assert_eq!(a.is_disjoint(&b), false);
/// ```
pub fn is_disjoint(&self, other: &RotatedArraySet<T>) -> bool {
self.intersection(other).next().is_none()
}
/// Returns `true` if the set is a subset of another,
/// i.e., `other` contains at least all the values in `self`.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let sup: RotatedArraySet<_> = vec![1, 2, 3].into();
/// let mut set = RotatedArraySet::new();
///
/// assert_eq!(set.is_subset(&sup), true);
/// set.insert(2);
/// assert_eq!(set.is_subset(&sup), true);
/// set.insert(4);
/// assert_eq!(set.is_subset(&sup), false);
/// ```
pub fn is_subset(&self, other: &RotatedArraySet<T>) -> bool {
// Same result as self.difference(other).next().is_none()
// but much faster.
if self.len() > other.len() {
false
} else {
// Iterate `self`, searching for matches in `other`.
for next in self {
if !other.contains(next) {
return false;
}
}
true
}
}
/// Returns `true` if the set is a superset of another,
/// i.e., `self` contains at least all the values in `other`.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let sub: RotatedArraySet<_> = vec![1, 2].into();
/// let mut set = RotatedArraySet::new();
///
/// assert_eq!(set.is_superset(&sub), false);
///
/// set.insert(0);
/// set.insert(1);
/// assert_eq!(set.is_superset(&sub), false);
///
/// set.insert(2);
/// assert_eq!(set.is_superset(&sub), true);
/// ```
pub fn is_superset(&self, other: &RotatedArraySet<T>) -> bool {
other.is_subset(self)
}
/// Returns a reference to the value in the set, if any, that is equal to the given value.
///
/// This is an `O(lg n)` operation.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let set: RotatedArraySet<_> = vec![1, 2, 3].into();
/// assert_eq!(set.get(&2), Some(&2));
/// assert_eq!(set.get(&4), None);
/// ```
pub fn get(&self, value: &T) -> Option<&T> {
let raw_idx = self.find_raw_index(value).ok()?;
Some(&self.data[raw_idx])
}
/// Returns the rank of the value in the set if it exists (as `Result::Ok`),
/// or the rank of its largest predecessor plus one, if it does not exist (as `Result::Err`).
/// This is a constant-time operation.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let set: RotatedArraySet<_> = vec![1, 2, 3].into();
/// assert_eq!(set.rank(&1), Ok(0));
/// assert_eq!(set.rank(&4), Err(3));
/// ```
pub fn rank(&self, value: &T) -> Result<usize, usize> {
let (raw_index, exists) = match self.find_raw_index(value) {
Ok(index) => (index, true),
Err(index) => (index, false),
};
if raw_index == self.data.len() {
return Err(raw_index);
}
debug_assert!(raw_index < self.data.len());
let subarray_idx = Self::get_subarray_idx_from_array_idx(raw_index);
let subarray_start_idx = Self::get_array_idx_from_subarray_idx(subarray_idx);
let subarray_len = if subarray_idx == self.min_indexes.len() - 1 {
self.data.len() - subarray_start_idx
} else {
subarray_idx + 1
};
let pivot_idx = subarray_start_idx + self.min_indexes[subarray_idx];
let logical_index = if raw_index >= pivot_idx {
subarray_start_idx + raw_index - pivot_idx
} else {
subarray_start_idx + subarray_len - (pivot_idx - raw_index)
};
if exists {
Ok(logical_index)
} else {
Err(logical_index)
}
}
/// Returns a reference to the value in the set, if any, with the given rank.
///
/// This is a constant-time operation.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let set: RotatedArraySet<_> = vec![1, 2, 3].into();
/// assert_eq!(set.select(0), Some(&1));
/// assert_eq!(set.select(3), None);
/// ```
pub fn select(&self, rank: usize) -> Option<&T> {
if rank >= self.data.len() {
return None;
}
let subarray_idx = Self::get_subarray_idx_from_array_idx(rank);
let subarray_start_idx = Self::get_array_idx_from_subarray_idx(subarray_idx);
let subarray_len = if subarray_idx == self.min_indexes.len() - 1 {
self.data.len() - subarray_start_idx
} else {
subarray_idx + 1
};
debug_assert!(rank >= subarray_start_idx);
let idx_offset = rank - subarray_start_idx;
let pivot_offset = self.min_indexes[subarray_idx];
let rotated_offset = (pivot_offset + idx_offset) % subarray_len;
debug_assert!(rotated_offset < subarray_len);
let raw_idx = subarray_start_idx + rotated_offset;
Some(&self.data[raw_idx])
}
/// Adds a value to the set.
///
/// This is an `O(√n)` operation.
///
/// If the set did not have this value present, `true` is returned.
///
/// If the set did have this value present, `false` is returned, and the
/// entry is not updated.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let mut set = RotatedArraySet::new();
///
/// assert_eq!(set.insert(2), true);
/// assert_eq!(set.insert(2), false);
/// assert_eq!(set.len(), 1);
/// ```
pub fn insert(&mut self, value: T) -> bool {
let insert_idx = match self.find_raw_index(&value).err() {
None => return false,
Some(idx) => idx,
};
// find subarray containing this insertion point
let subarray_idx = Self::get_subarray_idx_from_array_idx(insert_idx);
// inserted element could be in a new subarray
debug_assert!(subarray_idx <= self.min_indexes.len());
// create a new subarray if necessary
if subarray_idx == self.min_indexes.len() {
self.min_indexes.push(0);
self.min_data.push(T::default());
}
debug_assert_eq!(self.min_indexes.len(), self.min_data.len());
let subarray_offset = Self::get_array_idx_from_subarray_idx(subarray_idx);
// if insertion point is in last subarray and last subarray isn't full, just insert the new element
if subarray_idx == self.min_indexes.len() - 1 && !self.is_last_subarray_full() {
// Since we always insert into a partially full subarray in sorted order,
// there is no need to update the pivot location, but we do have to update
// the pivot value.
debug_assert!(self.min_indexes[subarray_idx] == 0);
self.data.insert(insert_idx, value);
// These writes are redundant unless the minimum has changed, but avoiding a branch may be worth it,
// given that the end of the data arrays should be in cache.
self.min_data[subarray_idx] = self.data[subarray_offset];
debug_assert!(self.assert_invariants());
return true;
}
// From now on, we can assume that the subarray we're inserting into is always full.
let next_subarray_offset = Self::get_array_idx_from_subarray_idx(subarray_idx + 1);
let subarray = &mut self.data[subarray_offset..next_subarray_offset];
let pivot_offset = self.min_indexes[subarray_idx];
let insert_offset = insert_idx - subarray_offset;
let max_offset = if pivot_offset == 0 {
subarray.len() - 1
} else {
pivot_offset - 1
};
let mut prev_max = subarray[max_offset];
// this logic is best understood with a diagram of a rotated array, e.g.:
//
// ------------------------------------------------------------------------
// | 12 | 13 | 14 | 15 | 16 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
// ------------------------------------------------------------------------
//
if max_offset < pivot_offset && insert_offset >= pivot_offset {
subarray.copy_within(pivot_offset..insert_offset, max_offset);
subarray[insert_offset - 1] = value;
self.min_indexes[subarray_idx] = max_offset;
self.min_data[subarray_idx] = subarray[max_offset];
} else {
subarray.copy_within(insert_offset..max_offset, insert_offset + 1);
subarray[insert_offset] = value;
if insert_offset == pivot_offset {
// inserted value is new minimum for subarray
self.min_data[subarray_idx] = value;
}
}
debug_assert!(self.assert_invariants());
let max_subarray_idx = self.min_indexes.len() - 1;
let next_subarray_idx = subarray_idx + 1;
let last_subarray_full = self.is_last_subarray_full();
// now loop over all remaining subarrays, setting the min (pivot) of each to the max of its predecessor
for (i, pivot_offset_ref) in self.min_indexes[next_subarray_idx..].iter_mut().enumerate() {
let cur_subarray_idx = next_subarray_idx + i;
// if the last subarray isn't full, skip it
if cur_subarray_idx == max_subarray_idx && !last_subarray_full {
break;
}
let max_offset = if *pivot_offset_ref == 0 {
cur_subarray_idx
} else {
*pivot_offset_ref - 1
};
let max_idx = max_offset + Self::get_array_idx_from_subarray_idx(cur_subarray_idx);
let next_max = self.data[max_idx];
self.data[max_idx] = prev_max;
*pivot_offset_ref = max_offset;
self.min_data[cur_subarray_idx] = prev_max;
prev_max = next_max;
}
// if the last subarray was full, append current max to a new subarray, otherwise insert max in sorted order
if last_subarray_full {
self.data.push(prev_max);
self.min_indexes.push(0);
self.min_data.push(prev_max);
} else {
let max_subarray_offset = Self::get_array_idx_from_subarray_idx(max_subarray_idx);
// since `max` is guaranteed to be <= the pivot value, we always insert it at the pivot location
debug_assert!(prev_max <= self.data[max_subarray_offset]);
self.data.insert(max_subarray_offset, prev_max);
self.min_data[max_subarray_idx] = prev_max;
}
debug_assert!(self.find_raw_index(&value).is_ok());
debug_assert!(self.assert_invariants());
true
}
/// Removes a value from the set. Returns whether the value was
/// present in the set.
///
/// This is an `O(√n)` operation.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let mut set = RotatedArraySet::new();
///
/// set.insert(2);
/// assert_eq!(set.remove(&2), true);
/// assert_eq!(set.remove(&2), false);
/// ```
pub fn remove(&mut self, value: &T) -> bool {
let mut remove_idx = match self.find_raw_index(&value).ok() {
Some(idx) => idx,
None => return false,
};
let max_subarray_idx = self.min_indexes.len() - 1;
let max_subarray_offset = Self::get_array_idx_from_subarray_idx(max_subarray_idx);
// find subarray containing the element to remove
let subarray_idx = Self::get_subarray_idx_from_array_idx(remove_idx);
debug_assert!(subarray_idx <= max_subarray_idx);
let subarray_offset = Self::get_array_idx_from_subarray_idx(subarray_idx);
// if we're not removing an element in the last subarray, then we end up deleting its minimum,
// which is always at the first offset since it's sorted
let mut max_subarray_remove_idx = if subarray_idx == max_subarray_idx {
remove_idx
} else {
max_subarray_offset
};
// if the last subarray was rotated, sort it to maintain insert invariant
if self.is_last_subarray_full() {
let last_min_offset = self.min_indexes[max_subarray_idx];
// rotate left by the min offset instead of sorting
self.data[max_subarray_offset..].rotate_left(last_min_offset);
self.min_indexes[max_subarray_idx] = 0;
// the remove index might change after sorting the last subarray
if subarray_idx == max_subarray_idx {
remove_idx = self
.find_raw_index(&value)
.expect("recalculating remove index after sorting");
max_subarray_remove_idx = remove_idx;
}
}
// if insertion point is not in last subarray, perform a "hard exchange"
if subarray_idx < max_subarray_idx {
// From now on, we can assume that the subarray we're removing from is full.
let next_subarray_offset = Self::get_array_idx_from_subarray_idx(subarray_idx + 1);
let subarray = &mut self.data[subarray_offset..next_subarray_offset];
let pivot_offset = self.min_indexes[subarray_idx];
let remove_offset = remove_idx - subarray_offset;
let max_offset = if pivot_offset == 0 {
subarray.len() - 1
} else {
pivot_offset - 1
};
// this logic is best understood with a diagram of a rotated array, e.g.:
//
// ------------------------------------------------------------------------
// | 12 | 13 | 14 | 15 | 16 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
// ------------------------------------------------------------------------
//
let mut prev_max_offset = if max_offset < pivot_offset && remove_offset >= pivot_offset
{
subarray.copy_within(pivot_offset..remove_offset, pivot_offset + 1);
let new_pivot_offset = if pivot_offset == subarray.len() - 1 {
0
} else {
pivot_offset + 1
};
self.min_indexes[subarray_idx] = new_pivot_offset;
self.min_data[subarray_idx] = subarray[new_pivot_offset];
pivot_offset
} else {
subarray.copy_within(remove_offset + 1..=max_offset, remove_offset);
if remove_offset == pivot_offset {
self.min_data[subarray_idx] = subarray[pivot_offset];
}
max_offset
};
let next_subarray_idx = min(max_subarray_idx, subarray_idx + 1);
// now perform an "easy exchange" in all remaining subarrays except the last,
// setting the max of each to the min of its successor.
for (i, pivot_offset_ref) in self.min_indexes[next_subarray_idx..max_subarray_idx]
.iter_mut()
.enumerate()
{
let cur_subarray_idx = next_subarray_idx + i;
let cur_subarray_offset = Self::get_array_idx_from_subarray_idx(cur_subarray_idx);
let prev_max_idx =
prev_max_offset + Self::get_array_idx_from_subarray_idx(cur_subarray_idx - 1);
self.data[prev_max_idx] = self.data[cur_subarray_offset + *pivot_offset_ref];
// the min_data array needs to be updated when the previous subarray's max offset
// coincides with its min offset, i.e., when it is subarray 0
if cur_subarray_idx == 1 {
self.min_data[0] = self.data[0];
debug_assert!(IsSorted::is_sorted(&mut self.min_data.iter()));
}
prev_max_offset = *pivot_offset_ref;
let new_min_offset = if *pivot_offset_ref == cur_subarray_idx {
0
} else {
*pivot_offset_ref + 1
};
*pivot_offset_ref = new_min_offset;
self.min_data[cur_subarray_idx] = self.data[cur_subarray_offset + new_min_offset];
debug_assert!(IsSorted::is_sorted(&mut self.min_data.iter()));
}
// now we fix up the last subarray. if it was initially full, we need to sort it to maintain the insert invariant.
// if the removed element is in the last subarray, we just sort and remove() on the vec, updating auxiliary arrays.
// otherwise, we copy the minimum to the max position of the previous subarray, then remove it and fix up
// auxiliary arrays.
let prev_max_idx =
prev_max_offset + Self::get_array_idx_from_subarray_idx(max_subarray_idx - 1);
// since the last subarray is always sorted, its minimum element is always on the first offset
self.data[prev_max_idx] = self.data[max_subarray_offset];
// the min_data array needs to be updated when the previous subarray's max offset
// coincides with its min offset, i.e., when it is subarray 0
if max_subarray_idx == 1 {
self.min_data[0] = self.data[0];
debug_assert!(IsSorted::is_sorted(&mut self.min_data.iter()));
}
}
self.data.remove(max_subarray_remove_idx);
// if last subarray is now empty, trim the auxiliary arrays
if max_subarray_offset == self.data.len() {
self.min_indexes.pop();
self.min_data.pop();
} else {
// since the last subarray is always sorted, its minimum is always on the first offset
self.min_data[max_subarray_idx] = self.data[max_subarray_offset];
debug_assert!(IsSorted::is_sorted(&mut self.min_data.iter()));
}
debug_assert!(self.find_raw_index(&value).is_err());
debug_assert!(self.assert_invariants());
true
}
/// Removes and returns the value in the set, if any, that is equal to the given one.
///
/// This is an `O(√n)` operation.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let mut set: RotatedArraySet<_> = vec![1, 2, 3].into();
/// assert_eq!(set.take(&2), Some(2));
/// assert_eq!(set.take(&2), None);
/// ```
pub fn take(&mut self, value: &T) -> Option<T> {
let ret = self.get(value).copied();
if ret.is_some() {
self.remove(value);
}
ret
}
/// Moves all elements from `other` into `Self`, leaving `other` empty.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let mut a = RotatedArraySet::new();
/// a.insert(1);
/// a.insert(2);
/// a.insert(3);
///
/// let mut b = RotatedArraySet::new();
/// b.insert(3);
/// b.insert(4);
/// b.insert(5);
///
/// a.append(&mut b);
///
/// assert_eq!(a.len(), 5);
/// assert_eq!(b.len(), 0);
///
/// assert!(a.contains(&1));
/// assert!(a.contains(&2));
/// assert!(a.contains(&3));
/// assert!(a.contains(&4));
/// assert!(a.contains(&5));
/// ```
pub fn append(&mut self, other: &mut Self) {
// allocate new set and copy union into it
let mut union: Self = self.union(other).cloned().collect();
// empty `other`
other.clear();
// steal data from new set and drop data from old set
mem::swap(self, &mut union);
}
/// Splits the collection into two at `value`. Returns everything after `value`,
/// including `value` itself.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let mut a = RotatedArraySet::new();
/// a.insert(1);
/// a.insert(2);
/// a.insert(3);
/// a.insert(17);
/// a.insert(41);
///
/// let b = a.split_off(&3);
///
/// assert_eq!(a.len(), 2);
/// assert_eq!(b.len(), 3);
///
/// assert!(a.contains(&1));
/// assert!(a.contains(&2));
///
/// assert!(b.contains(&3));
/// assert!(b.contains(&17));
/// assert!(b.contains(&41));
/// ```
pub fn split_off(&mut self, value: &T) -> Self {
let tail = self.range((Included(value), Unbounded));
if tail.len() == 0 {
// if key follows everything in set, just return empty set
Self::default()
} else if tail.len() == self.len() {
// if key precedes everything in set, just return moved self
mem::replace(self, Self::default())
} else {
// return tail and truncate self
let new_len = self.len() - tail.len();
let tail_set: Self = tail.cloned().collect();
self.truncate(new_len);
tail_set
}
}
/// Truncates the sorted sequence, keeping the first `len` elements and dropping
/// the rest.
///
/// If `len` is greater than the set's current length, this has no
/// effect.
///
/// # Examples
///
/// Truncating a five-element set to two elements:
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let mut set: RotatedArraySet<_> = vec![1, 2, 3, 4, 5].into();
/// set.truncate(2);
/// assert_eq!(set, vec![1, 2].into());
/// ```
///
/// No truncation occurs when `len` is greater than the vector's current
/// length:
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let mut set: RotatedArraySet<_> = vec![1, 2, 3].into();
/// set.truncate(8);
/// assert_eq!(set, vec![1, 2, 3].into());
/// ```
///
/// Truncating when `len == 0` is equivalent to calling the [`clear`]
/// method.
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let mut set: RotatedArraySet<_> = vec![1, 2, 3].into();
/// set.truncate(0);
/// assert_eq!(set, vec![].into());
/// ```
pub fn truncate(&mut self, len: usize) {
if len == 0 {
self.clear();
// if len >= self.len(), do nothing
} else if len < self.len() {
// logical index corresponding to truncated length
let index = len - 1;
// find subarray containing logical index (we don't need to translate to raw index for this)
let subarray_idx = Self::get_subarray_idx_from_array_idx(index);
let subarray_offset = Self::get_array_idx_from_subarray_idx(subarray_idx);
let next_subarray_offset = if subarray_idx == self.min_indexes.len() - 1 {
self.data.len()
} else {
Self::get_array_idx_from_subarray_idx(subarray_idx + 1)
};
let subarray = &mut self.data[subarray_offset..next_subarray_offset];
// sort subarray and update auxiliary arrays
let min_offset = self.min_indexes[subarray_idx];
subarray.rotate_left(min_offset);
self.min_indexes[subarray_idx] = 0;
// now we can truncate the whole data array at the logical index
self.data.truncate(len);
// trim auxiliary arrays
self.min_indexes.truncate(subarray_idx + 1);
self.min_data.truncate(subarray_idx + 1);
}
debug_assert!(self.assert_invariants());
}
/// Returns the number of elements in the set.
///
/// This is a constant-time operation.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let mut v = RotatedArraySet::new();
/// assert_eq!(v.len(), 0);
/// v.insert(1);
/// assert_eq!(v.len(), 1);
/// ```
pub fn len(&self) -> usize {
self.data.len()
}
/// Returns `true` if the set contains no elements.
///
/// This is a constant-time operation.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let mut v = RotatedArraySet::new();
/// assert!(v.is_empty());
/// v.insert(1);
/// assert!(!v.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
/// Gets a double-ended iterator that visits the values in the `RotatedArraySet` in ascending (descending) order.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let set: RotatedArraySet<usize> = RotatedArraySet::new();
/// let mut set_iter = set.iter();
/// assert_eq!(set_iter.next(), None);
/// ```
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let set: RotatedArraySet<usize> = vec![1, 2, 3].into();
/// let mut set_iter = set.iter();
/// assert_eq!(set_iter.next(), Some(&1));
/// assert_eq!(set_iter.next(), Some(&2));
/// assert_eq!(set_iter.next(), Some(&3));
/// assert_eq!(set_iter.next(), None);
/// ```
///
/// Values returned by the iterator are returned in ascending order:
///
/// ```
/// use rotated_array_set::RotatedArraySet;
///
/// let set: RotatedArraySet<usize> = vec![3, 1, 2].into();
/// let mut set_iter = set.iter();
/// assert_eq!(set_iter.next(), Some(&1));
/// assert_eq!(set_iter.next(), Some(&2));
/// assert_eq!(set_iter.next(), Some(&3));
/// assert_eq!(set_iter.next(), None);
/// ```
pub fn iter(&self) -> Iter<'_, T> {
Iter::new(Range::new(self))
}
/// Constructs a double-ended iterator over a sub-range of elements in the set.
/// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
/// yield elements from `min` (inclusive) to `max` (exclusive).
/// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
/// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
/// range from 4 to 10.
///
/// # Examples
///
/// ```
/// use rotated_array_set::RotatedArraySet;
/// use std::ops::Bound::Included;
///