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