|
26 | 26 | //! When this feature is enabled, `SmallVec<u8, _>` implements the `std::io::Write` trait.
|
27 | 27 | //! This feature is not compatible with `#![no_std]` programs.
|
28 | 28 | //!
|
| 29 | +//! ### `drain_filter` |
| 30 | +//! |
| 31 | +//! **This feature is unstable.** It may change to match the unstable `drain_filter` method in libstd. |
| 32 | +//! |
| 33 | +//! Enables the `drain_filter` method, which produces an iterator that calls a user-provided |
| 34 | +//! closure to determine which elements of the vector to remove and yield from the iterator. |
| 35 | +//! |
29 | 36 | //! ### `specialization`
|
30 | 37 | //!
|
31 | 38 | //! **This feature is unstable and requires a nightly build of the Rust toolchain.**
|
@@ -873,6 +880,48 @@ impl<T, const N: usize> SmallVec<T, N> {
|
873 | 880 | self.len.on_heap(Self::is_zst())
|
874 | 881 | }
|
875 | 882 |
|
| 883 | + /// Splits the collection into two at the given index. |
| 884 | + /// |
| 885 | + /// Returns a newly allocated vector containing the elements in the range |
| 886 | + /// `[at, len)`. After the call, the original vector will be left containing |
| 887 | + /// the elements `[0, at)` with its previous capacity unchanged. |
| 888 | + /// |
| 889 | + /// - If you want to take ownership of the entire contents and capacity of |
| 890 | + /// the vector, see [`mem::take`] or [`mem::replace`]. |
| 891 | + /// - If you don't need the returned vector at all, see [`SmallVec::truncate`]. |
| 892 | + /// - If you want to take ownership of an arbitrary subslice, or you don't |
| 893 | + /// necessarily want to store the removed items in a vector, see [`SmallVec::drain`]. |
| 894 | + /// |
| 895 | + /// # Panics |
| 896 | + /// |
| 897 | + /// Panics if `at > len`. |
| 898 | + /// |
| 899 | + /// # Examples |
| 900 | + /// |
| 901 | + /// ``` |
| 902 | + /// let mut vec = vec![1, 2, 3]; |
| 903 | + /// let vec2 = vec.split_off(1); |
| 904 | + /// assert_eq!(vec, [1]); |
| 905 | + /// assert_eq!(vec2, [2, 3]); |
| 906 | + /// ``` |
| 907 | + #[inline] |
| 908 | + pub fn split_off(&mut self, at: usize) -> Self { |
| 909 | + let len = self.len(); |
| 910 | + assert!(at <= len); |
| 911 | + |
| 912 | + let other_len = len - at; |
| 913 | + let mut other = Self::with_capacity(other_len); |
| 914 | + |
| 915 | + // Unsafely `set_len` and copy items to `other`. |
| 916 | + unsafe { |
| 917 | + self.set_len(at); |
| 918 | + other.set_len(other_len); |
| 919 | + |
| 920 | + core::ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other_len); |
| 921 | + } |
| 922 | + other |
| 923 | + } |
| 924 | + |
876 | 925 | pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, N>
|
877 | 926 | where
|
878 | 927 | R: core::ops::RangeBounds<usize>,
|
|
0 commit comments