]> git.lizzy.rs Git - rust.git/blob - src/liballoc/str.rs
Auto merge of #43903 - oli-obk:alignto, r=aturon
[rust.git] / src / liballoc / str.rs
1 // Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Unicode string slices.
12 //!
13 //! The `&str` type is one of the two main string types, the other being `String`.
14 //! Unlike its `String` counterpart, its contents are borrowed.
15 //!
16 //! # Basic Usage
17 //!
18 //! A basic string declaration of `&str` type:
19 //!
20 //! ```
21 //! let hello_world = "Hello, World!";
22 //! ```
23 //!
24 //! Here we have declared a string literal, also known as a string slice.
25 //! String literals have a static lifetime, which means the string `hello_world`
26 //! is guaranteed to be valid for the duration of the entire program.
27 //! We can explicitly specify `hello_world`'s lifetime as well:
28 //!
29 //! ```
30 //! let hello_world: &'static str = "Hello, world!";
31 //! ```
32 //!
33 //! *[See also the `str` primitive type](../../std/primitive.str.html).*
34
35 #![stable(feature = "rust1", since = "1.0.0")]
36
37 // Many of the usings in this module are only used in the test configuration.
38 // It's cleaner to just turn off the unused_imports warning than to fix them.
39 #![allow(unused_imports)]
40
41 use core::fmt;
42 use core::str as core_str;
43 use core::str::pattern::Pattern;
44 use core::str::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
45 use core::mem;
46 use core::iter::FusedIterator;
47 use std_unicode::str::{UnicodeStr, Utf16Encoder};
48
49 use vec_deque::VecDeque;
50 use borrow::{Borrow, ToOwned};
51 use string::String;
52 use std_unicode;
53 use vec::Vec;
54 use slice::{SliceConcatExt, SliceIndex};
55 use boxed::Box;
56
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub use core::str::{FromStr, Utf8Error};
59 #[allow(deprecated)]
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub use core::str::{Lines, LinesAny};
62 #[stable(feature = "rust1", since = "1.0.0")]
63 pub use core::str::{Split, RSplit};
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub use core::str::{SplitN, RSplitN};
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub use core::str::{SplitTerminator, RSplitTerminator};
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub use core::str::{Matches, RMatches};
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub use core::str::{MatchIndices, RMatchIndices};
72 #[stable(feature = "rust1", since = "1.0.0")]
73 pub use core::str::{from_utf8, from_utf8_mut, Chars, CharIndices, Bytes};
74 #[stable(feature = "rust1", since = "1.0.0")]
75 pub use core::str::{from_utf8_unchecked, from_utf8_unchecked_mut, ParseBoolError};
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub use std_unicode::str::SplitWhitespace;
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub use core::str::pattern;
80
81
82 #[unstable(feature = "slice_concat_ext",
83            reason = "trait should not have to exist",
84            issue = "27747")]
85 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
86     type Output = String;
87
88     fn concat(&self) -> String {
89         if self.is_empty() {
90             return String::new();
91         }
92
93         // `len` calculation may overflow but push_str will check boundaries
94         let len = self.iter().map(|s| s.borrow().len()).sum();
95         let mut result = String::with_capacity(len);
96
97         for s in self {
98             result.push_str(s.borrow())
99         }
100
101         result
102     }
103
104     fn join(&self, sep: &str) -> String {
105         if self.is_empty() {
106             return String::new();
107         }
108
109         // concat is faster
110         if sep.is_empty() {
111             return self.concat();
112         }
113
114         // this is wrong without the guarantee that `self` is non-empty
115         // `len` calculation may overflow but push_str but will check boundaries
116         let len = sep.len() * (self.len() - 1) +
117                   self.iter().map(|s| s.borrow().len()).sum::<usize>();
118         let mut result = String::with_capacity(len);
119         let mut first = true;
120
121         for s in self {
122             if first {
123                 first = false;
124             } else {
125                 result.push_str(sep);
126             }
127             result.push_str(s.borrow());
128         }
129         result
130     }
131
132     fn connect(&self, sep: &str) -> String {
133         self.join(sep)
134     }
135 }
136
137 /// An iterator of [`u16`] over the string encoded as UTF-16.
138 ///
139 /// [`u16`]: ../../std/primitive.u16.html
140 ///
141 /// This struct is created by the [`encode_utf16`] method on [`str`].
142 /// See its documentation for more.
143 ///
144 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
145 /// [`str`]: ../../std/primitive.str.html
146 #[derive(Clone)]
147 #[stable(feature = "encode_utf16", since = "1.8.0")]
148 pub struct EncodeUtf16<'a> {
149     encoder: Utf16Encoder<Chars<'a>>,
150 }
151
152 #[stable(feature = "collection_debug", since = "1.17.0")]
153 impl<'a> fmt::Debug for EncodeUtf16<'a> {
154     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
155         f.pad("EncodeUtf16 { .. }")
156     }
157 }
158
159 #[stable(feature = "encode_utf16", since = "1.8.0")]
160 impl<'a> Iterator for EncodeUtf16<'a> {
161     type Item = u16;
162
163     #[inline]
164     fn next(&mut self) -> Option<u16> {
165         self.encoder.next()
166     }
167
168     #[inline]
169     fn size_hint(&self) -> (usize, Option<usize>) {
170         self.encoder.size_hint()
171     }
172 }
173
174 #[unstable(feature = "fused", issue = "35602")]
175 impl<'a> FusedIterator for EncodeUtf16<'a> {}
176
177 #[stable(feature = "rust1", since = "1.0.0")]
178 impl Borrow<str> for String {
179     #[inline]
180     fn borrow(&self) -> &str {
181         &self[..]
182     }
183 }
184
185 #[stable(feature = "rust1", since = "1.0.0")]
186 impl ToOwned for str {
187     type Owned = String;
188     fn to_owned(&self) -> String {
189         unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
190     }
191
192     fn clone_into(&self, target: &mut String) {
193         let mut b = mem::replace(target, String::new()).into_bytes();
194         self.as_bytes().clone_into(&mut b);
195         *target = unsafe { String::from_utf8_unchecked(b) }
196     }
197 }
198
199 /// Methods for string slices.
200 #[lang = "str"]
201 #[cfg(not(test))]
202 impl str {
203     /// Returns the length of `self`.
204     ///
205     /// This length is in bytes, not [`char`]s or graphemes. In other words,
206     /// it may not be what a human considers the length of the string.
207     ///
208     /// [`char`]: primitive.char.html
209     ///
210     /// # Examples
211     ///
212     /// Basic usage:
213     ///
214     /// ```
215     /// let len = "foo".len();
216     /// assert_eq!(3, len);
217     ///
218     /// let len = "ƒoo".len(); // fancy f!
219     /// assert_eq!(4, len);
220     /// ```
221     #[stable(feature = "rust1", since = "1.0.0")]
222     #[inline]
223     pub fn len(&self) -> usize {
224         core_str::StrExt::len(self)
225     }
226
227     /// Returns `true` if `self` has a length of zero bytes.
228     ///
229     /// # Examples
230     ///
231     /// Basic usage:
232     ///
233     /// ```
234     /// let s = "";
235     /// assert!(s.is_empty());
236     ///
237     /// let s = "not empty";
238     /// assert!(!s.is_empty());
239     /// ```
240     #[inline]
241     #[stable(feature = "rust1", since = "1.0.0")]
242     pub fn is_empty(&self) -> bool {
243         core_str::StrExt::is_empty(self)
244     }
245
246     /// Checks that `index`-th byte lies at the start and/or end of a
247     /// UTF-8 code point sequence.
248     ///
249     /// The start and end of the string (when `index == self.len()`) are
250     /// considered to be
251     /// boundaries.
252     ///
253     /// Returns `false` if `index` is greater than `self.len()`.
254     ///
255     /// # Examples
256     ///
257     /// ```
258     /// let s = "Löwe 老虎 Léopard";
259     /// assert!(s.is_char_boundary(0));
260     /// // start of `老`
261     /// assert!(s.is_char_boundary(6));
262     /// assert!(s.is_char_boundary(s.len()));
263     ///
264     /// // second byte of `ö`
265     /// assert!(!s.is_char_boundary(2));
266     ///
267     /// // third byte of `老`
268     /// assert!(!s.is_char_boundary(8));
269     /// ```
270     #[stable(feature = "is_char_boundary", since = "1.9.0")]
271     #[inline]
272     pub fn is_char_boundary(&self, index: usize) -> bool {
273         core_str::StrExt::is_char_boundary(self, index)
274     }
275
276     /// Converts a string slice to a byte slice. To convert the byte slice back
277     /// into a string slice, use the [`str::from_utf8`] function.
278     ///
279     /// [`str::from_utf8`]: ./str/fn.from_utf8.html
280     ///
281     /// # Examples
282     ///
283     /// Basic usage:
284     ///
285     /// ```
286     /// let bytes = "bors".as_bytes();
287     /// assert_eq!(b"bors", bytes);
288     /// ```
289     #[stable(feature = "rust1", since = "1.0.0")]
290     #[inline(always)]
291     pub fn as_bytes(&self) -> &[u8] {
292         core_str::StrExt::as_bytes(self)
293     }
294
295     /// Converts a mutable string slice to a mutable byte slice. To convert the
296     /// mutable byte slice back into a mutable string slice, use the
297     /// [`str::from_utf8_mut`] function.
298     ///
299     /// [`str::from_utf8_mut`]: ./str/fn.from_utf8_mut.html
300     #[stable(feature = "str_mut_extras", since = "1.20.0")]
301     #[inline(always)]
302     pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
303         core_str::StrExt::as_bytes_mut(self)
304     }
305
306     /// Converts a string slice to a raw pointer.
307     ///
308     /// As string slices are a slice of bytes, the raw pointer points to a
309     /// [`u8`]. This pointer will be pointing to the first byte of the string
310     /// slice.
311     ///
312     /// [`u8`]: primitive.u8.html
313     ///
314     /// # Examples
315     ///
316     /// Basic usage:
317     ///
318     /// ```
319     /// let s = "Hello";
320     /// let ptr = s.as_ptr();
321     /// ```
322     #[stable(feature = "rust1", since = "1.0.0")]
323     #[inline]
324     pub fn as_ptr(&self) -> *const u8 {
325         core_str::StrExt::as_ptr(self)
326     }
327
328     /// Returns a subslice of `str`.
329     ///
330     /// This is the non-panicking alternative to indexing the `str`. Returns
331     /// [`None`] whenever equivalent indexing operation would panic.
332     ///
333     /// [`None`]: option/enum.Option.html#variant.None
334     ///
335     /// # Examples
336     ///
337     /// ```
338     /// let mut v = String::from("🗻∈🌏");
339     ///
340     /// assert_eq!(Some("🗻"), v.get(0..4));
341     ///
342     /// // indices not on UTF-8 sequence boundaries
343     /// assert!(v.get_mut(1..).is_none());
344     /// assert!(v.get_mut(..8).is_none());
345     ///
346     /// // out of bounds
347     /// assert!(v.get_mut(..42).is_none());
348     /// ```
349     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
350     #[inline]
351     pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
352         core_str::StrExt::get(self, i)
353     }
354
355     /// Returns a mutable subslice of `str`.
356     ///
357     /// This is the non-panicking alternative to indexing the `str`. Returns
358     /// [`None`] whenever equivalent indexing operation would panic.
359     ///
360     /// [`None`]: option/enum.Option.html#variant.None
361     ///
362     /// # Examples
363     ///
364     /// ```
365     /// let mut v = String::from("🗻∈🌏");
366     ///
367     /// assert_eq!(Some("🗻"), v.get_mut(0..4).map(|v| &*v));
368     ///
369     /// // indices not on UTF-8 sequence boundaries
370     /// assert!(v.get_mut(1..).is_none());
371     /// assert!(v.get_mut(..8).is_none());
372     ///
373     /// // out of bounds
374     /// assert!(v.get_mut(..42).is_none());
375     /// ```
376     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
377     #[inline]
378     pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
379         core_str::StrExt::get_mut(self, i)
380     }
381
382     /// Returns a unchecked subslice of `str`.
383     ///
384     /// This is the unchecked alternative to indexing the `str`.
385     ///
386     /// # Safety
387     ///
388     /// Callers of this function are responsible that these preconditions are
389     /// satisfied:
390     ///
391     /// * The starting index must come before the ending index;
392     /// * Indexes must be within bounds of the original slice;
393     /// * Indexes must lie on UTF-8 sequence boundaries.
394     ///
395     /// Failing that, the returned string slice may reference invalid memory or
396     /// violate the invariants communicated by the `str` type.
397     ///
398     /// # Examples
399     ///
400     /// ```
401     /// let v = "🗻∈🌏";
402     /// unsafe {
403     ///     assert_eq!("🗻", v.get_unchecked(0..4));
404     ///     assert_eq!("∈", v.get_unchecked(4..7));
405     ///     assert_eq!("🌏", v.get_unchecked(7..11));
406     /// }
407     /// ```
408     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
409     #[inline]
410     pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
411         core_str::StrExt::get_unchecked(self, i)
412     }
413
414     /// Returns a mutable, unchecked subslice of `str`.
415     ///
416     /// This is the unchecked alternative to indexing the `str`.
417     ///
418     /// # Safety
419     ///
420     /// Callers of this function are responsible that these preconditions are
421     /// satisfied:
422     ///
423     /// * The starting index must come before the ending index;
424     /// * Indexes must be within bounds of the original slice;
425     /// * Indexes must lie on UTF-8 sequence boundaries.
426     ///
427     /// Failing that, the returned string slice may reference invalid memory or
428     /// violate the invariants communicated by the `str` type.
429     ///
430     /// # Examples
431     ///
432     /// ```
433     /// let mut v = String::from("🗻∈🌏");
434     /// unsafe {
435     ///     assert_eq!("🗻", v.get_unchecked_mut(0..4));
436     ///     assert_eq!("∈", v.get_unchecked_mut(4..7));
437     ///     assert_eq!("🌏", v.get_unchecked_mut(7..11));
438     /// }
439     /// ```
440     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
441     #[inline]
442     pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
443         core_str::StrExt::get_unchecked_mut(self, i)
444     }
445
446     /// Creates a string slice from another string slice, bypassing safety
447     /// checks.
448     ///
449     /// This is generally not recommended, use with caution! For a safe
450     /// alternative see [`str`] and [`Index`].
451     ///
452     /// [`str`]: primitive.str.html
453     /// [`Index`]: ops/trait.Index.html
454     ///
455     /// This new slice goes from `begin` to `end`, including `begin` but
456     /// excluding `end`.
457     ///
458     /// To get a mutable string slice instead, see the
459     /// [`slice_mut_unchecked`] method.
460     ///
461     /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
462     ///
463     /// # Safety
464     ///
465     /// Callers of this function are responsible that three preconditions are
466     /// satisfied:
467     ///
468     /// * `begin` must come before `end`.
469     /// * `begin` and `end` must be byte positions within the string slice.
470     /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
471     ///
472     /// # Examples
473     ///
474     /// Basic usage:
475     ///
476     /// ```
477     /// let s = "Löwe 老虎 Léopard";
478     ///
479     /// unsafe {
480     ///     assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
481     /// }
482     ///
483     /// let s = "Hello, world!";
484     ///
485     /// unsafe {
486     ///     assert_eq!("world", s.slice_unchecked(7, 12));
487     /// }
488     /// ```
489     #[stable(feature = "rust1", since = "1.0.0")]
490     #[inline]
491     pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
492         core_str::StrExt::slice_unchecked(self, begin, end)
493     }
494
495     /// Creates a string slice from another string slice, bypassing safety
496     /// checks.
497     /// This is generally not recommended, use with caution! For a safe
498     /// alternative see [`str`] and [`IndexMut`].
499     ///
500     /// [`str`]: primitive.str.html
501     /// [`IndexMut`]: ops/trait.IndexMut.html
502     ///
503     /// This new slice goes from `begin` to `end`, including `begin` but
504     /// excluding `end`.
505     ///
506     /// To get an immutable string slice instead, see the
507     /// [`slice_unchecked`] method.
508     ///
509     /// [`slice_unchecked`]: #method.slice_unchecked
510     ///
511     /// # Safety
512     ///
513     /// Callers of this function are responsible that three preconditions are
514     /// satisfied:
515     ///
516     /// * `begin` must come before `end`.
517     /// * `begin` and `end` must be byte positions within the string slice.
518     /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
519     #[stable(feature = "str_slice_mut", since = "1.5.0")]
520     #[inline]
521     pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
522         core_str::StrExt::slice_mut_unchecked(self, begin, end)
523     }
524
525     /// Divide one string slice into two at an index.
526     ///
527     /// The argument, `mid`, should be a byte offset from the start of the
528     /// string. It must also be on the boundary of a UTF-8 code point.
529     ///
530     /// The two slices returned go from the start of the string slice to `mid`,
531     /// and from `mid` to the end of the string slice.
532     ///
533     /// To get mutable string slices instead, see the [`split_at_mut`]
534     /// method.
535     ///
536     /// [`split_at_mut`]: #method.split_at_mut
537     ///
538     /// # Panics
539     ///
540     /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
541     /// beyond the last code point of the string slice.
542     ///
543     /// # Examples
544     ///
545     /// Basic usage:
546     ///
547     /// ```
548     /// let s = "Per Martin-Löf";
549     ///
550     /// let (first, last) = s.split_at(3);
551     ///
552     /// assert_eq!("Per", first);
553     /// assert_eq!(" Martin-Löf", last);
554     /// ```
555     #[inline]
556     #[stable(feature = "str_split_at", since = "1.4.0")]
557     pub fn split_at(&self, mid: usize) -> (&str, &str) {
558         core_str::StrExt::split_at(self, mid)
559     }
560
561     /// Divide one mutable string slice into two at an index.
562     ///
563     /// The argument, `mid`, should be a byte offset from the start of the
564     /// string. It must also be on the boundary of a UTF-8 code point.
565     ///
566     /// The two slices returned go from the start of the string slice to `mid`,
567     /// and from `mid` to the end of the string slice.
568     ///
569     /// To get immutable string slices instead, see the [`split_at`] method.
570     ///
571     /// [`split_at`]: #method.split_at
572     ///
573     /// # Panics
574     ///
575     /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
576     /// beyond the last code point of the string slice.
577     ///
578     /// # Examples
579     ///
580     /// Basic usage:
581     ///
582     /// ```
583     /// use std::ascii::AsciiExt;
584     ///
585     /// let mut s = "Per Martin-Löf".to_string();
586     /// {
587     ///     let (first, last) = s.split_at_mut(3);
588     ///     first.make_ascii_uppercase();
589     ///     assert_eq!("PER", first);
590     ///     assert_eq!(" Martin-Löf", last);
591     /// }
592     /// assert_eq!("PER Martin-Löf", s);
593     /// ```
594     #[inline]
595     #[stable(feature = "str_split_at", since = "1.4.0")]
596     pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
597         core_str::StrExt::split_at_mut(self, mid)
598     }
599
600     /// Returns an iterator over the [`char`]s of a string slice.
601     ///
602     /// As a string slice consists of valid UTF-8, we can iterate through a
603     /// string slice by [`char`]. This method returns such an iterator.
604     ///
605     /// It's important to remember that [`char`] represents a Unicode Scalar
606     /// Value, and may not match your idea of what a 'character' is. Iteration
607     /// over grapheme clusters may be what you actually want.
608     ///
609     /// [`char`]: primitive.char.html
610     ///
611     /// # Examples
612     ///
613     /// Basic usage:
614     ///
615     /// ```
616     /// let word = "goodbye";
617     ///
618     /// let count = word.chars().count();
619     /// assert_eq!(7, count);
620     ///
621     /// let mut chars = word.chars();
622     ///
623     /// assert_eq!(Some('g'), chars.next());
624     /// assert_eq!(Some('o'), chars.next());
625     /// assert_eq!(Some('o'), chars.next());
626     /// assert_eq!(Some('d'), chars.next());
627     /// assert_eq!(Some('b'), chars.next());
628     /// assert_eq!(Some('y'), chars.next());
629     /// assert_eq!(Some('e'), chars.next());
630     ///
631     /// assert_eq!(None, chars.next());
632     /// ```
633     ///
634     /// Remember, [`char`]s may not match your human intuition about characters:
635     ///
636     /// ```
637     /// let y = "y̆";
638     ///
639     /// let mut chars = y.chars();
640     ///
641     /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
642     /// assert_eq!(Some('\u{0306}'), chars.next());
643     ///
644     /// assert_eq!(None, chars.next());
645     /// ```
646     #[stable(feature = "rust1", since = "1.0.0")]
647     #[inline]
648     pub fn chars(&self) -> Chars {
649         core_str::StrExt::chars(self)
650     }
651     /// Returns an iterator over the [`char`]s of a string slice, and their
652     /// positions.
653     ///
654     /// As a string slice consists of valid UTF-8, we can iterate through a
655     /// string slice by [`char`]. This method returns an iterator of both
656     /// these [`char`]s, as well as their byte positions.
657     ///
658     /// The iterator yields tuples. The position is first, the [`char`] is
659     /// second.
660     ///
661     /// [`char`]: primitive.char.html
662     ///
663     /// # Examples
664     ///
665     /// Basic usage:
666     ///
667     /// ```
668     /// let word = "goodbye";
669     ///
670     /// let count = word.char_indices().count();
671     /// assert_eq!(7, count);
672     ///
673     /// let mut char_indices = word.char_indices();
674     ///
675     /// assert_eq!(Some((0, 'g')), char_indices.next());
676     /// assert_eq!(Some((1, 'o')), char_indices.next());
677     /// assert_eq!(Some((2, 'o')), char_indices.next());
678     /// assert_eq!(Some((3, 'd')), char_indices.next());
679     /// assert_eq!(Some((4, 'b')), char_indices.next());
680     /// assert_eq!(Some((5, 'y')), char_indices.next());
681     /// assert_eq!(Some((6, 'e')), char_indices.next());
682     ///
683     /// assert_eq!(None, char_indices.next());
684     /// ```
685     ///
686     /// Remember, [`char`]s may not match your human intuition about characters:
687     ///
688     /// ```
689     /// let y = "y̆";
690     ///
691     /// let mut char_indices = y.char_indices();
692     ///
693     /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
694     /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
695     ///
696     /// assert_eq!(None, char_indices.next());
697     /// ```
698     #[stable(feature = "rust1", since = "1.0.0")]
699     #[inline]
700     pub fn char_indices(&self) -> CharIndices {
701         core_str::StrExt::char_indices(self)
702     }
703
704     /// An iterator over the bytes of a string slice.
705     ///
706     /// As a string slice consists of a sequence of bytes, we can iterate
707     /// through a string slice by byte. This method returns such an iterator.
708     ///
709     /// # Examples
710     ///
711     /// Basic usage:
712     ///
713     /// ```
714     /// let mut bytes = "bors".bytes();
715     ///
716     /// assert_eq!(Some(b'b'), bytes.next());
717     /// assert_eq!(Some(b'o'), bytes.next());
718     /// assert_eq!(Some(b'r'), bytes.next());
719     /// assert_eq!(Some(b's'), bytes.next());
720     ///
721     /// assert_eq!(None, bytes.next());
722     /// ```
723     #[stable(feature = "rust1", since = "1.0.0")]
724     #[inline]
725     pub fn bytes(&self) -> Bytes {
726         core_str::StrExt::bytes(self)
727     }
728
729     /// Split a string slice by whitespace.
730     ///
731     /// The iterator returned will return string slices that are sub-slices of
732     /// the original string slice, separated by any amount of whitespace.
733     ///
734     /// 'Whitespace' is defined according to the terms of the Unicode Derived
735     /// Core Property `White_Space`.
736     ///
737     /// # Examples
738     ///
739     /// Basic usage:
740     ///
741     /// ```
742     /// let mut iter = "A few words".split_whitespace();
743     ///
744     /// assert_eq!(Some("A"), iter.next());
745     /// assert_eq!(Some("few"), iter.next());
746     /// assert_eq!(Some("words"), iter.next());
747     ///
748     /// assert_eq!(None, iter.next());
749     /// ```
750     ///
751     /// All kinds of whitespace are considered:
752     ///
753     /// ```
754     /// let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
755     /// assert_eq!(Some("Mary"), iter.next());
756     /// assert_eq!(Some("had"), iter.next());
757     /// assert_eq!(Some("a"), iter.next());
758     /// assert_eq!(Some("little"), iter.next());
759     /// assert_eq!(Some("lamb"), iter.next());
760     ///
761     /// assert_eq!(None, iter.next());
762     /// ```
763     #[stable(feature = "split_whitespace", since = "1.1.0")]
764     #[inline]
765     pub fn split_whitespace(&self) -> SplitWhitespace {
766         UnicodeStr::split_whitespace(self)
767     }
768
769     /// An iterator over the lines of a string, as string slices.
770     ///
771     /// Lines are ended with either a newline (`\n`) or a carriage return with
772     /// a line feed (`\r\n`).
773     ///
774     /// The final line ending is optional.
775     ///
776     /// # Examples
777     ///
778     /// Basic usage:
779     ///
780     /// ```
781     /// let text = "foo\r\nbar\n\nbaz\n";
782     /// let mut lines = text.lines();
783     ///
784     /// assert_eq!(Some("foo"), lines.next());
785     /// assert_eq!(Some("bar"), lines.next());
786     /// assert_eq!(Some(""), lines.next());
787     /// assert_eq!(Some("baz"), lines.next());
788     ///
789     /// assert_eq!(None, lines.next());
790     /// ```
791     ///
792     /// The final line ending isn't required:
793     ///
794     /// ```
795     /// let text = "foo\nbar\n\r\nbaz";
796     /// let mut lines = text.lines();
797     ///
798     /// assert_eq!(Some("foo"), lines.next());
799     /// assert_eq!(Some("bar"), lines.next());
800     /// assert_eq!(Some(""), lines.next());
801     /// assert_eq!(Some("baz"), lines.next());
802     ///
803     /// assert_eq!(None, lines.next());
804     /// ```
805     #[stable(feature = "rust1", since = "1.0.0")]
806     #[inline]
807     pub fn lines(&self) -> Lines {
808         core_str::StrExt::lines(self)
809     }
810
811     /// An iterator over the lines of a string.
812     #[stable(feature = "rust1", since = "1.0.0")]
813     #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
814     #[inline]
815     #[allow(deprecated)]
816     pub fn lines_any(&self) -> LinesAny {
817         core_str::StrExt::lines_any(self)
818     }
819
820     /// Returns an iterator of `u16` over the string encoded as UTF-16.
821     #[stable(feature = "encode_utf16", since = "1.8.0")]
822     pub fn encode_utf16(&self) -> EncodeUtf16 {
823         EncodeUtf16 { encoder: Utf16Encoder::new(self[..].chars()) }
824     }
825
826     /// Returns `true` if the given pattern matches a sub-slice of
827     /// this string slice.
828     ///
829     /// Returns `false` if it does not.
830     ///
831     /// # Examples
832     ///
833     /// Basic usage:
834     ///
835     /// ```
836     /// let bananas = "bananas";
837     ///
838     /// assert!(bananas.contains("nana"));
839     /// assert!(!bananas.contains("apples"));
840     /// ```
841     #[stable(feature = "rust1", since = "1.0.0")]
842     #[inline]
843     pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
844         core_str::StrExt::contains(self, pat)
845     }
846
847     /// Returns `true` if the given pattern matches a prefix of this
848     /// string slice.
849     ///
850     /// Returns `false` if it does not.
851     ///
852     /// # Examples
853     ///
854     /// Basic usage:
855     ///
856     /// ```
857     /// let bananas = "bananas";
858     ///
859     /// assert!(bananas.starts_with("bana"));
860     /// assert!(!bananas.starts_with("nana"));
861     /// ```
862     #[stable(feature = "rust1", since = "1.0.0")]
863     pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
864         core_str::StrExt::starts_with(self, pat)
865     }
866
867     /// Returns `true` if the given pattern matches a suffix of this
868     /// string slice.
869     ///
870     /// Returns `false` if it does not.
871     ///
872     /// # Examples
873     ///
874     /// Basic usage:
875     ///
876     /// ```
877     /// let bananas = "bananas";
878     ///
879     /// assert!(bananas.ends_with("anas"));
880     /// assert!(!bananas.ends_with("nana"));
881     /// ```
882     #[stable(feature = "rust1", since = "1.0.0")]
883     pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
884         where P::Searcher: ReverseSearcher<'a>
885     {
886         core_str::StrExt::ends_with(self, pat)
887     }
888
889     /// Returns the byte index of the first character of this string slice that
890     /// matches the pattern.
891     ///
892     /// Returns [`None`] if the pattern doesn't match.
893     ///
894     /// The pattern can be a `&str`, [`char`], or a closure that determines if
895     /// a character matches.
896     ///
897     /// [`char`]: primitive.char.html
898     /// [`None`]: option/enum.Option.html#variant.None
899     ///
900     /// # Examples
901     ///
902     /// Simple patterns:
903     ///
904     /// ```
905     /// let s = "Löwe 老虎 Léopard";
906     ///
907     /// assert_eq!(s.find('L'), Some(0));
908     /// assert_eq!(s.find('é'), Some(14));
909     /// assert_eq!(s.find("Léopard"), Some(13));
910     /// ```
911     ///
912     /// More complex patterns with closures:
913     ///
914     /// ```
915     /// let s = "Löwe 老虎 Léopard";
916     ///
917     /// assert_eq!(s.find(char::is_whitespace), Some(5));
918     /// assert_eq!(s.find(char::is_lowercase), Some(1));
919     /// ```
920     ///
921     /// Not finding the pattern:
922     ///
923     /// ```
924     /// let s = "Löwe 老虎 Léopard";
925     /// let x: &[_] = &['1', '2'];
926     ///
927     /// assert_eq!(s.find(x), None);
928     /// ```
929     #[stable(feature = "rust1", since = "1.0.0")]
930     #[inline]
931     pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
932         core_str::StrExt::find(self, pat)
933     }
934
935     /// Returns the byte index of the last character of this string slice that
936     /// matches the pattern.
937     ///
938     /// Returns [`None`] if the pattern doesn't match.
939     ///
940     /// The pattern can be a `&str`, [`char`], or a closure that determines if
941     /// a character matches.
942     ///
943     /// [`char`]: primitive.char.html
944     /// [`None`]: option/enum.Option.html#variant.None
945     ///
946     /// # Examples
947     ///
948     /// Simple patterns:
949     ///
950     /// ```
951     /// let s = "Löwe 老虎 Léopard";
952     ///
953     /// assert_eq!(s.rfind('L'), Some(13));
954     /// assert_eq!(s.rfind('é'), Some(14));
955     /// ```
956     ///
957     /// More complex patterns with closures:
958     ///
959     /// ```
960     /// let s = "Löwe 老虎 Léopard";
961     ///
962     /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
963     /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
964     /// ```
965     ///
966     /// Not finding the pattern:
967     ///
968     /// ```
969     /// let s = "Löwe 老虎 Léopard";
970     /// let x: &[_] = &['1', '2'];
971     ///
972     /// assert_eq!(s.rfind(x), None);
973     /// ```
974     #[stable(feature = "rust1", since = "1.0.0")]
975     #[inline]
976     pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
977         where P::Searcher: ReverseSearcher<'a>
978     {
979         core_str::StrExt::rfind(self, pat)
980     }
981
982     /// An iterator over substrings of this string slice, separated by
983     /// characters matched by a pattern.
984     ///
985     /// The pattern can be a `&str`, [`char`], or a closure that determines the
986     /// split.
987     ///
988     /// # Iterator behavior
989     ///
990     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
991     /// allows a reverse search and forward/reverse search yields the same
992     /// elements. This is true for, eg, [`char`] but not for `&str`.
993     ///
994     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
995     ///
996     /// If the pattern allows a reverse search but its results might differ
997     /// from a forward search, the [`rsplit`] method can be used.
998     ///
999     /// [`char`]: primitive.char.html
1000     /// [`rsplit`]: #method.rsplit
1001     ///
1002     /// # Examples
1003     ///
1004     /// Simple patterns:
1005     ///
1006     /// ```
1007     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1008     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1009     ///
1010     /// let v: Vec<&str> = "".split('X').collect();
1011     /// assert_eq!(v, [""]);
1012     ///
1013     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1014     /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1015     ///
1016     /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1017     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1018     ///
1019     /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1020     /// assert_eq!(v, ["abc", "def", "ghi"]);
1021     ///
1022     /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1023     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1024     /// ```
1025     ///
1026     /// A more complex pattern, using a closure:
1027     ///
1028     /// ```
1029     /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1030     /// assert_eq!(v, ["abc", "def", "ghi"]);
1031     /// ```
1032     ///
1033     /// If a string contains multiple contiguous separators, you will end up
1034     /// with empty strings in the output:
1035     ///
1036     /// ```
1037     /// let x = "||||a||b|c".to_string();
1038     /// let d: Vec<_> = x.split('|').collect();
1039     ///
1040     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1041     /// ```
1042     ///
1043     /// Contiguous separators are separated by the empty string.
1044     ///
1045     /// ```
1046     /// let x = "(///)".to_string();
1047     /// let d: Vec<_> = x.split('/').collect();
1048     ///
1049     /// assert_eq!(d, &["(", "", "", ")"]);
1050     /// ```
1051     ///
1052     /// Separators at the start or end of a string are neighbored
1053     /// by empty strings.
1054     ///
1055     /// ```
1056     /// let d: Vec<_> = "010".split("0").collect();
1057     /// assert_eq!(d, &["", "1", ""]);
1058     /// ```
1059     ///
1060     /// When the empty string is used as a separator, it separates
1061     /// every character in the string, along with the beginning
1062     /// and end of the string.
1063     ///
1064     /// ```
1065     /// let f: Vec<_> = "rust".split("").collect();
1066     /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1067     /// ```
1068     ///
1069     /// Contiguous separators can lead to possibly surprising behavior
1070     /// when whitespace is used as the separator. This code is correct:
1071     ///
1072     /// ```
1073     /// let x = "    a  b c".to_string();
1074     /// let d: Vec<_> = x.split(' ').collect();
1075     ///
1076     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1077     /// ```
1078     ///
1079     /// It does _not_ give you:
1080     ///
1081     /// ```,ignore
1082     /// assert_eq!(d, &["a", "b", "c"]);
1083     /// ```
1084     ///
1085     /// Use [`split_whitespace`] for this behavior.
1086     ///
1087     /// [`split_whitespace`]: #method.split_whitespace
1088     #[stable(feature = "rust1", since = "1.0.0")]
1089     #[inline]
1090     pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1091         core_str::StrExt::split(self, pat)
1092     }
1093
1094     /// An iterator over substrings of the given string slice, separated by
1095     /// characters matched by a pattern and yielded in reverse order.
1096     ///
1097     /// The pattern can be a `&str`, [`char`], or a closure that determines the
1098     /// split.
1099     ///
1100     /// [`char`]: primitive.char.html
1101     ///
1102     /// # Iterator behavior
1103     ///
1104     /// The returned iterator requires that the pattern supports a reverse
1105     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1106     /// search yields the same elements.
1107     ///
1108     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1109     ///
1110     /// For iterating from the front, the [`split`] method can be used.
1111     ///
1112     /// [`split`]: #method.split
1113     ///
1114     /// # Examples
1115     ///
1116     /// Simple patterns:
1117     ///
1118     /// ```
1119     /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1120     /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1121     ///
1122     /// let v: Vec<&str> = "".rsplit('X').collect();
1123     /// assert_eq!(v, [""]);
1124     ///
1125     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1126     /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1127     ///
1128     /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1129     /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1130     /// ```
1131     ///
1132     /// A more complex pattern, using a closure:
1133     ///
1134     /// ```
1135     /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1136     /// assert_eq!(v, ["ghi", "def", "abc"]);
1137     /// ```
1138     #[stable(feature = "rust1", since = "1.0.0")]
1139     #[inline]
1140     pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1141         where P::Searcher: ReverseSearcher<'a>
1142     {
1143         core_str::StrExt::rsplit(self, pat)
1144     }
1145
1146     /// An iterator over substrings of the given string slice, separated by
1147     /// characters matched by a pattern.
1148     ///
1149     /// The pattern can be a `&str`, [`char`], or a closure that determines the
1150     /// split.
1151     ///
1152     /// Equivalent to [`split`], except that the trailing substring
1153     /// is skipped if empty.
1154     ///
1155     /// [`split`]: #method.split
1156     ///
1157     /// This method can be used for string data that is _terminated_,
1158     /// rather than _separated_ by a pattern.
1159     ///
1160     /// # Iterator behavior
1161     ///
1162     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1163     /// allows a reverse search and forward/reverse search yields the same
1164     /// elements. This is true for, eg, [`char`] but not for `&str`.
1165     ///
1166     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1167     /// [`char`]: primitive.char.html
1168     ///
1169     /// If the pattern allows a reverse search but its results might differ
1170     /// from a forward search, the [`rsplit_terminator`] method can be used.
1171     ///
1172     /// [`rsplit_terminator`]: #method.rsplit_terminator
1173     ///
1174     /// # Examples
1175     ///
1176     /// Basic usage:
1177     ///
1178     /// ```
1179     /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1180     /// assert_eq!(v, ["A", "B"]);
1181     ///
1182     /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1183     /// assert_eq!(v, ["A", "", "B", ""]);
1184     /// ```
1185     #[stable(feature = "rust1", since = "1.0.0")]
1186     #[inline]
1187     pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1188         core_str::StrExt::split_terminator(self, pat)
1189     }
1190
1191     /// An iterator over substrings of `self`, separated by characters
1192     /// matched by a pattern and yielded in reverse order.
1193     ///
1194     /// The pattern can be a simple `&str`, [`char`], or a closure that
1195     /// determines the split.
1196     /// Additional libraries might provide more complex patterns like
1197     /// regular expressions.
1198     ///
1199     /// [`char`]: primitive.char.html
1200     ///
1201     /// Equivalent to [`split`], except that the trailing substring is
1202     /// skipped if empty.
1203     ///
1204     /// [`split`]: #method.split
1205     ///
1206     /// This method can be used for string data that is _terminated_,
1207     /// rather than _separated_ by a pattern.
1208     ///
1209     /// # Iterator behavior
1210     ///
1211     /// The returned iterator requires that the pattern supports a
1212     /// reverse search, and it will be double ended if a forward/reverse
1213     /// search yields the same elements.
1214     ///
1215     /// For iterating from the front, the [`split_terminator`] method can be
1216     /// used.
1217     ///
1218     /// [`split_terminator`]: #method.split_terminator
1219     ///
1220     /// # Examples
1221     ///
1222     /// ```
1223     /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1224     /// assert_eq!(v, ["B", "A"]);
1225     ///
1226     /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1227     /// assert_eq!(v, ["", "B", "", "A"]);
1228     /// ```
1229     #[stable(feature = "rust1", since = "1.0.0")]
1230     #[inline]
1231     pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1232         where P::Searcher: ReverseSearcher<'a>
1233     {
1234         core_str::StrExt::rsplit_terminator(self, pat)
1235     }
1236
1237     /// An iterator over substrings of the given string slice, separated by a
1238     /// pattern, restricted to returning at most `n` items.
1239     ///
1240     /// If `n` substrings are returned, the last substring (the `n`th substring)
1241     /// will contain the remainder of the string.
1242     ///
1243     /// The pattern can be a `&str`, [`char`], or a closure that determines the
1244     /// split.
1245     ///
1246     /// [`char`]: primitive.char.html
1247     ///
1248     /// # Iterator behavior
1249     ///
1250     /// The returned iterator will not be double ended, because it is
1251     /// not efficient to support.
1252     ///
1253     /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1254     /// used.
1255     ///
1256     /// [`rsplitn`]: #method.rsplitn
1257     ///
1258     /// # Examples
1259     ///
1260     /// Simple patterns:
1261     ///
1262     /// ```
1263     /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1264     /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1265     ///
1266     /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1267     /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1268     ///
1269     /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1270     /// assert_eq!(v, ["abcXdef"]);
1271     ///
1272     /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1273     /// assert_eq!(v, [""]);
1274     /// ```
1275     ///
1276     /// A more complex pattern, using a closure:
1277     ///
1278     /// ```
1279     /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1280     /// assert_eq!(v, ["abc", "defXghi"]);
1281     /// ```
1282     #[stable(feature = "rust1", since = "1.0.0")]
1283     #[inline]
1284     pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1285         core_str::StrExt::splitn(self, n, pat)
1286     }
1287
1288     /// An iterator over substrings of this string slice, separated by a
1289     /// pattern, starting from the end of the string, restricted to returning
1290     /// at most `n` items.
1291     ///
1292     /// If `n` substrings are returned, the last substring (the `n`th substring)
1293     /// will contain the remainder of the string.
1294     ///
1295     /// The pattern can be a `&str`, [`char`], or a closure that
1296     /// determines the split.
1297     ///
1298     /// [`char`]: primitive.char.html
1299     ///
1300     /// # Iterator behavior
1301     ///
1302     /// The returned iterator will not be double ended, because it is not
1303     /// efficient to support.
1304     ///
1305     /// For splitting from the front, the [`splitn`] method can be used.
1306     ///
1307     /// [`splitn`]: #method.splitn
1308     ///
1309     /// # Examples
1310     ///
1311     /// Simple patterns:
1312     ///
1313     /// ```
1314     /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1315     /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1316     ///
1317     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1318     /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1319     ///
1320     /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1321     /// assert_eq!(v, ["leopard", "lion::tiger"]);
1322     /// ```
1323     ///
1324     /// A more complex pattern, using a closure:
1325     ///
1326     /// ```
1327     /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1328     /// assert_eq!(v, ["ghi", "abc1def"]);
1329     /// ```
1330     #[stable(feature = "rust1", since = "1.0.0")]
1331     #[inline]
1332     pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1333         where P::Searcher: ReverseSearcher<'a>
1334     {
1335         core_str::StrExt::rsplitn(self, n, pat)
1336     }
1337
1338     /// An iterator over the disjoint matches of a pattern within the given string
1339     /// slice.
1340     ///
1341     /// The pattern can be a `&str`, [`char`], or a closure that
1342     /// determines if a character matches.
1343     ///
1344     /// [`char`]: primitive.char.html
1345     ///
1346     /// # Iterator behavior
1347     ///
1348     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1349     /// allows a reverse search and forward/reverse search yields the same
1350     /// elements. This is true for, eg, [`char`] but not for `&str`.
1351     ///
1352     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1353     /// [`char`]: primitive.char.html
1354     ///
1355     /// If the pattern allows a reverse search but its results might differ
1356     /// from a forward search, the [`rmatches`] method can be used.
1357     ///
1358     /// [`rmatches`]: #method.rmatches
1359     ///
1360     /// # Examples
1361     ///
1362     /// Basic usage:
1363     ///
1364     /// ```
1365     /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1366     /// assert_eq!(v, ["abc", "abc", "abc"]);
1367     ///
1368     /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1369     /// assert_eq!(v, ["1", "2", "3"]);
1370     /// ```
1371     #[stable(feature = "str_matches", since = "1.2.0")]
1372     #[inline]
1373     pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1374         core_str::StrExt::matches(self, pat)
1375     }
1376
1377     /// An iterator over the disjoint matches of a pattern within this string slice,
1378     /// yielded in reverse order.
1379     ///
1380     /// The pattern can be a `&str`, [`char`], or a closure that determines if
1381     /// a character matches.
1382     ///
1383     /// [`char`]: primitive.char.html
1384     ///
1385     /// # Iterator behavior
1386     ///
1387     /// The returned iterator requires that the pattern supports a reverse
1388     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1389     /// search yields the same elements.
1390     ///
1391     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1392     ///
1393     /// For iterating from the front, the [`matches`] method can be used.
1394     ///
1395     /// [`matches`]: #method.matches
1396     ///
1397     /// # Examples
1398     ///
1399     /// Basic usage:
1400     ///
1401     /// ```
1402     /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1403     /// assert_eq!(v, ["abc", "abc", "abc"]);
1404     ///
1405     /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1406     /// assert_eq!(v, ["3", "2", "1"]);
1407     /// ```
1408     #[stable(feature = "str_matches", since = "1.2.0")]
1409     #[inline]
1410     pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1411         where P::Searcher: ReverseSearcher<'a>
1412     {
1413         core_str::StrExt::rmatches(self, pat)
1414     }
1415
1416     /// An iterator over the disjoint matches of a pattern within this string
1417     /// slice as well as the index that the match starts at.
1418     ///
1419     /// For matches of `pat` within `self` that overlap, only the indices
1420     /// corresponding to the first match are returned.
1421     ///
1422     /// The pattern can be a `&str`, [`char`], or a closure that determines
1423     /// if a character matches.
1424     ///
1425     /// [`char`]: primitive.char.html
1426     ///
1427     /// # Iterator behavior
1428     ///
1429     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1430     /// allows a reverse search and forward/reverse search yields the same
1431     /// elements. This is true for, eg, [`char`] but not for `&str`.
1432     ///
1433     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1434     ///
1435     /// If the pattern allows a reverse search but its results might differ
1436     /// from a forward search, the [`rmatch_indices`] method can be used.
1437     ///
1438     /// [`rmatch_indices`]: #method.rmatch_indices
1439     ///
1440     /// # Examples
1441     ///
1442     /// Basic usage:
1443     ///
1444     /// ```
1445     /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1446     /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1447     ///
1448     /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1449     /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1450     ///
1451     /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1452     /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1453     /// ```
1454     #[stable(feature = "str_match_indices", since = "1.5.0")]
1455     #[inline]
1456     pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1457         core_str::StrExt::match_indices(self, pat)
1458     }
1459
1460     /// An iterator over the disjoint matches of a pattern within `self`,
1461     /// yielded in reverse order along with the index of the match.
1462     ///
1463     /// For matches of `pat` within `self` that overlap, only the indices
1464     /// corresponding to the last match are returned.
1465     ///
1466     /// The pattern can be a `&str`, [`char`], or a closure that determines if a
1467     /// character matches.
1468     ///
1469     /// [`char`]: primitive.char.html
1470     ///
1471     /// # Iterator behavior
1472     ///
1473     /// The returned iterator requires that the pattern supports a reverse
1474     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1475     /// search yields the same elements.
1476     ///
1477     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1478     ///
1479     /// For iterating from the front, the [`match_indices`] method can be used.
1480     ///
1481     /// [`match_indices`]: #method.match_indices
1482     ///
1483     /// # Examples
1484     ///
1485     /// Basic usage:
1486     ///
1487     /// ```
1488     /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1489     /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1490     ///
1491     /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1492     /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1493     ///
1494     /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1495     /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1496     /// ```
1497     #[stable(feature = "str_match_indices", since = "1.5.0")]
1498     #[inline]
1499     pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1500         where P::Searcher: ReverseSearcher<'a>
1501     {
1502         core_str::StrExt::rmatch_indices(self, pat)
1503     }
1504
1505     /// Returns a string slice with leading and trailing whitespace removed.
1506     ///
1507     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1508     /// Core Property `White_Space`.
1509     ///
1510     /// # Examples
1511     ///
1512     /// Basic usage:
1513     ///
1514     /// ```
1515     /// let s = " Hello\tworld\t";
1516     ///
1517     /// assert_eq!("Hello\tworld", s.trim());
1518     /// ```
1519     #[stable(feature = "rust1", since = "1.0.0")]
1520     pub fn trim(&self) -> &str {
1521         UnicodeStr::trim(self)
1522     }
1523
1524     /// Returns a string slice with leading whitespace removed.
1525     ///
1526     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1527     /// Core Property `White_Space`.
1528     ///
1529     /// # Text directionality
1530     ///
1531     /// A string is a sequence of bytes. 'Left' in this context means the first
1532     /// position of that byte string; for a language like Arabic or Hebrew
1533     /// which are 'right to left' rather than 'left to right', this will be
1534     /// the _right_ side, not the left.
1535     ///
1536     /// # Examples
1537     ///
1538     /// Basic usage:
1539     ///
1540     /// ```
1541     /// let s = " Hello\tworld\t";
1542     ///
1543     /// assert_eq!("Hello\tworld\t", s.trim_left());
1544     /// ```
1545     ///
1546     /// Directionality:
1547     ///
1548     /// ```
1549     /// let s = "  English";
1550     /// assert!(Some('E') == s.trim_left().chars().next());
1551     ///
1552     /// let s = "  עברית";
1553     /// assert!(Some('ע') == s.trim_left().chars().next());
1554     /// ```
1555     #[stable(feature = "rust1", since = "1.0.0")]
1556     pub fn trim_left(&self) -> &str {
1557         UnicodeStr::trim_left(self)
1558     }
1559
1560     /// Returns a string slice with trailing whitespace removed.
1561     ///
1562     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1563     /// Core Property `White_Space`.
1564     ///
1565     /// # Text directionality
1566     ///
1567     /// A string is a sequence of bytes. 'Right' in this context means the last
1568     /// position of that byte string; for a language like Arabic or Hebrew
1569     /// which are 'right to left' rather than 'left to right', this will be
1570     /// the _left_ side, not the right.
1571     ///
1572     /// # Examples
1573     ///
1574     /// Basic usage:
1575     ///
1576     /// ```
1577     /// let s = " Hello\tworld\t";
1578     ///
1579     /// assert_eq!(" Hello\tworld", s.trim_right());
1580     /// ```
1581     ///
1582     /// Directionality:
1583     ///
1584     /// ```
1585     /// let s = "English  ";
1586     /// assert!(Some('h') == s.trim_right().chars().rev().next());
1587     ///
1588     /// let s = "עברית  ";
1589     /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1590     /// ```
1591     #[stable(feature = "rust1", since = "1.0.0")]
1592     pub fn trim_right(&self) -> &str {
1593         UnicodeStr::trim_right(self)
1594     }
1595
1596     /// Returns a string slice with all prefixes and suffixes that match a
1597     /// pattern repeatedly removed.
1598     ///
1599     /// The pattern can be a [`char`] or a closure that determines if a
1600     /// character matches.
1601     ///
1602     /// [`char`]: primitive.char.html
1603     ///
1604     /// # Examples
1605     ///
1606     /// Simple patterns:
1607     ///
1608     /// ```
1609     /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1610     /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1611     ///
1612     /// let x: &[_] = &['1', '2'];
1613     /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1614     /// ```
1615     ///
1616     /// A more complex pattern, using a closure:
1617     ///
1618     /// ```
1619     /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1620     /// ```
1621     #[stable(feature = "rust1", since = "1.0.0")]
1622     pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1623         where P::Searcher: DoubleEndedSearcher<'a>
1624     {
1625         core_str::StrExt::trim_matches(self, pat)
1626     }
1627
1628     /// Returns a string slice with all prefixes that match a pattern
1629     /// repeatedly removed.
1630     ///
1631     /// The pattern can be a `&str`, [`char`], or a closure that determines if
1632     /// a character matches.
1633     ///
1634     /// [`char`]: primitive.char.html
1635     ///
1636     /// # Text directionality
1637     ///
1638     /// A string is a sequence of bytes. 'Left' in this context means the first
1639     /// position of that byte string; for a language like Arabic or Hebrew
1640     /// which are 'right to left' rather than 'left to right', this will be
1641     /// the _right_ side, not the left.
1642     ///
1643     /// # Examples
1644     ///
1645     /// Basic usage:
1646     ///
1647     /// ```
1648     /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1649     /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1650     ///
1651     /// let x: &[_] = &['1', '2'];
1652     /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1653     /// ```
1654     #[stable(feature = "rust1", since = "1.0.0")]
1655     pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1656         core_str::StrExt::trim_left_matches(self, pat)
1657     }
1658
1659     /// Returns a string slice with all suffixes that match a pattern
1660     /// repeatedly removed.
1661     ///
1662     /// The pattern can be a `&str`, [`char`], or a closure that
1663     /// determines if a character matches.
1664     ///
1665     /// [`char`]: primitive.char.html
1666     ///
1667     /// # Text directionality
1668     ///
1669     /// A string is a sequence of bytes. 'Right' in this context means the last
1670     /// position of that byte string; for a language like Arabic or Hebrew
1671     /// which are 'right to left' rather than 'left to right', this will be
1672     /// the _left_ side, not the right.
1673     ///
1674     /// # Examples
1675     ///
1676     /// Simple patterns:
1677     ///
1678     /// ```
1679     /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1680     /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1681     ///
1682     /// let x: &[_] = &['1', '2'];
1683     /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1684     /// ```
1685     ///
1686     /// A more complex pattern, using a closure:
1687     ///
1688     /// ```
1689     /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1690     /// ```
1691     #[stable(feature = "rust1", since = "1.0.0")]
1692     pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1693         where P::Searcher: ReverseSearcher<'a>
1694     {
1695         core_str::StrExt::trim_right_matches(self, pat)
1696     }
1697
1698     /// Parses this string slice into another type.
1699     ///
1700     /// Because `parse` is so general, it can cause problems with type
1701     /// inference. As such, `parse` is one of the few times you'll see
1702     /// the syntax affectionately known as the 'turbofish': `::<>`. This
1703     /// helps the inference algorithm understand specifically which type
1704     /// you're trying to parse into.
1705     ///
1706     /// `parse` can parse any type that implements the [`FromStr`] trait.
1707     ///
1708     /// [`FromStr`]: str/trait.FromStr.html
1709     ///
1710     /// # Errors
1711     ///
1712     /// Will return [`Err`] if it's not possible to parse this string slice into
1713     /// the desired type.
1714     ///
1715     /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
1716     ///
1717     /// # Examples
1718     ///
1719     /// Basic usage
1720     ///
1721     /// ```
1722     /// let four: u32 = "4".parse().unwrap();
1723     ///
1724     /// assert_eq!(4, four);
1725     /// ```
1726     ///
1727     /// Using the 'turbofish' instead of annotating `four`:
1728     ///
1729     /// ```
1730     /// let four = "4".parse::<u32>();
1731     ///
1732     /// assert_eq!(Ok(4), four);
1733     /// ```
1734     ///
1735     /// Failing to parse:
1736     ///
1737     /// ```
1738     /// let nope = "j".parse::<u32>();
1739     ///
1740     /// assert!(nope.is_err());
1741     /// ```
1742     #[inline]
1743     #[stable(feature = "rust1", since = "1.0.0")]
1744     pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1745         core_str::StrExt::parse(self)
1746     }
1747
1748     /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
1749     #[stable(feature = "str_box_extras", since = "1.20.0")]
1750     pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
1751         self.into()
1752     }
1753
1754     /// Replaces all matches of a pattern with another string.
1755     ///
1756     /// `replace` creates a new [`String`], and copies the data from this string slice into it.
1757     /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1758     /// replaces them with the replacement string slice.
1759     ///
1760     /// [`String`]: string/struct.String.html
1761     ///
1762     /// # Examples
1763     ///
1764     /// Basic usage:
1765     ///
1766     /// ```
1767     /// let s = "this is old";
1768     ///
1769     /// assert_eq!("this is new", s.replace("old", "new"));
1770     /// ```
1771     ///
1772     /// When the pattern doesn't match:
1773     ///
1774     /// ```
1775     /// let s = "this is old";
1776     /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1777     /// ```
1778     #[stable(feature = "rust1", since = "1.0.0")]
1779     #[inline]
1780     pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
1781         let mut result = String::new();
1782         let mut last_end = 0;
1783         for (start, part) in self.match_indices(from) {
1784             result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1785             result.push_str(to);
1786             last_end = start + part.len();
1787         }
1788         result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1789         result
1790     }
1791
1792     /// Replaces first N matches of a pattern with another string.
1793     ///
1794     /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
1795     /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1796     /// replaces them with the replacement string slice at most `count` times.
1797     ///
1798     /// [`String`]: string/struct.String.html
1799     ///
1800     /// # Examples
1801     ///
1802     /// Basic usage:
1803     ///
1804     /// ```
1805     /// let s = "foo foo 123 foo";
1806     /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
1807     /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
1808     /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
1809     /// ```
1810     ///
1811     /// When the pattern doesn't match:
1812     ///
1813     /// ```
1814     /// let s = "this is old";
1815     /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1816     /// ```
1817     #[stable(feature = "str_replacen", since = "1.16.0")]
1818     pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
1819         // Hope to reduce the times of re-allocation
1820         let mut result = String::with_capacity(32);
1821         let mut last_end = 0;
1822         for (start, part) in self.match_indices(pat).take(count) {
1823             result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1824             result.push_str(to);
1825             last_end = start + part.len();
1826         }
1827         result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1828         result
1829     }
1830
1831     /// Returns the lowercase equivalent of this string slice, as a new [`String`].
1832     ///
1833     /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
1834     /// `Lowercase`.
1835     ///
1836     /// Since some characters can expand into multiple characters when changing
1837     /// the case, this function returns a [`String`] instead of modifying the
1838     /// parameter in-place.
1839     ///
1840     /// [`String`]: string/struct.String.html
1841     ///
1842     /// # Examples
1843     ///
1844     /// Basic usage:
1845     ///
1846     /// ```
1847     /// let s = "HELLO";
1848     ///
1849     /// assert_eq!("hello", s.to_lowercase());
1850     /// ```
1851     ///
1852     /// A tricky example, with sigma:
1853     ///
1854     /// ```
1855     /// let sigma = "Σ";
1856     ///
1857     /// assert_eq!("σ", sigma.to_lowercase());
1858     ///
1859     /// // but at the end of a word, it's ς, not σ:
1860     /// let odysseus = "ὈΔΥΣΣΕΎΣ";
1861     ///
1862     /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1863     /// ```
1864     ///
1865     /// Languages without case are not changed:
1866     ///
1867     /// ```
1868     /// let new_year = "农历新年";
1869     ///
1870     /// assert_eq!(new_year, new_year.to_lowercase());
1871     /// ```
1872     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1873     pub fn to_lowercase(&self) -> String {
1874         let mut s = String::with_capacity(self.len());
1875         for (i, c) in self[..].char_indices() {
1876             if c == 'Σ' {
1877                 // Σ maps to σ, except at the end of a word where it maps to ς.
1878                 // This is the only conditional (contextual) but language-independent mapping
1879                 // in `SpecialCasing.txt`,
1880                 // so hard-code it rather than have a generic "condition" mechanism.
1881                 // See https://github.com/rust-lang/rust/issues/26035
1882                 map_uppercase_sigma(self, i, &mut s)
1883             } else {
1884                 s.extend(c.to_lowercase());
1885             }
1886         }
1887         return s;
1888
1889         fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1890             // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1891             // for the definition of `Final_Sigma`.
1892             debug_assert!('Σ'.len_utf8() == 2);
1893             let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
1894                                 !case_ignoreable_then_cased(from[i + 2..].chars());
1895             to.push_str(if is_word_final { "ς" } else { "σ" });
1896         }
1897
1898         fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
1899             use std_unicode::derived_property::{Cased, Case_Ignorable};
1900             match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1901                 Some(c) => Cased(c),
1902                 None => false,
1903             }
1904         }
1905     }
1906
1907     /// Returns the uppercase equivalent of this string slice, as a new [`String`].
1908     ///
1909     /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1910     /// `Uppercase`.
1911     ///
1912     /// Since some characters can expand into multiple characters when changing
1913     /// the case, this function returns a [`String`] instead of modifying the
1914     /// parameter in-place.
1915     ///
1916     /// [`String`]: string/struct.String.html
1917     ///
1918     /// # Examples
1919     ///
1920     /// Basic usage:
1921     ///
1922     /// ```
1923     /// let s = "hello";
1924     ///
1925     /// assert_eq!("HELLO", s.to_uppercase());
1926     /// ```
1927     ///
1928     /// Scripts without case are not changed:
1929     ///
1930     /// ```
1931     /// let new_year = "农历新年";
1932     ///
1933     /// assert_eq!(new_year, new_year.to_uppercase());
1934     /// ```
1935     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1936     pub fn to_uppercase(&self) -> String {
1937         let mut s = String::with_capacity(self.len());
1938         s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1939         return s;
1940     }
1941
1942     /// Escapes each char in `s` with [`char::escape_debug`].
1943     ///
1944     /// [`char::escape_debug`]: primitive.char.html#method.escape_debug
1945     #[unstable(feature = "str_escape",
1946                reason = "return type may change to be an iterator",
1947                issue = "27791")]
1948     pub fn escape_debug(&self) -> String {
1949         self.chars().flat_map(|c| c.escape_debug()).collect()
1950     }
1951
1952     /// Escapes each char in `s` with [`char::escape_default`].
1953     ///
1954     /// [`char::escape_default`]: primitive.char.html#method.escape_default
1955     #[unstable(feature = "str_escape",
1956                reason = "return type may change to be an iterator",
1957                issue = "27791")]
1958     pub fn escape_default(&self) -> String {
1959         self.chars().flat_map(|c| c.escape_default()).collect()
1960     }
1961
1962     /// Escapes each char in `s` with [`char::escape_unicode`].
1963     ///
1964     /// [`char::escape_unicode`]: primitive.char.html#method.escape_unicode
1965     #[unstable(feature = "str_escape",
1966                reason = "return type may change to be an iterator",
1967                issue = "27791")]
1968     pub fn escape_unicode(&self) -> String {
1969         self.chars().flat_map(|c| c.escape_unicode()).collect()
1970     }
1971
1972     /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
1973     ///
1974     /// [`String`]: string/struct.String.html
1975     /// [`Box<str>`]: boxed/struct.Box.html
1976     ///
1977     /// # Examples
1978     ///
1979     /// Basic usage:
1980     ///
1981     /// ```
1982     /// let string = String::from("birthday gift");
1983     /// let boxed_str = string.clone().into_boxed_str();
1984     ///
1985     /// assert_eq!(boxed_str.into_string(), string);
1986     /// ```
1987     #[stable(feature = "box_str", since = "1.4.0")]
1988     pub fn into_string(self: Box<str>) -> String {
1989         unsafe {
1990             let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1991             String::from_utf8_unchecked(slice.into_vec())
1992         }
1993     }
1994
1995     /// Create a [`String`] by repeating a string `n` times.
1996     ///
1997     /// [`String`]: string/struct.String.html
1998     ///
1999     /// # Examples
2000     ///
2001     /// Basic usage:
2002     ///
2003     /// ```
2004     /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
2005     /// ```
2006     #[stable(feature = "repeat_str", since = "1.16.0")]
2007     pub fn repeat(&self, n: usize) -> String {
2008         let mut s = String::with_capacity(self.len() * n);
2009         s.extend((0..n).map(|_| self));
2010         s
2011     }
2012 }
2013
2014 /// Converts a boxed slice of bytes to a boxed string slice without checking
2015 /// that the string contains valid UTF-8.
2016 #[stable(feature = "str_box_extras", since = "1.20.0")]
2017 pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box<str> {
2018     mem::transmute(v)
2019 }