kernel/alloc/
kvec.rs

1// SPDX-License-Identifier: GPL-2.0
2
3//! Implementation of [`Vec`].
4
5use super::{
6    allocator::{KVmalloc, Kmalloc, Vmalloc},
7    layout::ArrayLayout,
8    AllocError, Allocator, Box, Flags,
9};
10use core::{
11    fmt,
12    marker::PhantomData,
13    mem::{ManuallyDrop, MaybeUninit},
14    ops::Deref,
15    ops::DerefMut,
16    ops::Index,
17    ops::IndexMut,
18    ptr,
19    ptr::NonNull,
20    slice,
21    slice::SliceIndex,
22};
23
24/// Create a [`KVec`] containing the arguments.
25///
26/// New memory is allocated with `GFP_KERNEL`.
27///
28/// # Examples
29///
30/// ```
31/// let mut v = kernel::kvec![];
32/// v.push(1, GFP_KERNEL)?;
33/// assert_eq!(v, [1]);
34///
35/// let mut v = kernel::kvec![1; 3]?;
36/// v.push(4, GFP_KERNEL)?;
37/// assert_eq!(v, [1, 1, 1, 4]);
38///
39/// let mut v = kernel::kvec![1, 2, 3]?;
40/// v.push(4, GFP_KERNEL)?;
41/// assert_eq!(v, [1, 2, 3, 4]);
42///
43/// # Ok::<(), Error>(())
44/// ```
45#[macro_export]
46macro_rules! kvec {
47    () => (
48        $crate::alloc::KVec::new()
49    );
50    ($elem:expr; $n:expr) => (
51        $crate::alloc::KVec::from_elem($elem, $n, GFP_KERNEL)
52    );
53    ($($x:expr),+ $(,)?) => (
54        match $crate::alloc::KBox::new_uninit(GFP_KERNEL) {
55            Ok(b) => Ok($crate::alloc::KVec::from($crate::alloc::KBox::write(b, [$($x),+]))),
56            Err(e) => Err(e),
57        }
58    );
59}
60
61/// The kernel's [`Vec`] type.
62///
63/// A contiguous growable array type with contents allocated with the kernel's allocators (e.g.
64/// [`Kmalloc`], [`Vmalloc`] or [`KVmalloc`]), written `Vec<T, A>`.
65///
66/// For non-zero-sized values, a [`Vec`] will use the given allocator `A` for its allocation. For
67/// the most common allocators the type aliases [`KVec`], [`VVec`] and [`KVVec`] exist.
68///
69/// For zero-sized types the [`Vec`]'s pointer must be `dangling_mut::<T>`; no memory is allocated.
70///
71/// Generally, [`Vec`] consists of a pointer that represents the vector's backing buffer, the
72/// capacity of the vector (the number of elements that currently fit into the vector), its length
73/// (the number of elements that are currently stored in the vector) and the `Allocator` type used
74/// to allocate (and free) the backing buffer.
75///
76/// A [`Vec`] can be deconstructed into and (re-)constructed from its previously named raw parts
77/// and manually modified.
78///
79/// [`Vec`]'s backing buffer gets, if required, automatically increased (re-allocated) when elements
80/// are added to the vector.
81///
82/// # Invariants
83///
84/// - `self.ptr` is always properly aligned and either points to memory allocated with `A` or, for
85///   zero-sized types, is a dangling, well aligned pointer.
86///
87/// - `self.len` always represents the exact number of elements stored in the vector.
88///
89/// - `self.layout` represents the absolute number of elements that can be stored within the vector
90///   without re-allocation. For ZSTs `self.layout`'s capacity is zero. However, it is legal for the
91///   backing buffer to be larger than `layout`.
92///
93/// - `self.len()` is always less than or equal to `self.capacity()`.
94///
95/// - The `Allocator` type `A` of the vector is the exact same `Allocator` type the backing buffer
96///   was allocated with (and must be freed with).
97pub struct Vec<T, A: Allocator> {
98    ptr: NonNull<T>,
99    /// Represents the actual buffer size as `cap` times `size_of::<T>` bytes.
100    ///
101    /// Note: This isn't quite the same as `Self::capacity`, which in contrast returns the number of
102    /// elements we can still store without reallocating.
103    layout: ArrayLayout<T>,
104    len: usize,
105    _p: PhantomData<A>,
106}
107
108/// Type alias for [`Vec`] with a [`Kmalloc`] allocator.
109///
110/// # Examples
111///
112/// ```
113/// let mut v = KVec::new();
114/// v.push(1, GFP_KERNEL)?;
115/// assert_eq!(&v, &[1]);
116///
117/// # Ok::<(), Error>(())
118/// ```
119pub type KVec<T> = Vec<T, Kmalloc>;
120
121/// Type alias for [`Vec`] with a [`Vmalloc`] allocator.
122///
123/// # Examples
124///
125/// ```
126/// let mut v = VVec::new();
127/// v.push(1, GFP_KERNEL)?;
128/// assert_eq!(&v, &[1]);
129///
130/// # Ok::<(), Error>(())
131/// ```
132pub type VVec<T> = Vec<T, Vmalloc>;
133
134/// Type alias for [`Vec`] with a [`KVmalloc`] allocator.
135///
136/// # Examples
137///
138/// ```
139/// let mut v = KVVec::new();
140/// v.push(1, GFP_KERNEL)?;
141/// assert_eq!(&v, &[1]);
142///
143/// # Ok::<(), Error>(())
144/// ```
145pub type KVVec<T> = Vec<T, KVmalloc>;
146
147// SAFETY: `Vec` is `Send` if `T` is `Send` because `Vec` owns its elements.
148unsafe impl<T, A> Send for Vec<T, A>
149where
150    T: Send,
151    A: Allocator,
152{
153}
154
155// SAFETY: `Vec` is `Sync` if `T` is `Sync` because `Vec` owns its elements.
156unsafe impl<T, A> Sync for Vec<T, A>
157where
158    T: Sync,
159    A: Allocator,
160{
161}
162
163impl<T, A> Vec<T, A>
164where
165    A: Allocator,
166{
167    #[inline]
168    const fn is_zst() -> bool {
169        core::mem::size_of::<T>() == 0
170    }
171
172    /// Returns the number of elements that can be stored within the vector without allocating
173    /// additional memory.
174    pub fn capacity(&self) -> usize {
175        if const { Self::is_zst() } {
176            usize::MAX
177        } else {
178            self.layout.len()
179        }
180    }
181
182    /// Returns the number of elements stored within the vector.
183    #[inline]
184    pub fn len(&self) -> usize {
185        self.len
186    }
187
188    /// Increments `self.len` by `additional`.
189    ///
190    /// # Safety
191    ///
192    /// - `additional` must be less than or equal to `self.capacity - self.len`.
193    /// - All elements within the interval [`self.len`,`self.len + additional`) must be initialized.
194    #[inline]
195    pub unsafe fn inc_len(&mut self, additional: usize) {
196        // Guaranteed by the type invariant to never underflow.
197        debug_assert!(additional <= self.capacity() - self.len());
198        // INVARIANT: By the safety requirements of this method this represents the exact number of
199        // elements stored within `self`.
200        self.len += additional;
201    }
202
203    /// Decreases `self.len` by `count`.
204    ///
205    /// Returns a mutable slice to the elements forgotten by the vector. It is the caller's
206    /// responsibility to drop these elements if necessary.
207    ///
208    /// # Safety
209    ///
210    /// - `count` must be less than or equal to `self.len`.
211    unsafe fn dec_len(&mut self, count: usize) -> &mut [T] {
212        debug_assert!(count <= self.len());
213        // INVARIANT: We relinquish ownership of the elements within the range `[self.len - count,
214        // self.len)`, hence the updated value of `set.len` represents the exact number of elements
215        // stored within `self`.
216        self.len -= count;
217        // SAFETY: The memory after `self.len()` is guaranteed to contain `count` initialized
218        // elements of type `T`.
219        unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().add(self.len), count) }
220    }
221
222    /// Returns a slice of the entire vector.
223    #[inline]
224    pub fn as_slice(&self) -> &[T] {
225        self
226    }
227
228    /// Returns a mutable slice of the entire vector.
229    #[inline]
230    pub fn as_mut_slice(&mut self) -> &mut [T] {
231        self
232    }
233
234    /// Returns a mutable raw pointer to the vector's backing buffer, or, if `T` is a ZST, a
235    /// dangling raw pointer.
236    #[inline]
237    pub fn as_mut_ptr(&mut self) -> *mut T {
238        self.ptr.as_ptr()
239    }
240
241    /// Returns a raw pointer to the vector's backing buffer, or, if `T` is a ZST, a dangling raw
242    /// pointer.
243    #[inline]
244    pub fn as_ptr(&self) -> *const T {
245        self.ptr.as_ptr()
246    }
247
248    /// Returns `true` if the vector contains no elements, `false` otherwise.
249    ///
250    /// # Examples
251    ///
252    /// ```
253    /// let mut v = KVec::new();
254    /// assert!(v.is_empty());
255    ///
256    /// v.push(1, GFP_KERNEL);
257    /// assert!(!v.is_empty());
258    /// ```
259    #[inline]
260    pub fn is_empty(&self) -> bool {
261        self.len() == 0
262    }
263
264    /// Creates a new, empty `Vec<T, A>`.
265    ///
266    /// This method does not allocate by itself.
267    #[inline]
268    pub const fn new() -> Self {
269        // INVARIANT: Since this is a new, empty `Vec` with no backing memory yet,
270        // - `ptr` is a properly aligned dangling pointer for type `T`,
271        // - `layout` is an empty `ArrayLayout` (zero capacity)
272        // - `len` is zero, since no elements can be or have been stored,
273        // - `A` is always valid.
274        Self {
275            ptr: NonNull::dangling(),
276            layout: ArrayLayout::empty(),
277            len: 0,
278            _p: PhantomData::<A>,
279        }
280    }
281
282    /// Returns a slice of `MaybeUninit<T>` for the remaining spare capacity of the vector.
283    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
284        // SAFETY:
285        // - `self.len` is smaller than `self.capacity` by the type invariant and hence, the
286        //   resulting pointer is guaranteed to be part of the same allocated object.
287        // - `self.len` can not overflow `isize`.
288        let ptr = unsafe { self.as_mut_ptr().add(self.len) } as *mut MaybeUninit<T>;
289
290        // SAFETY: The memory between `self.len` and `self.capacity` is guaranteed to be allocated
291        // and valid, but uninitialized.
292        unsafe { slice::from_raw_parts_mut(ptr, self.capacity() - self.len) }
293    }
294
295    /// Appends an element to the back of the [`Vec`] instance.
296    ///
297    /// # Examples
298    ///
299    /// ```
300    /// let mut v = KVec::new();
301    /// v.push(1, GFP_KERNEL)?;
302    /// assert_eq!(&v, &[1]);
303    ///
304    /// v.push(2, GFP_KERNEL)?;
305    /// assert_eq!(&v, &[1, 2]);
306    /// # Ok::<(), Error>(())
307    /// ```
308    pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
309        self.reserve(1, flags)?;
310
311        let spare = self.spare_capacity_mut();
312
313        // SAFETY: The call to `reserve` was successful so the spare capacity is at least 1.
314        unsafe { spare.get_unchecked_mut(0) }.write(v);
315
316        // SAFETY: We just initialised the first spare entry, so it is safe to increase the length
317        // by 1. We also know that the new length is <= capacity because of the previous call to
318        // `reserve` above.
319        unsafe { self.inc_len(1) };
320        Ok(())
321    }
322
323    /// Creates a new [`Vec`] instance with at least the given capacity.
324    ///
325    /// # Examples
326    ///
327    /// ```
328    /// let v = KVec::<u32>::with_capacity(20, GFP_KERNEL)?;
329    ///
330    /// assert!(v.capacity() >= 20);
331    /// # Ok::<(), Error>(())
332    /// ```
333    pub fn with_capacity(capacity: usize, flags: Flags) -> Result<Self, AllocError> {
334        let mut v = Vec::new();
335
336        v.reserve(capacity, flags)?;
337
338        Ok(v)
339    }
340
341    /// Creates a `Vec<T, A>` from a pointer, a length and a capacity using the allocator `A`.
342    ///
343    /// # Examples
344    ///
345    /// ```
346    /// let mut v = kernel::kvec![1, 2, 3]?;
347    /// v.reserve(1, GFP_KERNEL)?;
348    ///
349    /// let (mut ptr, mut len, cap) = v.into_raw_parts();
350    ///
351    /// // SAFETY: We've just reserved memory for another element.
352    /// unsafe { ptr.add(len).write(4) };
353    /// len += 1;
354    ///
355    /// // SAFETY: We only wrote an additional element at the end of the `KVec`'s buffer and
356    /// // correspondingly increased the length of the `KVec` by one. Otherwise, we construct it
357    /// // from the exact same raw parts.
358    /// let v = unsafe { KVec::from_raw_parts(ptr, len, cap) };
359    ///
360    /// assert_eq!(v, [1, 2, 3, 4]);
361    ///
362    /// # Ok::<(), Error>(())
363    /// ```
364    ///
365    /// # Safety
366    ///
367    /// If `T` is a ZST:
368    ///
369    /// - `ptr` must be a dangling, well aligned pointer.
370    ///
371    /// Otherwise:
372    ///
373    /// - `ptr` must have been allocated with the allocator `A`.
374    /// - `ptr` must satisfy or exceed the alignment requirements of `T`.
375    /// - `ptr` must point to memory with a size of at least `size_of::<T>() * capacity` bytes.
376    /// - The allocated size in bytes must not be larger than `isize::MAX`.
377    /// - `length` must be less than or equal to `capacity`.
378    /// - The first `length` elements must be initialized values of type `T`.
379    ///
380    /// It is also valid to create an empty `Vec` passing a dangling pointer for `ptr` and zero for
381    /// `cap` and `len`.
382    pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
383        let layout = if Self::is_zst() {
384            ArrayLayout::empty()
385        } else {
386            // SAFETY: By the safety requirements of this function, `capacity * size_of::<T>()` is
387            // smaller than `isize::MAX`.
388            unsafe { ArrayLayout::new_unchecked(capacity) }
389        };
390
391        // INVARIANT: For ZSTs, we store an empty `ArrayLayout`, all other type invariants are
392        // covered by the safety requirements of this function.
393        Self {
394            // SAFETY: By the safety requirements, `ptr` is either dangling or pointing to a valid
395            // memory allocation, allocated with `A`.
396            ptr: unsafe { NonNull::new_unchecked(ptr) },
397            layout,
398            len: length,
399            _p: PhantomData::<A>,
400        }
401    }
402
403    /// Consumes the `Vec<T, A>` and returns its raw components `pointer`, `length` and `capacity`.
404    ///
405    /// This will not run the destructor of the contained elements and for non-ZSTs the allocation
406    /// will stay alive indefinitely. Use [`Vec::from_raw_parts`] to recover the [`Vec`], drop the
407    /// elements and free the allocation, if any.
408    pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
409        let mut me = ManuallyDrop::new(self);
410        let len = me.len();
411        let capacity = me.capacity();
412        let ptr = me.as_mut_ptr();
413        (ptr, len, capacity)
414    }
415
416    /// Ensures that the capacity exceeds the length by at least `additional` elements.
417    ///
418    /// # Examples
419    ///
420    /// ```
421    /// let mut v = KVec::new();
422    /// v.push(1, GFP_KERNEL)?;
423    ///
424    /// v.reserve(10, GFP_KERNEL)?;
425    /// let cap = v.capacity();
426    /// assert!(cap >= 10);
427    ///
428    /// v.reserve(10, GFP_KERNEL)?;
429    /// let new_cap = v.capacity();
430    /// assert_eq!(new_cap, cap);
431    ///
432    /// # Ok::<(), Error>(())
433    /// ```
434    pub fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocError> {
435        let len = self.len();
436        let cap = self.capacity();
437
438        if cap - len >= additional {
439            return Ok(());
440        }
441
442        if Self::is_zst() {
443            // The capacity is already `usize::MAX` for ZSTs, we can't go higher.
444            return Err(AllocError);
445        }
446
447        // We know that `cap <= isize::MAX` because of the type invariants of `Self`. So the
448        // multiplication by two won't overflow.
449        let new_cap = core::cmp::max(cap * 2, len.checked_add(additional).ok_or(AllocError)?);
450        let layout = ArrayLayout::new(new_cap).map_err(|_| AllocError)?;
451
452        // SAFETY:
453        // - `ptr` is valid because it's either `None` or comes from a previous call to
454        //   `A::realloc`.
455        // - `self.layout` matches the `ArrayLayout` of the preceding allocation.
456        let ptr = unsafe {
457            A::realloc(
458                Some(self.ptr.cast()),
459                layout.into(),
460                self.layout.into(),
461                flags,
462            )?
463        };
464
465        // INVARIANT:
466        // - `layout` is some `ArrayLayout::<T>`,
467        // - `ptr` has been created by `A::realloc` from `layout`.
468        self.ptr = ptr.cast();
469        self.layout = layout;
470
471        Ok(())
472    }
473
474    /// Shortens the vector, setting the length to `len` and drops the removed values.
475    /// If `len` is greater than or equal to the current length, this does nothing.
476    ///
477    /// This has no effect on the capacity and will not allocate.
478    ///
479    /// # Examples
480    ///
481    /// ```
482    /// let mut v = kernel::kvec![1, 2, 3]?;
483    /// v.truncate(1);
484    /// assert_eq!(v.len(), 1);
485    /// assert_eq!(&v, &[1]);
486    ///
487    /// # Ok::<(), Error>(())
488    /// ```
489    pub fn truncate(&mut self, len: usize) {
490        if let Some(count) = self.len().checked_sub(len) {
491            // SAFETY: `count` is `self.len() - len` so it is guaranteed to be less than or
492            // equal to `self.len()`.
493            let ptr: *mut [T] = unsafe { self.dec_len(count) };
494
495            // SAFETY: the contract of `dec_len` guarantees that the elements in `ptr` are
496            // valid elements whose ownership has been transferred to the caller.
497            unsafe { ptr::drop_in_place(ptr) };
498        }
499    }
500}
501
502impl<T: Clone, A: Allocator> Vec<T, A> {
503    /// Extend the vector by `n` clones of `value`.
504    pub fn extend_with(&mut self, n: usize, value: T, flags: Flags) -> Result<(), AllocError> {
505        if n == 0 {
506            return Ok(());
507        }
508
509        self.reserve(n, flags)?;
510
511        let spare = self.spare_capacity_mut();
512
513        for item in spare.iter_mut().take(n - 1) {
514            item.write(value.clone());
515        }
516
517        // We can write the last element directly without cloning needlessly.
518        spare[n - 1].write(value);
519
520        // SAFETY:
521        // - `self.len() + n < self.capacity()` due to the call to reserve above,
522        // - the loop and the line above initialized the next `n` elements.
523        unsafe { self.inc_len(n) };
524
525        Ok(())
526    }
527
528    /// Pushes clones of the elements of slice into the [`Vec`] instance.
529    ///
530    /// # Examples
531    ///
532    /// ```
533    /// let mut v = KVec::new();
534    /// v.push(1, GFP_KERNEL)?;
535    ///
536    /// v.extend_from_slice(&[20, 30, 40], GFP_KERNEL)?;
537    /// assert_eq!(&v, &[1, 20, 30, 40]);
538    ///
539    /// v.extend_from_slice(&[50, 60], GFP_KERNEL)?;
540    /// assert_eq!(&v, &[1, 20, 30, 40, 50, 60]);
541    /// # Ok::<(), Error>(())
542    /// ```
543    pub fn extend_from_slice(&mut self, other: &[T], flags: Flags) -> Result<(), AllocError> {
544        self.reserve(other.len(), flags)?;
545        for (slot, item) in core::iter::zip(self.spare_capacity_mut(), other) {
546            slot.write(item.clone());
547        }
548
549        // SAFETY:
550        // - `other.len()` spare entries have just been initialized, so it is safe to increase
551        //   the length by the same number.
552        // - `self.len() + other.len() <= self.capacity()` is guaranteed by the preceding `reserve`
553        //   call.
554        unsafe { self.inc_len(other.len()) };
555        Ok(())
556    }
557
558    /// Create a new `Vec<T, A>` and extend it by `n` clones of `value`.
559    pub fn from_elem(value: T, n: usize, flags: Flags) -> Result<Self, AllocError> {
560        let mut v = Self::with_capacity(n, flags)?;
561
562        v.extend_with(n, value, flags)?;
563
564        Ok(v)
565    }
566
567    /// Resizes the [`Vec`] so that `len` is equal to `new_len`.
568    ///
569    /// If `new_len` is smaller than `len`, the `Vec` is [`Vec::truncate`]d.
570    /// If `new_len` is larger, each new slot is filled with clones of `value`.
571    ///
572    /// # Examples
573    ///
574    /// ```
575    /// let mut v = kernel::kvec![1, 2, 3]?;
576    /// v.resize(1, 42, GFP_KERNEL)?;
577    /// assert_eq!(&v, &[1]);
578    ///
579    /// v.resize(3, 42, GFP_KERNEL)?;
580    /// assert_eq!(&v, &[1, 42, 42]);
581    ///
582    /// # Ok::<(), Error>(())
583    /// ```
584    pub fn resize(&mut self, new_len: usize, value: T, flags: Flags) -> Result<(), AllocError> {
585        match new_len.checked_sub(self.len()) {
586            Some(n) => self.extend_with(n, value, flags),
587            None => {
588                self.truncate(new_len);
589                Ok(())
590            }
591        }
592    }
593}
594
595impl<T, A> Drop for Vec<T, A>
596where
597    A: Allocator,
598{
599    fn drop(&mut self) {
600        // SAFETY: `self.as_mut_ptr` is guaranteed to be valid by the type invariant.
601        unsafe {
602            ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
603                self.as_mut_ptr(),
604                self.len,
605            ))
606        };
607
608        // SAFETY:
609        // - `self.ptr` was previously allocated with `A`.
610        // - `self.layout` matches the `ArrayLayout` of the preceding allocation.
611        unsafe { A::free(self.ptr.cast(), self.layout.into()) };
612    }
613}
614
615impl<T, A, const N: usize> From<Box<[T; N], A>> for Vec<T, A>
616where
617    A: Allocator,
618{
619    fn from(b: Box<[T; N], A>) -> Vec<T, A> {
620        let len = b.len();
621        let ptr = Box::into_raw(b);
622
623        // SAFETY:
624        // - `b` has been allocated with `A`,
625        // - `ptr` fulfills the alignment requirements for `T`,
626        // - `ptr` points to memory with at least a size of `size_of::<T>() * len`,
627        // - all elements within `b` are initialized values of `T`,
628        // - `len` does not exceed `isize::MAX`.
629        unsafe { Vec::from_raw_parts(ptr as _, len, len) }
630    }
631}
632
633impl<T> Default for KVec<T> {
634    #[inline]
635    fn default() -> Self {
636        Self::new()
637    }
638}
639
640impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
641    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
642        fmt::Debug::fmt(&**self, f)
643    }
644}
645
646impl<T, A> Deref for Vec<T, A>
647where
648    A: Allocator,
649{
650    type Target = [T];
651
652    #[inline]
653    fn deref(&self) -> &[T] {
654        // SAFETY: The memory behind `self.as_ptr()` is guaranteed to contain `self.len`
655        // initialized elements of type `T`.
656        unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
657    }
658}
659
660impl<T, A> DerefMut for Vec<T, A>
661where
662    A: Allocator,
663{
664    #[inline]
665    fn deref_mut(&mut self) -> &mut [T] {
666        // SAFETY: The memory behind `self.as_ptr()` is guaranteed to contain `self.len`
667        // initialized elements of type `T`.
668        unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
669    }
670}
671
672impl<T: Eq, A> Eq for Vec<T, A> where A: Allocator {}
673
674impl<T, I: SliceIndex<[T]>, A> Index<I> for Vec<T, A>
675where
676    A: Allocator,
677{
678    type Output = I::Output;
679
680    #[inline]
681    fn index(&self, index: I) -> &Self::Output {
682        Index::index(&**self, index)
683    }
684}
685
686impl<T, I: SliceIndex<[T]>, A> IndexMut<I> for Vec<T, A>
687where
688    A: Allocator,
689{
690    #[inline]
691    fn index_mut(&mut self, index: I) -> &mut Self::Output {
692        IndexMut::index_mut(&mut **self, index)
693    }
694}
695
696macro_rules! impl_slice_eq {
697    ($([$($vars:tt)*] $lhs:ty, $rhs:ty,)*) => {
698        $(
699            impl<T, U, $($vars)*> PartialEq<$rhs> for $lhs
700            where
701                T: PartialEq<U>,
702            {
703                #[inline]
704                fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
705            }
706        )*
707    }
708}
709
710impl_slice_eq! {
711    [A1: Allocator, A2: Allocator] Vec<T, A1>, Vec<U, A2>,
712    [A: Allocator] Vec<T, A>, &[U],
713    [A: Allocator] Vec<T, A>, &mut [U],
714    [A: Allocator] &[T], Vec<U, A>,
715    [A: Allocator] &mut [T], Vec<U, A>,
716    [A: Allocator] Vec<T, A>, [U],
717    [A: Allocator] [T], Vec<U, A>,
718    [A: Allocator, const N: usize] Vec<T, A>, [U; N],
719    [A: Allocator, const N: usize] Vec<T, A>, &[U; N],
720}
721
722impl<'a, T, A> IntoIterator for &'a Vec<T, A>
723where
724    A: Allocator,
725{
726    type Item = &'a T;
727    type IntoIter = slice::Iter<'a, T>;
728
729    fn into_iter(self) -> Self::IntoIter {
730        self.iter()
731    }
732}
733
734impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A>
735where
736    A: Allocator,
737{
738    type Item = &'a mut T;
739    type IntoIter = slice::IterMut<'a, T>;
740
741    fn into_iter(self) -> Self::IntoIter {
742        self.iter_mut()
743    }
744}
745
746/// An [`Iterator`] implementation for [`Vec`] that moves elements out of a vector.
747///
748/// This structure is created by the [`Vec::into_iter`] method on [`Vec`] (provided by the
749/// [`IntoIterator`] trait).
750///
751/// # Examples
752///
753/// ```
754/// let v = kernel::kvec![0, 1, 2]?;
755/// let iter = v.into_iter();
756///
757/// # Ok::<(), Error>(())
758/// ```
759pub struct IntoIter<T, A: Allocator> {
760    ptr: *mut T,
761    buf: NonNull<T>,
762    len: usize,
763    layout: ArrayLayout<T>,
764    _p: PhantomData<A>,
765}
766
767impl<T, A> IntoIter<T, A>
768where
769    A: Allocator,
770{
771    fn into_raw_parts(self) -> (*mut T, NonNull<T>, usize, usize) {
772        let me = ManuallyDrop::new(self);
773        let ptr = me.ptr;
774        let buf = me.buf;
775        let len = me.len;
776        let cap = me.layout.len();
777        (ptr, buf, len, cap)
778    }
779
780    /// Same as `Iterator::collect` but specialized for `Vec`'s `IntoIter`.
781    ///
782    /// # Examples
783    ///
784    /// ```
785    /// let v = kernel::kvec![1, 2, 3]?;
786    /// let mut it = v.into_iter();
787    ///
788    /// assert_eq!(it.next(), Some(1));
789    ///
790    /// let v = it.collect(GFP_KERNEL);
791    /// assert_eq!(v, [2, 3]);
792    ///
793    /// # Ok::<(), Error>(())
794    /// ```
795    ///
796    /// # Implementation details
797    ///
798    /// Currently, we can't implement `FromIterator`. There are a couple of issues with this trait
799    /// in the kernel, namely:
800    ///
801    /// - Rust's specialization feature is unstable. This prevents us to optimize for the special
802    ///   case where `I::IntoIter` equals `Vec`'s `IntoIter` type.
803    /// - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator`
804    ///   doesn't require this type to be `'static`.
805    /// - `FromIterator::from_iter` does return `Self` instead of `Result<Self, AllocError>`, hence
806    ///   we can't properly handle allocation failures.
807    /// - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation
808    ///   flags.
809    ///
810    /// Instead, provide `IntoIter::collect`, such that we can at least convert a `IntoIter` into a
811    /// `Vec` again.
812    ///
813    /// Note that `IntoIter::collect` doesn't require `Flags`, since it re-uses the existing backing
814    /// buffer. However, this backing buffer may be shrunk to the actual count of elements.
815    pub fn collect(self, flags: Flags) -> Vec<T, A> {
816        let old_layout = self.layout;
817        let (mut ptr, buf, len, mut cap) = self.into_raw_parts();
818        let has_advanced = ptr != buf.as_ptr();
819
820        if has_advanced {
821            // Copy the contents we have advanced to at the beginning of the buffer.
822            //
823            // SAFETY:
824            // - `ptr` is valid for reads of `len * size_of::<T>()` bytes,
825            // - `buf.as_ptr()` is valid for writes of `len * size_of::<T>()` bytes,
826            // - `ptr` and `buf.as_ptr()` are not be subject to aliasing restrictions relative to
827            //   each other,
828            // - both `ptr` and `buf.ptr()` are properly aligned.
829            unsafe { ptr::copy(ptr, buf.as_ptr(), len) };
830            ptr = buf.as_ptr();
831
832            // SAFETY: `len` is guaranteed to be smaller than `self.layout.len()` by the type
833            // invariant.
834            let layout = unsafe { ArrayLayout::<T>::new_unchecked(len) };
835
836            // SAFETY: `buf` points to the start of the backing buffer and `len` is guaranteed by
837            // the type invariant to be smaller than `cap`. Depending on `realloc` this operation
838            // may shrink the buffer or leave it as it is.
839            ptr = match unsafe {
840                A::realloc(Some(buf.cast()), layout.into(), old_layout.into(), flags)
841            } {
842                // If we fail to shrink, which likely can't even happen, continue with the existing
843                // buffer.
844                Err(_) => ptr,
845                Ok(ptr) => {
846                    cap = len;
847                    ptr.as_ptr().cast()
848                }
849            };
850        }
851
852        // SAFETY: If the iterator has been advanced, the advanced elements have been copied to
853        // the beginning of the buffer and `len` has been adjusted accordingly.
854        //
855        // - `ptr` is guaranteed to point to the start of the backing buffer.
856        // - `cap` is either the original capacity or, after shrinking the buffer, equal to `len`.
857        // - `alloc` is guaranteed to be unchanged since `into_iter` has been called on the original
858        //   `Vec`.
859        unsafe { Vec::from_raw_parts(ptr, len, cap) }
860    }
861}
862
863impl<T, A> Iterator for IntoIter<T, A>
864where
865    A: Allocator,
866{
867    type Item = T;
868
869    /// # Examples
870    ///
871    /// ```
872    /// let v = kernel::kvec![1, 2, 3]?;
873    /// let mut it = v.into_iter();
874    ///
875    /// assert_eq!(it.next(), Some(1));
876    /// assert_eq!(it.next(), Some(2));
877    /// assert_eq!(it.next(), Some(3));
878    /// assert_eq!(it.next(), None);
879    ///
880    /// # Ok::<(), Error>(())
881    /// ```
882    fn next(&mut self) -> Option<T> {
883        if self.len == 0 {
884            return None;
885        }
886
887        let current = self.ptr;
888
889        // SAFETY: We can't overflow; decreasing `self.len` by one every time we advance `self.ptr`
890        // by one guarantees that.
891        unsafe { self.ptr = self.ptr.add(1) };
892
893        self.len -= 1;
894
895        // SAFETY: `current` is guaranteed to point at a valid element within the buffer.
896        Some(unsafe { current.read() })
897    }
898
899    /// # Examples
900    ///
901    /// ```
902    /// let v: KVec<u32> = kernel::kvec![1, 2, 3]?;
903    /// let mut iter = v.into_iter();
904    /// let size = iter.size_hint().0;
905    ///
906    /// iter.next();
907    /// assert_eq!(iter.size_hint().0, size - 1);
908    ///
909    /// iter.next();
910    /// assert_eq!(iter.size_hint().0, size - 2);
911    ///
912    /// iter.next();
913    /// assert_eq!(iter.size_hint().0, size - 3);
914    ///
915    /// # Ok::<(), Error>(())
916    /// ```
917    fn size_hint(&self) -> (usize, Option<usize>) {
918        (self.len, Some(self.len))
919    }
920}
921
922impl<T, A> Drop for IntoIter<T, A>
923where
924    A: Allocator,
925{
926    fn drop(&mut self) {
927        // SAFETY: `self.ptr` is guaranteed to be valid by the type invariant.
928        unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.ptr, self.len)) };
929
930        // SAFETY:
931        // - `self.buf` was previously allocated with `A`.
932        // - `self.layout` matches the `ArrayLayout` of the preceding allocation.
933        unsafe { A::free(self.buf.cast(), self.layout.into()) };
934    }
935}
936
937impl<T, A> IntoIterator for Vec<T, A>
938where
939    A: Allocator,
940{
941    type Item = T;
942    type IntoIter = IntoIter<T, A>;
943
944    /// Consumes the `Vec<T, A>` and creates an `Iterator`, which moves each value out of the
945    /// vector (from start to end).
946    ///
947    /// # Examples
948    ///
949    /// ```
950    /// let v = kernel::kvec![1, 2]?;
951    /// let mut v_iter = v.into_iter();
952    ///
953    /// let first_element: Option<u32> = v_iter.next();
954    ///
955    /// assert_eq!(first_element, Some(1));
956    /// assert_eq!(v_iter.next(), Some(2));
957    /// assert_eq!(v_iter.next(), None);
958    ///
959    /// # Ok::<(), Error>(())
960    /// ```
961    ///
962    /// ```
963    /// let v = kernel::kvec![];
964    /// let mut v_iter = v.into_iter();
965    ///
966    /// let first_element: Option<u32> = v_iter.next();
967    ///
968    /// assert_eq!(first_element, None);
969    ///
970    /// # Ok::<(), Error>(())
971    /// ```
972    #[inline]
973    fn into_iter(self) -> Self::IntoIter {
974        let buf = self.ptr;
975        let layout = self.layout;
976        let (ptr, len, _) = self.into_raw_parts();
977
978        IntoIter {
979            ptr,
980            buf,
981            len,
982            layout,
983            _p: PhantomData::<A>,
984        }
985    }
986}