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