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
//! [`UnsizedVec<T>`], like [`Vec<T>`][alloc::vec::Vec], is a contiguous growable array
//! type with heap-allocated contents. Unlike [`Vec<T>`], it can store unsized values.
//!
//! Vectors have *O*(1) indexing, amortized *O*(1) push (to the end) and
//! *O*(1) pop (from the end). When `T` is [`Sized`], they use one heap
//! allocation; when it is not, they use two.
//!
//! This crate is nightly-only and experimental.
//!
//! # Examples
//!
//! You can explicitly create an [`UnsizedVec`] with [`UnsizedVec::new`]:
//!
//! ```
//! # use unsized_vec::UnsizedVec;
//! let v: UnsizedVec<i32> = UnsizedVec::new();
//! ```
//!
//! ...or by using the [`unsize_vec!`] macro:
//!
//! ```
//! # use core::fmt::Debug;
//! # use unsized_vec::{unsize_vec, UnsizedVec};
//! let v: UnsizedVec<[u32]> = unsize_vec![];
//!
//! let v: UnsizedVec<dyn Debug> = unsize_vec![1_u32, "hello!", 3.0_f64, (), -17_i32];
//! ```
//!
//! You can [`push`] or [`push_unsize`] values onto the end of a vector (which will grow the vector
//! as needed):
//!
//! ```
//! # use core::fmt::Debug;
//! # use unsized_vec::{unsize_vec, UnsizedVec};
//! let mut v: UnsizedVec<dyn Debug> = unsize_vec![1_u32, "hello!", 3.0_f64, (), -17_i32];
//!
//! v.push_unsize(3);
//! ```
//!
//! Popping values works in much the same way:
//!
//! ```
//! # use core::fmt::Debug;
//! # use emplacable::box_new_with;
//! # use unsized_vec::{unsize_vec, UnsizedVec};
//! let mut v: UnsizedVec<dyn Debug> = unsize_vec![1_u32, "hello!"];
//!
//! // "hello!" is copied directly into a new heap allocation
//! let two: Option<Box<dyn Debug>> = v.pop_into().map(box_new_with);
//! ```
//!
//! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
//!
//! ```
//! # use core::fmt::Debug;
//! # use unsized_vec::{unsize_vec, UnsizedVec};
//! let mut v: UnsizedVec<dyn Debug> = unsize_vec![1_u32, "hello!", [(); 0]];
//! let greeting = &v[1];
//! dbg!(greeting);
//! ```
//! [`Vec<T>`]: alloc::vec::Vec
//! [`push`]: UnsizedVec::push
//! [`push_unsize`]: UnsizedVec::push_unsize

#![allow(incomplete_features)] // For `specialization`
#![feature(
    allocator_api,
    array_windows,
    const_align_of_val,
    const_nonnull_new,
    const_option,
    const_size_of_val,
    forget_unsized,
    int_roundings,
    ptr_metadata,
    // We avoid specializing based on subtyping,
    // so barring compiler bugs, our usage should be sound.
    specialization,
    strict_provenance,
    try_reserve_kind,
    type_alias_impl_trait,
    unchecked_math,
    unsize,
    unsized_fn_params,
)]
#![no_std]

mod helper;
mod inner;
mod marker;

#[doc(hidden)]
pub extern crate alloc;
use alloc::{alloc::handle_alloc_error, collections::TryReserveErrorKind};
use core::{
    self, cmp,
    fmt::{self, Debug, Formatter},
    hash::Hash,
    iter::FusedIterator,
    marker::Unsize,
    mem,
    ops::{Index, IndexMut},
};
use emplacable::{unsize, Emplacable, EmplacableFn, Emplacer};

use inner::{Align, Size, UnsizedVecImpl, UnsizedVecProvider};

/// The error type for `try_reserve` methods.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TryReserveError {
    kind: TryReserveErrorKind,
}

#[track_caller]
#[inline]
fn to_align<T: ?Sized>(align: usize) -> AlignTypeFor<T> {
    #[cold]
    #[inline(never)]
    fn invalid_align(align: usize) -> ! {
        panic!("align {align} is not a power of 2")
    }

    let Some(ret) = AlignTypeFor::<T>::new(align) else {
        invalid_align(align)
    };

    ret
}

#[track_caller]
#[inline]
fn unwrap_try_reserve_result<T>(result: Result<T, TryReserveError>) -> T {
    #[cold]
    #[inline(never)]
    fn handle_err(e: TryReserveError) -> ! {
        match e.kind {
            TryReserveErrorKind::CapacityOverflow => panic!("Capacity overflowed `isize::MAX`"),
            TryReserveErrorKind::AllocError { layout, .. } => handle_alloc_error(layout),
        }
    }

    match result {
        Ok(val) => val,
        Err(e) => handle_err(e),
    }
}

impl From<::alloc::collections::TryReserveError> for TryReserveError {
    fn from(value: ::alloc::collections::TryReserveError) -> Self {
        TryReserveError { kind: value.kind() }
    }
}

type AlignTypeFor<T> = <<T as UnsizedVecImpl>::Impl as UnsizedVecProvider<T>>::Align;
type SizeTypeFor<T> = <<T as UnsizedVecImpl>::Impl as UnsizedVecProvider<T>>::Size;

/// Like [`Vec`][0], but can store unsized values.
///
/// # Memory layout
///
/// `UnsizedVec` is actually three different types rolled in to one;
/// specialization is used to choose the optimal implementation based on the properties
/// of `T`.
///
/// 1. When `T` is a [`Sized`] type, `UnsizedVec<T>` is a newtype around [`Vec<T>`][0],
/// with exactly the same memoy layout.
///
/// 2. When `T` is a slice, there are two heap allocations.
/// The first is to the slices themsleves; they are laid out end-to-end, one after the other,
/// with no padding in between. The second heap allocation is to a list of offsets, to store
/// where each element begins and ends.
///
/// 3. When `T` is neither of the above, there are still two allocations.
/// The first allocation still contains the elements of the vector laid out end-to-end,
/// but now every element is padded to at least the alignment of the most-aligned element
/// in the `UnsizedVec`. For this reason, adding a new element to the vec with a larger alignment
/// than any of the elements already in it will add new padding to all the existing elements,
/// which will involve a lot of copying and probably a reallocation. By default, [`UnsizedVec::new`]
/// sets the alignment to [`core::mem::align_of::<usize>()`], so as long as none of your trait objects
/// are aligned to more than that, you won't have to worry about re-padding.
/// For this last case, the second allocation, in addition to storing offsets, also stores the pointer
/// metadata of each element.
///
/// ## Managing capacity
///
/// [`Vec<T>`][0] has only one kind of capacity to worry about: elementwise capacity. And so does
/// `UnsizedVec<T>`, as long as `T: Sized`. You can use functions like [`capacity`], [`with_capacity`]
/// and [`reserve`] to manage this capacity.
///
/// When `T` is a slice, there are two kinds of capacities: element capacity and byte capacity.
/// Adding new elements to the vec is guaranteed not to reallocate as long as
/// the number of elements doesn't exceed the element capacity *and* the total size of all
/// the elements in bytes doesn't exceed the byte capacity. You can use functions like
/// [`byte_capacity`], [`with_capacity_bytes`], and [`reserve_capacity_bytes`] to manage
/// these two capacities.
///
/// When `T` is a trait object, there is a third type of capacity: alignment. To avoid
/// reallocation when adding a new element to the vec, you need to ensure that you have
/// sufficient element and byte capacity, and that the vec's align is not less than the
/// alignment of the new element. Functions like [`align`], [`with_capacity_bytes_align`], and
/// [`reserve_capacity_bytes_align`], can be used to manage all three capacities in this case.
///
/// # Limitations
///
/// - `UnsizedVec<T>` is invariant with respect to `T`; ideally, it should be covariant.
/// This is because Rust forces invariance on all structs that contain associated types
/// referencing `T`. Hopefully, future language features will allow lifting this limitation.
/// - Rust functions can't directly return unsized types. So this crate's functions return
/// them indirectly, though the "emplacer" mechanism defined in the [`emplacable`] crate.
/// See that crate's documentation for details, and the documentation of [`pop_into`] and
/// [`remove_into`] for usage examples.
///
/// # Example
///
/// ```
/// #![feature(unsized_fn_params)]
/// use core::fmt::Debug;
///
/// use emplacable::box_new_with;
/// use unsized_vec::{unsize_vec, UnsizedVec};
///
/// let mut vec: UnsizedVec<dyn Debug> = unsize_vec![27.53_f32, "oh the places we'll go", Some(())];
///
/// for traitobj in &vec {
///     dbg!(traitobj);
/// };
///
/// assert_eq!(vec.len(), 3);
///
/// let maybe_popped: Option<Box<dyn Debug>> = vec.pop_into().map(box_new_with);
/// let popped = maybe_popped.unwrap();
/// dbg!(&*popped);
///
/// assert_eq!(vec.len(), 2);
/// ```
///
/// [0]: alloc::vec::Vec
/// [`emplacable`]: emplacable
/// [`capacity`]: UnsizedVec::capacity
/// [`with_capacity`]: UnsizedVec::with_capacity
/// [`reserve`]: UnsizedVec::reserve
/// [`byte_capacity`]: UnsizedVec::byte_capacity
/// [`with_capacity_bytes`]: UnsizedVec::with_capacity_bytes
/// [`reserve_capacity_bytes`]: UnsizedVec::reserve_capacity_bytes
/// [`align`]: UnsizedVec::align
/// [`with_capacity_bytes_align`]: UnsizedVec::with_capacity_bytes_align
/// [`reserve_capacity_bytes_align`]: UnsizedVec::reserve_capacity_bytes_align
/// [`pop_into`]: UnsizedVec::pop_into
/// [`remove_into`]: UnsizedVec::remove_into
#[repr(transparent)]
pub struct UnsizedVec<T>
where
    T: ?Sized,
{
    inner: <T as UnsizedVecImpl>::Impl,
}

impl<T: ?Sized> UnsizedVec<T> {
    /// Create a new, empty `UnsizedVec`.
    /// Does not allocate.
    ///
    /// When `T`'s alignmnent is not known
    /// at compile-time, this uses `mem::align_of::<usize>()`
    /// as the default alignment.
    #[must_use]
    #[inline]
    pub const fn new() -> UnsizedVec<T> {
        UnsizedVec {
            inner: UnsizedVecProvider::NEW_ALIGN_PTR,
        }
    }

    /// Create a new, empty `UnsizedVec` with the given capacity.
    ///
    /// When `T`'s alignmnent is not known
    /// at compile-time, this uses `mem::align_of::<usize>()`
    /// as the default alignment.
    #[must_use]
    #[inline]
    pub fn with_capacity(capacity: usize) -> UnsizedVec<T> {
        let mut vec = UnsizedVec::new();
        vec.reserve_exact(capacity);
        vec
    }

    /// Create a new, empty `UnsizedVec` with the given capacity.
    /// (When `T: Aligned` does not hold, an alignment of 1 is used.)
    ///
    /// When `T`'s alignmnent is not known
    /// at compile-time, this uses `mem::align_of::<usize>()`
    /// as the default alignment.
    #[must_use]
    #[inline]
    pub fn with_capacity_bytes(capacity: usize, byte_capacity: usize) -> UnsizedVec<T> {
        let mut vec = UnsizedVec::new();
        vec.reserve_exact_capacity_bytes(capacity, byte_capacity);
        vec
    }

    /// Create a new, empty `UnsizedVec` with the given capacity
    /// (in bytes) and alignment.
    ///
    /// `align` is ignored when `T`'s alignment is known at compile time
    #[must_use]
    #[inline]
    pub fn with_capacity_bytes_align(
        capacity: usize,
        byte_capacity: usize,
        align: usize,
    ) -> UnsizedVec<T> {
        let mut vec = UnsizedVec {
            inner: UnsizedVecProvider::NEW_ALIGN_1,
        };
        vec.reserve_exact_capacity_bytes_align(capacity, byte_capacity, align);
        vec
    }

    /// Returns the number of elements the vector can hold without
    /// reallocating.
    ///
    /// For `T: ?Sized`, this only concers whether metadata
    /// could get reallocated, not the elements themselves.
    #[must_use]
    #[inline]
    pub fn capacity(&self) -> usize {
        self.inner.capacity()
    }

    /// Returns the number of bytes the vector can hold without
    /// reallocating.
    #[must_use]
    #[inline]
    pub fn byte_capacity(&self) -> usize {
        self.inner.byte_capacity()
    }

    /// Returns the maximum alignment of the values this vector
    /// can hold without re-padding and reallocating.
    ///
    /// Only relevant when `T`'s alignment is not known at compile time.
    #[must_use]
    #[inline]
    pub fn align(&self) -> usize {
        self.inner.align()
    }

    /// Reserves capacity for at least `additional` more elements to be inserted
    /// in the given `UnsizedVec<T>`. The collection may reserve more space to
    /// speculatively avoid frequent reallocations.
    ///
    /// When `T` is not `Sized`, this only reseves space to store *metadata*.
    /// Consider using [`reserve_capacity_bytes`] instead in such cases.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` bytes.
    ///
    /// [`reserve_capacity_bytes`]: UnsizedVec::reserve_capacity_bytes
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        unwrap_try_reserve_result(self.try_reserve(additional));
    }

    /// Reserves capacity for at least `additional` more elements,
    /// taking up at least `additional_bytes` bytes of space, to be inserted
    /// in the given `UnsizedVec<T>`. The collection may reserve more space to
    /// speculatively avoid frequent reallocations.
    ///
    /// When `T`'s alignment is not known at compile time,
    /// the vec may still reallocate if you push a new element onto the
    /// vec with an alignment greater than `self.align()`. Consider
    /// using [`reserve_capacity_bytes_align`] instead in such cases.
    ///
    /// # Panics
    ///
    /// Panics if the either of the new capacities exceeds `isize::MAX` bytes.
    ///
    /// [`reserve_capacity_bytes_align`]: UnsizedVec::reserve_capacity_bytes_align
    #[inline]
    pub fn reserve_capacity_bytes(&mut self, additional: usize, additional_bytes: usize) {
        unwrap_try_reserve_result(self.try_reserve_capacity_bytes(additional, additional_bytes));
    }

    /// Reserves capacity for at least `additional` more elements,
    /// taking up at least `additional_bytes` bytes of space,
    /// and with alignment of at most `align`, to be inserted
    /// in the given `UnsizedVec<T>`. The collection may reserve more space to
    /// speculatively avoid frequent reallocations.
    ///
    /// When `T`'s alignment is known at compile time,
    /// `align` is ignored. Consider using [`reserve_capacity_bytes`]
    /// instead in such cases.
    ///
    /// # Panics
    ///
    /// Panics if the either of the new capacities exceeds `isize::MAX` bytes,
    /// or if `align` is not a power of two.
    ///
    /// [`reserve_capacity_bytes`]: UnsizedVec::reserve_capacity_bytes
    #[inline]
    pub fn reserve_capacity_bytes_align(
        &mut self,
        additional: usize,
        additional_bytes: usize,
        align: usize,
    ) {
        unwrap_try_reserve_result(self.try_reserve_capacity_bytes_align(
            additional,
            additional_bytes,
            align,
        ));
    }

    /// Reserves capacity for at least `additional` more elements to be inserted
    /// in the given `UnsizedVec<T>`. Unlike [`reserve`], this will not
    /// deliberately over-allocate to speculatively avoid frequent allocations.
    ///
    /// When `T` is not `Sized`, this only reseves space to store *metadata*.
    /// Consider using [`reserve_exact_capacity_bytes`] instead in such cases.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` bytes.
    ///
    /// [`reserve`]: UnsizedVec::reserve
    /// [`reserve_exact_capacity_bytes`]: UnsizedVec::reserve_exact_capacity_bytes
    #[inline]
    pub fn reserve_exact(&mut self, additional: usize) {
        unwrap_try_reserve_result(self.try_reserve_exact_capacity_bytes(additional, 0));
    }

    /// Reserves capacity for at least `additional` more elements,
    /// taking up at least `additional_bytes` bytes of space, to be inserted
    /// in the given `UnsizedVec<T>`. Unlike [`reserve_capacity_bytes`], this will not
    /// deliberately over-allocate to speculatively avoid frequent allocations.
    ///
    /// When `T`'s alignment is not known at compile time,
    /// the vec may still reallocate if you push a new element onto the
    /// vec with an alignment greater than `self.align()`. Consider
    /// using [`reserve_exact_capacity_bytes_align`] instead in such cases.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` bytes.
    ///
    /// [`reserve_capacity_bytes`]: UnsizedVec::reserve_capacity_bytes
    /// [`reserve_exact_capacity_bytes_align`]: UnsizedVec::reserve_exact_capacity_bytes_align
    #[inline]
    pub fn reserve_exact_capacity_bytes(&mut self, additional: usize, additional_bytes: usize) {
        unwrap_try_reserve_result(
            self.try_reserve_exact_capacity_bytes(additional, additional_bytes),
        );
    }

    /// Reserves capacity for at least `additional` more elements,
    /// taking up at least `additional_bytes` bytes of space,
    /// and with alignment of at most `align`, to be inserted
    /// in the given `UnsizedVec<T>`. Unlike [`reserve_capacity_bytes_align`], this will not
    /// deliberately over-allocate to speculatively avoid frequent allocations.
    ///
    /// When `T`'s alignment is known at compile time,
    /// `align` is ignored. Consider using [`reserve_exact_capacity_bytes`]
    /// instead in such cases.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` bytes.
    ///
    /// [`reserve_capacity_bytes_align`]: UnsizedVec::reserve_capacity_bytes_align
    /// [`reserve_exact_capacity_bytes`]: UnsizedVec::reserve_exact_capacity_bytes
    #[inline]
    pub fn reserve_exact_capacity_bytes_align(
        &mut self,
        additional: usize,
        additional_bytes: usize,
        align: usize,
    ) {
        unwrap_try_reserve_result(self.try_reserve_exact_capacity_bytes_align(
            additional,
            additional_bytes,
            align,
        ));
    }

    /// Reserves capacity for at least `additional` more elements to be inserted
    /// in the given `UnsizedVec<T>`. The collection may reserve more space to
    /// speculatively avoid frequent reallocations.
    ///
    /// When `T` is not `Sized`, this only reseves space to store *metadata*.
    /// Consider using [`try_reserve_capacity_bytes`] instead in such cases.
    ///
    /// # Errors
    ///
    /// If the capacity overflows, or the allocator reports a failure, then an error
    /// is returned.
    ///
    /// [`try_reserve_capacity_bytes`]: UnsizedVec::try_reserve_capacity_bytes
    #[inline]
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.inner.try_reserve(additional)
    }

    /// Reserves capacity for at least `additional` more elements,
    /// taking up at least `additional_bytes` bytes of space, to be inserted
    /// in the given `UnsizedVec<T>`. The collection may reserve more space to
    /// speculatively avoid frequent reallocations.
    ///
    /// When `T`'s alignment is not known at compile time,
    /// the vec may still reallocate if you push a new element onto the
    /// vec with an alignment greater than `self.align()`. Consider
    /// using [`try_reserve_capacity_bytes_align`] instead in such cases.
    ///
    /// # Errors
    ///
    /// If the capacity overflows, or the allocator reports a failure, then an error
    /// is returned.
    ///
    /// [`try_reserve_capacity_bytes_align`]: UnsizedVec::try_reserve_capacity_bytes_align
    #[inline]
    pub fn try_reserve_capacity_bytes(
        &mut self,
        additional: usize,
        additional_bytes: usize,
    ) -> Result<(), TryReserveError> {
        self.try_reserve_capacity_bytes_align(additional, additional_bytes, 1)
    }

    /// Reserves capacity for at least `additional` more elements,
    /// taking up at least `additional_bytes` bytes of space,
    /// and with alignment of at most `align`, to be inserted
    /// in the given `UnsizedVec<T>`. The collection may reserve more space to
    /// speculatively avoid frequent reallocations.
    ///
    /// When `T`'s alignment is known at compile time,
    /// `align` is ignored. Consider using [`try_reserve_capacity_bytes`]
    /// instead in such cases.
    ///
    /// # Errors
    ///
    /// If the capacity overflows, or the allocator reports a failure, then an error
    /// is returned.
    ///
    /// # Panics
    ///
    /// Panics if `align` is not a power of two.
    ///
    /// [`try_reserve_capacity_bytes`]: UnsizedVec::try_reserve_capacity_bytes
    #[inline]
    pub fn try_reserve_capacity_bytes_align(
        &mut self,
        additional: usize,
        additional_bytes: usize,
        align: usize,
    ) -> Result<(), TryReserveError> {
        self.try_reserve(additional)?;

        debug_assert!(self.capacity() >= self.len() + additional);

        let align = to_align::<T>(align);

        let byte_cap = self.byte_capacity();

        let needed_bytes = additional_bytes.saturating_sub(self.unused_byte_cap());

        let optimist_bytes = if needed_bytes > 0 {
            cmp::max(needed_bytes, byte_cap)
        } else {
            0
        };

        // First we try to double capacities.
        // if that fails, we try again with only what we really need.
        if optimist_bytes > needed_bytes {
            let result = self
                .inner
                .try_reserve_additional_bytes_align(optimist_bytes, align);

            if result.is_ok() {
                return result;
            }
        }

        let result = self
            .inner
            .try_reserve_additional_bytes_align(needed_bytes, align);

        debug_assert!(self.byte_capacity() >= self.byte_len() + additional_bytes);

        result
    }

    /// Reserves capacity for at least `additional` more elements to be inserted
    /// in the given `UnsizedVec<T>`. Unlike [`try_reserve`], this will not
    /// deliberately over-allocate to speculatively avoid frequent allocations.
    ///
    /// When `T` is not `Sized`, this only reseves space to store *metadata*.
    /// Consider using [`try_reserve_exact_capacity_bytes`] instead in such cases.
    ///
    /// # Errors
    ///
    /// If the capacity overflows, or the allocator reports a failure, then an error
    /// is returned.
    ///
    /// [`try_reserve`]: UnsizedVec::try_reserve
    /// [`try_reserve_exact_capacity_bytes`]: UnsizedVec::try_reserve_exact_capacity_bytes
    #[inline]
    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.inner.try_reserve_exact(additional)
    }

    /// Reserves capacity for at least `additional` more elements,
    /// taking up at least `additional_bytes` bytes of space, to be inserted
    /// in the given `UnsizedVec<T>`. Unlike [`try_reserve_capacity_bytes`], this will not
    /// deliberately over-allocate to speculatively avoid frequent allocations.
    ///
    /// When `T`'s alignment is not known at compile time,
    /// the vec may still reallocate if you push a new element onto the
    /// vec with an alignment greater than `self.align()`. Consider
    /// using [`try_reserve_exact_capacity_bytes_align`] instead in such cases.
    ///
    /// # Errors
    ///
    /// If the capacity overflows, or the allocator reports a failure, then an error
    /// is returned.
    ///
    /// [`try_reserve_capacity_bytes`]: UnsizedVec::try_reserve_capacity_bytes
    /// [`try_reserve_exact_capacity_bytes_align`]: UnsizedVec::try_reserve_exact_capacity_bytes_align
    #[inline]
    pub fn try_reserve_exact_capacity_bytes(
        &mut self,
        additional: usize,
        additional_bytes: usize,
    ) -> Result<(), TryReserveError> {
        self.try_reserve_exact_capacity_bytes_align(additional, additional_bytes, 1)
    }

    /// Reserves capacity for at least `additional` more elements,
    /// taking up at least `additional_bytes` bytes of space,
    /// and with alignment of at most `align`, to be inserted
    /// in the given `UnsizedVec<T>`. Unlike [`try_reserve_capacity_bytes_align`], this will not
    /// deliberately over-allocate to speculatively avoid frequent allocations.
    ///
    /// When `T`'s alignment is known at compile time,
    /// `align` is ignored. Consider using [`try_reserve_exact_capacity_bytes`]
    /// instead in such cases.
    ///
    /// # Errors
    ///
    /// If the capacity overflows, or the allocator reports a failure, then an error
    /// is returned.
    ///
    /// # Panics
    ///
    /// Panics if `align` is not a power of two.
    ///
    /// [`try_reserve_capacity_bytes_align`]: UnsizedVec::try_reserve_capacity_bytes_align
    /// [`try_reserve_exact_capacity_bytes`]: UnsizedVec::try_reserve_exact_capacity_bytes
    #[inline]
    pub fn try_reserve_exact_capacity_bytes_align(
        &mut self,
        additional: usize,
        additional_bytes: usize,
        align: usize,
    ) -> Result<(), TryReserveError> {
        self.inner.try_reserve(additional)?;
        let align = to_align::<T>(align);

        self.inner
            .try_reserve_additional_bytes_align(additional_bytes, align)
    }

    /// Shrinks all the capacities of the vec as much as possible.
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.inner
            .shrink_capacity_bytes_align_to(0, 0, to_align::<T>(1));
    }

    /// Shrinks the elementwise capacity of the vector with a lower bound.
    ///
    /// The capacity will remain at least as large as both the length
    /// and the supplied value.
    ///
    /// If the current capacity is less than the lower limit, this is a no-op.
    ///
    /// For `T: ?Sized`, this only effects elementwise capacity.
    /// Consider using [`shrink_capacity_bytes_to`] in such cases.
    ///
    /// [`shrink_capacity_bytes_to`]: UnsizedVec::shrink_capacity_bytes_to
    #[inline]
    pub fn shrink_to(&mut self, min_capacity: usize) {
        self.inner.shrink_capacity_bytes_align_to(
            min_capacity,
            usize::MAX,
            to_align::<T>(1 << (usize::BITS - 1)),
        );
    }

    /// Shrinks the elementwise and byte capacities of the vector with
    /// lower bounds.
    ///
    /// The capacities will remain at least as large as both the lengths
    /// and the supplied values.
    ///
    /// If the current capacities are less than the lower limits, this is a no-op.
    ///
    /// When `T`'s alignment is not known at compile-time, this only effects elementwise
    /// and bytewise capacities.
    /// Consider using [`shrink_capacity_bytes_align_to`] in such cases.
    ///
    /// [`shrink_capacity_bytes_align_to`]: UnsizedVec::shrink_capacity_bytes_align_to
    #[inline]
    pub fn shrink_capacity_bytes_to(&mut self, min_capacity: usize, min_byte_capacity: usize) {
        self.inner.shrink_capacity_bytes_align_to(
            min_capacity,
            min_byte_capacity,
            to_align::<T>(1 << (usize::BITS - 1)),
        );
    }

    /// Shrinks the elementwise, byte, and alignment capacities of the vector with
    /// lower bounds.
    ///
    /// The capacities will remain at least as large as both the lengths
    /// and the supplied values.
    ///
    /// If the current capacities are less than the lower limits, this is a no-op.
    ///
    /// # Panics
    ///
    /// Panics if `min_align` is not a power of two.
    #[inline]
    pub fn shrink_capacity_bytes_align_to(
        &mut self,
        min_capacity: usize,
        min_byte_capacity: usize,
        min_align: usize,
    ) {
        self.inner.shrink_capacity_bytes_align_to(
            min_capacity,
            min_byte_capacity,
            to_align::<T>(min_align),
        );
    }

    /// Inserts an element at position `index` within the vector, shifting all
    /// elements after it to the right.
    ///
    /// If `T` is not `Sized`, you will need
    /// `#![feature(unsized_fn_params)]` to call this.
    /// You may also need the [`unsize`] macro, which
    /// requires additional nightly features.
    ///
    /// Alternatively, you can use [`insert_unsize`][0],
    /// which takes care of unsizing for you.
    ///
    /// # Example
    ///
    /// ```
    /// #![feature(allocator_api, ptr_metadata, unsized_fn_params)]
    ///
    /// use core::fmt::Debug;
    ///
    /// use emplacable::unsize;
    /// use unsized_vec::UnsizedVec;
    ///
    /// let mut vec: UnsizedVec<dyn Debug> = UnsizedVec::new();
    ///
    /// vec.push(unsize!([1, 2], ([i32; 2]) -> dyn Debug));
    /// vec.insert(0, unsize!("can you believe it", (&str) -> dyn Debug));
    /// dbg!(&vec[0]);
    /// ```
    ///
    /// [0]: UnsizedVec::insert_unsize
    #[inline]
    pub fn insert(&mut self, index: usize, value: T) {
        #[track_caller]
        #[cold]
        #[inline(never)]
        fn assert_failed(index: usize, len: usize) -> ! {
            panic!("insertion index (is {index}) should be <= len (is {len})");
        }

        if index <= self.len() {
            let size_of_val = SizeTypeFor::<T>::of_val(&value);
            self.reserve_capacity_bytes_align(1, size_of_val.get(), mem::align_of_val(&value));

            // SAFETY: reserved needed capacity and performed bounds check above
            unsafe { self.inner.insert_unchecked(index, value, size_of_val) }
        } else {
            assert_failed(index, self.len())
        }
    }

    /// Appends an element to the back of a collection
    /// after unsizing it.
    ///
    /// # Examples
    ///
    /// ```
    /// use core::fmt::Debug;
    ///
    /// use unsized_vec::UnsizedVec;
    ///
    /// let mut vec: UnsizedVec<dyn Debug> = UnsizedVec::new();
    ///
    /// vec.push_unsize([1, 2]);
    /// vec.insert_unsize(0, "can you believe it");
    /// dbg!(&vec[0]);
    /// ```
    #[inline]
    pub fn insert_unsize<S>(&mut self, index: usize, value: S)
    where
        S: Unsize<T>,
    {
        self.insert(index, unsize!(value, (S) -> T));
    }

    /// Inserts an element at position `index` within the vector, shifting all
    /// elements after it to the right.
    ///
    /// Accepts the element as an [`Emplacable<T, _>`]
    /// instead of `T` directly, analogously
    /// to [`emplacable::box_new_with`].
    ///
    /// # Example
    ///
    /// ```
    /// #![feature(allocator_api, ptr_metadata, unsized_fn_params)]
    ///
    /// use core::fmt::Debug;
    ///
    /// use unsized_vec::{unsize_vec, UnsizedVec};
    ///
    /// let mut vec_1: UnsizedVec<dyn Debug> = unsize_vec![32, "hello"];
    /// let mut vec_2: UnsizedVec<dyn Debug> = unsize_vec![97];
    ///
    /// vec_2.insert_with(0, vec_1.pop_into().unwrap());
    ///
    /// assert_eq!(vec_1.len(), 1);
    /// assert_eq!(vec_2.len(), 2);
    /// dbg!(&vec_2[0]);
    /// ```
    #[inline]
    pub fn insert_with(&mut self, index: usize, value: Emplacable<T, impl EmplacableFn<T>>) {
        #[track_caller]
        #[cold]
        #[inline(never)]
        fn assert_failed(index: usize, len: usize) -> ! {
            panic!("insertion index (is {index}) should be <= len (is {len})");
        }

        if index <= self.len() {
            // SAFETY: did bounds check just above
            unsafe { self.inner.insert_with_unchecked(index, value) }
        } else {
            assert_failed(index, self.len())
        }
    }

    /// Removes and returns the element at position `index` within the vector,
    /// shifting all elements after it to the left.
    ///
    /// Because `T` might be unsized, and functions can't return
    /// unsized values directly, this method returns the element using
    /// the "emplacer" mechanism. You can pass the returned [`Emplacable<T, _>`]
    /// to a function like [`box_new_with`] to get the contained `T`.
    ///
    /// # Example
    ///
    /// ```
    /// use core::fmt::Debug;
    ///
    /// use emplacable::box_new_with;
    /// use unsized_vec::UnsizedVec;
    ///
    /// let mut vec = UnsizedVec::<dyn Debug>::new();
    ///
    /// vec.push_unsize("A beautiful day today innit");
    /// vec.push_unsize("Quite right ol chap");
    ///
    /// let popped: Box<dyn Debug> = box_new_with(vec.remove_into(0));
    /// dbg!(&popped);
    ///
    /// ```
    ///
    /// [`box_new_with`]: emplacable::box_new_with
    #[inline]
    pub fn remove_into(&mut self, index: usize) -> Emplacable<T, impl EmplacableFn<T> + '_> {
        #[track_caller]
        #[cold]
        #[inline(never)]
        fn assert_failed(index: usize, len: usize) -> ! {
            panic!("removal index (is {index}) should be < len (is {len})");
        }

        if index < self.len() {
            let closure = move |emplacer: &mut Emplacer<'_, T>| {
                // SAFETY: check `index < len` right above
                unsafe { self.inner.remove_into_unchecked(index, emplacer) };
            };
            // SAFETY: `remove_into_unchecked` upholds the requirements
            unsafe { Emplacable::from_fn(closure) }
        } else {
            assert_failed(index, self.len())
        }
    }

    /// Appends an element to the back of a collection.
    ///
    /// If `T` is not `Sized`, you will need
    /// `#![feature(unsized_fn_params)]` to call this.
    /// You may also need the [`unsize`] macro, which
    /// requires additional nightly features.
    ///
    /// Alternatively, you can use [`push_unsize`][0],
    /// which takes care of unsizing for you.
    ///
    /// # Example
    ///
    /// ```
    /// #![feature(allocator_api, ptr_metadata, unsized_fn_params)]
    ///
    /// use core::fmt::Debug;
    ///
    /// use emplacable::unsize;
    /// use unsized_vec::UnsizedVec;
    ///
    /// let mut vec: UnsizedVec<dyn Debug> = UnsizedVec::new();
    ///
    /// vec.push(unsize!([1, 2], ([i32; 2]) -> dyn Debug));
    /// dbg!(&vec[0]);
    /// ```
    ///
    /// [0]: UnsizedVec::push_unsize
    #[inline]
    pub fn push(&mut self, value: T) {
        let size_of_val = SizeTypeFor::<T>::of_val(&value);

        self.reserve_capacity_bytes_align(1, size_of_val.get(), mem::align_of_val(&value));

        // SAFETY: reserved needed capacity above
        unsafe { self.inner.push_unchecked(value, size_of_val) }
    }

    /// Appends an element to the back of a collection
    /// after coercing it to an unsized type.
    ///
    /// # Example
    ///
    /// ```
    /// use core::fmt::Debug;
    ///
    /// use unsized_vec::UnsizedVec;
    ///
    /// let mut vec: UnsizedVec<dyn Debug> = UnsizedVec::new();
    ///
    /// vec.push_unsize([1, 2]);
    /// dbg!(&vec[0]);
    ///
    /// ```
    #[inline]
    pub fn push_unsize<S: Unsize<T>>(&mut self, value: S) {
        self.push(unsize!(value, (S) -> T));
    }

    /// Appends an element to the back of a collection.
    ///
    /// Accepts the element as an [`Emplacable<T, _>`]
    /// instead of `T` directly, analogously
    /// to [`emplacable::box_new_with`].
    ///
    /// ```
    /// #![feature(allocator_api, ptr_metadata, unsized_fn_params)]
    ///
    /// use core::fmt::Debug;
    ///
    /// use unsized_vec::{unsize_vec, UnsizedVec};
    ///
    /// let mut vec_1: UnsizedVec<dyn Debug> = unsize_vec![32, "hello"];
    /// let mut vec_2: UnsizedVec<dyn Debug> = UnsizedVec::new();
    ///
    /// vec_2.push_with(vec_1.pop_into().unwrap());
    ///
    /// assert_eq!(vec_1.len(), 1);
    /// dbg!(&vec_2[0]);
    /// ```
    #[inline]
    pub fn push_with(&mut self, value: Emplacable<T, impl EmplacableFn<T>>) {
        self.inner.push_with(value);
    }

    /// Removes the last element from a vector and returns it, or [`None`] if it
    /// is empty.
    ///
    /// Because `T` might be unsized, and functions can't return
    /// unsized values directly, this method returns the element using
    /// the "emplacer" mechanism. You can pass the returned [`Emplacable<T, _>`]
    /// to a function like [`box_new_with`] to get the contained `T`.
    ///
    /// # Example
    ///
    /// ```
    /// use core::fmt::Debug;
    ///
    /// use emplacable::{box_new_with, Emplacable};
    /// use unsized_vec::{UnsizedVec};
    ///
    /// let mut vec = UnsizedVec::<dyn Debug>::new();
    ///
    /// dbg!(vec.is_empty());
    /// let nothing: Option<Box<dyn Debug>> = vec.pop_into().map(box_new_with);
    /// assert!(nothing.is_none());
    ///
    /// vec.push_unsize("A beautiful day today");
    /// let popped: Option<Box<dyn Debug>> = vec.pop_into().map(box_new_with);
    /// let unwrapped: Box<dyn Debug> = popped.unwrap();
    /// dbg!(&unwrapped);
    ///
    /// vec.push_unsize("innit?");
    /// dbg!(&vec);
    ///
    /// let mut popped_emplacable: Emplacable<dyn Debug, _> = vec.pop_into().unwrap();
    ///
    /// // vec.push_unsize("yea"); // error: cannot borrow `vec` as mutable more than once at a time
    /// // The `vec` will remain borrowed until you consume the `Emplacable`!
    ///
    /// // or we can just drop it...
    /// // dropping an `Emplacable` drops
    /// // the contained value.
    /// popped_emplacable;
    ///
    /// assert!(vec.is_empty());
    ///
    /// vec.push_unsize("yea"); // works now
    ///
    /// ```
    ///
    /// [`box_new_with`]: emplacable::box_new_with
    #[inline]
    pub fn pop_into(&mut self) -> Option<Emplacable<T, impl EmplacableFn<T> + '_>> {
        if !self.is_empty() {
            let closure = move |emplacer: &mut Emplacer<'_, T>| {
                // SAFETY: checked above that vec is non-empty
                unsafe { self.inner.pop_into_unchecked(emplacer) }
            };

            // SAFETY: `pop_into_unchecked` upholds the requirements of this closure
            Some(unsafe { Emplacable::from_fn(closure) })
        } else {
            None
        }
    }

    /// Returns the number of elements in the vector, also referred to
    /// as its 'length'.
    #[must_use]
    #[inline]
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns the number of used bytes in the vector.
    #[must_use]
    #[inline]
    pub fn byte_len(&self) -> usize {
        self.inner.byte_len()
    }

    /// Returns `true` if the vector contains no elements.
    #[must_use]
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns a reference to an element,
    /// or `None` if `index` is out of range.
    #[must_use]
    #[inline]
    pub fn get(&self, index: usize) -> Option<&T> {
        // SAFETY: Bounds check done right before
        (index < self.len()).then(|| unsafe { self.get_unchecked(index) })
    }

    /// Returns a mutable reference to an element,
    /// or `None` if `index` is out of range.
    #[must_use]
    #[inline]
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        // SAFETY: Bounds check done right before
        (index < self.len()).then(|| unsafe { self.get_unchecked_mut(index) })
    }

    /// Returns a reference to an element, without doing bounds
    /// checking.
    ///
    /// # Safety
    ///
    /// Calling this method with an out-of-bounds index is *[undefined behavior]*
    /// even if the resulting reference is not used.
    #[must_use]
    #[inline]
    pub unsafe fn get_unchecked(&self, index: usize) -> &T {
        // SAFETY: precondition of function
        unsafe { self.inner.get_unchecked_raw(index).as_ref() }
    }

    /// Returns a mutable reference to an element, without doing bounds
    /// checking.
    ///
    /// # Safety
    ///
    /// Calling this method with an out-of-bounds index is *[undefined behavior]*
    /// even if the resulting reference is not used.
    #[must_use]
    #[inline]
    pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
        // SAFETY: precondition of function
        unsafe { self.inner.get_unchecked_raw(index).as_mut() }
    }

    /// Returns an iterator over references to the elements of this vec.
    #[must_use]
    #[inline]
    pub fn iter(&self) -> UnsizedIter<'_, T> {
        UnsizedIter {
            inner: self.inner.iter(),
        }
    }

    /// Returns an iterator over mutable references to the elements of this vec.
    #[must_use]
    #[inline]
    pub fn iter_mut(&mut self) -> UnsizedIterMut<'_, T> {
        UnsizedIterMut {
            inner: self.inner.iter_mut(),
        }
    }

    /// Coerces this Vec's elements to an unsized type.
    ///
    /// # Example
    ///
    /// ```
    /// use core::fmt::Debug;
    ///
    /// use unsized_vec::UnsizedVec;
    ///
    /// let sized: Vec<u32> = vec![3, 4, 5];
    /// let unsize: UnsizedVec<dyn Debug> = UnsizedVec::unsize(sized.into());
    /// dbg!(&unsize);
    /// ```
    #[must_use]
    #[inline]
    pub fn unsize<U>(self) -> UnsizedVec<U>
    where
        T: Sized + Unsize<U>,
        U: ?Sized,
    {
        UnsizedVec {
            inner: <U as UnsizedVecImpl>::Impl::from_sized(self.inner),
        }
    }

    #[must_use]
    #[inline]
    fn unused_byte_cap(&self) -> usize {
        // SAFETY: len <= cap
        unsafe { self.byte_capacity().unchecked_sub(self.byte_len()) }
    }
}

impl<T> Default for UnsizedVec<T>
where
    T: ?Sized,
{
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

/// The iterator returned by [`UnsizedVec::iter`].
#[repr(transparent)]
pub struct UnsizedIter<'a, T>
where
    T: ?Sized + 'a,
{
    inner: <<T as UnsizedVecImpl>::Impl as UnsizedVecProvider<T>>::Iter<'a>,
}

/// The iterator returned by [`UnsizedVec::iter_mut`].
#[repr(transparent)]
pub struct UnsizedIterMut<'a, T>
where
    T: ?Sized + 'a,
{
    inner: <<T as UnsizedVecImpl>::Impl as UnsizedVecProvider<T>>::IterMut<'a>,
}

impl<T> From<::alloc::vec::Vec<T>> for UnsizedVec<T> {
    #[inline]
    fn from(value: ::alloc::vec::Vec<T>) -> Self {
        UnsizedVec { inner: value }
    }
}

impl<T> From<UnsizedVec<T>> for ::alloc::vec::Vec<T> {
    #[inline]
    fn from(value: UnsizedVec<T>) -> Self {
        value.inner
    }
}

impl<T> Index<usize> for UnsizedVec<T>
where
    T: ?Sized,
{
    type Output = T;

    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        self.get(index).expect("index out of range")
    }
}

impl<T> IndexMut<usize> for UnsizedVec<T>
where
    T: ?Sized,
{
    #[inline]
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        self.get_mut(index).expect("index out of range")
    }
}

impl<'a, T> From<core::slice::Iter<'a, T>> for UnsizedIter<'a, T>
where
    T: 'a,
{
    #[inline]
    fn from(value: core::slice::Iter<'a, T>) -> Self {
        UnsizedIter { inner: value }
    }
}

impl<'a, T> From<UnsizedIter<'a, T>> for core::slice::Iter<'a, T>
where
    T: 'a,
{
    #[inline]
    fn from(value: UnsizedIter<'a, T>) -> Self {
        value.inner
    }
}

macro_rules! iter_ref {
    ($iter_ty:ident $($muta:ident)?) => {
        impl<'a, T> Iterator for $iter_ty<'a, T>
        where
            T: ?Sized + 'a,
        {
            type Item = &'a $($muta)? T;

            #[inline]
            fn next(&mut self) -> Option<Self::Item> {
                self.inner.next()
            }

            #[inline]
            fn size_hint(&self) -> (usize, Option<usize>) {
                self.inner.size_hint()
            }

            #[inline]
            fn count(self) -> usize {
                self.inner.count()
            }

            #[inline]
            fn nth(&mut self, n: usize) -> Option<Self::Item> {
                self.inner.nth(n)
            }

            #[inline]
            fn last(self) -> Option<Self::Item> {
                self.inner.last()
            }

            #[inline]
            fn for_each<F>(self, f: F)
            where
                F: FnMut(Self::Item),
            {
                self.inner.for_each(f);
            }

            #[inline]
            fn all<F>(&mut self, f: F) -> bool
            where
                F: FnMut(Self::Item) -> bool,
            {
                self.inner.all(f)
            }

            #[inline]
            fn any<F>(&mut self, f: F) -> bool
            where
                F: FnMut(Self::Item) -> bool,
            {
                self.inner.any(f)
            }

            #[inline]
            fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
            where
                P: FnMut(&Self::Item) -> bool,
            {
                self.inner.find(predicate)
            }

            #[inline]
            fn find_map<B, F>(&mut self, f: F) -> Option<B>
            where
                F: FnMut(Self::Item) -> Option<B>,
            {
                self.inner.find_map(f)
            }

            #[inline]
            fn position<P>(&mut self, predicate: P) -> Option<usize>
            where
                P: FnMut(Self::Item) -> bool,
            {
                self.inner.position(predicate)
            }
        }

        impl<'a, T> DoubleEndedIterator for $iter_ty<'a, T>
        where
            T: ?Sized + 'a,
        {
            #[inline]
            fn next_back(&mut self) -> Option<Self::Item> {
                self.inner.next_back()
            }

            #[inline]
            fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
                self.inner.nth_back(n)
            }
        }

        impl<'a, T> ExactSizeIterator for $iter_ty<'a, T>
        where
            T: ?Sized + 'a,
        {}
        impl<'a, T> FusedIterator for $iter_ty<'a, T>
        where
            T: ?Sized + 'a,
        {}
    }
}

iter_ref!(UnsizedIter);
iter_ref!(UnsizedIterMut mut);

impl<'a, T> IntoIterator for &'a UnsizedVec<T>
where
    T: ?Sized + 'a,
{
    type Item = &'a T;

    type IntoIter = UnsizedIter<'a, T>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut UnsizedVec<T>
where
    T: ?Sized + 'a,
{
    type Item = &'a mut T;

    type IntoIter = UnsizedIterMut<'a, T>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl<T, F> FromIterator<Emplacable<T, F>> for UnsizedVec<T>
where
    T: ?Sized,
    F: EmplacableFn<T>,
{
    #[inline]
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = Emplacable<T, F>>,
    {
        let mut vec = UnsizedVec::new();
        vec.extend(iter);
        vec
    }
}

impl<T, F> Extend<Emplacable<T, F>> for UnsizedVec<T>
where
    T: ?Sized,
    F: EmplacableFn<T>,
{
    #[inline]
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = Emplacable<T, F>>,
    {
        fn extend_inner<T: ?Sized, F: EmplacableFn<T>, I: Iterator<Item = Emplacable<T, F>>>(
            vec: &mut UnsizedVec<T>,
            iter: I,
        ) {
            vec.reserve_exact(iter.size_hint().0);
            for emplacable in iter {
                vec.push_with(emplacable);
            }
        }

        extend_inner(self, iter.into_iter());
    }
}

impl<T> Debug for UnsizedVec<T>
where
    T: ?Sized + Debug,
{
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

impl<T> Clone for UnsizedVec<T>
where
    T: ?Sized + Clone,
{
    #[inline]
    fn clone(&self) -> Self {
        let mut ret = UnsizedVec::with_capacity_bytes_align(
            self.capacity(),
            self.byte_capacity(),
            self.align(),
        );
        for elem in self {
            ret.push(elem.clone());
        }
        ret
    }
}

impl<T, U> PartialEq<UnsizedVec<U>> for UnsizedVec<T>
where
    T: ?Sized + PartialEq<U>,
    U: ?Sized,
{
    #[inline]
    fn eq(&self, other: &UnsizedVec<U>) -> bool {
        self.len() == other.len() && self.iter().zip(other).all(|(l, r)| l == r)
    }
}

impl<T> Eq for UnsizedVec<T> where T: ?Sized + Eq {}

impl<T, U> PartialOrd<UnsizedVec<U>> for UnsizedVec<T>
where
    T: ?Sized + PartialOrd<U>,
    U: ?Sized,
{
    fn partial_cmp(&self, other: &UnsizedVec<U>) -> Option<cmp::Ordering> {
        for (l, r) in self.iter().zip(other) {
            match l.partial_cmp(r) {
                Some(cmp::Ordering::Equal) => (),
                res => return res,
            }
        }
        self.len().partial_cmp(&other.len())
    }
}

impl<T> Ord for UnsizedVec<T>
where
    T: ?Sized + Ord,
{
    #[inline]
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        for (l, r) in self.iter().zip(other) {
            match l.cmp(r) {
                cmp::Ordering::Equal => (),
                res => return res,
            }
        }
        self.len().cmp(&other.len())
    }
}

impl<T> Hash for UnsizedVec<T>
where
    T: ?Sized + Hash,
{
    #[inline]
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        for elem in self {
            elem.hash(state);
        }
    }
}

#[cfg(feature = "serde")]
use serde::{ser::SerializeSeq, Serialize};

#[cfg(feature = "serde")]
impl<T> Serialize for UnsizedVec<T>
where
    T: ?Sized + Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut elem_serialize = serializer.serialize_seq(Some(self.len()))?;
        for elem in self {
            elem_serialize.serialize_element(elem)?;
        }
        elem_serialize.end()
    }
}

/// Impementation detail of `unsized_vec` macro.
#[doc(hidden)]
pub trait PushToUnsizedVec<U: ?Sized> {
    fn push_to_unsized_vec(self, vec: &mut UnsizedVec<U>);
}

impl<T: ?Sized> PushToUnsizedVec<T> for T {
    #[inline]
    fn push_to_unsized_vec(self, vec: &mut UnsizedVec<T>) {
        vec.push(self);
    }
}

impl<T: ?Sized, F: EmplacableFn<T>> PushToUnsizedVec<T> for Emplacable<T, F> {
    #[inline]
    fn push_to_unsized_vec(self, vec: &mut UnsizedVec<T>) {
        vec.push_with(self);
    }
}

/// Like the standard library's [`vec`] macro.
/// Accepts both raw unsized `T`s and
/// [`Emplacable<T,_>`]s.
///
/// However, this does not accept sized values implementing
/// [`Unsize<T>`]; you can use [`unsize_vec`] for that.
///
/// # Example
///
/// ```
/// #![feature(allocator_api, ptr_metadata, unsized_fn_params)]
///
/// use emplacable::unsize;
/// use unsized_vec::{UnsizedVec, unsized_vec};
///
/// let my_vec = unsized_vec![[23_u32, 17], [16, 34], [23, 47]];
///
/// let mut my_vec_unsized: UnsizedVec<[u32]> = my_vec.unsize();
///
/// let another_vec = unsized_vec![unsize!([42], ([u32; 1]) -> [u32]), my_vec_unsized.remove_into(2)];
/// ```
///
/// [`vec`]: macro@alloc::vec
#[macro_export]
macro_rules! unsized_vec {
    () => (
        $crate::UnsizedVec::new()
    );
    ($($x:expr),+ $(,)?) => (
        {
            let mut ret = $crate::UnsizedVec::new();
            $($crate::PushToUnsizedVec::push_to_unsized_vec($x, &mut ret);)+
            ret
        }
    );
}

/// Like [`unsized_vec`], but unsizes its arguments
/// using the [`Unsize`] trait.
///
/// Accepts sized values that can coerce to an unsized `T`.
/// If you have raw unsized `T`s or [`Emplacable<T,_>`]s,
/// use [`unsized_vec`] instead.
///
/// # Example
///
/// ```
/// use core::fmt::Debug;
///
/// use unsized_vec::{unsize_vec, UnsizedVec};
///
/// let my_vec: UnsizedVec<dyn Debug> = unsize_vec![1, "hello!", 97.5];
/// ```
#[macro_export]
macro_rules! unsize_vec {
    () => (
        $crate::UnsizedVec::new()
    );
    ($($x:expr),+ $(,)?) => (
        {
            let mut ret = $crate::UnsizedVec::new();
            $(ret.push_unsize($x);)+
            ret
        }
    );
}