]> git.lizzy.rs Git - rust.git/blob - src/libcollections/str.rs
Remove some unused macros from the rust codebase
[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     pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
817         core_str::StrExt::contains(self, pat)
818     }
819
820     /// Returns `true` if the given pattern matches a prefix of this
821     /// string slice.
822     ///
823     /// Returns `false` if it does not.
824     ///
825     /// # Examples
826     ///
827     /// Basic usage:
828     ///
829     /// ```
830     /// let bananas = "bananas";
831     ///
832     /// assert!(bananas.starts_with("bana"));
833     /// assert!(!bananas.starts_with("nana"));
834     /// ```
835     #[stable(feature = "rust1", since = "1.0.0")]
836     pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
837         core_str::StrExt::starts_with(self, pat)
838     }
839
840     /// Returns `true` if the given pattern matches a suffix of this
841     /// string slice.
842     ///
843     /// Returns `false` if it does not.
844     ///
845     /// # Examples
846     ///
847     /// Basic usage:
848     ///
849     /// ```
850     /// let bananas = "bananas";
851     ///
852     /// assert!(bananas.ends_with("anas"));
853     /// assert!(!bananas.ends_with("nana"));
854     /// ```
855     #[stable(feature = "rust1", since = "1.0.0")]
856     pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
857         where P::Searcher: ReverseSearcher<'a>
858     {
859         core_str::StrExt::ends_with(self, pat)
860     }
861
862     /// Returns the byte index of the first character of this string slice that
863     /// matches the pattern.
864     ///
865     /// Returns [`None`] if the pattern doesn't match.
866     ///
867     /// The pattern can be a `&str`, [`char`], or a closure that determines if
868     /// a character matches.
869     ///
870     /// [`char`]: primitive.char.html
871     /// [`None`]: option/enum.Option.html#variant.None
872     ///
873     /// # Examples
874     ///
875     /// Simple patterns:
876     ///
877     /// ```
878     /// let s = "Löwe 老虎 Léopard";
879     ///
880     /// assert_eq!(s.find('L'), Some(0));
881     /// assert_eq!(s.find('é'), Some(14));
882     /// assert_eq!(s.find("Léopard"), Some(13));
883     /// ```
884     ///
885     /// More complex patterns with closures:
886     ///
887     /// ```
888     /// let s = "Löwe 老虎 Léopard";
889     ///
890     /// assert_eq!(s.find(char::is_whitespace), Some(5));
891     /// assert_eq!(s.find(char::is_lowercase), Some(1));
892     /// ```
893     ///
894     /// Not finding the pattern:
895     ///
896     /// ```
897     /// let s = "Löwe 老虎 Léopard";
898     /// let x: &[_] = &['1', '2'];
899     ///
900     /// assert_eq!(s.find(x), None);
901     /// ```
902     #[stable(feature = "rust1", since = "1.0.0")]
903     pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
904         core_str::StrExt::find(self, pat)
905     }
906
907     /// Returns the byte index of the last character of this string slice that
908     /// matches the pattern.
909     ///
910     /// Returns [`None`] if the pattern doesn't match.
911     ///
912     /// The pattern can be a `&str`, [`char`], or a closure that determines if
913     /// a character matches.
914     ///
915     /// [`char`]: primitive.char.html
916     /// [`None`]: option/enum.Option.html#variant.None
917     ///
918     /// # Examples
919     ///
920     /// Simple patterns:
921     ///
922     /// ```
923     /// let s = "Löwe 老虎 Léopard";
924     ///
925     /// assert_eq!(s.rfind('L'), Some(13));
926     /// assert_eq!(s.rfind('é'), Some(14));
927     /// ```
928     ///
929     /// More complex patterns with closures:
930     ///
931     /// ```
932     /// let s = "Löwe 老虎 Léopard";
933     ///
934     /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
935     /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
936     /// ```
937     ///
938     /// Not finding the pattern:
939     ///
940     /// ```
941     /// let s = "Löwe 老虎 Léopard";
942     /// let x: &[_] = &['1', '2'];
943     ///
944     /// assert_eq!(s.rfind(x), None);
945     /// ```
946     #[stable(feature = "rust1", since = "1.0.0")]
947     pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
948         where P::Searcher: ReverseSearcher<'a>
949     {
950         core_str::StrExt::rfind(self, pat)
951     }
952
953     /// An iterator over substrings of this string slice, separated by
954     /// characters matched by a pattern.
955     ///
956     /// The pattern can be a `&str`, [`char`], or a closure that determines the
957     /// split.
958     ///
959     /// # Iterator behavior
960     ///
961     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
962     /// allows a reverse search and forward/reverse search yields the same
963     /// elements. This is true for, eg, [`char`] but not for `&str`.
964     ///
965     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
966     ///
967     /// If the pattern allows a reverse search but its results might differ
968     /// from a forward search, the [`rsplit`] method can be used.
969     ///
970     /// [`char`]: primitive.char.html
971     /// [`rsplit`]: #method.rsplit
972     ///
973     /// # Examples
974     ///
975     /// Simple patterns:
976     ///
977     /// ```
978     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
979     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
980     ///
981     /// let v: Vec<&str> = "".split('X').collect();
982     /// assert_eq!(v, [""]);
983     ///
984     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
985     /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
986     ///
987     /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
988     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
989     ///
990     /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
991     /// assert_eq!(v, ["abc", "def", "ghi"]);
992     ///
993     /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
994     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
995     /// ```
996     ///
997     /// A more complex pattern, using a closure:
998     ///
999     /// ```
1000     /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1001     /// assert_eq!(v, ["abc", "def", "ghi"]);
1002     /// ```
1003     ///
1004     /// If a string contains multiple contiguous separators, you will end up
1005     /// with empty strings in the output:
1006     ///
1007     /// ```
1008     /// let x = "||||a||b|c".to_string();
1009     /// let d: Vec<_> = x.split('|').collect();
1010     ///
1011     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1012     /// ```
1013     ///
1014     /// Contiguous separators are separated by the empty string.
1015     ///
1016     /// ```
1017     /// let x = "(///)".to_string();
1018     /// let d: Vec<_> = x.split('/').collect();;
1019     ///
1020     /// assert_eq!(d, &["(", "", "", ")"]);
1021     /// ```
1022     ///
1023     /// Separators at the start or end of a string are neighbored
1024     /// by empty strings.
1025     ///
1026     /// ```
1027     /// let d: Vec<_> = "010".split("0").collect();
1028     /// assert_eq!(d, &["", "1", ""]);
1029     /// ```
1030     ///
1031     /// When the empty string is used as a separator, it separates
1032     /// every character in the string, along with the beginning
1033     /// and end of the string.
1034     ///
1035     /// ```
1036     /// let f: Vec<_> = "rust".split("").collect();
1037     /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1038     /// ```
1039     ///
1040     /// Contiguous separators can lead to possibly surprising behavior
1041     /// when whitespace is used as the separator. This code is correct:
1042     ///
1043     /// ```
1044     /// let x = "    a  b c".to_string();
1045     /// let d: Vec<_> = x.split(' ').collect();
1046     ///
1047     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1048     /// ```
1049     ///
1050     /// It does _not_ give you:
1051     ///
1052     /// ```,ignore
1053     /// assert_eq!(d, &["a", "b", "c"]);
1054     /// ```
1055     ///
1056     /// Use [`split_whitespace`] for this behavior.
1057     ///
1058     /// [`split_whitespace`]: #method.split_whitespace
1059     #[stable(feature = "rust1", since = "1.0.0")]
1060     pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1061         core_str::StrExt::split(self, pat)
1062     }
1063
1064     /// An iterator over substrings of the given string slice, separated by
1065     /// characters matched by a pattern and yielded in reverse order.
1066     ///
1067     /// The pattern can be a `&str`, [`char`], or a closure that determines the
1068     /// split.
1069     ///
1070     /// [`char`]: primitive.char.html
1071     ///
1072     /// # Iterator behavior
1073     ///
1074     /// The returned iterator requires that the pattern supports a reverse
1075     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1076     /// search yields the same elements.
1077     ///
1078     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1079     ///
1080     /// For iterating from the front, the [`split`] method can be used.
1081     ///
1082     /// [`split`]: #method.split
1083     ///
1084     /// # Examples
1085     ///
1086     /// Simple patterns:
1087     ///
1088     /// ```
1089     /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1090     /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1091     ///
1092     /// let v: Vec<&str> = "".rsplit('X').collect();
1093     /// assert_eq!(v, [""]);
1094     ///
1095     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1096     /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1097     ///
1098     /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1099     /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1100     /// ```
1101     ///
1102     /// A more complex pattern, using a closure:
1103     ///
1104     /// ```
1105     /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1106     /// assert_eq!(v, ["ghi", "def", "abc"]);
1107     /// ```
1108     #[stable(feature = "rust1", since = "1.0.0")]
1109     pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1110         where P::Searcher: ReverseSearcher<'a>
1111     {
1112         core_str::StrExt::rsplit(self, pat)
1113     }
1114
1115     /// An iterator over substrings of the given string slice, separated by
1116     /// characters matched by a pattern.
1117     ///
1118     /// The pattern can be a `&str`, [`char`], or a closure that determines the
1119     /// split.
1120     ///
1121     /// Equivalent to [`split`], except that the trailing substring
1122     /// is skipped if empty.
1123     ///
1124     /// [`split`]: #method.split
1125     ///
1126     /// This method can be used for string data that is _terminated_,
1127     /// rather than _separated_ by a pattern.
1128     ///
1129     /// # Iterator behavior
1130     ///
1131     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1132     /// allows a reverse search and forward/reverse search yields the same
1133     /// elements. This is true for, eg, [`char`] but not for `&str`.
1134     ///
1135     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1136     /// [`char`]: primitive.char.html
1137     ///
1138     /// If the pattern allows a reverse search but its results might differ
1139     /// from a forward search, the [`rsplit_terminator`] method can be used.
1140     ///
1141     /// [`rsplit_terminator`]: #method.rsplit_terminator
1142     ///
1143     /// # Examples
1144     ///
1145     /// Basic usage:
1146     ///
1147     /// ```
1148     /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1149     /// assert_eq!(v, ["A", "B"]);
1150     ///
1151     /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1152     /// assert_eq!(v, ["A", "", "B", ""]);
1153     /// ```
1154     #[stable(feature = "rust1", since = "1.0.0")]
1155     pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1156         core_str::StrExt::split_terminator(self, pat)
1157     }
1158
1159     /// An iterator over substrings of `self`, separated by characters
1160     /// matched by a pattern and yielded in reverse order.
1161     ///
1162     /// The pattern can be a simple `&str`, [`char`], or a closure that
1163     /// determines the split.
1164     /// Additional libraries might provide more complex patterns like
1165     /// regular expressions.
1166     ///
1167     /// [`char`]: primitive.char.html
1168     ///
1169     /// Equivalent to [`split`], except that the trailing substring is
1170     /// skipped if empty.
1171     ///
1172     /// [`split`]: #method.split
1173     ///
1174     /// This method can be used for string data that is _terminated_,
1175     /// rather than _separated_ by a pattern.
1176     ///
1177     /// # Iterator behavior
1178     ///
1179     /// The returned iterator requires that the pattern supports a
1180     /// reverse search, and it will be double ended if a forward/reverse
1181     /// search yields the same elements.
1182     ///
1183     /// For iterating from the front, the [`split_terminator`] method can be
1184     /// used.
1185     ///
1186     /// [`split_terminator`]: #method.split_terminator
1187     ///
1188     /// # Examples
1189     ///
1190     /// ```
1191     /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1192     /// assert_eq!(v, ["B", "A"]);
1193     ///
1194     /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1195     /// assert_eq!(v, ["", "B", "", "A"]);
1196     /// ```
1197     #[stable(feature = "rust1", since = "1.0.0")]
1198     pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1199         where P::Searcher: ReverseSearcher<'a>
1200     {
1201         core_str::StrExt::rsplit_terminator(self, pat)
1202     }
1203
1204     /// An iterator over substrings of the given string slice, separated by a
1205     /// pattern, restricted to returning at most `n` items.
1206     ///
1207     /// If `n` substrings are returned, the last substring (the `n`th substring)
1208     /// will contain the remainder of the string.
1209     ///
1210     /// The pattern can be a `&str`, [`char`], or a closure that determines the
1211     /// split.
1212     ///
1213     /// [`char`]: primitive.char.html
1214     ///
1215     /// # Iterator behavior
1216     ///
1217     /// The returned iterator will not be double ended, because it is
1218     /// not efficient to support.
1219     ///
1220     /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1221     /// used.
1222     ///
1223     /// [`rsplitn`]: #method.rsplitn
1224     ///
1225     /// # Examples
1226     ///
1227     /// Simple patterns:
1228     ///
1229     /// ```
1230     /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1231     /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1232     ///
1233     /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1234     /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1235     ///
1236     /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1237     /// assert_eq!(v, ["abcXdef"]);
1238     ///
1239     /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1240     /// assert_eq!(v, [""]);
1241     /// ```
1242     ///
1243     /// A more complex pattern, using a closure:
1244     ///
1245     /// ```
1246     /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1247     /// assert_eq!(v, ["abc", "defXghi"]);
1248     /// ```
1249     #[stable(feature = "rust1", since = "1.0.0")]
1250     pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1251         core_str::StrExt::splitn(self, n, pat)
1252     }
1253
1254     /// An iterator over substrings of this string slice, separated by a
1255     /// pattern, starting from the end of the string, restricted to returning
1256     /// at most `n` items.
1257     ///
1258     /// If `n` substrings are returned, the last substring (the `n`th substring)
1259     /// will contain the remainder of the string.
1260     ///
1261     /// The pattern can be a `&str`, [`char`], or a closure that
1262     /// determines the split.
1263     ///
1264     /// [`char`]: primitive.char.html
1265     ///
1266     /// # Iterator behavior
1267     ///
1268     /// The returned iterator will not be double ended, because it is not
1269     /// efficient to support.
1270     ///
1271     /// For splitting from the front, the [`splitn`] method can be used.
1272     ///
1273     /// [`splitn`]: #method.splitn
1274     ///
1275     /// # Examples
1276     ///
1277     /// Simple patterns:
1278     ///
1279     /// ```
1280     /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1281     /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1282     ///
1283     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1284     /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1285     ///
1286     /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1287     /// assert_eq!(v, ["leopard", "lion::tiger"]);
1288     /// ```
1289     ///
1290     /// A more complex pattern, using a closure:
1291     ///
1292     /// ```
1293     /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1294     /// assert_eq!(v, ["ghi", "abc1def"]);
1295     /// ```
1296     #[stable(feature = "rust1", since = "1.0.0")]
1297     pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1298         where P::Searcher: ReverseSearcher<'a>
1299     {
1300         core_str::StrExt::rsplitn(self, n, pat)
1301     }
1302
1303     /// An iterator over the matches of a pattern within the given string
1304     /// slice.
1305     ///
1306     /// The pattern can be a `&str`, [`char`], or a closure that
1307     /// determines if a character matches.
1308     ///
1309     /// [`char`]: primitive.char.html
1310     ///
1311     /// # Iterator behavior
1312     ///
1313     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1314     /// allows a reverse search and forward/reverse search yields the same
1315     /// elements. This is true for, eg, [`char`] but not for `&str`.
1316     ///
1317     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1318     /// [`char`]: primitive.char.html
1319     ///
1320     /// If the pattern allows a reverse search but its results might differ
1321     /// from a forward search, the [`rmatches`] method can be used.
1322     ///
1323     /// [`rmatches`]: #method.rmatches
1324     ///
1325     /// # Examples
1326     ///
1327     /// Basic usage:
1328     ///
1329     /// ```
1330     /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1331     /// assert_eq!(v, ["abc", "abc", "abc"]);
1332     ///
1333     /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1334     /// assert_eq!(v, ["1", "2", "3"]);
1335     /// ```
1336     #[stable(feature = "str_matches", since = "1.2.0")]
1337     pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1338         core_str::StrExt::matches(self, pat)
1339     }
1340
1341     /// An iterator over the matches of a pattern within this string slice,
1342     /// yielded in reverse order.
1343     ///
1344     /// The pattern can be a `&str`, [`char`], or a closure that determines if
1345     /// a character matches.
1346     ///
1347     /// [`char`]: primitive.char.html
1348     ///
1349     /// # Iterator behavior
1350     ///
1351     /// The returned iterator requires that the pattern supports a reverse
1352     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1353     /// search yields the same elements.
1354     ///
1355     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1356     ///
1357     /// For iterating from the front, the [`matches`] method can be used.
1358     ///
1359     /// [`matches`]: #method.matches
1360     ///
1361     /// # Examples
1362     ///
1363     /// Basic usage:
1364     ///
1365     /// ```
1366     /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1367     /// assert_eq!(v, ["abc", "abc", "abc"]);
1368     ///
1369     /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1370     /// assert_eq!(v, ["3", "2", "1"]);
1371     /// ```
1372     #[stable(feature = "str_matches", since = "1.2.0")]
1373     pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1374         where P::Searcher: ReverseSearcher<'a>
1375     {
1376         core_str::StrExt::rmatches(self, pat)
1377     }
1378
1379     /// An iterator over the disjoint matches of a pattern within this string
1380     /// slice as well as the index that the match starts at.
1381     ///
1382     /// For matches of `pat` within `self` that overlap, only the indices
1383     /// corresponding to the first match are returned.
1384     ///
1385     /// The pattern can be a `&str`, [`char`], or a closure that determines
1386     /// if a character matches.
1387     ///
1388     /// [`char`]: primitive.char.html
1389     ///
1390     /// # Iterator behavior
1391     ///
1392     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1393     /// allows a reverse search and forward/reverse search yields the same
1394     /// elements. This is true for, eg, [`char`] but not for `&str`.
1395     ///
1396     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1397     ///
1398     /// If the pattern allows a reverse search but its results might differ
1399     /// from a forward search, the [`rmatch_indices`] method can be used.
1400     ///
1401     /// [`rmatch_indices`]: #method.rmatch_indices
1402     ///
1403     /// # Examples
1404     ///
1405     /// Basic usage:
1406     ///
1407     /// ```
1408     /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1409     /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1410     ///
1411     /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1412     /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1413     ///
1414     /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1415     /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1416     /// ```
1417     #[stable(feature = "str_match_indices", since = "1.5.0")]
1418     pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1419         core_str::StrExt::match_indices(self, pat)
1420     }
1421
1422     /// An iterator over the disjoint matches of a pattern within `self`,
1423     /// yielded in reverse order along with the index of the match.
1424     ///
1425     /// For matches of `pat` within `self` that overlap, only the indices
1426     /// corresponding to the last match are returned.
1427     ///
1428     /// The pattern can be a `&str`, [`char`], or a closure that determines if a
1429     /// character matches.
1430     ///
1431     /// [`char`]: primitive.char.html
1432     ///
1433     /// # Iterator behavior
1434     ///
1435     /// The returned iterator requires that the pattern supports a reverse
1436     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1437     /// search yields the same elements.
1438     ///
1439     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1440     ///
1441     /// For iterating from the front, the [`match_indices`] method can be used.
1442     ///
1443     /// [`match_indices`]: #method.match_indices
1444     ///
1445     /// # Examples
1446     ///
1447     /// Basic usage:
1448     ///
1449     /// ```
1450     /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1451     /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1452     ///
1453     /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1454     /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1455     ///
1456     /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1457     /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1458     /// ```
1459     #[stable(feature = "str_match_indices", since = "1.5.0")]
1460     pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1461         where P::Searcher: ReverseSearcher<'a>
1462     {
1463         core_str::StrExt::rmatch_indices(self, pat)
1464     }
1465
1466     /// Returns a string slice with leading and trailing whitespace removed.
1467     ///
1468     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1469     /// Core Property `White_Space`.
1470     ///
1471     /// # Examples
1472     ///
1473     /// Basic usage:
1474     ///
1475     /// ```
1476     /// let s = " Hello\tworld\t";
1477     ///
1478     /// assert_eq!("Hello\tworld", s.trim());
1479     /// ```
1480     #[stable(feature = "rust1", since = "1.0.0")]
1481     pub fn trim(&self) -> &str {
1482         UnicodeStr::trim(self)
1483     }
1484
1485     /// Returns a string slice with leading whitespace removed.
1486     ///
1487     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1488     /// Core Property `White_Space`.
1489     ///
1490     /// # Text directionality
1491     ///
1492     /// A string is a sequence of bytes. 'Left' in this context means the first
1493     /// position of that byte string; for a language like Arabic or Hebrew
1494     /// which are 'right to left' rather than 'left to right', this will be
1495     /// the _right_ side, not the left.
1496     ///
1497     /// # Examples
1498     ///
1499     /// Basic usage:
1500     ///
1501     /// ```
1502     /// let s = " Hello\tworld\t";
1503     ///
1504     /// assert_eq!("Hello\tworld\t", s.trim_left());
1505     /// ```
1506     ///
1507     /// Directionality:
1508     ///
1509     /// ```
1510     /// let s = "  English";
1511     /// assert!(Some('E') == s.trim_left().chars().next());
1512     ///
1513     /// let s = "  עברית";
1514     /// assert!(Some('ע') == s.trim_left().chars().next());
1515     /// ```
1516     #[stable(feature = "rust1", since = "1.0.0")]
1517     pub fn trim_left(&self) -> &str {
1518         UnicodeStr::trim_left(self)
1519     }
1520
1521     /// Returns a string slice with trailing whitespace removed.
1522     ///
1523     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1524     /// Core Property `White_Space`.
1525     ///
1526     /// # Text directionality
1527     ///
1528     /// A string is a sequence of bytes. 'Right' in this context means the last
1529     /// position of that byte string; for a language like Arabic or Hebrew
1530     /// which are 'right to left' rather than 'left to right', this will be
1531     /// the _left_ side, not the right.
1532     ///
1533     /// # Examples
1534     ///
1535     /// Basic usage:
1536     ///
1537     /// ```
1538     /// let s = " Hello\tworld\t";
1539     ///
1540     /// assert_eq!(" Hello\tworld", s.trim_right());
1541     /// ```
1542     ///
1543     /// Directionality:
1544     ///
1545     /// ```
1546     /// let s = "English  ";
1547     /// assert!(Some('h') == s.trim_right().chars().rev().next());
1548     ///
1549     /// let s = "עברית  ";
1550     /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1551     /// ```
1552     #[stable(feature = "rust1", since = "1.0.0")]
1553     pub fn trim_right(&self) -> &str {
1554         UnicodeStr::trim_right(self)
1555     }
1556
1557     /// Returns a string slice with all prefixes and suffixes that match a
1558     /// pattern repeatedly removed.
1559     ///
1560     /// The pattern can be a [`char`] or a closure that determines if a
1561     /// character matches.
1562     ///
1563     /// [`char`]: primitive.char.html
1564     ///
1565     /// # Examples
1566     ///
1567     /// Simple patterns:
1568     ///
1569     /// ```
1570     /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1571     /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1572     ///
1573     /// let x: &[_] = &['1', '2'];
1574     /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1575     /// ```
1576     ///
1577     /// A more complex pattern, using a closure:
1578     ///
1579     /// ```
1580     /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1581     /// ```
1582     #[stable(feature = "rust1", since = "1.0.0")]
1583     pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1584         where P::Searcher: DoubleEndedSearcher<'a>
1585     {
1586         core_str::StrExt::trim_matches(self, pat)
1587     }
1588
1589     /// Returns a string slice with all prefixes that match a pattern
1590     /// repeatedly removed.
1591     ///
1592     /// The pattern can be a `&str`, [`char`], or a closure that determines if
1593     /// a character matches.
1594     ///
1595     /// [`char`]: primitive.char.html
1596     ///
1597     /// # Text directionality
1598     ///
1599     /// A string is a sequence of bytes. 'Left' in this context means the first
1600     /// position of that byte string; for a language like Arabic or Hebrew
1601     /// which are 'right to left' rather than 'left to right', this will be
1602     /// the _right_ side, not the left.
1603     ///
1604     /// # Examples
1605     ///
1606     /// Basic usage:
1607     ///
1608     /// ```
1609     /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1610     /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1611     ///
1612     /// let x: &[_] = &['1', '2'];
1613     /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1614     /// ```
1615     #[stable(feature = "rust1", since = "1.0.0")]
1616     pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1617         core_str::StrExt::trim_left_matches(self, pat)
1618     }
1619
1620     /// Returns a string slice with all suffixes that match a pattern
1621     /// repeatedly removed.
1622     ///
1623     /// The pattern can be a `&str`, [`char`], or a closure that
1624     /// determines if a character matches.
1625     ///
1626     /// [`char`]: primitive.char.html
1627     ///
1628     /// # Text directionality
1629     ///
1630     /// A string is a sequence of bytes. 'Right' in this context means the last
1631     /// position of that byte string; for a language like Arabic or Hebrew
1632     /// which are 'right to left' rather than 'left to right', this will be
1633     /// the _left_ side, not the right.
1634     ///
1635     /// # Examples
1636     ///
1637     /// Simple patterns:
1638     ///
1639     /// ```
1640     /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1641     /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1642     ///
1643     /// let x: &[_] = &['1', '2'];
1644     /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1645     /// ```
1646     ///
1647     /// A more complex pattern, using a closure:
1648     ///
1649     /// ```
1650     /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1651     /// ```
1652     #[stable(feature = "rust1", since = "1.0.0")]
1653     pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1654         where P::Searcher: ReverseSearcher<'a>
1655     {
1656         core_str::StrExt::trim_right_matches(self, pat)
1657     }
1658
1659     /// Parses this string slice into another type.
1660     ///
1661     /// Because `parse` is so general, it can cause problems with type
1662     /// inference. As such, `parse` is one of the few times you'll see
1663     /// the syntax affectionately known as the 'turbofish': `::<>`. This
1664     /// helps the inference algorithm understand specifically which type
1665     /// you're trying to parse into.
1666     ///
1667     /// `parse` can parse any type that implements the [`FromStr`] trait.
1668     ///
1669     /// [`FromStr`]: str/trait.FromStr.html
1670     ///
1671     /// # Errors
1672     ///
1673     /// Will return [`Err`] if it's not possible to parse this string slice into
1674     /// the desired type.
1675     ///
1676     /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
1677     ///
1678     /// # Example
1679     ///
1680     /// Basic usage
1681     ///
1682     /// ```
1683     /// let four: u32 = "4".parse().unwrap();
1684     ///
1685     /// assert_eq!(4, four);
1686     /// ```
1687     ///
1688     /// Using the 'turbofish' instead of annotating `four`:
1689     ///
1690     /// ```
1691     /// let four = "4".parse::<u32>();
1692     ///
1693     /// assert_eq!(Ok(4), four);
1694     /// ```
1695     ///
1696     /// Failing to parse:
1697     ///
1698     /// ```
1699     /// let nope = "j".parse::<u32>();
1700     ///
1701     /// assert!(nope.is_err());
1702     /// ```
1703     #[inline]
1704     #[stable(feature = "rust1", since = "1.0.0")]
1705     pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1706         core_str::StrExt::parse(self)
1707     }
1708
1709     /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
1710     #[unstable(feature = "str_box_extras", issue = "41119")]
1711     pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
1712         self.into()
1713     }
1714
1715     /// Replaces all matches of a pattern with another string.
1716     ///
1717     /// `replace` creates a new [`String`], and copies the data from this string slice into it.
1718     /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1719     /// replaces them with the replacement string slice.
1720     ///
1721     /// [`String`]: string/struct.String.html
1722     ///
1723     /// # Examples
1724     ///
1725     /// Basic usage:
1726     ///
1727     /// ```
1728     /// let s = "this is old";
1729     ///
1730     /// assert_eq!("this is new", s.replace("old", "new"));
1731     /// ```
1732     ///
1733     /// When the pattern doesn't match:
1734     ///
1735     /// ```
1736     /// let s = "this is old";
1737     /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1738     /// ```
1739     #[stable(feature = "rust1", since = "1.0.0")]
1740     pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
1741         let mut result = String::new();
1742         let mut last_end = 0;
1743         for (start, part) in self.match_indices(from) {
1744             result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1745             result.push_str(to);
1746             last_end = start + part.len();
1747         }
1748         result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1749         result
1750     }
1751
1752     /// Replaces first N matches of a pattern with another string.
1753     ///
1754     /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
1755     /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1756     /// replaces them with the replacement string slice at most `count` times.
1757     ///
1758     /// [`String`]: string/struct.String.html
1759     ///
1760     /// # Examples
1761     ///
1762     /// Basic usage:
1763     ///
1764     /// ```
1765     /// let s = "foo foo 123 foo";
1766     /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
1767     /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
1768     /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
1769     /// ```
1770     ///
1771     /// When the pattern doesn't match:
1772     ///
1773     /// ```
1774     /// let s = "this is old";
1775     /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1776     /// ```
1777     #[stable(feature = "str_replacen", since = "1.16.0")]
1778     pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
1779         // Hope to reduce the times of re-allocation
1780         let mut result = String::with_capacity(32);
1781         let mut last_end = 0;
1782         for (start, part) in self.match_indices(pat).take(count) {
1783             result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1784             result.push_str(to);
1785             last_end = start + part.len();
1786         }
1787         result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1788         result
1789     }
1790
1791     /// Returns the lowercase equivalent of this string slice, as a new [`String`].
1792     ///
1793     /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
1794     /// `Lowercase`.
1795     ///
1796     /// Since some characters can expand into multiple characters when changing
1797     /// the case, this function returns a [`String`] instead of modifying the
1798     /// parameter in-place.
1799     ///
1800     /// [`String`]: string/struct.String.html
1801     ///
1802     /// # Examples
1803     ///
1804     /// Basic usage:
1805     ///
1806     /// ```
1807     /// let s = "HELLO";
1808     ///
1809     /// assert_eq!("hello", s.to_lowercase());
1810     /// ```
1811     ///
1812     /// A tricky example, with sigma:
1813     ///
1814     /// ```
1815     /// let sigma = "Σ";
1816     ///
1817     /// assert_eq!("σ", sigma.to_lowercase());
1818     ///
1819     /// // but at the end of a word, it's ς, not σ:
1820     /// let odysseus = "ὈΔΥΣΣΕΎΣ";
1821     ///
1822     /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1823     /// ```
1824     ///
1825     /// Languages without case are not changed:
1826     ///
1827     /// ```
1828     /// let new_year = "农历新年";
1829     ///
1830     /// assert_eq!(new_year, new_year.to_lowercase());
1831     /// ```
1832     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1833     pub fn to_lowercase(&self) -> String {
1834         let mut s = String::with_capacity(self.len());
1835         for (i, c) in self[..].char_indices() {
1836             if c == 'Σ' {
1837                 // Σ maps to σ, except at the end of a word where it maps to ς.
1838                 // This is the only conditional (contextual) but language-independent mapping
1839                 // in `SpecialCasing.txt`,
1840                 // so hard-code it rather than have a generic "condition" mechanism.
1841                 // See https://github.com/rust-lang/rust/issues/26035
1842                 map_uppercase_sigma(self, i, &mut s)
1843             } else {
1844                 s.extend(c.to_lowercase());
1845             }
1846         }
1847         return s;
1848
1849         fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1850             // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1851             // for the definition of `Final_Sigma`.
1852             debug_assert!('Σ'.len_utf8() == 2);
1853             let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
1854                                 !case_ignoreable_then_cased(from[i + 2..].chars());
1855             to.push_str(if is_word_final { "ς" } else { "σ" });
1856         }
1857
1858         fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
1859             use std_unicode::derived_property::{Cased, Case_Ignorable};
1860             match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1861                 Some(c) => Cased(c),
1862                 None => false,
1863             }
1864         }
1865     }
1866
1867     /// Returns the uppercase equivalent of this string slice, as a new [`String`].
1868     ///
1869     /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1870     /// `Uppercase`.
1871     ///
1872     /// Since some characters can expand into multiple characters when changing
1873     /// the case, this function returns a [`String`] instead of modifying the
1874     /// parameter in-place.
1875     ///
1876     /// [`String`]: string/struct.String.html
1877     ///
1878     /// # Examples
1879     ///
1880     /// Basic usage:
1881     ///
1882     /// ```
1883     /// let s = "hello";
1884     ///
1885     /// assert_eq!("HELLO", s.to_uppercase());
1886     /// ```
1887     ///
1888     /// Scripts without case are not changed:
1889     ///
1890     /// ```
1891     /// let new_year = "农历新年";
1892     ///
1893     /// assert_eq!(new_year, new_year.to_uppercase());
1894     /// ```
1895     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1896     pub fn to_uppercase(&self) -> String {
1897         let mut s = String::with_capacity(self.len());
1898         s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1899         return s;
1900     }
1901
1902     /// Escapes each char in `s` with [`char::escape_debug`].
1903     ///
1904     /// [`char::escape_debug`]: primitive.char.html#method.escape_debug
1905     #[unstable(feature = "str_escape",
1906                reason = "return type may change to be an iterator",
1907                issue = "27791")]
1908     pub fn escape_debug(&self) -> String {
1909         self.chars().flat_map(|c| c.escape_debug()).collect()
1910     }
1911
1912     /// Escapes each char in `s` with [`char::escape_default`].
1913     ///
1914     /// [`char::escape_default`]: primitive.char.html#method.escape_default
1915     #[unstable(feature = "str_escape",
1916                reason = "return type may change to be an iterator",
1917                issue = "27791")]
1918     pub fn escape_default(&self) -> String {
1919         self.chars().flat_map(|c| c.escape_default()).collect()
1920     }
1921
1922     /// Escapes each char in `s` with [`char::escape_unicode`].
1923     ///
1924     /// [`char::escape_unicode`]: primitive.char.html#method.escape_unicode
1925     #[unstable(feature = "str_escape",
1926                reason = "return type may change to be an iterator",
1927                issue = "27791")]
1928     pub fn escape_unicode(&self) -> String {
1929         self.chars().flat_map(|c| c.escape_unicode()).collect()
1930     }
1931
1932     /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
1933     ///
1934     /// [`String`]: string/struct.String.html
1935     /// [`Box<str>`]: boxed/struct.Box.html
1936     ///
1937     /// # Examples
1938     ///
1939     /// Basic usage:
1940     ///
1941     /// ```
1942     /// let string = String::from("birthday gift");
1943     /// let boxed_str = string.clone().into_boxed_str();
1944     ///
1945     /// assert_eq!(boxed_str.into_string(), string);
1946     /// ```
1947     #[stable(feature = "box_str", since = "1.4.0")]
1948     pub fn into_string(self: Box<str>) -> String {
1949         unsafe {
1950             let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1951             String::from_utf8_unchecked(slice.into_vec())
1952         }
1953     }
1954
1955     /// Create a [`String`] by repeating a string `n` times.
1956     ///
1957     /// [`String`]: string/struct.String.html
1958     ///
1959     /// # Examples
1960     ///
1961     /// Basic usage:
1962     ///
1963     /// ```
1964     /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
1965     /// ```
1966     #[stable(feature = "repeat_str", since = "1.16.0")]
1967     pub fn repeat(&self, n: usize) -> String {
1968         let mut s = String::with_capacity(self.len() * n);
1969         s.extend((0..n).map(|_| self));
1970         s
1971     }
1972 }