vecmin 0.1.0

Provides a `VecMin` and `VecOne` newtype wrapper around `Vec` that enforces a minimum length at compile time.
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
//! Implementation of the [`VecMin`] and [`VecOne`] newtypes.

use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::collections::TryReserveError;
use alloc::vec::{self, Vec};
use core::borrow::{Borrow, BorrowMut};
use core::error::Error;
use core::fmt::{self, Debug, Display, Formatter};
use core::iter::repeat_with;
use core::mem::MaybeUninit;
use core::ops::{Deref, DerefMut, RangeBounds};
use core::slice;

use crate::{ModifyError, slice_range};

/// A [`VecMin`] with a minimum length of 1.
pub type VecOne<T> = VecMin<T, 1>;

/// A vector with a minimum length of `M`.
///
/// Most methods of `Vec` are available on `VecMin` except those that reduce the length of the vector an unknown amount.
/// Methods that reduce the length of the vector by a known amount (e.g. `remove`, `truncate`) are available on `VecMin`
/// but return an error if the operation would reduce the length of the vector below `M`.
#[repr(transparent)]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct VecMin<T, const M: usize> {
    vec: Vec<T>,
}

// --- Custom ---
impl<T, const M: usize> VecMin<T, M> {
    /// Assertion that that the length of the vector is at least `M`.
    #[inline]
    #[track_caller]
    pub const fn assert_invariant(&self) {
        assert!(self.vec.len() >= M);
    }

    /// Debug assertion that that the length of the vector is at least `M`.
    #[inline]
    #[track_caller]
    pub const fn debug_assert_invariant(&self) {
        debug_assert!(self.vec.len() >= M);
    }

    /// Returns the minimum length of the vector.
    #[inline]
    pub const fn minimum(&self) -> usize {
        M
    }

    /// Returns `true` if the length of the vector is equal to the minimum length `M`.
    #[inline]
    pub const fn is_minimum(&self) -> bool {
        self.vec.len() == M
    }

    /// Returns a slice to the first `M` elements of the vector, which are guaranteed to exist.
    #[inline]
    pub const fn min_slice(&self) -> &[T; M] {
        self.split_at_min().0
    }

    /// Returns a mutable slice to the first `M` elements of the vector, which are guaranteed to exist.
    #[inline]
    pub const fn min_slice_mut(&mut self) -> &mut [T; M] {
        self.split_at_min_mut().0
    }

    /// Returns a tuple of a slice to the first `M` elements of the vector, which are guaranteed to exist, and a slice to the remaining elements of the vector.
    #[inline]
    pub const fn split_at_min(&self) -> (&[T; M], &[T]) {
        self.debug_assert_invariant();

        let (min, extra) = unsafe { self.vec.as_slice().split_at_unchecked(M) };
        let min = unsafe { &*(min.as_ptr() as *const [T; M]) };
        (min, extra)
    }

    /// Returns a tuple of a mutable slice to the first `M` elements of the vector, which are guaranteed to exist, and a mutable slice to the remaining elements of the vector.
    #[inline]
    pub const fn split_at_min_mut(&mut self) -> (&mut [T; M], &mut [T]) {
        self.debug_assert_invariant();

        let (min, extra) = unsafe { self.vec.as_mut_slice().split_at_mut_unchecked(M) };
        let min = unsafe { &mut *(min.as_mut_ptr() as *mut [T; M]) };
        (min, extra)
    }
}

// --- Constructors, Convertors, and Destructors ---
/// A vector that is too short to be a valid `VecMin` returned as an error in a constructor.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ConstructError<T, const M: usize>(pub Vec<T>);

impl<T: Debug, const M: usize> Display for ConstructError<T, M> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Length {} of {:?} is less than the minimum {}",
            self.0.len(),
            self.0,
            M
        )
    }
}

impl<T: Debug, const M: usize> Error for ConstructError<T, M> {}

impl<T, const M: usize> VecMin<T, M> {
    /// Creates a new `VecMin` from a `Vec`
    ///
    /// # Safety
    /// - The length of the `Vec` must be at least `M`.
    #[inline]
    pub const unsafe fn from_vec_unchecked(vec: Vec<T>) -> Self {
        Self { vec }
    }

    /// Creates a new `VecMin` from a `Vec`, returning an error if the length of the provided `Vec` is less than `M`.
    #[inline]
    pub const fn try_from_vec(vec: Vec<T>) -> Result<Self, ConstructError<T, M>> {
        if vec.len() >= M {
            // Safety: We just checked that the length was at least `M`.
            Ok(unsafe { Self::from_vec_unchecked(vec) })
        } else {
            Err(ConstructError(vec))
        }
    }

    /// Creates a new `VecMin` from anything that can be converted into a `Vec`, returning an error if the length of the provided `Vec` is less than `M`.
    #[inline]
    pub fn try_new(vec: impl Into<Vec<T>>) -> Result<Self, ConstructError<T, M>> {
        Self::try_from_vec(vec.into())
    }

    /// Creates a new `VecMin` from an array containing the minimum elements.
    #[inline]
    pub fn from_array(array: [T; M]) -> Self {
        // Safety: An array of length `M` is guaranteed to have a length of at least `M`.
        unsafe { Self::from_vec_unchecked(array.into()) }
    }

    /// Creates a new `VecMin` from an iterator, returning an error if the length of the collected `Vec` is less than `M`.
    #[inline]
    pub fn collect(iter: impl IntoIterator<Item = T>) -> Result<Self, ConstructError<T, M>> {
        let iter = iter.into_iter();
        let (low, high) = iter.size_hint();

        Self::collect_with_capacity(iter, high.unwrap_or(low).max(M))
    }

    /// Creates a new `VecMin` from an iterator, returning an error if the length of the collected `Vec` is less than `M`.
    /// The provided `capacity` is preallocated into the `Vec`.
    #[inline]
    pub fn collect_with_capacity(
        iter: impl IntoIterator<Item = T>,
        capacity: usize,
    ) -> Result<Self, ConstructError<T, M>> {
        let mut vec = Vec::with_capacity(capacity);
        vec.extend(iter);

        Self::try_new(vec)
    }

    /// Returns the inner `Vec`, consuming the `VecMin`.
    #[inline]
    pub fn into_inner(self) -> Vec<T> {
        self.vec
    }

    /// See [`Vec::into_boxed_slice`].
    #[inline]
    pub fn into_boxed_slice(self) -> Box<[T]> {
        self.vec.into_boxed_slice()
    }

    /// See [`Vec::leak`].
    #[inline]
    pub fn leak(self) -> &'static mut [T] {
        self.vec.leak()
    }
}

impl<T: Default, const M: usize> Default for VecMin<T, M> {
    #[inline]
    fn default() -> Self {
        Self {
            vec: repeat_with(T::default).take(M).collect(),
        }
    }
}

impl<T, const M: usize> TryFrom<Vec<T>> for VecMin<T, M> {
    type Error = ConstructError<T, M>;

    #[inline]
    fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
        Self::try_new(vec)
    }
}

impl<T, const M: usize> From<VecMin<T, M>> for Vec<T> {
    #[inline]
    fn from(vec_min: VecMin<T, M>) -> Self {
        vec_min.vec
    }
}

impl<T, const M: usize> TryFrom<Box<[T]>> for VecMin<T, M> {
    type Error = ConstructError<T, M>;

    #[inline]
    fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
        Self::try_new(boxed_slice)
    }
}

impl<T, const M: usize> From<VecMin<T, M>> for Box<[T]> {
    #[inline]
    fn from(vec_min: VecMin<T, M>) -> Self {
        vec_min.vec.into_boxed_slice()
    }
}

impl<T: Clone, const M: usize> TryFrom<&[T]> for VecMin<T, M> {
    type Error = ConstructError<T, M>;

    #[inline]
    fn try_from(slice: &[T]) -> Result<Self, Self::Error> {
        Self::try_new(slice)
    }
}

impl<T: Clone, const M: usize> TryFrom<&mut [T]> for VecMin<T, M> {
    type Error = ConstructError<T, M>;

    #[inline]
    fn try_from(slice: &mut [T]) -> Result<Self, Self::Error> {
        Self::try_new(slice)
    }
}

impl<T: Clone, const M: usize> TryFrom<Cow<'_, [T]>> for VecMin<T, M> {
    type Error = ConstructError<T, M>;

    #[inline]
    fn try_from(cow: Cow<'_, [T]>) -> Result<Self, Self::Error> {
        Self::try_new(cow)
    }
}

impl<T, const N: usize, const M: usize> TryFrom<[T; N]> for VecMin<T, M> {
    type Error = ConstructError<T, M>;

    #[inline]
    fn try_from(array: [T; N]) -> Result<Self, Self::Error> {
        Self::try_new(array)
    }
}

impl<T: Clone, const N: usize, const M: usize> TryFrom<&[T; N]> for VecMin<T, M> {
    type Error = ConstructError<T, M>;

    #[inline]
    fn try_from(array: &[T; N]) -> Result<Self, Self::Error> {
        Self::try_new(array)
    }
}

impl<T: Clone, const N: usize, const M: usize> TryFrom<&mut [T; N]> for VecMin<T, M> {
    type Error = ConstructError<T, M>;

    #[inline]
    fn try_from(array: &mut [T; N]) -> Result<Self, Self::Error> {
        Self::try_new(array)
    }
}

impl<T, const N: usize, const M: usize> TryFrom<VecMin<T, M>> for [T; N] {
    type Error = VecMin<T, M>;

    #[inline]
    fn try_from(vec_min: VecMin<T, M>) -> Result<[T; N], Self::Error> {
        // Safety: We obtained the original `Vec` from a valid `VecMin`.
        vec_min
            .vec
            .try_into()
            .map_err(|vec| unsafe { VecMin::from_vec_unchecked(vec) })
    }
}

// --- View ---
impl<T, const M: usize> VecMin<T, M> {
    #[inline]
    /// See [`Vec::as_slice`].
    pub const fn as_slice(&self) -> &[T] {
        self.vec.as_slice()
    }

    /// See [`Vec::as_mut_slice`].
    #[inline]
    pub const fn as_mut_slice(&mut self) -> &mut [T] {
        self.vec.as_mut_slice()
    }

    #[inline]
    /// See [`Vec::as_ptr`].
    pub const fn as_ptr(&self) -> *const T {
        self.vec.as_ptr()
    }

    /// See [`Vec::as_mut_ptr`].
    #[inline]
    pub const fn as_mut_ptr(&mut self) -> *mut T {
        self.vec.as_mut_ptr()
    }

    /// See [`Vec::spare_capacity_mut`].
    #[inline]
    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
        self.vec.spare_capacity_mut()
    }
}

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

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.vec.deref()
    }
}

impl<T, const M: usize> DerefMut for VecMin<T, M> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.vec.deref_mut()
    }
}

impl<T, const M: usize> AsRef<[T]> for VecMin<T, M> {
    #[inline]
    fn as_ref(&self) -> &[T] {
        self.vec.as_ref()
    }
}

impl<T, const M: usize> AsMut<[T]> for VecMin<T, M> {
    #[inline]
    fn as_mut(&mut self) -> &mut [T] {
        self.vec.as_mut()
    }
}

impl<T, const M: usize> Borrow<[T]> for VecMin<T, M> {
    #[inline]
    fn borrow(&self) -> &[T] {
        self.vec.borrow()
    }
}

impl<T, const M: usize> BorrowMut<[T]> for VecMin<T, M> {
    #[inline]
    fn borrow_mut(&mut self) -> &mut [T] {
        self.vec.borrow_mut()
    }
}

// --- Iterators ---
impl<T, const M: usize> IntoIterator for VecMin<T, M> {
    type Item = T;
    type IntoIter = vec::IntoIter<T>;

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

impl<'a, T: 'a, const M: usize> IntoIterator for &'a VecMin<T, M> {
    type Item = &'a T;
    type IntoIter = slice::Iter<'a, T>;

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

impl<'a, T: 'a, const M: usize> IntoIterator for &'a mut VecMin<T, M> {
    type Item = &'a mut T;
    type IntoIter = slice::IterMut<'a, T>;

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

// --- Immutable Access ---
impl<T, const M: usize> VecMin<T, M> {
    /// See [`Vec::capacity`].
    #[inline]
    pub const fn capacity(&self) -> usize {
        self.vec.capacity()
    }

    /// See [`Vec::len`].
    #[inline]
    #[allow(clippy::len_without_is_empty)]
    pub const fn len(&self) -> usize {
        self.vec.len()
    }
}

// --- Mutable Access ---

// -- Not Len Decreasing --

// - Capacity -
impl<T, const M: usize> VecMin<T, M> {
    /// See [`Vec::reserve`].
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        self.vec.reserve(additional);
    }

    /// See [`Vec::reserve_exact`].
    #[inline]
    pub fn reserve_exact(&mut self, additional: usize) {
        self.vec.reserve_exact(additional);
    }

    /// See [`Vec::try_reserve`].
    #[inline]
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.vec.try_reserve(additional)
    }

    /// See [`Vec::try_reserve_exact`].
    #[inline]
    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.vec.try_reserve_exact(additional)
    }

    /// See [`Vec::shrink_to_fit`].
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.vec.shrink_to_fit();
    }

    /// See [`Vec::shrink_to`].
    #[inline]
    pub fn shrink_to(&mut self, min_capacity: usize) {
        self.vec.shrink_to(min_capacity);
    }
}

// - Growth -
impl<T, const M: usize> VecMin<T, M> {
    /// See [`Vec::push`].
    #[inline]
    pub fn push(&mut self, item: T) {
        self.vec.push(item);
    }

    /// See [`Vec::insert`].
    #[inline]
    pub fn insert(&mut self, index: usize, element: T) {
        self.vec.insert(index, element);
    }

    /// See [`Vec::append`].
    #[inline]
    pub fn append(&mut self, other: &mut Vec<T>) {
        self.vec.append(other);
    }

    /// See [`Vec::extend_from_slice`].
    #[inline]
    pub fn extend_from_slice(&mut self, other: &[T])
    where
        T: Clone,
    {
        self.vec.extend_from_slice(other);
    }

    /// See [`Vec::extend_from_within`].
    #[inline]
    pub fn extend_from_within<R>(&mut self, range: R)
    where
        R: RangeBounds<usize>,
        T: Clone,
    {
        self.vec.extend_from_within(range);
    }
}

impl<T, const M: usize> Extend<T> for VecMin<T, M> {
    #[inline]
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        self.vec.extend(iter);
    }
}

impl<'a, T: Copy, const M: usize> Extend<&'a T> for VecMin<T, M> {
    #[inline]
    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
        self.vec.extend(iter);
    }
}

// -- Len Decreasing --
impl<T, const M: usize> VecMin<T, M> {
    /// See [`Vec::pop`]. Pops an element from the vector if the length of the vector is greater than `M`, otherwise does nothing and returns `None`.
    #[inline]
    pub fn pop_to_min(&mut self) -> Option<T> {
        if self.vec.len() > M {
            self.vec.pop()
        } else {
            None
        }
    }

    /// See [`Vec::pop_if`]. Pops an element from the vector if the length of the vector is greater than `M` and the provided predicate returns `true`, otherwise does nothing and returns `None`.
    #[inline]
    pub fn pop_to_min_if(&mut self, pred: impl FnOnce(&mut T) -> bool) -> Option<T> {
        if self.vec.len() > M {
            self.vec.pop_if(pred)
        } else {
            None
        }
    }

    /// See [`Vec::remove`]. Returns an error if the operation would reduce the length of the vector below `M`.
    #[inline]
    #[must_use = "this operation may fail"]
    pub fn remove(&mut self, index: usize) -> Result<T, ModifyError<M>> {
        if self.vec.len() > M {
            Ok(self.vec.remove(index))
        } else {
            Err(ModifyError)
        }
    }

    /// See [`Vec::swap_remove`]. Returns an error if the operation would reduce the length of the vector below `M`.
    #[inline]
    #[must_use = "this operation may fail"]
    pub fn swap_remove(&mut self, index: usize) -> Result<T, ModifyError<M>> {
        if self.vec.len() > M {
            Ok(self.vec.swap_remove(index))
        } else {
            Err(ModifyError)
        }
    }

    /// See [`Vec::truncate`]. Returns an error if the operation would reduce the length of the vector below `M`.
    #[inline]
    #[must_use = "this operation may fail"]
    pub fn truncate(&mut self, len: usize) -> Result<(), ModifyError<M>> {
        if len >= M {
            self.vec.truncate(len);
            Ok(())
        } else {
            Err(ModifyError)
        }
    }

    /// See [`Vec::truncate`]. Truncates the vector to `len` if `len` is greater than or equal to `M`, otherwise truncates the vector to `M`.
    #[inline]
    pub fn truncate_or_min(&mut self, len: usize) {
        self.vec.truncate(len.max(M))
    }

    /// See [`Vec::truncate`]. Truncates the vector to `M`.
    #[inline]
    pub fn truncate_to_min(&mut self) {
        self.vec.truncate(M);
    }

    /// See [`Vec::resize`]. Returns an error if the operation would reduce the length of the vector below `M`.
    #[inline]
    #[must_use = "this operation may fail"]
    pub fn resize(&mut self, new_len: usize, value: T) -> Result<(), ModifyError<M>>
    where
        T: Clone,
    {
        if new_len >= M {
            self.vec.resize(new_len, value);
            Ok(())
        } else {
            Err(ModifyError)
        }
    }

    /// See [`Vec::resize`]. Resizes the vector to `new_len` if `new_len` is greater than or equal to `M`, otherwise resizes the vector to `M`.
    #[inline]
    pub fn resize_or_min(&mut self, new_len: usize, value: T)
    where
        T: Clone,
    {
        self.vec.resize(new_len.max(M), value);
    }

    /// See [`Vec::resize_with`]. Returns an error if the operation would reduce the length of the vector below `M`.
    #[inline]
    #[must_use = "this operation may fail"]
    pub fn resize_with<F>(&mut self, new_len: usize, generator: F) -> Result<(), ModifyError<M>>
    where
        F: FnMut() -> T,
    {
        if new_len >= M {
            self.vec.resize_with(new_len, generator);
            Ok(())
        } else {
            Err(ModifyError)
        }
    }

    /// See [`Vec::resize_with`]. Resizes the vector to `new_len` if `new_len` is greater than or equal to `M`, otherwise resizes the vector to `M`.
    #[inline]
    pub fn resize_or_min_with<F>(&mut self, new_len: usize, generator: F)
    where
        F: FnMut() -> T,
    {
        self.vec.resize_with(new_len.max(M), generator);
    }

    /// See [`Vec::drain`]. Returns an error if the operation would reduce the length of the vector below `M`.
    #[must_use = "this operation may fail"]
    pub fn drain<R>(&mut self, range: R) -> Result<vec::Drain<'_, T>, ModifyError<M>>
    where
        R: RangeBounds<usize>,
    {
        let drain_len = slice_range(&range, ..self.vec.len()).len();
        let final_len = self.vec.len() - drain_len;

        if final_len >= M {
            Ok(self.vec.drain(range))
        } else {
            Err(ModifyError)
        }
    }

    /// See [`Vec::split_off`]. Returns an error if the operation would reduce the length of the vector below `M`.
    #[inline]
    #[must_use = "this operation may fail"]
    pub fn split_off(&mut self, at: usize) -> Result<Vec<T>, ModifyError<M>> {
        if at >= M {
            Ok(self.vec.split_off(at))
        } else {
            Err(ModifyError)
        }
    }
}