hvec 0.5.1

A Vec-like structure that can store different types of different sizes contiguous with each other in memory.
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
//! In memory of Anna Harren, who coined the term
//! [turbofish](https://turbo.fish/) - which you'll see a lot of
//! if you use this crate.
//!
//! The main purpose of this crate is the `HarrenVec` type -
//! a [`Vec`]-like data structure that can store items
//! of different types and sizes from each other.
//!
//! Values of any type can be stored, and they are
//! stored contiguous in memory like a normal [`Vec`] would.
//!
//! The intended use case for this data structure is
//! efficiently packing structs with large optional fields,
//! while avoiding [`Box`]-ing those values.
//!
//! It supports values with a [`Drop`] implementation by default.
//!
//! However, if you include the `no_drop` feature, then
//! dropping the `HarrenVec` will _not_ call the destructors of
//! the contents. Instead you should use the
//! [`HarrenVec::into_iter`] method to ensure you are consuming
//! and dropping values correctly. If the values do not have
//! destructors, this is not necessary.
//!
//! # Examples
//! ```
//! use hvec::HarrenVec;
//!
//! struct SmallMessage {
//!     id: usize,
//!     has_extra: bool,
//! }
//!
//! struct LargeExtraField {
//!     data: [[f64; 4]; 4],
//! }
//!
//! let mut messages = HarrenVec::new();
//! messages.push(SmallMessage { id: 0, has_extra: false });
//! messages.push(SmallMessage { id: 1, has_extra: true });
//! messages.push(LargeExtraField { data: [[0.; 4]; 4] });
//! messages.push(SmallMessage { id: 2, has_extra: false });
//!
//! let mut iter = messages.into_iter();
//! while let Some(message) = iter.next::<SmallMessage>() {
//!     println!("id = {}", message.id);
//!     if message.has_extra {
//!         let extra = iter.next::<LargeExtraField>().unwrap();
//!         println!("extra data = {:?}", extra.data);
//!     }
//! }
//!
//! // Output:
//! // id = 0
//! // id = 1
//! // extra data = [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]]
//! // id = 2
//! ```

use std::any::TypeId;
use std::mem::MaybeUninit;

#[cfg(not(feature = "no_drop"))]
use std::collections::HashMap;

#[cfg(not(feature = "no_drop"))]
fn generic_drop<T>(p: *const ()) {
    let p = p as *const T;
    let _ = unsafe { p.read() };
}

#[cfg(not(feature = "no_drop"))]
fn drop_fn_ptr<T>() -> *const () {
    let f: fn(*const ()) = generic_drop::<T>;
    f as _
}

/// A [`Vec`]-like data structure that can store items
/// of different types and sizes from each other.
///
/// Values of any type can be stored, and they are
/// stored contiguous in memory like a normal [`Vec`] would.
///
/// The intended use case for this data structure is
/// efficiently packing structs with large optional fields,
/// while avoiding [`Box`]-ing those values.
///
/// It supports values with a [`Drop`] implementation by default.
///
/// However, if you include the `no_drop` feature, then
/// dropping the `HarrenVec` will _not_ call the destructors of
/// the contents. Instead you should use the
/// [`HarrenVec::into_iter`] method to ensure you are consuming
/// and dropping values correctly. If the values do not have
/// destructors, this is not necessary.
///
/// # Examples
/// ```
/// use hvec::HarrenVec;
///
/// struct SmallMessage {
///     id: usize,
///     has_extra: bool,
/// }
///
/// struct LargeExtraField {
///     data: [[f64; 4]; 4],
/// }
///
/// let mut messages = HarrenVec::new();
/// messages.push(SmallMessage { id: 0, has_extra: false });
/// messages.push(SmallMessage { id: 1, has_extra: true });
/// messages.push(LargeExtraField { data: [[0.; 4]; 4] });
/// messages.push(SmallMessage { id: 2, has_extra: false });
///
/// let mut iter = messages.into_iter();
/// while let Some(message) = iter.next::<SmallMessage>() {
///     println!("id = {}", message.id);
///     if message.has_extra {
///         let extra = iter.next::<LargeExtraField>().unwrap();
///         println!("extra data = {:?}", extra.data);
///     }
/// }
///
/// // Output:
/// // id = 0
/// // id = 1
/// // extra data = [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]]
/// // id = 2
/// ```
#[derive(Debug, Clone)]
pub struct HarrenVec {
    types: Vec<TypeId>,
    indices: Vec<usize>,
    backing: Vec<u8>,
    max_align: usize,

    #[cfg(not(feature = "no_drop"))]
    destructors: HashMap<TypeId, *const ()>,
}

impl Default for HarrenVec {
    fn default() -> Self {
        HarrenVec {
            types: Default::default(),
            indices: Default::default(),
            backing: Default::default(),
            max_align: 1,

            #[cfg(not(feature = "no_drop"))]
            destructors: HashMap::default(),
        }
    }
}

/// Type alias for [`HarrenVec`].
pub type HVec = HarrenVec;

impl HarrenVec {
    /// Constructs a new empty [`HarrenVec`].
    ///
    /// # Examples
    /// ```
    /// # use hvec::HarrenVec;
    /// let mut list = HarrenVec::new();
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Constructs a new empty [`HarrenVec`] with at least the
    /// specified capacity in items and bytes.
    ///
    /// The `HarrenVec` stores the types of the data separately
    /// from the data. In practice, it will re-allocate if
    /// either of these capacities are exceeded.
    ///
    /// # Examples
    /// ```
    /// # use hvec::HarrenVec;
    /// let mut list = HarrenVec::with_capacity(4, 64);
    /// assert!(list.item_capacity() >= 4);
    /// assert!(list.byte_capacity() >= 64);
    /// ```
    pub fn with_capacity(items: usize, bytes: usize) -> Self {
        HarrenVec {
            types: Vec::with_capacity(items),
            indices: Vec::with_capacity(items),
            backing: Vec::with_capacity(bytes),
            max_align: 1,

            #[cfg(not(feature = "no_drop"))]
            destructors: HashMap::default(),
        }
    }

    #[cfg(not(feature = "no_drop"))]
    fn register_destructor<T: 'static>(&mut self) {
        let type_id = TypeId::of::<T>();
        let drop_fn_p = drop_fn_ptr::<T>();
        self.destructors.entry(type_id).or_insert(drop_fn_p);
    }

    #[cfg(not(feature = "no_drop"))]
    fn run_destructor(&self, type_id: TypeId, ptr: *const ()) {
        let drop_fn_p = self.destructors[&type_id];
        let drop_fn: fn(*const ()) = unsafe { std::mem::transmute(drop_fn_p) };
        drop_fn(ptr);
    }

    /// Reserve capacity for at least `items` more items and
    /// `bytes` more bytes.
    pub fn reserve(&mut self, items: usize, bytes: usize) {
        self.types.reserve(items);
        self.indices.reserve(items);
        self.backing.reserve(bytes);
    }

    /// Reserve capacity for at least `items` more items and
    /// `bytes` more bytes. (Attempts to reserve the minimum
    /// possible, but this is not guaranteed.)
    pub fn reserve_exact(&mut self, items: usize, bytes: usize) {
        self.types.reserve_exact(items);
        self.indices.reserve_exact(items);
        self.backing.reserve_exact(bytes);
    }

    /// Reserve capacity for at least `items` more items and
    /// `bytes` more bytes.
    ///
    /// # Errors
    /// Returns an error if allocation fails.
    pub fn try_reserve(
        &mut self,
        items: usize,
        bytes: usize,
    ) -> Result<(), std::collections::TryReserveError> {
        self.types.try_reserve(items)?;
        self.indices.try_reserve(items)?;
        self.backing.try_reserve(bytes)?;
        Ok(())
    }

    /// Reserve capacity for at least `items` more items and
    /// `bytes` more bytes. (Attempts to reserve the minimum
    /// possible, but this is not guaranteed.)
    ///
    /// # Errors
    /// Returns an error if allocation fails.
    pub fn try_reserve_exact(
        &mut self,
        items: usize,
        bytes: usize,
    ) -> Result<(), std::collections::TryReserveError> {
        self.types.try_reserve_exact(items)?;
        self.indices.try_reserve_exact(items)?;
        self.backing.try_reserve_exact(bytes)?;
        Ok(())
    }

    fn pad_to_align(&mut self, align: usize) {
        let padding = (align - (self.backing.len() % align)) % align;
        for _ in 0..padding {
            self.backing.push(0);
        }
    }

    /// Move all elements from another `HarrenVec` into
    /// this one, leaving the `other` empty.
    ///
    /// # Examples
    /// ```
    /// # use hvec::hvec;
    /// let mut a = hvec![1, 2, 3];
    /// let mut b = hvec![4, 5, 6];
    /// a.append(&mut b);
    /// assert_eq!(a.len(), 6);
    /// assert_eq!(b.len(), 0);
    /// ```
    pub fn append(&mut self, other: &mut HarrenVec) {
        self.pad_to_align(other.max_align);

        let mut offset = 0;
        for i in 0..other.len() {
            let end = other
                .indices
                .get(i + 1)
                .copied()
                .unwrap_or(other.backing.len());

            self.indices.push(self.backing.len());
            self.backing.extend_from_slice(&other.backing[offset..end]);
            self.types.push(other.types[i]);

            offset = end;
        }

        #[cfg(not(feature = "no_drop"))]
        {
            for (type_id, drop_fn) in other.destructors.drain() {
                self.destructors.insert(type_id, drop_fn);
            }
        }

        other.clear_without_drop();
    }

    /// Clears the contents of the `HarrenVec`.
    ///
    /// (Note that if the `no_drop` feature is enabled, then
    /// this method will not call the destructors of any of its contents.
    ///
    /// If the contents do not have a [`Drop`] implementation, this is not a
    /// concern.)
    pub fn clear(&mut self) {
        #[cfg(not(feature = "no_drop"))]
        {
            for i in 0..self.len() {
                self.drop_item(i);
            }
        }
        self.clear_without_drop();
    }

    fn clear_without_drop(&mut self) {
        self.types.clear();
        self.indices.clear();
        self.backing.clear();
    }

    /// Truncates the contents of the `HarrenVec` to a set
    /// number of items, clearing the rest.
    ///
    /// (Note that if the `no_drop` feature is enabled, then
    /// this method will not call the destructors of any of its contents.
    ///
    /// If the contents do not have a [`Drop`] implementation, this is not a
    /// concern.)
    pub fn truncate(&mut self, items: usize) {
        #[cfg(not(feature = "no_drop"))]
        {
            let end = items + 1;
            if end < self.len() {
                for i in end..self.len() {
                    self.drop_item(i);
                }
            }
        }
        if let Some(last_index) = self.indices.get(items).copied() {
            self.types.truncate(items);
            self.indices.truncate(items);
            self.backing.truncate(last_index);
        }
    }

    /// Returns the type of the last item in the `HarrenVec`.
    ///
    /// # Examples
    /// ```
    /// # use hvec::hvec;
    /// use std::any::TypeId;
    ///
    /// let list = hvec![1_u8, 2_i32, 3_u64];
    /// assert_eq!(list.peek_type(), Some(TypeId::of::<u64>()));
    /// ```
    pub fn peek_type(&self) -> Option<TypeId> {
        self.types.last().copied()
    }

    /// Returns the type of the last item in the `HarrenVec`,
    /// as well as a pointer to the first byte of it.
    ///
    /// # Safety
    ///
    /// The pointer returned points to memory owned by the
    /// `HarrenVec`, and so it is only valid as long as it that
    /// data is unchanged.
    ///
    /// # Examples
    /// ```
    /// # use hvec::hvec;
    /// use std::any::TypeId;
    ///
    /// let list = hvec![1_u8, 2_i32, 3_u64];
    /// let (type_id, ptr) = list.peek_ptr().unwrap();
    ///
    /// assert_eq!(type_id, TypeId::of::<u64>());
    ///
    /// unsafe {
    ///     let ptr = ptr as *const u64;
    ///     assert_eq!(*ptr, 3_u64);
    /// }
    /// ```
    pub fn peek_ptr(&self) -> Option<(TypeId, *const u8)> {
        self.types.last().map(|&type_id| {
            let index = self.indices.last().unwrap();
            (type_id, &self.backing[*index] as *const u8)
        })
    }

    /// Returns the number of items in the `HarrenVec`.
    pub fn len(&self) -> usize {
        self.indices.len()
    }

    /// Returns the total number of bytes occupied by the
    /// contents of the `HarrenVec`.
    pub fn bytes_len(&self) -> usize {
        self.backing.len()
    }

    /// Returns `true` if there are no contents.
    pub fn is_empty(&self) -> bool {
        self.indices.is_empty()
    }

    /// Returns an Iterator-like structure for stepping through
    /// the contents of the `HarrenVec`.
    ///
    /// Note that because the type of each item can be
    /// different, and may not be known, this "iterator" cannot
    /// be used in `for` loops.
    ///
    /// # Examples
    ///
    /// The recommended way to use this method depends on how
    /// much you know about the contents. If there is a main
    /// type and you know in advance when that type will
    /// deviate, you can use a `while-let` loop:
    ///
    /// ```
    /// # use hvec::hvec;
    /// let list = hvec![1_usize, 2_usize, 999_usize, "Wow, big number!".to_string(), 3_usize];
    /// let mut iter = list.into_iter();
    ///
    /// let mut total = 0;
    /// while let Some(number) = iter.next::<usize>() {
    ///     if number > 100 {
    ///         let comment = iter.next::<String>().unwrap();
    ///         assert_eq!(comment, "Wow, big number!");
    ///     }
    ///     total += number;
    /// }
    /// assert_eq!(total, 1005);
    /// ```
    ///
    /// If you don't have a structure that allows you to know
    /// what type the next element is in advance, you can check
    /// the type of each item as you read it:
    ///
    /// ```
    /// # use hvec::hvec;
    /// use std::any::TypeId;
    ///
    /// let list = hvec![1_u8, 500_u16, 99999_u32];
    /// let mut iter = list.into_iter();
    ///
    /// let mut total: usize = 0;
    /// while let Some(type_id) = iter.peek_type() {
    ///     if type_id == TypeId::of::<u8>() {
    ///         total += iter.next::<u8>().unwrap() as usize;
    ///     } else if type_id == TypeId::of::<u16>() {
    ///         total += iter.next::<u16>().unwrap() as usize;
    ///     } else if type_id == TypeId::of::<u32>() {
    ///         total += iter.next::<u32>().unwrap() as usize;
    ///     }
    /// }
    /// assert_eq!(total, 100500);
    /// ```
    #[allow(clippy::should_implement_trait)]
    pub fn into_iter(self) -> HarrenIter {
        HarrenIter {
            cursor: 0,
            vec: self,
        }
    }

    /// Returns an Iterator-like structure for stepping through immutable references to
    /// the contents of the `HarrenVec`.
    ///
    /// See [`HarrenVec::into_iter`] for examples.
    pub fn iter(&self) -> HarrenRefIter<'_> {
        HarrenRefIter {
            cursor: 0,
            vec: self,
        }
    }

    /// Returns an Iterator-like structure for stepping through mutable references to
    /// the contents of the `HarrenVec`.
    ///
    /// See [`HarrenVec::into_iter`] for examples.
    pub fn iter_mut(&mut self) -> HarrenMutIter<'_> {
        HarrenMutIter {
            cursor: 0,
            vec: self,
        }
    }

    /// Add an element of any type to the `HarrenVec`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use hvec::HarrenVec;
    /// let mut list = HarrenVec::new();
    /// list.push(1_u8);
    /// list.push("Hello, world!".to_string());
    /// assert_eq!(list.len(), 2);
    /// ```
    pub fn push<T: 'static>(&mut self, t: T) {
        let type_id = TypeId::of::<T>();
        let ptr = &t as *const T as *const u8;
        let size = std::mem::size_of::<T>();
        let bytes = unsafe { std::slice::from_raw_parts(ptr, size) };

        let align = std::mem::align_of::<T>();
        self.max_align = std::cmp::max(self.max_align, align);
        self.pad_to_align(align);

        self.indices.push(self.backing.len());
        self.backing.extend_from_slice(bytes);
        self.types.push(type_id);

        #[cfg(not(feature = "no_drop"))]
        self.register_destructor::<T>();

        std::mem::forget(t);
    }

    /// Pop the last element from the `HarrenVec`.
    ///
    /// # Panics
    ///
    /// (This method can only panic if the `type_assertions` feature flag is enabled.)
    ///
    /// This method panics if the actual element is not an
    /// element of the specified type `T`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use hvec::hvec;
    /// let mut list = hvec!["Hello".to_string()];
    /// assert_eq!(list.pop::<String>().unwrap(), "Hello".to_string());
    /// ```
    pub fn pop<T: 'static>(&mut self) -> Option<T> {
        self.types.pop().map(|type_id| {
            let index = self.indices.pop().unwrap();

            #[cfg(feature = "type_assertions")]
            assert_eq!(TypeId::of::<T>(), type_id);

            let result = unsafe { self.take_at::<T>(index) };
            self.backing.truncate(index);
            result
        })
    }

    /// See [`Self::pop`]. Does not panic if the type doesn't match.
    ///
    /// # Safety
    ///
    /// This method is only safe if the bytes can be safely interpreted as a struct of type `T`.
    pub unsafe fn pop_unchecked<T: 'static>(&mut self) -> Option<T> {
        self.types.pop().map(|_| {
            let index = self.indices.pop().unwrap();
            let result = unsafe { self.take_at::<T>(index) };
            self.backing.truncate(index);
            result
        })
    }

    unsafe fn ref_at<T>(&self, offset: usize) -> &T {
        unsafe { std::mem::transmute(&self.backing[offset]) }
    }

    unsafe fn mut_ref_at<T>(&mut self, offset: usize) -> &mut T {
        unsafe { std::mem::transmute(&mut self.backing[offset]) }
    }

    unsafe fn take_at<T>(&self, offset: usize) -> T {
        let mut result: MaybeUninit<T> = MaybeUninit::uninit();

        let ptr = &self.backing[offset] as *const u8 as *const T;
        let dest = result.as_mut_ptr();
        unsafe {
            dest.copy_from(ptr, 1);
            result.assume_init()
        }
    }

    #[cfg(not(feature = "no_drop"))]
    fn drop_item(&mut self, index: usize) {
        let type_id = self.types[index];
        let offset = self.indices[index];
        let ptr = &self.backing[offset] as *const u8 as *const ();
        self.run_destructor(type_id, ptr);
    }

    /// Returns true if this `HarrenVec` contains the element.
    ///
    /// # Examples
    /// ```
    /// # use hvec::hvec;
    /// let list = hvec![1_usize, "Hello".to_string()];
    /// assert!(list.contains::<usize>(&1));
    /// assert!(list.contains::<String>(&"Hello".to_string()));
    /// assert!(!list.contains::<isize>(&1));
    /// assert!(!list.contains::<String>(&"???".to_string()));
    /// ```
    pub fn contains<T: PartialEq<T> + 'static>(&self, x: &T) -> bool {
        for (item_index, type_id) in self.types.iter().enumerate() {
            if *type_id == TypeId::of::<T>()
                && unsafe { self.ref_at::<T>(self.indices[item_index]) == x }
            {
                return true;
            }
        }
        false
    }

    /// Return a reference to the first item of the `HarrenVec`.
    ///
    /// # Panics
    ///
    /// (This method can only panic if the `type_assertions` feature flag is enabled.)
    ///
    /// This method panics if the item is not of the specified
    /// type `T`.
    pub fn first<T: 'static>(&self) -> Option<&T> {
        #[cfg(feature = "type_assertions")]
        assert_eq!(Some(&TypeId::of::<T>()), self.types.first());

        unsafe { self.first_unchecked::<T>() }
    }

    /// See [`Self::first`]. Does not panic if the type doesn't match.
    ///
    /// # Safety
    ///
    /// This method is only safe if the bytes can be safely interpreted as a struct of type `T`.
    pub unsafe fn first_unchecked<T: 'static>(&self) -> Option<&T> {
        self.indices
            .first()
            .copied()
            .map(|i| unsafe { self.ref_at::<T>(i) })
    }

    /// Return a mutable reference to the first item of
    /// the `HarrenVec`.
    ///
    /// # Panics
    ///
    /// (This method can only panic if the `type_assertions` feature flag is enabled.)
    ///
    /// This method panics if the item is not of the specified
    /// type `T`.
    pub fn first_mut<T: 'static>(&mut self) -> Option<&mut T> {
        #[cfg(feature = "type_assertions")]
        assert_eq!(Some(&TypeId::of::<T>()), self.types.first());

        unsafe { self.first_mut_unchecked() }
    }

    /// See [`Self::first_mut`]. Does not panic if the type doesn't match.
    ///
    /// # Safety
    ///
    /// This method is only safe if the bytes can be safely interpreted as a struct of type `T`.
    pub unsafe fn first_mut_unchecked<T: 'static>(&mut self) -> Option<&mut T> {
        self.indices
            .first()
            .copied()
            .map(|i| unsafe { self.mut_ref_at::<T>(i) })
    }

    /// Return a reference to the last item of the `HarrenVec`.
    ///
    /// # Panics
    ///
    /// (This method can only panic if the `type_assertions` feature flag is enabled.)
    ///
    /// This method panics if the item is not of the specified
    /// type `T`.
    pub fn last<T: 'static>(&self) -> Option<&T> {
        #[cfg(feature = "type_assertions")]
        assert_eq!(Some(&TypeId::of::<T>()), self.types.last());

        unsafe { self.last_unchecked() }
    }

    /// See [`Self::last`]. Does not panic if the type doesn't match.
    ///
    /// # Safety
    ///
    /// This method is only safe if the bytes can be safely interpreted as a struct of type `T`.
    pub unsafe fn last_unchecked<T: 'static>(&self) -> Option<&T> {
        self.indices
            .last()
            .copied()
            .map(|i| unsafe { self.ref_at::<T>(i) })
    }

    /// Return a mutable reference to the last item of
    /// the `HarrenVec`.
    ///
    /// # Panics
    ///
    /// (This method can only panic if the `type_assertions` feature flag is enabled.)
    ///
    /// This method panics if the item is not of the specified
    /// type `T`.
    pub fn last_mut<T: 'static>(&mut self) -> Option<&mut T> {
        #[cfg(feature = "type_assertions")]
        assert_eq!(Some(&TypeId::of::<T>()), self.types.last());

        unsafe { self.last_mut_unchecked() }
    }

    /// See [`Self::last_mut`]. Does not panic if the type doesn't match.
    ///
    /// # Safety
    ///
    /// This method is only safe if the bytes can be safely interpreted as a struct of type `T`.
    pub unsafe fn last_mut_unchecked<T: 'static>(&mut self) -> Option<&mut T> {
        self.indices
            .last()
            .copied()
            .map(|i| unsafe { self.mut_ref_at::<T>(i) })
    }

    /// Alias of the [`Self::last`] method.
    ///
    /// # Safety
    ///
    /// This method is only safe if the bytes can be safely interpreted as a struct of type `T`.
    pub fn peek<T: 'static>(&self) -> Option<&T> {
        self.last()
    }

    /// Alias of the [`Self::last_unchecked`] method.
    ///
    /// # Safety
    ///
    /// This method is only safe if the bytes can be safely interpreted as a struct of type `T`.
    pub unsafe fn peek_unchecked<T: 'static>(&self) -> Option<&T> {
        unsafe { self.last_unchecked() }
    }

    /// Alias of the [`Self::last_mut`] method.
    ///
    /// # Safety
    ///
    /// This method is only safe if the bytes can be safely interpreted as a struct of type `T`.
    pub fn peek_mut<T: 'static>(&mut self) -> Option<&mut T> {
        self.last_mut()
    }

    /// Alias of the [`Self::last_mut_unchecked`] method.
    ///
    /// # Safety
    ///
    /// This method is only safe if the bytes can be safely interpreted as a struct of type `T`.
    pub unsafe fn peek_mut_unchecked<T: 'static>(&mut self) -> Option<&mut T> {
        unsafe { self.last_mut_unchecked() }
    }

    /// Return a reference to the item of the `HarrenVec` at
    /// the given index.
    ///
    /// # Panics
    ///
    /// (This method can only panic if the `type_assertions` feature flag is enabled.)
    ///
    /// This method panics if the item is not of the specified
    /// type `T`.
    pub fn get<T: 'static>(&self, index: usize) -> Option<&T> {
        #[cfg(feature = "type_assertions")]
        assert_eq!(Some(&TypeId::of::<T>()), self.types.get(index));

        unsafe { self.get_unchecked(index) }
    }

    /// See [`Self::get`]. Does not panic if the type doesn't match.
    ///
    /// # Safety
    ///
    /// This method is only safe if the bytes can be safely interpreted as a struct of type `T`.
    pub unsafe fn get_unchecked<T: 'static>(&self, index: usize) -> Option<&T> {
        self.indices
            .get(index)
            .copied()
            .map(|i| unsafe { self.ref_at::<T>(i) })
    }

    /// Return a mutable reference to the item of
    /// the `HarrenVec` at the given index.
    ///
    /// # Panics
    ///
    /// (This method can only panic if the `type_assertions` feature flag is enabled.)
    ///
    /// This method panics if the item is not of the specified
    /// type `T`.
    pub fn get_mut<T: 'static>(&mut self, index: usize) -> Option<&mut T> {
        #[cfg(feature = "type_assertions")]
        assert_eq!(Some(&TypeId::of::<T>()), self.types.get(index));

        unsafe { self.get_mut_unchecked(index) }
    }

    /// See [`Self::get_mut`]. Does not panic if the type doesn't match.
    ///
    /// # Safety
    ///
    /// This method is only safe if the bytes can be safely interpreted as a struct of type `T`.
    pub unsafe fn get_mut_unchecked<T: 'static>(&mut self, index: usize) -> Option<&mut T> {
        self.indices
            .get(index)
            .copied()
            .map(|i| unsafe { self.mut_ref_at::<T>(i) })
    }

    /// Returns the total number of elements this `HarrenVec`
    /// can store without reallocating.
    ///
    /// Note that this is separate from its capacity in bytes.
    /// Allocation will occur if either capacity is exceeded.
    pub fn item_capacity(&self) -> usize {
        std::cmp::min(self.types.capacity(), self.indices.capacity())
    }

    /// Returns the total number of bytes this `HarrenVec`
    /// can store without reallocating.
    ///
    /// Note that this is separate from its capacity in items.
    /// Allocation will occur if either capacity is exceeded.
    pub fn byte_capacity(&self) -> usize {
        self.backing.capacity()
    }

    /// Returns true if `other` contains the exact same types
    /// and bytes as this `HarrenVec`. Not that this does _not_
    /// call the actual [`PartialEq`] implementation for the
    /// stored values, so the result may not be intuitive for
    /// more complex or heap-allocated types.
    ///
    /// # Examples
    ///
    /// ```
    /// # use hvec::hvec;
    /// let list_a = hvec![1_u8, 2_isize];
    /// let list_b = hvec![1_u8, 2_isize];
    ///
    /// let list_c = hvec![1_u8, "Hello".to_string()];
    /// let list_d = hvec![1_u8, "Hello".to_string()];
    ///
    /// // Numbers can be correctly compared as bytes
    /// assert!(list_a.bytes_eq(&list_b));
    ///
    /// // Strings contain pointers so identical strings may differ in bytes
    /// assert!(!list_c.bytes_eq(&list_d));
    /// ```
    pub fn bytes_eq(&self, other: &HarrenVec) -> bool {
        self.types == other.types && self.indices == other.indices && self.backing == other.backing
    }
}

#[cfg(not(feature = "no_drop"))]
impl Drop for HarrenVec {
    fn drop(&mut self) {
        self.clear();
    }
}

/// An [`Iterator`]-like structure for taking
/// ownership of the elements of a [`HarrenVec`].
///
/// (Note that if the `no_drop` feature is enabled, then
/// this iterator will not call the destructors of any of its contents
/// when dropped. Instead you should use the `next` method to ensure
/// you are consuming and dropping each value.
///
/// If the contents do not have a [`Drop`] implementation, this is not a
/// concern.)
#[derive(Debug)]
pub struct HarrenIter {
    cursor: usize,
    vec: HarrenVec,
}

impl HarrenIter {
    /// Checks the type of the next item in the iterator
    /// without actually advancing it.
    ///
    /// # Examples
    /// ```
    /// use std::any::TypeId;
    /// use hvec::hvec;
    ///
    /// let list = hvec![1_u64, 2_i32];
    /// let mut iter = list.into_iter();
    /// assert_eq!(iter.peek_type(), Some(TypeId::of::<u64>()));
    /// ```
    pub fn peek_type(&self) -> Option<TypeId> {
        self.vec.types.get(self.cursor).copied()
    }

    /// Advances the iterator and returns the next item if
    /// one exists - or else None.
    ///
    /// # Panics
    ///
    /// (This method can only panic if the `type_assertions` feature flag is enabled.)
    ///
    /// This method will panic if the actual type of the item
    /// differs from the `T` that this method was called with.
    ///
    /// # Examples
    /// ```
    /// use hvec::hvec;
    ///
    /// let list = hvec![1_u64, 2_i32];
    /// let mut iter = list.into_iter();
    /// assert_eq!(iter.next::<u64>(), Some(1_u64));
    /// assert_eq!(iter.next::<i32>(), Some(2_i32));
    /// assert_eq!(iter.next::<()>(), None);
    /// ```
    #[allow(clippy::should_implement_trait)]
    pub fn next<T: 'static>(&mut self) -> Option<T> {
        // TODO: Messy checking this twice
        if self.is_empty() {
            return None;
        }

        #[cfg(feature = "type_assertions")]
        {
            let type_id = self.vec.types[self.cursor];
            assert_eq!(type_id, TypeId::of::<T>());
        }

        unsafe { self.next_unchecked() }
    }

    /// See [`Self::next`]. Does not panic if the type doesn't match.
    ///
    /// # Safety
    ///
    /// This method is only safe if the bytes can be safely interpreted as a struct of type `T`.
    pub unsafe fn next_unchecked<T: 'static>(&mut self) -> Option<T> {
        if self.is_empty() {
            return None;
        }

        let index = self.vec.indices[self.cursor];
        let result = unsafe { self.vec.take_at::<T>(index) };
        self.cursor += 1;
        Some(result)
    }

    /// Returns true if there are no more elements in the
    /// iterator.
    pub fn is_empty(&self) -> bool {
        self.cursor >= self.vec.len()
    }
}

#[cfg(not(feature = "no_drop"))]
impl Drop for HarrenIter {
    fn drop(&mut self) {
        if !self.is_empty() {
            for i in self.cursor..self.vec.len() {
                self.vec.drop_item(i);
            }
        }
        self.vec.clear_without_drop();
    }
}

/// An [`Iterator`]-like structure for immutably borrowing
/// the elements of a [`HarrenVec`].
#[derive(Debug)]
pub struct HarrenRefIter<'a> {
    cursor: usize,
    vec: &'a HarrenVec,
}

impl HarrenRefIter<'_> {
    /// Checks the type of the next item in the iterator
    /// without actually advancing it.
    ///
    /// # Examples
    /// ```
    /// use std::any::TypeId;
    /// use hvec::hvec;
    ///
    /// let list = hvec![1_u64, 2_i32];
    /// let mut iter = list.into_iter();
    /// assert_eq!(iter.peek_type(), Some(TypeId::of::<u64>()));
    /// ```
    pub fn peek_type(&self) -> Option<TypeId> {
        self.vec.types.get(self.cursor).copied()
    }

    /// Advances the iterator and returns the next item if
    /// one exists - or else None.
    ///
    /// # Panics
    ///
    /// (This method can only panic if the `type_assertions` feature flag is enabled.)
    ///
    /// This method will panic if the actual type of the item
    /// differs from the `T` that this method was called with.
    ///
    /// # Examples
    /// ```
    /// use hvec::hvec;
    ///
    /// let list = hvec![1_u64, 2_i32];
    /// let mut iter = list.into_iter();
    /// assert_eq!(iter.next::<u64>(), Some(1_u64));
    /// assert_eq!(iter.next::<i32>(), Some(2_i32));
    /// assert_eq!(iter.next::<()>(), None);
    /// ```
    #[allow(clippy::should_implement_trait)]
    pub fn next<T: 'static>(&mut self) -> Option<&T> {
        // TODO: Messy checking this twice
        if self.is_empty() {
            return None;
        }

        #[cfg(feature = "type_assertions")]
        {
            let type_id = self.vec.types[self.cursor];
            assert_eq!(type_id, TypeId::of::<T>());
        }

        unsafe { self.next_unchecked() }
    }

    /// See [`Self::next`]. Does not panic if the type doesn't match.
    ///
    /// # Safety
    ///
    /// This method is only safe if the bytes can be safely interpreted as a struct of type `T`.
    pub unsafe fn next_unchecked<T: 'static>(&mut self) -> Option<&T> {
        if self.is_empty() {
            return None;
        }

        let index = self.vec.indices[self.cursor];
        let result = unsafe { self.vec.ref_at::<T>(index) };
        self.cursor += 1;
        Some(result)
    }

    /// Returns true if there are no more elements in the
    /// iterator.
    pub fn is_empty(&self) -> bool {
        self.cursor >= self.vec.len()
    }
}

/// An [`Iterator`]-like structure for mutably borrowing
/// the elements of a [`HarrenVec`].
#[derive(Debug)]
pub struct HarrenMutIter<'a> {
    cursor: usize,
    vec: &'a mut HarrenVec,
}

impl HarrenMutIter<'_> {
    /// Checks the type of the next item in the iterator
    /// without actually advancing it.
    ///
    /// # Examples
    /// ```
    /// use std::any::TypeId;
    /// use hvec::hvec;
    ///
    /// let list = hvec![1_u64, 2_i32];
    /// let mut iter = list.into_iter();
    /// assert_eq!(iter.peek_type(), Some(TypeId::of::<u64>()));
    /// ```
    pub fn peek_type(&self) -> Option<TypeId> {
        self.vec.types.get(self.cursor).copied()
    }

    /// Advances the iterator and returns the next item if
    /// one exists - or else None.
    ///
    /// # Panics
    ///
    /// (This method can only panic if the `type_assertions` feature flag is enabled.)
    ///
    /// This method will panic if the actual type of the item
    /// differs from the `T` that this method was called with.
    ///
    /// # Examples
    /// ```
    /// use hvec::hvec;
    ///
    /// let list = hvec![1_u64, 2_i32];
    /// let mut iter = list.into_iter();
    /// assert_eq!(iter.next::<u64>(), Some(1_u64));
    /// assert_eq!(iter.next::<i32>(), Some(2_i32));
    /// assert_eq!(iter.next::<()>(), None);
    /// ```
    #[allow(clippy::should_implement_trait)]
    pub fn next<T: 'static>(&mut self) -> Option<&mut T> {
        // TODO: Messy checking this twice
        if self.is_empty() {
            return None;
        }

        #[cfg(feature = "type_assertions")]
        {
            let type_id = self.vec.types[self.cursor];
            assert_eq!(type_id, TypeId::of::<T>());
        }

        unsafe { self.next_unchecked() }
    }

    /// See [`Self::next`]. Does not panic if the type doesn't match.
    ///
    /// # Safety
    ///
    /// This method is only safe if the bytes can be safely interpreted as a struct of type `T`.
    pub unsafe fn next_unchecked<T: 'static>(&mut self) -> Option<&mut T> {
        if self.is_empty() {
            return None;
        }

        let index = self.vec.indices[self.cursor];
        let result = unsafe { self.vec.mut_ref_at::<T>(index) };
        self.cursor += 1;
        Some(result)
    }

    /// Returns true if there are no more elements in the
    /// iterator.
    pub fn is_empty(&self) -> bool {
        self.cursor >= self.vec.len()
    }
}

/// Creates a [`HarrenVec`] containing the arguments.
///
/// # Examples
/// ```
/// use hvec::hvec;
///
/// let list_a = hvec![];
/// let list_b = hvec![1_u64; 2];
/// let list_c = hvec![1_u64, 2_i64, 3_u8];
///
/// assert!(list_a.len() == 0);
/// assert!(list_b.len() == 2);
/// assert!(list_c.len() == 3);
/// ```
#[macro_export]
macro_rules! hvec {
    () => { $crate::HarrenVec::new() };
    ($elem : expr ; $n : expr) => {{
        let mut vec = $crate::HarrenVec::new();
        for _ in 0..($n) {
            vec.push(($elem).clone());
        }
        vec
    }};
    ($($x : expr), + $(,) ?) => {{
        let mut vec = $crate::HarrenVec::new();
        $(vec.push($x);)*
        vec
    }};
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn construction_and_equality() {
        let macro_created = hvec![1_usize, 2_u8, [100_u32; 5]];
        let mut default = HVec::default();
        let mut with_cap = HVec::with_capacity(5, 64);

        {
            default.push(1_usize);
            default.push(2_u8);
            default.push([100_u32; 5]);
            with_cap.push(1_usize);
            with_cap.push(2_u8);
            with_cap.push([100_u32; 5]);
        }

        assert!(macro_created.bytes_eq(&default));
        assert!(default.bytes_eq(&with_cap));
        assert!(with_cap.bytes_eq(&macro_created));
    }

    #[test]
    fn macro_forms() {
        assert!(hvec![].bytes_eq(&HVec::default()));
        assert!(hvec![1_u8, 1_u8].bytes_eq(&hvec![1_u8; 2]));
    }

    #[test]
    fn bytes_eq_fails_for_strings() {
        let a = hvec!["Hello".to_string()];
        let b = hvec!["Hello".to_string()];
        assert!(!a.bytes_eq(&b));
    }

    #[test]
    fn capacity() {
        let mut list = HVec::with_capacity(2, 16);
        assert!(list.item_capacity() >= 2);
        assert!(list.byte_capacity() >= 16);

        list.push(1_u64);
        list.push(2_i64);
        list.push(3_u128);

        assert!(list.item_capacity() >= 3);
        assert!(list.byte_capacity() >= 32);
    }

    #[test]
    fn new_reserve() {
        let mut list = HVec::new();
        assert!(list.item_capacity() == 0);
        assert!(list.byte_capacity() == 0);

        list.reserve(4, 64);
        assert!(list.item_capacity() >= 4);
        assert!(list.byte_capacity() >= 64);
    }

    #[test]
    fn clear_truncate() {
        let mut list = hvec![1_u8, 2_i16, 3_u32, 4_i64];
        assert!(!list.is_empty());
        assert_eq!(list.len(), 4);

        list.truncate(2);
        assert_eq!(list.len(), 2);
        list.clear();
        assert_eq!(list.len(), 0);

        assert!(list.is_empty());
    }

    #[test]
    fn peek() {
        let list_a = hvec![11_u8, 22_i16, 33_u32];
        let list_b = hvec![11_u8, 22_i16];
        let list_c = hvec![11_u8];
        let list_d = hvec![];

        assert_eq!(list_a.peek_type(), Some(TypeId::of::<u32>()));
        assert_eq!(list_b.peek_type(), Some(TypeId::of::<i16>()));
        assert_eq!(list_c.peek_type(), Some(TypeId::of::<u8>()));
        assert_eq!(list_d.peek_type(), None);

        let (_, p_a) = list_a.peek_ptr().unwrap();
        let (_, p_b) = list_b.peek_ptr().unwrap();
        let (_, p_c) = list_c.peek_ptr().unwrap();

        unsafe {
            assert_eq!(*(p_a as *const u32), 33);
            assert_eq!(*(p_b as *const i16), 22);
            assert_eq!(*(p_c as *const u8), 11);
        }
    }

    #[test]
    fn append() {
        let mut a = hvec![1_u32, 2_u64, 3_u128];
        let mut b = hvec![4_i32, 5_i64, 6_i128];
        a.append(&mut b);

        assert!(a.len() == 6);
        assert!(b.is_empty());

        let mut iter = a.into_iter();
        assert_eq!(iter.next::<u32>(), Some(1_u32));
        assert_eq!(iter.next::<u64>(), Some(2_u64));
        assert_eq!(iter.next::<u128>(), Some(3_u128));
        assert_eq!(iter.next::<i32>(), Some(4_i32));
        assert_eq!(iter.next::<i64>(), Some(5_i64));
        assert_eq!(iter.next::<i128>(), Some(6_i128));
        assert_eq!(iter.next::<()>(), None);
    }

    #[test]
    fn push_peek_pop() {
        let mut list = hvec![];
        list.push(1_usize);
        list.push(2_u8);
        list.push("Hello".to_string());

        assert_eq!(list.peek::<String>().unwrap(), "Hello");
        assert_eq!(list.pop::<String>().unwrap(), "Hello");
        assert_eq!(list.peek::<u8>(), Some(&2));
        assert_eq!(list.pop::<u8>(), Some(2));
        assert_eq!(list.peek::<usize>(), Some(&1));
        assert_eq!(list.pop::<usize>(), Some(1));
    }

    #[test]
    fn first_last_get() {
        let a = hvec![1_u8, 2_isize, "3".to_string()];
        assert_eq!(a.first::<u8>(), Some(&1));
        assert_eq!(a.get::<isize>(1), Some(&2));
        assert_eq!(a.last::<String>(), Some(&"3".to_string()));
    }

    #[test]
    fn first_last_get_mut() {
        let mut a = hvec![1_u8, 2_isize, "3".to_string()];

        let target = a.first_mut::<u8>().unwrap();
        *target = 10;

        let target = a.get_mut::<isize>(1).unwrap();
        *target = 20;

        let target = a.last_mut::<String>().unwrap();
        *target = "30".to_string();

        assert_eq!(a.first::<u8>(), Some(&10));
        assert_eq!(a.get::<isize>(1), Some(&20));
        assert_eq!(a.last::<String>(), Some(&"30".to_string()));
    }

    #[test]
    fn contains() {
        let a = hvec![1_u8, 2_isize, "3".to_string()];
        assert!(a.contains::<u8>(&1));
        assert!(a.contains::<isize>(&2));
        assert!(a.contains::<String>(&"3".to_string()));
    }

    #[test]
    #[should_panic]
    fn wrong_first_panics() {
        let a = hvec![1_usize];
        a.first::<u8>();
    }

    #[test]
    #[should_panic]
    fn wrong_last_panics() {
        let a = hvec![1_usize];
        a.last::<u8>();
    }

    #[test]
    #[should_panic]
    fn wrong_get_panics() {
        let a = hvec![1_usize];
        a.get::<u8>(0);
    }

    #[test]
    #[should_panic]
    fn wrong_pop_panics() {
        let mut a = hvec![1_usize];
        a.pop::<u8>();
    }

    #[test]
    fn into_iter() {
        let mut list = HarrenVec::new();
        list.push(1_usize);
        list.push(2_u8);
        list.push("Hello".to_string());

        let mut items = list.into_iter();
        assert_eq!(items.peek_type(), Some(TypeId::of::<usize>()));
        assert_eq!(items.next::<usize>(), Some(1));
        assert_eq!(items.next::<u8>(), Some(2));
        assert_eq!(items.next::<String>(), Some("Hello".to_string()));
    }

    #[test]
    fn iter() {
        let mut list = HarrenVec::new();
        list.push(1_usize);
        list.push(2_u8);
        list.push("Hello".to_string());

        let mut items = list.iter();
        assert_eq!(items.peek_type(), Some(TypeId::of::<usize>()));
        assert_eq!(items.next::<usize>(), Some(&1));
        assert_eq!(items.next::<u8>(), Some(&2));
        assert_eq!(items.next::<String>(), Some(&"Hello".to_string()));
    }

    #[test]
    fn iter_mut() {
        let mut list = HarrenVec::new();
        list.push(1_usize);
        list.push(2_u8);
        list.push("Hello".to_string());

        let mut items = list.iter_mut();
        assert_eq!(items.peek_type(), Some(TypeId::of::<usize>()));
        assert_eq!(items.next::<usize>(), Some(&mut 1));
        assert_eq!(items.next::<u8>(), Some(&mut 2));
        assert_eq!(items.next::<String>(), Some(&mut "Hello".to_string()));
    }

    #[test]
    fn extra_props() {
        struct Entry {
            id: usize,
            extra: bool,
        }

        struct Extra {
            info: String,
        }

        let mut log = String::new();

        let mut list = HarrenVec::new();
        list.push(Entry {
            id: 0,
            extra: false,
        });
        list.push(Entry { id: 1, extra: true });
        list.push(Extra {
            info: "Hello".into(),
        });
        list.push(Entry {
            id: 2,
            extra: false,
        });

        let mut items = list.into_iter();
        while let Some(entry) = items.next::<Entry>() {
            log.push_str(&entry.id.to_string());
            if entry.extra {
                let extra = items.next::<Extra>().unwrap();
                log.push_str(&extra.info);
            }
        }

        assert_eq!(log, "01Hello2");
    }
}

#[cfg(all(test, feature = "no_drop"))]
mod dropless_tests {
    use super::*;

    use std::sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    };

    struct DropCounter(Arc<AtomicUsize>);

    impl Drop for DropCounter {
        fn drop(&mut self) {
            self.0.fetch_add(1, Ordering::Relaxed);
        }
    }

    #[test]
    fn contents_not_dropped_when_vec_dropped() {
        let count = Arc::new(AtomicUsize::new(0));
        let counter = DropCounter(Arc::clone(&count));

        {
            let mut list = HarrenVec::new();
            list.push(counter);
        }

        assert_eq!(count.load(Ordering::Relaxed), 0);
    }
}

#[cfg(all(test, not(feature = "no_drop")))]
mod droptests {
    use super::*;

    use std::sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    };

    struct DropCounter(Arc<AtomicUsize>);

    impl Drop for DropCounter {
        fn drop(&mut self) {
            self.0.fetch_add(1, Ordering::Relaxed);
        }
    }

    #[test]
    fn contents_dropped_when_vec_dropped() {
        let count = Arc::new(AtomicUsize::new(0));
        let counter = DropCounter(Arc::clone(&count));

        {
            let mut list = HarrenVec::new();
            list.push(counter);
        }

        assert_eq!(count.load(Ordering::Relaxed), 1);
    }
}