justly 0.1.1

An implementation of justified containers
Documentation
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
//! Collections that don’t need extra bounds-checking.
//!
//! # Overview
//!
//! **Justly** implements “justified” wrappers
//! for the standard Rust data structures
//! in [`std::collections`].
//! A *justified container* is one whose keys,
//! such as the [`usize`] indices into a [`Vec`],
//! keep track of their validity.
//! This has a few major consequences, listed below.
//!
//! ## Trustworthiness
//!
//! Justly is built on the idea of **trustworthy knowledge**:
//! [`call::Call`] represents a value called by a name,
//! which lets you encode *knowledge* about that named thing,
//! such as [`key::Key`], an index that you know is valid.
//! If you uphold the safety properties described in these APIs,
//! then such knowledge is called *trustworthy*,
//! and so you can rely on it to build safe abstractions.
//! Now unchecked indexing can be well and truly safe!
//!
//! ## No extra checks
//!
//! A “checked” method is one that performs bounds checking,
//! and an “unchecked” method is one that *unsafely* omits it.
//! Methods in Justly that *safely* omit bounds checks
//! are called **check-free**.
//! The Rust compiler attempts to elide checks
//! when it can prove that they will always succeed.
//! Justly implements check-free APIs
//! by giving you the tools to prove that checks can be skipped.
//!
//! It’s worth noting that some checks are strictly necessary!
//! For example, you *must* do a runtime test
//! to tell whether an arbitrary integer index is a valid key.
//! Justly only lets you avoid *extra* checks,
//! which are not strictly necessary,
//! yet the compiler cannot prove it.
//! But once you have gotten a typed key,
//! it proves that the test has already been done,
//! and doesn’t need to be repeated.
//!
//! Also, most indices that you get from the collection APIs
//! are already known to be valid keys,
//! so Justly merely adds that information in its wrapper APIs.
//!
//! ## No invalid indices
//!
//! When referring to elements in a collection,
//! Rust encourages using *indices*, relative to the collection,
//! instead of absolute pointers.
//! When a container is mutable,
//! mutating methods can reallocate the container’s storage
//! if its capacity is exceeded,
//! thereby invalidating all pointers to that storage.
//! So relative indexing makes it easier to uphold memory safety
//! compared to absolute addressing,
//! because indices automatically respond to *capacity* changes.
//!
//! However, relative indices
//! still don’t automatically handle changes in *size*:
//! any method that decreases the size of the container
//! must naturally invalidate any indices
//! referring to elements outside of its new bounds.
//!
//! Worse, since indices are just bare integers,
//! they come with no guarantees about the relationship
//! between the index and the value at that index.
//! For example, suppose we have a vector, `v`,
//! and we compute some indices into it, `i` and `j`.
//!
//! ```
//! let mut v = vec![1, 7, 16, 27, 40, 55];
//!
//! let i = v.iter().enumerate().position(|(k, &v)| k * 10 == v).unwrap();
//! let j = v.iter().enumerate().position(|(k, &v)| k * 11 == v).unwrap();
//!
//! println!("{}", v[i]);  // valid (40)
//! println!("{}", v[j]);  // valid (55)
//! ```
//!
//! If we `remove()` an element,
//! then this can easily break code
//! that makes assumptions about the indices:
//! `remove()` not only makes `j` inaccessible,
//! but also silently changes the meaning of `i`.
//! This is like a use-after-free error.
//!
//! ```should_panic
//! # let mut v = vec![1, 7, 16, 27, 40, 55];
//! # let i = 4;
//! # let j = 5;
//! v.remove(2);
//!
//! println!("{}", v[i]);  // logic error (55)
//! println!("{}", v[j]);  // runtime error (panic)
//! ```
//!
//! And of course if we `push()` an element,
//! the problem is compounded:
//! it silently makes `j` accessible again,
//! but with a different meaning as well.
//!
//! ```
//! # let mut v = vec![1, 7, 16, 27, 40, 55];
//! # let i = 4;
//! # let j = 5;
//! # v.remove(2);
//! v.push(68);
//!
//! println!("{}", v[j]);  // logic error (68)
//! ```
//!
//! So Justly wraps those *mutating* methods
//! that could invalidate the keys of a collection
//! in *consuming* methods that give back a modified object,
//! along with information about how the new keys
//! are related to the old ones.
//!
//! We do this with phantom type parameters,
//! so there is no runtime cost.
//!
//! # About this documentation
//!
//! Wrapper types and methods are annotated with tags
//! that describe their purpose, which are marked
//! with curly braces `{…}` for easier searching.
//!
//! ## {free}
//!
//! Marks methods that used to require bounds-checking
//! on the original type, but are now check-free.
//!
//! ## {just}
//!
//! On a container type, this says
//! that the type is a wrapper for a plain container
//! where some methods use typestate to add safety.
//!
//! On a method, it marks places
//! where we change the signature, typically either:
//!
//! * Taking ownership of `self`
//!   to replace a `mut` method on the wrapped type
//!   with one that tracks knowledge about the container
//!
//! * Adding wrappers such as [`key::Key`]
//!   to record some knowledge about the result
//!
//! ## {like}
//!
//! Links to the original wrapped thing.
//!
//! ## {safe}
//!
//! Marks things that used to be `unsafe` (usually *unchecked*)
//! but are now safe (implying check-freedom).
//!
//! # TODO
//!
//! ## Allow naming unsized things
//!
//! [`call::Call`] and [`link::Link`]
//! ask for `T: Sized`, but they don’t really need to,
//! since all the other fields are meant to be phantoms.
//!
//! ## Allocator support
//!
//! To support allocators,
//! there should be a type parameter on the wrappers,
//! such as `A = std::alloc::Global`.
//!
//! ## Implicit dereferencing
//!
//! We’re uneasy about whether to add implementations
//! of `Deref` and `DerefMut`
//! that would let a value be implicitly called by a name,
//! like these for `Vec`:
//!
//! ```ignore
//! impl<'name, T> Deref for Vec<'name, T> {
//!     type Target = Call<'name, vec::Vec<T>>;
//!     fn deref(&self) -> &Call<'name, vec::Vec<T>> {
//!         &self.same
//!     }
//! }
//!
//! impl<'name, T> DerefMut for Vec<'name, T> {
//!     fn deref_mut(
//!         &mut self,
//!     ) -> &mut Call<'name, vec::Vec<T>> {
//!         &mut self.same
//!     }
//! }
//! ```
//!
//! ## Tracking capacity
//!
//! At the time of this writing,
//! these APIs only track the validity of *indices*.
//! This means that if `std::collections` has a mutating method
//! that doesn’t change any indices,
//! we can just forward it and keep the same API,
//! which is likely better for usability.
//!
//! However, in principle
//! we could just as well track the *capacity* too.
//! This would reflect
//! the `std::collections` guarantees about allocation
//! at the type level,
//! making it possible in some circumstances
//! to statically guarantee that code will not allocate.
//! But it would come at the ergonomic cost
//! of using a different API
//! for functions that might change the capacity.
//!

#![feature(ptr_sub_ptr)]
#![feature(slice_split_at_unchecked)]
#![feature(slice_swap_unchecked)]
#![feature(slice_pattern)]
#![warn(missing_docs)]

pub mod name {

    //! Static, type-level names for runtime values.
    //!
    //! Names are represented using lifetime variables.
    //! For more on why, see [`mod@crate::call`].

    use core::marker::PhantomData;

    /// A name tag, which you can make for free.
    #[derive(Copy, Clone)]
    pub struct Name<'name>(PhantomData<&'name ()>);

    /// Make a name tag.
    pub const fn name<'name>() -> Name<'name> {
        Name(PhantomData)
    }
}

pub mod only {

    //! Helper for unique names.

    use super::name::{name, Name};

    /// Types whose values have unique names.
    ///
    /// Most likely you want [`crate::call::Call`]
    /// instead of this.
    ///
    /// # Safety
    ///
    /// `self` must uphold all trusted knowledge about `'name`.
    /// This means that `self` must be (or be the same as)
    /// the only bearer of this `'name`,
    /// so it must be immutable, or only ever used linearly.
    ///
    pub unsafe trait Only<'name> {
        /// Convenience method to get a name tag for `self`.
        fn name(&self) -> Name<'name> {
            name::<'name>()
        }
    }
}

pub mod call {

    //! `name ≡ value` relationships:
    //! *define* a unique static name for a dynamic value.
    //!
    //! To make a new name,
    //! we have to make up a new type-level constant.
    //! which is both statically known and unique.
    //!
    //! Often a “type constant” wants to be an existential type.
    //! However, `dyn Trait` types aren’t statically known,
    //! and `impl Trait` types aren’t necessarily unique.
    //! Happily, we can write rank-1 existential quantification
    //! using rank-2 universal quantification,
    //! which is allowed for lifetime variables.
    //!
    //! So we can write the name as a lifetime.
    //! That also lets us skip writing it sometimes,
    //! thanks to lifetime elision.
    //!

    use super::link::Link;
    use super::name::name;
    use super::only::Only;
    use core::ops::Deref;

    /// A value that’s called by a name.
    pub struct Call<'name, T> {
        link: Link<'name, T>,
    }

    unsafe impl<'name, T> Only<'name> for Call<'name, T> {}

    impl<'name, T> Call<'name, T> {
        /// Forgets its own name.
        pub fn into_owned(self) -> T {
            self.link.body
        }

        /// Changes the body *without* changing the name.
        ///
        /// # Safety
        ///
        /// Must uphold all trusted knowledge of `'name`.
        ///
        pub unsafe fn as_mut(&mut self) -> &mut T {
            &mut self.link.body
        }
    }

    impl<'name, T> Deref for Call<'name, T> {
        type Target = T;
        fn deref(&self) -> &T {
            &self.link.body
        }
    }

    /// Bestows a `'name` on something.
    ///
    /// Knowledge about the `'name`
    /// is now seen as knowledge about the named thing.
    ///
    /// As in “forge one’s own identity”, if you use it safely;
    /// or “commit forgery”, if you use it unsafely.
    ///
    /// If you just want a name and a value together,
    /// you likely need a plain [`crate::link::Link`].
    ///
    /// # Safety
    ///
    /// The thing must be the only one that bears this name.
    /// Otherwise, knowledge about the name might not be true.
    ///
    pub const unsafe fn forge<'name, T>(
        body: T,
    ) -> Call<'name, T> {
        Call {
            link: Link {
                body,
                name: name::<'name>(),
            },
        }
    }
}

pub mod called {

    //! Gives names to values.

    use super::call::{forge, Call};

    /// The set of types whose values can be called by a name.
    pub trait Called {
        /// Gives `self` a new name and evaluates `body`.
        ///
        /// Most often you will call this with a closure.
        ///
        /// ```ignore
        /// // TODO
        /// x.called(|x| {
        ///     // …
        /// })
        /// ```
        ///
        fn called<Out, Body>(self: Self, body: Body) -> Out
        where
            Body: for<'call> FnOnce(Call<'call, Self>) -> Out,
            Self: Sized;
    }

    /// Anything with a size can be called by a name.
    ///
    /// # TODO
    ///
    /// - [Allow naming unsized things][crate#allow-naming-unsized-things]
    ///
    impl<T> Called for T
    where
        T: Sized,
    {
        fn called<'here, Out, Body>(
            self: Self,
            body: Body,
        ) -> Out
        where
            Body: for<'call> FnOnce(Call<'call, Self>) -> Out,
            Self: Sized,
        {
            body(unsafe { forge(self) })
        }
    }
}

pub mod link {

    //! `name × value` relationships:
    //! *pair* a static name with a dynamic value.

    use super::name::{name, Name};

    /// A value, paired with a name
    /// that doesn’t have to be the name of the value itself.
    /// Often this is some kind of “reference”
    /// into the named parent structure,
    /// but it doesn’t need to be a Rust reference type,
    /// so to avoid potential confusion,
    /// we say there’s a “link” between them.
    ///
    /// # Safety
    ///
    /// It’s always *safe* to link to a name, but that means
    /// a link doesn’t necessarily say anything *trustworthy*
    /// about the relationship between `body` and `'name`.
    /// If you want that,
    /// you must make a newtype wrapper around it,
    /// or use one of the wrappers that Justly already offers,
    /// like [`crate::key::Key`].
    ///
    /// # TODO
    ///
    /// - [Allow naming unsized things][crate#allow-naming-unsized-things]
    ///
    #[derive(Copy, Clone)]
    pub struct Link<'name, T> {
        /// The value of the link.
        pub body: T,
        /// The name it is linked to.
        pub name: Name<'name>,
    }

    /// Pair a value with a name,
    /// where the value doesn’t lay claim to the name.
    pub const fn link<'name, T>(body: T) -> Link<'name, T> {
        Link {
            body,
            name: name::<'name>(),
        }
    }
}

pub mod prop {

    //! Common properties of collections.

    use super::name::Name;

    /// The property that a structure is sorted by `Ord`,
    /// that is, for indices `i` and `j`
    /// and their associated elements `n[i]` and `n[j]`,
    /// the association is monotonic:
    /// `i <= j` implies `n[i] <= n[j]`.

    pub struct Sorted<'name>(Name<'name>);
}

pub mod vec {

    //! [**{just}**](crate#just)
    //! [{like}](crate#like):[`mod@std::vec`]
    //! [{like}](crate#like):[`mod@std::slice`]
    //!
    //! `Vec<'name, T>` is a thin wrapper
    //! around a named vector, `Call<'name, std::vec::Vec<T>>`,
    //! which you can make
    //! using the [`crate::called::Called`] trait.
    //!
    //! As is typical for this library,
    //! the `Vec` wrapper replaces some methods
    //! with versions that track the state of the container
    //! to prove that unchecked indexing is safe,
    //! and offer some additional features enabled by this.
    //!
    //! The types `Slice` and `MutSlice`
    //! are similar thin wrappers for slices, and likewise
    //! `ConstPtr` and `MutPtr` for pointers.

    use super::call::{forge, Call};
    use super::key::Key;
    use super::link::{link, Link};
    use super::name::name;
    use super::only::Only;
    use super::proof::{assume, Eqv, Prf, Sub};
    use super::prop;
    use core::cmp::Ordering;
    use core::ops::Range;
    use core::slice;
    use core::slice::SlicePattern;
    use std::vec;

    /// A vector bestowed with a name.
    ///
    /// # Extensions
    ///
    /// - `contains_key`
    /// - `reverse_mut`
    ///
    /// # `Vec` support
    ///
    /// - [ ] [`std::vec::Vec::allocator()`]
    /// - [ ] [`std::vec::Vec::append()`]
    /// - [x] [`std::vec::Vec::as_mut_ptr()`]]
    /// - [x] [`std::vec::Vec::as_mut_slice()`]
    /// - [x] [`std::vec::Vec::as_ptr()`]
    /// - [x] [`std::vec::Vec::as_slice()`]
    /// - [x] [`std::vec::Vec::capacity()`]
    /// - [ ] [`std::vec::Vec::clear()`]
    /// - [ ] [`std::vec::Vec::dedup()`]
    /// - [ ] [`std::vec::Vec::dedup_by()`]
    /// - [ ] [`std::vec::Vec::dedup_by_key()`]
    /// - [ ] [`std::vec::Vec::drain()`]
    /// - [ ] [`std::vec::Vec::extend_from_slice()`]
    /// - [ ] [`std::vec::Vec::extend_from_within()`]
    /// - [x] [`std::vec::Vec::from_raw_parts()`]
    /// - [ ] [`std::vec::Vec::from_raw_parts_in()`]
    /// - [ ] [`std::vec::Vec::insert()`]
    /// - [ ] [`std::vec::Vec::into_boxed_slice()`]
    /// - [ ] [`std::vec::Vec::into_flattened()`]
    /// - [ ] [`std::vec::Vec::into_raw_parts()`]
    /// - [ ] [`std::vec::Vec::into_raw_parts_with_alloc()`]
    /// - [ ] [`std::vec::Vec::leak()`]
    /// - [x] [`std::vec::Vec::len()`]
    /// - [x] [`std::vec::Vec::new()`]
    /// - [ ] [`std::vec::Vec::new_in()`]
    /// - [ ] [`std::vec::Vec::pop()`]
    /// - [x] [`std::vec::Vec::push()`]
    /// - [ ] [`std::vec::Vec::push_within_capacity()`]
    /// - [ ] [`std::vec::Vec::remove()`]
    /// - [x] [`std::vec::Vec::reserve()`]
    /// - [x] [`std::vec::Vec::reserve_exact()`]
    /// - [ ] [`std::vec::Vec::resize()`]
    /// - [ ] [`std::vec::Vec::resize_with()`]
    /// - [ ] [`std::vec::Vec::retain()`]
    /// - [ ] [`std::vec::Vec::retain_mut()`]
    /// - [ ] [`std::vec::Vec::set_len()`]
    /// - [ ] [`std::vec::Vec::shrink_to()`]
    /// - [ ] [`std::vec::Vec::shrink_to_fit()`]
    /// - [ ] [`std::vec::Vec::spare_capacity_mut()`]
    /// - [ ] [`std::vec::Vec::splice()`]
    /// - [ ] [`std::vec::Vec::split_at_spare_mut()`]
    /// - [ ] [`std::vec::Vec::split_off()`]
    /// - [ ] [`std::vec::Vec::swap_remove()`]
    /// - [x] [`std::vec::Vec::truncate()`]
    /// - [x] [`std::vec::Vec::try_reserve_exact()`]
    /// - [x] [`std::vec::Vec::with_capacity()`]
    /// - [ ] [`std::vec::Vec::with_capacity_in()`]
    ///
    /// # `slice` support
    ///
    /// - [ ] [`slice::align_to()`]
    /// - [ ] [`slice::align_to_mut()`]
    /// - [ ] [`slice::array_chunks()`]
    /// - [ ] [`slice::array_chunks_mut()`]
    /// - [ ] [`slice::array_windows()`]
    /// - [ ] [`slice::as_chunks()`]
    /// - [ ] [`slice::as_chunks_mut()`]
    /// - [ ] [`slice::as_chunks_unchecked_mut()`]
    /// - [ ] [`slice::as_chunks_unchecked()`]
    /// - [x] [`slice::as_mut_ptr_range()`]
    /// - [x] [`slice::as_ptr_range()`]
    /// - [ ] [`slice::as_rchunks()`]
    /// - [ ] [`slice::as_rchunks_mut()`]
    /// - [ ] [`slice::as_simd()`]
    /// - [ ] [`slice::as_simd_mut()`]
    /// - [x] [`slice::binary_search()`]
    /// - [x] [`slice::binary_search_by()`]
    /// - [x] [`slice::binary_search_by_key()`]
    /// - [ ] [`slice::chunks()`]
    /// - [ ] [`slice::chunks_exact()`]
    /// - [ ] [`slice::chunks_exact_mut()`]
    /// - [ ] [`slice::chunks_mut()`]
    /// - [ ] [`slice::clone_from_slice()`]
    /// - [ ] [`slice::concat()`]
    /// - [x] [`slice::contains()`]
    /// - [ ] [`slice::copy_from_slice()`]
    /// - [ ] [`slice::copy_within()`]
    /// - [x] [`slice::ends_with()`]
    /// - [ ] [`slice::fill()`]
    /// - [ ] [`slice::fill_with()`]
    /// - [x] [`slice::get()`]
    /// - [ ] [`slice::get_many_mut()`]
    /// - [ ] [`slice::get_many_unchecked_mut()`]
    /// - [ ] [`slice::group_by()`]
    /// - [ ] [`slice::group_by_mut()`]
    /// - [ ] [`slice::is_empty()`]
    /// - [ ] [`slice::is_sorted()`]
    /// - [ ] [`slice::is_sorted_by_key()`]
    /// - [x] [`slice::iter()`]
    /// - [x] [`slice::iter_mut()`]
    /// - [ ] [`slice::join()`]
    /// - [ ] [`slice::partition_dedup()`]
    /// - [ ] [`slice::partition_dedup_by()`]
    /// - [ ] [`slice::partition_dedup_by_key()`]
    /// - [ ] [`slice::rchunks()`]
    /// - [ ] [`slice::rchunks_exact()`]
    /// - [ ] [`slice::rchunks_exact_mut()`]
    /// - [ ] [`slice::rchunks_mut()`]
    /// - [ ] [`slice::repeat()`]
    /// - [x] [`slice::reverse()`]
    /// - [ ] [`slice::rotate_left()`]
    /// - [ ] [`slice::rotate_right()`]
    /// - [ ] [`slice::rsplit()`]
    /// - [ ] [`slice::rsplit_array_mut()`]
    /// - [ ] [`slice::rsplit_array_ref()`]
    /// - [ ] [`slice::rsplit_mut()`]
    /// - [ ] [`slice::rsplitn()`]
    /// - [ ] [`slice::rsplitn_mut()`]
    /// - [ ] [`slice::select_nth_unstable()`]
    /// - [ ] [`slice::select_nth_unstable_by()`]
    /// - [ ] [`slice::select_nth_unstable_by_key()`]
    /// - [ ] [`slice::sort()`]
    /// - [ ] [`slice::sort_by()`]
    /// - [ ] [`slice::sort_by_key()`]
    /// - [ ] [`slice::sort_by_cached_key()`]
    /// - [x] [`slice::sort_unstable()`]
    /// - [ ] [`slice::sort_unstable_by()`]
    /// - [ ] [`slice::sort_unstable_by_key()`]
    /// - [ ] [`slice::split()`]
    /// - [ ] [`slice::split_array_mut()`]
    /// - [ ] [`slice::split_array_ref()`]
    /// - [x] [`slice::split_at()`]
    /// - [x] [`slice::split_at_mut()`]
    /// - [x] [`slice::split_at_mut_unchecked()`]
    /// - [x] [`slice::split_at_unchecked()`]
    /// - [ ] [`slice::split_inclusive()`]
    /// - [ ] [`slice::split_mut()`]
    /// - [ ] [`slice::splitn()`]
    /// - [ ] [`slice::splitn_mut()`]
    /// - [x] [`slice::starts_with()`]
    /// - [x] [`slice::strip_prefix()`]
    /// - [x] [`slice::strip_suffix()`]
    /// - [x] [`slice::swap()`]
    /// - [x] [`slice::swap_unchecked()`]
    /// - [ ] [`slice::swap_with_slice()`]
    /// - [ ] [`slice::take()`]
    /// - [ ] [`slice::take_first()`]
    /// - [ ] [`slice::take_first_mut()`]
    /// - [ ] [`slice::take_last()`]
    /// - [ ] [`slice::take_last_mut()`]
    /// - [ ] [`slice::take_mut()`]
    /// - [ ] [`slice::to_ascii_lowercase()`]
    /// - [ ] [`slice::to_ascii_uppercase()`]
    /// - [ ] [`slice::to_vec()`]
    /// - [ ] [`slice::to_vec_in()`]
    /// - [ ] [`slice::windows()`]
    ///
    /// # TODO
    ///
    /// - [Allocator support][crate#allocator-support]
    ///
    /// - [Implicit dereferencing][crate#implicit-dereferencing]
    ///

    pub struct Vec<'name, T> {
        own: Call<'name, vec::Vec<T>>,
    }

    /// A slice like `&[T]`
    /// but *known* to be of the named vector.
    /// [{like}](crate#like):[`prim@slice`]
    pub struct Slice<'name, 'vec, T> {
        #[allow(missing_docs)]
        pub own: Link<'name, &'vec [T]>,
    }

    impl<'name, 'vec, T> From<Link<'name, &'vec [T]>>
        for Slice<'name, 'vec, T>
    {
        fn from(own: Link<'name, &'vec [T]>) -> Self {
            Slice { own }
        }
    }

    /// A mutable slice like `&mut [T]`
    /// but *known* to be of the named vector.
    /// [{like}](crate#like):[`prim@slice`]
    pub struct MutSlice<'name, 'vec, T> {
        #[allow(missing_docs)]
        pub own: Link<'name, &'vec mut [T]>,
    }

    impl<'name, 'vec, T> From<Link<'name, &'vec mut [T]>>
        for MutSlice<'name, 'vec, T>
    {
        fn from(own: Link<'name, &'vec mut [T]>) -> Self {
            MutSlice { own }
        }
    }

    /// A pointer like `*const T`
    /// but *assumed* to be into the named vector.
    /// [{like}](crate#like):[`pointer`]
    pub struct ConstPtr<'name, T> {
        #[allow(missing_docs)]
        pub own: Link<'name, *const T>,
    }

    impl<'name, T> From<Link<'name, *const T>>
        for ConstPtr<'name, T>
    {
        fn from(own: Link<'name, *const T>) -> Self {
            ConstPtr { own }
        }
    }

    /// A mutable pointer like `*mut T`
    /// but *assumed* to be into the named vector.
    /// [{like}](crate#like):[`pointer`]
    pub struct MutPtr<'name, T> {
        #[allow(missing_docs)]
        pub own: Link<'name, *mut T>,
    }

    impl<'name, T> From<Link<'name, *mut T>> for MutPtr<'name, T> {
        fn from(own: Link<'name, *mut T>) -> Self {
            MutPtr { own }
        }
    }

    impl<'name, T> From<Call<'name, vec::Vec<T>>>
        for Vec<'name, T>
    {
        fn from(own: Call<'name, vec::Vec<T>>) -> Self {
            Vec { own }
        }
    }

    impl<'name, T> Vec<'name, T> {
        /// [{like}](crate#like):[`std::vec::Vec::new`]
        pub fn new() -> Vec<'name, T> {
            unsafe { Vec::from(forge(vec::Vec::new())) }
        }

        /// [{like}](crate#like):[`std::vec::Vec::with_capacity`]
        pub fn with_capacity(capacity: usize) -> Vec<'name, T> {
            unsafe {
                Vec::from(forge(vec::Vec::with_capacity(
                    capacity,
                )))
            }
        }

        /// [{like}](crate#like):[`std::vec::Vec::from_raw_parts`]
        pub unsafe fn from_raw_parts(
            ptr: *mut T,
            length: usize,
            capacity: usize,
        ) -> Vec<'name, T> {
            unsafe {
                Vec::from(forge(vec::Vec::from_raw_parts(
                    ptr, length, capacity,
                )))
            }
        }

        /// [{like}](crate#like):[`std::vec::Vec::capacity`]
        ///
        /// # TODO
        ///
        /// - [Tracking capacity](crate#tracking-capacity)

        pub fn capacity(&self) -> usize {
            self.own.capacity()
        }

        /// [{like}](crate#like):[`std::vec::Vec::reserve`]

        pub fn reserve(&mut self, additional: usize) -> () {
            unsafe { self.own.as_mut().reserve(additional) }
        }

        /// [{like}](crate#like):[`std::vec::Vec::reserve_exact`]
        ///
        /// # TODO
        ///
        /// - [Tracking capacity](crate#tracking-capacity)

        pub fn reserve_exact(
            &mut self,
            additional: usize,
        ) -> () {
            unsafe {
                self.own.as_mut().reserve_exact(additional)
            }
        }

        /// [{like}](crate#like):[`std::vec::Vec::try_reserve_exact`]

        pub fn try_reserve_exact(
            &mut self,
            additional: usize,
        ) -> Result<(), std::collections::TryReserveError>
        {
            unsafe {
                self.own.as_mut().try_reserve_exact(additional)
            }
        }
    } // impl Vec

    impl<'before_truncate, T> Vec<'before_truncate, T> {
        /// [**{just}**](crate#just)
        /// [{like}](crate#like):[`std::vec::Vec::truncate`]
        ///
        /// # Returns
        ///
        /// 0. Truncated vector
        /// 1. Proof that new keys are a subset of old keys
        /// 2. Partial mapping from old keys to new keys
        ///
        pub fn truncate<'after_truncate>(
            self,
            len: usize,
        ) -> (
            Vec<'after_truncate, T>,
            Prf<Sub<'after_truncate, 'before_truncate>>,
            impl Fn(
                Key<'before_truncate, usize>,
            )
                -> Option<Key<'after_truncate, usize>>,
        ) {
            let mut old = self.own.into_owned();
            old.truncate(len);
            (
                unsafe { Vec::from(forge(old)) },
                unsafe {
                    assume::<
                        Sub<'after_truncate, 'before_truncate>,
                    >()
                },
                move |key| {
                    if key.index() < len {
                        Some(unsafe {
                            Key::new(
                                key.index(),
                                name::<'after_truncate>(),
                            )
                        })
                    } else {
                        None
                    }
                },
            )
        }
    } // impl Vec

    impl<'name, T> Vec<'name, T> {
        /// [{like}](crate#like):[`std::vec::Vec::as_slice`]
        pub fn as_slice<'vec>(
            &'vec self,
        ) -> Slice<'name, 'vec, T>
        where
            'vec: 'name,
        {
            Slice::from(link(self.own.as_slice()))
        }

        /// [{like}](crate#like):[`std::vec::Vec::as_mut_slice`]
        pub fn as_mut_slice<'vec>(
            &'vec mut self,
        ) -> MutSlice<'name, 'vec, T>
        where
            'vec: 'name,
        {
            MutSlice::from(link(unsafe {
                self.own.as_mut().as_mut_slice()
            }))
        }

        /// [{like}](crate#like):[`std::vec::Vec::as_ptr`]
        pub unsafe fn as_ptr(&self) -> ConstPtr<'name, T> {
            ConstPtr::from(link(self.own.as_ptr()))
        }

        /// [{like}](crate#like):[`std::vec::Vec::as_mut_ptr`]
        pub unsafe fn as_mut_ptr(
            &mut self,
        ) -> MutPtr<'name, T> {
            MutPtr::from(link(self.own.as_mut().as_mut_ptr()))
        }

        /// [{like}](crate#like):[`slice::as_ptr_range()`]
        ///
        /// Since `Range` is half-open,
        /// the end point is *not* in the named vector.
        /// This doesn’t change safety,
        /// because `ConstPtr<'name, T>` doesn’t require
        /// that the pointer be in the named vector.
        pub unsafe fn as_ptr_range(
            &self,
        ) -> Range<ConstPtr<'name, T>> {
            let Range { start, end } = self.own.as_ptr_range();
            ConstPtr::from(link(start))
                ..ConstPtr::from(link(end))
        }

        /// [{like}](crate#like):[`slice::as_mut_ptr_range()`]
        ///
        /// # See Also
        ///
        /// - [`Vec::as_mut_ptr`].
        pub unsafe fn as_mut_ptr_range(
            &mut self,
        ) -> Range<MutPtr<'name, T>> {
            let Range { start, end } =
                self.own.as_mut().as_mut_ptr_range();
            MutPtr::from(link(start))..MutPtr::from(link(end))
        }

        /// [**{free}**](crate#free)
        /// [{like}](crate#like):[`slice::swap()`]
        pub fn swap(
            &mut self,
            a: Key<'name, usize>,
            b: Key<'name, usize>,
        ) {
            // Upholds `swap_unchecked`.
            debug_assert!(
                a.index() < self.len()
                    && b.index() < self.len()
            );
            unsafe {
                self.own
                    .as_mut()
                    .swap_unchecked(a.index(), b.index())
            }
        }

        /// [**{just}**](crate#just)
        /// {like}:[`std::vec::Vec::push()`]
        ///
        /// # Returns
        ///
        /// 0. Updated vector
        /// 1. Key of newly pushed element
        /// 2. Total mapping from old keys to new keys:
        ///    dom(in) ⊂ dom(out)
        ///
        pub fn push<'changed>(
            self,
            value: T,
        ) -> (
            Vec<'changed, T>,
            Key<'changed, usize>,
            impl Fn(Key<'name, usize>) -> Key<'changed, usize>,
        ) {
            let mut old = self.own.into_owned();
            let index = old.len();
            old.push(value);
            (
                unsafe { Vec::from(forge(old)) },
                unsafe { Key::new(index, name::<'changed>()) },
                |k| unsafe {
                    Key::new(k.index(), name::<'changed>())
                },
            )
        }

        /// [{like}](crate#like):[`std::vec::Vec::len`]
        ///
        /// # TODO
        ///
        /// We could annotate the result as evidence.
        pub fn len(&self) -> usize {
            self.own.len()
        }

        /// [**{safe}**](#safe)
        /// [{like}](crate#like):[`slice::swap_unchecked`]
        pub fn swap_unchecked(
            &mut self,
            a: Key<'name, usize>,
            b: Key<'name, usize>,
        ) {
            self.swap(a, b)
        }
    } // impl Vec

    impl<'before_reverse, T> Vec<'before_reverse, T> {
        /// [**{just}**](crate#just)
        /// [{like}](crate#like):[`slice::reverse()`]
        ///
        /// # Returns
        ///
        /// 0. Vector reversed by key–value pairs
        /// 1. Witness that all old keys are valid new keys:
        ///    dom(in) ≅ dom(out)
        ///
        pub fn reverse<'after_reverse>(
            self,
        ) -> (
            Vec<'after_reverse, T>,
            Prf<Eqv<'before_reverse, 'after_reverse>>,
            impl Fn(
                Key<'before_reverse, usize>,
            ) -> Key<'after_reverse, usize>,
        ) {
            let mut old = self.own.into_owned();
            old.reverse();
            let len = old.len();
            (
                unsafe { Vec::from(forge(old)) },
                unsafe {
                    assume::<Eqv<'before_reverse, 'after_reverse>>(
                    )
                },
                move |key| unsafe {
                    Key::new(
                        len - key.index() - 1,
                        name::<'after_reverse>(),
                    )
                },
            )
        }
    } // impl Vec

    impl<'name, T> Vec<'name, T> {
        /// [{like}](crate#like):[`slice::reverse()`]
        ///
        /// All keys stay valid, but their values are reversed.
        /// To invalidate the keys too, use [`Self::reverse()`].
        pub fn reverse_mut(&mut self) {
            unsafe { self.own.as_mut().reverse() }
        }

        /// [{like}](crate#like):[`slice::iter`]

        pub fn iter(&self) -> slice::Iter<'_, T> {
            self.own.iter()
        }

        /// [{like}](crate#like):[`slice::iter_mut`]

        pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
            unsafe { self.own.as_mut().iter_mut() }
        }

        /// [**{free}**](crate#free)
        /// [{like}](crate#like):[`slice::split_at()`]

        pub fn split_at<'vec>(
            &'vec self,
            mid: Key<'name, usize>,
        ) -> (Slice<'name, 'vec, T>, Slice<'name, 'vec, T>)
        where
            'vec: 'name,
        {
            // Upholds `split_at_unchecked`.
            debug_assert!(mid.index() <= self.len());
            unsafe {
                let (left, right) =
                    self.own.split_at_unchecked(mid.index());
                (
                    Slice::from(link(left)),
                    Slice::from(link(right)),
                )
            }
        }

        /// [**{free}**](crate#free)
        /// [{like}](crate#like):[`slice::split_at_mut()`]

        pub fn split_at_mut<'vec>(
            &'vec mut self,
            mid: Key<'name, usize>,
        ) -> (MutSlice<'name, 'vec, T>, MutSlice<'name, 'vec, T>)
        where
            'vec: 'name,
        {
            // Upholds `split_at_mut_unchecked`:
            //
            // > The caller has to ensure that
            // > `0 <= mid <= self.len()`.
            //
            debug_assert!(mid.index() <= self.len());
            unsafe {
                let (left, right) = self
                    .own
                    .as_mut()
                    .split_at_mut_unchecked(mid.index());
                (
                    MutSlice::from(link(left)),
                    MutSlice::from(link(right)),
                )
            }
        }

        /// [**{safe}**](crate#safe)
        /// [{like}](crate#like):`slice::split_at_unchecked`

        pub fn split_at_unchecked<'vec>(
            &'vec self,
            mid: Key<'name, usize>,
        ) -> (Slice<'name, 'vec, T>, Slice<'name, 'vec, T>)
        where
            'vec: 'name,
        {
            self.split_at(mid)
        }

        /// [**{safe}**](crate#safe)
        /// [{like}](crate#like):[`slice::split_at_mut_unchecked`]

        pub fn split_at_mut_unchecked<'vec>(
            &'vec mut self,
            mid: Key<'name, usize>,
        ) -> (MutSlice<'name, 'vec, T>, MutSlice<'name, 'vec, T>)
        where
            'vec: 'name,
        {
            self.split_at_mut(mid)
        }

        /// [{like}](crate#like):[`slice::contains`]

        pub fn contains(&self, x: &T) -> bool
        where
            T: PartialEq<T>,
        {
            self.own.contains(x)
        }

        /// [{like}](crate#like):[`slice::starts_with`]

        pub fn starts_with(&self, needle: &[T]) -> bool
        where
            T: PartialEq<T>,
        {
            self.own.starts_with(needle)
        }

        /// [{like}](crate#like):[`slice::ends_with`]

        pub fn ends_with(&self, needle: &[T]) -> bool
        where
            T: PartialEq<T>,
        {
            self.own.ends_with(needle)
        }

        /// [{like}](crate#like):[`slice::strip_prefix`]

        pub fn strip_prefix<'vec, P>(
            &'vec self,
            prefix: &P,
        ) -> Option<Slice<'name, 'vec, T>>
        where
            P: SlicePattern<Item = T> + ?Sized,
            T: PartialEq<T>,
            'vec: 'name,
        {
            self.own
                .strip_prefix(prefix)
                .map(|slice| Slice::from(link(slice)))
        }

        /// [{like}](crate#like):[`slice::strip_suffix`]

        pub fn strip_suffix<'vec, P>(
            &'vec self,
            suffix: &P,
        ) -> Option<Slice<'name, 'vec, T>>
        where
            P: SlicePattern<Item = T> + ?Sized,
            T: PartialEq<T>,
            'vec: 'name,
        {
            self.own
                .strip_suffix(suffix)
                .map(|slice| Slice::from(link(slice)))
        }

        /// [**{just}**](crate#just)
        /// [{like}](crate#like):[`slice::binary_search`]
        ///
        /// The `Ok` index is guaranteed to be valid,
        /// so we can wrap it in a `Key`.
        /// The `Err` index may be `len()` (past the end).

        pub fn binary_search(
            &self,
            x: &T,
        ) -> Result<Key<'name, usize>, usize>
        where
            T: Ord,
        {
            self.own.binary_search(x).map(|index| unsafe {
                Key::new(index, name::<'name>())
            })
        }

        /// [{like}](crate#like):[`slice::binary_search_by`]

        pub fn binary_search_by<F>(
            &self,
            f: F,
        ) -> Result<Key<'name, usize>, usize>
        where
            F: FnMut(&T) -> Ordering,
        {
            self.own.binary_search_by(f).map(|index| unsafe {
                Key::new(index, name::<'name>())
            })
        }

        /// [{like}](crate#like):[`slice::binary_search_by_key`]

        pub fn binary_search_by_key<B, F>(
            &self,
            b: &B,
            f: F,
        ) -> Result<Key<'name, usize>, usize>
        where
            F: FnMut(&T) -> B,
            B: Ord,
        {
            self.own.binary_search_by_key(b, f).map(
                |index| unsafe {
                    Key::new(index, name::<'name>())
                },
            )
        }

        /// [{like}](crate#like):[`slice::sort_unstable`]

        pub fn sort_unstable<'changed>(
            self,
        ) -> (Vec<'changed, T>, Prf<prop::Sorted<'changed>>)
        where
            T: Ord,
        {
            let mut old = self.own.into_owned();
            old.sort_unstable();
            (unsafe { Vec::from(forge(old)) }, unsafe {
                assume::<prop::Sorted<'changed>>()
            })
        }

        /// [**{just}**](crate#just)
        /// [{like}](crate#like):[`std::collections::HashMap::contains_key()`]
        ///
        /// Instead of a mere yes-or-no `bool`,
        /// we return an `Option` of a known-valid `Key`.

        pub fn contains_key(
            &self,
            index: usize,
        ) -> Option<Key<'name, usize>> {
            self.own.get(index).map(|_val| unsafe {
                Key::new(index, name::<'name>())
            })
        }

        /// [**{free}**](crate#free)
        /// [{like}](crate#like):[`slice::get()`]

        pub fn get(&self, key: Key<'name, usize>) -> &T {
            unsafe { self.own.get_unchecked(key.index()) }
        }
    } // impl Vec

    impl<'name, 'vec, T> Slice<'name, 'vec, T> {
        /// Safely gets the starting index of a slice in its
        /// parent vector.

        pub fn index(
            &self,
            vec: &'vec Vec<'name, T>,
        ) -> Key<'name, usize> {
            unsafe {
                // Uphold `sub_ptr`.
                debug_assert!(vec
                    .own
                    .as_ptr_range()
                    .contains(&self.own.body.as_ptr()));
                Key::new(
                    self.own
                        .body
                        .as_ptr()
                        .sub_ptr(vec.own.as_ptr()),
                    vec.own.name(),
                )
            }
        }
    } // impl Slice

    impl<'name, 'vec, T> MutSlice<'name, 'vec, T> {
        /// Safely gets the starting index of a mutable slice in
        /// its parent vector.

        pub fn index(
            &mut self,
            vec: &'vec mut Vec<'name, T>,
        ) -> Key<'name, usize> {
            unsafe {
                // Uphold `sub_ptr`.
                debug_assert!(vec
                    .own
                    .as_ptr_range()
                    .contains(&self.own.body.as_ptr()));
                Key::new(
                    self.own
                        .body
                        .as_mut_ptr()
                        .sub_ptr(vec.own.as_mut().as_mut_ptr()),
                    vec.own.name(),
                )
            }
        }
    } // impl MutSlice
}

pub mod vec_deque {

    //! [{like}](crate#like):[`std::collections::vec_deque`]

    use super::call::Call;
    use std::collections::vec_deque;

    /// [{like}](crate#like):[`std::collections::VecDeque`]
    ///
    /// # TODO
    ///
    /// ## Missing `VecDeque` methods
    ///
    pub type VecDeque<'name, T> =
        Call<'name, vec_deque::VecDeque<T>>;
}

pub mod linked_list {

    //! [{like}](crate#like):[`std::collections::linked_list`]

    use super::call::Call;
    use std::collections::linked_list;

    /// [{like}](crate#like):[`std::collections::LinkedList`]
    ///
    /// # TODO
    ///
    /// ## Missing `LinkedList` methods
    ///
    pub type LinkedList<'name, T> =
        Call<'name, linked_list::LinkedList<T>>;
}

pub mod hash_map {

    //! [{like}](crate#like):[`std::collections::hash_map`]

    use super::call::Call;
    use std::collections::hash_map;

    /// [{like}](crate#like):[`std::collections::HashMap`]
    ///
    /// # TODO
    ///
    /// ## Missing `HashMap` methods
    ///
    pub type HashMap<'name, K, V, S = hash_map::RandomState> =
        Call<'name, hash_map::HashMap<K, V, S>>;
}

pub mod btree_map {

    //! [{like}](crate#like):[`std::collections::btree_map`]

    use super::call::Call;
    use std::collections::btree_map;

    /// [{like}](crate#like):[`std::collections::BTreeMap`]
    ///
    /// # TODO
    ///
    /// ## Missing `BTreeMap` methods
    ///
    pub type BTreeMap<'name, K, V> =
        Call<'name, btree_map::BTreeMap<K, V>>;
}

pub mod binary_heap {

    //! [{like}](crate#like):[`std::collections::binary_heap`]

    use super::call::Call;
    use std::collections::binary_heap;

    /// [{like}](crate#like):[`std::collections::BinaryHeap`]
    ///
    /// # TODO
    ///
    /// ## Missing `BinaryHeap` methods
    ///
    pub type BinaryHeap<'name, T> =
        Call<'name, binary_heap::BinaryHeap<T>>;
}

pub mod key {

    //! Indices known to be valid keys in collections.

    use super::link::Link;
    use super::name::Name;

    /// A `Key<'name, Index>` is an `Index`
    /// that is known to be a valid key in `'name`.
    #[derive(Copy, Clone)]
    pub struct Key<'name, Index> {
        own: Link<'name, Index>,
    }

    impl<'name, Index> Key<'name, Index> {
        /// Say that an index is a valid key in a collection.
        ///
        /// # Safety
        ///
        /// The index must really be a valid key.
        ///
        pub unsafe fn new(
            body: Index,
            name: Name<'name>,
        ) -> Self {
            Key {
                own: Link { body, name },
            }
        }

        /// Get the index of a key.
        pub fn index(&self) -> Index
        where
            Index: Copy,
        {
            self.own.body
        }
    }
}

pub mod proof {

    //! Static proofs.

    use super::name::Name;
    use core::marker::PhantomData;

    /// Proof of proposition `A`.
    pub struct Prf<A>(PhantomData<A>);

    /// False proposition. Provable by `contradiction`.
    pub enum False {}

    /// True proposition. Proof is `trivial`.
    pub enum True {}

    /// Propositional NOT.
    ///
    /// Provable with `not()`.
    ///
    pub struct Not<A>(PhantomData<A>);

    /// Propositional AND: provable by both proving `A` and
    /// proving `B`.
    pub struct And<A, B>(PhantomData<(A, B)>);

    /// Propositional OR, provable by either proving `A` or
    /// proving `B`; or set union.
    pub struct Or<A, B>(PhantomData<(A, B)>);

    /// Propositional implication, provable by proving `B` given
    /// a proof of `A`.
    pub struct Imp<A, B>(PhantomData<(A, B)>);

    /// Subset or equal.
    pub struct Sub<'s, 't>(Name<'s>, Name<'t>);

    /// Propositional equivalence, provable by proving that `A`
    /// if and only if `B`.
    pub struct Iff<A, B>(PhantomData<(A, B)>);

    /// Set equivalence.
    pub struct Eqv<'s, 't>(Name<'s>, Name<'t>);

    /// Unsafely assume a proposition. It’s best to use this
    /// with an explicit type argument (turbofish) to document
    /// the intention, like `assume::<Or<A, Not<A>>>()`.
    ///
    pub unsafe fn assume<A>() -> Prf<A> {
        axiom()
    }

    /// Privately define an axiom.
    fn axiom<A>() -> Prf<A> {
        Prf(PhantomData)
    }

    /// Implication introduction.
    pub fn lam<A, B>(_s: impl Fn(A) -> B) -> Prf<Imp<A, B>> {
        axiom()
    }

    /// Implication elimination.
    pub fn app<A, B>(
        _a_to_b: &Prf<Imp<A, B>>,
        _a: &Prf<A>,
    ) -> Prf<B> {
        axiom()
    }

    /// Conjunction introduction. Proves a conjunction by
    /// proving each conjunct.
    pub fn and<A, B>(_a: Prf<A>, _b: Prf<B>) -> Prf<And<A, B>> {
        axiom()
    }

    /// Conjunction elimination. Constructs a proof from a
    /// conjunction by extracting the *first* conjunct.
    pub fn fst<A, B>(_a_and_b: Prf<And<A, B>>) -> Prf<A> {
        axiom()
    }

    /// Conjunction elimination. Constructs a proof from a
    /// conjunction by extracting the *second* conjunct.
    pub fn snd<A, B>(_a_and_b: Prf<And<A, B>>) -> Prf<B> {
        axiom()
    }

    /// Disjunction elimination. Uses a disjunction by using
    /// each disjunct.
    pub fn or<A, B, C>(
        _a_or_b: &Prf<Or<A, B>>,
        _a_to_c: &Prf<Imp<A, C>>,
        _b_to_c: &Prf<Imp<B, C>>,
    ) -> Prf<C> {
        axiom()
    }

    /// Disjunction introduction. Proves a disjunction by
    /// proving the *first* disjunct.
    pub fn left<A, B>(_a: &Prf<A>) -> Prf<Or<A, B>> {
        axiom()
    }

    /// Disjunction introduction. Proves a disjunction by
    /// proving the *second* disjunct.
    pub fn right<A, B>(_b: &Prf<B>) -> Prf<Or<A, B>> {
        axiom()
    }

    /// Negation introduction.
    /// Refutes a proposition by proving
    /// that it implies contradiction.
    pub fn not<A>(_a_to_f: &Prf<Imp<A, False>>) -> Prf<Not<A>> {
        axiom()
    }

    /// Shows a contradiction.
    pub fn contradiction<A>(
        _a: &Prf<A>,
        _not_a: &Prf<Not<A>>,
    ) -> Prf<False> {
        axiom()
    }

    /// Proves the trivially true proposition,
    /// which holds by definition.
    pub fn trivial<A>() -> Prf<True> {
        axiom()
    }

    /// Proof by absurdity (*ex falso quodlibet*).
    ///
    pub fn impossible<A>(_f: &Prf<False>) -> Prf<A> {
        axiom()
    }

    /// Any proposition is equivalent to itself.
    ///
    pub fn iff_refl<A>() -> Prf<Iff<A, A>> {
        axiom()
    }

    /// Any proposition implies itself.
    ///
    pub fn imp_refl<A>() -> Prf<Imp<A, A>> {
        axiom()
    }

    /// Propositional equivalence is symmetric.
    ///
    pub fn iff_symm<A, B>(
        _a_iff_b: &Prf<Iff<A, B>>,
    ) -> Prf<Iff<B, A>> {
        axiom()
    }

    /// Relational composition.
    ///
    /// Law of transitivity for propositional equivalence.
    ///
    pub fn iff_trans<A, B, C>(
        _a_iff_b: &Prf<Iff<A, B>>,
        _b_iff_c: &Prf<Iff<B, C>>,
    ) -> Prf<Iff<A, C>> {
        axiom()
    }

    /// Functional composition.
    ///
    /// Law of transitivity for implication.
    ///
    pub fn imp_trans<A, B, C>(
        _a_imp_b: &Prf<Imp<A, B>>,
        _b_imp_c: &Prf<Imp<B, C>>,
    ) -> Prf<Imp<A, C>> {
        axiom()
    }

    /// Law of antisymmetry for implication.
    ///
    pub fn imp_antisymm<A, B>(
        _a_imp_b: &Prf<Imp<A, B>>,
        _b_imp_a: &Prf<Imp<B, A>>,
    ) -> Prf<Iff<A, B>> {
        axiom()
    }
}

#[cfg(test)]
mod tests {

    use super::called::Called;
    use super::key::Key;
    use super::vec::Vec;

    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }

    #[test]
    fn named_vec() {
        std::vec::Vec::new().called(|filenames| {
            let filenames = Vec::from(filenames);
            let (filenames, _, _) =
                filenames.push(String::from("taxes.txt"));
            let (filenames, _, _) =
                filenames.push(String::from("passwords.txt"));
            let passwords = filenames.contains_key(1).unwrap();
            assert_eq!(
                filenames.get(passwords),
                &"passwords.txt"
            );
            let (filenames, poems, upcast) =
                filenames.push(String::from("poems.txt"));
            {
                fn assert_type<'passwords, 'poems>(
                    _: &Key<'passwords, usize>,
                    _: &Key<'poems, usize>,
                    _: &impl Fn(
                        Key<'passwords, usize>,
                    )
                        -> Key<'poems, usize>,
                ) {
                }
                assert_type(&passwords, &poems, &upcast);
            }
            assert_eq!(filenames.get(poems), &"poems.txt");
            assert_eq!(
                filenames.get(upcast(passwords)),
                &"passwords.txt"
            );
        });
    }
}