Critical: Use of 'unsafe' keyword bypasses Rust's safety guarantees. Requires careful auditing, clear justification (FFI, specific optimizations), and minimal scope.
unsafe impl<T: Sync> Sync for Iter<'_, T> {}
1//! Definitions of a bunch of iterators for `[T]`.23#[macro_use] // import iterator! and forward_iterator!4mod macros;56use super::{from_raw_parts, from_raw_parts_mut};7use crate::hint::assert_unchecked;8use crate::iter::{FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce};9use crate::marker::PhantomData;10use crate::mem::{self, SizedTypeProperties};11use crate::num::NonZero;12use crate::ptr::{NonNull, without_provenance, without_provenance_mut};13use crate::{cmp, fmt};1415#[stable(feature = "boxed_slice_into_iter", since = "1.80.0")]16impl<T> !Iterator for [T] {}1718#[stable(feature = "rust1", since = "1.0.0")]19impl<'a, T> IntoIterator for &'a [T] {20 type Item = &'a T;21 type IntoIter = Iter<'a, T>;2223 fn into_iter(self) -> Iter<'a, T> {24 self.iter()25 }26}2728#[stable(feature = "rust1", since = "1.0.0")]29impl<'a, T> IntoIterator for &'a mut [T] {30 type Item = &'a mut T;31 type IntoIter = IterMut<'a, T>;3233 fn into_iter(self) -> IterMut<'a, T> {34 self.iter_mut()35 }36}3738/// Immutable slice iterator39///40/// This struct is created by the [`iter`] method on [slices].41///42/// # Examples43///44/// Basic usage:45///46/// ```47/// // First, we need a slice to call the `iter` method on:48/// let slice = &[1, 2, 3];49///50/// // Then we call `iter` on the slice to get the `Iter` iterator,51/// // and iterate over it:52/// for element in slice.iter() {53/// println!("{element}");54/// }55///56/// // This for loop actually already works without calling `iter`:57/// for element in slice {58/// println!("{element}");59/// }60/// ```61///62/// [`iter`]: slice::iter63/// [slices]: slice64#[stable(feature = "rust1", since = "1.0.0")]65#[must_use = "iterators are lazy and do nothing unless consumed"]66#[rustc_diagnostic_item = "SliceIter"]67pub struct Iter<'a, T: 'a> {68 /// The pointer to the next element to return, or the past-the-end location69 /// if the iterator is empty.70 ///71 /// This address will be used for all ZST elements, never changed.72 ptr: NonNull<T>,73 /// For non-ZSTs, the non-null pointer to the past-the-end element.74 ///75 /// For ZSTs, this is `ptr::without_provenance_mut(len)`.76 end_or_len: *const T,77 _marker: PhantomData<&'a T>,78}7980#[stable(feature = "core_impl_debug", since = "1.9.0")]81impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {83 f.debug_tuple("Iter").field(&self.as_slice()).finish()84 }85}8687#[stable(feature = "rust1", since = "1.0.0")]88unsafe impl<T: Sync> Sync for Iter<'_, T> {}89#[stable(feature = "rust1", since = "1.0.0")]90unsafe impl<T: Sync> Send for Iter<'_, T> {}9192impl<'a, T> Iter<'a, T> {93 #[inline]94 pub(super) const fn new(slice: &'a [T]) -> Self {95 let len = slice.len();96 let ptr: NonNull<T> = NonNull::from_ref(slice).cast();97 // SAFETY: Similar to `IterMut::new`.98 unsafe {99 let end_or_len =100 if T::IS_ZST { without_provenance(len) } else { ptr.as_ptr().add(len) };101102 Self { ptr, end_or_len, _marker: PhantomData }103 }104 }105106 /// Views the underlying data as a subslice of the original data.107 ///108 /// # Examples109 ///110 /// Basic usage:111 ///112 /// ```113 /// // First, we need a slice to call the `iter` method on:114 /// let slice = &[1, 2, 3];115 ///116 /// // Then we call `iter` on the slice to get the `Iter` iterator:117 /// let mut iter = slice.iter();118 /// // Here `as_slice` still returns the whole slice, so this prints "[1, 2, 3]":119 /// println!("{:?}", iter.as_slice());120 ///121 /// // Now, we call the `next` method to remove the first element from the iterator:122 /// iter.next();123 /// // Here the iterator does not contain the first element of the slice any more,124 /// // so `as_slice` only returns the last two elements of the slice,125 /// // and so this prints "[2, 3]":126 /// println!("{:?}", iter.as_slice());127 ///128 /// // The underlying slice has not been modified and still contains three elements,129 /// // so this prints "[1, 2, 3]":130 /// println!("{:?}", slice);131 /// ```132 #[must_use]133 #[stable(feature = "iter_to_slice", since = "1.4.0")]134 #[inline]135 pub fn as_slice(&self) -> &'a [T] {136 self.make_slice()137 }138}139140iterator! {struct Iter -> *const T, &'a T, const, {/* no mut */}, as_ref, each_ref, {141 fn is_sorted_by<F>(self, mut compare: F) -> bool142 where143 Self: Sized,144 F: FnMut(&Self::Item, &Self::Item) -> bool,145 {146 self.as_slice().is_sorted_by(|a, b| compare(&a, &b))147 }148}}149150#[stable(feature = "rust1", since = "1.0.0")]151impl<T> Clone for Iter<'_, T> {152 #[inline]153 fn clone(&self) -> Self {154 Iter { ptr: self.ptr, end_or_len: self.end_or_len, _marker: self._marker }155 }156}157158#[stable(feature = "slice_iter_as_ref", since = "1.13.0")]159impl<T> AsRef<[T]> for Iter<'_, T> {160 #[inline]161 fn as_ref(&self) -> &[T] {162 self.as_slice()163 }164}165166/// Mutable slice iterator.167///168/// This struct is created by the [`iter_mut`] method on [slices].169///170/// # Examples171///172/// Basic usage:173///174/// ```175/// // First, we need a slice to call the `iter_mut` method on:176/// let slice = &mut [1, 2, 3];177///178/// // Then we call `iter_mut` on the slice to get the `IterMut` iterator,179/// // iterate over it and increment each element value:180/// for element in slice.iter_mut() {181/// *element += 1;182/// }183///184/// // We now have "[2, 3, 4]":185/// println!("{slice:?}");186/// ```187///188/// [`iter_mut`]: slice::iter_mut189/// [slices]: slice190#[stable(feature = "rust1", since = "1.0.0")]191#[must_use = "iterators are lazy and do nothing unless consumed"]192pub struct IterMut<'a, T: 'a> {193 /// The pointer to the next element to return, or the past-the-end location194 /// if the iterator is empty.195 ///196 /// This address will be used for all ZST elements, never changed.197 ptr: NonNull<T>,198 /// For non-ZSTs, the non-null pointer to the past-the-end element.199 ///200 /// For ZSTs, this is `ptr::without_provenance_mut(len)`.201 end_or_len: *mut T,202 _marker: PhantomData<&'a mut T>,203}204205#[stable(feature = "core_impl_debug", since = "1.9.0")]206impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {208 f.debug_tuple("IterMut").field(&self.make_slice()).finish()209 }210}211212#[stable(feature = "rust1", since = "1.0.0")]213unsafe impl<T: Sync> Sync for IterMut<'_, T> {}214#[stable(feature = "rust1", since = "1.0.0")]215unsafe impl<T: Send> Send for IterMut<'_, T> {}216217impl<'a, T> IterMut<'a, T> {218 #[inline]219 pub(super) const fn new(slice: &'a mut [T]) -> Self {220 let len = slice.len();221 let ptr: NonNull<T> = NonNull::from_mut(slice).cast();222 // SAFETY: There are several things here:223 //224 // `ptr` has been obtained by `slice.as_ptr()` where `slice` is a valid225 // reference thus it is non-NUL and safe to use and pass to226 // `NonNull::new_unchecked` .227 //228 // Adding `slice.len()` to the starting pointer gives a pointer229 // at the end of `slice`. `end` will never be dereferenced, only checked230 // for direct pointer equality with `ptr` to check if the iterator is231 // done.232 //233 // In the case of a ZST, the end pointer is just the length. It's never234 // used as a pointer at all, and thus it's fine to have no provenance.235 //236 // See the `next_unchecked!` and `is_empty!` macros as well as the237 // `post_inc_start` method for more information.238 unsafe {239 let end_or_len =240 if T::IS_ZST { without_provenance_mut(len) } else { ptr.as_ptr().add(len) };241242 Self { ptr, end_or_len, _marker: PhantomData }243 }244 }245246 /// Views the underlying data as a subslice of the original data.247 ///248 /// To avoid creating `&mut` references that alias, this is forced249 /// to consume the iterator.250 ///251 /// # Examples252 ///253 /// Basic usage:254 ///255 /// ```256 /// // First, we need a slice to call the `iter_mut` method on:257 /// let mut slice = &mut [1, 2, 3];258 ///259 /// // Then we call `iter_mut` on the slice to get the `IterMut` struct:260 /// let mut iter = slice.iter_mut();261 /// // Now, we call the `next` method to remove the first element of the iterator,262 /// // unwrap and dereference what we get from `next` and increase its value by 1:263 /// *iter.next().unwrap() += 1;264 /// // Here the iterator does not contain the first element of the slice any more,265 /// // so `into_slice` only returns the last two elements of the slice,266 /// // and so this prints "[2, 3]":267 /// println!("{:?}", iter.into_slice());268 /// // The underlying slice still contains three elements, but its first element269 /// // was increased by 1, so this prints "[2, 2, 3]":270 /// println!("{:?}", slice);271 /// ```272 #[must_use = "`self` will be dropped if the result is not used"]273 #[stable(feature = "iter_to_slice", since = "1.4.0")]274 pub fn into_slice(self) -> &'a mut [T] {275 // SAFETY: the iterator was created from a mutable slice with pointer276 // `self.ptr` and length `len!(self)`. This guarantees that all the prerequisites277 // for `from_raw_parts_mut` are fulfilled.278 unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }279 }280281 /// Views the underlying data as a subslice of the original data.282 ///283 /// # Examples284 ///285 /// Basic usage:286 ///287 /// ```288 /// // First, we need a slice to call the `iter_mut` method on:289 /// let slice = &mut [1, 2, 3];290 ///291 /// // Then we call `iter_mut` on the slice to get the `IterMut` iterator:292 /// let mut iter = slice.iter_mut();293 /// // Here `as_slice` still returns the whole slice, so this prints "[1, 2, 3]":294 /// println!("{:?}", iter.as_slice());295 ///296 /// // Now, we call the `next` method to remove the first element from the iterator297 /// // and increment its value:298 /// *iter.next().unwrap() += 1;299 /// // Here the iterator does not contain the first element of the slice any more,300 /// // so `as_slice` only returns the last two elements of the slice,301 /// // and so this prints "[2, 3]":302 /// println!("{:?}", iter.as_slice());303 ///304 /// // The underlying slice still contains three elements, but its first element305 /// // was increased by 1, so this prints "[2, 2, 3]":306 /// println!("{:?}", slice);307 /// ```308 #[must_use]309 #[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]310 #[inline]311 pub fn as_slice(&self) -> &[T] {312 self.make_slice()313 }314315 /// Views the underlying data as a mutable subslice of the original data.316 ///317 /// # Examples318 ///319 /// Basic usage:320 ///321 /// ```322 /// #![feature(slice_iter_mut_as_mut_slice)]323 ///324 /// let mut slice: &mut [usize] = &mut [1, 2, 3];325 ///326 /// // First, we get the iterator:327 /// let mut iter = slice.iter_mut();328 /// // Then, we get a mutable slice from it:329 /// let mut_slice = iter.as_mut_slice();330 /// // So if we check what the `as_mut_slice` method returned, we have "[1, 2, 3]":331 /// assert_eq!(mut_slice, &mut [1, 2, 3]);332 ///333 /// // We can use it to mutate the slice:334 /// mut_slice[0] = 4;335 /// mut_slice[2] = 5;336 ///337 /// // Next, we can move to the second element of the slice, checking that338 /// // it yields the value we just wrote:339 /// assert_eq!(iter.next(), Some(&mut 4));340 /// // Now `as_mut_slice` returns "[2, 5]":341 /// assert_eq!(iter.as_mut_slice(), &mut [2, 5]);342 /// ```343 #[must_use]344 // FIXME: Uncomment the `AsMut<[T]>` impl when this gets stabilized.345 #[unstable(feature = "slice_iter_mut_as_mut_slice", issue = "93079")]346 pub fn as_mut_slice(&mut self) -> &mut [T] {347 // SAFETY: the iterator was created from a mutable slice with pointer348 // `self.ptr` and length `len!(self)`. This guarantees that all the prerequisites349 // for `from_raw_parts_mut` are fulfilled.350 unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }351 }352}353354#[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]355impl<T> AsRef<[T]> for IterMut<'_, T> {356 #[inline]357 fn as_ref(&self) -> &[T] {358 self.as_slice()359 }360}361362// #[stable(feature = "slice_iter_mut_as_mut_slice", since = "FIXME")]363// impl<T> AsMut<[T]> for IterMut<'_, T> {364// fn as_mut(&mut self) -> &mut [T] {365// self.as_mut_slice()366// }367// }368369iterator! {struct IterMut -> *mut T, &'a mut T, mut, {mut}, as_mut, each_mut, {}}370371/// An internal abstraction over the splitting iterators, so that372/// splitn, splitn_mut etc can be implemented once.373#[doc(hidden)]374pub(super) trait SplitIter: DoubleEndedIterator {375 /// Marks the underlying iterator as complete, extracting the remaining376 /// portion of the slice.377 fn finish(&mut self) -> Option<Self::Item>;378}379380/// An iterator over subslices separated by elements that match a predicate381/// function.382///383/// This struct is created by the [`split`] method on [slices].384///385/// # Example386///387/// ```388/// let slice = [10, 40, 33, 20];389/// let mut iter = slice.split(|num| num % 3 == 0);390/// assert_eq!(iter.next(), Some(&[10, 40][..]));391/// assert_eq!(iter.next(), Some(&[20][..]));392/// assert_eq!(iter.next(), None);393/// ```394///395/// [`split`]: slice::split396/// [slices]: slice397#[stable(feature = "rust1", since = "1.0.0")]398#[must_use = "iterators are lazy and do nothing unless consumed"]399pub struct Split<'a, T: 'a, P>400where401 P: FnMut(&T) -> bool,402{403 // Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods404 pub(crate) v: &'a [T],405 pred: P,406 // Used for `SplitAsciiWhitespace` `as_str` method407 pub(crate) finished: bool,408}409410impl<'a, T: 'a, P: FnMut(&T) -> bool> Split<'a, T, P> {411 #[inline]412 pub(super) fn new(slice: &'a [T], pred: P) -> Self {413 Self { v: slice, pred, finished: false }414 }415 /// Returns a slice which contains items not yet handled by split.416 /// # Example417 ///418 /// ```419 /// #![feature(split_as_slice)]420 /// let slice = [1,2,3,4,5];421 /// let mut split = slice.split(|v| v % 2 == 0);422 /// assert!(split.next().is_some());423 /// assert_eq!(split.as_slice(), &[3,4,5]);424 /// ```425 #[unstable(feature = "split_as_slice", issue = "96137")]426 pub fn as_slice(&self) -> &'a [T] {427 if self.finished { &[] } else { self.v }428 }429}430431#[stable(feature = "core_impl_debug", since = "1.9.0")]432impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P>433where434 P: FnMut(&T) -> bool,435{436 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {437 f.debug_struct("Split").field("v", &self.v).field("finished", &self.finished).finish()438 }439}440441// FIXME(#26925) Remove in favor of `#[derive(Clone)]`442#[stable(feature = "rust1", since = "1.0.0")]443impl<T, P> Clone for Split<'_, T, P>444where445 P: Clone + FnMut(&T) -> bool,446{447 fn clone(&self) -> Self {448 Split { v: self.v, pred: self.pred.clone(), finished: self.finished }449 }450}451452#[stable(feature = "rust1", since = "1.0.0")]453impl<'a, T, P> Iterator for Split<'a, T, P>454where455 P: FnMut(&T) -> bool,456{457 type Item = &'a [T];458459 #[inline]460 fn next(&mut self) -> Option<&'a [T]> {461 if self.finished {462 return None;463 }464465 match self.v.iter().position(|x| (self.pred)(x)) {466 None => self.finish(),467 Some(idx) => {468 let (left, right) =469 // SAFETY: if v.iter().position returns Some(idx), that470 // idx is definitely a valid index for v471 unsafe { (self.v.get_unchecked(..idx), self.v.get_unchecked(idx + 1..)) };472 let ret = Some(left);473 self.v = right;474 ret475 }476 }477 }478479 #[inline]480 fn size_hint(&self) -> (usize, Option<usize>) {481 if self.finished {482 (0, Some(0))483 } else {484 // If the predicate doesn't match anything, we yield one slice.485 // If it matches every element, we yield `len() + 1` empty slices.486 (1, Some(self.v.len() + 1))487 }488 }489}490491#[stable(feature = "rust1", since = "1.0.0")]492impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P>493where494 P: FnMut(&T) -> bool,495{496 #[inline]497 fn next_back(&mut self) -> Option<&'a [T]> {498 if self.finished {499 return None;500 }501502 match self.v.iter().rposition(|x| (self.pred)(x)) {503 None => self.finish(),504 Some(idx) => {505 let (left, right) =506 // SAFETY: if v.iter().rposition returns Some(idx), then507 // idx is definitely a valid index for v508 unsafe { (self.v.get_unchecked(..idx), self.v.get_unchecked(idx + 1..)) };509 let ret = Some(right);510 self.v = left;511 ret512 }513 }514 }515}516517impl<'a, T, P> SplitIter for Split<'a, T, P>518where519 P: FnMut(&T) -> bool,520{521 #[inline]522 fn finish(&mut self) -> Option<&'a [T]> {523 if self.finished {524 None525 } else {526 self.finished = true;527 Some(self.v)528 }529 }530}531532#[stable(feature = "fused", since = "1.26.0")]533impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}534535/// An iterator over subslices separated by elements that match a predicate536/// function. Unlike `Split`, it contains the matched part as a terminator537/// of the subslice.538///539/// This struct is created by the [`split_inclusive`] method on [slices].540///541/// # Example542///543/// ```544/// let slice = [10, 40, 33, 20];545/// let mut iter = slice.split_inclusive(|num| num % 3 == 0);546/// assert_eq!(iter.next(), Some(&[10, 40, 33][..]));547/// assert_eq!(iter.next(), Some(&[20][..]));548/// assert_eq!(iter.next(), None);549/// ```550///551/// [`split_inclusive`]: slice::split_inclusive552/// [slices]: slice553#[stable(feature = "split_inclusive", since = "1.51.0")]554#[must_use = "iterators are lazy and do nothing unless consumed"]555pub struct SplitInclusive<'a, T: 'a, P>556where557 P: FnMut(&T) -> bool,558{559 v: &'a [T],560 pred: P,561 finished: bool,562}563564impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusive<'a, T, P> {565 #[inline]566 pub(super) fn new(slice: &'a [T], pred: P) -> Self {567 let finished = slice.is_empty();568 Self { v: slice, pred, finished }569 }570}571572#[stable(feature = "split_inclusive", since = "1.51.0")]573impl<T: fmt::Debug, P> fmt::Debug for SplitInclusive<'_, T, P>574where575 P: FnMut(&T) -> bool,576{577 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {578 f.debug_struct("SplitInclusive")579 .field("v", &self.v)580 .field("finished", &self.finished)581 .finish()582 }583}584585// FIXME(#26925) Remove in favor of `#[derive(Clone)]`586#[stable(feature = "split_inclusive", since = "1.51.0")]587impl<T, P> Clone for SplitInclusive<'_, T, P>588where589 P: Clone + FnMut(&T) -> bool,590{591 fn clone(&self) -> Self {592 SplitInclusive { v: self.v, pred: self.pred.clone(), finished: self.finished }593 }594}595596#[stable(feature = "split_inclusive", since = "1.51.0")]597impl<'a, T, P> Iterator for SplitInclusive<'a, T, P>598where599 P: FnMut(&T) -> bool,600{601 type Item = &'a [T];602603 #[inline]604 fn next(&mut self) -> Option<&'a [T]> {605 if self.finished {606 return None;607 }608609 let idx =610 self.v.iter().position(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(self.v.len());611 if idx == self.v.len() {612 self.finished = true;613 }614 let ret = Some(&self.v[..idx]);615 self.v = &self.v[idx..];616 ret617 }618619 #[inline]620 fn size_hint(&self) -> (usize, Option<usize>) {621 if self.finished {622 (0, Some(0))623 } else {624 // If the predicate doesn't match anything, we yield one slice.625 // If it matches every element, we yield `len()` one-element slices,626 // or a single empty slice.627 (1, Some(cmp::max(1, self.v.len())))628 }629 }630}631632#[stable(feature = "split_inclusive", since = "1.51.0")]633impl<'a, T, P> DoubleEndedIterator for SplitInclusive<'a, T, P>634where635 P: FnMut(&T) -> bool,636{637 #[inline]638 fn next_back(&mut self) -> Option<&'a [T]> {639 if self.finished {640 return None;641 }642643 // The last index of self.v is already checked and found to match644 // by the last iteration, so we start searching a new match645 // one index to the left.646 let remainder = if self.v.is_empty() { &[] } else { &self.v[..(self.v.len() - 1)] };647 let idx = remainder.iter().rposition(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(0);648 if idx == 0 {649 self.finished = true;650 }651 let ret = Some(&self.v[idx..]);652 self.v = &self.v[..idx];653 ret654 }655}656657#[stable(feature = "split_inclusive", since = "1.51.0")]658impl<T, P> FusedIterator for SplitInclusive<'_, T, P> where P: FnMut(&T) -> bool {}659660/// An iterator over the mutable subslices of the vector which are separated661/// by elements that match `pred`.662///663/// This struct is created by the [`split_mut`] method on [slices].664///665/// # Example666///667/// ```668/// let mut v = [10, 40, 30, 20, 60, 50];669/// let iter = v.split_mut(|num| *num % 3 == 0);670/// ```671///672/// [`split_mut`]: slice::split_mut673/// [slices]: slice674#[stable(feature = "rust1", since = "1.0.0")]675#[must_use = "iterators are lazy and do nothing unless consumed"]676pub struct SplitMut<'a, T: 'a, P>677where678 P: FnMut(&T) -> bool,679{680 v: &'a mut [T],681 pred: P,682 finished: bool,683}684685impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitMut<'a, T, P> {686 #[inline]687 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {688 Self { v: slice, pred, finished: false }689 }690}691692#[stable(feature = "core_impl_debug", since = "1.9.0")]693impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P>694where695 P: FnMut(&T) -> bool,696{697 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {698 f.debug_struct("SplitMut").field("v", &self.v).field("finished", &self.finished).finish()699 }700}701702impl<'a, T, P> SplitIter for SplitMut<'a, T, P>703where704 P: FnMut(&T) -> bool,705{706 #[inline]707 fn finish(&mut self) -> Option<&'a mut [T]> {708 if self.finished {709 None710 } else {711 self.finished = true;712 Some(mem::take(&mut self.v))713 }714 }715}716717#[stable(feature = "rust1", since = "1.0.0")]718impl<'a, T, P> Iterator for SplitMut<'a, T, P>719where720 P: FnMut(&T) -> bool,721{722 type Item = &'a mut [T];723724 #[inline]725 fn next(&mut self) -> Option<&'a mut [T]> {726 if self.finished {727 return None;728 }729730 match self.v.iter().position(|x| (self.pred)(x)) {731 None => self.finish(),732 Some(idx) => {733 let tmp = mem::take(&mut self.v);734 // idx is the index of the element we are splitting on. We want to set self to the735 // region after idx, and return the subslice before and not including idx.736 // So first we split after idx737 let (head, tail) = tmp.split_at_mut(idx + 1);738 self.v = tail;739 // Then return the subslice up to but not including the found element740 Some(&mut head[..idx])741 }742 }743 }744745 #[inline]746 fn size_hint(&self) -> (usize, Option<usize>) {747 if self.finished {748 (0, Some(0))749 } else {750 // If the predicate doesn't match anything, we yield one slice.751 // If it matches every element, we yield `len() + 1` empty slices.752 (1, Some(self.v.len() + 1))753 }754 }755}756757#[stable(feature = "rust1", since = "1.0.0")]758impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P>759where760 P: FnMut(&T) -> bool,761{762 #[inline]763 fn next_back(&mut self) -> Option<&'a mut [T]> {764 if self.finished {765 return None;766 }767768 let idx_opt = {769 // work around borrowck limitations770 let pred = &mut self.pred;771 self.v.iter().rposition(|x| (*pred)(x))772 };773 match idx_opt {774 None => self.finish(),775 Some(idx) => {776 let tmp = mem::take(&mut self.v);777 let (head, tail) = tmp.split_at_mut(idx);778 self.v = head;779 Some(&mut tail[1..])780 }781 }782 }783}784785#[stable(feature = "fused", since = "1.26.0")]786impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}787788/// An iterator over the mutable subslices of the vector which are separated789/// by elements that match `pred`. Unlike `SplitMut`, it contains the matched790/// parts in the ends of the subslices.791///792/// This struct is created by the [`split_inclusive_mut`] method on [slices].793///794/// # Example795///796/// ```797/// let mut v = [10, 40, 30, 20, 60, 50];798/// let iter = v.split_inclusive_mut(|num| *num % 3 == 0);799/// ```800///801/// [`split_inclusive_mut`]: slice::split_inclusive_mut802/// [slices]: slice803#[stable(feature = "split_inclusive", since = "1.51.0")]804#[must_use = "iterators are lazy and do nothing unless consumed"]805pub struct SplitInclusiveMut<'a, T: 'a, P>806where807 P: FnMut(&T) -> bool,808{809 v: &'a mut [T],810 pred: P,811 finished: bool,812}813814impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusiveMut<'a, T, P> {815 #[inline]816 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {817 let finished = slice.is_empty();818 Self { v: slice, pred, finished }819 }820}821822#[stable(feature = "split_inclusive", since = "1.51.0")]823impl<T: fmt::Debug, P> fmt::Debug for SplitInclusiveMut<'_, T, P>824where825 P: FnMut(&T) -> bool,826{827 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {828 f.debug_struct("SplitInclusiveMut")829 .field("v", &self.v)830 .field("finished", &self.finished)831 .finish()832 }833}834835#[stable(feature = "split_inclusive", since = "1.51.0")]836impl<'a, T, P> Iterator for SplitInclusiveMut<'a, T, P>837where838 P: FnMut(&T) -> bool,839{840 type Item = &'a mut [T];841842 #[inline]843 fn next(&mut self) -> Option<&'a mut [T]> {844 if self.finished {845 return None;846 }847848 let idx_opt = {849 // work around borrowck limitations850 let pred = &mut self.pred;851 self.v.iter().position(|x| (*pred)(x))852 };853 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(self.v.len());854 if idx == self.v.len() {855 self.finished = true;856 }857 let tmp = mem::take(&mut self.v);858 let (head, tail) = tmp.split_at_mut(idx);859 self.v = tail;860 Some(head)861 }862863 #[inline]864 fn size_hint(&self) -> (usize, Option<usize>) {865 if self.finished {866 (0, Some(0))867 } else {868 // If the predicate doesn't match anything, we yield one slice.869 // If it matches every element, we yield `len()` one-element slices,870 // or a single empty slice.871 (1, Some(cmp::max(1, self.v.len())))872 }873 }874}875876#[stable(feature = "split_inclusive", since = "1.51.0")]877impl<'a, T, P> DoubleEndedIterator for SplitInclusiveMut<'a, T, P>878where879 P: FnMut(&T) -> bool,880{881 #[inline]882 fn next_back(&mut self) -> Option<&'a mut [T]> {883 if self.finished {884 return None;885 }886887 let idx_opt = if self.v.is_empty() {888 None889 } else {890 // work around borrowck limitations891 let pred = &mut self.pred;892893 // The last index of self.v is already checked and found to match894 // by the last iteration, so we start searching a new match895 // one index to the left.896 let remainder = &self.v[..(self.v.len() - 1)];897 remainder.iter().rposition(|x| (*pred)(x))898 };899 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(0);900 if idx == 0 {901 self.finished = true;902 }903 let tmp = mem::take(&mut self.v);904 let (head, tail) = tmp.split_at_mut(idx);905 self.v = head;906 Some(tail)907 }908}909910#[stable(feature = "split_inclusive", since = "1.51.0")]911impl<T, P> FusedIterator for SplitInclusiveMut<'_, T, P> where P: FnMut(&T) -> bool {}912913/// An iterator over subslices separated by elements that match a predicate914/// function, starting from the end of the slice.915///916/// This struct is created by the [`rsplit`] method on [slices].917///918/// # Example919///920/// ```921/// let slice = [11, 22, 33, 0, 44, 55];922/// let mut iter = slice.rsplit(|num| *num == 0);923/// assert_eq!(iter.next(), Some(&[44, 55][..]));924/// assert_eq!(iter.next(), Some(&[11, 22, 33][..]));925/// assert_eq!(iter.next(), None);926/// ```927///928/// [`rsplit`]: slice::rsplit929/// [slices]: slice930#[stable(feature = "slice_rsplit", since = "1.27.0")]931#[must_use = "iterators are lazy and do nothing unless consumed"]932pub struct RSplit<'a, T: 'a, P>933where934 P: FnMut(&T) -> bool,935{936 inner: Split<'a, T, P>,937}938939impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplit<'a, T, P> {940 #[inline]941 pub(super) fn new(slice: &'a [T], pred: P) -> Self {942 Self { inner: Split::new(slice, pred) }943 }944}945946#[stable(feature = "slice_rsplit", since = "1.27.0")]947impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P>948where949 P: FnMut(&T) -> bool,950{951 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {952 f.debug_struct("RSplit")953 .field("v", &self.inner.v)954 .field("finished", &self.inner.finished)955 .finish()956 }957}958959// FIXME(#26925) Remove in favor of `#[derive(Clone)]`960#[stable(feature = "slice_rsplit", since = "1.27.0")]961impl<T, P> Clone for RSplit<'_, T, P>962where963 P: Clone + FnMut(&T) -> bool,964{965 fn clone(&self) -> Self {966 RSplit { inner: self.inner.clone() }967 }968}969970#[stable(feature = "slice_rsplit", since = "1.27.0")]971impl<'a, T, P> Iterator for RSplit<'a, T, P>972where973 P: FnMut(&T) -> bool,974{975 type Item = &'a [T];976977 #[inline]978 fn next(&mut self) -> Option<&'a [T]> {979 self.inner.next_back()980 }981982 #[inline]983 fn size_hint(&self) -> (usize, Option<usize>) {984 self.inner.size_hint()985 }986}987988#[stable(feature = "slice_rsplit", since = "1.27.0")]989impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P>990where991 P: FnMut(&T) -> bool,992{993 #[inline]994 fn next_back(&mut self) -> Option<&'a [T]> {995 self.inner.next()996 }997}998999#[stable(feature = "slice_rsplit", since = "1.27.0")]1000impl<'a, T, P> SplitIter for RSplit<'a, T, P>1001where1002 P: FnMut(&T) -> bool,1003{1004 #[inline]1005 fn finish(&mut self) -> Option<&'a [T]> {1006 self.inner.finish()1007 }1008}10091010#[stable(feature = "slice_rsplit", since = "1.27.0")]1011impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}10121013/// An iterator over the subslices of the vector which are separated1014/// by elements that match `pred`, starting from the end of the slice.1015///1016/// This struct is created by the [`rsplit_mut`] method on [slices].1017///1018/// # Example1019///1020/// ```1021/// let mut slice = [11, 22, 33, 0, 44, 55];1022/// let iter = slice.rsplit_mut(|num| *num == 0);1023/// ```1024///1025/// [`rsplit_mut`]: slice::rsplit_mut1026/// [slices]: slice1027#[stable(feature = "slice_rsplit", since = "1.27.0")]1028#[must_use = "iterators are lazy and do nothing unless consumed"]1029pub struct RSplitMut<'a, T: 'a, P>1030where1031 P: FnMut(&T) -> bool,1032{1033 inner: SplitMut<'a, T, P>,1034}10351036impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitMut<'a, T, P> {1037 #[inline]1038 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {1039 Self { inner: SplitMut::new(slice, pred) }1040 }1041}10421043#[stable(feature = "slice_rsplit", since = "1.27.0")]1044impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P>1045where1046 P: FnMut(&T) -> bool,1047{1048 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {1049 f.debug_struct("RSplitMut")1050 .field("v", &self.inner.v)1051 .field("finished", &self.inner.finished)1052 .finish()1053 }1054}10551056#[stable(feature = "slice_rsplit", since = "1.27.0")]1057impl<'a, T, P> SplitIter for RSplitMut<'a, T, P>1058where1059 P: FnMut(&T) -> bool,1060{1061 #[inline]1062 fn finish(&mut self) -> Option<&'a mut [T]> {1063 self.inner.finish()1064 }1065}10661067#[stable(feature = "slice_rsplit", since = "1.27.0")]1068impl<'a, T, P> Iterator for RSplitMut<'a, T, P>1069where1070 P: FnMut(&T) -> bool,1071{1072 type Item = &'a mut [T];10731074 #[inline]1075 fn next(&mut self) -> Option<&'a mut [T]> {1076 self.inner.next_back()1077 }10781079 #[inline]1080 fn size_hint(&self) -> (usize, Option<usize>) {1081 self.inner.size_hint()1082 }1083}10841085#[stable(feature = "slice_rsplit", since = "1.27.0")]1086impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P>1087where1088 P: FnMut(&T) -> bool,1089{1090 #[inline]1091 fn next_back(&mut self) -> Option<&'a mut [T]> {1092 self.inner.next()1093 }1094}10951096#[stable(feature = "slice_rsplit", since = "1.27.0")]1097impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}10981099/// An private iterator over subslices separated by elements that1100/// match a predicate function, splitting at most a fixed number of1101/// times.1102#[derive(Debug)]1103struct GenericSplitN<I> {1104 iter: I,1105 count: usize,1106}11071108impl<T, I: SplitIter<Item = T>> Iterator for GenericSplitN<I> {1109 type Item = T;11101111 #[inline]1112 fn next(&mut self) -> Option<T> {1113 match self.count {1114 0 => None,1115 1 => {1116 self.count -= 1;1117 self.iter.finish()1118 }1119 _ => {1120 self.count -= 1;1121 self.iter.next()1122 }1123 }1124 }11251126 #[inline]1127 fn size_hint(&self) -> (usize, Option<usize>) {1128 let (lower, upper_opt) = self.iter.size_hint();1129 (1130 cmp::min(self.count, lower),1131 Some(upper_opt.map_or(self.count, |upper| cmp::min(self.count, upper))),1132 )1133 }1134}11351136/// An iterator over subslices separated by elements that match a predicate1137/// function, limited to a given number of splits.1138///1139/// This struct is created by the [`splitn`] method on [slices].1140///1141/// # Example1142///1143/// ```1144/// let slice = [10, 40, 30, 20, 60, 50];1145/// let mut iter = slice.splitn(2, |num| *num % 3 == 0);1146/// assert_eq!(iter.next(), Some(&[10, 40][..]));1147/// assert_eq!(iter.next(), Some(&[20, 60, 50][..]));1148/// assert_eq!(iter.next(), None);1149/// ```1150///1151/// [`splitn`]: slice::splitn1152/// [slices]: slice1153#[stable(feature = "rust1", since = "1.0.0")]1154#[must_use = "iterators are lazy and do nothing unless consumed"]1155pub struct SplitN<'a, T: 'a, P>1156where1157 P: FnMut(&T) -> bool,1158{1159 inner: GenericSplitN<Split<'a, T, P>>,1160}11611162impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitN<'a, T, P> {1163 #[inline]1164 pub(super) fn new(s: Split<'a, T, P>, n: usize) -> Self {1165 Self { inner: GenericSplitN { iter: s, count: n } }1166 }1167}11681169#[stable(feature = "core_impl_debug", since = "1.9.0")]1170impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P>1171where1172 P: FnMut(&T) -> bool,1173{1174 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {1175 f.debug_struct("SplitN").field("inner", &self.inner).finish()1176 }1177}11781179/// An iterator over subslices separated by elements that match a1180/// predicate function, limited to a given number of splits, starting1181/// from the end of the slice.1182///1183/// This struct is created by the [`rsplitn`] method on [slices].1184///1185/// # Example1186///1187/// ```1188/// let slice = [10, 40, 30, 20, 60, 50];1189/// let mut iter = slice.rsplitn(2, |num| *num % 3 == 0);1190/// assert_eq!(iter.next(), Some(&[50][..]));1191/// assert_eq!(iter.next(), Some(&[10, 40, 30, 20][..]));1192/// assert_eq!(iter.next(), None);1193/// ```1194///1195/// [`rsplitn`]: slice::rsplitn1196/// [slices]: slice1197#[stable(feature = "rust1", since = "1.0.0")]1198#[must_use = "iterators are lazy and do nothing unless consumed"]1199pub struct RSplitN<'a, T: 'a, P>1200where1201 P: FnMut(&T) -> bool,1202{1203 inner: GenericSplitN<RSplit<'a, T, P>>,1204}12051206impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitN<'a, T, P> {1207 #[inline]1208 pub(super) fn new(s: RSplit<'a, T, P>, n: usize) -> Self {1209 Self { inner: GenericSplitN { iter: s, count: n } }1210 }1211}12121213#[stable(feature = "core_impl_debug", since = "1.9.0")]1214impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P>1215where1216 P: FnMut(&T) -> bool,1217{1218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {1219 f.debug_struct("RSplitN").field("inner", &self.inner).finish()1220 }1221}12221223/// An iterator over subslices separated by elements that match a predicate1224/// function, limited to a given number of splits.1225///1226/// This struct is created by the [`splitn_mut`] method on [slices].1227///1228/// # Example1229///1230/// ```1231/// let mut slice = [10, 40, 30, 20, 60, 50];1232/// let iter = slice.splitn_mut(2, |num| *num % 3 == 0);1233/// ```1234///1235/// [`splitn_mut`]: slice::splitn_mut1236/// [slices]: slice1237#[stable(feature = "rust1", since = "1.0.0")]1238#[must_use = "iterators are lazy and do nothing unless consumed"]1239pub struct SplitNMut<'a, T: 'a, P>1240where1241 P: FnMut(&T) -> bool,1242{1243 inner: GenericSplitN<SplitMut<'a, T, P>>,1244}12451246impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitNMut<'a, T, P> {1247 #[inline]1248 pub(super) fn new(s: SplitMut<'a, T, P>, n: usize) -> Self {1249 Self { inner: GenericSplitN { iter: s, count: n } }1250 }1251}12521253#[stable(feature = "core_impl_debug", since = "1.9.0")]1254impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P>1255where1256 P: FnMut(&T) -> bool,1257{1258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {1259 f.debug_struct("SplitNMut").field("inner", &self.inner).finish()1260 }1261}12621263/// An iterator over subslices separated by elements that match a1264/// predicate function, limited to a given number of splits, starting1265/// from the end of the slice.1266///1267/// This struct is created by the [`rsplitn_mut`] method on [slices].1268///1269/// # Example1270///1271/// ```1272/// let mut slice = [10, 40, 30, 20, 60, 50];1273/// let iter = slice.rsplitn_mut(2, |num| *num % 3 == 0);1274/// ```1275///1276/// [`rsplitn_mut`]: slice::rsplitn_mut1277/// [slices]: slice1278#[stable(feature = "rust1", since = "1.0.0")]1279#[must_use = "iterators are lazy and do nothing unless consumed"]1280pub struct RSplitNMut<'a, T: 'a, P>1281where1282 P: FnMut(&T) -> bool,1283{1284 inner: GenericSplitN<RSplitMut<'a, T, P>>,1285}12861287impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitNMut<'a, T, P> {1288 #[inline]1289 pub(super) fn new(s: RSplitMut<'a, T, P>, n: usize) -> Self {1290 Self { inner: GenericSplitN { iter: s, count: n } }1291 }1292}12931294#[stable(feature = "core_impl_debug", since = "1.9.0")]1295impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P>1296where1297 P: FnMut(&T) -> bool,1298{1299 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {1300 f.debug_struct("RSplitNMut").field("inner", &self.inner).finish()1301 }1302}13031304forward_iterator! { SplitN: T, &'a [T] }1305forward_iterator! { RSplitN: T, &'a [T] }1306forward_iterator! { SplitNMut: T, &'a mut [T] }1307forward_iterator! { RSplitNMut: T, &'a mut [T] }13081309/// An iterator over overlapping subslices of length `size`.1310///1311/// This struct is created by the [`windows`] method on [slices].1312///1313/// # Example1314///1315/// ```1316/// let slice = ['r', 'u', 's', 't'];1317/// let mut iter = slice.windows(2);1318/// assert_eq!(iter.next(), Some(&['r', 'u'][..]));1319/// assert_eq!(iter.next(), Some(&['u', 's'][..]));1320/// assert_eq!(iter.next(), Some(&['s', 't'][..]));1321/// assert_eq!(iter.next(), None);1322/// ```1323///1324/// [`windows`]: slice::windows1325/// [slices]: slice1326#[derive(Debug)]1327#[stable(feature = "rust1", since = "1.0.0")]1328#[must_use = "iterators are lazy and do nothing unless consumed"]1329pub struct Windows<'a, T: 'a> {1330 v: &'a [T],1331 size: NonZero<usize>,1332}13331334impl<'a, T: 'a> Windows<'a, T> {1335 #[inline]1336 pub(super) const fn new(slice: &'a [T], size: NonZero<usize>) -> Self {1337 Self { v: slice, size }1338 }1339}13401341// FIXME(#26925) Remove in favor of `#[derive(Clone)]`1342#[stable(feature = "rust1", since = "1.0.0")]1343impl<T> Clone for Windows<'_, T> {1344 fn clone(&self) -> Self {1345 Windows { v: self.v, size: self.size }1346 }1347}13481349#[stable(feature = "rust1", since = "1.0.0")]1350impl<'a, T> Iterator for Windows<'a, T> {1351 type Item = &'a [T];13521353 #[inline]1354 fn next(&mut self) -> Option<&'a [T]> {1355 if self.size.get() > self.v.len() {1356 None1357 } else {1358 let ret = Some(&self.v[..self.size.get()]);1359 self.v = &self.v[1..];1360 ret1361 }1362 }13631364 #[inline]1365 fn size_hint(&self) -> (usize, Option<usize>) {1366 if self.size.get() > self.v.len() {1367 (0, Some(0))1368 } else {1369 let size = self.v.len() - self.size.get() + 1;1370 (size, Some(size))1371 }1372 }13731374 #[inline]1375 fn count(self) -> usize {1376 self.len()1377 }13781379 #[inline]1380 fn nth(&mut self, n: usize) -> Option<Self::Item> {1381 let size = self.size.get();1382 if let Some(rest) = self.v.get(n..)1383 && let Some(nth) = rest.get(..size)1384 {1385 self.v = &rest[1..];1386 Some(nth)1387 } else {1388 // setting length to 0 is cheaper than overwriting the pointer when assigning &[]1389 self.v = &self.v[..0]; // cheaper than &[]1390 None1391 }1392 }13931394 #[inline]1395 fn last(self) -> Option<Self::Item> {1396 if self.size.get() > self.v.len() {1397 None1398 } else {1399 let start = self.v.len() - self.size.get();1400 Some(&self.v[start..])1401 }1402 }14031404 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {1405 // SAFETY: since the caller guarantees that `i` is in bounds,1406 // which means that `i` cannot overflow an `isize`, and the1407 // slice created by `from_raw_parts` is a subslice of `self.v`1408 // thus is guaranteed to be valid for the lifetime `'a` of `self.v`.1409 unsafe { from_raw_parts(self.v.as_ptr().add(idx), self.size.get()) }1410 }1411}14121413#[stable(feature = "rust1", since = "1.0.0")]1414impl<'a, T> DoubleEndedIterator for Windows<'a, T> {1415 #[inline]1416 fn next_back(&mut self) -> Option<Self::Item> {1417 self.nth_back(0)1418 }14191420 #[inline]1421 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {1422 if let Some(end) = self.v.len().checked_sub(n)1423 && let Some(start) = end.checked_sub(self.size.get())1424 {1425 let res = &self.v[start..end];1426 self.v = &self.v[..end - 1];1427 Some(res)1428 } else {1429 self.v = &self.v[..0]; // cheaper than &[]1430 None1431 }1432 }1433}14341435#[stable(feature = "rust1", since = "1.0.0")]1436impl<T> ExactSizeIterator for Windows<'_, T> {}14371438#[unstable(feature = "trusted_len", issue = "37572")]1439unsafe impl<T> TrustedLen for Windows<'_, T> {}14401441#[stable(feature = "fused", since = "1.26.0")]1442impl<T> FusedIterator for Windows<'_, T> {}14431444#[doc(hidden)]1445#[unstable(feature = "trusted_random_access", issue = "none")]1446unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {}14471448#[doc(hidden)]1449#[unstable(feature = "trusted_random_access", issue = "none")]1450unsafe impl<'a, T> TrustedRandomAccessNoCoerce for Windows<'a, T> {1451 const MAY_HAVE_SIDE_EFFECT: bool = false;1452}14531454/// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a1455/// time), starting at the beginning of the slice.1456///1457/// When the slice len is not evenly divided by the chunk size, the last slice1458/// of the iteration will be the remainder.1459///1460/// This struct is created by the [`chunks`] method on [slices].1461///1462/// # Example1463///1464/// ```1465/// let slice = ['l', 'o', 'r', 'e', 'm'];1466/// let mut iter = slice.chunks(2);1467/// assert_eq!(iter.next(), Some(&['l', 'o'][..]));1468/// assert_eq!(iter.next(), Some(&['r', 'e'][..]));1469/// assert_eq!(iter.next(), Some(&['m'][..]));1470/// assert_eq!(iter.next(), None);1471/// ```1472///1473/// [`chunks`]: slice::chunks1474/// [slices]: slice1475#[derive(Debug)]1476#[stable(feature = "rust1", since = "1.0.0")]1477#[must_use = "iterators are lazy and do nothing unless consumed"]1478pub struct Chunks<'a, T: 'a> {1479 v: &'a [T],1480 chunk_size: usize,1481}14821483impl<'a, T: 'a> Chunks<'a, T> {1484 #[inline]1485 pub(super) const fn new(slice: &'a [T], size: usize) -> Self {1486 Self { v: slice, chunk_size: size }1487 }1488}14891490// FIXME(#26925) Remove in favor of `#[derive(Clone)]`1491#[stable(feature = "rust1", since = "1.0.0")]1492impl<T> Clone for Chunks<'_, T> {1493 fn clone(&self) -> Self {1494 Chunks { v: self.v, chunk_size: self.chunk_size }1495 }1496}14971498#[stable(feature = "rust1", since = "1.0.0")]1499impl<'a, T> Iterator for Chunks<'a, T> {1500 type Item = &'a [T];15011502 #[inline]1503 fn next(&mut self) -> Option<&'a [T]> {1504 if self.v.is_empty() {1505 None1506 } else {1507 let chunksz = cmp::min(self.v.len(), self.chunk_size);1508 let (fst, snd) = self.v.split_at(chunksz);1509 self.v = snd;1510 Some(fst)1511 }1512 }15131514 #[inline]1515 fn size_hint(&self) -> (usize, Option<usize>) {1516 if self.v.is_empty() {1517 (0, Some(0))1518 } else {1519 let n = self.v.len().div_ceil(self.chunk_size);1520 (n, Some(n))1521 }1522 }15231524 #[inline]1525 fn count(self) -> usize {1526 self.len()1527 }15281529 #[inline]1530 fn nth(&mut self, n: usize) -> Option<Self::Item> {1531 if let Some(start) = n.checked_mul(self.chunk_size)1532 && start < self.v.len()1533 {1534 let rest = &self.v[start..];1535 let (chunk, rest) = rest.split_at(self.chunk_size.min(rest.len()));1536 self.v = rest;1537 Some(chunk)1538 } else {1539 self.v = &self.v[..0]; // cheaper than &[]1540 None1541 }1542 }15431544 #[inline]1545 fn last(self) -> Option<Self::Item> {1546 if self.v.is_empty() {1547 None1548 } else {1549 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;1550 Some(&self.v[start..])1551 }1552 }15531554 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {1555 let start = idx * self.chunk_size;1556 // SAFETY: the caller guarantees that `i` is in bounds,1557 // which means that `start` must be in bounds of the1558 // underlying `self.v` slice, and we made sure that `len`1559 // is also in bounds of `self.v`. Thus, `start` cannot overflow1560 // an `isize`, and the slice constructed by `from_raw_parts`1561 // is a subslice of `self.v` which is guaranteed to be valid1562 // for the lifetime `'a` of `self.v`.1563 unsafe {1564 let len = cmp::min(self.v.len().unchecked_sub(start), self.chunk_size);1565 from_raw_parts(self.v.as_ptr().add(start), len)1566 }1567 }1568}15691570#[stable(feature = "rust1", since = "1.0.0")]1571impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {1572 #[inline]1573 fn next_back(&mut self) -> Option<&'a [T]> {1574 if self.v.is_empty() {1575 None1576 } else {1577 let remainder = self.v.len() % self.chunk_size;1578 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };1579 // SAFETY: split_at_unchecked requires the argument be less than or1580 // equal to the length. This is guaranteed, but subtle: `chunksz`1581 // will always either be `self.v.len() % self.chunk_size`, which1582 // will always evaluate to strictly less than `self.v.len()` (or1583 // panic, in the case that `self.chunk_size` is zero), or it can be1584 // `self.chunk_size`, in the case that the length is exactly1585 // divisible by the chunk size.1586 //1587 // While it seems like using `self.chunk_size` in this case could1588 // lead to a value greater than `self.v.len()`, it cannot: if1589 // `self.chunk_size` were greater than `self.v.len()`, then1590 // `self.v.len() % self.chunk_size` would return nonzero (note that1591 // in this branch of the `if`, we already know that `self.v` is1592 // non-empty).1593 let (fst, snd) = unsafe { self.v.split_at_unchecked(self.v.len() - chunksz) };1594 self.v = fst;1595 Some(snd)1596 }1597 }15981599 #[inline]1600 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {1601 let len = self.len();1602 if n < len {1603 let start = (len - 1 - n) * self.chunk_size;1604 let end = start + (self.v.len() - start).min(self.chunk_size);1605 let nth_back = &self.v[start..end];1606 self.v = &self.v[..start];1607 Some(nth_back)1608 } else {1609 self.v = &self.v[..0]; // cheaper than &[]1610 None1611 }1612 }1613}16141615#[stable(feature = "rust1", since = "1.0.0")]1616impl<T> ExactSizeIterator for Chunks<'_, T> {}16171618#[unstable(feature = "trusted_len", issue = "37572")]1619unsafe impl<T> TrustedLen for Chunks<'_, T> {}16201621#[stable(feature = "fused", since = "1.26.0")]1622impl<T> FusedIterator for Chunks<'_, T> {}16231624#[doc(hidden)]1625#[unstable(feature = "trusted_random_access", issue = "none")]1626unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {}16271628#[doc(hidden)]1629#[unstable(feature = "trusted_random_access", issue = "none")]1630unsafe impl<'a, T> TrustedRandomAccessNoCoerce for Chunks<'a, T> {1631 const MAY_HAVE_SIDE_EFFECT: bool = false;1632}16331634/// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`1635/// elements at a time), starting at the beginning of the slice.1636///1637/// When the slice len is not evenly divided by the chunk size, the last slice1638/// of the iteration will be the remainder.1639///1640/// This struct is created by the [`chunks_mut`] method on [slices].1641///1642/// # Example1643///1644/// ```1645/// let mut slice = ['l', 'o', 'r', 'e', 'm'];1646/// let iter = slice.chunks_mut(2);1647/// ```1648///1649/// [`chunks_mut`]: slice::chunks_mut1650/// [slices]: slice1651#[derive(Debug)]1652#[stable(feature = "rust1", since = "1.0.0")]1653#[must_use = "iterators are lazy and do nothing unless consumed"]1654pub struct ChunksMut<'a, T: 'a> {1655 /// # Safety1656 /// This slice pointer must point at a valid region of `T` with at least length `v.len()`. Normally,1657 /// those requirements would mean that we could instead use a `&mut [T]` here, but we cannot1658 /// because `__iterator_get_unchecked` needs to return `&mut [T]`, which guarantees certain aliasing1659 /// properties that we cannot uphold if we hold on to the full original `&mut [T]`. Wrapping a raw1660 /// slice instead lets us hand out non-overlapping `&mut [T]` subslices of the slice we wrap.1661 v: *mut [T],1662 chunk_size: usize,1663 _marker: PhantomData<&'a mut T>,1664}16651666impl<'a, T: 'a> ChunksMut<'a, T> {1667 #[inline]1668 pub(super) const fn new(slice: &'a mut [T], size: usize) -> Self {1669 Self { v: slice, chunk_size: size, _marker: PhantomData }1670 }1671}16721673#[stable(feature = "rust1", since = "1.0.0")]1674impl<'a, T> Iterator for ChunksMut<'a, T> {1675 type Item = &'a mut [T];16761677 #[inline]1678 fn next(&mut self) -> Option<&'a mut [T]> {1679 if self.v.is_empty() {1680 None1681 } else {1682 let sz = cmp::min(self.v.len(), self.chunk_size);1683 // SAFETY: The self.v contract ensures that any split_at_mut is valid.1684 let (head, tail) = unsafe { self.v.split_at_mut(sz) };1685 self.v = tail;1686 // SAFETY: Nothing else points to or will point to the contents of this slice.1687 Some(unsafe { &mut *head })1688 }1689 }16901691 #[inline]1692 fn size_hint(&self) -> (usize, Option<usize>) {1693 if self.v.is_empty() {1694 (0, Some(0))1695 } else {1696 let n = self.v.len().div_ceil(self.chunk_size);1697 (n, Some(n))1698 }1699 }17001701 #[inline]1702 fn count(self) -> usize {1703 self.len()1704 }17051706 #[inline]1707 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {1708 if let Some(start) = n.checked_mul(self.chunk_size)1709 && start < self.v.len()1710 {1711 // SAFETY: `start < self.v.len()` ensures this is in bounds1712 let (_, rest) = unsafe { self.v.split_at_mut(start) };1713 // SAFETY: `.min(rest.len()` ensures this is in bounds1714 let (chunk, rest) = unsafe { rest.split_at_mut(self.chunk_size.min(rest.len())) };1715 self.v = rest;1716 // SAFETY: Nothing else points to or will point to the contents of this slice.1717 Some(unsafe { &mut *chunk })1718 } else {1719 self.v = &mut [];1720 None1721 }1722 }17231724 #[inline]1725 fn last(self) -> Option<Self::Item> {1726 if self.v.is_empty() {1727 None1728 } else {1729 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;1730 // SAFETY: Nothing else points to or will point to the contents of this slice.1731 Some(unsafe { &mut *self.v.get_unchecked_mut(start..) })1732 }1733 }17341735 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {1736 let start = idx * self.chunk_size;1737 // SAFETY: see comments for `Chunks::__iterator_get_unchecked` and `self.v`.1738 //1739 // Also note that the caller also guarantees that we're never called1740 // with the same index again, and that no other methods that will1741 // access this subslice are called, so it is valid for the returned1742 // slice to be mutable.1743 unsafe {1744 let len = cmp::min(self.v.len().unchecked_sub(start), self.chunk_size);1745 from_raw_parts_mut(self.v.as_mut_ptr().add(start), len)1746 }1747 }1748}17491750#[stable(feature = "rust1", since = "1.0.0")]1751impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {1752 #[inline]1753 fn next_back(&mut self) -> Option<&'a mut [T]> {1754 if self.v.is_empty() {1755 None1756 } else {1757 let remainder = self.v.len() % self.chunk_size;1758 let sz = if remainder != 0 { remainder } else { self.chunk_size };1759 let len = self.v.len();1760 // SAFETY: Similar to `Chunks::next_back`1761 let (head, tail) = unsafe { self.v.split_at_mut_unchecked(len - sz) };1762 self.v = head;1763 // SAFETY: Nothing else points to or will point to the contents of this slice.1764 Some(unsafe { &mut *tail })1765 }1766 }17671768 #[inline]1769 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {1770 let len = self.len();1771 if n < len {1772 let start = (len - 1 - n) * self.chunk_size;1773 let end = match start.checked_add(self.chunk_size) {1774 Some(res) => cmp::min(self.v.len(), res),1775 None => self.v.len(),1776 };1777 // SAFETY: The self.v contract ensures that any split_at_mut is valid.1778 let (temp, _tail) = unsafe { self.v.split_at_mut(end) };1779 // SAFETY: The self.v contract ensures that any split_at_mut is valid.1780 let (head, nth_back) = unsafe { temp.split_at_mut(start) };1781 self.v = head;1782 // SAFETY: Nothing else points to or will point to the contents of this slice.1783 Some(unsafe { &mut *nth_back })1784 } else {1785 self.v = &mut [];1786 None1787 }1788 }1789}17901791#[stable(feature = "rust1", since = "1.0.0")]1792impl<T> ExactSizeIterator for ChunksMut<'_, T> {}17931794#[unstable(feature = "trusted_len", issue = "37572")]1795unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}17961797#[stable(feature = "fused", since = "1.26.0")]1798impl<T> FusedIterator for ChunksMut<'_, T> {}17991800#[doc(hidden)]1801#[unstable(feature = "trusted_random_access", issue = "none")]1802unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {}18031804#[doc(hidden)]1805#[unstable(feature = "trusted_random_access", issue = "none")]1806unsafe impl<'a, T> TrustedRandomAccessNoCoerce for ChunksMut<'a, T> {1807 const MAY_HAVE_SIDE_EFFECT: bool = false;1808}18091810#[stable(feature = "rust1", since = "1.0.0")]1811unsafe impl<T> Send for ChunksMut<'_, T> where T: Send {}18121813#[stable(feature = "rust1", since = "1.0.0")]1814unsafe impl<T> Sync for ChunksMut<'_, T> where T: Sync {}18151816/// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a1817/// time), starting at the beginning of the slice.1818///1819/// When the slice len is not evenly divided by the chunk size, the last1820/// up to `chunk_size-1` elements will be omitted but can be retrieved from1821/// the [`remainder`] function from the iterator.1822///1823/// This struct is created by the [`chunks_exact`] method on [slices].1824///1825/// # Example1826///1827/// ```1828/// let slice = ['l', 'o', 'r', 'e', 'm'];1829/// let mut iter = slice.chunks_exact(2);1830/// assert_eq!(iter.next(), Some(&['l', 'o'][..]));1831/// assert_eq!(iter.next(), Some(&['r', 'e'][..]));1832/// assert_eq!(iter.next(), None);1833/// ```1834///1835/// [`chunks_exact`]: slice::chunks_exact1836/// [`remainder`]: ChunksExact::remainder1837/// [slices]: slice1838#[derive(Debug)]1839#[stable(feature = "chunks_exact", since = "1.31.0")]1840#[must_use = "iterators are lazy and do nothing unless consumed"]1841pub struct ChunksExact<'a, T: 'a> {1842 v: &'a [T],1843 rem: &'a [T],1844 chunk_size: usize,1845}18461847impl<'a, T> ChunksExact<'a, T> {1848 #[inline]1849 pub(super) const fn new(slice: &'a [T], chunk_size: usize) -> Self {1850 let rem = slice.len() % chunk_size;1851 let fst_len = slice.len() - rem;1852 // SAFETY: 0 <= fst_len <= slice.len() by construction above1853 let (fst, snd) = unsafe { slice.split_at_unchecked(fst_len) };1854 Self { v: fst, rem: snd, chunk_size }1855 }18561857 /// Returns the remainder of the original slice that is not going to be1858 /// returned by the iterator. The returned slice has at most `chunk_size-1`1859 /// elements.1860 ///1861 /// # Example1862 ///1863 /// ```1864 /// let slice = ['l', 'o', 'r', 'e', 'm'];1865 /// let mut iter = slice.chunks_exact(2);1866 /// assert_eq!(iter.remainder(), &['m'][..]);1867 /// assert_eq!(iter.next(), Some(&['l', 'o'][..]));1868 /// assert_eq!(iter.remainder(), &['m'][..]);1869 /// assert_eq!(iter.next(), Some(&['r', 'e'][..]));1870 /// assert_eq!(iter.remainder(), &['m'][..]);1871 /// assert_eq!(iter.next(), None);1872 /// assert_eq!(iter.remainder(), &['m'][..]);1873 /// ```1874 #[must_use]1875 #[stable(feature = "chunks_exact", since = "1.31.0")]1876 pub fn remainder(&self) -> &'a [T] {1877 self.rem1878 }1879}18801881// FIXME(#26925) Remove in favor of `#[derive(Clone)]`1882#[stable(feature = "chunks_exact", since = "1.31.0")]1883impl<T> Clone for ChunksExact<'_, T> {1884 fn clone(&self) -> Self {1885 ChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }1886 }1887}18881889#[stable(feature = "chunks_exact", since = "1.31.0")]1890impl<'a, T> Iterator for ChunksExact<'a, T> {1891 type Item = &'a [T];18921893 #[inline]1894 fn next(&mut self) -> Option<&'a [T]> {1895 self.v.split_at_checked(self.chunk_size).and_then(|(chunk, rest)| {1896 self.v = rest;1897 Some(chunk)1898 })1899 }19001901 #[inline]1902 fn size_hint(&self) -> (usize, Option<usize>) {1903 let n = self.v.len() / self.chunk_size;1904 (n, Some(n))1905 }19061907 #[inline]1908 fn count(self) -> usize {1909 self.len()1910 }19111912 #[inline]1913 fn nth(&mut self, n: usize) -> Option<Self::Item> {1914 if let Some(start) = n.checked_mul(self.chunk_size)1915 && start < self.v.len()1916 {1917 self.v = &self.v[start..];1918 self.next()1919 } else {1920 self.v = &self.v[..0]; // cheaper than &[]1921 None1922 }1923 }19241925 #[inline]1926 fn last(mut self) -> Option<Self::Item> {1927 self.next_back()1928 }19291930 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {1931 let start = idx * self.chunk_size;1932 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.1933 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }1934 }1935}19361937#[stable(feature = "chunks_exact", since = "1.31.0")]1938impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {1939 #[inline]1940 fn next_back(&mut self) -> Option<&'a [T]> {1941 if self.v.len() < self.chunk_size {1942 None1943 } else {1944 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);1945 self.v = fst;1946 Some(snd)1947 }1948 }19491950 #[inline]1951 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {1952 let len = self.len();1953 if n < len {1954 let start = (len - 1 - n) * self.chunk_size;1955 let end = start + self.chunk_size;1956 let nth_back = &self.v[start..end];1957 self.v = &self.v[..start];1958 Some(nth_back)1959 } else {1960 self.v = &self.v[..0]; // cheaper than &[]1961 None1962 }1963 }1964}19651966#[stable(feature = "chunks_exact", since = "1.31.0")]1967impl<T> ExactSizeIterator for ChunksExact<'_, T> {1968 fn is_empty(&self) -> bool {1969 self.v.is_empty()1970 }1971}19721973#[unstable(feature = "trusted_len", issue = "37572")]1974unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}19751976#[stable(feature = "chunks_exact", since = "1.31.0")]1977impl<T> FusedIterator for ChunksExact<'_, T> {}19781979#[doc(hidden)]1980#[unstable(feature = "trusted_random_access", issue = "none")]1981unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {}19821983#[doc(hidden)]1984#[unstable(feature = "trusted_random_access", issue = "none")]1985unsafe impl<'a, T> TrustedRandomAccessNoCoerce for ChunksExact<'a, T> {1986 const MAY_HAVE_SIDE_EFFECT: bool = false;1987}19881989/// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`1990/// elements at a time), starting at the beginning of the slice.1991///1992/// When the slice len is not evenly divided by the chunk size, the last up to1993/// `chunk_size-1` elements will be omitted but can be retrieved from the1994/// [`into_remainder`] function from the iterator.1995///1996/// This struct is created by the [`chunks_exact_mut`] method on [slices].1997///1998/// # Example1999///2000/// ```
Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.