noalloc-vec-rs 0.1.2

A no-allocation vector implementation for environment without memory allocation.
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
use core::mem::ManuallyDrop;
use core::mem::MaybeUninit;
use core::mem::size_of;
use core::ops::Deref;
use core::ops::DerefMut;
use core::ptr;
use core::slice;

use crate::assert_lte;

/// A fixed-size vector with a maximum length specified at compile time.
#[derive(Debug)]
pub struct Vec<T, const MAX_LENGTH: usize> {
    array: [MaybeUninit<T>; MAX_LENGTH],
    length: usize,
}

/// An iterator over the elements of a `Vec`.
pub struct IntoIter<T, const MAX_LENGTH: usize> {
    vec: Vec<T, MAX_LENGTH>,
    next: usize,
}

impl<T, const MAX_LENGTH: usize> IntoIter<T, MAX_LENGTH> {
    /// Creates a new `IntoIter` from a `Vec`.
    ///
    /// # Arguments
    ///
    /// * `vec` - The `Vec` to iterate over.
    ///
    /// # Returns
    ///
    /// A new `IntoIter` instance.
    #[must_use]
    pub const fn new(vec: Vec<T, MAX_LENGTH>) -> Self {
        Self { vec, next: 0 }
    }
}

impl<T, const MAX_LENGTH: usize> Vec<T, MAX_LENGTH> {
    /// Creates a new, empty `Vec` with a maximum length specified at compile time.
    ///
    /// # Returns
    ///
    /// A new, empty `Vec` instance.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            array: [const { MaybeUninit::uninit() }; MAX_LENGTH],
            length: 0,
        }
    }

    /// Attempts to push a value onto the vector.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to push onto the vector.
    ///
    /// # Returns
    ///
    /// * `Ok(())` if the value was successfully pushed
    /// * `Err(())` if the vector is full.
    #[allow(clippy::result_unit_err)]
    pub fn push(&mut self, value: T) -> Result<(), ()> {
        if self.length < MAX_LENGTH {
            // This is a safe operation because we've checked that the vector is not full
            unsafe { self.push_unchecked(value) };

            Ok(())
        } else {
            Err(())
        }
    }

    /// Pushes a value onto the vector without checking if it is full.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to push onto the vector.
    ///
    /// # Safety
    ///
    /// Capacity must be checked before calling this function.
    pub const unsafe fn push_unchecked(&mut self, value: T) {
        self.array[self.length].write(value);
        self.length += 1;
    }

    /// Removes the last element from the vector and returns it.
    ///
    /// # Returns
    ///
    /// * `Some(T)` if the vector is not empty
    /// * `None` if the vector is empty.
    #[must_use]
    pub fn pop(&mut self) -> Option<T> {
        if self.length > 0 {
            // This is a safe operation because we've checked that the vector is not empty
            unsafe { Some(self.pop_unchecked()) }
        } else {
            None
        }
    }

    /// Removes the last element from the vector and returns it without checking if it is empty.
    ///
    /// # Returns
    ///
    /// The last element of the vector.
    ///
    /// # Safety
    ///
    /// Capacity must be checked before calling this function.
    #[must_use]
    pub unsafe fn pop_unchecked(&mut self) -> T {
        self.length -= 1;
        unsafe { self.get_unchecked(self.length) }
    }

    /// Writes a value to the specified index in the vector.
    ///
    /// # Arguments
    ///
    /// * `index` - The index at which to write the value.
    /// * `value` - The value to write.
    ///
    /// # Returns
    ///
    /// * `Ok(())` if the value was successfully written.
    /// * `Err(())` if the index is out of bounds.
    #[allow(clippy::result_unit_err)]
    pub fn write(&mut self, index: usize, value: T) -> Result<(), ()> {
        if index <= self.length && index < MAX_LENGTH {
            // This is a safe operation because we've checked that the vector can hold the value
            unsafe { self.write_unchecked(index, value) };

            Ok(())
        } else {
            Err(())
        }
    }

    /// Writes a value to the specified index in the vector without checking bounds.
    ///
    /// # Arguments
    ///
    /// * `index` - The index at which to write the value.
    /// * `value` - The value to write.
    ///
    /// # Safety
    ///
    /// Capacity must be checked before calling this function.
    pub const unsafe fn write_unchecked(&mut self, index: usize, value: T) {
        // Make sure all the previous bytes are initialized before reading the array
        self.array[index].write(value);
        if index >= self.length {
            self.length = index + 1;
        }
    }

    /// Writes a slice of values to the vector starting at the specified index.
    ///
    /// # Arguments
    ///
    /// * `index` - The starting index at which to write the slice.
    /// * `value` - The slice of values to write.
    ///
    /// # Returns
    ///
    /// * `Ok(())` if the slice was successfully written.
    /// * `Err(())` if the index or slice length is out of bounds.
    #[allow(clippy::result_unit_err)]
    pub const fn write_slice(&mut self, index: usize, value: &[T]) -> Result<(), ()>
    where
        T: Copy,
    {
        if index <= self.length && index + value.len() <= MAX_LENGTH {
            // This is a safe operation because we've checked that the vector can hold the slice
            unsafe { self.write_slice_unchecked(index, value) };

            Ok(())
        } else {
            Err(())
        }
    }

    /// Writes a slice of values to the vector starting at the specified index without checking bounds.
    ///
    /// # Arguments
    ///
    /// * `start_index` - The starting index at which to write the slice.
    /// * `value` - The slice of values to write.
    ///
    /// # Safety
    ///
    /// Capacity must be checked before calling this function.
    pub const unsafe fn write_slice_unchecked(&mut self, mut start_index: usize, value: &[T])
    where
        T: Copy,
    {
        // Make sure all the previous bytes are initialized before reading the array
        let mut index = 0;
        while index < value.len() {
            unsafe { self.write_unchecked(start_index, value[index]) };

            index += 1;
            start_index += 1;
        }
    }

    /// Attempts to insert a value at the specified index in the vector.
    ///
    /// # Arguments
    ///
    /// * `index` - The index at which to insert the value.
    /// * `value` - The value to insert.
    ///
    /// # Returns
    ///
    /// * `Ok(())` if the value was successfully inserted.
    /// * `Err(())` if the index is out of bounds or the vector is full.
    #[allow(clippy::result_unit_err)]
    pub fn insert(&mut self, index: usize, value: T) -> Result<(), ()> {
        // Check if the element can be inserted
        if index > self.length || self.length + 1 > MAX_LENGTH {
            Err(())
        } else {
            // Shift all the elements after the index to the right
            unsafe {
                let start_slice = self.as_mut_ptr().add(index);
                ptr::copy(start_slice, start_slice.add(1), self.length - index);
                ptr::write(start_slice, value);
            }

            self.length += 1;

            Ok(())
        }
    }

    /// Removes the element at the specified index from the vector and returns it.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the element to remove.
    ///
    /// # Returns
    ///
    /// * `Some(T)` if the element was successfully removed.
    /// * `None` if the index is out of bounds.
    #[must_use]
    pub fn remove(&mut self, index: usize) -> Option<T> {
        if index < self.length {
            // This is a safe operation because we know that the index is within bounds
            let value = unsafe { self.get_unchecked(index) };

            // Shift all the elements after the index to the left
            unsafe {
                let start_slice = self.as_mut_ptr().add(index);
                ptr::copy(start_slice.add(1), start_slice, self.length - index - 1);
            }

            self.length -= 1;

            Some(value)
        } else {
            None
        }
    }

    /// Returns a reference to the element at the specified index.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the element to get.
    ///
    /// # Returns
    ///
    /// * `Some(&T)` if the index is within bounds.
    /// * `None` if the index is out of bounds.
    #[must_use]
    pub fn get(&self, index: usize) -> Option<T> {
        if index < self.length {
            // This is a safe operation because we know that the index is within bounds
            unsafe { Some(self.get_unchecked(index)) }
        } else {
            None
        }
    }

    /// Returns a reference to the element at the specified index without checking bounds.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the element to get.
    ///
    /// # Returns
    ///
    /// A reference to the element at the specified index.
    ///
    /// # Safety
    ///
    /// Capacity must be checked before calling this function.
    #[must_use]
    pub unsafe fn get_unchecked(&self, index: usize) -> T {
        unsafe { self.array.get_unchecked(index).as_ptr().read() }
    }

    /// Returns a mutable reference to the element at the specified index.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the element to get.
    ///
    /// # Returns
    ///
    /// * `Some(&mut T)` if the index is within bounds.
    /// * `None` if the index is out of bounds.
    #[must_use]
    pub fn get_mut(&mut self, index: usize) -> Option<T> {
        if index < self.length {
            // This is a safe operation because we know the index is within bounds
            unsafe { Some(self.get_mut_unchecked(index)) }
        } else {
            None
        }
    }

    /// Returns a mutable reference to the element at the specified index without checking bounds.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the element to get.
    ///
    /// # Returns
    ///
    /// A mutable reference to the element at the specified index.
    ///
    /// # Safety
    ///
    /// Capacity must be checked before calling this function.
    #[must_use]
    pub unsafe fn get_mut_unchecked(&mut self, index: usize) -> T {
        unsafe { self.array.get_unchecked_mut(index).as_mut_ptr().read() }
    }

    /// Truncates the vector to the specified length.
    ///
    /// # Arguments
    ///
    /// * `new_length` - The new length of the vector.
    pub fn truncate(&mut self, new_length: usize) {
        if new_length >= self.length {
            return;
        }

        // Update the length
        let remaining_len = self.length - new_length;
        self.length = new_length;

        // Drop the old elements that are outside of the new length
        let start_slice = unsafe { self.as_mut_ptr().add(new_length) };
        let slice_to_drop = ptr::slice_from_raw_parts_mut(start_slice, remaining_len);
        unsafe {
            ptr::drop_in_place(slice_to_drop);
        }
    }

    /// Clears the vector, removing all elements.
    pub fn clear(&mut self) {
        self.truncate(0);
    }

    unsafe fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = T>,
    {
        for elem in iter {
            unsafe { self.push_unchecked(elem) };
        }
    }

    /// Returns a slice containing the entire vector.
    ///
    /// # Returns
    ///
    /// A slice containing the entire vector.
    #[must_use]
    pub const fn as_slice(&self) -> &[T] {
        unsafe { slice::from_raw_parts(self.array.as_ptr().cast::<T>(), self.length) }
    }

    /// Returns a mutable slice containing the entire vector.
    ///
    /// # Returns
    ///
    /// A mutable slice containing the entire vector.
    #[must_use]
    pub const fn as_mut_slice(&mut self) -> &mut [T] {
        unsafe { slice::from_raw_parts_mut(self.array.as_mut_ptr().cast::<T>(), self.length) }
    }

    #[must_use]
    unsafe fn from_array_unchecked<const LENGTH: usize>(from_array: [T; LENGTH]) -> Self {
        let mut vec = Self::new();

        // Do not drop the elements of the array, since we're moving them into the vector
        let array = ManuallyDrop::new(from_array);

        while vec.length < array.len() {
            vec.array[vec.length] =
                MaybeUninit::new(unsafe { ptr::read(&raw const array[vec.length]) });
            vec.length += 1;
        }

        vec
    }

    #[must_use]
    const unsafe fn from_slice_unchecked(from_slice: &[T]) -> Self
    where
        T: Copy,
    {
        let mut vec = Self::new();

        while vec.length < from_slice.len() {
            vec.array[vec.length] = MaybeUninit::new(from_slice[vec.length]);
            vec.length += 1;
        }

        vec
    }

    #[must_use]
    unsafe fn from_uint_unchecked(mut value: u64, max_length: usize) -> Self
    where
        T: From<u8>,
    {
        let mut vec = Self::new();

        let mut real_length = 0;
        let mut index = 0;
        while index < max_length {
            let byte = (value & 0xff) as u8;
            if byte != 0 {
                real_length = index + 1;
            }

            unsafe { vec.push_unchecked(byte.into()) };

            // Shift the value to the right
            value >>= 8;

            index += 1;
        }

        vec.length = real_length;
        vec
    }

    #[must_use]
    fn to_uint(&self) -> u64
    where
        T: Into<u8>,
    {
        let mut value = 0;
        let mut index = 0;
        while index < self.len() {
            // This is a safe operation because we know that the index is within bounds
            let byte = unsafe { self.get_unchecked(index).into() };

            value |= u64::from(byte) << (index * 8);

            index += 1;
        }

        value
    }

    /// Returns the current length of the vector.
    ///
    /// # Returns
    ///
    /// The current length of the vector.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.length
    }

    /// Returns the remaining capacity of the vector.
    ///
    /// # Returns
    ///
    /// The remaining capacity of the vector.
    #[must_use]
    pub const fn remaining_len(&self) -> usize {
        MAX_LENGTH - self.length
    }

    /// Checks if the vector is empty.
    ///
    /// # Returns
    ///
    /// * `true` if the vector is empty
    /// * `false` if the vector is not empty
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.length == 0
    }
}

/// Default implementation for `Vec`.
///
/// This allows creating a `Vec` using `Vec::default()`.
impl<T, const MAX_LENGTH: usize> Default for Vec<T, MAX_LENGTH> {
    /// Creates a new, empty `Vec` with a maximum length specified at compile time.
    ///
    /// # Returns
    ///
    /// A new, empty `Vec` instance.
    fn default() -> Self {
        Self::new()
    }
}

/// Drop implementation for `Vec`.
///
/// This ensures that all elements in the `Vec` are properly dropped when the `Vec` goes out of scope.
impl<T, const LENGTH: usize> Drop for Vec<T, LENGTH> {
    /// Drops all elements in the `Vec`.
    fn drop(&mut self) {
        unsafe {
            ptr::drop_in_place(self.as_mut_slice());
        }
    }
}

/// Implementation of `IntoIterator` for `&Vec`.
///
/// This allows iterating over references to the elements of a `Vec`.
impl<'a, T, const MAX_LENGTH: usize> IntoIterator for &'a Vec<T, MAX_LENGTH> {
    type Item = &'a T;
    type IntoIter = slice::Iter<'a, T>;

    /// Returns an iterator over the elements of the `Vec`.
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Implementation of `Iterator` for `IntoIter`.
///
/// This allows iterating over the elements of a `Vec` by value.
impl<T, const MAX_LENGTH: usize> Iterator for IntoIter<T, MAX_LENGTH> {
    type Item = T;

    /// Returns the next element in the iterator.
    fn next(&mut self) -> Option<Self::Item> {
        if self.next < self.vec.len() {
            // This is a safe operation because we know that the index is within bounds
            let value = unsafe { self.vec.get_unchecked(self.next) };
            self.next += 1;

            Some(value)
        } else {
            None
        }
    }
}

/// Drop implementation for `IntoIter`.
///
/// This ensures that all remaining elements in the `IntoIter` are properly dropped when the `IntoIter` goes out of scope.
impl<T, const MAX_LENGTH: usize> Drop for IntoIter<T, MAX_LENGTH> {
    /// Drops all remaining elements in the `IntoIter`.
    fn drop(&mut self) {
        unsafe {
            // Drop all the remaining elements, and set the length to 0
            ptr::drop_in_place(&raw mut self.vec.as_mut_slice()[self.next..]);
            self.vec.length = 0;
        }
    }
}

/// Implementation of `IntoIterator` for `Vec`.
///
/// This allows converting a `Vec` into an `IntoIter`.
impl<T, const MAX_LENGTH: usize> IntoIterator for Vec<T, MAX_LENGTH> {
    type Item = T;
    type IntoIter = IntoIter<T, MAX_LENGTH>;

    /// Converts the `Vec` into an `IntoIter`.
    fn into_iter(self) -> Self::IntoIter {
        IntoIter::new(self)
    }
}

/// Implementation of `PartialEq` for `Vec`.
///
/// This allows comparing two `Vec`s for equality.
impl<TA, TB, const MAX_LENGTH_A: usize, const MAX_LENGTH_B: usize> PartialEq<Vec<TB, MAX_LENGTH_B>>
    for Vec<TA, MAX_LENGTH_A>
where
    TA: PartialEq<TB>,
{
    /// Compares two `Vec`s for equality.
    fn eq(&self, other: &Vec<TB, MAX_LENGTH_B>) -> bool {
        <[TA]>::eq(self, &**other)
    }
}

/// Implementation of `Eq` for `Vec`.
///
/// This allows comparing two `Vec`s for equality.
impl<T, const MAX_LENGTH: usize> Eq for Vec<T, MAX_LENGTH> where T: Eq {}

/// Implementation of `TryFrom` for `Vec`.
///
/// This allows converting a slice into a `Vec`.
impl<T: Copy, const MAX_LENGTH: usize> TryFrom<&[T]> for Vec<T, MAX_LENGTH> {
    type Error = ();

    /// Converts a slice into a `Vec`.
    fn try_from(values: &[T]) -> Result<Self, Self::Error> {
        // Runtime check
        if values.len() > MAX_LENGTH {
            return Err(());
        }

        // This is a safe operation because we check at runtime that the length is sufficient
        Ok(unsafe { Self::from_slice_unchecked(values) })
    }
}

/// Implementation of `From` for `Vec`.
///
/// This allows converting a `Vec` into another `Vec`.
impl<T: Copy, const LENGTH: usize, const MAX_LENGTH: usize> From<&Vec<T, LENGTH>>
    for Vec<T, MAX_LENGTH>
{
    /// Converts a `Vec` into another `Vec`.
    fn from(values: &Vec<T, LENGTH>) -> Self {
        // Build time assertion
        assert_lte!(LENGTH, MAX_LENGTH);

        // This is a safe operation because we check at build time that the length is sufficient
        unsafe { Self::from_slice_unchecked(values) }
    }
}

/// Implementation of `From` for `Vec`.
///
/// This allows converting an array into a `Vec`.
impl<T, const LENGTH: usize, const MAX_LENGTH: usize> From<[T; LENGTH]> for Vec<T, MAX_LENGTH> {
    /// Converts an array into a `Vec`.
    fn from(values: [T; LENGTH]) -> Self {
        // Build time assertion
        assert_lte!(LENGTH, MAX_LENGTH);

        // This is a safe operation because we check at build time that the length is sufficient
        unsafe { Self::from_array_unchecked(values) }
    }
}

/// Implementation of `From` for `Vec`.
///
/// This allows converting a reference to an array into a `Vec`.
impl<T: Copy, const LENGTH: usize, const MAX_LENGTH: usize> From<&[T; LENGTH]>
    for Vec<T, MAX_LENGTH>
{
    /// Converts a reference to an array into a `Vec`.
    fn from(values: &[T; LENGTH]) -> Self {
        // Build time assertion
        assert_lte!(LENGTH, MAX_LENGTH);

        // This is a safe operation because we check at build time that the length is sufficient
        unsafe { Self::from_slice_unchecked(values) }
    }
}

/// Implementation of `From` for `Vec`.
///
/// This allows converting a `u8` into a `Vec`.
impl<const MAX_LENGTH: usize> From<u8> for Vec<u8, MAX_LENGTH> {
    /// Converts a `u8` into a `Vec`.
    fn from(value: u8) -> Self {
        // Build time assertion
        const VALUE_LENGTH: usize = size_of::<u8>();
        assert_lte!(VALUE_LENGTH, MAX_LENGTH);

        // This is a safe operation because we check at build time that the length is sufficient
        unsafe { Self::from_uint_unchecked(u64::from(value), VALUE_LENGTH) }
    }
}

/// Implementation of `From` for `Vec`.
///
/// This allows converting a `u16` into a `Vec`.
impl<const MAX_LENGTH: usize> From<u16> for Vec<u8, MAX_LENGTH> {
    /// Converts a `u16` into a `Vec`.
    fn from(value: u16) -> Self {
        // Build time assertion
        const VALUE_LENGTH: usize = size_of::<u16>();
        assert_lte!(VALUE_LENGTH, MAX_LENGTH);

        // This is a safe operation because we check at build time that the length is sufficient
        unsafe { Self::from_uint_unchecked(u64::from(value), VALUE_LENGTH) }
    }
}

/// Implementation of `From` for `Vec`.
///
/// This allows converting a `u32` into a `Vec`.
impl<const MAX_LENGTH: usize> From<u32> for Vec<u8, MAX_LENGTH> {
    /// Converts a `u32` into a `Vec`.
    fn from(value: u32) -> Self {
        // Build time assertion
        const VALUE_LENGTH: usize = size_of::<u32>();
        assert_lte!(VALUE_LENGTH, MAX_LENGTH);

        // This is a safe operation because we check at build time that the length is sufficient
        unsafe { Self::from_uint_unchecked(u64::from(value), VALUE_LENGTH) }
    }
}

/// Implementation of `From` for `Vec`.
///
/// This allows converting a `u64` into a `Vec`.
impl<const MAX_LENGTH: usize> From<u64> for Vec<u8, MAX_LENGTH> {
    /// Converts a `u64` into a `Vec`.
    fn from(value: u64) -> Self {
        // Build time assertion
        const VALUE_LENGTH: usize = size_of::<u64>();
        assert_lte!(VALUE_LENGTH, MAX_LENGTH);

        // This is a safe operation because we check at build time that the length is sufficient
        unsafe { Self::from_uint_unchecked(value, VALUE_LENGTH) }
    }
}

/// Implementation of `Deref` for `Vec`.
///
/// This allows dereferencing a `Vec` to get a slice of its elements.
impl<T, const MAX_LENGTH: usize> Deref for Vec<T, MAX_LENGTH> {
    type Target = [T];

    /// Dereferences the `Vec` to get a slice of its elements.
    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

/// Implementation of `DerefMut` for `Vec`.
///
/// This allows dereferencing a mutable `Vec` to get a mutable slice of its elements.
impl<T, const MAX_LENGTH: usize> DerefMut for Vec<T, MAX_LENGTH> {
    /// Dereferences the mutable `Vec` to get a mutable slice of its elements.
    fn deref_mut(&mut self) -> &mut [T] {
        self.as_mut_slice()
    }
}

/// Implementation of `From` for `u8`.
///
/// This allows converting a `Vec` into a `u8`.
impl<T, const MAX_LENGTH: usize> From<&Vec<T, MAX_LENGTH>> for u8
where
    T: Into<Self>,
{
    #[allow(clippy::cast_possible_truncation)]
    /// Converts a `Vec` into a `u8`.
    fn from(value: &Vec<T, MAX_LENGTH>) -> Self {
        value.to_uint() as Self
    }
}

/// Implementation of `From` for `u16`.
///
/// This allows converting a `Vec` into a `u16`.
impl<T, const MAX_LENGTH: usize> From<&Vec<T, MAX_LENGTH>> for u16
where
    T: Into<u8>,
{
    #[allow(clippy::cast_possible_truncation)]
    /// Converts a `Vec` into a `u16`.
    fn from(value: &Vec<T, MAX_LENGTH>) -> Self {
        value.to_uint() as Self
    }
}

/// Implementation of `From` for `u32`.
///
/// This allows converting a `Vec` into a `u32`.
impl<T, const MAX_LENGTH: usize> From<&Vec<T, MAX_LENGTH>> for u32
where
    T: Into<u8>,
{
    #[allow(clippy::cast_possible_truncation)]
    /// Converts a `Vec` into a `u32`.
    fn from(value: &Vec<T, MAX_LENGTH>) -> Self {
        value.to_uint() as Self
    }
}

/// Implementation of `From` for `u64`.
///
/// This allows converting a `Vec` into a `u64`.
impl<T, const MAX_LENGTH: usize> From<&Vec<T, MAX_LENGTH>> for u64
where
    T: Into<u8>,
{
    /// Converts a `Vec` into a `u64`.
    fn from(value: &Vec<T, MAX_LENGTH>) -> Self {
        value.to_uint() as Self
    }
}

/// Implementation of `Extend` for `Vec`.
///
/// This allows extending a `Vec` with references to elements.
impl<'a, T, const MAX_LENGTH: usize> Extend<&'a T> for Vec<T, MAX_LENGTH>
where
    T: 'a + Copy,
{
    /// Extends the `Vec` with references to elements.
    /// Check left capacity before using this method.
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = &'a T>,
    {
        // This is not a safe operation, the caller must ensure there is enough capacity
        unsafe { self.extend(iter.into_iter().copied()) };
    }
}

/// Implementation of `Extend` for `Vec`.
///
/// This allows extending a `Vec` with elements.
impl<T, const MAX_LENGTH: usize> Extend<T> for Vec<T, MAX_LENGTH>
where
    T: Copy,
{
    /// Extends the `Vec` with elements.
    /// Check left capacity before using this method.
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = T>,
    {
        // This is not a safe operation, the caller must ensure there is enough capacity
        unsafe { self.extend(iter) };
    }
}

/// Implementation of `Clone` for `Vec`.
///
/// This allows cloning a `Vec`.
impl<T, const MAX_LENGTH: usize> Clone for Vec<T, MAX_LENGTH>
where
    T: Clone,
{
    /// Clones the `Vec`.
    fn clone(&self) -> Self {
        let mut new_vec = Self::new();
        for elem in self {
            // This is a safe operation because the destination vector has the same capacity as the source vector
            unsafe { new_vec.push_unchecked(elem.clone()) };
        }

        new_vec
    }
}

#[cfg(test)]
mod tests {
    use crate::vec::Vec;

    #[test]
    fn test_vec_new() {
        let vec = Vec::<u8, 1>::new();

        assert_eq!(0, vec.len());
        assert!(vec.is_empty());
    }

    #[test]
    fn test_vec_push() {
        let mut vec = Vec::<u8, 1>::new();

        assert_eq!(Ok(()), vec.push(1));
        assert_eq!(1, vec.len());
        assert!(!vec.is_empty());
    }

    #[test]
    fn test_vec_push_out_of_bound() {
        let mut vec = Vec::<u8, 1>::new();

        assert_eq!(Ok(()), vec.push(1));
        assert_eq!(Err(()), vec.push(2));
    }

    #[test]
    fn test_vec_push_unchecked() {
        let mut vec = Vec::<u8, 1>::new();

        unsafe { vec.push_unchecked(1) };

        assert_eq!(1, vec.len());
        assert!(!vec.is_empty());
    }

    #[test]
    fn test_vec_pop() {
        let mut vec = Vec::<u8, 1>::new();

        assert_eq!(Ok(()), vec.push(1));
        assert_eq!(Some(1), vec.pop());
        assert_eq!(0, vec.len());
        assert_eq!(None, vec.pop());
    }

    #[test]
    fn test_vec_pop_unchecked() {
        let mut vec = Vec::<u8, 1>::new();
        let _ = vec.push(1);

        assert_eq!(1, unsafe { vec.pop_unchecked() });
        assert_eq!(0, vec.len());
        assert_eq!(None, vec.pop());
    }

    #[test]
    fn test_vec_write() {
        let mut vec = Vec::<u8, 3>::new();

        assert_eq!(Ok(()), vec.write(0, 1));
        assert_eq!(1, vec.len());
        assert_eq!(Some(1), vec.get(0));
        assert_eq!(None, vec.get(1));
    }

    #[test]
    fn test_vec_write_out_of_bound() {
        let mut vec = Vec::<u8, 3>::new();

        assert_eq!(Err(()), vec.write(3, 1));
    }

    #[test]
    fn test_vec_write_unchecked() {
        let mut vec = Vec::<u8, 3>::new();

        unsafe { vec.write_unchecked(0, 1) };

        assert_eq!(1, vec.len());
        assert_eq!(Some(1), vec.get(0));
        assert_eq!(None, vec.get(1));
    }

    #[test]
    fn test_vec_write_slice() {
        let mut vec = Vec::<u8, 3>::new();

        assert_eq!(Ok(()), vec.write_slice(0, &[1, 2, 3]));
        assert_eq!(3, vec.len());
        assert_eq!(Some(1), vec.get(0));
        assert_eq!(Some(2), vec.get(1));
        assert_eq!(Some(3), vec.get(2));
        assert_eq!(None, vec.get(3));
    }

    #[test]
    fn test_vec_write_slice_out_of_bound() {
        let mut vec = Vec::<u8, 3>::new();

        assert_eq!(Err(()), vec.write_slice(1, &[1, 2, 3]));
    }

    #[test]
    fn test_vec_write_slice_unchecked() {
        let mut vec = Vec::<u8, 3>::new();

        unsafe { vec.write_slice_unchecked(0, &[1, 2, 3]) };

        assert_eq!(3, vec.len());
        assert_eq!(Some(1), vec.get(0));
        assert_eq!(Some(2), vec.get(1));
        assert_eq!(Some(3), vec.get(2));
        assert_eq!(None, vec.get(3));
    }

    #[test]
    fn test_vec_insert_at_start() {
        let mut vec = Vec::<u8, 3>::new();

        assert_eq!(Ok(()), vec.insert(0, 1));
        assert_eq!(1, vec.len());
        assert_eq!(Some(1), vec.get(0));
        assert_eq!(None, vec.get(1));
    }

    #[test]
    fn test_vec_insert_in_middle() {
        let mut vec = Vec::<u8, 4>::from([1, 2, 3]);

        assert_eq!(Ok(()), vec.insert(1, 4));
        assert_eq!(4, vec.len());
        assert_eq!(Some(1), vec.get(0));
        assert_eq!(Some(4), vec.get(1));
        assert_eq!(Some(2), vec.get(2));
        assert_eq!(Some(3), vec.get(3));
    }

    #[test]
    fn test_vec_insert_out_of_bound() {
        let mut vec = Vec::<u8, 0>::new();

        assert_eq!(Err(()), vec.insert(1, 1));
    }

    #[test]
    fn test_vec_remove() {
        let mut vec = Vec::<u8, 3>::from([1, 2, 3]);

        assert_eq!(Some(2), vec.remove(1));
        assert_eq!(2, vec.len());
        assert_eq!(Some(1), vec.get(0));
        assert_eq!(Some(3), vec.get(1));
        assert_eq!(None, vec.get(2));
    }

    #[test]
    fn test_vec_remove_last() {
        let mut vec = Vec::<u8, 3>::from([1, 2, 3]);

        assert_eq!(Some(3), vec.remove(2));
        assert_eq!(2, vec.len());
        assert_eq!(Some(1), vec.get(0));
        assert_eq!(Some(2), vec.get(1));
        assert_eq!(None, vec.get(2));
    }

    #[test]
    fn test_vec_remove_out_of_bound() {
        let mut vec = Vec::<u8, 1>::new();

        assert_eq!(None, vec.remove(1));
    }

    #[test]
    fn test_vec_get() {
        let mut vec = Vec::<u8, 1>::new();
        let _ = vec.push(1);

        assert_eq!(Some(1), vec.get(0));
        assert_eq!(1, vec.len());
        assert_eq!(None, vec.get(1));
    }

    #[test]
    fn test_vec_get_out_of_bound() {
        let mut vec = Vec::<u8, 1>::new();
        let _ = vec.push(1);

        assert_eq!(None, vec.get(1));
        assert_eq!(1, vec.len());
    }

    #[test]
    fn test_vec_get_unchecked() {
        let mut vec = Vec::<u8, 1>::new();
        let _ = vec.push(1);

        assert_eq!(1, unsafe { vec.get_unchecked(0) });
        assert_eq!(1, vec.len());
    }

    #[test]
    fn test_vec_get_mut() {
        let mut vec = Vec::<u8, 1>::new();
        let _ = vec.push(1);

        assert_eq!(Some(1), vec.get_mut(0));
        assert_eq!(1, vec.len());
        assert_eq!(None, vec.get_mut(1));
    }

    #[test]
    fn test_vec_get_mut_out_of_bound() {
        let mut vec = Vec::<u8, 1>::new();
        let _ = vec.push(1);

        assert_eq!(None, vec.get_mut(1));
        assert_eq!(1, vec.len());
    }

    #[test]
    fn test_vec_get_mut_unchecked() {
        let mut vec = Vec::<u8, 1>::new();
        let _ = vec.push(1);

        assert_eq!(1, unsafe { vec.get_mut_unchecked(0) });
        assert_eq!(1, vec.len());
    }

    #[test]
    fn test_vec_extend() {
        let mut vec = Vec::<u8, 3>::new();
        let array: [u8; 3] = [1, 2, 3];

        unsafe { vec.extend(array.iter().copied()) };
        assert_eq!(3, vec.len());
        assert_eq!(Some(1), vec.get(0));
        assert_eq!(Some(2), vec.get(1));
        assert_eq!(Some(3), vec.get(2));
        assert_eq!(None, vec.get(3));
    }

    #[test]
    fn test_as_slice_with_empty_vec() {
        let vec = Vec::<u8, 1>::new();

        let array = vec.as_slice();

        assert_eq!(0, array.len());
    }

    #[test]
    fn test_as_mut_slice_with_empty_vec() {
        let mut vec = Vec::<u8, 1>::new();

        let array = vec.as_mut_slice();

        assert_eq!(0, array.len());
    }

    #[test]
    fn test_vec_truncate() {
        let mut vec = Vec::<u8, 1>::new();

        assert_eq!(Ok(()), vec.push(1));
        assert!(!vec.is_empty());

        vec.truncate(0);

        assert_eq!(0, vec.len());
        assert!(vec.is_empty());
    }

    #[test]
    fn test_vec_truncate_with_new_length_equal_current_length() {
        let mut vec = Vec::<u8, 1>::new();

        assert_eq!(Ok(()), vec.push(1));
        assert!(!vec.is_empty());

        vec.truncate(1);

        assert_eq!(1, vec.len());
        assert!(!vec.is_empty());
    }

    #[test]
    fn test_vec_truncate_with_new_length_superior_to_current_length() {
        let mut vec = Vec::<u8, 1>::new();

        assert_eq!(Ok(()), vec.push(1));
        assert!(!vec.is_empty());

        vec.truncate(2);

        assert_eq!(1, vec.len());
        assert!(!vec.is_empty());
    }

    #[test]
    fn test_vec_clear() {
        let mut vec = Vec::<u8, 1>::new();

        assert_eq!(Ok(()), vec.push(1));
        assert!(!vec.is_empty());

        vec.clear();

        assert_eq!(0, vec.len());
        assert!(vec.is_empty());
    }

    #[test]
    fn test_vec_try_from_array_as_slice() {
        let vec: Vec<u8, 3> = [1, 2, 3].as_slice().try_into().unwrap();

        assert_eq!(3, vec.len());
        assert_eq!(Some(1), vec.get(0));
        assert_eq!(Some(2), vec.get(1));
        assert_eq!(Some(3), vec.get(2));
        assert_eq!(None, vec.get(3));
    }

    #[test]
    fn test_vec_try_from_array_as_slice_shorter_than_vec_size() {
        let vec: Vec<u8, 8> = [1, 2, 3].as_slice().try_into().unwrap();

        assert_eq!(3, vec.len());
        assert_eq!(Some(1), vec.get(0));
        assert_eq!(Some(2), vec.get(1));
        assert_eq!(Some(3), vec.get(2));
        assert_eq!(None, vec.get(3));
    }

    #[test]
    fn test_small_vec_try_from_array_as_slice_should_failed() {
        let vec_result: Result<Vec<u8, 1>, _> = [1, 2, 3].as_slice().try_into();

        assert!(vec_result.is_err());
    }

    #[test]
    fn test_vec_from_array() {
        let vec: Vec<u8, 3> = Vec::from(&[1, 2, 3]);

        assert_eq!(3, vec.len());
        assert_eq!(Some(1), vec.get(0));
        assert_eq!(Some(2), vec.get(1));
        assert_eq!(Some(3), vec.get(2));
        assert_eq!(None, vec.get(3));
    }

    #[test]
    fn test_vec_from_array_same_size_as_vec() {
        let vec: Vec<u8, 3> = [1, 2, 3].into();

        assert_eq!(3, vec.len());
        assert_eq!(Some(1), vec.get(0));
        assert_eq!(Some(2), vec.get(1));
        assert_eq!(Some(3), vec.get(2));
        assert_eq!(None, vec.get(3));
    }

    #[test]
    fn test_vec_from_u8() {
        let vec: Vec<u8, 8> = 0xffu8.into();

        assert_eq!(1, vec.len());
        assert_eq!(Some(0xff), vec.get(0));
        assert_eq!(None, vec.get(1));
        assert_eq!(None, vec.get(2));
        assert_eq!(None, vec.get(3));
        assert_eq!(None, vec.get(4));
        assert_eq!(None, vec.get(5));
        assert_eq!(None, vec.get(6));
        assert_eq!(None, vec.get(7));
    }

    #[test]
    fn test_vec_from_u16() {
        let vec: Vec<u8, 8> = 0xff00u16.into();

        assert_eq!(2, vec.len());
        assert_eq!(Some(0x00), vec.get(0));
        assert_eq!(Some(0xff), vec.get(1));
        assert_eq!(None, vec.get(2));
        assert_eq!(None, vec.get(3));
        assert_eq!(None, vec.get(4));
        assert_eq!(None, vec.get(5));
        assert_eq!(None, vec.get(6));
        assert_eq!(None, vec.get(7));
    }

    #[test]
    fn test_vec_from_number_shorter_than_real_u16() {
        let vec: Vec<u8, 8> = 0x00ffu16.into();

        assert_eq!(1, vec.len());
        assert_eq!(Some(0xff), vec.get(0));
        assert_eq!(None, vec.get(1));
        assert_eq!(None, vec.get(2));
        assert_eq!(None, vec.get(3));
        assert_eq!(None, vec.get(4));
        assert_eq!(None, vec.get(5));
        assert_eq!(None, vec.get(6));
        assert_eq!(None, vec.get(7));
    }

    #[test]
    fn test_vec_from_u32() {
        let vec: Vec<u8, 8> = 0xff00_ff00_u32.into();

        assert_eq!(4, vec.len());
        assert_eq!(Some(0x00), vec.get(0));
        assert_eq!(Some(0xff), vec.get(1));
        assert_eq!(Some(0x00), vec.get(2));
        assert_eq!(Some(0xff), vec.get(3));
        assert_eq!(None, vec.get(4));
        assert_eq!(None, vec.get(5));
        assert_eq!(None, vec.get(6));
        assert_eq!(None, vec.get(7));
    }

    #[test]
    fn test_vec_from_u64() {
        let vec: Vec<u8, 8> = 0xff00_ff00_ff00_ff00_u64.into();

        assert_eq!(8, vec.len());
        assert_eq!(Some(0x00), vec.get(0));
        assert_eq!(Some(0xff), vec.get(1));
        assert_eq!(Some(0x00), vec.get(2));
        assert_eq!(Some(0xff), vec.get(3));
        assert_eq!(Some(0x00), vec.get(4));
        assert_eq!(Some(0xff), vec.get(5));
        assert_eq!(Some(0x00), vec.get(6));
        assert_eq!(Some(0xff), vec.get(7));
    }

    #[test]
    fn test_u8_from_vec() {
        let vec: Vec<u8, 1> = Vec::from([0x2A]);
        let value = u8::from(&vec);

        assert_eq!(42, value);
    }

    #[test]
    fn test_u16_from_vec() {
        let vec: Vec<u8, 2> = Vec::from([0xD2, 0x04]);
        let value = u16::from(&vec);

        assert_eq!(1234, value);
    }

    #[test]
    fn test_u32_from_vec() {
        let vec: Vec<u8, 4> = Vec::from([0x52, 0xAA, 0x08, 0x00]);
        let value = u32::from(&vec);

        assert_eq!(567_890, value);
    }

    #[test]
    fn test_u64_from_vec() {
        let vec: Vec<u8, 8> = Vec::from([0x08, 0x1A, 0x99, 0xBE, 0x1C, 0x00, 0x00, 0x00]);
        let value = u64::from(&vec);

        assert_eq!(123_456_789_000, value);
    }

    #[test]
    fn test_deref_with_empty_vec() {
        let vec = Vec::<u8, 1>::new();

        let array = &*vec;

        assert_eq!(0, array.len());
    }

    #[test]
    #[allow(unused_mut)]
    fn test_deref_mut_with_empty_vec() {
        let mut vec = Vec::<u8, 1>::new();

        let array = &*vec;

        assert_eq!(0, array.len());
    }

    #[test]
    fn test_into_iter_vec_with_for_loop() {
        let vec: Vec<u8, 3> = [1, 2, 3].as_slice().try_into().unwrap();

        // Using for loop
        vec.into_iter().for_each(|value| {
            assert!(matches!(value, 1..=3));
        });
    }

    #[test]
    fn test_into_iter_vec_with_iterator() {
        let vec: Vec<u8, 3> = [1, 2, 3].as_slice().try_into().unwrap();

        // Using iterator
        let mut into_iter = vec.into_iter();
        assert_eq!(Some(1), into_iter.next());
        assert_eq!(Some(2), into_iter.next());
        assert_eq!(Some(3), into_iter.next());
    }
}