kernel/alloc/kvec.rs
1// SPDX-License-Identifier: GPL-2.0
2
3//! Implementation of [`Vec`].
4
5use super::{
6 allocator::{KVmalloc, Kmalloc, Vmalloc, VmallocPageIter},
7 layout::ArrayLayout,
8 AllocError, Allocator, Box, Flags, NumaNode,
9};
10use crate::{
11 fmt,
12 page::{
13 AsPageIter,
14 PAGE_SIZE, //
15 },
16};
17use core::{
18 borrow::{Borrow, BorrowMut},
19 marker::PhantomData,
20 mem::{ManuallyDrop, MaybeUninit},
21 ops::Deref,
22 ops::DerefMut,
23 ops::Index,
24 ops::IndexMut,
25 ptr,
26 ptr::NonNull,
27 slice,
28 slice::SliceIndex,
29};
30
31mod errors;
32pub use self::errors::{InsertError, PushError, RemoveError};
33
34/// Create a [`KVec`] containing the arguments.
35///
36/// New memory is allocated with `GFP_KERNEL`.
37///
38/// # Examples
39///
40/// ```
41/// let mut v = kernel::kvec![];
42/// v.push(1, GFP_KERNEL)?;
43/// assert_eq!(v, [1]);
44///
45/// let mut v = kernel::kvec![1; 3]?;
46/// v.push(4, GFP_KERNEL)?;
47/// assert_eq!(v, [1, 1, 1, 4]);
48///
49/// let mut v = kernel::kvec![1, 2, 3]?;
50/// v.push(4, GFP_KERNEL)?;
51/// assert_eq!(v, [1, 2, 3, 4]);
52///
53/// # Ok::<(), Error>(())
54/// ```
55#[macro_export]
56macro_rules! kvec {
57 () => (
58 $crate::alloc::KVec::new()
59 );
60 ($elem:expr; $n:expr) => (
61 $crate::alloc::KVec::from_elem($elem, $n, GFP_KERNEL)
62 );
63 ($($x:expr),+ $(,)?) => (
64 match $crate::alloc::KBox::new_uninit(GFP_KERNEL) {
65 Ok(b) => Ok($crate::alloc::KVec::from($crate::alloc::KBox::write(b, [$($x),+]))),
66 Err(e) => Err(e),
67 }
68 );
69}
70
71/// The kernel's [`Vec`] type.
72///
73/// A contiguous growable array type with contents allocated with the kernel's allocators (e.g.
74/// [`Kmalloc`], [`Vmalloc`] or [`KVmalloc`]), written `Vec<T, A>`.
75///
76/// For non-zero-sized values, a [`Vec`] will use the given allocator `A` for its allocation. For
77/// the most common allocators the type aliases [`KVec`], [`VVec`] and [`KVVec`] exist.
78///
79/// For zero-sized types the [`Vec`]'s pointer must be `dangling_mut::<T>`; no memory is allocated.
80///
81/// Generally, [`Vec`] consists of a pointer that represents the vector's backing buffer, the
82/// capacity of the vector (the number of elements that currently fit into the vector), its length
83/// (the number of elements that are currently stored in the vector) and the `Allocator` type used
84/// to allocate (and free) the backing buffer.
85///
86/// A [`Vec`] can be deconstructed into and (re-)constructed from its previously named raw parts
87/// and manually modified.
88///
89/// [`Vec`]'s backing buffer gets, if required, automatically increased (re-allocated) when elements
90/// are added to the vector.
91///
92/// # Invariants
93///
94/// - `self.ptr` is always properly aligned and either points to memory allocated with `A` or, for
95/// zero-sized types, is a dangling, well aligned pointer.
96///
97/// - `self.len` always represents the exact number of elements stored in the vector.
98///
99/// - `self.layout` represents the absolute number of elements that can be stored within the vector
100/// without re-allocation. For ZSTs `self.layout`'s capacity is zero. However, it is legal for the
101/// backing buffer to be larger than `layout`.
102///
103/// - `self.len()` is always less than or equal to `self.capacity()`.
104///
105/// - The `Allocator` type `A` of the vector is the exact same `Allocator` type the backing buffer
106/// was allocated with (and must be freed with).
107pub struct Vec<T, A: Allocator> {
108 ptr: NonNull<T>,
109 /// Represents the actual buffer size as `cap` times `size_of::<T>` bytes.
110 ///
111 /// Note: This isn't quite the same as `Self::capacity`, which in contrast returns the number of
112 /// elements we can still store without reallocating.
113 layout: ArrayLayout<T>,
114 len: usize,
115 _p: PhantomData<A>,
116}
117
118/// Type alias for [`Vec`] with a [`Kmalloc`] allocator.
119///
120/// # Examples
121///
122/// ```
123/// let mut v = KVec::new();
124/// v.push(1, GFP_KERNEL)?;
125/// assert_eq!(&v, &[1]);
126///
127/// # Ok::<(), Error>(())
128/// ```
129pub type KVec<T> = Vec<T, Kmalloc>;
130
131/// Type alias for [`Vec`] with a [`Vmalloc`] allocator.
132///
133/// # Examples
134///
135/// ```
136/// let mut v = VVec::new();
137/// v.push(1, GFP_KERNEL)?;
138/// assert_eq!(&v, &[1]);
139///
140/// # Ok::<(), Error>(())
141/// ```
142pub type VVec<T> = Vec<T, Vmalloc>;
143
144/// Type alias for [`Vec`] with a [`KVmalloc`] allocator.
145///
146/// # Examples
147///
148/// ```
149/// let mut v = KVVec::new();
150/// v.push(1, GFP_KERNEL)?;
151/// assert_eq!(&v, &[1]);
152///
153/// # Ok::<(), Error>(())
154/// ```
155pub type KVVec<T> = Vec<T, KVmalloc>;
156
157// SAFETY: `Vec` is `Send` if `T` is `Send` because `Vec` owns its elements.
158unsafe impl<T, A> Send for Vec<T, A>
159where
160 T: Send,
161 A: Allocator,
162{
163}
164
165// SAFETY: `Vec` is `Sync` if `T` is `Sync` because `Vec` owns its elements.
166unsafe impl<T, A> Sync for Vec<T, A>
167where
168 T: Sync,
169 A: Allocator,
170{
171}
172
173impl<T, A> Vec<T, A>
174where
175 A: Allocator,
176{
177 #[inline]
178 const fn is_zst() -> bool {
179 core::mem::size_of::<T>() == 0
180 }
181
182 /// Returns the number of elements that can be stored within the vector without allocating
183 /// additional memory.
184 pub const fn capacity(&self) -> usize {
185 if const { Self::is_zst() } {
186 usize::MAX
187 } else {
188 self.layout.len()
189 }
190 }
191
192 /// Returns the number of elements stored within the vector.
193 #[inline]
194 pub const fn len(&self) -> usize {
195 self.len
196 }
197
198 /// Increments `self.len` by `additional`.
199 ///
200 /// # Safety
201 ///
202 /// - `additional` must be less than or equal to `self.capacity - self.len`.
203 /// - All elements within the interval [`self.len`,`self.len + additional`) must be initialized.
204 #[inline]
205 pub const unsafe fn inc_len(&mut self, additional: usize) {
206 // Guaranteed by the type invariant to never underflow.
207 debug_assert!(additional <= self.capacity() - self.len());
208 // INVARIANT: By the safety requirements of this method this represents the exact number of
209 // elements stored within `self`.
210 self.len += additional;
211 }
212
213 /// Decreases `self.len` by `count`.
214 ///
215 /// Returns a mutable slice to the elements forgotten by the vector. It is the caller's
216 /// responsibility to drop these elements if necessary.
217 ///
218 /// # Safety
219 ///
220 /// - `count` must be less than or equal to `self.len`.
221 unsafe fn dec_len(&mut self, count: usize) -> &mut [T] {
222 debug_assert!(count <= self.len());
223 // INVARIANT: We relinquish ownership of the elements within the range `[self.len - count,
224 // self.len)`, hence the updated value of `set.len` represents the exact number of elements
225 // stored within `self`.
226 self.len -= count;
227 // SAFETY: The memory after `self.len()` is guaranteed to contain `count` initialized
228 // elements of type `T`.
229 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().add(self.len), count) }
230 }
231
232 /// Returns a slice of the entire vector.
233 ///
234 /// # Examples
235 ///
236 /// ```
237 /// let mut v = KVec::new();
238 /// v.push(1, GFP_KERNEL)?;
239 /// v.push(2, GFP_KERNEL)?;
240 /// assert_eq!(v.as_slice(), &[1, 2]);
241 /// # Ok::<(), Error>(())
242 /// ```
243 #[inline]
244 pub fn as_slice(&self) -> &[T] {
245 self
246 }
247
248 /// Returns a mutable slice of the entire vector.
249 #[inline]
250 pub fn as_mut_slice(&mut self) -> &mut [T] {
251 self
252 }
253
254 /// Returns a mutable raw pointer to the vector's backing buffer, or, if `T` is a ZST, a
255 /// dangling raw pointer.
256 #[inline]
257 pub fn as_mut_ptr(&mut self) -> *mut T {
258 self.ptr.as_ptr()
259 }
260
261 /// Returns a raw pointer to the vector's backing buffer, or, if `T` is a ZST, a dangling raw
262 /// pointer.
263 #[inline]
264 pub const fn as_ptr(&self) -> *const T {
265 self.ptr.as_ptr()
266 }
267
268 /// Returns `true` if the vector contains no elements, `false` otherwise.
269 ///
270 /// # Examples
271 ///
272 /// ```
273 /// let mut v = KVec::new();
274 /// assert!(v.is_empty());
275 ///
276 /// v.push(1, GFP_KERNEL);
277 /// assert!(!v.is_empty());
278 /// ```
279 #[inline]
280 pub const fn is_empty(&self) -> bool {
281 self.len() == 0
282 }
283
284 /// Creates a new, empty `Vec<T, A>`.
285 ///
286 /// This method does not allocate by itself.
287 #[inline]
288 pub const fn new() -> Self {
289 // INVARIANT: Since this is a new, empty `Vec` with no backing memory yet,
290 // - `ptr` is a properly aligned dangling pointer for type `T`,
291 // - `layout` is an empty `ArrayLayout` (zero capacity)
292 // - `len` is zero, since no elements can be or have been stored,
293 // - `A` is always valid.
294 Self {
295 ptr: NonNull::dangling(),
296 layout: ArrayLayout::empty(),
297 len: 0,
298 _p: PhantomData::<A>,
299 }
300 }
301
302 /// Returns a slice of `MaybeUninit<T>` for the remaining spare capacity of the vector.
303 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
304 // SAFETY:
305 // - `self.len` is smaller than `self.capacity` by the type invariant and hence, the
306 // resulting pointer is guaranteed to be part of the same allocated object.
307 // - `self.len` can not overflow `isize`.
308 let ptr = unsafe { self.as_mut_ptr().add(self.len) }.cast::<MaybeUninit<T>>();
309
310 // SAFETY: The memory between `self.len` and `self.capacity` is guaranteed to be allocated
311 // and valid, but uninitialized.
312 unsafe { slice::from_raw_parts_mut(ptr, self.capacity() - self.len) }
313 }
314
315 /// Appends an element to the back of the [`Vec`] instance.
316 ///
317 /// # Examples
318 ///
319 /// ```
320 /// let mut v = KVec::new();
321 /// v.push(1, GFP_KERNEL)?;
322 /// assert_eq!(&v, &[1]);
323 ///
324 /// v.push(2, GFP_KERNEL)?;
325 /// assert_eq!(&v, &[1, 2]);
326 /// # Ok::<(), Error>(())
327 /// ```
328 pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
329 self.reserve(1, flags)?;
330 // SAFETY: The call to `reserve` was successful, so the capacity is at least one greater
331 // than the length.
332 unsafe { self.push_within_capacity_unchecked(v) };
333 Ok(())
334 }
335
336 /// Appends an element to the back of the [`Vec`] instance without reallocating.
337 ///
338 /// Fails if the vector does not have capacity for the new element.
339 ///
340 /// # Examples
341 ///
342 /// ```
343 /// let mut v = KVec::with_capacity(10, GFP_KERNEL)?;
344 /// for i in 0..10 {
345 /// v.push_within_capacity(i)?;
346 /// }
347 ///
348 /// assert!(v.push_within_capacity(10).is_err());
349 /// # Ok::<(), Error>(())
350 /// ```
351 pub fn push_within_capacity(&mut self, v: T) -> Result<(), PushError<T>> {
352 if self.len() < self.capacity() {
353 // SAFETY: The length is less than the capacity.
354 unsafe { self.push_within_capacity_unchecked(v) };
355 Ok(())
356 } else {
357 Err(PushError(v))
358 }
359 }
360
361 /// Appends an element to the back of the [`Vec`] instance without reallocating.
362 ///
363 /// # Safety
364 ///
365 /// The length must be less than the capacity.
366 unsafe fn push_within_capacity_unchecked(&mut self, v: T) {
367 let spare = self.spare_capacity_mut();
368
369 // SAFETY: By the safety requirements, `spare` is non-empty.
370 unsafe { spare.get_unchecked_mut(0) }.write(v);
371
372 // SAFETY: We just initialised the first spare entry, so it is safe to increase the length
373 // by 1. We also know that the new length is <= capacity because the caller guarantees that
374 // the length is less than the capacity at the beginning of this function.
375 unsafe { self.inc_len(1) };
376 }
377
378 /// Inserts an element at the given index in the [`Vec`] instance.
379 ///
380 /// Fails if the vector does not have capacity for the new element. Panics if the index is out
381 /// of bounds.
382 ///
383 /// # Examples
384 ///
385 /// ```
386 /// use kernel::alloc::kvec::InsertError;
387 ///
388 /// let mut v = KVec::with_capacity(5, GFP_KERNEL)?;
389 /// for i in 0..5 {
390 /// v.insert_within_capacity(0, i)?;
391 /// }
392 ///
393 /// assert!(matches!(v.insert_within_capacity(0, 5), Err(InsertError::OutOfCapacity(_))));
394 /// assert!(matches!(v.insert_within_capacity(1000, 5), Err(InsertError::IndexOutOfBounds(_))));
395 /// assert_eq!(v, [4, 3, 2, 1, 0]);
396 /// # Ok::<(), Error>(())
397 /// ```
398 pub fn insert_within_capacity(
399 &mut self,
400 index: usize,
401 element: T,
402 ) -> Result<(), InsertError<T>> {
403 let len = self.len();
404 if index > len {
405 return Err(InsertError::IndexOutOfBounds(element));
406 }
407
408 if len >= self.capacity() {
409 return Err(InsertError::OutOfCapacity(element));
410 }
411
412 // SAFETY: This is in bounds since `index <= len < capacity`.
413 let p = unsafe { self.as_mut_ptr().add(index) };
414 // INVARIANT: This breaks the Vec invariants by making `index` contain an invalid element,
415 // but we restore the invariants below.
416 // SAFETY: Both the src and dst ranges end no later than one element after the length.
417 // Since the length is less than the capacity, both ranges are in bounds of the allocation.
418 unsafe { ptr::copy(p, p.add(1), len - index) };
419 // INVARIANT: This restores the Vec invariants.
420 // SAFETY: The pointer is in-bounds of the allocation.
421 unsafe { ptr::write(p, element) };
422 // SAFETY: Index `len` contains a valid element due to the above copy and write.
423 unsafe { self.inc_len(1) };
424 Ok(())
425 }
426
427 /// Removes the last element from a vector and returns it, or `None` if it is empty.
428 ///
429 /// # Examples
430 ///
431 /// ```
432 /// let mut v = KVec::new();
433 /// v.push(1, GFP_KERNEL)?;
434 /// v.push(2, GFP_KERNEL)?;
435 /// assert_eq!(&v, &[1, 2]);
436 ///
437 /// assert_eq!(v.pop(), Some(2));
438 /// assert_eq!(v.pop(), Some(1));
439 /// assert_eq!(v.pop(), None);
440 /// # Ok::<(), Error>(())
441 /// ```
442 pub fn pop(&mut self) -> Option<T> {
443 if self.is_empty() {
444 return None;
445 }
446
447 let removed: *mut T = {
448 // SAFETY: We just checked that the length is at least one.
449 let slice = unsafe { self.dec_len(1) };
450 // SAFETY: The argument to `dec_len` was 1 so this returns a slice of length 1.
451 unsafe { slice.get_unchecked_mut(0) }
452 };
453
454 // SAFETY: The guarantees of `dec_len` allow us to take ownership of this value.
455 Some(unsafe { removed.read() })
456 }
457
458 /// Removes the element at the given index.
459 ///
460 /// # Examples
461 ///
462 /// ```
463 /// let mut v = kernel::kvec![1, 2, 3]?;
464 /// assert_eq!(v.remove(1)?, 2);
465 /// assert_eq!(v, [1, 3]);
466 /// # Ok::<(), Error>(())
467 /// ```
468 pub fn remove(&mut self, i: usize) -> Result<T, RemoveError> {
469 let value = {
470 let value_ref = self.get(i).ok_or(RemoveError)?;
471 // INVARIANT: This breaks the invariants by invalidating the value at index `i`, but we
472 // restore the invariants below.
473 // SAFETY: The value at index `i` is valid, because otherwise we would have already
474 // failed with `RemoveError`.
475 unsafe { ptr::read(value_ref) }
476 };
477
478 // SAFETY: We checked that `i` is in-bounds.
479 let p = unsafe { self.as_mut_ptr().add(i) };
480
481 // INVARIANT: After this call, the invalid value is at the last slot, so the Vec invariants
482 // are restored after the below call to `dec_len(1)`.
483 // SAFETY: `p.add(1).add(self.len - i - 1)` is `i+1+len-i-1 == len` elements after the
484 // beginning of the vector, so this is in-bounds of the vector's allocation.
485 unsafe { ptr::copy(p.add(1), p, self.len - i - 1) };
486
487 // SAFETY: Since the check at the beginning of this call did not fail with `RemoveError`,
488 // the length is at least one.
489 unsafe { self.dec_len(1) };
490
491 Ok(value)
492 }
493
494 /// Creates a new [`Vec`] instance with at least the given capacity.
495 ///
496 /// # Examples
497 ///
498 /// ```
499 /// let v = KVec::<u32>::with_capacity(20, GFP_KERNEL)?;
500 ///
501 /// assert!(v.capacity() >= 20);
502 /// # Ok::<(), Error>(())
503 /// ```
504 pub fn with_capacity(capacity: usize, flags: Flags) -> Result<Self, AllocError> {
505 let mut v = Vec::new();
506
507 v.reserve(capacity, flags)?;
508
509 Ok(v)
510 }
511
512 /// Creates a `Vec<T, A>` from a pointer, a length and a capacity using the allocator `A`.
513 ///
514 /// # Examples
515 ///
516 /// ```
517 /// let mut v = kernel::kvec![1, 2, 3]?;
518 /// v.reserve(1, GFP_KERNEL)?;
519 ///
520 /// let (mut ptr, mut len, cap) = v.into_raw_parts();
521 ///
522 /// // SAFETY: We've just reserved memory for another element.
523 /// unsafe { ptr.add(len).write(4) };
524 /// len += 1;
525 ///
526 /// // SAFETY: We only wrote an additional element at the end of the `KVec`'s buffer and
527 /// // correspondingly increased the length of the `KVec` by one. Otherwise, we construct it
528 /// // from the exact same raw parts.
529 /// let v = unsafe { KVec::from_raw_parts(ptr, len, cap) };
530 ///
531 /// assert_eq!(v, [1, 2, 3, 4]);
532 ///
533 /// # Ok::<(), Error>(())
534 /// ```
535 ///
536 /// # Safety
537 ///
538 /// If `T` is a ZST:
539 ///
540 /// - `ptr` must be a dangling, well aligned pointer.
541 ///
542 /// Otherwise:
543 ///
544 /// - `ptr` must have been allocated with the allocator `A`.
545 /// - `ptr` must satisfy or exceed the alignment requirements of `T`.
546 /// - `ptr` must point to memory with a size of at least `size_of::<T>() * capacity` bytes.
547 /// - The allocated size in bytes must not be larger than `isize::MAX`.
548 /// - `length` must be less than or equal to `capacity`.
549 /// - The first `length` elements must be initialized values of type `T`.
550 ///
551 /// It is also valid to create an empty `Vec` passing a dangling pointer for `ptr` and zero for
552 /// `cap` and `len`.
553 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
554 let layout = if Self::is_zst() {
555 ArrayLayout::empty()
556 } else {
557 // SAFETY: By the safety requirements of this function, `capacity * size_of::<T>()` is
558 // smaller than `isize::MAX`.
559 unsafe { ArrayLayout::new_unchecked(capacity) }
560 };
561
562 // INVARIANT: For ZSTs, we store an empty `ArrayLayout`, all other type invariants are
563 // covered by the safety requirements of this function.
564 Self {
565 // SAFETY: By the safety requirements, `ptr` is either dangling or pointing to a valid
566 // memory allocation, allocated with `A`.
567 ptr: unsafe { NonNull::new_unchecked(ptr) },
568 layout,
569 len: length,
570 _p: PhantomData::<A>,
571 }
572 }
573
574 /// Consumes the `Vec<T, A>` and returns its raw components `pointer`, `length` and `capacity`.
575 ///
576 /// This will not run the destructor of the contained elements and for non-ZSTs the allocation
577 /// will stay alive indefinitely. Use [`Vec::from_raw_parts`] to recover the [`Vec`], drop the
578 /// elements and free the allocation, if any.
579 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
580 let mut me = ManuallyDrop::new(self);
581 let len = me.len();
582 let capacity = me.capacity();
583 let ptr = me.as_mut_ptr();
584 (ptr, len, capacity)
585 }
586
587 /// Clears the vector, removing all values.
588 ///
589 /// Note that this method has no effect on the allocated capacity
590 /// of the vector.
591 ///
592 /// # Examples
593 ///
594 /// ```
595 /// let mut v = kernel::kvec![1, 2, 3]?;
596 ///
597 /// v.clear();
598 ///
599 /// assert!(v.is_empty());
600 /// # Ok::<(), Error>(())
601 /// ```
602 #[inline]
603 pub fn clear(&mut self) {
604 self.truncate(0);
605 }
606
607 /// Ensures that the capacity exceeds the length by at least `additional` elements.
608 ///
609 /// # Examples
610 ///
611 /// ```
612 /// let mut v = KVec::new();
613 /// v.push(1, GFP_KERNEL)?;
614 ///
615 /// v.reserve(10, GFP_KERNEL)?;
616 /// let cap = v.capacity();
617 /// assert!(cap >= 10);
618 ///
619 /// v.reserve(10, GFP_KERNEL)?;
620 /// let new_cap = v.capacity();
621 /// assert_eq!(new_cap, cap);
622 ///
623 /// # Ok::<(), Error>(())
624 /// ```
625 pub fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocError> {
626 let len = self.len();
627 let cap = self.capacity();
628
629 if cap - len >= additional {
630 return Ok(());
631 }
632
633 if Self::is_zst() {
634 // The capacity is already `usize::MAX` for ZSTs, we can't go higher.
635 return Err(AllocError);
636 }
637
638 // We know that `cap <= isize::MAX` because of the type invariants of `Self`. So the
639 // multiplication by two won't overflow.
640 let new_cap = core::cmp::max(cap * 2, len.checked_add(additional).ok_or(AllocError)?);
641 let layout = ArrayLayout::new(new_cap).map_err(|_| AllocError)?;
642
643 // SAFETY:
644 // - `ptr` is valid because it's either `None` or comes from a previous call to
645 // `A::realloc`.
646 // - `self.layout` matches the `ArrayLayout` of the preceding allocation.
647 let ptr = unsafe {
648 A::realloc(
649 Some(self.ptr.cast()),
650 layout.into(),
651 self.layout.into(),
652 flags,
653 NumaNode::NO_NODE,
654 )?
655 };
656
657 // INVARIANT:
658 // - `layout` is some `ArrayLayout::<T>`,
659 // - `ptr` has been created by `A::realloc` from `layout`.
660 self.ptr = ptr.cast();
661 self.layout = layout;
662
663 Ok(())
664 }
665
666 /// Shortens the vector, setting the length to `len` and drops the removed values.
667 /// If `len` is greater than or equal to the current length, this does nothing.
668 ///
669 /// This has no effect on the capacity and will not allocate.
670 ///
671 /// # Examples
672 ///
673 /// ```
674 /// let mut v = kernel::kvec![1, 2, 3]?;
675 /// v.truncate(1);
676 /// assert_eq!(v.len(), 1);
677 /// assert_eq!(&v, &[1]);
678 ///
679 /// # Ok::<(), Error>(())
680 /// ```
681 pub fn truncate(&mut self, len: usize) {
682 if let Some(count) = self.len().checked_sub(len) {
683 // SAFETY: `count` is `self.len() - len` so it is guaranteed to be less than or
684 // equal to `self.len()`.
685 let ptr: *mut [T] = unsafe { self.dec_len(count) };
686
687 // SAFETY: the contract of `dec_len` guarantees that the elements in `ptr` are
688 // valid elements whose ownership has been transferred to the caller.
689 unsafe { ptr::drop_in_place(ptr) };
690 }
691 }
692
693 /// Takes ownership of all items in this vector without consuming the allocation.
694 ///
695 /// # Examples
696 ///
697 /// ```
698 /// let mut v = kernel::kvec![0, 1, 2, 3]?;
699 ///
700 /// for (i, j) in v.drain_all().enumerate() {
701 /// assert_eq!(i, j);
702 /// }
703 ///
704 /// assert!(v.capacity() >= 4);
705 /// # Ok::<(), Error>(())
706 /// ```
707 pub fn drain_all(&mut self) -> DrainAll<'_, T> {
708 // SAFETY: This does not underflow the length.
709 let elems = unsafe { self.dec_len(self.len()) };
710 // INVARIANT: The first `len` elements of the spare capacity are valid values, and as we
711 // just set the length to zero, we may transfer ownership to the `DrainAll` object.
712 DrainAll {
713 elements: elems.iter_mut(),
714 }
715 }
716
717 /// Removes all elements that don't match the provided closure.
718 ///
719 /// # Examples
720 ///
721 /// ```
722 /// let mut v = kernel::kvec![1, 2, 3, 4]?;
723 /// v.retain(|i| *i % 2 == 0);
724 /// assert_eq!(v, [2, 4]);
725 /// # Ok::<(), Error>(())
726 /// ```
727 pub fn retain(&mut self, mut f: impl FnMut(&mut T) -> bool) {
728 let mut num_kept = 0;
729 let mut next_to_check = 0;
730 while let Some(to_check) = self.get_mut(next_to_check) {
731 if f(to_check) {
732 self.swap(num_kept, next_to_check);
733 num_kept += 1;
734 }
735 next_to_check += 1;
736 }
737 self.truncate(num_kept);
738 }
739}
740// TODO: This is a temporary KVVec-specific implementation. It should be replaced with a generic
741// `shrink_to()` for `impl<T, A: Allocator> Vec<T, A>` that uses `A::realloc()` once the
742// underlying allocators properly support shrinking via realloc.
743impl<T> Vec<T, KVmalloc> {
744 /// Shrinks the capacity of the vector with a lower bound.
745 ///
746 /// The capacity will remain at least as large as both the length and the supplied value.
747 /// If the current capacity is less than the lower limit, this is a no-op.
748 ///
749 /// For `kmalloc` allocations, this delegates to `realloc()`, which decides whether
750 /// shrinking is worthwhile. For `vmalloc` allocations, shrinking only occurs if the
751 /// operation would free at least one page of memory, and performs a deep copy since
752 /// `vrealloc` does not yet support in-place shrinking.
753 ///
754 /// # Examples
755 ///
756 /// ```
757 /// // Allocate enough capacity to span multiple pages.
758 /// let elements_per_page = kernel::page::PAGE_SIZE / core::mem::size_of::<u32>();
759 /// let mut v = KVVec::with_capacity(elements_per_page * 4, GFP_KERNEL)?;
760 /// v.push(1, GFP_KERNEL)?;
761 /// v.push(2, GFP_KERNEL)?;
762 ///
763 /// v.shrink_to(0, GFP_KERNEL)?;
764 /// # Ok::<(), Error>(())
765 /// ```
766 pub fn shrink_to(&mut self, min_capacity: usize, flags: Flags) -> Result<(), AllocError> {
767 let target_cap = core::cmp::max(self.len(), min_capacity);
768
769 if self.capacity() <= target_cap {
770 return Ok(());
771 }
772
773 if Self::is_zst() {
774 return Ok(());
775 }
776
777 // For kmalloc allocations, delegate to realloc() and let the allocator decide
778 // whether shrinking is worthwhile.
779 //
780 // SAFETY: `self.ptr` points to a valid `KVmalloc` allocation.
781 if !unsafe { bindings::is_vmalloc_addr(self.ptr.as_ptr().cast()) } {
782 let new_layout = ArrayLayout::<T>::new(target_cap).map_err(|_| AllocError)?;
783
784 // SAFETY:
785 // - `self.ptr` is valid and was previously allocated with `KVmalloc`.
786 // - `self.layout` matches the `ArrayLayout` of the preceding allocation.
787 let ptr = unsafe {
788 KVmalloc::realloc(
789 Some(self.ptr.cast()),
790 new_layout.into(),
791 self.layout.into(),
792 flags,
793 NumaNode::NO_NODE,
794 )?
795 };
796
797 self.ptr = ptr.cast();
798 self.layout = new_layout;
799 return Ok(());
800 }
801
802 // Only shrink if we would free at least one page.
803 let current_size = self.capacity() * core::mem::size_of::<T>();
804 let target_size = target_cap * core::mem::size_of::<T>();
805 let current_pages = current_size.div_ceil(PAGE_SIZE);
806 let target_pages = target_size.div_ceil(PAGE_SIZE);
807
808 if current_pages <= target_pages {
809 return Ok(());
810 }
811
812 if target_cap == 0 {
813 if !self.layout.is_empty() {
814 // SAFETY:
815 // - `self.ptr` was previously allocated with `KVmalloc`.
816 // - `self.layout` matches the `ArrayLayout` of the preceding allocation.
817 unsafe { KVmalloc::free(self.ptr.cast(), self.layout.into()) };
818 }
819 self.ptr = NonNull::dangling();
820 self.layout = ArrayLayout::empty();
821 return Ok(());
822 }
823
824 // SAFETY: `target_cap <= self.capacity()` and original capacity was valid.
825 let new_layout = unsafe { ArrayLayout::<T>::new_unchecked(target_cap) };
826
827 let new_ptr = KVmalloc::alloc(new_layout.into(), flags, NumaNode::NO_NODE)?;
828
829 // SAFETY:
830 // - `self.as_ptr()` is valid for reads of `self.len()` elements of `T`.
831 // - `new_ptr` is valid for writes of at least `target_cap >= self.len()` elements.
832 // - The two allocations do not overlap since `new_ptr` is freshly allocated.
833 // - Both pointers are properly aligned for `T`.
834 unsafe {
835 ptr::copy_nonoverlapping(self.as_ptr(), new_ptr.as_ptr().cast::<T>(), self.len())
836 };
837
838 // SAFETY:
839 // - `self.ptr` was previously allocated with `KVmalloc`.
840 // - `self.layout` matches the `ArrayLayout` of the preceding allocation.
841 unsafe { KVmalloc::free(self.ptr.cast(), self.layout.into()) };
842
843 self.ptr = new_ptr.cast::<T>();
844 self.layout = new_layout;
845
846 Ok(())
847 }
848}
849
850impl<T: Clone, A: Allocator> Vec<T, A> {
851 /// Extend the vector by `n` clones of `value`.
852 pub fn extend_with(&mut self, n: usize, value: T, flags: Flags) -> Result<(), AllocError> {
853 if n == 0 {
854 return Ok(());
855 }
856
857 self.reserve(n, flags)?;
858
859 let spare = self.spare_capacity_mut();
860
861 for item in spare.iter_mut().take(n - 1) {
862 item.write(value.clone());
863 }
864
865 // We can write the last element directly without cloning needlessly.
866 spare[n - 1].write(value);
867
868 // SAFETY:
869 // - `self.len() + n < self.capacity()` due to the call to reserve above,
870 // - the loop and the line above initialized the next `n` elements.
871 unsafe { self.inc_len(n) };
872
873 Ok(())
874 }
875
876 /// Pushes clones of the elements of slice into the [`Vec`] instance.
877 ///
878 /// # Examples
879 ///
880 /// ```
881 /// let mut v = KVec::new();
882 /// v.push(1, GFP_KERNEL)?;
883 ///
884 /// v.extend_from_slice(&[20, 30, 40], GFP_KERNEL)?;
885 /// assert_eq!(&v, &[1, 20, 30, 40]);
886 ///
887 /// v.extend_from_slice(&[50, 60], GFP_KERNEL)?;
888 /// assert_eq!(&v, &[1, 20, 30, 40, 50, 60]);
889 /// # Ok::<(), Error>(())
890 /// ```
891 pub fn extend_from_slice(&mut self, other: &[T], flags: Flags) -> Result<(), AllocError> {
892 self.reserve(other.len(), flags)?;
893 for (slot, item) in core::iter::zip(self.spare_capacity_mut(), other) {
894 slot.write(item.clone());
895 }
896
897 // SAFETY:
898 // - `other.len()` spare entries have just been initialized, so it is safe to increase
899 // the length by the same number.
900 // - `self.len() + other.len() <= self.capacity()` is guaranteed by the preceding `reserve`
901 // call.
902 unsafe { self.inc_len(other.len()) };
903 Ok(())
904 }
905
906 /// Create a new `Vec<T, A>` and extend it by `n` clones of `value`.
907 pub fn from_elem(value: T, n: usize, flags: Flags) -> Result<Self, AllocError> {
908 let mut v = Self::with_capacity(n, flags)?;
909
910 v.extend_with(n, value, flags)?;
911
912 Ok(v)
913 }
914
915 /// Resizes the [`Vec`] so that `len` is equal to `new_len`.
916 ///
917 /// If `new_len` is smaller than `len`, the `Vec` is [`Vec::truncate`]d.
918 /// If `new_len` is larger, each new slot is filled with clones of `value`.
919 ///
920 /// # Examples
921 ///
922 /// ```
923 /// let mut v = kernel::kvec![1, 2, 3]?;
924 /// v.resize(1, 42, GFP_KERNEL)?;
925 /// assert_eq!(&v, &[1]);
926 ///
927 /// v.resize(3, 42, GFP_KERNEL)?;
928 /// assert_eq!(&v, &[1, 42, 42]);
929 ///
930 /// # Ok::<(), Error>(())
931 /// ```
932 pub fn resize(&mut self, new_len: usize, value: T, flags: Flags) -> Result<(), AllocError> {
933 match new_len.checked_sub(self.len()) {
934 Some(n) => self.extend_with(n, value, flags),
935 None => {
936 self.truncate(new_len);
937 Ok(())
938 }
939 }
940 }
941}
942
943impl<T, A> Drop for Vec<T, A>
944where
945 A: Allocator,
946{
947 fn drop(&mut self) {
948 // SAFETY: `self.as_mut_ptr` is guaranteed to be valid by the type invariant.
949 unsafe {
950 ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
951 self.as_mut_ptr(),
952 self.len,
953 ))
954 };
955
956 // SAFETY:
957 // - `self.ptr` was previously allocated with `A`.
958 // - `self.layout` matches the `ArrayLayout` of the preceding allocation.
959 unsafe { A::free(self.ptr.cast(), self.layout.into()) };
960 }
961}
962
963impl<T, A, const N: usize> From<Box<[T; N], A>> for Vec<T, A>
964where
965 A: Allocator,
966{
967 fn from(b: Box<[T; N], A>) -> Vec<T, A> {
968 let len = b.len();
969 let ptr = Box::into_raw(b);
970
971 // SAFETY:
972 // - `b` has been allocated with `A`,
973 // - `ptr` fulfills the alignment requirements for `T`,
974 // - `ptr` points to memory with at least a size of `size_of::<T>() * len`,
975 // - all elements within `b` are initialized values of `T`,
976 // - `len` does not exceed `isize::MAX`.
977 unsafe { Vec::from_raw_parts(ptr.cast(), len, len) }
978 }
979}
980
981impl<T, A: Allocator> Default for Vec<T, A> {
982 #[inline]
983 fn default() -> Self {
984 Self::new()
985 }
986}
987
988impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
989 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
990 fmt::Debug::fmt(&**self, f)
991 }
992}
993
994impl<T, A> Deref for Vec<T, A>
995where
996 A: Allocator,
997{
998 type Target = [T];
999
1000 #[inline]
1001 fn deref(&self) -> &[T] {
1002 // SAFETY: The memory behind `self.as_ptr()` is guaranteed to contain `self.len`
1003 // initialized elements of type `T`.
1004 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
1005 }
1006}
1007
1008impl<T, A> DerefMut for Vec<T, A>
1009where
1010 A: Allocator,
1011{
1012 #[inline]
1013 fn deref_mut(&mut self) -> &mut [T] {
1014 // SAFETY: The memory behind `self.as_ptr()` is guaranteed to contain `self.len`
1015 // initialized elements of type `T`.
1016 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
1017 }
1018}
1019
1020/// # Examples
1021///
1022/// ```
1023/// # use core::borrow::Borrow;
1024/// struct Foo<B: Borrow<[u32]>>(B);
1025///
1026/// // Owned array.
1027/// let owned_array = Foo([1, 2, 3]);
1028///
1029/// // Owned vector.
1030/// let owned_vec = Foo(KVec::from_elem(0, 3, GFP_KERNEL)?);
1031///
1032/// let arr = [1, 2, 3];
1033/// // Borrowed slice from `arr`.
1034/// let borrowed_slice = Foo(&arr[..]);
1035/// # Ok::<(), Error>(())
1036/// ```
1037impl<T, A> Borrow<[T]> for Vec<T, A>
1038where
1039 A: Allocator,
1040{
1041 fn borrow(&self) -> &[T] {
1042 self.as_slice()
1043 }
1044}
1045
1046/// # Examples
1047///
1048/// ```
1049/// # use core::borrow::BorrowMut;
1050/// struct Foo<B: BorrowMut<[u32]>>(B);
1051///
1052/// // Owned array.
1053/// let owned_array = Foo([1, 2, 3]);
1054///
1055/// // Owned vector.
1056/// let owned_vec = Foo(KVec::from_elem(0, 3, GFP_KERNEL)?);
1057///
1058/// let mut arr = [1, 2, 3];
1059/// // Borrowed slice from `arr`.
1060/// let borrowed_slice = Foo(&mut arr[..]);
1061/// # Ok::<(), Error>(())
1062/// ```
1063impl<T, A> BorrowMut<[T]> for Vec<T, A>
1064where
1065 A: Allocator,
1066{
1067 fn borrow_mut(&mut self) -> &mut [T] {
1068 self.as_mut_slice()
1069 }
1070}
1071
1072impl<T: Eq, A> Eq for Vec<T, A> where A: Allocator {}
1073
1074impl<T, I: SliceIndex<[T]>, A> Index<I> for Vec<T, A>
1075where
1076 A: Allocator,
1077{
1078 type Output = I::Output;
1079
1080 #[inline]
1081 fn index(&self, index: I) -> &Self::Output {
1082 Index::index(&**self, index)
1083 }
1084}
1085
1086impl<T, I: SliceIndex<[T]>, A> IndexMut<I> for Vec<T, A>
1087where
1088 A: Allocator,
1089{
1090 #[inline]
1091 fn index_mut(&mut self, index: I) -> &mut Self::Output {
1092 IndexMut::index_mut(&mut **self, index)
1093 }
1094}
1095
1096macro_rules! impl_slice_eq {
1097 ($([$($vars:tt)*] $lhs:ty, $rhs:ty,)*) => {
1098 $(
1099 impl<T, U, $($vars)*> PartialEq<$rhs> for $lhs
1100 where
1101 T: PartialEq<U>,
1102 {
1103 #[inline]
1104 fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
1105 }
1106 )*
1107 }
1108}
1109
1110impl_slice_eq! {
1111 [A1: Allocator, A2: Allocator] Vec<T, A1>, Vec<U, A2>,
1112 [A: Allocator] Vec<T, A>, &[U],
1113 [A: Allocator] Vec<T, A>, &mut [U],
1114 [A: Allocator] &[T], Vec<U, A>,
1115 [A: Allocator] &mut [T], Vec<U, A>,
1116 [A: Allocator] Vec<T, A>, [U],
1117 [A: Allocator] [T], Vec<U, A>,
1118 [A: Allocator, const N: usize] Vec<T, A>, [U; N],
1119 [A: Allocator, const N: usize] Vec<T, A>, &[U; N],
1120}
1121
1122impl<'a, T, A> IntoIterator for &'a Vec<T, A>
1123where
1124 A: Allocator,
1125{
1126 type Item = &'a T;
1127 type IntoIter = slice::Iter<'a, T>;
1128
1129 fn into_iter(self) -> Self::IntoIter {
1130 self.iter()
1131 }
1132}
1133
1134impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A>
1135where
1136 A: Allocator,
1137{
1138 type Item = &'a mut T;
1139 type IntoIter = slice::IterMut<'a, T>;
1140
1141 fn into_iter(self) -> Self::IntoIter {
1142 self.iter_mut()
1143 }
1144}
1145
1146/// # Examples
1147///
1148/// ```
1149/// # use kernel::prelude::*;
1150/// use kernel::alloc::allocator::VmallocPageIter;
1151/// use kernel::page::{AsPageIter, PAGE_SIZE};
1152///
1153/// let mut vec = VVec::<u8>::new();
1154///
1155/// assert!(vec.page_iter().next().is_none());
1156///
1157/// vec.reserve(PAGE_SIZE, GFP_KERNEL)?;
1158///
1159/// let page = vec.page_iter().next().expect("At least one page should be available.\n");
1160///
1161/// // SAFETY: There is no concurrent read or write to the same page.
1162/// unsafe { page.fill_zero_raw(0, PAGE_SIZE)? };
1163/// # Ok::<(), Error>(())
1164/// ```
1165impl<T> AsPageIter for VVec<T> {
1166 type Iter<'a>
1167 = VmallocPageIter<'a>
1168 where
1169 T: 'a;
1170
1171 fn page_iter(&mut self) -> Self::Iter<'_> {
1172 let ptr = self.ptr.cast();
1173 let size = self.layout.size();
1174
1175 // SAFETY:
1176 // - `ptr` is a valid pointer to the beginning of a `Vmalloc` allocation.
1177 // - `ptr` is guaranteed to be valid for the lifetime of `'a`.
1178 // - `size` is the size of the `Vmalloc` allocation `ptr` points to.
1179 unsafe { VmallocPageIter::new(ptr, size) }
1180 }
1181}
1182
1183/// An [`Iterator`] implementation for [`Vec`] that moves elements out of a vector.
1184///
1185/// This structure is created by the [`Vec::into_iter`] method on [`Vec`] (provided by the
1186/// [`IntoIterator`] trait).
1187///
1188/// # Examples
1189///
1190/// ```
1191/// let v = kernel::kvec![0, 1, 2]?;
1192/// let iter = v.into_iter();
1193///
1194/// # Ok::<(), Error>(())
1195/// ```
1196pub struct IntoIter<T, A: Allocator> {
1197 ptr: *mut T,
1198 buf: NonNull<T>,
1199 len: usize,
1200 layout: ArrayLayout<T>,
1201 _p: PhantomData<A>,
1202}
1203
1204impl<T, A> IntoIter<T, A>
1205where
1206 A: Allocator,
1207{
1208 fn into_raw_parts(self) -> (*mut T, NonNull<T>, usize, usize) {
1209 let me = ManuallyDrop::new(self);
1210 let ptr = me.ptr;
1211 let buf = me.buf;
1212 let len = me.len;
1213 let cap = me.layout.len();
1214 (ptr, buf, len, cap)
1215 }
1216
1217 /// Same as `Iterator::collect` but specialized for `Vec`'s `IntoIter`.
1218 ///
1219 /// # Examples
1220 ///
1221 /// ```
1222 /// let v = kernel::kvec![1, 2, 3]?;
1223 /// let mut it = v.into_iter();
1224 ///
1225 /// assert_eq!(it.next(), Some(1));
1226 ///
1227 /// let v = it.collect(GFP_KERNEL);
1228 /// assert_eq!(v, [2, 3]);
1229 ///
1230 /// # Ok::<(), Error>(())
1231 /// ```
1232 ///
1233 /// # Implementation details
1234 ///
1235 /// Currently, we can't implement `FromIterator`. There are a couple of issues with this trait
1236 /// in the kernel, namely:
1237 ///
1238 /// - Rust's specialization feature is unstable. This prevents us to optimize for the special
1239 /// case where `I::IntoIter` equals `Vec`'s `IntoIter` type.
1240 /// - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator`
1241 /// doesn't require this type to be `'static`.
1242 /// - `FromIterator::from_iter` does return `Self` instead of `Result<Self, AllocError>`, hence
1243 /// we can't properly handle allocation failures.
1244 /// - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation
1245 /// flags.
1246 ///
1247 /// Instead, provide `IntoIter::collect`, such that we can at least convert a `IntoIter` into a
1248 /// `Vec` again.
1249 ///
1250 /// Note that `IntoIter::collect` doesn't require `Flags`, since it re-uses the existing backing
1251 /// buffer. However, this backing buffer may be shrunk to the actual count of elements.
1252 pub fn collect(self, flags: Flags) -> Vec<T, A> {
1253 let old_layout = self.layout;
1254 let (mut ptr, buf, len, mut cap) = self.into_raw_parts();
1255 let has_advanced = ptr != buf.as_ptr();
1256
1257 if has_advanced {
1258 // Copy the contents we have advanced to at the beginning of the buffer.
1259 //
1260 // SAFETY:
1261 // - `ptr` is valid for reads of `len * size_of::<T>()` bytes,
1262 // - `buf.as_ptr()` is valid for writes of `len * size_of::<T>()` bytes,
1263 // - `ptr` and `buf.as_ptr()` are not be subject to aliasing restrictions relative to
1264 // each other,
1265 // - both `ptr` and `buf.ptr()` are properly aligned.
1266 unsafe { ptr::copy(ptr, buf.as_ptr(), len) };
1267 ptr = buf.as_ptr();
1268
1269 // SAFETY: `len` is guaranteed to be smaller than `self.layout.len()` by the type
1270 // invariant.
1271 let layout = unsafe { ArrayLayout::<T>::new_unchecked(len) };
1272
1273 // SAFETY: `buf` points to the start of the backing buffer and `len` is guaranteed by
1274 // the type invariant to be smaller than `cap`. Depending on `realloc` this operation
1275 // may shrink the buffer or leave it as it is.
1276 ptr = match unsafe {
1277 A::realloc(
1278 Some(buf.cast()),
1279 layout.into(),
1280 old_layout.into(),
1281 flags,
1282 NumaNode::NO_NODE,
1283 )
1284 } {
1285 // If we fail to shrink, which likely can't even happen, continue with the existing
1286 // buffer.
1287 Err(_) => ptr,
1288 Ok(ptr) => {
1289 cap = len;
1290 ptr.as_ptr().cast()
1291 }
1292 };
1293 }
1294
1295 // SAFETY: If the iterator has been advanced, the advanced elements have been copied to
1296 // the beginning of the buffer and `len` has been adjusted accordingly.
1297 //
1298 // - `ptr` is guaranteed to point to the start of the backing buffer.
1299 // - `cap` is either the original capacity or, after shrinking the buffer, equal to `len`.
1300 // - `alloc` is guaranteed to be unchanged since `into_iter` has been called on the original
1301 // `Vec`.
1302 unsafe { Vec::from_raw_parts(ptr, len, cap) }
1303 }
1304}
1305
1306impl<T, A> Iterator for IntoIter<T, A>
1307where
1308 A: Allocator,
1309{
1310 type Item = T;
1311
1312 /// # Examples
1313 ///
1314 /// ```
1315 /// let v = kernel::kvec![1, 2, 3]?;
1316 /// let mut it = v.into_iter();
1317 ///
1318 /// assert_eq!(it.next(), Some(1));
1319 /// assert_eq!(it.next(), Some(2));
1320 /// assert_eq!(it.next(), Some(3));
1321 /// assert_eq!(it.next(), None);
1322 ///
1323 /// # Ok::<(), Error>(())
1324 /// ```
1325 fn next(&mut self) -> Option<T> {
1326 if self.len == 0 {
1327 return None;
1328 }
1329
1330 let current = self.ptr;
1331
1332 // SAFETY: We can't overflow; decreasing `self.len` by one every time we advance `self.ptr`
1333 // by one guarantees that.
1334 unsafe { self.ptr = self.ptr.add(1) };
1335
1336 self.len -= 1;
1337
1338 // SAFETY: `current` is guaranteed to point at a valid element within the buffer.
1339 Some(unsafe { current.read() })
1340 }
1341
1342 /// # Examples
1343 ///
1344 /// ```
1345 /// let v: KVec<u32> = kernel::kvec![1, 2, 3]?;
1346 /// let mut iter = v.into_iter();
1347 /// let size = iter.size_hint().0;
1348 ///
1349 /// iter.next();
1350 /// assert_eq!(iter.size_hint().0, size - 1);
1351 ///
1352 /// iter.next();
1353 /// assert_eq!(iter.size_hint().0, size - 2);
1354 ///
1355 /// iter.next();
1356 /// assert_eq!(iter.size_hint().0, size - 3);
1357 ///
1358 /// # Ok::<(), Error>(())
1359 /// ```
1360 fn size_hint(&self) -> (usize, Option<usize>) {
1361 (self.len, Some(self.len))
1362 }
1363}
1364
1365impl<T, A> Drop for IntoIter<T, A>
1366where
1367 A: Allocator,
1368{
1369 fn drop(&mut self) {
1370 // SAFETY: `self.ptr` is guaranteed to be valid by the type invariant.
1371 unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.ptr, self.len)) };
1372
1373 // SAFETY:
1374 // - `self.buf` was previously allocated with `A`.
1375 // - `self.layout` matches the `ArrayLayout` of the preceding allocation.
1376 unsafe { A::free(self.buf.cast(), self.layout.into()) };
1377 }
1378}
1379
1380impl<T, A> IntoIterator for Vec<T, A>
1381where
1382 A: Allocator,
1383{
1384 type Item = T;
1385 type IntoIter = IntoIter<T, A>;
1386
1387 /// Consumes the `Vec<T, A>` and creates an `Iterator`, which moves each value out of the
1388 /// vector (from start to end).
1389 ///
1390 /// # Examples
1391 ///
1392 /// ```
1393 /// let v = kernel::kvec![1, 2]?;
1394 /// let mut v_iter = v.into_iter();
1395 ///
1396 /// let first_element: Option<u32> = v_iter.next();
1397 ///
1398 /// assert_eq!(first_element, Some(1));
1399 /// assert_eq!(v_iter.next(), Some(2));
1400 /// assert_eq!(v_iter.next(), None);
1401 ///
1402 /// # Ok::<(), Error>(())
1403 /// ```
1404 ///
1405 /// ```
1406 /// let v = kernel::kvec![];
1407 /// let mut v_iter = v.into_iter();
1408 ///
1409 /// let first_element: Option<u32> = v_iter.next();
1410 ///
1411 /// assert_eq!(first_element, None);
1412 ///
1413 /// # Ok::<(), Error>(())
1414 /// ```
1415 #[inline]
1416 fn into_iter(self) -> Self::IntoIter {
1417 let buf = self.ptr;
1418 let layout = self.layout;
1419 let (ptr, len, _) = self.into_raw_parts();
1420
1421 IntoIter {
1422 ptr,
1423 buf,
1424 len,
1425 layout,
1426 _p: PhantomData::<A>,
1427 }
1428 }
1429}
1430
1431/// An iterator that owns all items in a vector, but does not own its allocation.
1432///
1433/// # Invariants
1434///
1435/// Every `&mut T` returned by the iterator references a `T` that the iterator may take ownership
1436/// of.
1437pub struct DrainAll<'vec, T> {
1438 elements: slice::IterMut<'vec, T>,
1439}
1440
1441impl<'vec, T> Iterator for DrainAll<'vec, T> {
1442 type Item = T;
1443
1444 fn next(&mut self) -> Option<T> {
1445 let elem: *mut T = self.elements.next()?;
1446 // SAFETY: By the type invariants, we may take ownership of this value.
1447 Some(unsafe { elem.read() })
1448 }
1449
1450 fn size_hint(&self) -> (usize, Option<usize>) {
1451 self.elements.size_hint()
1452 }
1453}
1454
1455impl<'vec, T> Drop for DrainAll<'vec, T> {
1456 fn drop(&mut self) {
1457 if core::mem::needs_drop::<T>() {
1458 let iter = core::mem::take(&mut self.elements);
1459 let ptr: *mut [T] = iter.into_slice();
1460 // SAFETY: By the type invariants, we own these values so we may destroy them.
1461 unsafe { ptr::drop_in_place(ptr) };
1462 }
1463 }
1464}
1465
1466#[macros::kunit_tests(rust_kvec)]
1467mod tests {
1468 use super::*;
1469 use crate::prelude::*;
1470
1471 #[test]
1472 fn test_kvec_retain() {
1473 /// Verify correctness for one specific function.
1474 #[expect(clippy::needless_range_loop)]
1475 fn verify(c: &[bool]) {
1476 let mut vec1: KVec<usize> = KVec::with_capacity(c.len(), GFP_KERNEL).unwrap();
1477 let mut vec2: KVec<usize> = KVec::with_capacity(c.len(), GFP_KERNEL).unwrap();
1478
1479 for i in 0..c.len() {
1480 vec1.push_within_capacity(i).unwrap();
1481 if c[i] {
1482 vec2.push_within_capacity(i).unwrap();
1483 }
1484 }
1485
1486 vec1.retain(|i| c[*i]);
1487
1488 assert_eq!(vec1, vec2);
1489 }
1490
1491 /// Add one to a binary integer represented as a boolean array.
1492 fn add(value: &mut [bool]) {
1493 let mut carry = true;
1494 for v in value {
1495 let new_v = carry != *v;
1496 carry = carry && *v;
1497 *v = new_v;
1498 }
1499 }
1500
1501 // This boolean array represents a function from index to boolean. We check that `retain`
1502 // behaves correctly for all possible boolean arrays of every possible length less than
1503 // ten.
1504 let mut func = KVec::with_capacity(10, GFP_KERNEL).unwrap();
1505 for len in 0..10 {
1506 for _ in 0u32..1u32 << len {
1507 verify(&func);
1508 add(&mut func);
1509 }
1510 func.push_within_capacity(false).unwrap();
1511 }
1512 }
1513
1514 #[test]
1515 fn test_kvvec_shrink_to() {
1516 use crate::page::PAGE_SIZE;
1517
1518 // Create a vector with capacity spanning multiple pages.
1519 let mut v = KVVec::<u8>::with_capacity(PAGE_SIZE * 4, GFP_KERNEL).unwrap();
1520
1521 // Add a few elements.
1522 v.push(1, GFP_KERNEL).unwrap();
1523 v.push(2, GFP_KERNEL).unwrap();
1524 v.push(3, GFP_KERNEL).unwrap();
1525
1526 let initial_capacity = v.capacity();
1527 assert!(initial_capacity >= PAGE_SIZE * 4);
1528
1529 // Shrink to a capacity that would free at least one page.
1530 v.shrink_to(PAGE_SIZE, GFP_KERNEL).unwrap();
1531
1532 // Capacity should have been reduced.
1533 assert!(v.capacity() < initial_capacity);
1534 assert!(v.capacity() >= PAGE_SIZE);
1535
1536 // Elements should be preserved.
1537 assert_eq!(v.len(), 3);
1538 assert_eq!(v[0], 1);
1539 assert_eq!(v[1], 2);
1540 assert_eq!(v[2], 3);
1541
1542 // Shrink to zero (should shrink to len).
1543 v.shrink_to(0, GFP_KERNEL).unwrap();
1544
1545 // Capacity should be at least the length.
1546 assert!(v.capacity() >= v.len());
1547
1548 // Elements should still be preserved.
1549 assert_eq!(v.len(), 3);
1550 assert_eq!(v[0], 1);
1551 assert_eq!(v[1], 2);
1552 assert_eq!(v[2], 3);
1553 }
1554
1555 #[test]
1556 fn test_kvvec_shrink_to_empty() {
1557 use crate::page::PAGE_SIZE;
1558
1559 // Create a vector with large capacity but no elements.
1560 let mut v = KVVec::<u8>::with_capacity(PAGE_SIZE * 4, GFP_KERNEL).unwrap();
1561
1562 assert!(v.is_empty());
1563
1564 // Shrink empty vector to zero.
1565 v.shrink_to(0, GFP_KERNEL).unwrap();
1566
1567 // Should have freed the allocation.
1568 assert_eq!(v.capacity(), 0);
1569 assert!(v.is_empty());
1570 }
1571
1572 #[test]
1573 fn test_kvvec_shrink_to_no_op() {
1574 use crate::page::PAGE_SIZE;
1575
1576 // Create a small vector.
1577 let mut v = KVVec::<u8>::with_capacity(PAGE_SIZE, GFP_KERNEL).unwrap();
1578 v.push(1, GFP_KERNEL).unwrap();
1579
1580 let capacity_before = v.capacity();
1581
1582 // Try to shrink to a capacity larger than current - should be no-op.
1583 v.shrink_to(capacity_before + 100, GFP_KERNEL).unwrap();
1584
1585 assert_eq!(v.capacity(), capacity_before);
1586 assert_eq!(v.len(), 1);
1587 assert_eq!(v[0], 1);
1588 }
1589
1590 #[test]
1591 fn test_kvvec_shrink_to_respects_min_capacity() {
1592 use crate::page::PAGE_SIZE;
1593
1594 // Create a vector with large capacity.
1595 let mut v = KVVec::<u8>::with_capacity(PAGE_SIZE * 4, GFP_KERNEL).unwrap();
1596
1597 // Add some elements.
1598 for i in 0..10u8 {
1599 v.push(i, GFP_KERNEL).unwrap();
1600 }
1601
1602 // Shrink to a min_capacity larger than length.
1603 let min_cap = PAGE_SIZE * 2;
1604 v.shrink_to(min_cap, GFP_KERNEL).unwrap();
1605
1606 // Capacity should be at least min_capacity.
1607 assert!(v.capacity() >= min_cap);
1608
1609 // All elements preserved.
1610 assert_eq!(v.len(), 10);
1611 for i in 0..10u8 {
1612 assert_eq!(v[i as usize], i);
1613 }
1614 }
1615}