-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
tests.rs
2565 lines (2232 loc) · 81.5 KB
/
tests.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
use core::assert_matches::assert_matches;
use std::iter;
use std::ops::Bound::{Excluded, Included, Unbounded};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
use super::*;
use crate::boxed::Box;
use crate::fmt::Debug;
use crate::rc::Rc;
use crate::string::{String, ToString};
use crate::testing::crash_test::{CrashTestDummy, Panic};
use crate::testing::ord_chaos::{Cyclic3, Governed, Governor};
use crate::testing::rng::DeterministicRng;
// Minimum number of elements to insert, to guarantee a tree with 2 levels,
// i.e., a tree who's root is an internal node at height 1, with edges to leaf nodes.
// It's not the minimum size: removing an element from such a tree does not always reduce height.
const MIN_INSERTS_HEIGHT_1: usize = node::CAPACITY + 1;
// Minimum number of elements to insert in ascending order, to guarantee a tree with 3 levels,
// i.e., a tree who's root is an internal node at height 2, with edges to more internal nodes.
// It's not the minimum size: removing an element from such a tree does not always reduce height.
const MIN_INSERTS_HEIGHT_2: usize = 89;
// Gathers all references from a mutable iterator and makes sure Miri notices if
// using them is dangerous.
fn test_all_refs<'a, T: 'a>(dummy: &mut T, iter: impl Iterator<Item = &'a mut T>) {
// Gather all those references.
let mut refs: Vec<&mut T> = iter.collect();
// Use them all. Twice, to be sure we got all interleavings.
for r in refs.iter_mut() {
mem::swap(dummy, r);
}
for r in refs {
mem::swap(dummy, r);
}
}
impl<K, V> BTreeMap<K, V> {
// Panics if the map (or the code navigating it) is corrupted.
fn check_invariants(&self) {
if let Some(root) = &self.root {
let root_node = root.reborrow();
// Check the back pointers top-down, before we attempt to rely on
// more serious navigation code.
assert!(root_node.ascend().is_err());
root_node.assert_back_pointers();
// Check consistency of `length` with what navigation code encounters.
assert_eq!(self.length, root_node.calc_length());
// Lastly, check the invariant causing the least harm.
root_node.assert_min_len(if root_node.height() > 0 { 1 } else { 0 });
} else {
assert_eq!(self.length, 0);
}
// Check that `assert_strictly_ascending` will encounter all keys.
assert_eq!(self.length, self.keys().count());
}
// Panics if the map is corrupted or if the keys are not in strictly
// ascending order, in the current opinion of the `Ord` implementation.
// If the `Ord` implementation violates transitivity, this method does not
// guarantee that all keys are unique, just that adjacent keys are unique.
fn check(&self)
where
K: Debug + Ord,
{
self.check_invariants();
self.assert_strictly_ascending();
}
// Returns the height of the root, if any.
fn height(&self) -> Option<usize> {
self.root.as_ref().map(node::Root::height)
}
fn dump_keys(&self) -> String
where
K: Debug,
{
if let Some(root) = self.root.as_ref() {
root.reborrow().dump_keys()
} else {
String::from("not yet allocated")
}
}
// Panics if the keys are not in strictly ascending order.
fn assert_strictly_ascending(&self)
where
K: Debug + Ord,
{
let mut keys = self.keys();
if let Some(mut previous) = keys.next() {
for next in keys {
assert!(previous < next, "{:?} >= {:?}", previous, next);
previous = next;
}
}
}
// Transform the tree to minimize wasted space, obtaining fewer nodes that
// are mostly filled up to their capacity. The same compact tree could have
// been obtained by inserting keys in a shrewd order.
fn compact(&mut self)
where
K: Ord,
{
let iter = mem::take(self).into_iter();
if !iter.is_empty() {
self.root.insert(Root::new(*self.alloc)).bulk_push(iter, &mut self.length, *self.alloc);
}
}
}
impl<'a, K: 'a, V: 'a> NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal> {
fn assert_min_len(self, min_len: usize) {
assert!(self.len() >= min_len, "node len {} < {}", self.len(), min_len);
if let node::ForceResult::Internal(node) = self.force() {
for idx in 0..=node.len() {
let edge = unsafe { Handle::new_edge(node, idx) };
edge.descend().assert_min_len(MIN_LEN);
}
}
}
}
// Tests our value of MIN_INSERTS_HEIGHT_2. Failure may mean you just need to
// adapt that value to match a change in node::CAPACITY or the choices made
// during insertion, otherwise other test cases may fail or be less useful.
#[test]
fn test_levels() {
let mut map = BTreeMap::new();
map.check();
assert_eq!(map.height(), None);
assert_eq!(map.len(), 0);
map.insert(0, ());
while map.height() == Some(0) {
let last_key = *map.last_key_value().unwrap().0;
map.insert(last_key + 1, ());
}
map.check();
// Structure:
// - 1 element in internal root node with 2 children
// - 6 elements in left leaf child
// - 5 elements in right leaf child
assert_eq!(map.height(), Some(1));
assert_eq!(map.len(), MIN_INSERTS_HEIGHT_1, "{}", map.dump_keys());
while map.height() == Some(1) {
let last_key = *map.last_key_value().unwrap().0;
map.insert(last_key + 1, ());
}
map.check();
// Structure:
// - 1 element in internal root node with 2 children
// - 6 elements in left internal child with 7 grandchildren
// - 42 elements in left child's 7 grandchildren with 6 elements each
// - 5 elements in right internal child with 6 grandchildren
// - 30 elements in right child's 5 first grandchildren with 6 elements each
// - 5 elements in right child's last grandchild
assert_eq!(map.height(), Some(2));
assert_eq!(map.len(), MIN_INSERTS_HEIGHT_2, "{}", map.dump_keys());
}
// Ensures the testing infrastructure usually notices order violations.
#[test]
#[should_panic]
fn test_check_ord_chaos() {
let gov = Governor::new();
let map = BTreeMap::from([(Governed(1, &gov), ()), (Governed(2, &gov), ())]);
gov.flip();
map.check();
}
// Ensures the testing infrastructure doesn't always mind order violations.
#[test]
fn test_check_invariants_ord_chaos() {
let gov = Governor::new();
let map = BTreeMap::from([(Governed(1, &gov), ()), (Governed(2, &gov), ())]);
gov.flip();
map.check_invariants();
}
#[test]
fn test_basic_large() {
let mut map = BTreeMap::new();
// Miri is too slow
let size = if cfg!(miri) { MIN_INSERTS_HEIGHT_2 } else { 10000 };
let size = size + (size % 2); // round up to even number
assert_eq!(map.len(), 0);
for i in 0..size {
assert_eq!(map.insert(i, 10 * i), None);
assert_eq!(map.len(), i + 1);
}
assert_eq!(map.first_key_value(), Some((&0, &0)));
assert_eq!(map.last_key_value(), Some((&(size - 1), &(10 * (size - 1)))));
assert_eq!(map.first_entry().unwrap().key(), &0);
assert_eq!(map.last_entry().unwrap().key(), &(size - 1));
for i in 0..size {
assert_eq!(map.get(&i).unwrap(), &(i * 10));
}
for i in size..size * 2 {
assert_eq!(map.get(&i), None);
}
for i in 0..size {
assert_eq!(map.insert(i, 100 * i), Some(10 * i));
assert_eq!(map.len(), size);
}
for i in 0..size {
assert_eq!(map.get(&i).unwrap(), &(i * 100));
}
for i in 0..size / 2 {
assert_eq!(map.remove(&(i * 2)), Some(i * 200));
assert_eq!(map.len(), size - i - 1);
}
for i in 0..size / 2 {
assert_eq!(map.get(&(2 * i)), None);
assert_eq!(map.get(&(2 * i + 1)).unwrap(), &(i * 200 + 100));
}
for i in 0..size / 2 {
assert_eq!(map.remove(&(2 * i)), None);
assert_eq!(map.remove(&(2 * i + 1)), Some(i * 200 + 100));
assert_eq!(map.len(), size / 2 - i - 1);
}
map.check();
}
#[test]
fn test_basic_small() {
let mut map = BTreeMap::new();
// Empty, root is absent (None):
assert_eq!(map.remove(&1), None);
assert_eq!(map.len(), 0);
assert_eq!(map.get(&1), None);
assert_eq!(map.get_mut(&1), None);
assert_eq!(map.first_key_value(), None);
assert_eq!(map.last_key_value(), None);
assert_eq!(map.keys().count(), 0);
assert_eq!(map.values().count(), 0);
assert_eq!(map.range(..).next(), None);
assert_eq!(map.range(..1).next(), None);
assert_eq!(map.range(1..).next(), None);
assert_eq!(map.range(1..=1).next(), None);
assert_eq!(map.range(1..2).next(), None);
assert_eq!(map.height(), None);
assert_eq!(map.insert(1, 1), None);
assert_eq!(map.height(), Some(0));
map.check();
// 1 key-value pair:
assert_eq!(map.len(), 1);
assert_eq!(map.get(&1), Some(&1));
assert_eq!(map.get_mut(&1), Some(&mut 1));
assert_eq!(map.first_key_value(), Some((&1, &1)));
assert_eq!(map.last_key_value(), Some((&1, &1)));
assert_eq!(map.keys().collect::<Vec<_>>(), vec![&1]);
assert_eq!(map.values().collect::<Vec<_>>(), vec![&1]);
assert_eq!(map.insert(1, 2), Some(1));
assert_eq!(map.len(), 1);
assert_eq!(map.get(&1), Some(&2));
assert_eq!(map.get_mut(&1), Some(&mut 2));
assert_eq!(map.first_key_value(), Some((&1, &2)));
assert_eq!(map.last_key_value(), Some((&1, &2)));
assert_eq!(map.keys().collect::<Vec<_>>(), vec![&1]);
assert_eq!(map.values().collect::<Vec<_>>(), vec![&2]);
assert_eq!(map.insert(2, 4), None);
assert_eq!(map.height(), Some(0));
map.check();
// 2 key-value pairs:
assert_eq!(map.len(), 2);
assert_eq!(map.get(&2), Some(&4));
assert_eq!(map.get_mut(&2), Some(&mut 4));
assert_eq!(map.first_key_value(), Some((&1, &2)));
assert_eq!(map.last_key_value(), Some((&2, &4)));
assert_eq!(map.keys().collect::<Vec<_>>(), vec![&1, &2]);
assert_eq!(map.values().collect::<Vec<_>>(), vec![&2, &4]);
assert_eq!(map.remove(&1), Some(2));
assert_eq!(map.height(), Some(0));
map.check();
// 1 key-value pair:
assert_eq!(map.len(), 1);
assert_eq!(map.get(&1), None);
assert_eq!(map.get_mut(&1), None);
assert_eq!(map.get(&2), Some(&4));
assert_eq!(map.get_mut(&2), Some(&mut 4));
assert_eq!(map.first_key_value(), Some((&2, &4)));
assert_eq!(map.last_key_value(), Some((&2, &4)));
assert_eq!(map.keys().collect::<Vec<_>>(), vec![&2]);
assert_eq!(map.values().collect::<Vec<_>>(), vec![&4]);
assert_eq!(map.remove(&2), Some(4));
assert_eq!(map.height(), Some(0));
map.check();
// Empty but root is owned (Some(...)):
assert_eq!(map.len(), 0);
assert_eq!(map.get(&1), None);
assert_eq!(map.get_mut(&1), None);
assert_eq!(map.first_key_value(), None);
assert_eq!(map.last_key_value(), None);
assert_eq!(map.keys().count(), 0);
assert_eq!(map.values().count(), 0);
assert_eq!(map.range(..).next(), None);
assert_eq!(map.range(..1).next(), None);
assert_eq!(map.range(1..).next(), None);
assert_eq!(map.range(1..=1).next(), None);
assert_eq!(map.range(1..2).next(), None);
assert_eq!(map.remove(&1), None);
assert_eq!(map.height(), Some(0));
map.check();
}
#[test]
fn test_iter() {
// Miri is too slow
let size = if cfg!(miri) { 200 } else { 10000 };
let mut map = BTreeMap::from_iter((0..size).map(|i| (i, i)));
fn test<T>(size: usize, mut iter: T)
where
T: Iterator<Item = (usize, usize)>,
{
for i in 0..size {
assert_eq!(iter.size_hint(), (size - i, Some(size - i)));
assert_eq!(iter.next().unwrap(), (i, i));
}
assert_eq!(iter.size_hint(), (0, Some(0)));
assert_eq!(iter.next(), None);
}
test(size, map.iter().map(|(&k, &v)| (k, v)));
test(size, map.iter_mut().map(|(&k, &mut v)| (k, v)));
test(size, map.into_iter());
}
#[test]
fn test_iter_rev() {
// Miri is too slow
let size = if cfg!(miri) { 200 } else { 10000 };
let mut map = BTreeMap::from_iter((0..size).map(|i| (i, i)));
fn test<T>(size: usize, mut iter: T)
where
T: Iterator<Item = (usize, usize)>,
{
for i in 0..size {
assert_eq!(iter.size_hint(), (size - i, Some(size - i)));
assert_eq!(iter.next().unwrap(), (size - i - 1, size - i - 1));
}
assert_eq!(iter.size_hint(), (0, Some(0)));
assert_eq!(iter.next(), None);
}
test(size, map.iter().rev().map(|(&k, &v)| (k, v)));
test(size, map.iter_mut().rev().map(|(&k, &mut v)| (k, v)));
test(size, map.into_iter().rev());
}
// Specifically tests iter_mut's ability to mutate the value of pairs in-line.
fn do_test_iter_mut_mutation<T>(size: usize)
where
T: Copy + Debug + Ord + TryFrom<usize>,
<T as TryFrom<usize>>::Error: Debug,
{
let zero = T::try_from(0).unwrap();
let mut map = BTreeMap::from_iter((0..size).map(|i| (T::try_from(i).unwrap(), zero)));
// Forward and backward iteration sees enough pairs (also tested elsewhere)
assert_eq!(map.iter_mut().count(), size);
assert_eq!(map.iter_mut().rev().count(), size);
// Iterate forwards, trying to mutate to unique values
for (i, (k, v)) in map.iter_mut().enumerate() {
assert_eq!(*k, T::try_from(i).unwrap());
assert_eq!(*v, zero);
*v = T::try_from(i + 1).unwrap();
}
// Iterate backwards, checking that mutations succeeded and trying to mutate again
for (i, (k, v)) in map.iter_mut().rev().enumerate() {
assert_eq!(*k, T::try_from(size - i - 1).unwrap());
assert_eq!(*v, T::try_from(size - i).unwrap());
*v = T::try_from(2 * size - i).unwrap();
}
// Check that backward mutations succeeded
for (i, (k, v)) in map.iter_mut().enumerate() {
assert_eq!(*k, T::try_from(i).unwrap());
assert_eq!(*v, T::try_from(size + i + 1).unwrap());
}
map.check();
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(align(32))]
struct Align32(usize);
impl TryFrom<usize> for Align32 {
type Error = ();
fn try_from(s: usize) -> Result<Align32, ()> {
Ok(Align32(s))
}
}
#[test]
fn test_iter_mut_mutation() {
// Check many alignments and trees with roots at various heights.
do_test_iter_mut_mutation::<u8>(0);
do_test_iter_mut_mutation::<u8>(1);
do_test_iter_mut_mutation::<u8>(MIN_INSERTS_HEIGHT_1);
do_test_iter_mut_mutation::<u8>(MIN_INSERTS_HEIGHT_2);
do_test_iter_mut_mutation::<u16>(1);
do_test_iter_mut_mutation::<u16>(MIN_INSERTS_HEIGHT_1);
do_test_iter_mut_mutation::<u16>(MIN_INSERTS_HEIGHT_2);
do_test_iter_mut_mutation::<u32>(1);
do_test_iter_mut_mutation::<u32>(MIN_INSERTS_HEIGHT_1);
do_test_iter_mut_mutation::<u32>(MIN_INSERTS_HEIGHT_2);
do_test_iter_mut_mutation::<u64>(1);
do_test_iter_mut_mutation::<u64>(MIN_INSERTS_HEIGHT_1);
do_test_iter_mut_mutation::<u64>(MIN_INSERTS_HEIGHT_2);
do_test_iter_mut_mutation::<u128>(1);
do_test_iter_mut_mutation::<u128>(MIN_INSERTS_HEIGHT_1);
do_test_iter_mut_mutation::<u128>(MIN_INSERTS_HEIGHT_2);
do_test_iter_mut_mutation::<Align32>(1);
do_test_iter_mut_mutation::<Align32>(MIN_INSERTS_HEIGHT_1);
do_test_iter_mut_mutation::<Align32>(MIN_INSERTS_HEIGHT_2);
}
#[test]
fn test_values_mut() {
let mut a = BTreeMap::from_iter((0..MIN_INSERTS_HEIGHT_2).map(|i| (i, i)));
test_all_refs(&mut 13, a.values_mut());
a.check();
}
#[test]
fn test_values_mut_mutation() {
let mut a = BTreeMap::new();
a.insert(1, String::from("hello"));
a.insert(2, String::from("goodbye"));
for value in a.values_mut() {
value.push_str("!");
}
let values = Vec::from_iter(a.values().cloned());
assert_eq!(values, [String::from("hello!"), String::from("goodbye!")]);
a.check();
}
#[test]
fn test_iter_entering_root_twice() {
let mut map = BTreeMap::from([(0, 0), (1, 1)]);
let mut it = map.iter_mut();
let front = it.next().unwrap();
let back = it.next_back().unwrap();
assert_eq!(front, (&0, &mut 0));
assert_eq!(back, (&1, &mut 1));
*front.1 = 24;
*back.1 = 42;
assert_eq!(front, (&0, &mut 24));
assert_eq!(back, (&1, &mut 42));
assert_eq!(it.next(), None);
assert_eq!(it.next_back(), None);
map.check();
}
#[test]
fn test_iter_descending_to_same_node_twice() {
let mut map = BTreeMap::from_iter((0..MIN_INSERTS_HEIGHT_1).map(|i| (i, i)));
let mut it = map.iter_mut();
// Descend into first child.
let front = it.next().unwrap();
// Descend into first child again, after running through second child.
while it.next_back().is_some() {}
// Check immutable access.
assert_eq!(front, (&0, &mut 0));
// Perform mutable access.
*front.1 = 42;
map.check();
}
#[test]
fn test_iter_mixed() {
// Miri is too slow
let size = if cfg!(miri) { 200 } else { 10000 };
let mut map = BTreeMap::from_iter((0..size).map(|i| (i, i)));
fn test<T>(size: usize, mut iter: T)
where
T: Iterator<Item = (usize, usize)> + DoubleEndedIterator,
{
for i in 0..size / 4 {
assert_eq!(iter.size_hint(), (size - i * 2, Some(size - i * 2)));
assert_eq!(iter.next().unwrap(), (i, i));
assert_eq!(iter.next_back().unwrap(), (size - i - 1, size - i - 1));
}
for i in size / 4..size * 3 / 4 {
assert_eq!(iter.size_hint(), (size * 3 / 4 - i, Some(size * 3 / 4 - i)));
assert_eq!(iter.next().unwrap(), (i, i));
}
assert_eq!(iter.size_hint(), (0, Some(0)));
assert_eq!(iter.next(), None);
}
test(size, map.iter().map(|(&k, &v)| (k, v)));
test(size, map.iter_mut().map(|(&k, &mut v)| (k, v)));
test(size, map.into_iter());
}
#[test]
fn test_iter_min_max() {
let mut a = BTreeMap::new();
assert_eq!(a.iter().min(), None);
assert_eq!(a.iter().max(), None);
assert_eq!(a.iter_mut().min(), None);
assert_eq!(a.iter_mut().max(), None);
assert_eq!(a.range(..).min(), None);
assert_eq!(a.range(..).max(), None);
assert_eq!(a.range_mut(..).min(), None);
assert_eq!(a.range_mut(..).max(), None);
assert_eq!(a.keys().min(), None);
assert_eq!(a.keys().max(), None);
assert_eq!(a.values().min(), None);
assert_eq!(a.values().max(), None);
assert_eq!(a.values_mut().min(), None);
assert_eq!(a.values_mut().max(), None);
a.insert(1, 42);
a.insert(2, 24);
assert_eq!(a.iter().min(), Some((&1, &42)));
assert_eq!(a.iter().max(), Some((&2, &24)));
assert_eq!(a.iter_mut().min(), Some((&1, &mut 42)));
assert_eq!(a.iter_mut().max(), Some((&2, &mut 24)));
assert_eq!(a.range(..).min(), Some((&1, &42)));
assert_eq!(a.range(..).max(), Some((&2, &24)));
assert_eq!(a.range_mut(..).min(), Some((&1, &mut 42)));
assert_eq!(a.range_mut(..).max(), Some((&2, &mut 24)));
assert_eq!(a.keys().min(), Some(&1));
assert_eq!(a.keys().max(), Some(&2));
assert_eq!(a.values().min(), Some(&24));
assert_eq!(a.values().max(), Some(&42));
assert_eq!(a.values_mut().min(), Some(&mut 24));
assert_eq!(a.values_mut().max(), Some(&mut 42));
a.check();
}
fn range_keys(map: &BTreeMap<i32, i32>, range: impl RangeBounds<i32>) -> Vec<i32> {
Vec::from_iter(map.range(range).map(|(&k, &v)| {
assert_eq!(k, v);
k
}))
}
#[test]
fn test_range_small() {
let size = 4;
let all = Vec::from_iter(1..=size);
let (first, last) = (vec![all[0]], vec![all[size as usize - 1]]);
let map = BTreeMap::from_iter(all.iter().copied().map(|i| (i, i)));
assert_eq!(range_keys(&map, (Excluded(0), Excluded(size + 1))), all);
assert_eq!(range_keys(&map, (Excluded(0), Included(size + 1))), all);
assert_eq!(range_keys(&map, (Excluded(0), Included(size))), all);
assert_eq!(range_keys(&map, (Excluded(0), Unbounded)), all);
assert_eq!(range_keys(&map, (Included(0), Excluded(size + 1))), all);
assert_eq!(range_keys(&map, (Included(0), Included(size + 1))), all);
assert_eq!(range_keys(&map, (Included(0), Included(size))), all);
assert_eq!(range_keys(&map, (Included(0), Unbounded)), all);
assert_eq!(range_keys(&map, (Included(1), Excluded(size + 1))), all);
assert_eq!(range_keys(&map, (Included(1), Included(size + 1))), all);
assert_eq!(range_keys(&map, (Included(1), Included(size))), all);
assert_eq!(range_keys(&map, (Included(1), Unbounded)), all);
assert_eq!(range_keys(&map, (Unbounded, Excluded(size + 1))), all);
assert_eq!(range_keys(&map, (Unbounded, Included(size + 1))), all);
assert_eq!(range_keys(&map, (Unbounded, Included(size))), all);
assert_eq!(range_keys(&map, ..), all);
assert_eq!(range_keys(&map, (Excluded(0), Excluded(1))), vec![]);
assert_eq!(range_keys(&map, (Excluded(0), Included(0))), vec![]);
assert_eq!(range_keys(&map, (Included(0), Included(0))), vec![]);
assert_eq!(range_keys(&map, (Included(0), Excluded(1))), vec![]);
assert_eq!(range_keys(&map, (Unbounded, Excluded(1))), vec![]);
assert_eq!(range_keys(&map, (Unbounded, Included(0))), vec![]);
assert_eq!(range_keys(&map, (Excluded(0), Excluded(2))), first);
assert_eq!(range_keys(&map, (Excluded(0), Included(1))), first);
assert_eq!(range_keys(&map, (Included(0), Excluded(2))), first);
assert_eq!(range_keys(&map, (Included(0), Included(1))), first);
assert_eq!(range_keys(&map, (Included(1), Excluded(2))), first);
assert_eq!(range_keys(&map, (Included(1), Included(1))), first);
assert_eq!(range_keys(&map, (Unbounded, Excluded(2))), first);
assert_eq!(range_keys(&map, (Unbounded, Included(1))), first);
assert_eq!(range_keys(&map, (Excluded(size - 1), Excluded(size + 1))), last);
assert_eq!(range_keys(&map, (Excluded(size - 1), Included(size + 1))), last);
assert_eq!(range_keys(&map, (Excluded(size - 1), Included(size))), last);
assert_eq!(range_keys(&map, (Excluded(size - 1), Unbounded)), last);
assert_eq!(range_keys(&map, (Included(size), Excluded(size + 1))), last);
assert_eq!(range_keys(&map, (Included(size), Included(size + 1))), last);
assert_eq!(range_keys(&map, (Included(size), Included(size))), last);
assert_eq!(range_keys(&map, (Included(size), Unbounded)), last);
assert_eq!(range_keys(&map, (Excluded(size), Excluded(size + 1))), vec![]);
assert_eq!(range_keys(&map, (Excluded(size), Included(size))), vec![]);
assert_eq!(range_keys(&map, (Excluded(size), Unbounded)), vec![]);
assert_eq!(range_keys(&map, (Included(size + 1), Excluded(size + 1))), vec![]);
assert_eq!(range_keys(&map, (Included(size + 1), Included(size + 1))), vec![]);
assert_eq!(range_keys(&map, (Included(size + 1), Unbounded)), vec![]);
assert_eq!(range_keys(&map, ..3), vec![1, 2]);
assert_eq!(range_keys(&map, 3..), vec![3, 4]);
assert_eq!(range_keys(&map, 2..=3), vec![2, 3]);
}
#[test]
fn test_range_height_1() {
// Tests tree with a root and 2 leaves. We test around the middle of the
// keys because one of those is the single key in the root node.
let map = BTreeMap::from_iter((0..MIN_INSERTS_HEIGHT_1 as i32).map(|i| (i, i)));
let middle = MIN_INSERTS_HEIGHT_1 as i32 / 2;
for root in middle - 2..=middle + 2 {
assert_eq!(range_keys(&map, (Excluded(root), Excluded(root + 1))), vec![]);
assert_eq!(range_keys(&map, (Excluded(root), Included(root + 1))), vec![root + 1]);
assert_eq!(range_keys(&map, (Included(root), Excluded(root + 1))), vec![root]);
assert_eq!(range_keys(&map, (Included(root), Included(root + 1))), vec![root, root + 1]);
assert_eq!(range_keys(&map, (Excluded(root - 1), Excluded(root))), vec![]);
assert_eq!(range_keys(&map, (Included(root - 1), Excluded(root))), vec![root - 1]);
assert_eq!(range_keys(&map, (Excluded(root - 1), Included(root))), vec![root]);
assert_eq!(range_keys(&map, (Included(root - 1), Included(root))), vec![root - 1, root]);
}
}
#[test]
fn test_range_large() {
let size = 200;
let all = Vec::from_iter(1..=size);
let (first, last) = (vec![all[0]], vec![all[size as usize - 1]]);
let map = BTreeMap::from_iter(all.iter().copied().map(|i| (i, i)));
assert_eq!(range_keys(&map, (Excluded(0), Excluded(size + 1))), all);
assert_eq!(range_keys(&map, (Excluded(0), Included(size + 1))), all);
assert_eq!(range_keys(&map, (Excluded(0), Included(size))), all);
assert_eq!(range_keys(&map, (Excluded(0), Unbounded)), all);
assert_eq!(range_keys(&map, (Included(0), Excluded(size + 1))), all);
assert_eq!(range_keys(&map, (Included(0), Included(size + 1))), all);
assert_eq!(range_keys(&map, (Included(0), Included(size))), all);
assert_eq!(range_keys(&map, (Included(0), Unbounded)), all);
assert_eq!(range_keys(&map, (Included(1), Excluded(size + 1))), all);
assert_eq!(range_keys(&map, (Included(1), Included(size + 1))), all);
assert_eq!(range_keys(&map, (Included(1), Included(size))), all);
assert_eq!(range_keys(&map, (Included(1), Unbounded)), all);
assert_eq!(range_keys(&map, (Unbounded, Excluded(size + 1))), all);
assert_eq!(range_keys(&map, (Unbounded, Included(size + 1))), all);
assert_eq!(range_keys(&map, (Unbounded, Included(size))), all);
assert_eq!(range_keys(&map, ..), all);
assert_eq!(range_keys(&map, (Excluded(0), Excluded(1))), vec![]);
assert_eq!(range_keys(&map, (Excluded(0), Included(0))), vec![]);
assert_eq!(range_keys(&map, (Included(0), Included(0))), vec![]);
assert_eq!(range_keys(&map, (Included(0), Excluded(1))), vec![]);
assert_eq!(range_keys(&map, (Unbounded, Excluded(1))), vec![]);
assert_eq!(range_keys(&map, (Unbounded, Included(0))), vec![]);
assert_eq!(range_keys(&map, (Excluded(0), Excluded(2))), first);
assert_eq!(range_keys(&map, (Excluded(0), Included(1))), first);
assert_eq!(range_keys(&map, (Included(0), Excluded(2))), first);
assert_eq!(range_keys(&map, (Included(0), Included(1))), first);
assert_eq!(range_keys(&map, (Included(1), Excluded(2))), first);
assert_eq!(range_keys(&map, (Included(1), Included(1))), first);
assert_eq!(range_keys(&map, (Unbounded, Excluded(2))), first);
assert_eq!(range_keys(&map, (Unbounded, Included(1))), first);
assert_eq!(range_keys(&map, (Excluded(size - 1), Excluded(size + 1))), last);
assert_eq!(range_keys(&map, (Excluded(size - 1), Included(size + 1))), last);
assert_eq!(range_keys(&map, (Excluded(size - 1), Included(size))), last);
assert_eq!(range_keys(&map, (Excluded(size - 1), Unbounded)), last);
assert_eq!(range_keys(&map, (Included(size), Excluded(size + 1))), last);
assert_eq!(range_keys(&map, (Included(size), Included(size + 1))), last);
assert_eq!(range_keys(&map, (Included(size), Included(size))), last);
assert_eq!(range_keys(&map, (Included(size), Unbounded)), last);
assert_eq!(range_keys(&map, (Excluded(size), Excluded(size + 1))), vec![]);
assert_eq!(range_keys(&map, (Excluded(size), Included(size))), vec![]);
assert_eq!(range_keys(&map, (Excluded(size), Unbounded)), vec![]);
assert_eq!(range_keys(&map, (Included(size + 1), Excluded(size + 1))), vec![]);
assert_eq!(range_keys(&map, (Included(size + 1), Included(size + 1))), vec![]);
assert_eq!(range_keys(&map, (Included(size + 1), Unbounded)), vec![]);
fn check<'a, L, R>(lhs: L, rhs: R)
where
L: IntoIterator<Item = (&'a i32, &'a i32)>,
R: IntoIterator<Item = (&'a i32, &'a i32)>,
{
assert_eq!(Vec::from_iter(lhs), Vec::from_iter(rhs));
}
check(map.range(..=100), map.range(..101));
check(map.range(5..=8), vec![(&5, &5), (&6, &6), (&7, &7), (&8, &8)]);
check(map.range(-1..=2), vec![(&1, &1), (&2, &2)]);
}
#[test]
fn test_range_inclusive_max_value() {
let max = usize::MAX;
let map = BTreeMap::from([(max, 0)]);
assert_eq!(Vec::from_iter(map.range(max..=max)), &[(&max, &0)]);
}
#[test]
fn test_range_equal_empty_cases() {
let map = BTreeMap::from_iter((0..5).map(|i| (i, i)));
assert_eq!(map.range((Included(2), Excluded(2))).next(), None);
assert_eq!(map.range((Excluded(2), Included(2))).next(), None);
}
#[test]
#[should_panic]
fn test_range_equal_excluded() {
let map = BTreeMap::from_iter((0..5).map(|i| (i, i)));
let _ = map.range((Excluded(2), Excluded(2)));
}
#[test]
#[should_panic]
fn test_range_backwards_1() {
let map = BTreeMap::from_iter((0..5).map(|i| (i, i)));
let _ = map.range((Included(3), Included(2)));
}
#[test]
#[should_panic]
fn test_range_backwards_2() {
let map = BTreeMap::from_iter((0..5).map(|i| (i, i)));
let _ = map.range((Included(3), Excluded(2)));
}
#[test]
#[should_panic]
fn test_range_backwards_3() {
let map = BTreeMap::from_iter((0..5).map(|i| (i, i)));
let _ = map.range((Excluded(3), Included(2)));
}
#[test]
#[should_panic]
fn test_range_backwards_4() {
let map = BTreeMap::from_iter((0..5).map(|i| (i, i)));
let _ = map.range((Excluded(3), Excluded(2)));
}
#[test]
fn test_range_finding_ill_order_in_map() {
let mut map = BTreeMap::new();
map.insert(Cyclic3::B, ());
// Lacking static_assert, call `range` conditionally, to emphasise that
// we cause a different panic than `test_range_backwards_1` does.
// A more refined `should_panic` would be welcome.
if Cyclic3::C < Cyclic3::A {
let _ = map.range(Cyclic3::C..=Cyclic3::A);
}
}
#[test]
fn test_range_finding_ill_order_in_range_ord() {
// Has proper order the first time asked, then flips around.
struct EvilTwin(i32);
impl PartialOrd for EvilTwin {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
static COMPARES: AtomicUsize = AtomicUsize::new(0);
impl Ord for EvilTwin {
fn cmp(&self, other: &Self) -> Ordering {
let ord = self.0.cmp(&other.0);
if COMPARES.fetch_add(1, SeqCst) > 0 { ord.reverse() } else { ord }
}
}
impl PartialEq for EvilTwin {
fn eq(&self, other: &Self) -> bool {
self.0.eq(&other.0)
}
}
impl Eq for EvilTwin {}
#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct CompositeKey(i32, EvilTwin);
impl Borrow<EvilTwin> for CompositeKey {
fn borrow(&self) -> &EvilTwin {
&self.1
}
}
let map = BTreeMap::from_iter((0..12).map(|i| (CompositeKey(i, EvilTwin(i)), ())));
let _ = map.range(EvilTwin(5)..=EvilTwin(7));
}
#[test]
fn test_range_1000() {
// Miri is too slow
let size = if cfg!(miri) { MIN_INSERTS_HEIGHT_2 as u32 } else { 1000 };
let map = BTreeMap::from_iter((0..size).map(|i| (i, i)));
fn test(map: &BTreeMap<u32, u32>, size: u32, min: Bound<&u32>, max: Bound<&u32>) {
let mut kvs = map.range((min, max)).map(|(&k, &v)| (k, v));
let mut pairs = (0..size).map(|i| (i, i));
for (kv, pair) in kvs.by_ref().zip(pairs.by_ref()) {
assert_eq!(kv, pair);
}
assert_eq!(kvs.next(), None);
assert_eq!(pairs.next(), None);
}
test(&map, size, Included(&0), Excluded(&size));
test(&map, size, Unbounded, Excluded(&size));
test(&map, size, Included(&0), Included(&(size - 1)));
test(&map, size, Unbounded, Included(&(size - 1)));
test(&map, size, Included(&0), Unbounded);
test(&map, size, Unbounded, Unbounded);
}
#[test]
fn test_range_borrowed_key() {
let mut map = BTreeMap::new();
map.insert("aardvark".to_string(), 1);
map.insert("baboon".to_string(), 2);
map.insert("coyote".to_string(), 3);
map.insert("dingo".to_string(), 4);
// NOTE: would like to use simply "b".."d" here...
let mut iter = map.range::<str, _>((Included("b"), Excluded("d")));
assert_eq!(iter.next(), Some((&"baboon".to_string(), &2)));
assert_eq!(iter.next(), Some((&"coyote".to_string(), &3)));
assert_eq!(iter.next(), None);
}
#[test]
fn test_range() {
let size = 200;
// Miri is too slow
let step = if cfg!(miri) { 66 } else { 1 };
let map = BTreeMap::from_iter((0..size).map(|i| (i, i)));
for i in (0..size).step_by(step) {
for j in (i..size).step_by(step) {
let mut kvs = map.range((Included(&i), Included(&j))).map(|(&k, &v)| (k, v));
let mut pairs = (i..=j).map(|i| (i, i));
for (kv, pair) in kvs.by_ref().zip(pairs.by_ref()) {
assert_eq!(kv, pair);
}
assert_eq!(kvs.next(), None);
assert_eq!(pairs.next(), None);
}
}
}
#[test]
fn test_range_mut() {
let size = 200;
// Miri is too slow
let step = if cfg!(miri) { 66 } else { 1 };
let mut map = BTreeMap::from_iter((0..size).map(|i| (i, i)));
for i in (0..size).step_by(step) {
for j in (i..size).step_by(step) {
let mut kvs = map.range_mut((Included(&i), Included(&j))).map(|(&k, &mut v)| (k, v));
let mut pairs = (i..=j).map(|i| (i, i));
for (kv, pair) in kvs.by_ref().zip(pairs.by_ref()) {
assert_eq!(kv, pair);
}
assert_eq!(kvs.next(), None);
assert_eq!(pairs.next(), None);
}
}
map.check();
}
#[should_panic(expected = "range start is greater than range end in BTreeMap")]
#[test]
fn test_range_panic_1() {
let mut map = BTreeMap::new();
map.insert(3, "a");
map.insert(5, "b");
map.insert(8, "c");
let _invalid_range = map.range((Included(&8), Included(&3)));
}
#[should_panic(expected = "range start and end are equal and excluded in BTreeMap")]
#[test]
fn test_range_panic_2() {
let mut map = BTreeMap::new();
map.insert(3, "a");
map.insert(5, "b");
map.insert(8, "c");
let _invalid_range = map.range((Excluded(&5), Excluded(&5)));
}
#[should_panic(expected = "range start and end are equal and excluded in BTreeMap")]
#[test]
fn test_range_panic_3() {
let mut map: BTreeMap<i32, ()> = BTreeMap::new();
map.insert(3, ());
map.insert(5, ());
map.insert(8, ());
let _invalid_range = map.range((Excluded(&5), Excluded(&5)));
}
#[test]
fn test_retain() {
let mut map = BTreeMap::from_iter((0..100).map(|x| (x, x * 10)));
map.retain(|&k, _| k % 2 == 0);
assert_eq!(map.len(), 50);
assert_eq!(map[&2], 20);
assert_eq!(map[&4], 40);
assert_eq!(map[&6], 60);
}
mod test_extract_if {
use super::*;
#[test]
fn empty() {
let mut map: BTreeMap<i32, i32> = BTreeMap::new();
map.extract_if(|_, _| unreachable!("there's nothing to decide on")).for_each(drop);
assert_eq!(map.height(), None);
map.check();
}
// Explicitly consumes the iterator, where most test cases drop it instantly.
#[test]
fn consumed_keeping_all() {
let pairs = (0..3).map(|i| (i, i));
let mut map = BTreeMap::from_iter(pairs);
assert!(map.extract_if(|_, _| false).eq(iter::empty()));
map.check();
}
// Explicitly consumes the iterator, where most test cases drop it instantly.
#[test]
fn consumed_removing_all() {
let pairs = (0..3).map(|i| (i, i));
let mut map = BTreeMap::from_iter(pairs.clone());
assert!(map.extract_if(|_, _| true).eq(pairs));
assert!(map.is_empty());
map.check();
}
// Explicitly consumes the iterator and modifies values through it.
#[test]
fn mutating_and_keeping() {
let pairs = (0..3).map(|i| (i, i));
let mut map = BTreeMap::from_iter(pairs);
assert!(
map.extract_if(|_, v| {
*v += 6;
false
})
.eq(iter::empty())
);
assert!(map.keys().copied().eq(0..3));
assert!(map.values().copied().eq(6..9));
map.check();
}
// Explicitly consumes the iterator and modifies values through it.
#[test]
fn mutating_and_removing() {
let pairs = (0..3).map(|i| (i, i));
let mut map = BTreeMap::from_iter(pairs);
assert!(
map.extract_if(|_, v| {
*v += 6;
true
})
.eq((0..3).map(|i| (i, i + 6)))
);
assert!(map.is_empty());