]> git.lizzy.rs Git - rust.git/blob - library/core/src/str/iter.rs
Rollup merge of #104163 - H4x5:once-repeat-with-debug, r=dtolnay
[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     unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> u8 {
302         // SAFETY: the caller must uphold the safety contract
303         // for `Iterator::__iterator_get_unchecked`.
304         unsafe { self.0.__iterator_get_unchecked(idx) }
305     }
306 }
307
308 #[stable(feature = "rust1", since = "1.0.0")]
309 impl DoubleEndedIterator for Bytes<'_> {
310     #[inline]
311     fn next_back(&mut self) -> Option<u8> {
312         self.0.next_back()
313     }
314
315     #[inline]
316     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
317         self.0.nth_back(n)
318     }
319
320     #[inline]
321     fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
322     where
323         P: FnMut(&Self::Item) -> bool,
324     {
325         self.0.rfind(predicate)
326     }
327 }
328
329 #[stable(feature = "rust1", since = "1.0.0")]
330 impl ExactSizeIterator for Bytes<'_> {
331     #[inline]
332     fn len(&self) -> usize {
333         self.0.len()
334     }
335
336     #[inline]
337     fn is_empty(&self) -> bool {
338         self.0.is_empty()
339     }
340 }
341
342 #[stable(feature = "fused", since = "1.26.0")]
343 impl FusedIterator for Bytes<'_> {}
344
345 #[unstable(feature = "trusted_len", issue = "37572")]
346 unsafe impl TrustedLen for Bytes<'_> {}
347
348 #[doc(hidden)]
349 #[unstable(feature = "trusted_random_access", issue = "none")]
350 unsafe impl TrustedRandomAccess for Bytes<'_> {}
351
352 #[doc(hidden)]
353 #[unstable(feature = "trusted_random_access", issue = "none")]
354 unsafe impl TrustedRandomAccessNoCoerce for Bytes<'_> {
355     const MAY_HAVE_SIDE_EFFECT: bool = false;
356 }
357
358 /// This macro generates a Clone impl for string pattern API
359 /// wrapper types of the form X<'a, P>
360 macro_rules! derive_pattern_clone {
361     (clone $t:ident with |$s:ident| $e:expr) => {
362         impl<'a, P> Clone for $t<'a, P>
363         where
364             P: Pattern<'a, Searcher: Clone>,
365         {
366             fn clone(&self) -> Self {
367                 let $s = self;
368                 $e
369             }
370         }
371     };
372 }
373
374 /// This macro generates two public iterator structs
375 /// wrapping a private internal one that makes use of the `Pattern` API.
376 ///
377 /// For all patterns `P: Pattern<'a>` the following items will be
378 /// generated (generics omitted):
379 ///
380 /// struct $forward_iterator($internal_iterator);
381 /// struct $reverse_iterator($internal_iterator);
382 ///
383 /// impl Iterator for $forward_iterator
384 /// { /* internal ends up calling Searcher::next_match() */ }
385 ///
386 /// impl DoubleEndedIterator for $forward_iterator
387 ///       where P::Searcher: DoubleEndedSearcher
388 /// { /* internal ends up calling Searcher::next_match_back() */ }
389 ///
390 /// impl Iterator for $reverse_iterator
391 ///       where P::Searcher: ReverseSearcher
392 /// { /* internal ends up calling Searcher::next_match_back() */ }
393 ///
394 /// impl DoubleEndedIterator for $reverse_iterator
395 ///       where P::Searcher: DoubleEndedSearcher
396 /// { /* internal ends up calling Searcher::next_match() */ }
397 ///
398 /// The internal one is defined outside the macro, and has almost the same
399 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
400 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
401 ///
402 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
403 /// `Pattern` might not return the same elements, so actually implementing
404 /// `DoubleEndedIterator` for it would be incorrect.
405 /// (See the docs in `str::pattern` for more details)
406 ///
407 /// However, the internal struct still represents a single ended iterator from
408 /// either end, and depending on pattern is also a valid double ended iterator,
409 /// so the two wrapper structs implement `Iterator`
410 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
411 /// to the complex impls seen above.
412 macro_rules! generate_pattern_iterators {
413     {
414         // Forward iterator
415         forward:
416             $(#[$forward_iterator_attribute:meta])*
417             struct $forward_iterator:ident;
418
419         // Reverse iterator
420         reverse:
421             $(#[$reverse_iterator_attribute:meta])*
422             struct $reverse_iterator:ident;
423
424         // Stability of all generated items
425         stability:
426             $(#[$common_stability_attribute:meta])*
427
428         // Internal almost-iterator that is being delegated to
429         internal:
430             $internal_iterator:ident yielding ($iterty:ty);
431
432         // Kind of delegation - either single ended or double ended
433         delegate $($t:tt)*
434     } => {
435         $(#[$forward_iterator_attribute])*
436         $(#[$common_stability_attribute])*
437         pub struct $forward_iterator<'a, P: Pattern<'a>>(pub(super) $internal_iterator<'a, P>);
438
439         $(#[$common_stability_attribute])*
440         impl<'a, P> fmt::Debug for $forward_iterator<'a, P>
441         where
442             P: Pattern<'a, Searcher: fmt::Debug>,
443         {
444             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445                 f.debug_tuple(stringify!($forward_iterator))
446                     .field(&self.0)
447                     .finish()
448             }
449         }
450
451         $(#[$common_stability_attribute])*
452         impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
453             type Item = $iterty;
454
455             #[inline]
456             fn next(&mut self) -> Option<$iterty> {
457                 self.0.next()
458             }
459         }
460
461         $(#[$common_stability_attribute])*
462         impl<'a, P> Clone for $forward_iterator<'a, P>
463         where
464             P: Pattern<'a, Searcher: Clone>,
465         {
466             fn clone(&self) -> Self {
467                 $forward_iterator(self.0.clone())
468             }
469         }
470
471         $(#[$reverse_iterator_attribute])*
472         $(#[$common_stability_attribute])*
473         pub struct $reverse_iterator<'a, P: Pattern<'a>>(pub(super) $internal_iterator<'a, P>);
474
475         $(#[$common_stability_attribute])*
476         impl<'a, P> fmt::Debug for $reverse_iterator<'a, P>
477         where
478             P: Pattern<'a, Searcher: fmt::Debug>,
479         {
480             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
481                 f.debug_tuple(stringify!($reverse_iterator))
482                     .field(&self.0)
483                     .finish()
484             }
485         }
486
487         $(#[$common_stability_attribute])*
488         impl<'a, P> Iterator for $reverse_iterator<'a, P>
489         where
490             P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
491         {
492             type Item = $iterty;
493
494             #[inline]
495             fn next(&mut self) -> Option<$iterty> {
496                 self.0.next_back()
497             }
498         }
499
500         $(#[$common_stability_attribute])*
501         impl<'a, P> Clone for $reverse_iterator<'a, P>
502         where
503             P: Pattern<'a, Searcher: Clone>,
504         {
505             fn clone(&self) -> Self {
506                 $reverse_iterator(self.0.clone())
507             }
508         }
509
510         #[stable(feature = "fused", since = "1.26.0")]
511         impl<'a, P: Pattern<'a>> FusedIterator for $forward_iterator<'a, P> {}
512
513         #[stable(feature = "fused", since = "1.26.0")]
514         impl<'a, P> FusedIterator for $reverse_iterator<'a, P>
515         where
516             P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
517         {}
518
519         generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
520                                                 $forward_iterator,
521                                                 $reverse_iterator, $iterty);
522     };
523     {
524         double ended; with $(#[$common_stability_attribute:meta])*,
525                            $forward_iterator:ident,
526                            $reverse_iterator:ident, $iterty:ty
527     } => {
528         $(#[$common_stability_attribute])*
529         impl<'a, P> DoubleEndedIterator for $forward_iterator<'a, P>
530         where
531             P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>,
532         {
533             #[inline]
534             fn next_back(&mut self) -> Option<$iterty> {
535                 self.0.next_back()
536             }
537         }
538
539         $(#[$common_stability_attribute])*
540         impl<'a, P> DoubleEndedIterator for $reverse_iterator<'a, P>
541         where
542             P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>,
543         {
544             #[inline]
545             fn next_back(&mut self) -> Option<$iterty> {
546                 self.0.next()
547             }
548         }
549     };
550     {
551         single ended; with $(#[$common_stability_attribute:meta])*,
552                            $forward_iterator:ident,
553                            $reverse_iterator:ident, $iterty:ty
554     } => {}
555 }
556
557 derive_pattern_clone! {
558     clone SplitInternal
559     with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
560 }
561
562 pub(super) struct SplitInternal<'a, P: Pattern<'a>> {
563     pub(super) start: usize,
564     pub(super) end: usize,
565     pub(super) matcher: P::Searcher,
566     pub(super) allow_trailing_empty: bool,
567     pub(super) finished: bool,
568 }
569
570 impl<'a, P> fmt::Debug for SplitInternal<'a, P>
571 where
572     P: Pattern<'a, Searcher: fmt::Debug>,
573 {
574     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
575         f.debug_struct("SplitInternal")
576             .field("start", &self.start)
577             .field("end", &self.end)
578             .field("matcher", &self.matcher)
579             .field("allow_trailing_empty", &self.allow_trailing_empty)
580             .field("finished", &self.finished)
581             .finish()
582     }
583 }
584
585 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
586     #[inline]
587     fn get_end(&mut self) -> Option<&'a str> {
588         if !self.finished {
589             self.finished = true;
590
591             if self.allow_trailing_empty || self.end - self.start > 0 {
592                 // SAFETY: `self.start` and `self.end` always lie on unicode boundaries.
593                 let string = unsafe { self.matcher.haystack().get_unchecked(self.start..self.end) };
594                 return Some(string);
595             }
596         }
597
598         None
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 remainder(&self) -> Option<&'a str> {
721         // `Self::get_end` doesn't change `self.start`
722         if self.finished {
723             return None;
724         }
725
726         // SAFETY: `self.start` and `self.end` always lie on unicode boundaries.
727         Some(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     /// If the iterator is empty, returns `None`.
753     ///
754     /// # Examples
755     ///
756     /// ```
757     /// #![feature(str_split_remainder)]
758     /// let mut split = "Mary had a little lamb".split(' ');
759     /// assert_eq!(split.remainder(), Some("Mary had a little lamb"));
760     /// split.next();
761     /// assert_eq!(split.remainder(), Some("had a little lamb"));
762     /// split.by_ref().for_each(drop);
763     /// assert_eq!(split.remainder(), None);
764     /// ```
765     #[inline]
766     #[unstable(feature = "str_split_remainder", issue = "77998")]
767     pub fn remainder(&self) -> Option<&'a str> {
768         self.0.remainder()
769     }
770 }
771
772 impl<'a, P: Pattern<'a>> RSplit<'a, P> {
773     /// Returns remainder of the split string.
774     ///
775     /// If the iterator is empty, returns `None`.
776     ///
777     /// # Examples
778     ///
779     /// ```
780     /// #![feature(str_split_remainder)]
781     /// let mut split = "Mary had a little lamb".rsplit(' ');
782     /// assert_eq!(split.remainder(), Some("Mary had a little lamb"));
783     /// split.next();
784     /// assert_eq!(split.remainder(), Some("Mary had a little"));
785     /// split.by_ref().for_each(drop);
786     /// assert_eq!(split.remainder(), None);
787     /// ```
788     #[inline]
789     #[unstable(feature = "str_split_remainder", issue = "77998")]
790     pub fn remainder(&self) -> Option<&'a str> {
791         self.0.remainder()
792     }
793 }
794
795 generate_pattern_iterators! {
796     forward:
797         /// Created with the method [`split_terminator`].
798         ///
799         /// [`split_terminator`]: str::split_terminator
800         struct SplitTerminator;
801     reverse:
802         /// Created with the method [`rsplit_terminator`].
803         ///
804         /// [`rsplit_terminator`]: str::rsplit_terminator
805         struct RSplitTerminator;
806     stability:
807         #[stable(feature = "rust1", since = "1.0.0")]
808     internal:
809         SplitInternal yielding (&'a str);
810     delegate double ended;
811 }
812
813 impl<'a, P: Pattern<'a>> SplitTerminator<'a, P> {
814     /// Returns remainder of the split string.
815     ///
816     /// If the iterator is empty, returns `None`.
817     ///
818     /// # Examples
819     ///
820     /// ```
821     /// #![feature(str_split_remainder)]
822     /// let mut split = "A..B..".split_terminator('.');
823     /// assert_eq!(split.remainder(), Some("A..B.."));
824     /// split.next();
825     /// assert_eq!(split.remainder(), Some(".B.."));
826     /// split.by_ref().for_each(drop);
827     /// assert_eq!(split.remainder(), None);
828     /// ```
829     #[inline]
830     #[unstable(feature = "str_split_remainder", issue = "77998")]
831     pub fn remainder(&self) -> Option<&'a str> {
832         self.0.remainder()
833     }
834 }
835
836 impl<'a, P: Pattern<'a>> RSplitTerminator<'a, P> {
837     /// Returns remainder of the split string.
838     ///
839     /// If the iterator is empty, returns `None`.
840     ///
841     /// # Examples
842     ///
843     /// ```
844     /// #![feature(str_split_remainder)]
845     /// let mut split = "A..B..".rsplit_terminator('.');
846     /// assert_eq!(split.remainder(), Some("A..B.."));
847     /// split.next();
848     /// assert_eq!(split.remainder(), Some("A..B"));
849     /// split.by_ref().for_each(drop);
850     /// assert_eq!(split.remainder(), None);
851     /// ```
852     #[inline]
853     #[unstable(feature = "str_split_remainder", issue = "77998")]
854     pub fn remainder(&self) -> Option<&'a str> {
855         self.0.remainder()
856     }
857 }
858
859 derive_pattern_clone! {
860     clone SplitNInternal
861     with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
862 }
863
864 pub(super) struct SplitNInternal<'a, P: Pattern<'a>> {
865     pub(super) iter: SplitInternal<'a, P>,
866     /// The number of splits remaining
867     pub(super) count: usize,
868 }
869
870 impl<'a, P> fmt::Debug for SplitNInternal<'a, P>
871 where
872     P: Pattern<'a, Searcher: fmt::Debug>,
873 {
874     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
875         f.debug_struct("SplitNInternal")
876             .field("iter", &self.iter)
877             .field("count", &self.count)
878             .finish()
879     }
880 }
881
882 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
883     #[inline]
884     fn next(&mut self) -> Option<&'a str> {
885         match self.count {
886             0 => None,
887             1 => {
888                 self.count = 0;
889                 self.iter.get_end()
890             }
891             _ => {
892                 self.count -= 1;
893                 self.iter.next()
894             }
895         }
896     }
897
898     #[inline]
899     fn next_back(&mut self) -> Option<&'a str>
900     where
901         P::Searcher: ReverseSearcher<'a>,
902     {
903         match self.count {
904             0 => None,
905             1 => {
906                 self.count = 0;
907                 self.iter.get_end()
908             }
909             _ => {
910                 self.count -= 1;
911                 self.iter.next_back()
912             }
913         }
914     }
915
916     #[inline]
917     fn remainder(&self) -> Option<&'a str> {
918         self.iter.remainder()
919     }
920 }
921
922 generate_pattern_iterators! {
923     forward:
924         /// Created with the method [`splitn`].
925         ///
926         /// [`splitn`]: str::splitn
927         struct SplitN;
928     reverse:
929         /// Created with the method [`rsplitn`].
930         ///
931         /// [`rsplitn`]: str::rsplitn
932         struct RSplitN;
933     stability:
934         #[stable(feature = "rust1", since = "1.0.0")]
935     internal:
936         SplitNInternal yielding (&'a str);
937     delegate single ended;
938 }
939
940 impl<'a, P: Pattern<'a>> SplitN<'a, P> {
941     /// Returns remainder of the split string.
942     ///
943     /// If the iterator is empty, returns `None`.
944     ///
945     /// # Examples
946     ///
947     /// ```
948     /// #![feature(str_split_remainder)]
949     /// let mut split = "Mary had a little lamb".splitn(3, ' ');
950     /// assert_eq!(split.remainder(), Some("Mary had a little lamb"));
951     /// split.next();
952     /// assert_eq!(split.remainder(), Some("had a little lamb"));
953     /// split.by_ref().for_each(drop);
954     /// assert_eq!(split.remainder(), None);
955     /// ```
956     #[inline]
957     #[unstable(feature = "str_split_remainder", issue = "77998")]
958     pub fn remainder(&self) -> Option<&'a str> {
959         self.0.remainder()
960     }
961 }
962
963 impl<'a, P: Pattern<'a>> RSplitN<'a, P> {
964     /// Returns remainder of the split string.
965     ///
966     /// If the iterator is empty, returns `None`.
967     ///
968     /// # Examples
969     ///
970     /// ```
971     /// #![feature(str_split_remainder)]
972     /// let mut split = "Mary had a little lamb".rsplitn(3, ' ');
973     /// assert_eq!(split.remainder(), Some("Mary had a little lamb"));
974     /// split.next();
975     /// assert_eq!(split.remainder(), Some("Mary had a little"));
976     /// split.by_ref().for_each(drop);
977     /// assert_eq!(split.remainder(), None);
978     /// ```
979     #[inline]
980     #[unstable(feature = "str_split_remainder", issue = "77998")]
981     pub fn remainder(&self) -> Option<&'a str> {
982         self.0.remainder()
983     }
984 }
985
986 derive_pattern_clone! {
987     clone MatchIndicesInternal
988     with |s| MatchIndicesInternal(s.0.clone())
989 }
990
991 pub(super) struct MatchIndicesInternal<'a, P: Pattern<'a>>(pub(super) P::Searcher);
992
993 impl<'a, P> fmt::Debug for MatchIndicesInternal<'a, P>
994 where
995     P: Pattern<'a, Searcher: fmt::Debug>,
996 {
997     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
998         f.debug_tuple("MatchIndicesInternal").field(&self.0).finish()
999     }
1000 }
1001
1002 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
1003     #[inline]
1004     fn next(&mut self) -> Option<(usize, &'a str)> {
1005         self.0
1006             .next_match()
1007             // SAFETY: `Searcher` guarantees that `start` and `end` lie on unicode boundaries.
1008             .map(|(start, end)| unsafe { (start, self.0.haystack().get_unchecked(start..end)) })
1009     }
1010
1011     #[inline]
1012     fn next_back(&mut self) -> Option<(usize, &'a str)>
1013     where
1014         P::Searcher: ReverseSearcher<'a>,
1015     {
1016         self.0
1017             .next_match_back()
1018             // SAFETY: `Searcher` guarantees that `start` and `end` lie on unicode boundaries.
1019             .map(|(start, end)| unsafe { (start, self.0.haystack().get_unchecked(start..end)) })
1020     }
1021 }
1022
1023 generate_pattern_iterators! {
1024     forward:
1025         /// Created with the method [`match_indices`].
1026         ///
1027         /// [`match_indices`]: str::match_indices
1028         struct MatchIndices;
1029     reverse:
1030         /// Created with the method [`rmatch_indices`].
1031         ///
1032         /// [`rmatch_indices`]: str::rmatch_indices
1033         struct RMatchIndices;
1034     stability:
1035         #[stable(feature = "str_match_indices", since = "1.5.0")]
1036     internal:
1037         MatchIndicesInternal yielding ((usize, &'a str));
1038     delegate double ended;
1039 }
1040
1041 derive_pattern_clone! {
1042     clone MatchesInternal
1043     with |s| MatchesInternal(s.0.clone())
1044 }
1045
1046 pub(super) struct MatchesInternal<'a, P: Pattern<'a>>(pub(super) P::Searcher);
1047
1048 impl<'a, P> fmt::Debug for MatchesInternal<'a, P>
1049 where
1050     P: Pattern<'a, Searcher: fmt::Debug>,
1051 {
1052     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1053         f.debug_tuple("MatchesInternal").field(&self.0).finish()
1054     }
1055 }
1056
1057 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
1058     #[inline]
1059     fn next(&mut self) -> Option<&'a str> {
1060         // SAFETY: `Searcher` guarantees that `start` and `end` lie on unicode boundaries.
1061         self.0.next_match().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     #[inline]
1068     fn next_back(&mut self) -> Option<&'a str>
1069     where
1070         P::Searcher: ReverseSearcher<'a>,
1071     {
1072         // SAFETY: `Searcher` guarantees that `start` and `end` lie on unicode boundaries.
1073         self.0.next_match_back().map(|(a, b)| unsafe {
1074             // Indices are known to be on utf8 boundaries
1075             self.0.haystack().get_unchecked(a..b)
1076         })
1077     }
1078 }
1079
1080 generate_pattern_iterators! {
1081     forward:
1082         /// Created with the method [`matches`].
1083         ///
1084         /// [`matches`]: str::matches
1085         struct Matches;
1086     reverse:
1087         /// Created with the method [`rmatches`].
1088         ///
1089         /// [`rmatches`]: str::rmatches
1090         struct RMatches;
1091     stability:
1092         #[stable(feature = "str_matches", since = "1.2.0")]
1093     internal:
1094         MatchesInternal yielding (&'a str);
1095     delegate double ended;
1096 }
1097
1098 /// An iterator over the lines of a string, as string slices.
1099 ///
1100 /// This struct is created with the [`lines`] method on [`str`].
1101 /// See its documentation for more.
1102 ///
1103 /// [`lines`]: str::lines
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 #[must_use = "iterators are lazy and do nothing unless consumed"]
1106 #[derive(Clone, Debug)]
1107 pub struct Lines<'a>(pub(super) Map<SplitTerminator<'a, char>, LinesAnyMap>);
1108
1109 #[stable(feature = "rust1", since = "1.0.0")]
1110 impl<'a> Iterator for Lines<'a> {
1111     type Item = &'a str;
1112
1113     #[inline]
1114     fn next(&mut self) -> Option<&'a str> {
1115         self.0.next()
1116     }
1117
1118     #[inline]
1119     fn size_hint(&self) -> (usize, Option<usize>) {
1120         self.0.size_hint()
1121     }
1122
1123     #[inline]
1124     fn last(mut self) -> Option<&'a str> {
1125         self.next_back()
1126     }
1127 }
1128
1129 #[stable(feature = "rust1", since = "1.0.0")]
1130 impl<'a> DoubleEndedIterator for Lines<'a> {
1131     #[inline]
1132     fn next_back(&mut self) -> Option<&'a str> {
1133         self.0.next_back()
1134     }
1135 }
1136
1137 #[stable(feature = "fused", since = "1.26.0")]
1138 impl FusedIterator for Lines<'_> {}
1139
1140 /// Created with the method [`lines_any`].
1141 ///
1142 /// [`lines_any`]: str::lines_any
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 #[deprecated(since = "1.4.0", note = "use lines()/Lines instead now")]
1145 #[must_use = "iterators are lazy and do nothing unless consumed"]
1146 #[derive(Clone, Debug)]
1147 #[allow(deprecated)]
1148 pub struct LinesAny<'a>(pub(super) Lines<'a>);
1149
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 #[allow(deprecated)]
1152 impl<'a> Iterator for LinesAny<'a> {
1153     type Item = &'a str;
1154
1155     #[inline]
1156     fn next(&mut self) -> Option<&'a str> {
1157         self.0.next()
1158     }
1159
1160     #[inline]
1161     fn size_hint(&self) -> (usize, Option<usize>) {
1162         self.0.size_hint()
1163     }
1164 }
1165
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 #[allow(deprecated)]
1168 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1169     #[inline]
1170     fn next_back(&mut self) -> Option<&'a str> {
1171         self.0.next_back()
1172     }
1173 }
1174
1175 #[stable(feature = "fused", since = "1.26.0")]
1176 #[allow(deprecated)]
1177 impl FusedIterator for LinesAny<'_> {}
1178
1179 /// An iterator over the non-whitespace substrings of a string,
1180 /// separated by any amount of whitespace.
1181 ///
1182 /// This struct is created by the [`split_whitespace`] method on [`str`].
1183 /// See its documentation for more.
1184 ///
1185 /// [`split_whitespace`]: str::split_whitespace
1186 #[stable(feature = "split_whitespace", since = "1.1.0")]
1187 #[derive(Clone, Debug)]
1188 pub struct SplitWhitespace<'a> {
1189     pub(super) inner: Filter<Split<'a, IsWhitespace>, IsNotEmpty>,
1190 }
1191
1192 /// An iterator over the non-ASCII-whitespace substrings of a string,
1193 /// separated by any amount of ASCII whitespace.
1194 ///
1195 /// This struct is created by the [`split_ascii_whitespace`] method on [`str`].
1196 /// See its documentation for more.
1197 ///
1198 /// [`split_ascii_whitespace`]: str::split_ascii_whitespace
1199 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
1200 #[derive(Clone, Debug)]
1201 pub struct SplitAsciiWhitespace<'a> {
1202     pub(super) inner:
1203         Map<Filter<SliceSplit<'a, u8, IsAsciiWhitespace>, BytesIsNotEmpty>, UnsafeBytesToStr>,
1204 }
1205
1206 /// An iterator over the substrings of a string,
1207 /// terminated by a substring matching to a predicate function
1208 /// Unlike `Split`, it contains the matched part as a terminator
1209 /// of the subslice.
1210 ///
1211 /// This struct is created by the [`split_inclusive`] method on [`str`].
1212 /// See its documentation for more.
1213 ///
1214 /// [`split_inclusive`]: str::split_inclusive
1215 #[stable(feature = "split_inclusive", since = "1.51.0")]
1216 pub struct SplitInclusive<'a, P: Pattern<'a>>(pub(super) SplitInternal<'a, P>);
1217
1218 #[stable(feature = "split_whitespace", since = "1.1.0")]
1219 impl<'a> Iterator for SplitWhitespace<'a> {
1220     type Item = &'a str;
1221
1222     #[inline]
1223     fn next(&mut self) -> Option<&'a str> {
1224         self.inner.next()
1225     }
1226
1227     #[inline]
1228     fn size_hint(&self) -> (usize, Option<usize>) {
1229         self.inner.size_hint()
1230     }
1231
1232     #[inline]
1233     fn last(mut self) -> Option<&'a str> {
1234         self.next_back()
1235     }
1236 }
1237
1238 #[stable(feature = "split_whitespace", since = "1.1.0")]
1239 impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
1240     #[inline]
1241     fn next_back(&mut self) -> Option<&'a str> {
1242         self.inner.next_back()
1243     }
1244 }
1245
1246 #[stable(feature = "fused", since = "1.26.0")]
1247 impl FusedIterator for SplitWhitespace<'_> {}
1248
1249 impl<'a> SplitWhitespace<'a> {
1250     /// Returns remainder of the split string
1251     ///
1252     /// # Examples
1253     ///
1254     /// ```
1255     /// #![feature(str_split_whitespace_remainder)]
1256     ///
1257     /// let mut split = "Mary had a little lamb".split_whitespace();
1258     /// assert_eq!(split.remainder(), Some("Mary had a little lamb"));
1259     ///
1260     /// split.next();
1261     /// assert_eq!(split.remainder(), Some("had a little lamb"));
1262     ///
1263     /// split.by_ref().for_each(drop);
1264     /// assert_eq!(split.remainder(), None);
1265     /// ```
1266     #[inline]
1267     #[must_use]
1268     #[unstable(feature = "str_split_whitespace_remainder", issue = "77998")]
1269     pub fn remainder(&self) -> Option<&'a str> {
1270         self.inner.iter.remainder()
1271     }
1272 }
1273
1274 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
1275 impl<'a> Iterator for SplitAsciiWhitespace<'a> {
1276     type Item = &'a str;
1277
1278     #[inline]
1279     fn next(&mut self) -> Option<&'a str> {
1280         self.inner.next()
1281     }
1282
1283     #[inline]
1284     fn size_hint(&self) -> (usize, Option<usize>) {
1285         self.inner.size_hint()
1286     }
1287
1288     #[inline]
1289     fn last(mut self) -> Option<&'a str> {
1290         self.next_back()
1291     }
1292 }
1293
1294 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
1295 impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> {
1296     #[inline]
1297     fn next_back(&mut self) -> Option<&'a str> {
1298         self.inner.next_back()
1299     }
1300 }
1301
1302 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
1303 impl FusedIterator for SplitAsciiWhitespace<'_> {}
1304
1305 impl<'a> SplitAsciiWhitespace<'a> {
1306     /// Returns remainder of the split string.
1307     ///
1308     /// If the iterator is empty, returns `None`.
1309     ///
1310     /// # Examples
1311     ///
1312     /// ```
1313     /// #![feature(str_split_whitespace_remainder)]
1314     ///
1315     /// let mut split = "Mary had a little lamb".split_ascii_whitespace();
1316     /// assert_eq!(split.remainder(), Some("Mary had a little lamb"));
1317     ///
1318     /// split.next();
1319     /// assert_eq!(split.remainder(), Some("had a little lamb"));
1320     ///
1321     /// split.by_ref().for_each(drop);
1322     /// assert_eq!(split.remainder(), None);
1323     /// ```
1324     #[inline]
1325     #[must_use]
1326     #[unstable(feature = "str_split_whitespace_remainder", issue = "77998")]
1327     pub fn remainder(&self) -> Option<&'a str> {
1328         if self.inner.iter.iter.finished {
1329             return None;
1330         }
1331
1332         // SAFETY: Slice is created from str.
1333         Some(unsafe { crate::str::from_utf8_unchecked(&self.inner.iter.iter.v) })
1334     }
1335 }
1336
1337 #[stable(feature = "split_inclusive", since = "1.51.0")]
1338 impl<'a, P: Pattern<'a>> Iterator for SplitInclusive<'a, P> {
1339     type Item = &'a str;
1340
1341     #[inline]
1342     fn next(&mut self) -> Option<&'a str> {
1343         self.0.next_inclusive()
1344     }
1345 }
1346
1347 #[stable(feature = "split_inclusive", since = "1.51.0")]
1348 impl<'a, P: Pattern<'a, Searcher: fmt::Debug>> fmt::Debug for SplitInclusive<'a, P> {
1349     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1350         f.debug_struct("SplitInclusive").field("0", &self.0).finish()
1351     }
1352 }
1353
1354 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1355 #[stable(feature = "split_inclusive", since = "1.51.0")]
1356 impl<'a, P: Pattern<'a, Searcher: Clone>> Clone for SplitInclusive<'a, P> {
1357     fn clone(&self) -> Self {
1358         SplitInclusive(self.0.clone())
1359     }
1360 }
1361
1362 #[stable(feature = "split_inclusive", since = "1.51.0")]
1363 impl<'a, P: Pattern<'a, Searcher: ReverseSearcher<'a>>> DoubleEndedIterator
1364     for SplitInclusive<'a, P>
1365 {
1366     #[inline]
1367     fn next_back(&mut self) -> Option<&'a str> {
1368         self.0.next_back_inclusive()
1369     }
1370 }
1371
1372 #[stable(feature = "split_inclusive", since = "1.51.0")]
1373 impl<'a, P: Pattern<'a>> FusedIterator for SplitInclusive<'a, P> {}
1374
1375 impl<'a, P: Pattern<'a>> SplitInclusive<'a, P> {
1376     /// Returns remainder of the split string.
1377     ///
1378     /// If the iterator is empty, returns `None`.
1379     ///
1380     /// # Examples
1381     ///
1382     /// ```
1383     /// #![feature(str_split_inclusive_remainder)]
1384     /// let mut split = "Mary had a little lamb".split_inclusive(' ');
1385     /// assert_eq!(split.remainder(), Some("Mary had a little lamb"));
1386     /// split.next();
1387     /// assert_eq!(split.remainder(), Some("had a little lamb"));
1388     /// split.by_ref().for_each(drop);
1389     /// assert_eq!(split.remainder(), None);
1390     /// ```
1391     #[inline]
1392     #[unstable(feature = "str_split_inclusive_remainder", issue = "77998")]
1393     pub fn remainder(&self) -> Option<&'a str> {
1394         self.0.remainder()
1395     }
1396 }
1397
1398 /// An iterator of [`u16`] over the string encoded as UTF-16.
1399 ///
1400 /// This struct is created by the [`encode_utf16`] method on [`str`].
1401 /// See its documentation for more.
1402 ///
1403 /// [`encode_utf16`]: str::encode_utf16
1404 #[derive(Clone)]
1405 #[stable(feature = "encode_utf16", since = "1.8.0")]
1406 pub struct EncodeUtf16<'a> {
1407     pub(super) chars: Chars<'a>,
1408     pub(super) extra: u16,
1409 }
1410
1411 #[stable(feature = "collection_debug", since = "1.17.0")]
1412 impl fmt::Debug for EncodeUtf16<'_> {
1413     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1414         f.debug_struct("EncodeUtf16").finish_non_exhaustive()
1415     }
1416 }
1417
1418 #[stable(feature = "encode_utf16", since = "1.8.0")]
1419 impl<'a> Iterator for EncodeUtf16<'a> {
1420     type Item = u16;
1421
1422     #[inline]
1423     fn next(&mut self) -> Option<u16> {
1424         if self.extra != 0 {
1425             let tmp = self.extra;
1426             self.extra = 0;
1427             return Some(tmp);
1428         }
1429
1430         let mut buf = [0; 2];
1431         self.chars.next().map(|ch| {
1432             let n = ch.encode_utf16(&mut buf).len();
1433             if n == 2 {
1434                 self.extra = buf[1];
1435             }
1436             buf[0]
1437         })
1438     }
1439
1440     #[inline]
1441     fn size_hint(&self) -> (usize, Option<usize>) {
1442         let (low, high) = self.chars.size_hint();
1443         // every char gets either one u16 or two u16,
1444         // so this iterator is between 1 or 2 times as
1445         // long as the underlying iterator.
1446         (low, high.and_then(|n| n.checked_mul(2)))
1447     }
1448 }
1449
1450 #[stable(feature = "fused", since = "1.26.0")]
1451 impl FusedIterator for EncodeUtf16<'_> {}
1452
1453 /// The return type of [`str::escape_debug`].
1454 #[stable(feature = "str_escape", since = "1.34.0")]
1455 #[derive(Clone, Debug)]
1456 pub struct EscapeDebug<'a> {
1457     pub(super) inner: Chain<
1458         Flatten<option::IntoIter<char::EscapeDebug>>,
1459         FlatMap<Chars<'a>, char::EscapeDebug, CharEscapeDebugContinue>,
1460     >,
1461 }
1462
1463 /// The return type of [`str::escape_default`].
1464 #[stable(feature = "str_escape", since = "1.34.0")]
1465 #[derive(Clone, Debug)]
1466 pub struct EscapeDefault<'a> {
1467     pub(super) inner: FlatMap<Chars<'a>, char::EscapeDefault, CharEscapeDefault>,
1468 }
1469
1470 /// The return type of [`str::escape_unicode`].
1471 #[stable(feature = "str_escape", since = "1.34.0")]
1472 #[derive(Clone, Debug)]
1473 pub struct EscapeUnicode<'a> {
1474     pub(super) inner: FlatMap<Chars<'a>, char::EscapeUnicode, CharEscapeUnicode>,
1475 }
1476
1477 macro_rules! escape_types_impls {
1478     ($( $Name: ident ),+) => {$(
1479         #[stable(feature = "str_escape", since = "1.34.0")]
1480         impl<'a> fmt::Display for $Name<'a> {
1481             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1482                 self.clone().try_for_each(|c| f.write_char(c))
1483             }
1484         }
1485
1486         #[stable(feature = "str_escape", since = "1.34.0")]
1487         impl<'a> Iterator for $Name<'a> {
1488             type Item = char;
1489
1490             #[inline]
1491             fn next(&mut self) -> Option<char> { self.inner.next() }
1492
1493             #[inline]
1494             fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1495
1496             #[inline]
1497             fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
1498                 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Output = Acc>
1499             {
1500                 self.inner.try_fold(init, fold)
1501             }
1502
1503             #[inline]
1504             fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1505                 where Fold: FnMut(Acc, Self::Item) -> Acc,
1506             {
1507                 self.inner.fold(init, fold)
1508             }
1509         }
1510
1511         #[stable(feature = "str_escape", since = "1.34.0")]
1512         impl<'a> FusedIterator for $Name<'a> {}
1513     )+}
1514 }
1515
1516 escape_types_impls!(EscapeDebug, EscapeDefault, EscapeUnicode);