Skip to main content

core/str/
iter.rs

1//! Iterators for `str` methods.
2
3use super::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher};
4use super::validations::{next_code_point, next_code_point_reverse};
5use super::{
6    BytesIsNotEmpty, CharEscapeDebug, CharEscapeDefault, CharEscapeUnicode, IsAsciiWhitespace,
7    IsNotEmpty, IsWhitespace, LinesMap, UnsafeBytesToStr, from_utf8_unchecked,
8};
9use crate::char as char_mod;
10use crate::fmt::{self, Write};
11use crate::iter::{
12    Copied, Filter, FlatMap, FusedIterator, Map, TrustedLen, TrustedRandomAccess,
13    TrustedRandomAccessNoCoerce,
14};
15use crate::num::NonZero;
16use crate::ops::Try;
17use crate::slice::{self, Split as SliceSplit};
18
19/// An iterator over the [`char`]s of a string slice.
20///
21///
22/// This struct is created by the [`chars`] method on [`str`].
23/// See its documentation for more.
24///
25/// [`char`]: prim@char
26/// [`chars`]: str::chars
27#[derive(Clone)]
28#[must_use = "iterators are lazy and do nothing unless consumed"]
29#[stable(feature = "rust1", since = "1.0.0")]
30#[ferrocene::prevalidated]
31pub struct Chars<'a> {
32    pub(super) iter: slice::Iter<'a, u8>,
33}
34
35#[stable(feature = "rust1", since = "1.0.0")]
36impl<'a> Iterator for Chars<'a> {
37    type Item = char;
38
39    #[inline]
40    #[ferrocene::prevalidated]
41    fn next(&mut self) -> Option<char> {
42        // SAFETY: `str` invariant says `self.iter` is a valid UTF-8 string and
43        // the resulting `ch` is a valid Unicode Scalar Value.
44        unsafe { next_code_point(&mut self.iter).map(|ch| char::from_u32_unchecked(ch)) }
45    }
46
47    #[inline]
48    #[ferrocene::prevalidated]
49    fn count(self) -> usize {
50        super::count::count_chars(self.as_str())
51    }
52
53    #[inline]
54    #[ferrocene::prevalidated]
55    fn advance_by(&mut self, mut remainder: usize) -> Result<(), NonZero<usize>> {
56        const CHUNK_SIZE: usize = 32;
57
58        if remainder >= CHUNK_SIZE {
59            let mut chunks = self.iter.as_slice().as_chunks::<CHUNK_SIZE>().0.iter();
60            let mut bytes_skipped: usize = 0;
61
62            while remainder > CHUNK_SIZE
63                && let Some(chunk) = chunks.next()
64            {
65                bytes_skipped += CHUNK_SIZE;
66
67                let mut start_bytes = [false; CHUNK_SIZE];
68
69                for i in 0..CHUNK_SIZE {
70                    start_bytes[i] = !super::validations::utf8_is_cont_byte(chunk[i]);
71                }
72
73                remainder -= start_bytes.into_iter().map(|i| i as u8).sum::<u8>() as usize;
74            }
75
76            // SAFETY: The amount of bytes exists since we just iterated over them,
77            // so advance_by will succeed.
78            unsafe { self.iter.advance_by(bytes_skipped).unwrap_unchecked() };
79
80            // skip trailing continuation bytes
81            while self.iter.len() > 0 {
82                let b = self.iter.as_slice()[0];
83                if !super::validations::utf8_is_cont_byte(b) {
84                    break;
85                }
86                // SAFETY: We just peeked at the byte, therefore it exists
87                unsafe { self.iter.advance_by(1).unwrap_unchecked() };
88            }
89        }
90
91        while (remainder > 0) && (self.iter.len() > 0) {
92            remainder -= 1;
93            let b = self.iter.as_slice()[0];
94            let slurp = super::validations::utf8_char_width(b);
95            // SAFETY: utf8 validity requires that the string must contain
96            // the continuation bytes (if any)
97            unsafe { self.iter.advance_by(slurp).unwrap_unchecked() };
98        }
99
100        NonZero::new(remainder).map_or(Ok(()), Err)
101    }
102
103    #[inline]
104    #[ferrocene::prevalidated]
105    fn size_hint(&self) -> (usize, Option<usize>) {
106        let len = self.iter.len();
107        (len.div_ceil(4), Some(len))
108    }
109
110    #[inline]
111    #[ferrocene::prevalidated]
112    fn last(mut self) -> Option<char> {
113        // No need to go through the entire string.
114        self.next_back()
115    }
116}
117
118#[stable(feature = "chars_debug_impl", since = "1.38.0")]
119impl fmt::Debug for Chars<'_> {
120    #[ferrocene::prevalidated]
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        write!(f, "Chars(")?;
123        f.debug_list().entries(self.clone()).finish()?;
124        write!(f, ")")?;
125        Ok(())
126    }
127}
128
129#[stable(feature = "rust1", since = "1.0.0")]
130impl<'a> DoubleEndedIterator for Chars<'a> {
131    #[inline]
132    #[ferrocene::prevalidated]
133    fn next_back(&mut self) -> Option<char> {
134        // SAFETY: `str` invariant says `self.iter` is a valid UTF-8 string and
135        // the resulting `ch` is a valid Unicode Scalar Value.
136        unsafe { next_code_point_reverse(&mut self.iter).map(|ch| char::from_u32_unchecked(ch)) }
137    }
138}
139
140#[stable(feature = "fused", since = "1.26.0")]
141impl FusedIterator for Chars<'_> {}
142
143impl<'a> Chars<'a> {
144    /// Views the underlying data as a subslice of the original data.
145    ///
146    /// This has the same lifetime as the original slice, and so the
147    /// iterator can continue to be used while this exists.
148    ///
149    /// # Examples
150    ///
151    /// ```
152    /// let mut chars = "abc".chars();
153    ///
154    /// assert_eq!(chars.as_str(), "abc");
155    /// chars.next();
156    /// assert_eq!(chars.as_str(), "bc");
157    /// chars.next();
158    /// chars.next();
159    /// assert_eq!(chars.as_str(), "");
160    /// ```
161    #[stable(feature = "iter_to_slice", since = "1.4.0")]
162    #[must_use]
163    #[inline]
164    #[ferrocene::prevalidated]
165    pub fn as_str(&self) -> &'a str {
166        // SAFETY: `Chars` is only made from a str, which guarantees the iter is valid UTF-8.
167        unsafe { from_utf8_unchecked(self.iter.as_slice()) }
168    }
169}
170
171/// An iterator over the [`char`]s of a string slice, and their positions.
172///
173/// This struct is created by the [`char_indices`] method on [`str`].
174/// See its documentation for more.
175///
176/// [`char`]: prim@char
177/// [`char_indices`]: str::char_indices
178#[derive(Clone, Debug)]
179#[must_use = "iterators are lazy and do nothing unless consumed"]
180#[stable(feature = "rust1", since = "1.0.0")]
181#[ferrocene::prevalidated]
182pub struct CharIndices<'a> {
183    pub(super) front_offset: usize,
184    pub(super) iter: Chars<'a>,
185}
186
187#[stable(feature = "rust1", since = "1.0.0")]
188impl<'a> Iterator for CharIndices<'a> {
189    type Item = (usize, char);
190
191    #[inline]
192    #[ferrocene::prevalidated]
193    fn next(&mut self) -> Option<(usize, char)> {
194        let pre_len = self.iter.iter.len();
195        match self.iter.next() {
196            None => None,
197            Some(ch) => {
198                let index = self.front_offset;
199                let len = self.iter.iter.len();
200                self.front_offset += pre_len - len;
201                Some((index, ch))
202            }
203        }
204    }
205
206    #[inline]
207    #[ferrocene::prevalidated]
208    fn count(self) -> usize {
209        self.iter.count()
210    }
211
212    #[inline]
213    #[ferrocene::prevalidated]
214    fn size_hint(&self) -> (usize, Option<usize>) {
215        self.iter.size_hint()
216    }
217
218    #[inline]
219    #[ferrocene::prevalidated]
220    fn last(mut self) -> Option<(usize, char)> {
221        // No need to go through the entire string.
222        self.next_back()
223    }
224}
225
226#[stable(feature = "rust1", since = "1.0.0")]
227impl<'a> DoubleEndedIterator for CharIndices<'a> {
228    #[inline]
229    #[ferrocene::prevalidated]
230    fn next_back(&mut self) -> Option<(usize, char)> {
231        self.iter.next_back().map(|ch| {
232            let index = self.front_offset + self.iter.iter.len();
233            (index, ch)
234        })
235    }
236}
237
238#[stable(feature = "fused", since = "1.26.0")]
239impl FusedIterator for CharIndices<'_> {}
240
241impl<'a> CharIndices<'a> {
242    /// Views the underlying data as a subslice of the original data.
243    ///
244    /// This has the same lifetime as the original slice, and so the
245    /// iterator can continue to be used while this exists.
246    #[stable(feature = "iter_to_slice", since = "1.4.0")]
247    #[must_use]
248    #[inline]
249    #[ferrocene::prevalidated]
250    pub fn as_str(&self) -> &'a str {
251        self.iter.as_str()
252    }
253
254    /// Returns the byte position of the next character, or the length
255    /// of the underlying string if there are no more characters.
256    ///
257    /// This means that, when the iterator has not been fully consumed,
258    /// the returned value will match the index that will be returned
259    /// by the next call to [`next()`](Self::next).
260    ///
261    /// # Examples
262    ///
263    /// ```
264    /// let mut chars = "a楽".char_indices();
265    ///
266    /// // `next()` has not been called yet, so `offset()` returns the byte
267    /// // index of the first character of the string, which is always 0.
268    /// assert_eq!(chars.offset(), 0);
269    /// // As expected, the first call to `next()` also returns 0 as index.
270    /// assert_eq!(chars.next(), Some((0, 'a')));
271    ///
272    /// // `next()` has been called once, so `offset()` returns the byte index
273    /// // of the second character ...
274    /// assert_eq!(chars.offset(), 1);
275    /// // ... which matches the index returned by the next call to `next()`.
276    /// assert_eq!(chars.next(), Some((1, '楽')));
277    ///
278    /// // Once the iterator has been consumed, `offset()` returns the length
279    /// // in bytes of the string.
280    /// assert_eq!(chars.offset(), 4);
281    /// assert_eq!(chars.next(), None);
282    /// ```
283    #[inline]
284    #[must_use]
285    #[stable(feature = "char_indices_offset", since = "1.82.0")]
286    #[ferrocene::prevalidated]
287    pub fn offset(&self) -> usize {
288        self.front_offset
289    }
290}
291
292/// An iterator over the bytes of a string slice.
293///
294/// This struct is created by the [`bytes`] method on [`str`].
295/// See its documentation for more.
296///
297/// [`bytes`]: str::bytes
298#[must_use = "iterators are lazy and do nothing unless consumed"]
299#[stable(feature = "rust1", since = "1.0.0")]
300#[derive(Clone, Debug)]
301#[ferrocene::prevalidated]
302pub struct Bytes<'a>(pub(super) Copied<slice::Iter<'a, u8>>);
303
304#[stable(feature = "rust1", since = "1.0.0")]
305impl Iterator for Bytes<'_> {
306    type Item = u8;
307
308    #[inline]
309    #[ferrocene::prevalidated]
310    fn next(&mut self) -> Option<u8> {
311        self.0.next()
312    }
313
314    #[inline]
315    #[ferrocene::prevalidated]
316    fn size_hint(&self) -> (usize, Option<usize>) {
317        self.0.size_hint()
318    }
319
320    #[inline]
321    #[ferrocene::prevalidated]
322    fn count(self) -> usize {
323        self.0.count()
324    }
325
326    #[inline]
327    #[ferrocene::prevalidated]
328    fn last(self) -> Option<Self::Item> {
329        self.0.last()
330    }
331
332    #[inline]
333    #[ferrocene::prevalidated]
334    fn nth(&mut self, n: usize) -> Option<Self::Item> {
335        self.0.nth(n)
336    }
337
338    #[inline]
339    #[ferrocene::prevalidated]
340    fn all<F>(&mut self, f: F) -> bool
341    where
342        F: FnMut(Self::Item) -> bool,
343    {
344        self.0.all(f)
345    }
346
347    #[inline]
348    #[ferrocene::prevalidated]
349    fn any<F>(&mut self, f: F) -> bool
350    where
351        F: FnMut(Self::Item) -> bool,
352    {
353        self.0.any(f)
354    }
355
356    #[inline]
357    #[ferrocene::prevalidated]
358    fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
359    where
360        P: FnMut(&Self::Item) -> bool,
361    {
362        self.0.find(predicate)
363    }
364
365    #[inline]
366    #[ferrocene::prevalidated]
367    fn position<P>(&mut self, predicate: P) -> Option<usize>
368    where
369        P: FnMut(Self::Item) -> bool,
370    {
371        self.0.position(predicate)
372    }
373
374    #[inline]
375    #[ferrocene::prevalidated]
376    fn rposition<P>(&mut self, predicate: P) -> Option<usize>
377    where
378        P: FnMut(Self::Item) -> bool,
379    {
380        self.0.rposition(predicate)
381    }
382
383    #[inline]
384    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> u8 {
385        // SAFETY: the caller must uphold the safety contract
386        // for `Iterator::__iterator_get_unchecked`.
387        unsafe { self.0.__iterator_get_unchecked(idx) }
388    }
389}
390
391#[stable(feature = "rust1", since = "1.0.0")]
392impl DoubleEndedIterator for Bytes<'_> {
393    #[inline]
394    fn next_back(&mut self) -> Option<u8> {
395        self.0.next_back()
396    }
397
398    #[inline]
399    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
400        self.0.nth_back(n)
401    }
402
403    #[inline]
404    fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
405    where
406        P: FnMut(&Self::Item) -> bool,
407    {
408        self.0.rfind(predicate)
409    }
410}
411
412#[stable(feature = "rust1", since = "1.0.0")]
413impl ExactSizeIterator for Bytes<'_> {
414    #[inline]
415    fn len(&self) -> usize {
416        self.0.len()
417    }
418
419    #[inline]
420    fn is_empty(&self) -> bool {
421        self.0.is_empty()
422    }
423}
424
425#[stable(feature = "fused", since = "1.26.0")]
426impl FusedIterator for Bytes<'_> {}
427
428#[unstable(feature = "trusted_len", issue = "37572")]
429unsafe impl TrustedLen for Bytes<'_> {}
430
431#[doc(hidden)]
432#[unstable(feature = "trusted_random_access", issue = "none")]
433unsafe impl TrustedRandomAccess for Bytes<'_> {}
434
435#[doc(hidden)]
436#[unstable(feature = "trusted_random_access", issue = "none")]
437unsafe impl TrustedRandomAccessNoCoerce for Bytes<'_> {
438    const MAY_HAVE_SIDE_EFFECT: bool = false;
439}
440
441/// This macro generates a Clone impl for string pattern API
442/// wrapper types of the form X<'a, P>
443macro_rules! derive_pattern_clone {
444    (clone $t:ident with |$s:ident| $e:expr) => {
445        impl<'a, P> Clone for $t<'a, P>
446        where
447            P: Pattern<Searcher<'a>: Clone>,
448        {
449            fn clone(&self) -> Self {
450                let $s = self;
451                $e
452            }
453        }
454    };
455}
456
457/// This macro generates two public iterator structs
458/// wrapping a private internal one that makes use of the `Pattern` API.
459///
460/// For all patterns `P: Pattern` the following items will be
461/// generated (generics omitted):
462///
463/// struct $forward_iterator($internal_iterator);
464/// struct $reverse_iterator($internal_iterator);
465///
466/// impl Iterator for $forward_iterator
467/// { /* internal ends up calling Searcher::next_match() */ }
468///
469/// impl DoubleEndedIterator for $forward_iterator
470///       where P::Searcher: DoubleEndedSearcher
471/// { /* internal ends up calling Searcher::next_match_back() */ }
472///
473/// impl Iterator for $reverse_iterator
474///       where P::Searcher: ReverseSearcher
475/// { /* internal ends up calling Searcher::next_match_back() */ }
476///
477/// impl DoubleEndedIterator for $reverse_iterator
478///       where P::Searcher: DoubleEndedSearcher
479/// { /* internal ends up calling Searcher::next_match() */ }
480///
481/// The internal one is defined outside the macro, and has almost the same
482/// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
483/// `pattern::ReverseSearcher` for both forward and reverse iteration.
484///
485/// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
486/// `Pattern` might not return the same elements, so actually implementing
487/// `DoubleEndedIterator` for it would be incorrect.
488/// (See the docs in `str::pattern` for more details)
489///
490/// However, the internal struct still represents a single ended iterator from
491/// either end, and depending on pattern is also a valid double ended iterator,
492/// so the two wrapper structs implement `Iterator`
493/// and `DoubleEndedIterator` depending on the concrete pattern type, leading
494/// to the complex impls seen above.
495macro_rules! generate_pattern_iterators {
496    {
497        // Forward iterator
498        forward:
499            $(#[$forward_iterator_attribute:meta])*
500            struct $forward_iterator:ident;
501
502        // Reverse iterator
503        reverse:
504            $(#[$reverse_iterator_attribute:meta])*
505            struct $reverse_iterator:ident;
506
507        // Stability of all generated items
508        stability:
509            $(#[$common_stability_attribute:meta])*
510
511        // Internal almost-iterator that is being delegated to
512        internal:
513            $internal_iterator:ident yielding ($iterty:ty);
514
515        // Kind of delegation - either single ended or double ended
516        delegate $($t:tt)*
517    } => {
518        $(#[$forward_iterator_attribute])*
519        $(#[$common_stability_attribute])*
520        pub struct $forward_iterator<'a, P: Pattern>(pub(super) $internal_iterator<'a, P>);
521
522        $(#[$common_stability_attribute])*
523        impl<'a, P> fmt::Debug for $forward_iterator<'a, P>
524        where
525            P: Pattern<Searcher<'a>: fmt::Debug>,
526        {
527            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528                f.debug_tuple(stringify!($forward_iterator))
529                    .field(&self.0)
530                    .finish()
531            }
532        }
533
534        $(#[$common_stability_attribute])*
535        impl<'a, P: Pattern> Iterator for $forward_iterator<'a, P> {
536            type Item = $iterty;
537
538            #[ferrocene::prevalidated]
539            #[inline]
540            fn next(&mut self) -> Option<$iterty> {
541                self.0.next()
542            }
543        }
544
545        $(#[$common_stability_attribute])*
546        impl<'a, P> Clone for $forward_iterator<'a, P>
547        where
548            P: Pattern<Searcher<'a>: Clone>,
549        {
550            fn clone(&self) -> Self {
551                $forward_iterator(self.0.clone())
552            }
553        }
554
555        $(#[$reverse_iterator_attribute])*
556        $(#[$common_stability_attribute])*
557        pub struct $reverse_iterator<'a, P: Pattern>(pub(super) $internal_iterator<'a, P>);
558
559        $(#[$common_stability_attribute])*
560        impl<'a, P> fmt::Debug for $reverse_iterator<'a, P>
561        where
562            P: Pattern<Searcher<'a>: fmt::Debug>,
563        {
564            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
565                f.debug_tuple(stringify!($reverse_iterator))
566                    .field(&self.0)
567                    .finish()
568            }
569        }
570
571        $(#[$common_stability_attribute])*
572        impl<'a, P> Iterator for $reverse_iterator<'a, P>
573        where
574            P: Pattern<Searcher<'a>: ReverseSearcher<'a>>,
575        {
576            type Item = $iterty;
577
578            #[inline]
579            fn next(&mut self) -> Option<$iterty> {
580                self.0.next_back()
581            }
582        }
583
584        $(#[$common_stability_attribute])*
585        impl<'a, P> Clone for $reverse_iterator<'a, P>
586        where
587            P: Pattern<Searcher<'a>: Clone>,
588        {
589            fn clone(&self) -> Self {
590                $reverse_iterator(self.0.clone())
591            }
592        }
593
594        #[stable(feature = "fused", since = "1.26.0")]
595        impl<'a, P: Pattern> FusedIterator for $forward_iterator<'a, P> {}
596
597        #[stable(feature = "fused", since = "1.26.0")]
598        impl<'a, P> FusedIterator for $reverse_iterator<'a, P>
599        where
600            P: Pattern<Searcher<'a>: ReverseSearcher<'a>>,
601        {}
602
603        generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
604                                                $forward_iterator,
605                                                $reverse_iterator, $iterty);
606    };
607    {
608        double ended; with $(#[$common_stability_attribute:meta])*,
609                           $forward_iterator:ident,
610                           $reverse_iterator:ident, $iterty:ty
611    } => {
612        $(#[$common_stability_attribute])*
613        impl<'a, P> DoubleEndedIterator for $forward_iterator<'a, P>
614        where
615            P: Pattern<Searcher<'a>: DoubleEndedSearcher<'a>>,
616        {
617            #[inline]
618            fn next_back(&mut self) -> Option<$iterty> {
619                self.0.next_back()
620            }
621        }
622
623        $(#[$common_stability_attribute])*
624        impl<'a, P> DoubleEndedIterator for $reverse_iterator<'a, P>
625        where
626            P: Pattern<Searcher<'a>: DoubleEndedSearcher<'a>>,
627        {
628            #[inline]
629            fn next_back(&mut self) -> Option<$iterty> {
630                self.0.next()
631            }
632        }
633    };
634    {
635        single ended; with $(#[$common_stability_attribute:meta])*,
636                           $forward_iterator:ident,
637                           $reverse_iterator:ident, $iterty:ty
638    } => {}
639}
640
641derive_pattern_clone! {
642    clone SplitInternal
643    with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
644}
645
646#[ferrocene::prevalidated]
647pub(super) struct SplitInternal<'a, P: Pattern> {
648    pub(super) start: usize,
649    pub(super) end: usize,
650    pub(super) matcher: P::Searcher<'a>,
651    pub(super) allow_trailing_empty: bool,
652    pub(super) finished: bool,
653}
654
655impl<'a, P> fmt::Debug for SplitInternal<'a, P>
656where
657    P: Pattern<Searcher<'a>: fmt::Debug>,
658{
659    #[ferrocene::prevalidated]
660    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661        f.debug_struct("SplitInternal")
662            .field("start", &self.start)
663            .field("end", &self.end)
664            .field("matcher", &self.matcher)
665            .field("allow_trailing_empty", &self.allow_trailing_empty)
666            .field("finished", &self.finished)
667            .finish()
668    }
669}
670
671impl<'a, P: Pattern> SplitInternal<'a, P> {
672    #[inline]
673    #[ferrocene::prevalidated]
674    fn get_end(&mut self) -> Option<&'a str> {
675        if !self.finished {
676            self.finished = true;
677
678            if self.allow_trailing_empty || self.end - self.start > 0 {
679                // SAFETY: `self.start` and `self.end` always lie on unicode boundaries.
680                let string = unsafe { self.matcher.haystack().get_unchecked(self.start..self.end) };
681                return Some(string);
682            }
683        }
684
685        None
686    }
687
688    #[ferrocene::prevalidated]
689    #[inline]
690    fn next(&mut self) -> Option<&'a str> {
691        if self.finished {
692            return None;
693        }
694
695        let haystack = self.matcher.haystack();
696        match self.matcher.next_match() {
697            // SAFETY: `Searcher` guarantees that:
698            // - `a` and `b` lie on unicode boundaries.
699            // - `a <= b <= haystack().len()` is satisfied.
700            Some((a, b)) => unsafe {
701                let elt = haystack.get_unchecked(self.start..a);
702                self.start = b;
703                Some(elt)
704            },
705            None => self.get_end(),
706        }
707    }
708
709    #[inline]
710    #[ferrocene::prevalidated]
711    fn next_inclusive(&mut self) -> Option<&'a str> {
712        if self.finished {
713            return None;
714        }
715
716        let haystack = self.matcher.haystack();
717        match self.matcher.next_match() {
718            // SAFETY: `Searcher` guarantees that:
719            // - `b` lies on unicode boundary.
720            // - `self.start` is either the start of the original string,
721            // or `b` was assigned to it, so it also lies on unicode boundary.
722            // - `self.start <= b <= haystack().len()` is satisfied.
723            Some((_, b)) => unsafe {
724                let elt = haystack.get_unchecked(self.start..b);
725                self.start = b;
726                Some(elt)
727            },
728            None => self.get_end(),
729        }
730    }
731
732    #[inline]
733    fn next_back(&mut self) -> Option<&'a str>
734    where
735        P::Searcher<'a>: ReverseSearcher<'a>,
736    {
737        if self.finished {
738            return None;
739        }
740
741        if !self.allow_trailing_empty {
742            self.allow_trailing_empty = true;
743            match self.next_back() {
744                Some(elt) if !elt.is_empty() => return Some(elt),
745                _ => {
746                    if self.finished {
747                        return None;
748                    }
749                }
750            }
751        }
752
753        let haystack = self.matcher.haystack();
754        match self.matcher.next_match_back() {
755            // SAFETY: `Searcher` guarantees that:
756            // - `a` and `b` lie on unicode boundaries.
757            // - `self.end` is either the end of the original string,
758            // or `a` was assigned to it, so it also lies on unicode boundary.
759            // - `a <= b <= haystack().len()` is satisfied.
760            Some((a, b)) => unsafe {
761                let elt = haystack.get_unchecked(b..self.end);
762                self.end = a;
763                Some(elt)
764            },
765            // SAFETY: `self.start` and `self.end` always lie on unicode boundaries.
766            None => unsafe {
767                self.finished = true;
768                Some(haystack.get_unchecked(self.start..self.end))
769            },
770        }
771    }
772
773    #[inline]
774    fn next_back_inclusive(&mut self) -> Option<&'a str>
775    where
776        P::Searcher<'a>: ReverseSearcher<'a>,
777    {
778        if self.finished {
779            return None;
780        }
781
782        if !self.allow_trailing_empty {
783            self.allow_trailing_empty = true;
784            match self.next_back_inclusive() {
785                Some(elt) if !elt.is_empty() => return Some(elt),
786                _ => {
787                    if self.finished {
788                        return None;
789                    }
790                }
791            }
792        }
793
794        let haystack = self.matcher.haystack();
795        match self.matcher.next_match_back() {
796            // SAFETY: `Searcher` guarantees that:
797            // - `b` lies on unicode boundary.
798            // - self.end is either the end of the original string,
799            // or `b` was assigned to it, so it also lies on unicode boundary.
800            // - `self.end <= b <= haystack.len()` is satisfied.
801            Some((_, b)) => unsafe {
802                let elt = haystack.get_unchecked(b..self.end);
803                self.end = b;
804                Some(elt)
805            },
806            // SAFETY: self.start is either the start of the original string,
807            // or start of a substring that represents the part of the string that hasn't
808            // iterated yet. Either way, it is guaranteed to lie on unicode boundary.
809            // self.end is either the end of the original string,
810            // or `b` was assigned to it, so it also lies on unicode boundary.
811            None => unsafe {
812                self.finished = true;
813                Some(haystack.get_unchecked(self.start..self.end))
814            },
815        }
816    }
817
818    #[inline]
819    fn remainder(&self) -> Option<&'a str> {
820        // `Self::get_end` doesn't change `self.start`
821        if self.finished {
822            return None;
823        }
824
825        // SAFETY: `self.start` and `self.end` always lie on unicode boundaries.
826        Some(unsafe { self.matcher.haystack().get_unchecked(self.start..self.end) })
827    }
828}
829
830generate_pattern_iterators! {
831    forward:
832        /// Created with the method [`split`].
833        ///
834        /// [`split`]: str::split
835        struct Split;
836    reverse:
837        /// Created with the method [`rsplit`].
838        ///
839        /// [`rsplit`]: str::rsplit
840        struct RSplit;
841    stability:
842        #[stable(feature = "rust1", since = "1.0.0")]
843    internal:
844        SplitInternal yielding (&'a str);
845    delegate double ended;
846}
847
848impl<'a, P: Pattern> Split<'a, P> {
849    /// Returns remainder of the split string.
850    ///
851    /// If the iterator is empty, returns `None`.
852    ///
853    /// # Examples
854    ///
855    /// ```
856    /// #![feature(str_split_remainder)]
857    /// let mut split = "Mary had a little lamb".split(' ');
858    /// assert_eq!(split.remainder(), Some("Mary had a little lamb"));
859    /// split.next();
860    /// assert_eq!(split.remainder(), Some("had a little lamb"));
861    /// split.by_ref().for_each(drop);
862    /// assert_eq!(split.remainder(), None);
863    /// ```
864    #[inline]
865    #[unstable(feature = "str_split_remainder", issue = "77998")]
866    pub fn remainder(&self) -> Option<&'a str> {
867        self.0.remainder()
868    }
869}
870
871impl<'a, P: Pattern> RSplit<'a, P> {
872    /// Returns remainder of the split string.
873    ///
874    /// If the iterator is empty, returns `None`.
875    ///
876    /// # Examples
877    ///
878    /// ```
879    /// #![feature(str_split_remainder)]
880    /// let mut split = "Mary had a little lamb".rsplit(' ');
881    /// assert_eq!(split.remainder(), Some("Mary had a little lamb"));
882    /// split.next();
883    /// assert_eq!(split.remainder(), Some("Mary had a little"));
884    /// split.by_ref().for_each(drop);
885    /// assert_eq!(split.remainder(), None);
886    /// ```
887    #[inline]
888    #[unstable(feature = "str_split_remainder", issue = "77998")]
889    pub fn remainder(&self) -> Option<&'a str> {
890        self.0.remainder()
891    }
892}
893
894generate_pattern_iterators! {
895    forward:
896        /// Created with the method [`split_terminator`].
897        ///
898        /// [`split_terminator`]: str::split_terminator
899        struct SplitTerminator;
900    reverse:
901        /// Created with the method [`rsplit_terminator`].
902        ///
903        /// [`rsplit_terminator`]: str::rsplit_terminator
904        struct RSplitTerminator;
905    stability:
906        #[stable(feature = "rust1", since = "1.0.0")]
907    internal:
908        SplitInternal yielding (&'a str);
909    delegate double ended;
910}
911
912impl<'a, P: Pattern> SplitTerminator<'a, P> {
913    /// Returns remainder of the split string.
914    ///
915    /// If the iterator is empty, returns `None`.
916    ///
917    /// # Examples
918    ///
919    /// ```
920    /// #![feature(str_split_remainder)]
921    /// let mut split = "A..B..".split_terminator('.');
922    /// assert_eq!(split.remainder(), Some("A..B.."));
923    /// split.next();
924    /// assert_eq!(split.remainder(), Some(".B.."));
925    /// split.by_ref().for_each(drop);
926    /// assert_eq!(split.remainder(), None);
927    /// ```
928    #[inline]
929    #[unstable(feature = "str_split_remainder", issue = "77998")]
930    pub fn remainder(&self) -> Option<&'a str> {
931        self.0.remainder()
932    }
933}
934
935impl<'a, P: Pattern> RSplitTerminator<'a, P> {
936    /// Returns remainder of the split string.
937    ///
938    /// If the iterator is empty, returns `None`.
939    ///
940    /// # Examples
941    ///
942    /// ```
943    /// #![feature(str_split_remainder)]
944    /// let mut split = "A..B..".rsplit_terminator('.');
945    /// assert_eq!(split.remainder(), Some("A..B.."));
946    /// split.next();
947    /// assert_eq!(split.remainder(), Some("A..B"));
948    /// split.by_ref().for_each(drop);
949    /// assert_eq!(split.remainder(), None);
950    /// ```
951    #[inline]
952    #[unstable(feature = "str_split_remainder", issue = "77998")]
953    pub fn remainder(&self) -> Option<&'a str> {
954        self.0.remainder()
955    }
956}
957
958derive_pattern_clone! {
959    clone SplitNInternal
960    with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
961}
962
963pub(super) struct SplitNInternal<'a, P: Pattern> {
964    pub(super) iter: SplitInternal<'a, P>,
965    /// The number of splits remaining
966    pub(super) count: usize,
967}
968
969impl<'a, P> fmt::Debug for SplitNInternal<'a, P>
970where
971    P: Pattern<Searcher<'a>: fmt::Debug>,
972{
973    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
974        f.debug_struct("SplitNInternal")
975            .field("iter", &self.iter)
976            .field("count", &self.count)
977            .finish()
978    }
979}
980
981impl<'a, P: Pattern> SplitNInternal<'a, P> {
982    #[ferrocene::prevalidated]
983    #[inline]
984    fn next(&mut self) -> Option<&'a str> {
985        match self.count {
986            0 => None,
987            1 => {
988                self.count = 0;
989                self.iter.get_end()
990            }
991            _ => {
992                self.count -= 1;
993                self.iter.next()
994            }
995        }
996    }
997
998    #[inline]
999    fn next_back(&mut self) -> Option<&'a str>
1000    where
1001        P::Searcher<'a>: ReverseSearcher<'a>,
1002    {
1003        match self.count {
1004            0 => None,
1005            1 => {
1006                self.count = 0;
1007                self.iter.get_end()
1008            }
1009            _ => {
1010                self.count -= 1;
1011                self.iter.next_back()
1012            }
1013        }
1014    }
1015
1016    #[inline]
1017    fn remainder(&self) -> Option<&'a str> {
1018        self.iter.remainder()
1019    }
1020}
1021
1022generate_pattern_iterators! {
1023    forward:
1024        /// Created with the method [`splitn`].
1025        ///
1026        /// [`splitn`]: str::splitn
1027        struct SplitN;
1028    reverse:
1029        /// Created with the method [`rsplitn`].
1030        ///
1031        /// [`rsplitn`]: str::rsplitn
1032        struct RSplitN;
1033    stability:
1034        #[stable(feature = "rust1", since = "1.0.0")]
1035    internal:
1036        SplitNInternal yielding (&'a str);
1037    delegate single ended;
1038}
1039
1040impl<'a, P: Pattern> SplitN<'a, P> {
1041    /// Returns remainder of the split string.
1042    ///
1043    /// If the iterator is empty, returns `None`.
1044    ///
1045    /// # Examples
1046    ///
1047    /// ```
1048    /// #![feature(str_split_remainder)]
1049    /// let mut split = "Mary had a little lamb".splitn(3, ' ');
1050    /// assert_eq!(split.remainder(), Some("Mary had a little lamb"));
1051    /// split.next();
1052    /// assert_eq!(split.remainder(), Some("had a little lamb"));
1053    /// split.by_ref().for_each(drop);
1054    /// assert_eq!(split.remainder(), None);
1055    /// ```
1056    #[inline]
1057    #[unstable(feature = "str_split_remainder", issue = "77998")]
1058    pub fn remainder(&self) -> Option<&'a str> {
1059        self.0.remainder()
1060    }
1061}
1062
1063impl<'a, P: Pattern> RSplitN<'a, P> {
1064    /// Returns remainder of the split string.
1065    ///
1066    /// If the iterator is empty, returns `None`.
1067    ///
1068    /// # Examples
1069    ///
1070    /// ```
1071    /// #![feature(str_split_remainder)]
1072    /// let mut split = "Mary had a little lamb".rsplitn(3, ' ');
1073    /// assert_eq!(split.remainder(), Some("Mary had a little lamb"));
1074    /// split.next();
1075    /// assert_eq!(split.remainder(), Some("Mary had a little"));
1076    /// split.by_ref().for_each(drop);
1077    /// assert_eq!(split.remainder(), None);
1078    /// ```
1079    #[inline]
1080    #[unstable(feature = "str_split_remainder", issue = "77998")]
1081    pub fn remainder(&self) -> Option<&'a str> {
1082        self.0.remainder()
1083    }
1084}
1085
1086derive_pattern_clone! {
1087    clone MatchIndicesInternal
1088    with |s| MatchIndicesInternal(s.0.clone())
1089}
1090
1091pub(super) struct MatchIndicesInternal<'a, P: Pattern>(pub(super) P::Searcher<'a>);
1092
1093impl<'a, P> fmt::Debug for MatchIndicesInternal<'a, P>
1094where
1095    P: Pattern<Searcher<'a>: fmt::Debug>,
1096{
1097    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1098        f.debug_tuple("MatchIndicesInternal").field(&self.0).finish()
1099    }
1100}
1101
1102impl<'a, P: Pattern> MatchIndicesInternal<'a, P> {
1103    #[ferrocene::prevalidated]
1104    #[inline]
1105    fn next(&mut self) -> Option<(usize, &'a str)> {
1106        self.0
1107            .next_match()
1108            // SAFETY: `Searcher` guarantees that `start` and `end` lie on unicode boundaries.
1109            .map(|(start, end)| unsafe { (start, self.0.haystack().get_unchecked(start..end)) })
1110    }
1111
1112    #[inline]
1113    fn next_back(&mut self) -> Option<(usize, &'a str)>
1114    where
1115        P::Searcher<'a>: ReverseSearcher<'a>,
1116    {
1117        self.0
1118            .next_match_back()
1119            // SAFETY: `Searcher` guarantees that `start` and `end` lie on unicode boundaries.
1120            .map(|(start, end)| unsafe { (start, self.0.haystack().get_unchecked(start..end)) })
1121    }
1122}
1123
1124generate_pattern_iterators! {
1125    forward:
1126        /// Created with the method [`match_indices`].
1127        ///
1128        /// [`match_indices`]: str::match_indices
1129        struct MatchIndices;
1130    reverse:
1131        /// Created with the method [`rmatch_indices`].
1132        ///
1133        /// [`rmatch_indices`]: str::rmatch_indices
1134        struct RMatchIndices;
1135    stability:
1136        #[stable(feature = "str_match_indices", since = "1.5.0")]
1137    internal:
1138        MatchIndicesInternal yielding ((usize, &'a str));
1139    delegate double ended;
1140}
1141
1142derive_pattern_clone! {
1143    clone MatchesInternal
1144    with |s| MatchesInternal(s.0.clone())
1145}
1146
1147pub(super) struct MatchesInternal<'a, P: Pattern>(pub(super) P::Searcher<'a>);
1148
1149impl<'a, P> fmt::Debug for MatchesInternal<'a, P>
1150where
1151    P: Pattern<Searcher<'a>: fmt::Debug>,
1152{
1153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1154        f.debug_tuple("MatchesInternal").field(&self.0).finish()
1155    }
1156}
1157
1158impl<'a, P: Pattern> MatchesInternal<'a, P> {
1159    #[ferrocene::prevalidated]
1160    #[inline]
1161    fn next(&mut self) -> Option<&'a str> {
1162        // SAFETY: `Searcher` guarantees that `start` and `end` lie on unicode boundaries.
1163        self.0.next_match().map(|(a, b)| unsafe {
1164            // Indices are known to be on utf8 boundaries
1165            self.0.haystack().get_unchecked(a..b)
1166        })
1167    }
1168
1169    #[inline]
1170    fn next_back(&mut self) -> Option<&'a str>
1171    where
1172        P::Searcher<'a>: ReverseSearcher<'a>,
1173    {
1174        // SAFETY: `Searcher` guarantees that `start` and `end` lie on unicode boundaries.
1175        self.0.next_match_back().map(|(a, b)| unsafe {
1176            // Indices are known to be on utf8 boundaries
1177            self.0.haystack().get_unchecked(a..b)
1178        })
1179    }
1180}
1181
1182generate_pattern_iterators! {
1183    forward:
1184        /// Created with the method [`matches`].
1185        ///
1186        /// [`matches`]: str::matches
1187        struct Matches;
1188    reverse:
1189        /// Created with the method [`rmatches`].
1190        ///
1191        /// [`rmatches`]: str::rmatches
1192        struct RMatches;
1193    stability:
1194        #[stable(feature = "str_matches", since = "1.2.0")]
1195    internal:
1196        MatchesInternal yielding (&'a str);
1197    delegate double ended;
1198}
1199
1200/// An iterator over the lines of a string, as string slices.
1201///
1202/// This struct is created with the [`lines`] method on [`str`].
1203/// See its documentation for more.
1204///
1205/// [`lines`]: str::lines
1206#[stable(feature = "rust1", since = "1.0.0")]
1207#[must_use = "iterators are lazy and do nothing unless consumed"]
1208#[derive(Clone, Debug)]
1209pub struct Lines<'a>(pub(super) Map<SplitInclusive<'a, char>, LinesMap>);
1210
1211#[stable(feature = "rust1", since = "1.0.0")]
1212impl<'a> Iterator for Lines<'a> {
1213    type Item = &'a str;
1214
1215    #[inline]
1216    fn next(&mut self) -> Option<&'a str> {
1217        self.0.next()
1218    }
1219
1220    #[inline]
1221    fn size_hint(&self) -> (usize, Option<usize>) {
1222        self.0.size_hint()
1223    }
1224
1225    #[inline]
1226    fn last(mut self) -> Option<&'a str> {
1227        self.next_back()
1228    }
1229}
1230
1231#[stable(feature = "rust1", since = "1.0.0")]
1232impl<'a> DoubleEndedIterator for Lines<'a> {
1233    #[inline]
1234    fn next_back(&mut self) -> Option<&'a str> {
1235        self.0.next_back()
1236    }
1237}
1238
1239#[stable(feature = "fused", since = "1.26.0")]
1240impl FusedIterator for Lines<'_> {}
1241
1242impl<'a> Lines<'a> {
1243    /// Returns the remaining lines of the split string.
1244    ///
1245    /// # Examples
1246    ///
1247    /// ```
1248    /// #![feature(str_lines_remainder)]
1249    ///
1250    /// let mut lines = "a\nb\nc\nd".lines();
1251    /// assert_eq!(lines.remainder(), Some("a\nb\nc\nd"));
1252    ///
1253    /// lines.next();
1254    /// assert_eq!(lines.remainder(), Some("b\nc\nd"));
1255    ///
1256    /// lines.by_ref().for_each(drop);
1257    /// assert_eq!(lines.remainder(), None);
1258    /// ```
1259    #[inline]
1260    #[must_use]
1261    #[unstable(feature = "str_lines_remainder", issue = "77998")]
1262    pub fn remainder(&self) -> Option<&'a str> {
1263        self.0.iter.remainder()
1264    }
1265}
1266
1267/// Created with the method [`lines_any`].
1268///
1269/// [`lines_any`]: str::lines_any
1270#[stable(feature = "rust1", since = "1.0.0")]
1271#[deprecated(since = "1.4.0", note = "use lines()/Lines instead now")]
1272#[must_use = "iterators are lazy and do nothing unless consumed"]
1273#[derive(Clone, Debug)]
1274#[allow(deprecated)]
1275pub struct LinesAny<'a>(pub(super) Lines<'a>);
1276
1277#[stable(feature = "rust1", since = "1.0.0")]
1278#[allow(deprecated)]
1279impl<'a> Iterator for LinesAny<'a> {
1280    type Item = &'a str;
1281
1282    #[inline]
1283    fn next(&mut self) -> Option<&'a str> {
1284        self.0.next()
1285    }
1286
1287    #[inline]
1288    fn size_hint(&self) -> (usize, Option<usize>) {
1289        self.0.size_hint()
1290    }
1291}
1292
1293#[stable(feature = "rust1", since = "1.0.0")]
1294#[allow(deprecated)]
1295impl<'a> DoubleEndedIterator for LinesAny<'a> {
1296    #[inline]
1297    fn next_back(&mut self) -> Option<&'a str> {
1298        self.0.next_back()
1299    }
1300}
1301
1302#[stable(feature = "fused", since = "1.26.0")]
1303#[allow(deprecated)]
1304impl FusedIterator for LinesAny<'_> {}
1305
1306/// An iterator over the non-whitespace substrings of a string,
1307/// separated by any amount of whitespace.
1308///
1309/// This struct is created by the [`split_whitespace`] method on [`str`].
1310/// See its documentation for more.
1311///
1312/// [`split_whitespace`]: str::split_whitespace
1313#[stable(feature = "split_whitespace", since = "1.1.0")]
1314#[derive(Clone, Debug)]
1315pub struct SplitWhitespace<'a> {
1316    pub(super) inner: Filter<Split<'a, IsWhitespace>, IsNotEmpty>,
1317}
1318
1319/// An iterator over the non-ASCII-whitespace substrings of a string,
1320/// separated by any amount of ASCII whitespace.
1321///
1322/// This struct is created by the [`split_ascii_whitespace`] method on [`str`].
1323/// See its documentation for more.
1324///
1325/// [`split_ascii_whitespace`]: str::split_ascii_whitespace
1326#[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
1327#[derive(Clone, Debug)]
1328pub struct SplitAsciiWhitespace<'a> {
1329    pub(super) inner:
1330        Map<Filter<SliceSplit<'a, u8, IsAsciiWhitespace>, BytesIsNotEmpty>, UnsafeBytesToStr>,
1331}
1332
1333/// An iterator over the substrings of a string,
1334/// terminated by a substring matching to a predicate function.
1335/// Unlike `Split`, it contains the matched part as a terminator
1336/// of the subslice.
1337///
1338/// This struct is created by the [`split_inclusive`] method on [`str`].
1339/// See its documentation for more.
1340///
1341/// [`split_inclusive`]: str::split_inclusive
1342#[stable(feature = "split_inclusive", since = "1.51.0")]
1343#[ferrocene::prevalidated]
1344pub struct SplitInclusive<'a, P: Pattern>(pub(super) SplitInternal<'a, P>);
1345
1346#[stable(feature = "split_whitespace", since = "1.1.0")]
1347impl<'a> Iterator for SplitWhitespace<'a> {
1348    type Item = &'a str;
1349
1350    #[inline]
1351    fn next(&mut self) -> Option<&'a str> {
1352        self.inner.next()
1353    }
1354
1355    #[inline]
1356    fn size_hint(&self) -> (usize, Option<usize>) {
1357        self.inner.size_hint()
1358    }
1359
1360    #[inline]
1361    fn last(mut self) -> Option<&'a str> {
1362        self.next_back()
1363    }
1364}
1365
1366#[stable(feature = "split_whitespace", since = "1.1.0")]
1367impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
1368    #[inline]
1369    fn next_back(&mut self) -> Option<&'a str> {
1370        self.inner.next_back()
1371    }
1372}
1373
1374#[stable(feature = "fused", since = "1.26.0")]
1375impl FusedIterator for SplitWhitespace<'_> {}
1376
1377impl<'a> SplitWhitespace<'a> {
1378    /// Returns remainder of the split string
1379    ///
1380    /// # Examples
1381    ///
1382    /// ```
1383    /// #![feature(str_split_whitespace_remainder)]
1384    ///
1385    /// let mut split = "Mary had a little lamb".split_whitespace();
1386    /// assert_eq!(split.remainder(), Some("Mary had a little lamb"));
1387    ///
1388    /// split.next();
1389    /// assert_eq!(split.remainder(), Some("had a little lamb"));
1390    ///
1391    /// split.by_ref().for_each(drop);
1392    /// assert_eq!(split.remainder(), None);
1393    /// ```
1394    #[inline]
1395    #[must_use]
1396    #[unstable(feature = "str_split_whitespace_remainder", issue = "77998")]
1397    pub fn remainder(&self) -> Option<&'a str> {
1398        self.inner.iter.remainder()
1399    }
1400}
1401
1402#[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
1403impl<'a> Iterator for SplitAsciiWhitespace<'a> {
1404    type Item = &'a str;
1405
1406    #[inline]
1407    fn next(&mut self) -> Option<&'a str> {
1408        self.inner.next()
1409    }
1410
1411    #[inline]
1412    fn size_hint(&self) -> (usize, Option<usize>) {
1413        self.inner.size_hint()
1414    }
1415
1416    #[inline]
1417    fn last(mut self) -> Option<&'a str> {
1418        self.next_back()
1419    }
1420}
1421
1422#[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
1423impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> {
1424    #[inline]
1425    fn next_back(&mut self) -> Option<&'a str> {
1426        self.inner.next_back()
1427    }
1428}
1429
1430#[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
1431impl FusedIterator for SplitAsciiWhitespace<'_> {}
1432
1433impl<'a> SplitAsciiWhitespace<'a> {
1434    /// Returns remainder of the split string.
1435    ///
1436    /// If the iterator is empty, returns `None`.
1437    ///
1438    /// # Examples
1439    ///
1440    /// ```
1441    /// #![feature(str_split_whitespace_remainder)]
1442    ///
1443    /// let mut split = "Mary had a little lamb".split_ascii_whitespace();
1444    /// assert_eq!(split.remainder(), Some("Mary had a little lamb"));
1445    ///
1446    /// split.next();
1447    /// assert_eq!(split.remainder(), Some("had a little lamb"));
1448    ///
1449    /// split.by_ref().for_each(drop);
1450    /// assert_eq!(split.remainder(), None);
1451    /// ```
1452    #[inline]
1453    #[must_use]
1454    #[unstable(feature = "str_split_whitespace_remainder", issue = "77998")]
1455    pub fn remainder(&self) -> Option<&'a str> {
1456        if self.inner.iter.iter.finished {
1457            return None;
1458        }
1459
1460        // SAFETY: Slice is created from str.
1461        Some(unsafe { crate::str::from_utf8_unchecked(self.inner.iter.iter.v) })
1462    }
1463}
1464
1465#[stable(feature = "split_inclusive", since = "1.51.0")]
1466impl<'a, P: Pattern> Iterator for SplitInclusive<'a, P> {
1467    type Item = &'a str;
1468
1469    #[inline]
1470    #[ferrocene::prevalidated]
1471    fn next(&mut self) -> Option<&'a str> {
1472        self.0.next_inclusive()
1473    }
1474}
1475
1476#[stable(feature = "split_inclusive", since = "1.51.0")]
1477impl<'a, P: Pattern<Searcher<'a>: fmt::Debug>> fmt::Debug for SplitInclusive<'a, P> {
1478    #[ferrocene::prevalidated]
1479    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1480        f.debug_struct("SplitInclusive").field("0", &self.0).finish()
1481    }
1482}
1483
1484// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1485#[stable(feature = "split_inclusive", since = "1.51.0")]
1486impl<'a, P: Pattern<Searcher<'a>: Clone>> Clone for SplitInclusive<'a, P> {
1487    fn clone(&self) -> Self {
1488        SplitInclusive(self.0.clone())
1489    }
1490}
1491
1492#[stable(feature = "split_inclusive", since = "1.51.0")]
1493impl<'a, P: Pattern<Searcher<'a>: DoubleEndedSearcher<'a>>> DoubleEndedIterator
1494    for SplitInclusive<'a, P>
1495{
1496    #[inline]
1497    fn next_back(&mut self) -> Option<&'a str> {
1498        self.0.next_back_inclusive()
1499    }
1500}
1501
1502#[stable(feature = "split_inclusive", since = "1.51.0")]
1503impl<'a, P: Pattern> FusedIterator for SplitInclusive<'a, P> {}
1504
1505impl<'a, P: Pattern> SplitInclusive<'a, P> {
1506    /// Returns remainder of the split string.
1507    ///
1508    /// If the iterator is empty, returns `None`.
1509    ///
1510    /// # Examples
1511    ///
1512    /// ```
1513    /// #![feature(str_split_inclusive_remainder)]
1514    /// let mut split = "Mary had a little lamb".split_inclusive(' ');
1515    /// assert_eq!(split.remainder(), Some("Mary had a little lamb"));
1516    /// split.next();
1517    /// assert_eq!(split.remainder(), Some("had a little lamb"));
1518    /// split.by_ref().for_each(drop);
1519    /// assert_eq!(split.remainder(), None);
1520    /// ```
1521    #[inline]
1522    #[unstable(feature = "str_split_inclusive_remainder", issue = "77998")]
1523    pub fn remainder(&self) -> Option<&'a str> {
1524        self.0.remainder()
1525    }
1526}
1527
1528/// An iterator of [`u16`] over the string encoded as UTF-16.
1529///
1530/// This struct is created by the [`encode_utf16`] method on [`str`].
1531/// See its documentation for more.
1532///
1533/// [`encode_utf16`]: str::encode_utf16
1534#[derive(Clone)]
1535#[stable(feature = "encode_utf16", since = "1.8.0")]
1536pub struct EncodeUtf16<'a> {
1537    pub(super) chars: Chars<'a>,
1538    pub(super) extra: u16,
1539}
1540
1541#[stable(feature = "collection_debug", since = "1.17.0")]
1542impl fmt::Debug for EncodeUtf16<'_> {
1543    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1544        f.debug_struct("EncodeUtf16").finish_non_exhaustive()
1545    }
1546}
1547
1548#[stable(feature = "encode_utf16", since = "1.8.0")]
1549impl<'a> Iterator for EncodeUtf16<'a> {
1550    type Item = u16;
1551
1552    #[inline]
1553    fn next(&mut self) -> Option<u16> {
1554        if self.extra != 0 {
1555            let tmp = self.extra;
1556            self.extra = 0;
1557            return Some(tmp);
1558        }
1559
1560        let mut buf = [0; 2];
1561        self.chars.next().map(|ch| {
1562            let n = ch.encode_utf16(&mut buf).len();
1563            if n == 2 {
1564                self.extra = buf[1];
1565            }
1566            buf[0]
1567        })
1568    }
1569
1570    #[inline]
1571    fn size_hint(&self) -> (usize, Option<usize>) {
1572        let len = self.chars.iter.len();
1573        // The highest bytes:code units ratio occurs for 3-byte sequences,
1574        // since a 4-byte sequence results in 2 code units. The lower bound
1575        // is therefore determined by assuming the remaining bytes contain as
1576        // many 3-byte sequences as possible. The highest bytes:code units
1577        // ratio is for 1-byte sequences, so use this for the upper bound.
1578        if self.extra == 0 {
1579            (len.div_ceil(3), Some(len))
1580        } else {
1581            // We're in the middle of a surrogate pair, so add the remaining
1582            // surrogate to the bounds.
1583            (len.div_ceil(3) + 1, Some(len + 1))
1584        }
1585    }
1586
1587    #[inline]
1588    fn count(self) -> usize {
1589        let extra = if self.extra == 0 { 0 } else { 1 };
1590        // Find UTF-8 non-continuation bytes and map:
1591        //
1592        // len_utf8() | len_utf16()
1593        // -----------|------------
1594        // 1          | 1
1595        // 2          | 1
1596        // 3          | 1
1597        // 4          | 2
1598        //
1599        // Because we never map to larger values the result is never larger than
1600        // `self.chars.as_str().len()` so the sum can never overflow
1601        self.chars.as_str().as_bytes().iter().fold(extra, |acc, &byte| {
1602            acc.wrapping_add({
1603                if byte < 0b1000_0000 {
1604                    // 0b0xxx_xxxx: ASCII-compatible U+0000 to U+007F
1605                    1
1606                } else if byte < 0b1100_0000 {
1607                    // 0b10xx_xxxx: UTF-8 continuation byte, skip
1608                    0
1609                } else if byte < 0b1111_0000 {
1610                    // 0b110x_xxxx: start of a 2-byte UTF-8 sequence for U+0080 to U+07FF
1611                    // 0b1110_xxxx: start of a 3-byte UTF-8 sequence for U+0800 to U+FFFF
1612                    1
1613                } else {
1614                    // 0b1111_0xxx: start of a 4-byte UTF-8 sequence for U+010000 to U+10FFFF
1615                    // This is exactly the range encoded as a surrogate pair in UTF-16
1616                    //
1617                    // 0b1111_1xxx: would fall here but never occurs in valid UTF-8
1618                    2
1619                }
1620            })
1621        })
1622    }
1623}
1624
1625#[stable(feature = "fused", since = "1.26.0")]
1626impl FusedIterator for EncodeUtf16<'_> {}
1627
1628/// The return type of [`str::escape_debug`].
1629#[stable(feature = "str_escape", since = "1.34.0")]
1630#[derive(Clone, Debug)]
1631pub struct EscapeDebug<'a> {
1632    pub(super) inner: FlatMap<Chars<'a>, char_mod::EscapeDebug, CharEscapeDebug>,
1633}
1634
1635/// The return type of [`str::escape_default`].
1636#[stable(feature = "str_escape", since = "1.34.0")]
1637#[derive(Clone, Debug)]
1638pub struct EscapeDefault<'a> {
1639    pub(super) inner: FlatMap<Chars<'a>, char_mod::EscapeDefault, CharEscapeDefault>,
1640}
1641
1642impl<'a> EscapeDefault<'a> {
1643    /// Disassembles the iterator into its internal state.
1644    /// Used by alloc for an optimized to_string impl.
1645    #[unstable(feature = "std_internals", issue = "none")]
1646    pub fn into_parts(
1647        self,
1648    ) -> (Option<impl Iterator<Item = char>>, Option<Chars<'a>>, Option<impl Iterator<Item = char>>)
1649    {
1650        self.inner.into_parts()
1651    }
1652}
1653
1654/// The return type of [`str::escape_unicode`].
1655#[stable(feature = "str_escape", since = "1.34.0")]
1656#[derive(Clone, Debug)]
1657pub struct EscapeUnicode<'a> {
1658    pub(super) inner: FlatMap<Chars<'a>, char_mod::EscapeUnicode, CharEscapeUnicode>,
1659}
1660
1661macro_rules! escape_types_impls {
1662    ($( $Name: ident ),+) => {$(
1663        #[stable(feature = "str_escape", since = "1.34.0")]
1664        impl<'a> fmt::Display for $Name<'a> {
1665            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1666                self.clone().try_for_each(|c| f.write_char(c))
1667            }
1668        }
1669
1670        #[stable(feature = "str_escape", since = "1.34.0")]
1671        impl<'a> Iterator for $Name<'a> {
1672            type Item = char;
1673
1674            #[inline]
1675            fn next(&mut self) -> Option<char> { self.inner.next() }
1676
1677            #[inline]
1678            fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1679
1680            #[inline]
1681            fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
1682                Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Output = Acc>
1683            {
1684                self.inner.try_fold(init, fold)
1685            }
1686
1687            #[inline]
1688            fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1689                where Fold: FnMut(Acc, Self::Item) -> Acc,
1690            {
1691                self.inner.fold(init, fold)
1692            }
1693        }
1694
1695        #[stable(feature = "str_escape", since = "1.34.0")]
1696        impl<'a> FusedIterator for $Name<'a> {}
1697    )+}
1698}
1699
1700escape_types_impls!(EscapeDebug, EscapeDefault, EscapeUnicode);