]> git.lizzy.rs Git - rust.git/blob - src/liballoc/str.rs
1705c80d5f50c259dcbce8b60ad5ed8b72491615
[rust.git] / src / liballoc / str.rs
1 //! Unicode string slices.
2 //!
3 //! *[See also the `str` primitive type](../../std/primitive.str.html).*
4 //!
5 //! The `&str` type is one of the two main string types, the other being `String`.
6 //! Unlike its `String` counterpart, its contents are borrowed.
7 //!
8 //! # Basic Usage
9 //!
10 //! A basic string declaration of `&str` type:
11 //!
12 //! ```
13 //! let hello_world = "Hello, World!";
14 //! ```
15 //!
16 //! Here we have declared a string literal, also known as a string slice.
17 //! String literals have a static lifetime, which means the string `hello_world`
18 //! is guaranteed to be valid for the duration of the entire program.
19 //! We can explicitly specify `hello_world`'s lifetime as well:
20 //!
21 //! ```
22 //! let hello_world: &'static str = "Hello, world!";
23 //! ```
24
25 #![stable(feature = "rust1", since = "1.0.0")]
26
27 // Many of the usings in this module are only used in the test configuration.
28 // It's cleaner to just turn off the unused_imports warning than to fix them.
29 #![allow(unused_imports)]
30
31 use core::borrow::Borrow;
32 use core::fmt::{self, Write};
33 use core::char;
34 use core::iter::{Chain, Flatten, FlatMap};
35 use core::str::pattern::{Pattern, Searcher, ReverseSearcher, DoubleEndedSearcher};
36 use core::mem;
37 use core::ops::Try;
38 use core::option;
39 use core::ptr;
40 use core::iter::FusedIterator;
41 use core::unicode::conversions;
42
43 use crate::borrow::ToOwned;
44 use crate::boxed::Box;
45 use crate::slice::{SliceConcatExt, SliceIndex};
46 use crate::string::String;
47 use crate::vec::Vec;
48
49 #[stable(feature = "rust1", since = "1.0.0")]
50 pub use core::str::{FromStr, Utf8Error};
51 #[allow(deprecated)]
52 #[stable(feature = "rust1", since = "1.0.0")]
53 pub use core::str::{Lines, LinesAny};
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub use core::str::{Split, RSplit};
56 #[stable(feature = "rust1", since = "1.0.0")]
57 pub use core::str::{SplitN, RSplitN};
58 #[stable(feature = "rust1", since = "1.0.0")]
59 pub use core::str::{SplitTerminator, RSplitTerminator};
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub use core::str::{Matches, RMatches};
62 #[stable(feature = "rust1", since = "1.0.0")]
63 pub use core::str::{MatchIndices, RMatchIndices};
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub use core::str::{from_utf8, from_utf8_mut, Chars, CharIndices, Bytes};
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub use core::str::{from_utf8_unchecked, from_utf8_unchecked_mut, ParseBoolError};
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub use core::str::SplitWhitespace;
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub use core::str::pattern;
72 #[stable(feature = "encode_utf16", since = "1.8.0")]
73 pub use core::str::EncodeUtf16;
74 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
75 pub use core::str::SplitAsciiWhitespace;
76
77 #[unstable(feature = "slice_concat_ext",
78            reason = "trait should not have to exist",
79            issue = "27747")]
80 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
81     type Output = String;
82
83     fn concat(&self) -> String {
84         self.join("")
85     }
86
87     fn join(&self, sep: &str) -> String {
88         unsafe {
89             String::from_utf8_unchecked( join_generic_copy(self, sep.as_bytes()) )
90         }
91     }
92
93     fn connect(&self, sep: &str) -> String {
94         self.join(sep)
95     }
96 }
97
98 macro_rules! spezialize_for_lengths {
99     ($separator:expr, $target:expr, $iter:expr; $($num:expr),*) => {
100         let mut target = $target;
101         let iter = $iter;
102         let sep_bytes = $separator;
103         match $separator.len() {
104             $(
105                 // loops with hardcoded sizes run much faster
106                 // specialize the cases with small separator lengths
107                 $num => {
108                     for s in iter {
109                         copy_slice_and_advance!(target, sep_bytes);
110                         copy_slice_and_advance!(target, s.borrow().as_ref());
111                     }
112                 },
113             )*
114             _ => {
115                 // arbitrary non-zero size fallback
116                 for s in iter {
117                     copy_slice_and_advance!(target, sep_bytes);
118                     copy_slice_and_advance!(target, s.borrow().as_ref());
119                 }
120             }
121         }
122     };
123 }
124
125 macro_rules! copy_slice_and_advance {
126     ($target:expr, $bytes:expr) => {
127         let len = $bytes.len();
128         let (head, tail) = {$target}.split_at_mut(len);
129         head.copy_from_slice($bytes);
130         $target = tail;
131     }
132 }
133
134 // Optimized join implementation that works for both Vec<T> (T: Copy) and String's inner vec
135 // Currently (2018-05-13) there is a bug with type inference and specialization (see issue #36262)
136 // For this reason SliceConcatExt<T> is not specialized for T: Copy and SliceConcatExt<str> is the
137 // only user of this function. It is left in place for the time when that is fixed.
138 //
139 // the bounds for String-join are S: Borrow<str> and for Vec-join Borrow<[T]>
140 // [T] and str both impl AsRef<[T]> for some T
141 // => s.borrow().as_ref() and we always have slices
142 fn join_generic_copy<B, T, S>(slice: &[S], sep: &[T]) -> Vec<T>
143 where
144     T: Copy,
145     B: AsRef<[T]> + ?Sized,
146     S: Borrow<B>,
147 {
148     let sep_len = sep.len();
149     let mut iter = slice.iter();
150
151     // the first slice is the only one without a separator preceding it
152     let first = match iter.next() {
153         Some(first) => first,
154         None => return vec![],
155     };
156
157     // compute the exact total length of the joined Vec
158     // if the `len` calculation overflows, we'll panic
159     // we would have run out of memory anyway and the rest of the function requires
160     // the entire Vec pre-allocated for safety
161     let len =  sep_len.checked_mul(iter.len()).and_then(|n| {
162             slice.iter()
163                 .map(|s| s.borrow().as_ref().len())
164                 .try_fold(n, usize::checked_add)
165         }).expect("attempt to join into collection with len > usize::MAX");
166
167     // crucial for safety
168     let mut result = Vec::with_capacity(len);
169     assert!(result.capacity() >= len);
170
171     result.extend_from_slice(first.borrow().as_ref());
172
173     unsafe {
174         {
175             let pos = result.len();
176             let target = result.get_unchecked_mut(pos..len);
177
178             // copy separator and slices over without bounds checks
179             // generate loops with hardcoded offsets for small separators
180             // massive improvements possible (~ x2)
181             spezialize_for_lengths!(sep, target, iter; 0, 1, 2, 3, 4);
182         }
183         result.set_len(len);
184     }
185     result
186 }
187
188 #[stable(feature = "rust1", since = "1.0.0")]
189 impl Borrow<str> for String {
190     #[inline]
191     fn borrow(&self) -> &str {
192         &self[..]
193     }
194 }
195
196 #[stable(feature = "rust1", since = "1.0.0")]
197 impl ToOwned for str {
198     type Owned = String;
199     #[inline]
200     fn to_owned(&self) -> String {
201         unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
202     }
203
204     fn clone_into(&self, target: &mut String) {
205         let mut b = mem::replace(target, String::new()).into_bytes();
206         self.as_bytes().clone_into(&mut b);
207         *target = unsafe { String::from_utf8_unchecked(b) }
208     }
209 }
210
211 /// Methods for string slices.
212 #[lang = "str_alloc"]
213 #[cfg(not(test))]
214 impl str {
215     /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
216     ///
217     /// # Examples
218     ///
219     /// Basic usage:
220     ///
221     /// ```
222     /// let s = "this is a string";
223     /// let boxed_str = s.to_owned().into_boxed_str();
224     /// let boxed_bytes = boxed_str.into_boxed_bytes();
225     /// assert_eq!(*boxed_bytes, *s.as_bytes());
226     /// ```
227     #[stable(feature = "str_box_extras", since = "1.20.0")]
228     #[inline]
229     pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
230         self.into()
231     }
232
233     /// Replaces all matches of a pattern with another string.
234     ///
235     /// `replace` creates a new [`String`], and copies the data from this string slice into it.
236     /// While doing so, it attempts to find matches of a pattern. If it finds any, it
237     /// replaces them with the replacement string slice.
238     ///
239     /// [`String`]: string/struct.String.html
240     ///
241     /// # Examples
242     ///
243     /// Basic usage:
244     ///
245     /// ```
246     /// let s = "this is old";
247     ///
248     /// assert_eq!("this is new", s.replace("old", "new"));
249     /// ```
250     ///
251     /// When the pattern doesn't match:
252     ///
253     /// ```
254     /// let s = "this is old";
255     /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
256     /// ```
257     #[must_use = "this returns the replaced string as a new allocation, \
258                   without modifying the original"]
259     #[stable(feature = "rust1", since = "1.0.0")]
260     #[inline]
261     pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
262         let mut result = String::new();
263         let mut last_end = 0;
264         for (start, part) in self.match_indices(from) {
265             result.push_str(unsafe { self.get_unchecked(last_end..start) });
266             result.push_str(to);
267             last_end = start + part.len();
268         }
269         result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
270         result
271     }
272
273     /// Replaces first N matches of a pattern with another string.
274     ///
275     /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
276     /// While doing so, it attempts to find matches of a pattern. If it finds any, it
277     /// replaces them with the replacement string slice at most `count` times.
278     ///
279     /// [`String`]: string/struct.String.html
280     ///
281     /// # Examples
282     ///
283     /// Basic usage:
284     ///
285     /// ```
286     /// let s = "foo foo 123 foo";
287     /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
288     /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
289     /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
290     /// ```
291     ///
292     /// When the pattern doesn't match:
293     ///
294     /// ```
295     /// let s = "this is old";
296     /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
297     /// ```
298     #[must_use = "this returns the replaced string as a new allocation, \
299                   without modifying the original"]
300     #[stable(feature = "str_replacen", since = "1.16.0")]
301     pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
302         // Hope to reduce the times of re-allocation
303         let mut result = String::with_capacity(32);
304         let mut last_end = 0;
305         for (start, part) in self.match_indices(pat).take(count) {
306             result.push_str(unsafe { self.get_unchecked(last_end..start) });
307             result.push_str(to);
308             last_end = start + part.len();
309         }
310         result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
311         result
312     }
313
314     /// Returns the lowercase equivalent of this string slice, as a new [`String`].
315     ///
316     /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
317     /// `Lowercase`.
318     ///
319     /// Since some characters can expand into multiple characters when changing
320     /// the case, this function returns a [`String`] instead of modifying the
321     /// parameter in-place.
322     ///
323     /// [`String`]: string/struct.String.html
324     ///
325     /// # Examples
326     ///
327     /// Basic usage:
328     ///
329     /// ```
330     /// let s = "HELLO";
331     ///
332     /// assert_eq!("hello", s.to_lowercase());
333     /// ```
334     ///
335     /// A tricky example, with sigma:
336     ///
337     /// ```
338     /// let sigma = "Σ";
339     ///
340     /// assert_eq!("σ", sigma.to_lowercase());
341     ///
342     /// // but at the end of a word, it's ς, not σ:
343     /// let odysseus = "ὈΔΥΣΣΕΎΣ";
344     ///
345     /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
346     /// ```
347     ///
348     /// Languages without case are not changed:
349     ///
350     /// ```
351     /// let new_year = "农历新年";
352     ///
353     /// assert_eq!(new_year, new_year.to_lowercase());
354     /// ```
355     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
356     pub fn to_lowercase(&self) -> String {
357         let mut s = String::with_capacity(self.len());
358         for (i, c) in self[..].char_indices() {
359             if c == 'Σ' {
360                 // Σ maps to σ, except at the end of a word where it maps to ς.
361                 // This is the only conditional (contextual) but language-independent mapping
362                 // in `SpecialCasing.txt`,
363                 // so hard-code it rather than have a generic "condition" mechanism.
364                 // See https://github.com/rust-lang/rust/issues/26035
365                 map_uppercase_sigma(self, i, &mut s)
366             } else {
367                 match conversions::to_lower(c) {
368                     [a, '\0', _] => s.push(a),
369                     [a, b, '\0'] => {
370                         s.push(a);
371                         s.push(b);
372                     }
373                     [a, b, c] => {
374                         s.push(a);
375                         s.push(b);
376                         s.push(c);
377                     }
378                 }
379             }
380         }
381         return s;
382
383         fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
384             // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
385             // for the definition of `Final_Sigma`.
386             debug_assert!('Σ'.len_utf8() == 2);
387             let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
388                                 !case_ignoreable_then_cased(from[i + 2..].chars());
389             to.push_str(if is_word_final { "ς" } else { "σ" });
390         }
391
392         fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
393             use core::unicode::derived_property::{Cased, Case_Ignorable};
394             match iter.skip_while(|&c| Case_Ignorable(c)).next() {
395                 Some(c) => Cased(c),
396                 None => false,
397             }
398         }
399     }
400
401     /// Returns the uppercase equivalent of this string slice, as a new [`String`].
402     ///
403     /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
404     /// `Uppercase`.
405     ///
406     /// Since some characters can expand into multiple characters when changing
407     /// the case, this function returns a [`String`] instead of modifying the
408     /// parameter in-place.
409     ///
410     /// [`String`]: string/struct.String.html
411     ///
412     /// # Examples
413     ///
414     /// Basic usage:
415     ///
416     /// ```
417     /// let s = "hello";
418     ///
419     /// assert_eq!("HELLO", s.to_uppercase());
420     /// ```
421     ///
422     /// Scripts without case are not changed:
423     ///
424     /// ```
425     /// let new_year = "农历新年";
426     ///
427     /// assert_eq!(new_year, new_year.to_uppercase());
428     /// ```
429     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
430     pub fn to_uppercase(&self) -> String {
431         let mut s = String::with_capacity(self.len());
432         for c in self[..].chars() {
433             match conversions::to_upper(c) {
434                 [a, '\0', _] => s.push(a),
435                 [a, b, '\0'] => {
436                     s.push(a);
437                     s.push(b);
438                 }
439                 [a, b, c] => {
440                     s.push(a);
441                     s.push(b);
442                     s.push(c);
443                 }
444             }
445         }
446         return s;
447     }
448
449     /// Escapes each char in `s` with [`char::escape_debug`].
450     ///
451     /// Note: only extended grapheme codepoints that begin the string will be
452     /// escaped.
453     ///
454     /// [`char::escape_debug`]: primitive.char.html#method.escape_debug
455     #[unstable(feature = "str_escape",
456                reason = "return type may change to be an iterator",
457                issue = "27791")]
458     pub fn escape_debug(&self) -> EscapeDebug {
459         let mut chars = self.chars();
460         EscapeDebug {
461             inner: chars.next()
462                 .map(|first| first.escape_debug_ext(true))
463                 .into_iter()
464                 .flatten()
465                 .chain(chars.flat_map(CharEscapeDebugContinue))
466         }
467     }
468
469     /// Escapes each char in `s` with [`char::escape_default`].
470     ///
471     /// [`char::escape_default`]: primitive.char.html#method.escape_default
472     #[unstable(feature = "str_escape",
473                reason = "return type may change to be an iterator",
474                issue = "27791")]
475     pub fn escape_default(&self) -> EscapeDefault {
476         EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
477     }
478
479     /// Escapes each char in `s` with [`char::escape_unicode`].
480     ///
481     /// [`char::escape_unicode`]: primitive.char.html#method.escape_unicode
482     #[unstable(feature = "str_escape",
483                reason = "return type may change to be an iterator",
484                issue = "27791")]
485     pub fn escape_unicode(&self) -> EscapeUnicode {
486         EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
487     }
488
489     /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
490     ///
491     /// [`String`]: string/struct.String.html
492     /// [`Box<str>`]: boxed/struct.Box.html
493     ///
494     /// # Examples
495     ///
496     /// Basic usage:
497     ///
498     /// ```
499     /// let string = String::from("birthday gift");
500     /// let boxed_str = string.clone().into_boxed_str();
501     ///
502     /// assert_eq!(boxed_str.into_string(), string);
503     /// ```
504     #[stable(feature = "box_str", since = "1.4.0")]
505     #[inline]
506     pub fn into_string(self: Box<str>) -> String {
507         let slice = Box::<[u8]>::from(self);
508         unsafe { String::from_utf8_unchecked(slice.into_vec()) }
509     }
510
511     /// Creates a new [`String`] by repeating a string `n` times.
512     ///
513     /// # Panics
514     ///
515     /// This function will panic if the capacity would overflow.
516     ///
517     /// [`String`]: string/struct.String.html
518     ///
519     /// # Examples
520     ///
521     /// Basic usage:
522     ///
523     /// ```
524     /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
525     /// ```
526     ///
527     /// A panic upon overflow:
528     ///
529     /// ```should_panic
530     /// fn main() {
531     ///     // this will panic at runtime
532     ///     "0123456789abcdef".repeat(usize::max_value());
533     /// }
534     /// ```
535     #[stable(feature = "repeat_str", since = "1.16.0")]
536     pub fn repeat(&self, n: usize) -> String {
537         unsafe { String::from_utf8_unchecked(self.as_bytes().repeat(n)) }
538     }
539
540     /// Returns a copy of this string where each character is mapped to its
541     /// ASCII upper case equivalent.
542     ///
543     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
544     /// but non-ASCII letters are unchanged.
545     ///
546     /// To uppercase the value in-place, use [`make_ascii_uppercase`].
547     ///
548     /// To uppercase ASCII characters in addition to non-ASCII characters, use
549     /// [`to_uppercase`].
550     ///
551     /// # Examples
552     ///
553     /// ```
554     /// let s = "Grüße, Jürgen ❤";
555     ///
556     /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
557     /// ```
558     ///
559     /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
560     /// [`to_uppercase`]: #method.to_uppercase
561     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
562     #[inline]
563     pub fn to_ascii_uppercase(&self) -> String {
564         let mut bytes = self.as_bytes().to_vec();
565         bytes.make_ascii_uppercase();
566         // make_ascii_uppercase() preserves the UTF-8 invariant.
567         unsafe { String::from_utf8_unchecked(bytes) }
568     }
569
570     /// Returns a copy of this string where each character is mapped to its
571     /// ASCII lower case equivalent.
572     ///
573     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
574     /// but non-ASCII letters are unchanged.
575     ///
576     /// To lowercase the value in-place, use [`make_ascii_lowercase`].
577     ///
578     /// To lowercase ASCII characters in addition to non-ASCII characters, use
579     /// [`to_lowercase`].
580     ///
581     /// # Examples
582     ///
583     /// ```
584     /// let s = "Grüße, Jürgen ❤";
585     ///
586     /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
587     /// ```
588     ///
589     /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
590     /// [`to_lowercase`]: #method.to_lowercase
591     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
592     #[inline]
593     pub fn to_ascii_lowercase(&self) -> String {
594         let mut bytes = self.as_bytes().to_vec();
595         bytes.make_ascii_lowercase();
596         // make_ascii_lowercase() preserves the UTF-8 invariant.
597         unsafe { String::from_utf8_unchecked(bytes) }
598     }
599 }
600
601 /// Converts a boxed slice of bytes to a boxed string slice without checking
602 /// that the string contains valid UTF-8.
603 ///
604 /// # Examples
605 ///
606 /// Basic usage:
607 ///
608 /// ```
609 /// let smile_utf8 = Box::new([226, 152, 186]);
610 /// let smile = unsafe { std::str::from_boxed_utf8_unchecked(smile_utf8) };
611 ///
612 /// assert_eq!("☺", &*smile);
613 /// ```
614 #[stable(feature = "str_box_extras", since = "1.20.0")]
615 #[inline]
616 pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box<str> {
617     Box::from_raw(Box::into_raw(v) as *mut str)
618 }
619
620 impl_fn_for_zst! {
621     #[derive(Clone)]
622     struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
623         c.escape_debug_ext(false)
624     };
625
626     #[derive(Clone)]
627     struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
628         c.escape_unicode()
629     };
630     #[derive(Clone)]
631     struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
632         c.escape_default()
633     };
634 }
635
636 macro_rules! escape_types {
637     ($(
638         struct $Name: ident<'a> {
639             inner: $Inner: ty,
640         }
641     )+) => {$(
642         #[unstable(feature = "str_escape", issue = "27791")]
643         #[derive(Clone, Debug)]
644         pub struct $Name<'a> {
645             inner: $Inner,
646         }
647
648         #[unstable(feature = "str_escape", issue = "27791")]
649         impl<'a> fmt::Display for $Name<'a> {
650             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
651                 self.clone().try_for_each(|c| f.write_char(c))
652             }
653         }
654
655         #[unstable(feature = "str_escape", issue = "27791")]
656         impl<'a> Iterator for $Name<'a> {
657             type Item = char;
658
659             #[inline]
660             fn next(&mut self) -> Option<char> { self.inner.next() }
661
662             #[inline]
663             fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
664
665             #[inline]
666             fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
667                 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
668             {
669                 self.inner.try_fold(init, fold)
670             }
671
672             #[inline]
673             fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
674                 where Fold: FnMut(Acc, Self::Item) -> Acc,
675             {
676                 self.inner.fold(init, fold)
677             }
678         }
679
680         #[unstable(feature = "str_escape", issue = "27791")]
681         impl<'a> FusedIterator for $Name<'a> {}
682     )+}
683 }
684
685 escape_types! {
686     struct EscapeDebug<'a> {
687         inner: Chain<
688             Flatten<option::IntoIter<char::EscapeDebug>>,
689             FlatMap<Chars<'a>, char::EscapeDebug, CharEscapeDebugContinue>
690         >,
691     }
692     struct EscapeUnicode<'a> {
693         inner: FlatMap<Chars<'a>, char::EscapeUnicode, CharEscapeUnicode>,
694     }
695     struct EscapeDefault<'a> {
696         inner: FlatMap<Chars<'a>, char::EscapeDefault, CharEscapeDefault>,
697     }
698 }