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