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