summaryrefslogtreecommitdiff
path: root/rust/alloc/vec/drain.rs
diff options
context:
space:
mode:
authorLinus Torvalds <torvalds@linux-foundation.org>2024-05-13 15:13:54 -0700
committerLinus Torvalds <torvalds@linux-foundation.org>2024-05-13 15:13:54 -0700
commit8f5b5f78113e881cb8570c961b0dc42b218a1b9e (patch)
tree23b6c6271d8299e0d30f5b032ef9257d4ead903c /rust/alloc/vec/drain.rs
parent84c7d76b5ab6a52e1b3d8101b9f910c128dca396 (diff)
parent97ab3e8eec0ce79d9e265e6c9e4c480492180409 (diff)
Merge tag 'rust-6.10' of https://github.com/Rust-for-Linux/linux
Pull Rust updates from Miguel Ojeda: "The most notable change is the drop of the 'alloc' in-tree fork. This is nicely reflected in the diffstat as a ~10k lines drop. In turn, this makes the version upgrades way simpler and smaller in the future, e.g. the latest one in commit 56f64b370612 ("rust: upgrade to Rust 1.78.0"). More importantly, this increases the chances that a newer compiler version just works, which in turn means supporting several compiler versions is easier now. Thus we will look into finally setting a minimum version in the near future. Toolchain and infrastructure: - Upgrade to Rust 1.78.0 This time around, due to how the kernel and Rust schedules have aligned, there are two upgrades in fact. These allow us to remove one more unstable feature ('offset_of') from the list, among other improvements - Drop 'alloc' in-tree fork of the standard library crate, which means all the unstable features used by 'alloc' (~30 language ones, ~60 library ones) are not a concern anymore - Support DWARFv5 via the '-Zdwarf-version' flag - Support zlib and zstd debuginfo compression via the '-Zdebuginfo-compression' flag 'kernel' crate: - Support allocation flags ('GFP_*'), particularly in 'Box' (via 'BoxExt'), 'Vec' (via 'VecExt'), 'Arc' and 'UniqueArc', as well as in the 'init' module APIs - Remove usage of the 'allocator_api' unstable feature - Remove 'try_' prefix in allocation APIs' names - Add 'VecExt' (an extension trait) to be able to drop the 'alloc' fork - Add the '{make,to}_{upper,lower}case()' methods to 'CStr'/'CString' - Add the 'as_ptr' method to 'ThisModule' - Add the 'from_raw' method to 'ArcBorrow' - Add the 'into_unique_or_drop' method to 'Arc' - Display column number in the 'dbg!' macro output by applying the equivalent change done to the standard library one - Migrate 'Work' to '#[pin_data]' thanks to the changes in the 'macros' crate, which allows to remove an unsafe call in its 'new' associated function - Prevent namespacing issues when using the '[try_][pin_]init!' macros by changing the generated name of guard variables - Make the 'get' method in 'Opaque' const - Implement the 'Default' trait for 'LockClassKey' - Remove unneeded 'kernel::prelude' imports from doctests - Remove redundant imports 'macros' crate: - Add 'decl_generics' to 'parse_generics()' to support default values, and use that to allow them in '#[pin_data]' Helpers: - Trivial English grammar fix Documentation: - Add section on Rust Kselftests to the 'Testing' document - Expand the 'Abstractions vs. bindings' section of the 'General Information' document" * tag 'rust-6.10' of https://github.com/Rust-for-Linux/linux: (31 commits) rust: alloc: fix dangling pointer in VecExt<T>::reserve() rust: upgrade to Rust 1.78.0 rust: kernel: remove redundant imports rust: sync: implement `Default` for `LockClassKey` docs: rust: extend abstraction and binding documentation docs: rust: Add instructions for the Rust kselftest rust: remove unneeded `kernel::prelude` imports from doctests rust: update `dbg!()` to format column number rust: helpers: Fix grammar in comment rust: init: change the generated name of guard variables rust: sync: add `Arc::into_unique_or_drop` rust: sync: add `ArcBorrow::from_raw` rust: types: Make Opaque::get const rust: kernel: remove usage of `allocator_api` unstable feature rust: init: update `init` module to take allocation flags rust: sync: update `Arc` and `UniqueArc` to take allocation flags rust: alloc: update `VecExt` to take allocation flags rust: alloc: introduce the `BoxExt` trait rust: alloc: introduce allocation flags rust: alloc: remove our fork of the `alloc` crate ...
Diffstat (limited to 'rust/alloc/vec/drain.rs')
-rw-r--r--rust/alloc/vec/drain.rs255
1 files changed, 0 insertions, 255 deletions
diff --git a/rust/alloc/vec/drain.rs b/rust/alloc/vec/drain.rs
deleted file mode 100644
index 78177a9e2ad0..000000000000
--- a/rust/alloc/vec/drain.rs
+++ /dev/null
@@ -1,255 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0 OR MIT
-
-use crate::alloc::{Allocator, Global};
-use core::fmt;
-use core::iter::{FusedIterator, TrustedLen};
-use core::mem::{self, ManuallyDrop, SizedTypeProperties};
-use core::ptr::{self, NonNull};
-use core::slice::{self};
-
-use super::Vec;
-
-/// A draining iterator for `Vec<T>`.
-///
-/// This `struct` is created by [`Vec::drain`].
-/// See its documentation for more.
-///
-/// # Example
-///
-/// ```
-/// let mut v = vec![0, 1, 2];
-/// let iter: std::vec::Drain<'_, _> = v.drain(..);
-/// ```
-#[stable(feature = "drain", since = "1.6.0")]
-pub struct Drain<
- 'a,
- T: 'a,
- #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + 'a = Global,
-> {
- /// Index of tail to preserve
- pub(super) tail_start: usize,
- /// Length of tail
- pub(super) tail_len: usize,
- /// Current remaining range to remove
- pub(super) iter: slice::Iter<'a, T>,
- pub(super) vec: NonNull<Vec<T, A>>,
-}
-
-#[stable(feature = "collection_debug", since = "1.17.0")]
-impl<T: fmt::Debug, A: Allocator> fmt::Debug for Drain<'_, T, A> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
- }
-}
-
-impl<'a, T, A: Allocator> Drain<'a, T, A> {
- /// Returns the remaining items of this iterator as a slice.
- ///
- /// # Examples
- ///
- /// ```
- /// let mut vec = vec!['a', 'b', 'c'];
- /// let mut drain = vec.drain(..);
- /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
- /// let _ = drain.next().unwrap();
- /// assert_eq!(drain.as_slice(), &['b', 'c']);
- /// ```
- #[must_use]
- #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
- pub fn as_slice(&self) -> &[T] {
- self.iter.as_slice()
- }
-
- /// Returns a reference to the underlying allocator.
- #[unstable(feature = "allocator_api", issue = "32838")]
- #[must_use]
- #[inline]
- pub fn allocator(&self) -> &A {
- unsafe { self.vec.as_ref().allocator() }
- }
-
- /// Keep unyielded elements in the source `Vec`.
- ///
- /// # Examples
- ///
- /// ```
- /// #![feature(drain_keep_rest)]
- ///
- /// let mut vec = vec!['a', 'b', 'c'];
- /// let mut drain = vec.drain(..);
- ///
- /// assert_eq!(drain.next().unwrap(), 'a');
- ///
- /// // This call keeps 'b' and 'c' in the vec.
- /// drain.keep_rest();
- ///
- /// // If we wouldn't call `keep_rest()`,
- /// // `vec` would be empty.
- /// assert_eq!(vec, ['b', 'c']);
- /// ```
- #[unstable(feature = "drain_keep_rest", issue = "101122")]
- pub fn keep_rest(self) {
- // At this moment layout looks like this:
- //
- // [head] [yielded by next] [unyielded] [yielded by next_back] [tail]
- // ^-- start \_________/-- unyielded_len \____/-- self.tail_len
- // ^-- unyielded_ptr ^-- tail
- //
- // Normally `Drop` impl would drop [unyielded] and then move [tail] to the `start`.
- // Here we want to
- // 1. Move [unyielded] to `start`
- // 2. Move [tail] to a new start at `start + len(unyielded)`
- // 3. Update length of the original vec to `len(head) + len(unyielded) + len(tail)`
- // a. In case of ZST, this is the only thing we want to do
- // 4. Do *not* drop self, as everything is put in a consistent state already, there is nothing to do
- let mut this = ManuallyDrop::new(self);
-
- unsafe {
- let source_vec = this.vec.as_mut();
-
- let start = source_vec.len();
- let tail = this.tail_start;
-
- let unyielded_len = this.iter.len();
- let unyielded_ptr = this.iter.as_slice().as_ptr();
-
- // ZSTs have no identity, so we don't need to move them around.
- if !T::IS_ZST {
- let start_ptr = source_vec.as_mut_ptr().add(start);
-
- // memmove back unyielded elements
- if unyielded_ptr != start_ptr {
- let src = unyielded_ptr;
- let dst = start_ptr;
-
- ptr::copy(src, dst, unyielded_len);
- }
-
- // memmove back untouched tail
- if tail != (start + unyielded_len) {
- let src = source_vec.as_ptr().add(tail);
- let dst = start_ptr.add(unyielded_len);
- ptr::copy(src, dst, this.tail_len);
- }
- }
-
- source_vec.set_len(start + unyielded_len + this.tail_len);
- }
- }
-}
-
-#[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
-impl<'a, T, A: Allocator> AsRef<[T]> for Drain<'a, T, A> {
- fn as_ref(&self) -> &[T] {
- self.as_slice()
- }
-}
-
-#[stable(feature = "drain", since = "1.6.0")]
-unsafe impl<T: Sync, A: Sync + Allocator> Sync for Drain<'_, T, A> {}
-#[stable(feature = "drain", since = "1.6.0")]
-unsafe impl<T: Send, A: Send + Allocator> Send for Drain<'_, T, A> {}
-
-#[stable(feature = "drain", since = "1.6.0")]
-impl<T, A: Allocator> Iterator for Drain<'_, T, A> {
- type Item = T;
-
- #[inline]
- fn next(&mut self) -> Option<T> {
- self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
- }
-
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
- }
-}
-
-#[stable(feature = "drain", since = "1.6.0")]
-impl<T, A: Allocator> DoubleEndedIterator for Drain<'_, T, A> {
- #[inline]
- fn next_back(&mut self) -> Option<T> {
- self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
- }
-}
-
-#[stable(feature = "drain", since = "1.6.0")]
-impl<T, A: Allocator> Drop for Drain<'_, T, A> {
- fn drop(&mut self) {
- /// Moves back the un-`Drain`ed elements to restore the original `Vec`.
- struct DropGuard<'r, 'a, T, A: Allocator>(&'r mut Drain<'a, T, A>);
-
- impl<'r, 'a, T, A: Allocator> Drop for DropGuard<'r, 'a, T, A> {
- fn drop(&mut self) {
- if self.0.tail_len > 0 {
- unsafe {
- let source_vec = self.0.vec.as_mut();
- // memmove back untouched tail, update to new length
- let start = source_vec.len();
- let tail = self.0.tail_start;
- if tail != start {
- let src = source_vec.as_ptr().add(tail);
- let dst = source_vec.as_mut_ptr().add(start);
- ptr::copy(src, dst, self.0.tail_len);
- }
- source_vec.set_len(start + self.0.tail_len);
- }
- }
- }
- }
-
- let iter = mem::take(&mut self.iter);
- let drop_len = iter.len();
-
- let mut vec = self.vec;
-
- if T::IS_ZST {
- // ZSTs have no identity, so we don't need to move them around, we only need to drop the correct amount.
- // this can be achieved by manipulating the Vec length instead of moving values out from `iter`.
- unsafe {
- let vec = vec.as_mut();
- let old_len = vec.len();
- vec.set_len(old_len + drop_len + self.tail_len);
- vec.truncate(old_len + self.tail_len);
- }
-
- return;
- }
-
- // ensure elements are moved back into their appropriate places, even when drop_in_place panics
- let _guard = DropGuard(self);
-
- if drop_len == 0 {
- return;
- }
-
- // as_slice() must only be called when iter.len() is > 0 because
- // it also gets touched by vec::Splice which may turn it into a dangling pointer
- // which would make it and the vec pointer point to different allocations which would
- // lead to invalid pointer arithmetic below.
- let drop_ptr = iter.as_slice().as_ptr();
-
- unsafe {
- // drop_ptr comes from a slice::Iter which only gives us a &[T] but for drop_in_place
- // a pointer with mutable provenance is necessary. Therefore we must reconstruct
- // it from the original vec but also avoid creating a &mut to the front since that could
- // invalidate raw pointers to it which some unsafe code might rely on.
- let vec_ptr = vec.as_mut().as_mut_ptr();
- let drop_offset = drop_ptr.sub_ptr(vec_ptr);
- let to_drop = ptr::slice_from_raw_parts_mut(vec_ptr.add(drop_offset), drop_len);
- ptr::drop_in_place(to_drop);
- }
- }
-}
-
-#[stable(feature = "drain", since = "1.6.0")]
-impl<T, A: Allocator> ExactSizeIterator for Drain<'_, T, A> {
- fn is_empty(&self) -> bool {
- self.iter.is_empty()
- }
-}
-
-#[unstable(feature = "trusted_len", issue = "37572")]
-unsafe impl<T, A: Allocator> TrustedLen for Drain<'_, T, A> {}
-
-#[stable(feature = "fused", since = "1.26.0")]
-impl<T, A: Allocator> FusedIterator for Drain<'_, T, A> {}