Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

Merge tag 'alloc-next-v6.16-2025-05-13' of https://github.com/Rust-for-Linux/linux into rust-next

Pull alloc updates from Danilo Krummrich:
"Box:

- Support for type coercion, e.g. 'Box<T>' to 'Box<dyn U>' if T
implements U

Vec:

- Implement new methods (prerequisites for nova-core and binder)
- Vec::truncate()
- Vec::resize()
- Vec::clear()
- Vec::pop()
- Vec::push_within_capacity()
- New error type: PushError
- Vec::drain_all()
- Vec::retain()
- Vec::remove()
- New error type: RemoveError
- Vec::insert_within_capacity
- New error type: InsertError

- Simplify Vec::push() using Vec::spare_capacity_mut()

- Split Vec::set_len() into Vec::inc_len() and Vec::dec_len()
- Add type invariant Vec::len() <= Vec::capacity
- Simplify Vec::truncate() using Vec::dec_len()"

* tag 'alloc-next-v6.16-2025-05-13' of https://github.com/Rust-for-Linux/linux:
rust: alloc: add Vec::insert_within_capacity
rust: alloc: add Vec::remove
rust: alloc: add Vec::retain
rust: alloc: add Vec::drain_all
rust: alloc: add Vec::push_within_capacity
rust: alloc: add Vec::pop
rust: alloc: add Vec::clear
rust: alloc: replace `Vec::set_len` with `inc_len`
rust: alloc: refactor `Vec::truncate` using `dec_len`
rust: alloc: add `Vec::dec_len`
rust: alloc: add Vec::len() <= Vec::capacity invariant
rust: alloc: allow coercion from `Box<T>` to `Box<dyn U>` if T implements U
rust: alloc: use `spare_capacity_mut` to reduce unsafe
rust: alloc: add Vec::resize method
rust: alloc: add Vec::truncate method
rust: alloc: add missing invariant in Vec::set_len()

+506 -29
+39 -1
rust/kernel/alloc/kbox.rs
··· 57 57 /// assert!(KVBox::<Huge>::new_uninit(GFP_KERNEL).is_ok()); 58 58 /// ``` 59 59 /// 60 + /// [`Box`]es can also be used to store trait objects by coercing their type: 61 + /// 62 + /// ``` 63 + /// trait FooTrait {} 64 + /// 65 + /// struct FooStruct; 66 + /// impl FooTrait for FooStruct {} 67 + /// 68 + /// let _ = KBox::new(FooStruct, GFP_KERNEL)? as KBox<dyn FooTrait>; 69 + /// # Ok::<(), Error>(()) 70 + /// ``` 71 + /// 60 72 /// # Invariants 61 73 /// 62 74 /// `self.0` is always properly aligned and either points to memory allocated with `A` or, for 63 75 /// zero-sized types, is a dangling, well aligned pointer. 64 76 #[repr(transparent)] 65 - pub struct Box<T: ?Sized, A: Allocator>(NonNull<T>, PhantomData<A>); 77 + #[cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, derive(core::marker::CoercePointee))] 78 + pub struct Box<#[cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, pointee)] T: ?Sized, A: Allocator>( 79 + NonNull<T>, 80 + PhantomData<A>, 81 + ); 82 + 83 + // This is to allow coercion from `Box<T, A>` to `Box<U, A>` if `T` can be converted to the 84 + // dynamically-sized type (DST) `U`. 85 + #[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))] 86 + impl<T, U, A> core::ops::CoerceUnsized<Box<U, A>> for Box<T, A> 87 + where 88 + T: ?Sized + core::marker::Unsize<U>, 89 + U: ?Sized, 90 + A: Allocator, 91 + { 92 + } 93 + 94 + // This is to allow `Box<U, A>` to be dispatched on when `Box<T, A>` can be coerced into `Box<U, 95 + // A>`. 96 + #[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))] 97 + impl<T, U, A> core::ops::DispatchFromDyn<Box<U, A>> for Box<T, A> 98 + where 99 + T: ?Sized + core::marker::Unsize<U>, 100 + U: ?Sized, 101 + A: Allocator, 102 + { 103 + } 66 104 67 105 /// Type alias for [`Box`] with a [`Kmalloc`] allocator. 68 106 ///
+404 -26
rust/kernel/alloc/kvec.rs
··· 24 24 slice::SliceIndex, 25 25 }; 26 26 27 + mod errors; 28 + pub use self::errors::{InsertError, PushError, RemoveError}; 29 + 27 30 /// Create a [`KVec`] containing the arguments. 28 31 /// 29 32 /// New memory is allocated with `GFP_KERNEL`. ··· 95 92 /// - `self.layout` represents the absolute number of elements that can be stored within the vector 96 93 /// without re-allocation. For ZSTs `self.layout`'s capacity is zero. However, it is legal for the 97 94 /// backing buffer to be larger than `layout`. 95 + /// 96 + /// - `self.len()` is always less than or equal to `self.capacity()`. 98 97 /// 99 98 /// - The `Allocator` type `A` of the vector is the exact same `Allocator` type the backing buffer 100 99 /// was allocated with (and must be freed with). ··· 191 186 self.len 192 187 } 193 188 194 - /// Forcefully sets `self.len` to `new_len`. 189 + /// Increments `self.len` by `additional`. 195 190 /// 196 191 /// # Safety 197 192 /// 198 - /// - `new_len` must be less than or equal to [`Self::capacity`]. 199 - /// - If `new_len` is greater than `self.len`, all elements within the interval 200 - /// [`self.len`,`new_len`) must be initialized. 193 + /// - `additional` must be less than or equal to `self.capacity - self.len`. 194 + /// - All elements within the interval [`self.len`,`self.len + additional`) must be initialized. 201 195 #[inline] 202 - pub unsafe fn set_len(&mut self, new_len: usize) { 203 - debug_assert!(new_len <= self.capacity()); 204 - self.len = new_len; 196 + pub unsafe fn inc_len(&mut self, additional: usize) { 197 + // Guaranteed by the type invariant to never underflow. 198 + debug_assert!(additional <= self.capacity() - self.len()); 199 + // INVARIANT: By the safety requirements of this method this represents the exact number of 200 + // elements stored within `self`. 201 + self.len += additional; 202 + } 203 + 204 + /// Decreases `self.len` by `count`. 205 + /// 206 + /// Returns a mutable slice to the elements forgotten by the vector. It is the caller's 207 + /// responsibility to drop these elements if necessary. 208 + /// 209 + /// # Safety 210 + /// 211 + /// - `count` must be less than or equal to `self.len`. 212 + unsafe fn dec_len(&mut self, count: usize) -> &mut [T] { 213 + debug_assert!(count <= self.len()); 214 + // INVARIANT: We relinquish ownership of the elements within the range `[self.len - count, 215 + // self.len)`, hence the updated value of `set.len` represents the exact number of elements 216 + // stored within `self`. 217 + self.len -= count; 218 + // SAFETY: The memory after `self.len()` is guaranteed to contain `count` initialized 219 + // elements of type `T`. 220 + unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().add(self.len), count) } 205 221 } 206 222 207 223 /// Returns a slice of the entire vector. ··· 288 262 /// Returns a slice of `MaybeUninit<T>` for the remaining spare capacity of the vector. 289 263 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] { 290 264 // SAFETY: 291 - // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is 292 - // guaranteed to be part of the same allocated object. 265 + // - `self.len` is smaller than `self.capacity` by the type invariant and hence, the 266 + // resulting pointer is guaranteed to be part of the same allocated object. 293 267 // - `self.len` can not overflow `isize`. 294 268 let ptr = unsafe { self.as_mut_ptr().add(self.len) } as *mut MaybeUninit<T>; 295 269 ··· 313 287 /// ``` 314 288 pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> { 315 289 self.reserve(1, flags)?; 290 + // SAFETY: The call to `reserve` was successful, so the capacity is at least one greater 291 + // than the length. 292 + unsafe { self.push_within_capacity_unchecked(v) }; 293 + Ok(()) 294 + } 316 295 317 - // SAFETY: 318 - // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is 319 - // guaranteed to be part of the same allocated object. 320 - // - `self.len` can not overflow `isize`. 321 - let ptr = unsafe { self.as_mut_ptr().add(self.len) }; 296 + /// Appends an element to the back of the [`Vec`] instance without reallocating. 297 + /// 298 + /// Fails if the vector does not have capacity for the new element. 299 + /// 300 + /// # Examples 301 + /// 302 + /// ``` 303 + /// let mut v = KVec::with_capacity(10, GFP_KERNEL)?; 304 + /// for i in 0..10 { 305 + /// v.push_within_capacity(i)?; 306 + /// } 307 + /// 308 + /// assert!(v.push_within_capacity(10).is_err()); 309 + /// # Ok::<(), Error>(()) 310 + /// ``` 311 + pub fn push_within_capacity(&mut self, v: T) -> Result<(), PushError<T>> { 312 + if self.len() < self.capacity() { 313 + // SAFETY: The length is less than the capacity. 314 + unsafe { self.push_within_capacity_unchecked(v) }; 315 + Ok(()) 316 + } else { 317 + Err(PushError(v)) 318 + } 319 + } 322 320 323 - // SAFETY: 324 - // - `ptr` is properly aligned and valid for writes. 325 - unsafe { core::ptr::write(ptr, v) }; 321 + /// Appends an element to the back of the [`Vec`] instance without reallocating. 322 + /// 323 + /// # Safety 324 + /// 325 + /// The length must be less than the capacity. 326 + unsafe fn push_within_capacity_unchecked(&mut self, v: T) { 327 + let spare = self.spare_capacity_mut(); 328 + 329 + // SAFETY: By the safety requirements, `spare` is non-empty. 330 + unsafe { spare.get_unchecked_mut(0) }.write(v); 326 331 327 332 // SAFETY: We just initialised the first spare entry, so it is safe to increase the length 328 - // by 1. We also know that the new length is <= capacity because of the previous call to 329 - // `reserve` above. 330 - unsafe { self.set_len(self.len() + 1) }; 333 + // by 1. We also know that the new length is <= capacity because the caller guarantees that 334 + // the length is less than the capacity at the beginning of this function. 335 + unsafe { self.inc_len(1) }; 336 + } 337 + 338 + /// Inserts an element at the given index in the [`Vec`] instance. 339 + /// 340 + /// Fails if the vector does not have capacity for the new element. Panics if the index is out 341 + /// of bounds. 342 + /// 343 + /// # Examples 344 + /// 345 + /// ``` 346 + /// use kernel::alloc::kvec::InsertError; 347 + /// 348 + /// let mut v = KVec::with_capacity(5, GFP_KERNEL)?; 349 + /// for i in 0..5 { 350 + /// v.insert_within_capacity(0, i)?; 351 + /// } 352 + /// 353 + /// assert!(matches!(v.insert_within_capacity(0, 5), Err(InsertError::OutOfCapacity(_)))); 354 + /// assert!(matches!(v.insert_within_capacity(1000, 5), Err(InsertError::IndexOutOfBounds(_)))); 355 + /// assert_eq!(v, [4, 3, 2, 1, 0]); 356 + /// # Ok::<(), Error>(()) 357 + /// ``` 358 + pub fn insert_within_capacity( 359 + &mut self, 360 + index: usize, 361 + element: T, 362 + ) -> Result<(), InsertError<T>> { 363 + let len = self.len(); 364 + if index > len { 365 + return Err(InsertError::IndexOutOfBounds(element)); 366 + } 367 + 368 + if len >= self.capacity() { 369 + return Err(InsertError::OutOfCapacity(element)); 370 + } 371 + 372 + // SAFETY: This is in bounds since `index <= len < capacity`. 373 + let p = unsafe { self.as_mut_ptr().add(index) }; 374 + // INVARIANT: This breaks the Vec invariants by making `index` contain an invalid element, 375 + // but we restore the invariants below. 376 + // SAFETY: Both the src and dst ranges end no later than one element after the length. 377 + // Since the length is less than the capacity, both ranges are in bounds of the allocation. 378 + unsafe { ptr::copy(p, p.add(1), len - index) }; 379 + // INVARIANT: This restores the Vec invariants. 380 + // SAFETY: The pointer is in-bounds of the allocation. 381 + unsafe { ptr::write(p, element) }; 382 + // SAFETY: Index `len` contains a valid element due to the above copy and write. 383 + unsafe { self.inc_len(1) }; 331 384 Ok(()) 385 + } 386 + 387 + /// Removes the last element from a vector and returns it, or `None` if it is empty. 388 + /// 389 + /// # Examples 390 + /// 391 + /// ``` 392 + /// let mut v = KVec::new(); 393 + /// v.push(1, GFP_KERNEL)?; 394 + /// v.push(2, GFP_KERNEL)?; 395 + /// assert_eq!(&v, &[1, 2]); 396 + /// 397 + /// assert_eq!(v.pop(), Some(2)); 398 + /// assert_eq!(v.pop(), Some(1)); 399 + /// assert_eq!(v.pop(), None); 400 + /// # Ok::<(), Error>(()) 401 + /// ``` 402 + pub fn pop(&mut self) -> Option<T> { 403 + if self.is_empty() { 404 + return None; 405 + } 406 + 407 + let removed: *mut T = { 408 + // SAFETY: We just checked that the length is at least one. 409 + let slice = unsafe { self.dec_len(1) }; 410 + // SAFETY: The argument to `dec_len` was 1 so this returns a slice of length 1. 411 + unsafe { slice.get_unchecked_mut(0) } 412 + }; 413 + 414 + // SAFETY: The guarantees of `dec_len` allow us to take ownership of this value. 415 + Some(unsafe { removed.read() }) 416 + } 417 + 418 + /// Removes the element at the given index. 419 + /// 420 + /// # Examples 421 + /// 422 + /// ``` 423 + /// let mut v = kernel::kvec![1, 2, 3]?; 424 + /// assert_eq!(v.remove(1)?, 2); 425 + /// assert_eq!(v, [1, 3]); 426 + /// # Ok::<(), Error>(()) 427 + /// ``` 428 + pub fn remove(&mut self, i: usize) -> Result<T, RemoveError> { 429 + let value = { 430 + let value_ref = self.get(i).ok_or(RemoveError)?; 431 + // INVARIANT: This breaks the invariants by invalidating the value at index `i`, but we 432 + // restore the invariants below. 433 + // SAFETY: The value at index `i` is valid, because otherwise we would have already 434 + // failed with `RemoveError`. 435 + unsafe { ptr::read(value_ref) } 436 + }; 437 + 438 + // SAFETY: We checked that `i` is in-bounds. 439 + let p = unsafe { self.as_mut_ptr().add(i) }; 440 + 441 + // INVARIANT: After this call, the invalid value is at the last slot, so the Vec invariants 442 + // are restored after the below call to `dec_len(1)`. 443 + // SAFETY: `p.add(1).add(self.len - i - 1)` is `i+1+len-i-1 == len` elements after the 444 + // beginning of the vector, so this is in-bounds of the vector's allocation. 445 + unsafe { ptr::copy(p.add(1), p, self.len - i - 1) }; 446 + 447 + // SAFETY: Since the check at the beginning of this call did not fail with `RemoveError`, 448 + // the length is at least one. 449 + unsafe { self.dec_len(1) }; 450 + 451 + Ok(value) 332 452 } 333 453 334 454 /// Creates a new [`Vec`] instance with at least the given capacity. ··· 570 398 (ptr, len, capacity) 571 399 } 572 400 401 + /// Clears the vector, removing all values. 402 + /// 403 + /// Note that this method has no effect on the allocated capacity 404 + /// of the vector. 405 + /// 406 + /// # Examples 407 + /// 408 + /// ``` 409 + /// let mut v = kernel::kvec![1, 2, 3]?; 410 + /// 411 + /// v.clear(); 412 + /// 413 + /// assert!(v.is_empty()); 414 + /// # Ok::<(), Error>(()) 415 + /// ``` 416 + #[inline] 417 + pub fn clear(&mut self) { 418 + self.truncate(0); 419 + } 420 + 573 421 /// Ensures that the capacity exceeds the length by at least `additional` elements. 574 422 /// 575 423 /// # Examples ··· 647 455 648 456 Ok(()) 649 457 } 458 + 459 + /// Shortens the vector, setting the length to `len` and drops the removed values. 460 + /// If `len` is greater than or equal to the current length, this does nothing. 461 + /// 462 + /// This has no effect on the capacity and will not allocate. 463 + /// 464 + /// # Examples 465 + /// 466 + /// ``` 467 + /// let mut v = kernel::kvec![1, 2, 3]?; 468 + /// v.truncate(1); 469 + /// assert_eq!(v.len(), 1); 470 + /// assert_eq!(&v, &[1]); 471 + /// 472 + /// # Ok::<(), Error>(()) 473 + /// ``` 474 + pub fn truncate(&mut self, len: usize) { 475 + if let Some(count) = self.len().checked_sub(len) { 476 + // SAFETY: `count` is `self.len() - len` so it is guaranteed to be less than or 477 + // equal to `self.len()`. 478 + let ptr: *mut [T] = unsafe { self.dec_len(count) }; 479 + 480 + // SAFETY: the contract of `dec_len` guarantees that the elements in `ptr` are 481 + // valid elements whose ownership has been transferred to the caller. 482 + unsafe { ptr::drop_in_place(ptr) }; 483 + } 484 + } 485 + 486 + /// Takes ownership of all items in this vector without consuming the allocation. 487 + /// 488 + /// # Examples 489 + /// 490 + /// ``` 491 + /// let mut v = kernel::kvec![0, 1, 2, 3]?; 492 + /// 493 + /// for (i, j) in v.drain_all().enumerate() { 494 + /// assert_eq!(i, j); 495 + /// } 496 + /// 497 + /// assert!(v.capacity() >= 4); 498 + /// # Ok::<(), Error>(()) 499 + /// ``` 500 + pub fn drain_all(&mut self) -> DrainAll<'_, T> { 501 + // SAFETY: This does not underflow the length. 502 + let elems = unsafe { self.dec_len(self.len()) }; 503 + // INVARIANT: The first `len` elements of the spare capacity are valid values, and as we 504 + // just set the length to zero, we may transfer ownership to the `DrainAll` object. 505 + DrainAll { 506 + elements: elems.iter_mut(), 507 + } 508 + } 509 + 510 + /// Removes all elements that don't match the provided closure. 511 + /// 512 + /// # Examples 513 + /// 514 + /// ``` 515 + /// let mut v = kernel::kvec![1, 2, 3, 4]?; 516 + /// v.retain(|i| *i % 2 == 0); 517 + /// assert_eq!(v, [2, 4]); 518 + /// # Ok::<(), Error>(()) 519 + /// ``` 520 + pub fn retain(&mut self, mut f: impl FnMut(&mut T) -> bool) { 521 + let mut num_kept = 0; 522 + let mut next_to_check = 0; 523 + while let Some(to_check) = self.get_mut(next_to_check) { 524 + if f(to_check) { 525 + self.swap(num_kept, next_to_check); 526 + num_kept += 1; 527 + } 528 + next_to_check += 1; 529 + } 530 + self.truncate(num_kept); 531 + } 650 532 } 651 533 652 534 impl<T: Clone, A: Allocator> Vec<T, A> { ··· 744 478 // SAFETY: 745 479 // - `self.len() + n < self.capacity()` due to the call to reserve above, 746 480 // - the loop and the line above initialized the next `n` elements. 747 - unsafe { self.set_len(self.len() + n) }; 481 + unsafe { self.inc_len(n) }; 748 482 749 483 Ok(()) 750 484 } ··· 775 509 // the length by the same number. 776 510 // - `self.len() + other.len() <= self.capacity()` is guaranteed by the preceding `reserve` 777 511 // call. 778 - unsafe { self.set_len(self.len() + other.len()) }; 512 + unsafe { self.inc_len(other.len()) }; 779 513 Ok(()) 780 514 } 781 515 ··· 786 520 v.extend_with(n, value, flags)?; 787 521 788 522 Ok(v) 523 + } 524 + 525 + /// Resizes the [`Vec`] so that `len` is equal to `new_len`. 526 + /// 527 + /// If `new_len` is smaller than `len`, the `Vec` is [`Vec::truncate`]d. 528 + /// If `new_len` is larger, each new slot is filled with clones of `value`. 529 + /// 530 + /// # Examples 531 + /// 532 + /// ``` 533 + /// let mut v = kernel::kvec![1, 2, 3]?; 534 + /// v.resize(1, 42, GFP_KERNEL)?; 535 + /// assert_eq!(&v, &[1]); 536 + /// 537 + /// v.resize(3, 42, GFP_KERNEL)?; 538 + /// assert_eq!(&v, &[1, 42, 42]); 539 + /// 540 + /// # Ok::<(), Error>(()) 541 + /// ``` 542 + pub fn resize(&mut self, new_len: usize, value: T, flags: Flags) -> Result<(), AllocError> { 543 + match new_len.checked_sub(self.len()) { 544 + Some(n) => self.extend_with(n, value, flags), 545 + None => { 546 + self.truncate(new_len); 547 + Ok(()) 548 + } 549 + } 789 550 } 790 551 } 791 552 ··· 1053 760 unsafe { ptr::copy(ptr, buf.as_ptr(), len) }; 1054 761 ptr = buf.as_ptr(); 1055 762 1056 - // SAFETY: `len` is guaranteed to be smaller than `self.layout.len()`. 763 + // SAFETY: `len` is guaranteed to be smaller than `self.layout.len()` by the type 764 + // invariant. 1057 765 let layout = unsafe { ArrayLayout::<T>::new_unchecked(len) }; 1058 766 1059 - // SAFETY: `buf` points to the start of the backing buffer and `len` is guaranteed to be 1060 - // smaller than `cap`. Depending on `alloc` this operation may shrink the buffer or leaves 1061 - // it as it is. 767 + // SAFETY: `buf` points to the start of the backing buffer and `len` is guaranteed by 768 + // the type invariant to be smaller than `cap`. Depending on `realloc` this operation 769 + // may shrink the buffer or leave it as it is. 1062 770 ptr = match unsafe { 1063 771 A::realloc(Some(buf.cast()), layout.into(), old_layout.into(), flags) 1064 772 } { ··· 1205 911 len, 1206 912 layout, 1207 913 _p: PhantomData::<A>, 914 + } 915 + } 916 + } 917 + 918 + /// An iterator that owns all items in a vector, but does not own its allocation. 919 + /// 920 + /// # Invariants 921 + /// 922 + /// Every `&mut T` returned by the iterator references a `T` that the iterator may take ownership 923 + /// of. 924 + pub struct DrainAll<'vec, T> { 925 + elements: slice::IterMut<'vec, T>, 926 + } 927 + 928 + impl<'vec, T> Iterator for DrainAll<'vec, T> { 929 + type Item = T; 930 + 931 + fn next(&mut self) -> Option<T> { 932 + let elem: *mut T = self.elements.next()?; 933 + // SAFETY: By the type invariants, we may take ownership of this value. 934 + Some(unsafe { elem.read() }) 935 + } 936 + 937 + fn size_hint(&self) -> (usize, Option<usize>) { 938 + self.elements.size_hint() 939 + } 940 + } 941 + 942 + impl<'vec, T> Drop for DrainAll<'vec, T> { 943 + fn drop(&mut self) { 944 + if core::mem::needs_drop::<T>() { 945 + let iter = core::mem::take(&mut self.elements); 946 + let ptr: *mut [T] = iter.into_slice(); 947 + // SAFETY: By the type invariants, we own these values so we may destroy them. 948 + unsafe { ptr::drop_in_place(ptr) }; 949 + } 950 + } 951 + } 952 + 953 + #[macros::kunit_tests(rust_kvec_kunit)] 954 + mod tests { 955 + use super::*; 956 + use crate::prelude::*; 957 + 958 + #[test] 959 + fn test_kvec_retain() { 960 + /// Verify correctness for one specific function. 961 + #[expect(clippy::needless_range_loop)] 962 + fn verify(c: &[bool]) { 963 + let mut vec1: KVec<usize> = KVec::with_capacity(c.len(), GFP_KERNEL).unwrap(); 964 + let mut vec2: KVec<usize> = KVec::with_capacity(c.len(), GFP_KERNEL).unwrap(); 965 + 966 + for i in 0..c.len() { 967 + vec1.push_within_capacity(i).unwrap(); 968 + if c[i] { 969 + vec2.push_within_capacity(i).unwrap(); 970 + } 971 + } 972 + 973 + vec1.retain(|i| c[*i]); 974 + 975 + assert_eq!(vec1, vec2); 976 + } 977 + 978 + /// Add one to a binary integer represented as a boolean array. 979 + fn add(value: &mut [bool]) { 980 + let mut carry = true; 981 + for v in value { 982 + let new_v = carry != *v; 983 + carry = carry && *v; 984 + *v = new_v; 985 + } 986 + } 987 + 988 + // This boolean array represents a function from index to boolean. We check that `retain` 989 + // behaves correctly for all possible boolean arrays of every possible length less than 990 + // ten. 991 + let mut func = KVec::with_capacity(10, GFP_KERNEL).unwrap(); 992 + for len in 0..10 { 993 + for _ in 0u32..1u32 << len { 994 + verify(&func); 995 + add(&mut func); 996 + } 997 + func.push_within_capacity(false).unwrap(); 1208 998 } 1209 999 } 1210 1000 }
+61
rust/kernel/alloc/kvec/errors.rs
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + 3 + //! Errors for the [`Vec`] type. 4 + 5 + use core::fmt::{self, Debug, Formatter}; 6 + use kernel::prelude::*; 7 + 8 + /// Error type for [`Vec::push_within_capacity`]. 9 + pub struct PushError<T>(pub T); 10 + 11 + impl<T> Debug for PushError<T> { 12 + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 13 + write!(f, "Not enough capacity") 14 + } 15 + } 16 + 17 + impl<T> From<PushError<T>> for Error { 18 + fn from(_: PushError<T>) -> Error { 19 + // Returning ENOMEM isn't appropriate because the system is not out of memory. The vector 20 + // is just full and we are refusing to resize it. 21 + EINVAL 22 + } 23 + } 24 + 25 + /// Error type for [`Vec::remove`]. 26 + pub struct RemoveError; 27 + 28 + impl Debug for RemoveError { 29 + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 30 + write!(f, "Index out of bounds") 31 + } 32 + } 33 + 34 + impl From<RemoveError> for Error { 35 + fn from(_: RemoveError) -> Error { 36 + EINVAL 37 + } 38 + } 39 + 40 + /// Error type for [`Vec::insert_within_capacity`]. 41 + pub enum InsertError<T> { 42 + /// The value could not be inserted because the index is out of bounds. 43 + IndexOutOfBounds(T), 44 + /// The value could not be inserted because the vector is out of capacity. 45 + OutOfCapacity(T), 46 + } 47 + 48 + impl<T> Debug for InsertError<T> { 49 + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 50 + match self { 51 + InsertError::IndexOutOfBounds(_) => write!(f, "Index out of bounds"), 52 + InsertError::OutOfCapacity(_) => write!(f, "Not enough capacity"), 53 + } 54 + } 55 + } 56 + 57 + impl<T> From<InsertError<T>> for Error { 58 + fn from(_: InsertError<T>) -> Error { 59 + EINVAL 60 + } 61 + }
+1 -1
rust/kernel/str.rs
··· 886 886 887 887 // SAFETY: The number of bytes that can be written to `f` is bounded by `size`, which is 888 888 // `buf`'s capacity. The contents of the buffer have been initialised by writes to `f`. 889 - unsafe { buf.set_len(f.bytes_written()) }; 889 + unsafe { buf.inc_len(f.bytes_written()) }; 890 890 891 891 // Check that there are no `NUL` bytes before the end. 892 892 // SAFETY: The buffer is valid for read because `f.bytes_written()` is bounded by `size`
+1 -1
rust/kernel/uaccess.rs
··· 288 288 289 289 // SAFETY: Since the call to `read_raw` was successful, so the next `len` bytes of the 290 290 // vector have been initialized. 291 - unsafe { buf.set_len(buf.len() + len) }; 291 + unsafe { buf.inc_len(len) }; 292 292 Ok(()) 293 293 } 294 294 }