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