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