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