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