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