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