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