minsize 0.1.2

Collections with a statically known minimum size (using const generics)
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
#![warn(
    missing_debug_implementations,
    missing_docs,
    rust_2018_idioms,
    unreachable_pub
)]
#![deny(rustdoc::broken_intra_doc_links)]
#![forbid(unsafe_code)]

//! Collections with a statically known minimum size.
//!
//! # Crate features
//!
//! - `arbitrary`: Add support for the [`arbitrary`](https://crates.io/crates/arbitrary) crate
//! - `serde`: Add implementations for the [`serde`](https://crates.io/crates/serde) traits

use std::{
    cmp,
    convert::{TryFrom, TryInto},
    fmt,
    ops::{Deref, DerefMut, Index, IndexMut},
    slice::{Iter as SliceIter, IterMut as SliceIterMut, SliceIndex},
    vec::IntoIter,
};

/// Marker trait for non-empty minimum sizes.
///
/// The purpose of this is to abstract over the length restriction until const expressions are
/// stabilized. Currently it is implemented for some useful sizes manually, but once the necessary
/// language features are stabilized, this will be replaced with a blanket impl for all unsigned
/// integers greater than zero.
pub trait NotEmpty: sealed::Sealed {}

mod sealed {
    pub trait Sealed {}
}

macro_rules! impl_for_arrays {
    ($($size:literal),+) => {
        $(
            impl<T> sealed::Sealed for MinSizedVec<T, $size> {}
            impl<T> NotEmpty for MinSizedVec<T, $size> {}
        )*
    };
}

impl_for_arrays!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 32, 64, 128);

/// A [`Vec`] that always contains at least one element.
///
/// This is just a utility alias, so see the [`MinSizedVec`] docs for available methods.
pub type NonEmptyVec<T> = MinSizedVec<T, 1>;

/// A [`Vec`] with a minimum size.
///
/// This wraps a plain standard library [`Vec`], but inserts checks that it never falls below the
/// required length.
///
/// This type derefs to slices in the same way [`Vec`] does, so most of the methods you already
/// know are available too.
#[derive(Clone, Eq, Ord, Hash)]
pub struct MinSizedVec<T, const N: usize>(Vec<T>);

impl<T, const MINIMUM_SIZE: usize> MinSizedVec<T, MINIMUM_SIZE> {
    /// The minimum size of this collection.
    pub const MINIMUM_SIZE: usize = MINIMUM_SIZE;

    /// Create a `MinSizedVec` from a plain `Vec`.
    ///
    /// This checks the length, handing you back the input if it is less than the required length.
    ///
    /// This is equivalent to the [`TryFrom<Vec<T>>`][`TryFrom`] impl.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::convert::TryInto;
    /// # use minsize::MinSizedVec;
    /// let min_size: MinSizedVec<_, 3> = vec![1, 2, 3].try_into().unwrap();
    ///
    /// // Too short input:
    /// let result: Result<MinSizedVec<_, 2>, _> = vec![1].try_into();
    /// assert_eq!(result, Err(vec![1]));
    /// ```
    pub fn new(value: Vec<T>) -> Result<MinSizedVec<T, MINIMUM_SIZE>, Vec<T>> {
        Self::try_from(value)
    }

    /// Create a `MinSizedVec` from an iterator.
    ///
    /// This collects the given iterator into a plain [`Vec`] and then checks the length, returning
    /// either a `MinSizedVec`, or the raw collected [`Vec`] if it is too short.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let v = MinSizedVec::<_, 2>::from_iterator(vec![1, 2, 3]).unwrap();
    /// assert_eq!(v.len(), 3);
    ///
    /// let v = MinSizedVec::<_, 2>::from_iterator(vec![1]);
    /// assert_eq!(v, Err(vec![1]));
    /// ```
    pub fn from_iterator<I>(iterator: I) -> Result<MinSizedVec<T, MINIMUM_SIZE>, Vec<T>>
    where
        I: IntoIterator<Item = T>,
    {
        let vec: Vec<T> = iterator.into_iter().collect();

        if vec.len() >= MINIMUM_SIZE {
            Ok(Self(vec))
        } else {
            Err(vec)
        }
    }

    /// Extract the contained [`Vec`], thus removing the length restriction.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let v: MinSizedVec<_, 3> = MinSizedVec::new(vec![1, 2, 3]).unwrap();
    /// let v: Vec<_> = v.into_inner();
    /// assert_eq!(v, vec![1, 2, 3]);
    /// ```
    #[must_use]
    pub fn into_inner(self) -> Vec<T> {
        self.0
    }

    /// Append a value.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2]).unwrap();
    /// v.push(3);
    /// assert_eq!(v, &[1, 2, 3]);
    /// ```
    pub fn push(&mut self, value: T) {
        self.0.push(value);
    }

    /// Remove a value from the end of the collection.
    ///
    /// This will return `None` when the minimum length is reached.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2, 3]).unwrap();
    /// assert_eq!(v.pop(), Some(3));
    /// assert_eq!(v.pop(), None);
    /// assert_eq!(v, &[1, 2]);
    /// ```
    pub fn pop(&mut self) -> Option<T> {
        if self.len() > MINIMUM_SIZE {
            self.0.pop()
        } else {
            None
        }
    }

    /// Clear the collection to the minimum size required.
    ///
    /// This drops any elements after the index required for the minimum size.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2, 3]).unwrap();
    /// v.clear_to_minimum();
    /// assert_eq!(v, &[1, 2]);
    /// ```
    pub fn clear_to_minimum(&mut self) {
        self.truncate(MINIMUM_SIZE);
    }

    /// Shorten the collection, keeping the first `len` elements.
    ///
    /// If `len` is greater than the current length, this has no effect. If `len` is smaller than
    /// the minimum size, the collection is shortened to the minimum size.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2, 3, 4]).unwrap();
    /// v.truncate(3);
    /// assert_eq!(v, &[1, 2, 3]);
    ///
    /// // The length is still capped to the minimum size:
    /// v.truncate(0);
    /// assert_eq!(v, &[1, 2]);
    /// ```
    pub fn truncate(&mut self, len: usize) {
        let len = cmp::max(len, MINIMUM_SIZE);
        self.0.truncate(len);
    }

    /// Clones and appends all elements in `other` to the collection.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2]).unwrap();
    /// v.extend_from_slice(&[3, 4]);
    /// assert_eq!(v, &[1, 2, 3, 4]);
    /// ```
    pub fn extend_from_slice(&mut self, other: &[T])
    where
        T: Clone,
    {
        self.0.extend_from_slice(other);
    }

    /// Reserves capacity for at least `additional` more elements to be inserted.
    ///
    /// See [`Vec::reserve`] for details.
    pub fn reserve(&mut self, additional: usize) {
        self.0.reserve(additional);
    }

    /// Reserves the minimum capacity for exactly `additional` more elements to be inserted.
    ///
    /// See [`Vec::reserve_exact`] for details.
    pub fn reserve_exact(&mut self, additional: usize) {
        self.0.reserve_exact(additional);
    }

    /// Resizes the collection so that the length equals `new_len`.
    ///
    /// If the current length is less than `new_len`, clones of `value` are appended.
    ///
    /// If the current length is larger than `new_len`, the collection is truncated to `new_len` or
    /// the minimum size, whichever is larger.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2, 3]).unwrap();
    ///
    /// v.resize(5, 4);
    /// assert_eq!(v, &[1, 2, 3, 4, 4]);
    ///
    /// v.resize(3, 4);
    /// assert_eq!(v, &[1, 2, 3]);
    ///
    /// v.resize(0, 4);
    /// assert_eq!(v, &[1, 2]);
    /// ```
    pub fn resize(&mut self, new_len: usize, value: T)
    where
        T: Clone,
    {
        self.0.resize(cmp::max(new_len, MINIMUM_SIZE), value);
    }

    /// Resizes the collection so that the length equals `new_len`.
    ///
    /// If the current length is less than `new_len`, the collection is extended by the values
    /// returned from calling the `f` closure.
    ///
    /// If the current length is larger than `new_len`, the collection is truncated to `new_len` or
    /// the minimum size, whichever is larger.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2, 3]).unwrap();
    ///
    /// let mut start = v.len();
    /// v.resize_with(5, || { start += 1; start });
    /// assert_eq!(v, &[1, 2, 3, 4, 5]);
    ///
    /// v.resize_with(3, || 4);
    /// assert_eq!(v, &[1, 2, 3]);
    ///
    /// v.resize_with(0,  || 4);
    /// assert_eq!(v, &[1, 2]);
    /// ```
    pub fn resize_with<F>(&mut self, new_len: usize, f: F)
    where
        F: FnMut() -> T,
    {
        self.0.resize_with(cmp::max(new_len, MINIMUM_SIZE), f);
    }

    /// Insert the given `element` at the given `index`, shifting all elements after it to the right.
    ///
    /// # Panics
    ///
    /// Panics if the given index is greater than the length of the collection.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v = MinSizedVec::from([1, 2]);
    /// v.insert(2, 3);
    /// assert_eq!(v, &[1, 2, 3]);
    /// v.insert(2, 4);
    /// assert_eq!(v, &[1, 2, 4, 3]);
    /// ```
    pub fn insert(&mut self, index: usize, element: T) {
        self.0.insert(index, element);
    }

    /// Remove and return the element at the given index from the collection.
    ///
    /// This will shift all elements after `index` to the left.
    ///
    /// # Panics
    ///
    /// This will panic if `index` is out of bounds, or if removing the element would put the
    /// collection below the minimum size.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2, 3]).unwrap();
    /// assert_eq!(v.remove(1), 2);
    /// assert_eq!(v, &[1, 3]);
    /// ```
    ///
    /// ```should_panic
    /// # use minsize::MinSizedVec;
    /// let mut v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2]).unwrap();
    /// // This will panic, since the minimum size is 2:
    /// v.remove(1);
    /// ```
    #[track_caller]
    pub fn remove(&mut self, index: usize) -> T {
        if index >= self.len() {
            panic!(
                "index {} out of bounds for MinSizedVec of length {}",
                index,
                self.len()
            );
        }

        if self.len() == MINIMUM_SIZE {
            panic!(
                "removing element at index {} would underflow minimum size of {}",
                index, MINIMUM_SIZE
            );
        }

        self.0.remove(index)
    }

    /// Remove and return the element at the given index from the collection.
    ///
    /// This will replace the empty slot left by the removal with the last element in the
    /// collection. This does not preserve ordering, but is O(1).
    ///
    /// # Panics
    ///
    /// This will panic if `index` is out of bounds, or if removing the element would put the
    /// collection below the minimum size.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2, 3]).unwrap();
    /// assert_eq!(v.swap_remove(0), 1);
    /// assert_eq!(v, &[3, 2]);
    /// ```
    ///
    /// ```should_panic
    /// # use minsize::MinSizedVec;
    /// let mut v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2]).unwrap();
    /// // This will panic, since the minimum size is 2:
    /// v.swap_remove(1);
    /// ```
    #[track_caller]
    pub fn swap_remove(&mut self, index: usize) -> T {
        if index >= self.len() {
            panic!(
                "index {} out of bounds for MinSizedVec of length {}",
                index,
                self.len()
            );
        }

        if self.len() == MINIMUM_SIZE {
            panic!(
                "removing element at index {} would underflow minimum size of {}",
                index, MINIMUM_SIZE
            );
        }

        self.0.swap_remove(index)
    }

    /// Retain only the elements specified by the predicate, capped to the minimum size.
    ///
    /// This will remove all elements for which `f` returns `false` from the collection, until the
    /// minimum size has been reached. The closure will be called with each element starting from
    /// the beginning, but will stop being called after the maximum removable number of elements
    /// have been removed.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2, 3, 4, 5]).unwrap();
    /// v.capped_retain(|&e| e % 2 == 0);
    /// assert_eq!(v, &[2, 4]);
    /// ```
    ///
    /// The length remains capped, and will stop removing elements once it is reached:
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2, 3, 4, 5]).unwrap();
    /// v.capped_retain(|_| false); // try to remove everything
    /// assert_eq!(v, &[4, 5]); // the last two elements remain
    /// ```
    pub fn capped_retain<F>(&mut self, mut f: F)
    where
        F: FnMut(&T) -> bool,
    {
        let mut allowed_to_remove = self.len() - MINIMUM_SIZE;

        if allowed_to_remove == 0 {
            return;
        }

        self.0.retain(|e| {
            let remove = allowed_to_remove != 0 && !f(e);

            if remove {
                allowed_to_remove -= 1;
            }

            !remove
        });
    }

    /// Retain only the elements specified by the predicate.
    ///
    /// This will remove all elements for which `f` returns `false` from the collection. The
    /// closure will be called with each element starting from the beginning.
    ///
    /// If the length after the removal operations is still greater than the minimum size, the
    /// collection is returned in the `Ok()` variant. If it is less than the minimum size, the
    /// collection is degraded to a plain [`Vec`] and return in the `Err(_)` variant.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2, 3, 4, 5]).unwrap();
    /// let v = v.try_retain(|&e| e % 2 == 0);
    /// assert_eq!(v, Ok(MinSizedVec::from([2, 4])));
    /// ```
    ///
    /// The length remains capped, and will stop removing elements once it is reached:
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2, 3, 4, 5]).unwrap();
    /// let v = v.try_retain(|_| false); // try to remove everything
    /// assert_eq!(v, Err(vec![])); // a plain empty Vec remains
    /// ```
    pub fn try_retain<F>(mut self, f: F) -> Result<Self, Vec<T>>
    where
        F: FnMut(&T) -> bool,
    {
        self.0.retain(f);

        if self.0.len() >= MINIMUM_SIZE {
            Ok(self)
        } else {
            Err(self.0)
        }
    }

    /// Try to change the minimum size of the collection to `NEW`.
    ///
    /// This will inspect the current **runtime** length of the collection. If it is greater than
    /// or equal to `NEW`, a successful [`Result`] containing a collection with the updated minimum
    /// size is returned. If it is smaller, the original collection is returned in an `Err`
    /// variant.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2, 3, 4, 5]).unwrap();
    ///
    /// assert!(v.clone().change_minimum_size::<5>().is_ok());
    /// assert!(v.clone().change_minimum_size::<6>().is_err());
    /// ```
    pub fn change_minimum_size<const NEW: usize>(self) -> Result<MinSizedVec<T, NEW>, Self> {
        if self.len() >= NEW {
            Ok(MinSizedVec(self.0))
        } else {
            Err(self)
        }
    }

    /// Returns the number of elements the collection can hold without reallocating.
    pub fn capacity(&self) -> usize {
        self.0.capacity()
    }

    /// Returns the entire collection as a slice.
    fn as_slice(&self) -> &[T] {
        self
    }

    /// Returns a fixed-size array of the start of the collection.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2, 3]).unwrap();
    ///
    /// assert_eq!(*v.guaranteed_head(), [1, 2]);
    /// ```
    pub fn guaranteed_head(&self) -> &[T; MINIMUM_SIZE] {
        self.0[..MINIMUM_SIZE].try_into().unwrap()
    }

    /// Returns a fixed-size array of the end of the collection.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let v: MinSizedVec<_, 2> = MinSizedVec::new(vec![1, 2, 3]).unwrap();
    ///
    /// assert_eq!(*v.guaranteed_tail(), [2, 3]);
    /// ```
    pub fn guaranteed_tail(&self) -> &[T; MINIMUM_SIZE] {
        self.0[(self.len() - MINIMUM_SIZE)..].try_into().unwrap()
    }
}

/// **NOTE**: This impl block contains methods that are available if the minimum size is greater
/// than 0.
impl<T, const MINIMUM_SIZE: usize> MinSizedVec<T, MINIMUM_SIZE>
where
    MinSizedVec<T, MINIMUM_SIZE>: NotEmpty,
{
    /// Returns a mutable reference to the first element.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v = MinSizedVec::from([1, 2]);
    ///
    /// let first = v.first_mut();
    /// assert_eq!(*first, 1);
    ///
    /// *first = 3;
    /// assert_eq!(v, &[3, 2]);
    /// ```
    pub fn first_mut(&mut self) -> &mut T {
        self.0.first_mut().unwrap()
    }

    /// Returns a mutable reference to the last element.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v = MinSizedVec::from([1, 2]);
    ///
    /// let last = v.last_mut();
    /// assert_eq!(*last, 2);
    ///
    /// *last = 3;
    /// assert_eq!(v, &[1, 3]);
    /// ```
    pub fn last_mut(&mut self) -> &mut T {
        self.0.last_mut().unwrap()
    }

    /// Returns a reference to the first element.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v = MinSizedVec::from([1, 2]);
    ///
    /// let first = v.first();
    /// assert_eq!(*first, 1);
    /// ```
    pub fn first(&self) -> &T {
        self.0.first().unwrap()
    }

    /// Returns a reference to the last element.
    ///
    /// # Examples
    ///
    /// ```
    /// # use minsize::MinSizedVec;
    /// let mut v = MinSizedVec::from([1, 2]);
    ///
    /// let last = v.last();
    /// assert_eq!(*last, 2);
    /// ```
    pub fn last(&self) -> &T {
        self.0.last().unwrap()
    }
}

impl<T, const N: usize> fmt::Debug for MinSizedVec<T, N>
where
    T: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl<T, const N: usize> Default for MinSizedVec<T, N>
where
    T: Default,
{
    /// Creates a [`MinSizedVec`] filled to its minimum capacity with the default value for the
    /// contained type.
    fn default() -> Self {
        let mut vec = Vec::new();
        vec.resize_with(N, T::default);
        Self(vec)
    }
}

impl<T, const N: usize> Deref for MinSizedVec<T, N> {
    type Target = [T];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T, const N: usize> DerefMut for MinSizedVec<T, N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T, I, const N: usize> Index<I> for MinSizedVec<T, N>
where
    I: SliceIndex<[T]>,
{
    type Output = <I as SliceIndex<[T]>>::Output;

    fn index(&self, index: I) -> &Self::Output {
        self.0.index(index)
    }
}

impl<T, I, const N: usize> IndexMut<I> for MinSizedVec<T, N>
where
    I: SliceIndex<[T]>,
{
    fn index_mut(&mut self, index: I) -> &mut Self::Output {
        self.0.index_mut(index)
    }
}

impl<T, U, const A: usize, const B: usize> PartialEq<MinSizedVec<U, B>> for MinSizedVec<T, A>
where
    T: PartialEq<U>,
{
    fn eq(&self, other: &MinSizedVec<U, B>) -> bool {
        self.as_slice() == other.as_slice()
    }
}

impl<T, U, const N: usize> PartialEq<[U]> for MinSizedVec<T, N>
where
    T: PartialEq<U>,
{
    fn eq(&self, other: &[U]) -> bool {
        self.as_slice() == other
    }
}

impl<'a, T, U, const N: usize> PartialEq<&'a [U]> for MinSizedVec<T, N>
where
    T: PartialEq<U>,
{
    fn eq(&self, other: &&'a [U]) -> bool {
        self.as_slice() == *other
    }
}

impl<T, U, const A: usize, const B: usize> PartialEq<[U; B]> for MinSizedVec<T, A>
where
    T: PartialEq<U>,
{
    fn eq(&self, other: &[U; B]) -> bool {
        self.as_slice() == other
    }
}

impl<'a, T, U, const A: usize, const B: usize> PartialEq<&'a [U; B]> for MinSizedVec<T, A>
where
    T: PartialEq<U>,
{
    fn eq(&self, other: &&'a [U; B]) -> bool {
        self.as_slice() == *other
    }
}

impl<T, const A: usize, const B: usize> PartialOrd<MinSizedVec<T, B>> for MinSizedVec<T, A>
where
    T: PartialOrd,
{
    fn partial_cmp(&self, other: &MinSizedVec<T, B>) -> Option<cmp::Ordering> {
        self.as_slice().partial_cmp(other)
    }
}

impl<T, const N: usize> AsRef<[T]> for MinSizedVec<T, N> {
    fn as_ref(&self) -> &[T] {
        self
    }
}

impl<T, const N: usize> AsMut<[T]> for MinSizedVec<T, N> {
    fn as_mut(&mut self) -> &mut [T] {
        self
    }
}

impl<T, const N: usize> IntoIterator for MinSizedVec<T, N> {
    type Item = T;

    type IntoIter = IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a, T, const N: usize> IntoIterator for &'a MinSizedVec<T, N> {
    type Item = &'a T;

    type IntoIter = SliceIter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T, const N: usize> IntoIterator for &'a mut MinSizedVec<T, N> {
    type Item = &'a mut T;

    type IntoIter = SliceIterMut<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl<T, const N: usize> Extend<T> for MinSizedVec<T, N> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        self.0.extend(iter);
    }
}

impl<T, const N: usize> From<[T; N]> for MinSizedVec<T, N> {
    fn from(val: [T; N]) -> Self {
        let mut vec = Vec::new();
        vec.extend(val);
        MinSizedVec(vec)
    }
}

impl<T, const N: usize> TryFrom<Vec<T>> for MinSizedVec<T, N> {
    type Error = Vec<T>;

    fn try_from(value: Vec<T>) -> Result<Self, Self::Error> {
        if value.len() >= N {
            Ok(Self(value))
        } else {
            Err(value)
        }
    }
}

#[cfg(feature = "arbitrary")]
impl<'a, T, const N: usize> arbitrary::Arbitrary<'a> for MinSizedVec<T, N>
where
    T: arbitrary::Arbitrary<'a>,
{
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        // Generate initial minimum number of elements
        let start = u.arbitrary::<[T; N]>()?;
        let mut out = MinSizedVec::from(start);

        // Optionally extend with more
        let additional = u.arbitrary_len::<T>()?;
        for _ in 0..additional {
            out.push(u.arbitrary()?);
        }

        Ok(out)
    }

    fn size_hint(depth: usize) -> (usize, Option<usize>) {
        arbitrary::size_hint::recursion_guard(depth, |depth| {
            arbitrary::size_hint::and(
                <[T; N] as arbitrary::Arbitrary>::size_hint(depth),
                <Vec<T> as arbitrary::Arbitrary>::size_hint(depth),
            )
        })
    }
}

#[cfg(any(feature = "serde", test))]
mod serde_impl {
    use super::*;
    use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};

    impl<T, const N: usize> Serialize for MinSizedVec<T, N>
    where
        T: Serialize,
    {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            serializer.collect_seq(self)
        }
    }

    impl<'de, T, const N: usize> Deserialize<'de> for MinSizedVec<T, N>
    where
        T: Deserialize<'de>,
    {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            let v = <Vec<T>>::deserialize(deserializer)?;

            if v.len() >= N {
                Ok(Self(v))
            } else {
                Err(<D::Error>::custom(format!(
                    "expected at least {} elements, found only {}",
                    N,
                    v.len()
                )))
            }
        }
    }
}

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

    #[test]
    fn serde_serialize() {
        let serialized = serde_json::to_string(&MinSizedVec::from([1, 2, 3])).unwrap();
        assert_eq!(serialized, "[1,2,3]");
    }

    #[test]
    fn serde_deserialize() {
        let v = serde_json::from_str::<MinSizedVec<i32, 3>>("[1,2,3]").unwrap();
        assert_eq!(v, &[1, 2, 3]);

        let v = serde_json::from_str::<MinSizedVec<i32, 3>>("[1,2]");
        assert!(v.is_err());
    }
}