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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
//! A `Vec<T>`-like collection which guarantees stable indices and features
//! O(1) deletion of elements.
//!
//! You can find nearly all the relevant documentation on the type
//! [`StableVecFacade`]. This is the main type which is configurable over the
//! core implementation. To use a pre-configured stable vector, use
//! [`StableVec`].
//!
//! This crate uses `#![no_std]` but requires the `alloc` crate.
//!
//!
//! # Why?
//!
//! The standard `Vec<T>` always stores all elements contiguously. While this
//! has many advantages (most notable: cache friendliness), it has the
//! disadvantage that you can't simply remove an element from the middle; at
//! least not without shifting all elements after it to the left. And this has
//! two major drawbacks:
//!
//! 1. It has a linear O(n) time complexity
//! 2. It invalidates all indices of the shifted elements
//!
//! Invalidating an index means that a given index `i` who referred to an
//! element `a` before, now refers to another element `b`. On the contrary, a
//! *stable* index means, that the index always refers to the same element.
//!
//! Stable indices are needed in quite a few situations. One example are graph
//! data structures (or complex data structures in general). Instead of
//! allocating heap memory for every node and edge, all nodes and all edges are
//! stored in a vector (each). But how does the programmer unambiguously refer
//! to one specific node? A pointer is not possible due to the reallocation
//! strategy of most dynamically growing arrays (the pointer itself is not
//! *stable*). Thus, often the index is used.
//!
//! But in order to use the index, it has to be stable. This is one example,
//! where this data structure comes into play.
//!
//!
//! # How?
//!
//! We can trade O(1) deletions and stable indices for a higher memory
//! consumption.
//!
//! When `StableVec::remove()` is called, the element is just marked as
//! "deleted" (and the actual element is dropped), but other than that, nothing
//! happens. This has the very obvious disadvantage that deleted objects (so
//! called empty slots) just waste space. This is also the most important thing
//! to understand:
//!
//! The memory requirement of this data structure is `O(|inserted elements|)`;
//! instead of `O(|inserted elements| - |removed elements|)`. The latter is the
//! memory requirement of normal `Vec<T>`. Thus, if deletions are far more
//! numerous than insertions in your situation, then this data structure is
//! probably not fitting your needs.
//!
//!
//! # Why not?
//!
//! As mentioned above, this data structure is rather simple and has many
//! disadvantages on its own. Here are some reason not to use it:
//!
//! - You don't need stable indices or O(1) removal
//! - Your deletions significantly outnumber your insertions
//! - You want to choose your keys/indices
//! - Lookup times do not matter so much to you
//!
//! Especially in the last two cases, you could consider using a `HashMap` with
//! integer keys, best paired with a fast hash function for small keys.
//!
//! If you not only want stable indices, but stable pointers, you might want
//! to use something similar to a linked list. Although: think carefully about
//! your problem before using a linked list.
//!
//!
//! # Use of `unsafe` in this crate
//!
//! Unfortunately, implementing the features of this crate in a fast manner
//! requires `unsafe`. This was measured in micro-benchmarks (included in this
//! repository) and on a larger project using this crate. Thus, the use of
//! `unsafe` is measurement-guided and not just because it was assumed `unsafe`
//! makes things faster.
//!
//! This crate takes great care to ensure that all instances of `unsafe` are
//! actually safe. All methods on the (low level) `Core` trait have extensive
//! documentation of preconditions, invariants and postconditions. Comments in
//! functions usually describe why `unsafe` is safe. This crate contains a
//! fairly large number of unit tests and some tests with randomized input.
//! These tests are executed with `miri` to try to catch UB caused by invalid
//! `unsafe` code.
//!
//! That said, of course it cannot be guaranteed this crate is perfectly safe.
//! If you think you found an instance of incorrect usage of `unsafe` or any
//! UB, don't hesitate to open an issue immediately. Also, if you find `unsafe`
//! code that is not necessary and you can show that removing it does not
//! decrease execution speed, please also open an issue or PR!
//!

#![deny(missing_debug_implementations)]
#![deny(broken_intra_doc_links)]

// ----- Deal with `no_std` stuff --------------------------------------------
#![no_std]

// Import the real `std` for tests.
#[cfg(test)]
#[macro_use]
extern crate std;

// When compiling in a normal way, we use this compatibility layer that
// reexports symbols from `core` and `alloc` under the name `std`. This is just
// convenience so that all other imports in this crate can just use `std`.
#[cfg(not(test))]
extern crate no_std_compat as std;
// ---------------------------------------------------------------------------


use std::{
    prelude::v1::*,
    cmp,
    fmt,
    iter::FromIterator,
    mem,
    ops::{Index, IndexMut},
};
use crate::{
    core::{Core, DefaultCore, OwningCore, OptionCore, BitVecCore},
    iter::{Indices, Iter, IterMut, IntoIter, Values, ValuesMut},
};

#[cfg(test)]
mod tests;
pub mod core;
pub mod iter;



/// A stable vector with the default core implementation.
pub type StableVec<T> = StableVecFacade<T, DefaultCore<T>>;

/// A stable vector which stores the "deleted information" inline. This is very
/// close to `Vec<Option<T>>`.
///
/// This is particularly useful if `T` benefits from "null optimization", i.e.
/// if `size_of::<T>() == size_of::<Option<T>>()`.
pub type InlineStableVec<T> = StableVecFacade<T, OptionCore<T>>;

/// A stable vector which stores the "deleted information" externally in a bit
/// vector.
pub type ExternStableVec<T> = StableVecFacade<T, BitVecCore<T>>;


/// A `Vec<T>`-like collection which guarantees stable indices and features
/// O(1) deletion of elements.
///
///
/// # Terminology and overview of a stable vector
///
/// A stable vector has slots. Each slot can either be filled or empty. There
/// are three numbers describing a stable vector (each of those functions runs
/// in O(1)):
///
/// - [`capacity()`][StableVecFacade::capacity]: the total number of slots
///   (filled and empty).
/// - [`num_elements()`][StableVecFacade::num_elements]: the number of filled
///   slots.
/// - [`next_push_index()`][StableVecFacade::next_push_index]: the index of the
///   first slot (i.e. with the smallest index) that was never filled. This is
///   the index that is returned by [`push`][StableVecFacade::push]. This
///   implies that all filled slots have indices smaller than
///   `next_push_index()`.
///
/// Here is an example visualization (with `num_elements = 4`).
///
/// ```text
///      0   1   2   3   4   5   6   7   8   9   10
///    ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
///    │ a │ - │ b │ c │ - │ - │ d │ - │ - │ - │
///    └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
///                                      ↑       ↑
///                        next_push_index       capacity
/// ```
///
/// Unlike `Vec<T>`, `StableVecFacade` allows access to all slots with indices
/// between 0 and `capacity()`. In particular, it is allowed to call
/// [`insert`][StableVecFacade::insert] with all indices smaller than
/// `capacity()`.
///
///
/// # The Core implementation `C`
///
/// You might have noticed the type parameter `C`. There are actually multiple
/// ways how to implement the abstact data structure described above. One might
/// basically use a `Vec<Option<T>>`. But there are other ways, too.
///
/// Most of the time, you can simply use the alias [`StableVec`] which uses the
/// [`DefaultCore`]. This is fine for almost all cases. That's why all
/// documentation examples use that type instead of the generic
/// `StableVecFacade`.
///
///
/// # Implemented traits
///
/// This type implements a couple of traits. Some of those implementations
/// require further explanation:
///
/// - `Clone`: the cloned instance is exactly the same as the original,
///   including empty slots.
/// - `Extend`, `FromIterator`, `From<AsRef<[T]>>`: these impls work as if all
///   of the source elements are just `push`ed onto the stable vector in order.
/// - `PartialEq<Self>`/`Eq`: empty slots, capacity, `next_push_index` and the
///   indices of elements are all checked. In other words: all observable
///   properties of the stable vectors need to be the same for them to be
///   "equal".
/// - `PartialEq<[B]>`/`PartialEq<Vec<B>>`: capacity, `next_push_index`, empty
///   slots and indices are ignored for the comparison. It is equivalent to
///   `sv.iter().eq(vec)`.
///
/// # Overview of important methods
///
/// (*there are more methods than mentioned in this overview*)
///
/// **Creating a stable vector**
///
/// - [`new`][StableVecFacade::new]
/// - [`with_capacity`][StableVecFacade::with_capacity]
/// - [`FromIterator::from_iter`](#impl-FromIterator<T>)
///
/// **Adding and removing elements**
///
/// - [`push`][StableVecFacade::push]
/// - [`insert`][StableVecFacade::insert]
/// - [`remove`][StableVecFacade::remove]
///
/// **Accessing elements**
///
/// - [`get`][StableVecFacade::get] and [`get_mut`][StableVecFacade::get_mut]
///   (returns `Option<&T>` and `Option<&mut T>`)
/// - [the `[]` index operator](#impl-Index<usize>) (returns `&T` or `&mut T`)
/// - [`remove`][StableVecFacade::remove] (returns `Option<T>`)
///
/// **Stable vector specifics**
///
/// - [`has_element_at`][StableVecFacade::has_element_at]
/// - [`next_push_index`][StableVecFacade::next_push_index]
/// - [`is_compact`][StableVecFacade::is_compact]
///
#[derive(Clone)]
pub struct StableVecFacade<T, C: Core<T>> {
    core: OwningCore<T, C>,
    num_elements: usize,
}

impl<T, C: Core<T>> StableVecFacade<T, C> {
    /// Constructs a new, empty stable vector.
    ///
    /// The stable-vector will not allocate until elements are pushed onto it.
    pub fn new() -> Self {
        Self {
            core: OwningCore::new(C::new()),
            num_elements: 0,
        }
    }

    /// Constructs a new, empty stable vector with the specified capacity.
    ///
    /// The stable-vector will be able to hold exactly `capacity` elements
    /// without reallocating. If `capacity` is 0, the stable-vector will not
    /// allocate any memory. See [`reserve`][StableVecFacade::reserve] for more
    /// information.
    pub fn with_capacity(capacity: usize) -> Self {
        let mut out = Self::new();
        out.reserve_exact(capacity);
        out
    }

    /// Inserts the new element `elem` at index `self.next_push_index` and
    /// returns said index.
    ///
    /// The inserted element will always be accessible via the returned index.
    ///
    /// This method has an amortized runtime complexity of O(1), just like
    /// `Vec::push`.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::new();
    /// let star_idx = sv.push('★');
    /// let heart_idx = sv.push('♥');
    ///
    /// assert_eq!(sv.get(heart_idx), Some(&'♥'));
    ///
    /// // After removing the star we can still use the heart's index to access
    /// // the element!
    /// sv.remove(star_idx);
    /// assert_eq!(sv.get(heart_idx), Some(&'♥'));
    /// ```
    pub fn push(&mut self, elem: T) -> usize {
        let index = self.core.len();
        self.reserve(1);

        unsafe {
            // Due to `reserve`, the core holds at least one empty slot, so we
            // know that `index` is smaller than the capacity. We also know
            // that at `index` there is no element (the definition of `len`
            // guarantees this).
            self.core.set_len(index + 1);
            self.core.insert_at(index, elem);
        }

        self.num_elements += 1;
        index
    }

    /// Inserts the given value at the given index.
    ///
    /// If the slot at `index` is empty, the `elem` is inserted at that
    /// position and `None` is returned. If there is an existing element `x` at
    /// that position, that element is replaced by `elem` and `Some(x)` is
    /// returned. The `next_push_index` is adjusted accordingly if `index >=
    /// next_push_index()`.
    ///
    ///
    /// # Panics
    ///
    /// Panics if the index is `>= self.capacity()`.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::new();
    /// let star_idx = sv.push('★');
    /// let heart_idx = sv.push('♥');
    ///
    /// // Inserting into an empty slot (element was deleted).
    /// sv.remove(star_idx);
    /// assert_eq!(sv.num_elements(), 1);
    /// assert_eq!(sv.insert(star_idx, 'x'), None);
    /// assert_eq!(sv.num_elements(), 2);
    /// assert_eq!(sv[star_idx], 'x');
    ///
    /// // We can also reserve memory (create new empty slots) and insert into
    /// // such a new slot. Note that that `next_push_index` gets adjusted.
    /// sv.reserve_for(5);
    /// assert_eq!(sv.insert(5, 'y'), None);
    /// assert_eq!(sv.num_elements(), 3);
    /// assert_eq!(sv.next_push_index(), 6);
    /// assert_eq!(sv[5], 'y');
    ///
    /// // Inserting into a filled slot replaces the value and returns the old
    /// // value.
    /// assert_eq!(sv.insert(heart_idx, 'z'), Some('♥'));
    /// assert_eq!(sv[heart_idx], 'z');
    /// ```
    pub fn insert(&mut self, index: usize, mut elem: T) -> Option<T> {
        // If the index is out of bounds, we cannot insert the new element.
        if index >= self.core.cap() {
            panic!(
                "`index ({}) >= capacity ({})` in `StableVecFacade::insert`",
                index,
                self.core.cap(),
            );
        }

        if self.has_element_at(index) {
            unsafe {
                // We just checked there is an element at that position, so
                // this is fine.
                mem::swap(self.core.get_unchecked_mut(index), &mut elem);
            }
            Some(elem)
        } else {
            if index >= self.core.len() {
                // Due to the bounds check above, we know that `index + 1` is ≤
                // `capacity`.
                unsafe {
                    self.core.set_len(index + 1);
                }
            }

            unsafe {
                // `insert_at` requires that `index < cap` and
                // `!has_element_at(index)`. Both of these conditions are met
                // by the two explicit checks above.
                self.core.insert_at(index, elem);
            }

            self.num_elements += 1;

            None
        }
    }

    /// Removes and returns the element at position `index`. If the slot at
    /// `index` is empty, nothing is changed and `None` is returned.
    ///
    /// This simply marks the slot at `index` as empty. The elements after the
    /// given index are **not** shifted to the left. Thus, the time complexity
    /// of this method is O(1).
    ///
    /// # Panic
    ///
    /// Panics if `index >= self.capacity()`.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::new();
    /// let star_idx = sv.push('★');
    /// let heart_idx = sv.push('♥');
    ///
    /// assert_eq!(sv.remove(star_idx), Some('★'));
    /// assert_eq!(sv.remove(star_idx), None); // the star was already removed
    ///
    /// // We can use the heart's index here. It has not been invalidated by
    /// // the removal of the star.
    /// assert_eq!(sv.remove(heart_idx), Some('♥'));
    /// assert_eq!(sv.remove(heart_idx), None); // the heart was already removed
    /// ```
    pub fn remove(&mut self, index: usize) -> Option<T> {
        // If the index is out of bounds, we cannot insert the new element.
        if index >= self.core.cap() {
            panic!(
                "`index ({}) >= capacity ({})` in `StableVecFacade::remove`",
                index,
                self.core.cap(),
            );
        }

        if self.has_element_at(index) {
            // We checked with `Self::has_element_at` that the conditions for
            // `remove_at` are met.
            let elem = unsafe {
                self.core.remove_at(index)
            };

            self.num_elements -= 1;
            Some(elem)
        } else {
            None
        }
    }

    /// Removes all elements from this collection.
    ///
    /// After calling this, `num_elements()` will return 0. All indices are
    /// invalidated. However, no memory is deallocated, so the capacity stays
    /// as it was before. `self.next_push_index` is 0 after calling this method.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&['a', 'b']);
    ///
    /// sv.clear();
    /// assert_eq!(sv.num_elements(), 0);
    /// assert!(sv.capacity() >= 2);
    /// ```
    pub fn clear(&mut self) {
        self.core.clear();
        self.num_elements = 0;
    }

    /// Returns a reference to the element at the given index, or `None` if
    /// there exists no element at that index.
    ///
    /// If you are calling `unwrap()` on the result of this method anyway,
    /// rather use the index operator instead: `stable_vec[index]`.
    pub fn get(&self, index: usize) -> Option<&T> {
        if self.has_element_at(index) {
            // We might call this, because we checked both conditions via
            // `Self::has_element_at`.
            let elem = unsafe {
                self.core.get_unchecked(index)
            };
            Some(elem)
        } else {
            None
        }
    }

    /// Returns a mutable reference to the element at the given index, or
    /// `None` if there exists no element at that index.
    ///
    /// If you are calling `unwrap()` on the result of this method anyway,
    /// rather use the index operator instead: `stable_vec[index]`.
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        if self.has_element_at(index) {
            // We might call this, because we checked both conditions via
            // `Self::has_element_at`.
            let elem = unsafe {
                self.core.get_unchecked_mut(index)
            };
            Some(elem)
        } else {
            None
        }
    }

    /// Returns a reference to the element at the given index without checking
    /// the index.
    ///
    /// # Security
    ///
    /// When calling this method `self.has_element_at(index)` has to be `true`,
    /// otherwise this method's behavior is undefined! This requirement implies
    /// the requirement `index < self.next_push_index()`.
    pub unsafe fn get_unchecked(&self, index: usize) -> &T {
        self.core.get_unchecked(index)
    }

    /// Returns a mutable reference to the element at the given index without
    /// checking the index.
    ///
    /// # Security
    ///
    /// When calling this method `self.has_element_at(index)` has to be `true`,
    /// otherwise this method's behavior is undefined! This requirement implies
    /// the requirement `index < self.next_push_index()`.
    pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
        self.core.get_unchecked_mut(index)
    }

    /// Returns `true` if there exists an element at the given index (i.e. the
    /// slot at `index` is *not* empty), `false` otherwise.
    ///
    /// An element is said to exist if the index is not out of bounds and the
    /// slot at the given index is not empty. In particular, this method can
    /// also be called with indices larger than the current capacity (although,
    /// `false` is always returned in those cases).
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::new();
    /// assert!(!sv.has_element_at(3));         // no: index out of bounds
    ///
    /// let heart_idx = sv.push('♥');
    /// assert!(sv.has_element_at(heart_idx));  // yes
    ///
    /// sv.remove(heart_idx);
    /// assert!(!sv.has_element_at(heart_idx)); // no: was removed
    /// ```
    pub fn has_element_at(&self, index: usize) -> bool {
        if index >= self.core.cap() {
            false
        } else {
            unsafe {
                // The index is smaller than the capacity, as checked aboved,
                // so we can call this without a problem.
                self.core.has_element_at(index)
            }
        }
    }

    /// Returns the number of existing elements in this collection.
    ///
    /// As long as no element is ever removed, `num_elements()` equals
    /// `next_push_index()`. Once an element has been removed, `num_elements()`
    /// will always be less than `next_push_index()` (assuming
    /// `[reordering_]make_compact()` is not called).
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::new();
    /// assert_eq!(sv.num_elements(), 0);
    ///
    /// let heart_idx = sv.push('♥');
    /// assert_eq!(sv.num_elements(), 1);
    ///
    /// sv.remove(heart_idx);
    /// assert_eq!(sv.num_elements(), 0);
    /// ```
    pub fn num_elements(&self) -> usize {
        self.num_elements
    }

    /// Returns the index that would be returned by calling
    /// [`push()`][StableVecFacade::push]. All filled slots have indices below
    /// `next_push_index()`.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&['a', 'b', 'c']);
    ///
    /// let next_push_index = sv.next_push_index();
    /// let index_of_d = sv.push('d');
    ///
    /// assert_eq!(next_push_index, index_of_d);
    /// ```
    pub fn next_push_index(&self) -> usize {
        self.core.len()
    }

    /// Returns the number of slots in this stable vector.
    pub fn capacity(&self) -> usize {
        self.core.cap()
    }

    /// Returns `true` if this collection doesn't contain any existing
    /// elements.
    ///
    /// This means that `is_empty()` returns true iff no elements were inserted
    /// *or* all inserted elements were removed again.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::new();
    /// assert!(sv.is_empty());
    ///
    /// let heart_idx = sv.push('♥');
    /// assert!(!sv.is_empty());
    ///
    /// sv.remove(heart_idx);
    /// assert!(sv.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.num_elements == 0
    }

    /// Returns `true` if all existing elements are stored contiguously from
    /// the beginning (in other words: there are no empty slots with indices
    /// below `self.next_push_index()`).
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[0, 1, 2, 3, 4]);
    /// assert!(sv.is_compact());
    ///
    /// sv.remove(1);
    /// assert!(!sv.is_compact());
    /// ```
    pub fn is_compact(&self) -> bool {
        self.num_elements == self.core.len()
    }

    /// Returns an iterator over indices and immutable references to the stable
    /// vector's elements. Elements are yielded in order of their increasing
    /// indices.
    ///
    /// Note that you can also obtain this iterator via the `IntoIterator` impl
    /// of `&StableVecFacade`.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[10, 11, 12, 13, 14]);
    /// sv.remove(1);
    ///
    /// let mut it = sv.iter().filter(|&(_, &n)| n <= 13);
    /// assert_eq!(it.next(), Some((0, &10)));
    /// assert_eq!(it.next(), Some((2, &12)));
    /// assert_eq!(it.next(), Some((3, &13)));
    /// assert_eq!(it.next(), None);
    /// ```
    pub fn iter(&self) -> Iter<'_, T, C> {
        Iter::new(self)
    }

    /// Returns an iterator over indices and mutable references to the stable
    /// vector's elements. Elements are yielded in order of their increasing
    /// indices.
    ///
    /// Note that you can also obtain this iterator via the `IntoIterator` impl
    /// of `&mut StableVecFacade`.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[10, 11, 12, 13, 14]);
    /// sv.remove(1);
    ///
    /// for (idx, elem) in &mut sv {
    ///     if idx % 2 == 0 {
    ///         *elem *= 2;
    ///     }
    /// }
    ///
    /// assert_eq!(sv, vec![20, 24, 13, 28]);
    /// ```
    pub fn iter_mut(&mut self) -> IterMut<'_, T, C> {
        IterMut::new(self)
    }

    /// Returns an iterator over immutable references to the existing elements
    /// of this stable vector. Elements are yielded in order of their
    /// increasing indices.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[0, 1, 2, 3, 4]);
    /// sv.remove(1);
    ///
    /// let mut it = sv.values().filter(|&&n| n <= 3);
    /// assert_eq!(it.next(), Some(&0));
    /// assert_eq!(it.next(), Some(&2));
    /// assert_eq!(it.next(), Some(&3));
    /// assert_eq!(it.next(), None);
    /// ```
    pub fn values(&self) -> Values<'_, T, C> {
        Values::new(self)
    }

    /// Returns an iterator over mutable references to the existing elements
    /// of this stable vector. Elements are yielded in order of their
    /// increasing indices.
    ///
    /// Through this iterator, the elements within the stable vector can be
    /// mutated.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[1.0, 2.0, 3.0]);
    ///
    /// for e in sv.values_mut() {
    ///     *e *= 2.0;
    /// }
    ///
    /// assert_eq!(sv, &[2.0, 4.0, 6.0] as &[_]);
    /// ```
    pub fn values_mut(&mut self) -> ValuesMut<T, C> {
        ValuesMut::new(self)
    }

    /// Returns an iterator over all indices of filled slots of this stable
    /// vector. Indices are yielded in increasing order.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&['a', 'b', 'c', 'd']);
    /// sv.remove(1);
    ///
    /// let mut it = sv.indices();
    /// assert_eq!(it.next(), Some(0));
    /// assert_eq!(it.next(), Some(2));
    /// assert_eq!(it.next(), Some(3));
    /// assert_eq!(it.next(), None);
    /// ```
    ///
    /// Simply using the `for`-loop:
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&['a', 'b', 'c', 'd']);
    ///
    /// for index in sv.indices() {
    ///     println!("index: {}", index);
    /// }
    /// ```
    pub fn indices(&self) -> Indices<'_, T, C> {
        Indices::new(self)
    }

    /// Reserves memory for at least `additional` more elements to be inserted
    /// at indices `>= self.next_push_index()`.
    ///
    /// This method might allocate more than `additional` to avoid frequent
    /// reallocations. Does nothing if the current capacity is already
    /// sufficient. After calling this method, `self.capacity()` is ≥
    /// `self.next_push_index() + additional`.
    ///
    /// Unlike `Vec::reserve`, the additional reserved memory is not completely
    /// unaccessible. Instead, additional empty slots are added to this stable
    /// vector. These can be used just like any other empty slot; in
    /// particular, you can insert into it.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::new();
    /// let star_idx = sv.push('★');
    ///
    /// // After we inserted one element, the next element would sit at index
    /// // 1, as expected.
    /// assert_eq!(sv.next_push_index(), 1);
    ///
    /// sv.reserve(2); // insert two empty slots
    ///
    /// // `reserve` doesn't change any of this
    /// assert_eq!(sv.num_elements(), 1);
    /// assert_eq!(sv.next_push_index(), 1);
    ///
    /// // We can now insert an element at index 2.
    /// sv.insert(2, 'x');
    /// assert_eq!(sv[2], 'x');
    ///
    /// // These values get adjusted accordingly.
    /// assert_eq!(sv.num_elements(), 2);
    /// assert_eq!(sv.next_push_index(), 3);
    /// ```
    pub fn reserve(&mut self, additional: usize) {
        #[inline(never)]
        #[cold]
        fn capacity_overflow() -> ! {
            panic!("capacity overflow in `stable_vec::StableVecFacade::reserve` (attempt \
                to allocate more than `isize::MAX` elements");
        }

        //:    new_cap = len + additional  ∧  additional >= 0
        //: => new_cap >= len
        let new_cap = match self.core.len().checked_add(additional) {
            None => capacity_overflow(),
            Some(new_cap) => new_cap,
        };

        if self.core.cap() < new_cap {
            // We at least double our capacity. Otherwise repeated `push`es are
            // O(n²).
            //
            // This multiplication can't overflow, because we know the capacity
            // is `<= isize::MAX`.
            //
            //:    new_cap = max(new_cap_before, 2 * cap)
            //:        ∧ cap >= len
            //:        ∧ new_cap_before >= len
            //: => new_cap >= len
            let new_cap = cmp::max(new_cap, 2 * self.core.cap());

            if new_cap > isize::max_value() as usize {
                capacity_overflow();
            }

            //: new_cap >= len  ∧  new_cap <= isize::MAX
            //
            // These both properties are exactly the preconditions of
            // `realloc`, so we can safely call that method.
            unsafe {
                self.core.realloc(new_cap);
            }
        }
    }

    /// Reserve enough memory so that there is a slot at `index`. Does nothing
    /// if `index < self.capacity()`.
    ///
    /// This method might allocate more memory than requested to avoid frequent
    /// allocations. After calling this method, `self.capacity() >= index + 1`.
    ///
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::new();
    /// let star_idx = sv.push('★');
    ///
    /// // Allocate enough memory so that we have a slot at index 5.
    /// sv.reserve_for(5);
    /// assert!(sv.capacity() >= 6);
    ///
    /// // We can now insert an element at index 5.
    /// sv.insert(5, 'x');
    /// assert_eq!(sv[5], 'x');
    ///
    /// // This won't do anything as the slot with index 3 already exists.
    /// let capacity_before = sv.capacity();
    /// sv.reserve_for(3);
    /// assert_eq!(sv.capacity(), capacity_before);
    /// ```
    pub fn reserve_for(&mut self, index: usize) {
        if index >= self.capacity() {
            // Won't underflow as `index >= capacity >= next_push_index`.
            self.reserve(1 + index - self.next_push_index());
        }
    }

    /// Like [`reserve`][StableVecFacade::reserve], but tries to allocate
    /// memory for exactly `additional` more elements.
    ///
    /// The underlying allocator might allocate more memory than requested,
    /// meaning that you cannot rely on the capacity of this stable vector
    /// having an exact value after calling this method.
    pub fn reserve_exact(&mut self, additional: usize) {
        #[inline(never)]
        #[cold]
        fn capacity_overflow() -> ! {
            panic!("capacity overflow in `stable_vec::StableVecFacade::reserve_exact` (attempt \
                to allocate more than `isize::MAX` elements");
        }

        //:    new_cap = len + additional  ∧  additional >= 0
        //: => new_cap >= len
        let new_cap = match self.core.len().checked_add(additional) {
            None => capacity_overflow(),
            Some(new_cap) => new_cap,
        };

        if self.core.cap() < new_cap {
            if new_cap > isize::max_value() as usize {
                capacity_overflow();
            }

            //: new_cap >= len  ∧  new_cap <= isize::MAX
            //
            // These both properties are exactly the preconditions of
            // `realloc`, so we can safely call that method.
            unsafe {
                self.core.realloc(new_cap);
            }
        }
    }

    /// Removes and returns the first element from this collection, or `None`
    /// if it's empty.
    ///
    /// This method uses exactly the same deletion strategy as
    /// [`remove()`][StableVecFacade::remove].
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[1, 2, 3]);
    /// assert_eq!(sv.remove_first(), Some(1));
    /// assert_eq!(sv, vec![2, 3]);
    /// ```
    ///
    /// # Note
    ///
    /// This method needs to find the index of the first valid element. Finding
    /// it has a worst case time complexity of O(n). If you already know the
    /// index, use [`remove()`][StableVecFacade::remove] instead.
    pub fn remove_first(&mut self) -> Option<T> {
        self.find_first_index().and_then(|index| self.remove(index))
    }

    /// Removes and returns the last element from this collection, or `None` if
    /// it's empty.
    ///
    /// This method uses exactly the same deletion strategy as
    /// [`remove()`][StableVecFacade::remove].
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[1, 2, 3]);
    /// assert_eq!(sv.remove_last(), Some(3));
    /// assert_eq!(sv, vec![1, 2]);
    /// ```
    ///
    /// # Note
    ///
    /// This method needs to find the index of the last valid element. Finding
    /// it has a worst case time complexity of O(n). If you already know the
    /// index, use [`remove()`][StableVecFacade::remove] instead.
    pub fn remove_last(&mut self) -> Option<T> {
        self.find_last_index().and_then(|index| self.remove(index))
    }

    /// Finds the first element and returns a reference to it, or `None` if
    /// the stable vector is empty.
    ///
    /// This method has a worst case time complexity of O(n).
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[1, 2]);
    /// sv.remove(0);
    /// assert_eq!(sv.find_first(), Some(&2));
    /// ```
    pub fn find_first(&self) -> Option<&T> {
        self.find_first_index().map(|index| unsafe { self.core.get_unchecked(index) })
    }

    /// Finds the first element and returns a mutable reference to it, or
    /// `None` if the stable vector is empty.
    ///
    /// This method has a worst case time complexity of O(n).
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[1, 2]);
    /// {
    ///     let first = sv.find_first_mut().unwrap();
    ///     assert_eq!(*first, 1);
    ///
    ///     *first = 3;
    /// }
    /// assert_eq!(sv, vec![3, 2]);
    /// ```
    pub fn find_first_mut(&mut self) -> Option<&mut T> {
        self.find_first_index().map(move |index| unsafe { self.core.get_unchecked_mut(index) })
    }

    /// Finds the last element and returns a reference to it, or `None` if
    /// the stable vector is empty.
    ///
    /// This method has a worst case time complexity of O(n).
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[1, 2]);
    /// sv.remove(1);
    /// assert_eq!(sv.find_last(), Some(&1));
    /// ```
    pub fn find_last(&self) -> Option<&T> {
        self.find_last_index().map(|index| unsafe { self.core.get_unchecked(index) })
    }

    /// Finds the last element and returns a mutable reference to it, or `None`
    /// if the stable vector is empty.
    ///
    /// This method has a worst case time complexity of O(n).
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[1, 2]);
    /// {
    ///     let last = sv.find_last_mut().unwrap();
    ///     assert_eq!(*last, 2);
    ///
    ///     *last = 3;
    /// }
    /// assert_eq!(sv, vec![1, 3]);
    /// ```
    pub fn find_last_mut(&mut self) -> Option<&mut T> {
        self.find_last_index().map(move |index| unsafe { self.core.get_unchecked_mut(index) })
    }

    /// Performs a forwards search starting at index `start`, returning the
    /// index of the first filled slot that is found.
    ///
    /// Specifically, if an element at index `start` exists, `Some(start)` is
    /// returned. If all slots with indices `start` and higher are empty (or
    /// don't exist), `None` is returned. This method can be used to iterate
    /// over all existing elements without an iterator object.
    ///
    /// The inputs `start >= self.next_push_index()` are only allowed for
    /// convenience. For those `start` values, `None` is always returned.
    ///
    /// # Panics
    ///
    /// Panics if `start > self.capacity()`. Note: `start == self.capacity()`
    /// is allowed for convenience, but always returns `None`.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[0, 1, 2, 3, 4]);
    /// sv.remove(1);
    /// sv.remove(2);
    /// sv.remove(4);
    ///
    /// assert_eq!(sv.first_filled_slot_from(0), Some(0));
    /// assert_eq!(sv.first_filled_slot_from(1), Some(3));
    /// assert_eq!(sv.first_filled_slot_from(2), Some(3));
    /// assert_eq!(sv.first_filled_slot_from(3), Some(3));
    /// assert_eq!(sv.first_filled_slot_from(4), None);
    /// assert_eq!(sv.first_filled_slot_from(5), None);
    /// ```
    pub fn first_filled_slot_from(&self, start: usize) -> Option<usize> {
        if start > self.core.cap() {
            panic!(
                "`start` is {}, but capacity is {} in `first_filled_slot_from`",
                start,
                self.capacity(),
            );
        } else {
            // The precondition `start <= self.core.cap()` is satisfied.
            unsafe { self.core.first_filled_slot_from(start) }
        }
    }

    /// Performs a backwards search starting at index `start - 1`, returning
    /// the index of the first filled slot that is found. For `start == 0`,
    /// `None` is returned.
    ///
    /// Note: passing in `start >= self.len()` just wastes time, as those slots
    /// are never filled.
    ///
    /// # Panics
    ///
    /// Panics if `start > self.capacity()`. Note: `start == self.capacity()`
    /// is allowed for convenience, but wastes time.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[0, 1, 2, 3, 4]);
    /// sv.remove(0);
    /// sv.remove(2);
    /// sv.remove(3);
    ///
    /// assert_eq!(sv.first_filled_slot_below(0), None);
    /// assert_eq!(sv.first_filled_slot_below(1), None);
    /// assert_eq!(sv.first_filled_slot_below(2), Some(1));
    /// assert_eq!(sv.first_filled_slot_below(3), Some(1));
    /// assert_eq!(sv.first_filled_slot_below(4), Some(1));
    /// assert_eq!(sv.first_filled_slot_below(5), Some(4));
    /// ```
    pub fn first_filled_slot_below(&self, start: usize) -> Option<usize> {
        if start > self.core.cap() {
            panic!(
                "`start` is {}, but capacity is {} in `first_filled_slot_below`",
                start,
                self.capacity(),
            );
        } else {
            // The precondition `start <= self.core.cap()` is satisfied.
            unsafe { self.core.first_filled_slot_below(start) }
        }
    }

    /// Performs a forwards search starting at index `start`, returning the
    /// index of the first empty slot that is found.
    ///
    /// Specifically, if the slot at index `start` is empty, `Some(start)` is
    /// returned. If all slots with indices `start` and higher are filled,
    /// `None` is returned.
    ///
    ///
    /// # Panics
    ///
    /// Panics if `start > self.capacity()`. Note: `start == self.capacity()`
    /// is allowed for convenience, but always returns `None`.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[0, 1, 2, 3, 4, 5]);
    /// sv.remove(1);
    /// sv.remove(2);
    /// sv.remove(4);
    ///
    /// assert_eq!(sv.first_empty_slot_from(0), Some(1));
    /// assert_eq!(sv.first_empty_slot_from(1), Some(1));
    /// assert_eq!(sv.first_empty_slot_from(2), Some(2));
    /// assert_eq!(sv.first_empty_slot_from(3), Some(4));
    /// assert_eq!(sv.first_empty_slot_from(4), Some(4));
    ///
    /// // Make sure we have at least one empty slot at the end
    /// sv.reserve_for(6);
    /// assert_eq!(sv.first_empty_slot_from(5), Some(6));
    /// assert_eq!(sv.first_empty_slot_from(6), Some(6));
    /// ```
    pub fn first_empty_slot_from(&self, start: usize) -> Option<usize> {
        if start > self.core.cap() {
            panic!(
                "`start` is {}, but capacity is {} in `first_empty_slot_from`",
                start,
                self.capacity(),
            );
        } else {
            unsafe { self.core.first_empty_slot_from(start) }
        }
    }

    /// Performs a backwards search starting at index `start - 1`, returning
    /// the index of the first empty slot that is found. For `start == 0`,
    /// `None` is returned.
    ///
    /// If all slots with indices below `start` are filled, `None` is returned.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[0, 1, 2, 3, 4, 5]);
    /// sv.remove(1);
    /// sv.remove(2);
    /// sv.remove(4);
    ///
    /// assert_eq!(sv.first_empty_slot_below(0), None);
    /// assert_eq!(sv.first_empty_slot_below(1), None);
    /// assert_eq!(sv.first_empty_slot_below(2), Some(1));
    /// assert_eq!(sv.first_empty_slot_below(3), Some(2));
    /// assert_eq!(sv.first_empty_slot_below(4), Some(2));
    /// assert_eq!(sv.first_empty_slot_below(5), Some(4));
    /// assert_eq!(sv.first_empty_slot_below(6), Some(4));
    /// ```
    pub fn first_empty_slot_below(&self, start: usize) -> Option<usize> {
        if start > self.core.cap() {
            panic!(
                "`start` is {}, but capacity is {} in `first_empty_slot_below`",
                start,
                self.capacity(),
            );
        } else {
            unsafe { self.core.first_empty_slot_below(start) }
        }
    }


    /// Finds the first element and returns its index, or `None` if the stable
    /// vector is empty.
    ///
    /// This method has a worst case time complexity of O(n).
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[1, 2]);
    /// sv.remove(0);
    /// assert_eq!(sv.find_first_index(), Some(1));
    /// ```
    pub fn find_first_index(&self) -> Option<usize> {
        // `0 <= self.core.cap()` is always true
        unsafe {
            self.core.first_filled_slot_from(0)
        }
    }

    /// Finds the last element and returns its index, or `None` if the stable
    /// vector is empty.
    ///
    /// This method has a worst case time complexity of O(n).
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[1, 2]);
    /// sv.remove(1);
    /// assert_eq!(sv.find_last_index(), Some(0));
    /// ```
    pub fn find_last_index(&self) -> Option<usize> {
        // `self.core.len() <= self.core.cap()` is always true
        unsafe {
            self.core.first_filled_slot_below(self.core.len())
        }
    }

    /// Reallocates to have a capacity as small as possible while still holding
    /// `self.next_push_index()` slots.
    ///
    /// Note that this does not move existing elements around and thus does not
    /// invalidate indices. This method also doesn't change what
    /// `next_push_index` returns. Instead, only the capacity is changed. Due
    /// to the underlying allocator, it cannot be guaranteed that the capacity
    /// is exactly `self.next_push_index()` after calling this method.
    ///
    /// If you want to compact this stable vector by removing deleted elements,
    /// use the method [`make_compact`][StableVecFacade::make_compact] or
    /// [`reordering_make_compact`][StableVecFacade::reordering_make_compact]
    /// instead.
    pub fn shrink_to_fit(&mut self) {
        // `realloc` has the following preconditions:
        // - (a) `new_cap ≥ self.len()`
        // - (b) `new_cap ≤ isize::MAX`
        //
        // It's trivial to see that (a) is not violated here. (b) is also never
        // violated, because the `Core` trait says that `len < cap` and `cap <
        // isize::MAX`.
        unsafe {
            let new_cap = self.core.len();
            self.core.realloc(new_cap);
        }
    }

    /// Rearranges elements to reclaim memory. **Invalidates indices!**
    ///
    /// After calling this method, all existing elements stored contiguously in
    /// memory. You might want to call [`shrink_to_fit()`][StableVecFacade::shrink_to_fit]
    /// afterwards to actually free memory previously used by removed elements.
    /// This method itself does not deallocate any memory.
    ///
    /// The `next_push_index` value is also changed by this method (if the
    /// stable vector wasn't compact before).
    ///
    /// In comparison to
    /// [`reordering_make_compact()`][StableVecFacade::reordering_make_compact],
    /// this method does not change the order of elements. Due to this, this
    /// method is a bit slower.
    ///
    /// # Warning
    ///
    /// This method invalidates the indices of all elements that are stored
    /// after the first empty slot in the stable vector!
    pub fn make_compact(&mut self) {
        if self.is_compact() {
            return;
        }

        // We only have to move elements, if we have any.
        if self.num_elements > 0 {
            unsafe {
                // We have to find the position of the first hole. We know that
                // there is at least one hole, so we can unwrap.
                let first_hole_index = self.core.first_empty_slot_from(0).unwrap();

                // This variable will store the first possible index of an element
                // which can be inserted in the hole.
                let mut element_index = first_hole_index + 1;

                // Beginning from the first hole, we have to fill each index with
                // a new value. This is required to keep the order of elements.
                for hole_index in first_hole_index..self.num_elements {
                    // Actually find the next element which we can use to fill the
                    // hole. Note that we do not check if `element_index` runs out
                    // of bounds. This will never happen! We do have enough
                    // elements to fill all holes. And once all holes are filled,
                    // the outer loop will stop.
                    while !self.core.has_element_at(element_index) {
                        element_index += 1;
                    }

                    // So at this point `hole_index` points to a valid hole and
                    // `element_index` points to a valid element. Time to swap!
                    self.core.swap(hole_index, element_index);
                }
            }
        }

        // We can safely call `set_len()` here: all elements are in the
        // range 0..self.num_elements.
        unsafe {
            self.core.set_len(self.num_elements);
        }
    }

    /// Rearranges elements to reclaim memory. **Invalidates indices and
    /// changes the order of the elements!**
    ///
    /// After calling this method, all existing elements stored contiguously
    /// in memory. You might want to call [`shrink_to_fit()`][StableVecFacade::shrink_to_fit]
    /// afterwards to actually free memory previously used by removed elements.
    /// This method itself does not deallocate any memory.
    ///
    /// The `next_push_index` value is also changed by this method (if the
    /// stable vector wasn't compact before).
    ///
    /// If you do need to preserve the order of elements, use
    /// [`make_compact()`][StableVecFacade::make_compact] instead. However, if
    /// you don't care about element order, you should prefer using this
    /// method, because it is faster.
    ///
    /// # Warning
    ///
    /// This method invalidates the indices of all elements that are stored
    /// after the first hole and it does not preserve the order of elements!
    pub fn reordering_make_compact(&mut self) {
        if self.is_compact() {
            return;
        }

        // We only have to move elements, if we have any.
        if self.num_elements > 0 {
            unsafe {
                // We use two indices:
                //
                // - `hole_index` starts from the front and searches for a hole
                //   that can be filled with an element.
                // - `element_index` starts from the back and searches for an
                //   element.
                let len = self.core.len();
                let mut element_index = len;
                let mut hole_index = 0;
                loop {
                    element_index = self.core.first_filled_slot_below(element_index).unwrap_or(0);
                    hole_index = self.core.first_empty_slot_from(hole_index).unwrap_or(len);

                    // If both indices passed each other, we can stop. There are no
                    // holes left of `hole_index` and no element right of
                    // `element_index`.
                    if hole_index > element_index {
                        break;
                    }

                    // We found an element and a hole left of the element. That
                    // means that we can swap.
                    self.core.swap(hole_index, element_index);
                }
            }
        }

        // We can safely call `set_len()` here: all elements are in the
        // range 0..self.num_elements.
        unsafe {
            self.core.set_len(self.num_elements);
        }
    }

    /// Returns `true` if the stable vector contains an element with the given
    /// value, `false` otherwise.
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&['a', 'b', 'c']);
    /// assert!(sv.contains(&'b'));
    ///
    /// sv.remove(1);   // 'b' is stored at index 1
    /// assert!(!sv.contains(&'b'));
    /// ```
    pub fn contains<U>(&self, item: &U) -> bool
    where
        U: PartialEq<T>,
    {
        self.values().any(|e| item == e)
    }

    /// Swaps the slot at index `a` with the slot at index `b`.
    ///
    /// The full slots are swapped, including the element and the "filled"
    /// state. If you swap slots with an element in it, that element's index is
    /// invalidated, of course. This method automatically sets
    /// `next_push_index` to a larger value if that's necessary.
    ///
    /// # Panics
    ///
    /// This panics if `a` or `b` are not smaller than `self.capacity()`.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&['a', 'b', 'c', 'd']);
    /// sv.reserve_for(5);
    /// assert_eq!(sv.next_push_index(), 4);
    ///
    /// // Swapping an empty slot with a filled one
    /// sv.swap(0, 5);
    /// assert_eq!(sv.get(0), None);
    /// assert_eq!(sv.get(1), Some(&'b'));
    /// assert_eq!(sv.get(2), Some(&'c'));
    /// assert_eq!(sv.get(3), Some(&'d'));
    /// assert_eq!(sv.get(4), None);
    /// assert_eq!(sv.get(5), Some(&'a'));
    /// assert_eq!(sv.next_push_index(), 6);
    ///
    /// // Swapping two filled slots
    /// sv.swap(1, 2);
    /// assert_eq!(sv.get(0), None);
    /// assert_eq!(sv.get(1), Some(&'c'));
    /// assert_eq!(sv.get(2), Some(&'b'));
    /// assert_eq!(sv.get(3), Some(&'d'));
    /// assert_eq!(sv.get(4), None);
    /// assert_eq!(sv.get(5), Some(&'a'));
    ///
    /// // You can also swap two empty slots, but that doesn't change anything.
    /// sv.swap(0, 4);
    /// assert_eq!(sv.get(0), None);
    /// assert_eq!(sv.get(1), Some(&'c'));
    /// assert_eq!(sv.get(2), Some(&'b'));
    /// assert_eq!(sv.get(3), Some(&'d'));
    /// assert_eq!(sv.get(4), None);
    /// assert_eq!(sv.get(5), Some(&'a'));
    /// ```
    pub fn swap(&mut self, a: usize, b: usize) {
        assert!(a < self.core.cap());
        assert!(b < self.core.cap());

        // Adjust the `len`
        let mut len = self.core.len();
        if a >= len && self.has_element_at(b) {
            len = a + 1;
        }
        if b >= len && self.has_element_at(a) {
            len = b + 1;
        }

        // Both indices are less than `cap`. These indices + 1 are <= cap. And
        // all slots with indices > `len` are empty.
        unsafe { self.core.set_len(len) };

        // With the asserts above we made sure the preconditions are met. The
        // maintain the core invariants, we increased the length.
        unsafe { self.core.swap(a, b) };

    }

    /// Retains only the elements specified by the given predicate.
    ///
    /// Each element `e` for which `should_be_kept(&e)` returns `false` is
    /// removed from the stable vector.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::from(&[1, 2, 3, 4, 5]);
    /// sv.retain(|&e| e % 2 == 0);
    ///
    /// assert_eq!(sv, &[2, 4] as &[_]);
    /// ```
    pub fn retain<P>(&mut self, mut should_be_kept: P)
    where
        P: FnMut(&T) -> bool,
    {
        let mut pos = 0;

        // These unsafe calls are fine: indices returned by
        // `first_filled_slot_from` are always valid and point to an existing
        // element.
        unsafe {
            while let Some(idx) = self.core.first_filled_slot_from(pos) {
                let elem = self.core.get_unchecked(idx);
                if !should_be_kept(elem) {
                    self.core.remove_at(idx);
                    self.num_elements -= 1;
                }

                pos = idx + 1;
            }
        }
    }

    /// Retains only the elements with indices specified by the given
    /// predicate.
    ///
    /// Each element with index `i` for which `should_be_kept(i)` returns
    /// `false` is removed from the stable vector.
    ///
    /// # Example
    ///
    /// ```
    /// # use stable_vec::StableVec;
    /// let mut sv = StableVec::new();
    /// sv.push(1);
    /// let two = sv.push(2);
    /// sv.push(3);
    /// sv.retain_indices(|i| i == two);
    ///
    /// assert_eq!(sv, &[2] as &[_]);
    /// ```
    pub fn retain_indices<P>(&mut self, mut should_be_kept: P)
    where
        P: FnMut(usize) -> bool,
    {
        let mut pos = 0;

        // These unsafe call is fine: indices returned by
        // `first_filled_slot_from` are always valid and point to an existing
        // element.
        unsafe {
            while let Some(idx) = self.core.first_filled_slot_from(pos) {
                if !should_be_kept(idx) {
                    self.core.remove_at(idx);
                    self.num_elements -= 1;
                }

                pos = idx + 1;
            }
        }
    }

    /// Appends all elements in `new_elements` to this stable vector. This is
    /// equivalent to calling [`push()`][StableVecFacade::push] for each
    /// element.
    pub fn extend_from_slice(&mut self, new_elements: &[T])
    where
        T: Clone,
    {
        let len = new_elements.len();

        self.reserve(len);
        self.num_elements += len;

        // It's important that a panic in `clone()` does not lead to memory
        // unsafety! The only way that could happen is if some uninitialized
        // values would be read when `out` is dropped. However, this won't
        // happen: the core won't ever drop uninitialized elements.
        //
        // So that's good. But we also would like to drop all elements that
        // have already been inserted. That's why we set the length first.
        unsafe {
            let mut i = self.core.len();
            let new_len = self.core.len() + len;
            self.core.set_len(new_len);

            for elem in new_elements {
                self.core.insert_at(i, elem.clone());
                i += 1;
            }
        }
    }
}


#[inline(never)]
#[cold]
fn index_fail(idx: usize) -> ! {
    panic!("attempt to index StableVec with index {}, but no element exists at that index", idx);
}

impl<T, C: Core<T>> Index<usize> for StableVecFacade<T, C> {
    type Output = T;

    fn index(&self, index: usize) -> &T {
        match self.get(index) {
            Some(v) => v,
            None => index_fail(index),
        }
    }
}

impl<T, C: Core<T>> IndexMut<usize> for StableVecFacade<T, C> {
    fn index_mut(&mut self, index: usize) -> &mut T {
        match self.get_mut(index) {
            Some(v) => v,
            None => index_fail(index),
        }
    }
}

impl<T, C: Core<T>> Default for StableVecFacade<T, C> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T, S, C: Core<T>> From<S> for StableVecFacade<T, C>
where
    S: AsRef<[T]>,
    T: Clone,
{
    fn from(slice: S) -> Self {
        let mut out = Self::new();
        out.extend_from_slice(slice.as_ref());
        out
    }
}

impl<T, C: Core<T>> FromIterator<T> for StableVecFacade<T, C> {
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = T>,
    {
        let mut out = Self::new();
        out.extend(iter);
        out
    }
}

impl<T, C: Core<T>> Extend<T> for StableVecFacade<T, C> {
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = T>,
    {
        let it = iter.into_iter();
        self.reserve(it.size_hint().0);

        for elem in it {
            self.push(elem);
        }
    }
}

impl<'a, T, C: Core<T>> IntoIterator for &'a StableVecFacade<T, C> {
    type Item = (usize, &'a T);
    type IntoIter = Iter<'a, T, C>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T, C: Core<T>> IntoIterator for &'a mut StableVecFacade<T, C> {
    type Item = (usize, &'a mut T);
    type IntoIter = IterMut<'a, T, C>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl<T, C: Core<T>> IntoIterator for StableVecFacade<T, C> {
    type Item = (usize, T);
    type IntoIter = IntoIter<T, C>;
    fn into_iter(self) -> Self::IntoIter {
        IntoIter::new(self)
    }
}

impl<T: fmt::Debug, C: Core<T>> fmt::Debug for StableVecFacade<T, C> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "StableVec ")?;
        f.debug_list().entries(self.values()).finish()
    }
}

impl<Ta, Tb, Ca, Cb> PartialEq<StableVecFacade<Tb, Cb>> for StableVecFacade<Ta, Ca>
where
    Ta: PartialEq<Tb>,
    Ca: Core<Ta>,
    Cb: Core<Tb>,
{
    fn eq(&self, other: &StableVecFacade<Tb, Cb>) -> bool {
        self.num_elements() == other.num_elements()
            && self.capacity() == other.capacity()
            && self.next_push_index() == other.next_push_index()
            && (0..self.capacity()).all(|idx| {
                match (self.get(idx), other.get(idx)) {
                    (None, None) => true,
                    (Some(a), Some(b)) => a == b,
                    _ => false,
                }
            })
    }
}

impl<T: Eq, C: Core<T>> Eq for StableVecFacade<T, C> {}

impl<A, B, C: Core<A>> PartialEq<[B]> for StableVecFacade<A, C>
where
    A: PartialEq<B>,
{
    fn eq(&self, other: &[B]) -> bool {
        self.values().eq(other)
    }
}

impl<'other, A, B, C: Core<A>> PartialEq<&'other [B]> for StableVecFacade<A, C>
where
    A: PartialEq<B>,
{
    fn eq(&self, other: &&'other [B]) -> bool {
        self == *other
    }
}

impl<A, B, C: Core<A>> PartialEq<Vec<B>> for StableVecFacade<A, C>
where
    A: PartialEq<B>,
{
    fn eq(&self, other: &Vec<B>) -> bool {
        self == &other[..]
    }
}