]> git.lizzy.rs Git - rust.git/blob - src/liballoc/str.rs
Copy `AsciiExt` methods to `str` directly
[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     /// use std::ascii::AsciiExt;
394     ///
395     /// let mut v = String::from("hello");
396     /// // correct length
397     /// assert!(v.get_mut(0..5).is_some());
398     /// // out of bounds
399     /// assert!(v.get_mut(..42).is_none());
400     /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
401     ///
402     /// assert_eq!("hello", v);
403     /// {
404     ///     let s = v.get_mut(0..2);
405     ///     let s = s.map(|s| {
406     ///         s.make_ascii_uppercase();
407     ///         &*s
408     ///     });
409     ///     assert_eq!(Some("HE"), s);
410     /// }
411     /// assert_eq!("HEllo", v);
412     /// ```
413     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
414     #[inline]
415     pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
416         core_str::StrExt::get_mut(self, i)
417     }
418
419     /// Returns a unchecked subslice of `str`.
420     ///
421     /// This is the unchecked alternative to indexing the `str`.
422     ///
423     /// # Safety
424     ///
425     /// Callers of this function are responsible that these preconditions are
426     /// satisfied:
427     ///
428     /// * The starting index must come before the ending index;
429     /// * Indexes must be within bounds of the original slice;
430     /// * Indexes must lie on UTF-8 sequence boundaries.
431     ///
432     /// Failing that, the returned string slice may reference invalid memory or
433     /// violate the invariants communicated by the `str` type.
434     ///
435     /// # Examples
436     ///
437     /// ```
438     /// let v = "🗻∈🌏";
439     /// unsafe {
440     ///     assert_eq!("🗻", v.get_unchecked(0..4));
441     ///     assert_eq!("∈", v.get_unchecked(4..7));
442     ///     assert_eq!("🌏", v.get_unchecked(7..11));
443     /// }
444     /// ```
445     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
446     #[inline]
447     pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
448         core_str::StrExt::get_unchecked(self, i)
449     }
450
451     /// Returns a mutable, unchecked subslice of `str`.
452     ///
453     /// This is the unchecked alternative to indexing the `str`.
454     ///
455     /// # Safety
456     ///
457     /// Callers of this function are responsible that these preconditions are
458     /// satisfied:
459     ///
460     /// * The starting index must come before the ending index;
461     /// * Indexes must be within bounds of the original slice;
462     /// * Indexes must lie on UTF-8 sequence boundaries.
463     ///
464     /// Failing that, the returned string slice may reference invalid memory or
465     /// violate the invariants communicated by the `str` type.
466     ///
467     /// # Examples
468     ///
469     /// ```
470     /// let mut v = String::from("🗻∈🌏");
471     /// unsafe {
472     ///     assert_eq!("🗻", v.get_unchecked_mut(0..4));
473     ///     assert_eq!("∈", v.get_unchecked_mut(4..7));
474     ///     assert_eq!("🌏", v.get_unchecked_mut(7..11));
475     /// }
476     /// ```
477     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
478     #[inline]
479     pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
480         core_str::StrExt::get_unchecked_mut(self, i)
481     }
482
483     /// Creates a string slice from another string slice, bypassing safety
484     /// checks.
485     ///
486     /// This is generally not recommended, use with caution! For a safe
487     /// alternative see [`str`] and [`Index`].
488     ///
489     /// [`str`]: primitive.str.html
490     /// [`Index`]: ops/trait.Index.html
491     ///
492     /// This new slice goes from `begin` to `end`, including `begin` but
493     /// excluding `end`.
494     ///
495     /// To get a mutable string slice instead, see the
496     /// [`slice_mut_unchecked`] method.
497     ///
498     /// [`slice_mut_unchecked`]: #method.slice_mut_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     ///
509     /// # Examples
510     ///
511     /// Basic usage:
512     ///
513     /// ```
514     /// let s = "Löwe 老虎 Léopard";
515     ///
516     /// unsafe {
517     ///     assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
518     /// }
519     ///
520     /// let s = "Hello, world!";
521     ///
522     /// unsafe {
523     ///     assert_eq!("world", s.slice_unchecked(7, 12));
524     /// }
525     /// ```
526     #[stable(feature = "rust1", since = "1.0.0")]
527     #[inline]
528     pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
529         core_str::StrExt::slice_unchecked(self, begin, end)
530     }
531
532     /// Creates a string slice from another string slice, bypassing safety
533     /// checks.
534     /// This is generally not recommended, use with caution! For a safe
535     /// alternative see [`str`] and [`IndexMut`].
536     ///
537     /// [`str`]: primitive.str.html
538     /// [`IndexMut`]: ops/trait.IndexMut.html
539     ///
540     /// This new slice goes from `begin` to `end`, including `begin` but
541     /// excluding `end`.
542     ///
543     /// To get an immutable string slice instead, see the
544     /// [`slice_unchecked`] method.
545     ///
546     /// [`slice_unchecked`]: #method.slice_unchecked
547     ///
548     /// # Safety
549     ///
550     /// Callers of this function are responsible that three preconditions are
551     /// satisfied:
552     ///
553     /// * `begin` must come before `end`.
554     /// * `begin` and `end` must be byte positions within the string slice.
555     /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
556     #[stable(feature = "str_slice_mut", since = "1.5.0")]
557     #[inline]
558     pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
559         core_str::StrExt::slice_mut_unchecked(self, begin, end)
560     }
561
562     /// Divide one string slice into two at an index.
563     ///
564     /// The argument, `mid`, should be a byte offset from the start of the
565     /// string. It must also be on the boundary of a UTF-8 code point.
566     ///
567     /// The two slices returned go from the start of the string slice to `mid`,
568     /// and from `mid` to the end of the string slice.
569     ///
570     /// To get mutable string slices instead, see the [`split_at_mut`]
571     /// method.
572     ///
573     /// [`split_at_mut`]: #method.split_at_mut
574     ///
575     /// # Panics
576     ///
577     /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
578     /// beyond the last code point of the string slice.
579     ///
580     /// # Examples
581     ///
582     /// Basic usage:
583     ///
584     /// ```
585     /// let s = "Per Martin-Löf";
586     ///
587     /// let (first, last) = s.split_at(3);
588     ///
589     /// assert_eq!("Per", first);
590     /// assert_eq!(" Martin-Löf", last);
591     /// ```
592     #[inline]
593     #[stable(feature = "str_split_at", since = "1.4.0")]
594     pub fn split_at(&self, mid: usize) -> (&str, &str) {
595         core_str::StrExt::split_at(self, mid)
596     }
597
598     /// Divide one mutable string slice into two at an index.
599     ///
600     /// The argument, `mid`, should be a byte offset from the start of the
601     /// string. It must also be on the boundary of a UTF-8 code point.
602     ///
603     /// The two slices returned go from the start of the string slice to `mid`,
604     /// and from `mid` to the end of the string slice.
605     ///
606     /// To get immutable string slices instead, see the [`split_at`] method.
607     ///
608     /// [`split_at`]: #method.split_at
609     ///
610     /// # Panics
611     ///
612     /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
613     /// beyond the last code point of the string slice.
614     ///
615     /// # Examples
616     ///
617     /// Basic usage:
618     ///
619     /// ```
620     /// use std::ascii::AsciiExt;
621     ///
622     /// let mut s = "Per Martin-Löf".to_string();
623     /// {
624     ///     let (first, last) = s.split_at_mut(3);
625     ///     first.make_ascii_uppercase();
626     ///     assert_eq!("PER", first);
627     ///     assert_eq!(" Martin-Löf", last);
628     /// }
629     /// assert_eq!("PER Martin-Löf", s);
630     /// ```
631     #[inline]
632     #[stable(feature = "str_split_at", since = "1.4.0")]
633     pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
634         core_str::StrExt::split_at_mut(self, mid)
635     }
636
637     /// Returns an iterator over the [`char`]s of a string slice.
638     ///
639     /// As a string slice consists of valid UTF-8, we can iterate through a
640     /// string slice by [`char`]. This method returns such an iterator.
641     ///
642     /// It's important to remember that [`char`] represents a Unicode Scalar
643     /// Value, and may not match your idea of what a 'character' is. Iteration
644     /// over grapheme clusters may be what you actually want.
645     ///
646     /// [`char`]: primitive.char.html
647     ///
648     /// # Examples
649     ///
650     /// Basic usage:
651     ///
652     /// ```
653     /// let word = "goodbye";
654     ///
655     /// let count = word.chars().count();
656     /// assert_eq!(7, count);
657     ///
658     /// let mut chars = word.chars();
659     ///
660     /// assert_eq!(Some('g'), chars.next());
661     /// assert_eq!(Some('o'), chars.next());
662     /// assert_eq!(Some('o'), chars.next());
663     /// assert_eq!(Some('d'), chars.next());
664     /// assert_eq!(Some('b'), chars.next());
665     /// assert_eq!(Some('y'), chars.next());
666     /// assert_eq!(Some('e'), chars.next());
667     ///
668     /// assert_eq!(None, chars.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 chars = y.chars();
677     ///
678     /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
679     /// assert_eq!(Some('\u{0306}'), chars.next());
680     ///
681     /// assert_eq!(None, chars.next());
682     /// ```
683     #[stable(feature = "rust1", since = "1.0.0")]
684     #[inline]
685     pub fn chars(&self) -> Chars {
686         core_str::StrExt::chars(self)
687     }
688     /// Returns an iterator over the [`char`]s of a string slice, and their
689     /// positions.
690     ///
691     /// As a string slice consists of valid UTF-8, we can iterate through a
692     /// string slice by [`char`]. This method returns an iterator of both
693     /// these [`char`]s, as well as their byte positions.
694     ///
695     /// The iterator yields tuples. The position is first, the [`char`] is
696     /// second.
697     ///
698     /// [`char`]: primitive.char.html
699     ///
700     /// # Examples
701     ///
702     /// Basic usage:
703     ///
704     /// ```
705     /// let word = "goodbye";
706     ///
707     /// let count = word.char_indices().count();
708     /// assert_eq!(7, count);
709     ///
710     /// let mut char_indices = word.char_indices();
711     ///
712     /// assert_eq!(Some((0, 'g')), char_indices.next());
713     /// assert_eq!(Some((1, 'o')), char_indices.next());
714     /// assert_eq!(Some((2, 'o')), char_indices.next());
715     /// assert_eq!(Some((3, 'd')), char_indices.next());
716     /// assert_eq!(Some((4, 'b')), char_indices.next());
717     /// assert_eq!(Some((5, 'y')), char_indices.next());
718     /// assert_eq!(Some((6, 'e')), char_indices.next());
719     ///
720     /// assert_eq!(None, char_indices.next());
721     /// ```
722     ///
723     /// Remember, [`char`]s may not match your human intuition about characters:
724     ///
725     /// ```
726     /// let y = "y̆";
727     ///
728     /// let mut char_indices = y.char_indices();
729     ///
730     /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
731     /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
732     ///
733     /// assert_eq!(None, char_indices.next());
734     /// ```
735     #[stable(feature = "rust1", since = "1.0.0")]
736     #[inline]
737     pub fn char_indices(&self) -> CharIndices {
738         core_str::StrExt::char_indices(self)
739     }
740
741     /// An iterator over the bytes of a string slice.
742     ///
743     /// As a string slice consists of a sequence of bytes, we can iterate
744     /// through a string slice by byte. This method returns such an iterator.
745     ///
746     /// # Examples
747     ///
748     /// Basic usage:
749     ///
750     /// ```
751     /// let mut bytes = "bors".bytes();
752     ///
753     /// assert_eq!(Some(b'b'), bytes.next());
754     /// assert_eq!(Some(b'o'), bytes.next());
755     /// assert_eq!(Some(b'r'), bytes.next());
756     /// assert_eq!(Some(b's'), bytes.next());
757     ///
758     /// assert_eq!(None, bytes.next());
759     /// ```
760     #[stable(feature = "rust1", since = "1.0.0")]
761     #[inline]
762     pub fn bytes(&self) -> Bytes {
763         core_str::StrExt::bytes(self)
764     }
765
766     /// Split a string slice by whitespace.
767     ///
768     /// The iterator returned will return string slices that are sub-slices of
769     /// the original string slice, separated by any amount of whitespace.
770     ///
771     /// 'Whitespace' is defined according to the terms of the Unicode Derived
772     /// Core Property `White_Space`.
773     ///
774     /// # Examples
775     ///
776     /// Basic usage:
777     ///
778     /// ```
779     /// let mut iter = "A few words".split_whitespace();
780     ///
781     /// assert_eq!(Some("A"), iter.next());
782     /// assert_eq!(Some("few"), iter.next());
783     /// assert_eq!(Some("words"), iter.next());
784     ///
785     /// assert_eq!(None, iter.next());
786     /// ```
787     ///
788     /// All kinds of whitespace are considered:
789     ///
790     /// ```
791     /// let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
792     /// assert_eq!(Some("Mary"), iter.next());
793     /// assert_eq!(Some("had"), iter.next());
794     /// assert_eq!(Some("a"), iter.next());
795     /// assert_eq!(Some("little"), iter.next());
796     /// assert_eq!(Some("lamb"), iter.next());
797     ///
798     /// assert_eq!(None, iter.next());
799     /// ```
800     #[stable(feature = "split_whitespace", since = "1.1.0")]
801     #[inline]
802     pub fn split_whitespace(&self) -> SplitWhitespace {
803         UnicodeStr::split_whitespace(self)
804     }
805
806     /// An iterator over the lines of a string, as string slices.
807     ///
808     /// Lines are ended with either a newline (`\n`) or a carriage return with
809     /// a line feed (`\r\n`).
810     ///
811     /// The final line ending is optional.
812     ///
813     /// # Examples
814     ///
815     /// Basic usage:
816     ///
817     /// ```
818     /// let text = "foo\r\nbar\n\nbaz\n";
819     /// let mut lines = text.lines();
820     ///
821     /// assert_eq!(Some("foo"), lines.next());
822     /// assert_eq!(Some("bar"), lines.next());
823     /// assert_eq!(Some(""), lines.next());
824     /// assert_eq!(Some("baz"), lines.next());
825     ///
826     /// assert_eq!(None, lines.next());
827     /// ```
828     ///
829     /// The final line ending isn't required:
830     ///
831     /// ```
832     /// let text = "foo\nbar\n\r\nbaz";
833     /// let mut lines = text.lines();
834     ///
835     /// assert_eq!(Some("foo"), lines.next());
836     /// assert_eq!(Some("bar"), lines.next());
837     /// assert_eq!(Some(""), lines.next());
838     /// assert_eq!(Some("baz"), lines.next());
839     ///
840     /// assert_eq!(None, lines.next());
841     /// ```
842     #[stable(feature = "rust1", since = "1.0.0")]
843     #[inline]
844     pub fn lines(&self) -> Lines {
845         core_str::StrExt::lines(self)
846     }
847
848     /// An iterator over the lines of a string.
849     #[stable(feature = "rust1", since = "1.0.0")]
850     #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
851     #[inline]
852     #[allow(deprecated)]
853     pub fn lines_any(&self) -> LinesAny {
854         core_str::StrExt::lines_any(self)
855     }
856
857     /// Returns an iterator of `u16` over the string encoded as UTF-16.
858     ///
859     /// # Examples
860     ///
861     /// Basic usage:
862     ///
863     /// ```
864     /// let text = "Zażółć gęślą jaźń";
865     ///
866     /// let utf8_len = text.len();
867     /// let utf16_len = text.encode_utf16().count();
868     ///
869     /// assert!(utf16_len <= utf8_len);
870     /// ```
871     #[stable(feature = "encode_utf16", since = "1.8.0")]
872     pub fn encode_utf16(&self) -> EncodeUtf16 {
873         EncodeUtf16 { encoder: Utf16Encoder::new(self[..].chars()) }
874     }
875
876     /// Returns `true` if the given pattern matches a sub-slice of
877     /// this string slice.
878     ///
879     /// Returns `false` if it does not.
880     ///
881     /// # Examples
882     ///
883     /// Basic usage:
884     ///
885     /// ```
886     /// let bananas = "bananas";
887     ///
888     /// assert!(bananas.contains("nana"));
889     /// assert!(!bananas.contains("apples"));
890     /// ```
891     #[stable(feature = "rust1", since = "1.0.0")]
892     #[inline]
893     pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
894         core_str::StrExt::contains(self, pat)
895     }
896
897     /// Returns `true` if the given pattern matches a prefix of this
898     /// string slice.
899     ///
900     /// Returns `false` if it does not.
901     ///
902     /// # Examples
903     ///
904     /// Basic usage:
905     ///
906     /// ```
907     /// let bananas = "bananas";
908     ///
909     /// assert!(bananas.starts_with("bana"));
910     /// assert!(!bananas.starts_with("nana"));
911     /// ```
912     #[stable(feature = "rust1", since = "1.0.0")]
913     pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
914         core_str::StrExt::starts_with(self, pat)
915     }
916
917     /// Returns `true` if the given pattern matches a suffix of this
918     /// string slice.
919     ///
920     /// Returns `false` if it does not.
921     ///
922     /// # Examples
923     ///
924     /// Basic usage:
925     ///
926     /// ```
927     /// let bananas = "bananas";
928     ///
929     /// assert!(bananas.ends_with("anas"));
930     /// assert!(!bananas.ends_with("nana"));
931     /// ```
932     #[stable(feature = "rust1", since = "1.0.0")]
933     pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
934         where P::Searcher: ReverseSearcher<'a>
935     {
936         core_str::StrExt::ends_with(self, pat)
937     }
938
939     /// Returns the byte index of the first character of this string slice that
940     /// matches the pattern.
941     ///
942     /// Returns [`None`] if the pattern doesn't match.
943     ///
944     /// The pattern can be a `&str`, [`char`], or a closure that determines if
945     /// a character matches.
946     ///
947     /// [`char`]: primitive.char.html
948     /// [`None`]: option/enum.Option.html#variant.None
949     ///
950     /// # Examples
951     ///
952     /// Simple patterns:
953     ///
954     /// ```
955     /// let s = "Löwe 老虎 Léopard";
956     ///
957     /// assert_eq!(s.find('L'), Some(0));
958     /// assert_eq!(s.find('é'), Some(14));
959     /// assert_eq!(s.find("Léopard"), Some(13));
960     /// ```
961     ///
962     /// More complex patterns using point-free style and closures:
963     ///
964     /// ```
965     /// let s = "Löwe 老虎 Léopard";
966     ///
967     /// assert_eq!(s.find(char::is_whitespace), Some(5));
968     /// assert_eq!(s.find(char::is_lowercase), Some(1));
969     /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
970     /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
971     /// ```
972     ///
973     /// Not finding the pattern:
974     ///
975     /// ```
976     /// let s = "Löwe 老虎 Léopard";
977     /// let x: &[_] = &['1', '2'];
978     ///
979     /// assert_eq!(s.find(x), None);
980     /// ```
981     #[stable(feature = "rust1", since = "1.0.0")]
982     #[inline]
983     pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
984         core_str::StrExt::find(self, pat)
985     }
986
987     /// Returns the byte index of the last character of this string slice that
988     /// matches the pattern.
989     ///
990     /// Returns [`None`] if the pattern doesn't match.
991     ///
992     /// The pattern can be a `&str`, [`char`], or a closure that determines if
993     /// a character matches.
994     ///
995     /// [`char`]: primitive.char.html
996     /// [`None`]: option/enum.Option.html#variant.None
997     ///
998     /// # Examples
999     ///
1000     /// Simple patterns:
1001     ///
1002     /// ```
1003     /// let s = "Löwe 老虎 Léopard";
1004     ///
1005     /// assert_eq!(s.rfind('L'), Some(13));
1006     /// assert_eq!(s.rfind('é'), Some(14));
1007     /// ```
1008     ///
1009     /// More complex patterns with closures:
1010     ///
1011     /// ```
1012     /// let s = "Löwe 老虎 Léopard";
1013     ///
1014     /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1015     /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1016     /// ```
1017     ///
1018     /// Not finding the pattern:
1019     ///
1020     /// ```
1021     /// let s = "Löwe 老虎 Léopard";
1022     /// let x: &[_] = &['1', '2'];
1023     ///
1024     /// assert_eq!(s.rfind(x), None);
1025     /// ```
1026     #[stable(feature = "rust1", since = "1.0.0")]
1027     #[inline]
1028     pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1029         where P::Searcher: ReverseSearcher<'a>
1030     {
1031         core_str::StrExt::rfind(self, pat)
1032     }
1033
1034     /// An iterator over substrings of this string slice, separated by
1035     /// characters matched by a pattern.
1036     ///
1037     /// The pattern can be a `&str`, [`char`], or a closure that determines the
1038     /// split.
1039     ///
1040     /// # Iterator behavior
1041     ///
1042     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1043     /// allows a reverse search and forward/reverse search yields the same
1044     /// elements. This is true for, eg, [`char`] but not for `&str`.
1045     ///
1046     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1047     ///
1048     /// If the pattern allows a reverse search but its results might differ
1049     /// from a forward search, the [`rsplit`] method can be used.
1050     ///
1051     /// [`char`]: primitive.char.html
1052     /// [`rsplit`]: #method.rsplit
1053     ///
1054     /// # Examples
1055     ///
1056     /// Simple patterns:
1057     ///
1058     /// ```
1059     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1060     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1061     ///
1062     /// let v: Vec<&str> = "".split('X').collect();
1063     /// assert_eq!(v, [""]);
1064     ///
1065     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1066     /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1067     ///
1068     /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1069     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1070     ///
1071     /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1072     /// assert_eq!(v, ["abc", "def", "ghi"]);
1073     ///
1074     /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1075     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1076     /// ```
1077     ///
1078     /// A more complex pattern, using a closure:
1079     ///
1080     /// ```
1081     /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1082     /// assert_eq!(v, ["abc", "def", "ghi"]);
1083     /// ```
1084     ///
1085     /// If a string contains multiple contiguous separators, you will end up
1086     /// with empty strings in the output:
1087     ///
1088     /// ```
1089     /// let x = "||||a||b|c".to_string();
1090     /// let d: Vec<_> = x.split('|').collect();
1091     ///
1092     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1093     /// ```
1094     ///
1095     /// Contiguous separators are separated by the empty string.
1096     ///
1097     /// ```
1098     /// let x = "(///)".to_string();
1099     /// let d: Vec<_> = x.split('/').collect();
1100     ///
1101     /// assert_eq!(d, &["(", "", "", ")"]);
1102     /// ```
1103     ///
1104     /// Separators at the start or end of a string are neighbored
1105     /// by empty strings.
1106     ///
1107     /// ```
1108     /// let d: Vec<_> = "010".split("0").collect();
1109     /// assert_eq!(d, &["", "1", ""]);
1110     /// ```
1111     ///
1112     /// When the empty string is used as a separator, it separates
1113     /// every character in the string, along with the beginning
1114     /// and end of the string.
1115     ///
1116     /// ```
1117     /// let f: Vec<_> = "rust".split("").collect();
1118     /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1119     /// ```
1120     ///
1121     /// Contiguous separators can lead to possibly surprising behavior
1122     /// when whitespace is used as the separator. This code is correct:
1123     ///
1124     /// ```
1125     /// let x = "    a  b c".to_string();
1126     /// let d: Vec<_> = x.split(' ').collect();
1127     ///
1128     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1129     /// ```
1130     ///
1131     /// It does _not_ give you:
1132     ///
1133     /// ```,ignore
1134     /// assert_eq!(d, &["a", "b", "c"]);
1135     /// ```
1136     ///
1137     /// Use [`split_whitespace`] for this behavior.
1138     ///
1139     /// [`split_whitespace`]: #method.split_whitespace
1140     #[stable(feature = "rust1", since = "1.0.0")]
1141     #[inline]
1142     pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1143         core_str::StrExt::split(self, pat)
1144     }
1145
1146     /// An iterator over substrings of the given string slice, separated by
1147     /// characters matched by a pattern and yielded in reverse order.
1148     ///
1149     /// The pattern can be a `&str`, [`char`], or a closure that determines the
1150     /// split.
1151     ///
1152     /// [`char`]: primitive.char.html
1153     ///
1154     /// # Iterator behavior
1155     ///
1156     /// The returned iterator requires that the pattern supports a reverse
1157     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1158     /// search yields the same elements.
1159     ///
1160     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1161     ///
1162     /// For iterating from the front, the [`split`] method can be used.
1163     ///
1164     /// [`split`]: #method.split
1165     ///
1166     /// # Examples
1167     ///
1168     /// Simple patterns:
1169     ///
1170     /// ```
1171     /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1172     /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1173     ///
1174     /// let v: Vec<&str> = "".rsplit('X').collect();
1175     /// assert_eq!(v, [""]);
1176     ///
1177     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1178     /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1179     ///
1180     /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1181     /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1182     /// ```
1183     ///
1184     /// A more complex pattern, using a closure:
1185     ///
1186     /// ```
1187     /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1188     /// assert_eq!(v, ["ghi", "def", "abc"]);
1189     /// ```
1190     #[stable(feature = "rust1", since = "1.0.0")]
1191     #[inline]
1192     pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1193         where P::Searcher: ReverseSearcher<'a>
1194     {
1195         core_str::StrExt::rsplit(self, pat)
1196     }
1197
1198     /// An iterator over substrings of the given string slice, separated by
1199     /// characters matched by a pattern.
1200     ///
1201     /// The pattern can be a `&str`, [`char`], or a closure that determines the
1202     /// split.
1203     ///
1204     /// Equivalent to [`split`], except that the trailing substring
1205     /// is skipped if empty.
1206     ///
1207     /// [`split`]: #method.split
1208     ///
1209     /// This method can be used for string data that is _terminated_,
1210     /// rather than _separated_ by a pattern.
1211     ///
1212     /// # Iterator behavior
1213     ///
1214     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1215     /// allows a reverse search and forward/reverse search yields the same
1216     /// elements. This is true for, eg, [`char`] but not for `&str`.
1217     ///
1218     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1219     /// [`char`]: primitive.char.html
1220     ///
1221     /// If the pattern allows a reverse search but its results might differ
1222     /// from a forward search, the [`rsplit_terminator`] method can be used.
1223     ///
1224     /// [`rsplit_terminator`]: #method.rsplit_terminator
1225     ///
1226     /// # Examples
1227     ///
1228     /// Basic usage:
1229     ///
1230     /// ```
1231     /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1232     /// assert_eq!(v, ["A", "B"]);
1233     ///
1234     /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1235     /// assert_eq!(v, ["A", "", "B", ""]);
1236     /// ```
1237     #[stable(feature = "rust1", since = "1.0.0")]
1238     #[inline]
1239     pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1240         core_str::StrExt::split_terminator(self, pat)
1241     }
1242
1243     /// An iterator over substrings of `self`, separated by characters
1244     /// matched by a pattern and yielded in reverse order.
1245     ///
1246     /// The pattern can be a simple `&str`, [`char`], or a closure that
1247     /// determines the split.
1248     /// Additional libraries might provide more complex patterns like
1249     /// regular expressions.
1250     ///
1251     /// [`char`]: primitive.char.html
1252     ///
1253     /// Equivalent to [`split`], except that the trailing substring is
1254     /// skipped if empty.
1255     ///
1256     /// [`split`]: #method.split
1257     ///
1258     /// This method can be used for string data that is _terminated_,
1259     /// rather than _separated_ by a pattern.
1260     ///
1261     /// # Iterator behavior
1262     ///
1263     /// The returned iterator requires that the pattern supports a
1264     /// reverse search, and it will be double ended if a forward/reverse
1265     /// search yields the same elements.
1266     ///
1267     /// For iterating from the front, the [`split_terminator`] method can be
1268     /// used.
1269     ///
1270     /// [`split_terminator`]: #method.split_terminator
1271     ///
1272     /// # Examples
1273     ///
1274     /// ```
1275     /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1276     /// assert_eq!(v, ["B", "A"]);
1277     ///
1278     /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1279     /// assert_eq!(v, ["", "B", "", "A"]);
1280     /// ```
1281     #[stable(feature = "rust1", since = "1.0.0")]
1282     #[inline]
1283     pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1284         where P::Searcher: ReverseSearcher<'a>
1285     {
1286         core_str::StrExt::rsplit_terminator(self, pat)
1287     }
1288
1289     /// An iterator over substrings of the given string slice, separated by a
1290     /// pattern, restricted to returning at most `n` items.
1291     ///
1292     /// If `n` substrings are returned, the last substring (the `n`th substring)
1293     /// will contain the remainder of the string.
1294     ///
1295     /// The pattern can be a `&str`, [`char`], or a closure that determines the
1296     /// split.
1297     ///
1298     /// [`char`]: primitive.char.html
1299     ///
1300     /// # Iterator behavior
1301     ///
1302     /// The returned iterator will not be double ended, because it is
1303     /// not efficient to support.
1304     ///
1305     /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1306     /// used.
1307     ///
1308     /// [`rsplitn`]: #method.rsplitn
1309     ///
1310     /// # Examples
1311     ///
1312     /// Simple patterns:
1313     ///
1314     /// ```
1315     /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1316     /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1317     ///
1318     /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1319     /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1320     ///
1321     /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1322     /// assert_eq!(v, ["abcXdef"]);
1323     ///
1324     /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1325     /// assert_eq!(v, [""]);
1326     /// ```
1327     ///
1328     /// A more complex pattern, using a closure:
1329     ///
1330     /// ```
1331     /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1332     /// assert_eq!(v, ["abc", "defXghi"]);
1333     /// ```
1334     #[stable(feature = "rust1", since = "1.0.0")]
1335     #[inline]
1336     pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1337         core_str::StrExt::splitn(self, n, pat)
1338     }
1339
1340     /// An iterator over substrings of this string slice, separated by a
1341     /// pattern, starting from the end of the string, restricted to returning
1342     /// at most `n` items.
1343     ///
1344     /// If `n` substrings are returned, the last substring (the `n`th substring)
1345     /// will contain the remainder of the string.
1346     ///
1347     /// The pattern can be a `&str`, [`char`], or a closure that
1348     /// determines the split.
1349     ///
1350     /// [`char`]: primitive.char.html
1351     ///
1352     /// # Iterator behavior
1353     ///
1354     /// The returned iterator will not be double ended, because it is not
1355     /// efficient to support.
1356     ///
1357     /// For splitting from the front, the [`splitn`] method can be used.
1358     ///
1359     /// [`splitn`]: #method.splitn
1360     ///
1361     /// # Examples
1362     ///
1363     /// Simple patterns:
1364     ///
1365     /// ```
1366     /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1367     /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1368     ///
1369     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1370     /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1371     ///
1372     /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1373     /// assert_eq!(v, ["leopard", "lion::tiger"]);
1374     /// ```
1375     ///
1376     /// A more complex pattern, using a closure:
1377     ///
1378     /// ```
1379     /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1380     /// assert_eq!(v, ["ghi", "abc1def"]);
1381     /// ```
1382     #[stable(feature = "rust1", since = "1.0.0")]
1383     #[inline]
1384     pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1385         where P::Searcher: ReverseSearcher<'a>
1386     {
1387         core_str::StrExt::rsplitn(self, n, pat)
1388     }
1389
1390     /// An iterator over the disjoint matches of a pattern within the given string
1391     /// slice.
1392     ///
1393     /// The pattern can be a `&str`, [`char`], or a closure that
1394     /// determines if a character matches.
1395     ///
1396     /// [`char`]: primitive.char.html
1397     ///
1398     /// # Iterator behavior
1399     ///
1400     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1401     /// allows a reverse search and forward/reverse search yields the same
1402     /// elements. This is true for, eg, [`char`] but not for `&str`.
1403     ///
1404     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1405     /// [`char`]: primitive.char.html
1406     ///
1407     /// If the pattern allows a reverse search but its results might differ
1408     /// from a forward search, the [`rmatches`] method can be used.
1409     ///
1410     /// [`rmatches`]: #method.rmatches
1411     ///
1412     /// # Examples
1413     ///
1414     /// Basic usage:
1415     ///
1416     /// ```
1417     /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1418     /// assert_eq!(v, ["abc", "abc", "abc"]);
1419     ///
1420     /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1421     /// assert_eq!(v, ["1", "2", "3"]);
1422     /// ```
1423     #[stable(feature = "str_matches", since = "1.2.0")]
1424     #[inline]
1425     pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1426         core_str::StrExt::matches(self, pat)
1427     }
1428
1429     /// An iterator over the disjoint matches of a pattern within this string slice,
1430     /// yielded in reverse order.
1431     ///
1432     /// The pattern can be a `&str`, [`char`], or a closure that determines if
1433     /// a character matches.
1434     ///
1435     /// [`char`]: primitive.char.html
1436     ///
1437     /// # Iterator behavior
1438     ///
1439     /// The returned iterator requires that the pattern supports a reverse
1440     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1441     /// search yields the same elements.
1442     ///
1443     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1444     ///
1445     /// For iterating from the front, the [`matches`] method can be used.
1446     ///
1447     /// [`matches`]: #method.matches
1448     ///
1449     /// # Examples
1450     ///
1451     /// Basic usage:
1452     ///
1453     /// ```
1454     /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1455     /// assert_eq!(v, ["abc", "abc", "abc"]);
1456     ///
1457     /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1458     /// assert_eq!(v, ["3", "2", "1"]);
1459     /// ```
1460     #[stable(feature = "str_matches", since = "1.2.0")]
1461     #[inline]
1462     pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1463         where P::Searcher: ReverseSearcher<'a>
1464     {
1465         core_str::StrExt::rmatches(self, pat)
1466     }
1467
1468     /// An iterator over the disjoint matches of a pattern within this string
1469     /// slice as well as the index that the match starts at.
1470     ///
1471     /// For matches of `pat` within `self` that overlap, only the indices
1472     /// corresponding to the first match are returned.
1473     ///
1474     /// The pattern can be a `&str`, [`char`], or a closure that determines
1475     /// if a character matches.
1476     ///
1477     /// [`char`]: primitive.char.html
1478     ///
1479     /// # Iterator behavior
1480     ///
1481     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1482     /// allows a reverse search and forward/reverse search yields the same
1483     /// elements. This is true for, eg, [`char`] but not for `&str`.
1484     ///
1485     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1486     ///
1487     /// If the pattern allows a reverse search but its results might differ
1488     /// from a forward search, the [`rmatch_indices`] method can be used.
1489     ///
1490     /// [`rmatch_indices`]: #method.rmatch_indices
1491     ///
1492     /// # Examples
1493     ///
1494     /// Basic usage:
1495     ///
1496     /// ```
1497     /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1498     /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1499     ///
1500     /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1501     /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1502     ///
1503     /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1504     /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1505     /// ```
1506     #[stable(feature = "str_match_indices", since = "1.5.0")]
1507     #[inline]
1508     pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1509         core_str::StrExt::match_indices(self, pat)
1510     }
1511
1512     /// An iterator over the disjoint matches of a pattern within `self`,
1513     /// yielded in reverse order along with the index of the match.
1514     ///
1515     /// For matches of `pat` within `self` that overlap, only the indices
1516     /// corresponding to the last match are returned.
1517     ///
1518     /// The pattern can be a `&str`, [`char`], or a closure that determines if a
1519     /// character matches.
1520     ///
1521     /// [`char`]: primitive.char.html
1522     ///
1523     /// # Iterator behavior
1524     ///
1525     /// The returned iterator requires that the pattern supports a reverse
1526     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1527     /// search yields the same elements.
1528     ///
1529     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1530     ///
1531     /// For iterating from the front, the [`match_indices`] method can be used.
1532     ///
1533     /// [`match_indices`]: #method.match_indices
1534     ///
1535     /// # Examples
1536     ///
1537     /// Basic usage:
1538     ///
1539     /// ```
1540     /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1541     /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1542     ///
1543     /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1544     /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1545     ///
1546     /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1547     /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1548     /// ```
1549     #[stable(feature = "str_match_indices", since = "1.5.0")]
1550     #[inline]
1551     pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1552         where P::Searcher: ReverseSearcher<'a>
1553     {
1554         core_str::StrExt::rmatch_indices(self, pat)
1555     }
1556
1557     /// Returns a string slice with leading and trailing whitespace removed.
1558     ///
1559     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1560     /// Core Property `White_Space`.
1561     ///
1562     /// # Examples
1563     ///
1564     /// Basic usage:
1565     ///
1566     /// ```
1567     /// let s = " Hello\tworld\t";
1568     ///
1569     /// assert_eq!("Hello\tworld", s.trim());
1570     /// ```
1571     #[stable(feature = "rust1", since = "1.0.0")]
1572     pub fn trim(&self) -> &str {
1573         UnicodeStr::trim(self)
1574     }
1575
1576     /// Returns a string slice with leading whitespace removed.
1577     ///
1578     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1579     /// Core Property `White_Space`.
1580     ///
1581     /// # Text directionality
1582     ///
1583     /// A string is a sequence of bytes. 'Left' in this context means the first
1584     /// position of that byte string; for a language like Arabic or Hebrew
1585     /// which are 'right to left' rather than 'left to right', this will be
1586     /// the _right_ side, not the left.
1587     ///
1588     /// # Examples
1589     ///
1590     /// Basic usage:
1591     ///
1592     /// ```
1593     /// let s = " Hello\tworld\t";
1594     ///
1595     /// assert_eq!("Hello\tworld\t", s.trim_left());
1596     /// ```
1597     ///
1598     /// Directionality:
1599     ///
1600     /// ```
1601     /// let s = "  English";
1602     /// assert!(Some('E') == s.trim_left().chars().next());
1603     ///
1604     /// let s = "  עברית";
1605     /// assert!(Some('ע') == s.trim_left().chars().next());
1606     /// ```
1607     #[stable(feature = "rust1", since = "1.0.0")]
1608     pub fn trim_left(&self) -> &str {
1609         UnicodeStr::trim_left(self)
1610     }
1611
1612     /// Returns a string slice with trailing whitespace removed.
1613     ///
1614     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1615     /// Core Property `White_Space`.
1616     ///
1617     /// # Text directionality
1618     ///
1619     /// A string is a sequence of bytes. 'Right' in this context means the last
1620     /// position of that byte string; for a language like Arabic or Hebrew
1621     /// which are 'right to left' rather than 'left to right', this will be
1622     /// the _left_ side, not the right.
1623     ///
1624     /// # Examples
1625     ///
1626     /// Basic usage:
1627     ///
1628     /// ```
1629     /// let s = " Hello\tworld\t";
1630     ///
1631     /// assert_eq!(" Hello\tworld", s.trim_right());
1632     /// ```
1633     ///
1634     /// Directionality:
1635     ///
1636     /// ```
1637     /// let s = "English  ";
1638     /// assert!(Some('h') == s.trim_right().chars().rev().next());
1639     ///
1640     /// let s = "עברית  ";
1641     /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1642     /// ```
1643     #[stable(feature = "rust1", since = "1.0.0")]
1644     pub fn trim_right(&self) -> &str {
1645         UnicodeStr::trim_right(self)
1646     }
1647
1648     /// Returns a string slice with all prefixes and suffixes that match a
1649     /// pattern repeatedly removed.
1650     ///
1651     /// The pattern can be a [`char`] or a closure that determines if a
1652     /// character matches.
1653     ///
1654     /// [`char`]: primitive.char.html
1655     ///
1656     /// # Examples
1657     ///
1658     /// Simple patterns:
1659     ///
1660     /// ```
1661     /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1662     /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1663     ///
1664     /// let x: &[_] = &['1', '2'];
1665     /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1666     /// ```
1667     ///
1668     /// A more complex pattern, using a closure:
1669     ///
1670     /// ```
1671     /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1672     /// ```
1673     #[stable(feature = "rust1", since = "1.0.0")]
1674     pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1675         where P::Searcher: DoubleEndedSearcher<'a>
1676     {
1677         core_str::StrExt::trim_matches(self, pat)
1678     }
1679
1680     /// Returns a string slice with all prefixes that match a pattern
1681     /// repeatedly removed.
1682     ///
1683     /// The pattern can be a `&str`, [`char`], or a closure that determines if
1684     /// a character matches.
1685     ///
1686     /// [`char`]: primitive.char.html
1687     ///
1688     /// # Text directionality
1689     ///
1690     /// A string is a sequence of bytes. 'Left' in this context means the first
1691     /// position of that byte string; for a language like Arabic or Hebrew
1692     /// which are 'right to left' rather than 'left to right', this will be
1693     /// the _right_ side, not the left.
1694     ///
1695     /// # Examples
1696     ///
1697     /// Basic usage:
1698     ///
1699     /// ```
1700     /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1701     /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1702     ///
1703     /// let x: &[_] = &['1', '2'];
1704     /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1705     /// ```
1706     #[stable(feature = "rust1", since = "1.0.0")]
1707     pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1708         core_str::StrExt::trim_left_matches(self, pat)
1709     }
1710
1711     /// Returns a string slice with all suffixes that match a pattern
1712     /// repeatedly removed.
1713     ///
1714     /// The pattern can be a `&str`, [`char`], or a closure that
1715     /// determines if a character matches.
1716     ///
1717     /// [`char`]: primitive.char.html
1718     ///
1719     /// # Text directionality
1720     ///
1721     /// A string is a sequence of bytes. 'Right' in this context means the last
1722     /// position of that byte string; for a language like Arabic or Hebrew
1723     /// which are 'right to left' rather than 'left to right', this will be
1724     /// the _left_ side, not the right.
1725     ///
1726     /// # Examples
1727     ///
1728     /// Simple patterns:
1729     ///
1730     /// ```
1731     /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1732     /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1733     ///
1734     /// let x: &[_] = &['1', '2'];
1735     /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1736     /// ```
1737     ///
1738     /// A more complex pattern, using a closure:
1739     ///
1740     /// ```
1741     /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1742     /// ```
1743     #[stable(feature = "rust1", since = "1.0.0")]
1744     pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1745         where P::Searcher: ReverseSearcher<'a>
1746     {
1747         core_str::StrExt::trim_right_matches(self, pat)
1748     }
1749
1750     /// Parses this string slice into another type.
1751     ///
1752     /// Because `parse` is so general, it can cause problems with type
1753     /// inference. As such, `parse` is one of the few times you'll see
1754     /// the syntax affectionately known as the 'turbofish': `::<>`. This
1755     /// helps the inference algorithm understand specifically which type
1756     /// you're trying to parse into.
1757     ///
1758     /// `parse` can parse any type that implements the [`FromStr`] trait.
1759     ///
1760     /// [`FromStr`]: str/trait.FromStr.html
1761     ///
1762     /// # Errors
1763     ///
1764     /// Will return [`Err`] if it's not possible to parse this string slice into
1765     /// the desired type.
1766     ///
1767     /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
1768     ///
1769     /// # Examples
1770     ///
1771     /// Basic usage
1772     ///
1773     /// ```
1774     /// let four: u32 = "4".parse().unwrap();
1775     ///
1776     /// assert_eq!(4, four);
1777     /// ```
1778     ///
1779     /// Using the 'turbofish' instead of annotating `four`:
1780     ///
1781     /// ```
1782     /// let four = "4".parse::<u32>();
1783     ///
1784     /// assert_eq!(Ok(4), four);
1785     /// ```
1786     ///
1787     /// Failing to parse:
1788     ///
1789     /// ```
1790     /// let nope = "j".parse::<u32>();
1791     ///
1792     /// assert!(nope.is_err());
1793     /// ```
1794     #[inline]
1795     #[stable(feature = "rust1", since = "1.0.0")]
1796     pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1797         core_str::StrExt::parse(self)
1798     }
1799
1800     /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
1801     ///
1802     /// # Examples
1803     ///
1804     /// Basic usage:
1805     ///
1806     /// ```
1807     /// let s = "this is a string";
1808     /// let boxed_str = s.to_owned().into_boxed_str();
1809     /// let boxed_bytes = boxed_str.into_boxed_bytes();
1810     /// assert_eq!(*boxed_bytes, *s.as_bytes());
1811     /// ```
1812     #[stable(feature = "str_box_extras", since = "1.20.0")]
1813     pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
1814         self.into()
1815     }
1816
1817     /// Replaces all matches of a pattern with another string.
1818     ///
1819     /// `replace` creates a new [`String`], and copies the data from this string slice into it.
1820     /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1821     /// replaces them with the replacement string slice.
1822     ///
1823     /// [`String`]: string/struct.String.html
1824     ///
1825     /// # Examples
1826     ///
1827     /// Basic usage:
1828     ///
1829     /// ```
1830     /// let s = "this is old";
1831     ///
1832     /// assert_eq!("this is new", s.replace("old", "new"));
1833     /// ```
1834     ///
1835     /// When the pattern doesn't match:
1836     ///
1837     /// ```
1838     /// let s = "this is old";
1839     /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1840     /// ```
1841     #[stable(feature = "rust1", since = "1.0.0")]
1842     #[inline]
1843     pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
1844         let mut result = String::new();
1845         let mut last_end = 0;
1846         for (start, part) in self.match_indices(from) {
1847             result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1848             result.push_str(to);
1849             last_end = start + part.len();
1850         }
1851         result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1852         result
1853     }
1854
1855     /// Replaces first N matches of a pattern with another string.
1856     ///
1857     /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
1858     /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1859     /// replaces them with the replacement string slice at most `count` times.
1860     ///
1861     /// [`String`]: string/struct.String.html
1862     ///
1863     /// # Examples
1864     ///
1865     /// Basic usage:
1866     ///
1867     /// ```
1868     /// let s = "foo foo 123 foo";
1869     /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
1870     /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
1871     /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
1872     /// ```
1873     ///
1874     /// When the pattern doesn't match:
1875     ///
1876     /// ```
1877     /// let s = "this is old";
1878     /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1879     /// ```
1880     #[stable(feature = "str_replacen", since = "1.16.0")]
1881     pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
1882         // Hope to reduce the times of re-allocation
1883         let mut result = String::with_capacity(32);
1884         let mut last_end = 0;
1885         for (start, part) in self.match_indices(pat).take(count) {
1886             result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1887             result.push_str(to);
1888             last_end = start + part.len();
1889         }
1890         result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1891         result
1892     }
1893
1894     /// Returns the lowercase equivalent of this string slice, as a new [`String`].
1895     ///
1896     /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
1897     /// `Lowercase`.
1898     ///
1899     /// Since some characters can expand into multiple characters when changing
1900     /// the case, this function returns a [`String`] instead of modifying the
1901     /// parameter in-place.
1902     ///
1903     /// [`String`]: string/struct.String.html
1904     ///
1905     /// # Examples
1906     ///
1907     /// Basic usage:
1908     ///
1909     /// ```
1910     /// let s = "HELLO";
1911     ///
1912     /// assert_eq!("hello", s.to_lowercase());
1913     /// ```
1914     ///
1915     /// A tricky example, with sigma:
1916     ///
1917     /// ```
1918     /// let sigma = "Σ";
1919     ///
1920     /// assert_eq!("σ", sigma.to_lowercase());
1921     ///
1922     /// // but at the end of a word, it's ς, not σ:
1923     /// let odysseus = "ὈΔΥΣΣΕΎΣ";
1924     ///
1925     /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1926     /// ```
1927     ///
1928     /// Languages without case are not changed:
1929     ///
1930     /// ```
1931     /// let new_year = "农历新年";
1932     ///
1933     /// assert_eq!(new_year, new_year.to_lowercase());
1934     /// ```
1935     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1936     pub fn to_lowercase(&self) -> String {
1937         let mut s = String::with_capacity(self.len());
1938         for (i, c) in self[..].char_indices() {
1939             if c == 'Σ' {
1940                 // Σ maps to σ, except at the end of a word where it maps to ς.
1941                 // This is the only conditional (contextual) but language-independent mapping
1942                 // in `SpecialCasing.txt`,
1943                 // so hard-code it rather than have a generic "condition" mechanism.
1944                 // See https://github.com/rust-lang/rust/issues/26035
1945                 map_uppercase_sigma(self, i, &mut s)
1946             } else {
1947                 s.extend(c.to_lowercase());
1948             }
1949         }
1950         return s;
1951
1952         fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1953             // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1954             // for the definition of `Final_Sigma`.
1955             debug_assert!('Σ'.len_utf8() == 2);
1956             let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
1957                                 !case_ignoreable_then_cased(from[i + 2..].chars());
1958             to.push_str(if is_word_final { "ς" } else { "σ" });
1959         }
1960
1961         fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
1962             use std_unicode::derived_property::{Cased, Case_Ignorable};
1963             match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1964                 Some(c) => Cased(c),
1965                 None => false,
1966             }
1967         }
1968     }
1969
1970     /// Returns the uppercase equivalent of this string slice, as a new [`String`].
1971     ///
1972     /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1973     /// `Uppercase`.
1974     ///
1975     /// Since some characters can expand into multiple characters when changing
1976     /// the case, this function returns a [`String`] instead of modifying the
1977     /// parameter in-place.
1978     ///
1979     /// [`String`]: string/struct.String.html
1980     ///
1981     /// # Examples
1982     ///
1983     /// Basic usage:
1984     ///
1985     /// ```
1986     /// let s = "hello";
1987     ///
1988     /// assert_eq!("HELLO", s.to_uppercase());
1989     /// ```
1990     ///
1991     /// Scripts without case are not changed:
1992     ///
1993     /// ```
1994     /// let new_year = "农历新年";
1995     ///
1996     /// assert_eq!(new_year, new_year.to_uppercase());
1997     /// ```
1998     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1999     pub fn to_uppercase(&self) -> String {
2000         let mut s = String::with_capacity(self.len());
2001         s.extend(self.chars().flat_map(|c| c.to_uppercase()));
2002         return s;
2003     }
2004
2005     /// Escapes each char in `s` with [`char::escape_debug`].
2006     ///
2007     /// [`char::escape_debug`]: primitive.char.html#method.escape_debug
2008     #[unstable(feature = "str_escape",
2009                reason = "return type may change to be an iterator",
2010                issue = "27791")]
2011     pub fn escape_debug(&self) -> String {
2012         self.chars().flat_map(|c| c.escape_debug()).collect()
2013     }
2014
2015     /// Escapes each char in `s` with [`char::escape_default`].
2016     ///
2017     /// [`char::escape_default`]: primitive.char.html#method.escape_default
2018     #[unstable(feature = "str_escape",
2019                reason = "return type may change to be an iterator",
2020                issue = "27791")]
2021     pub fn escape_default(&self) -> String {
2022         self.chars().flat_map(|c| c.escape_default()).collect()
2023     }
2024
2025     /// Escapes each char in `s` with [`char::escape_unicode`].
2026     ///
2027     /// [`char::escape_unicode`]: primitive.char.html#method.escape_unicode
2028     #[unstable(feature = "str_escape",
2029                reason = "return type may change to be an iterator",
2030                issue = "27791")]
2031     pub fn escape_unicode(&self) -> String {
2032         self.chars().flat_map(|c| c.escape_unicode()).collect()
2033     }
2034
2035     /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
2036     ///
2037     /// [`String`]: string/struct.String.html
2038     /// [`Box<str>`]: boxed/struct.Box.html
2039     ///
2040     /// # Examples
2041     ///
2042     /// Basic usage:
2043     ///
2044     /// ```
2045     /// let string = String::from("birthday gift");
2046     /// let boxed_str = string.clone().into_boxed_str();
2047     ///
2048     /// assert_eq!(boxed_str.into_string(), string);
2049     /// ```
2050     #[stable(feature = "box_str", since = "1.4.0")]
2051     pub fn into_string(self: Box<str>) -> String {
2052         let slice = Box::<[u8]>::from(self);
2053         unsafe { String::from_utf8_unchecked(slice.into_vec()) }
2054     }
2055
2056     /// Create a [`String`] by repeating a string `n` times.
2057     ///
2058     /// [`String`]: string/struct.String.html
2059     ///
2060     /// # Examples
2061     ///
2062     /// Basic usage:
2063     ///
2064     /// ```
2065     /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
2066     /// ```
2067     #[stable(feature = "repeat_str", since = "1.16.0")]
2068     pub fn repeat(&self, n: usize) -> String {
2069         let mut s = String::with_capacity(self.len() * n);
2070         s.extend((0..n).map(|_| self));
2071         s
2072     }
2073
2074     /// Checks if all characters in this string are within the ASCII range.
2075     ///
2076     /// # Examples
2077     ///
2078     /// ```
2079     /// let ascii = "hello!\n";
2080     /// let non_ascii = "Grüße, Jürgen ❤";
2081     ///
2082     /// assert!(ascii.is_ascii());
2083     /// assert!(!non_ascii.is_ascii());
2084     /// ```
2085     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2086     #[inline]
2087     pub fn is_ascii(&self) -> bool {
2088         // We can treat each byte as character here: all multibyte characters
2089         // start with a byte that is not in the ascii range, so we will stop
2090         // there already.
2091         self.bytes().all(|b| b.is_ascii())
2092     }
2093
2094     /// Returns a copy of this string where each character is mapped to its
2095     /// ASCII upper case equivalent.
2096     ///
2097     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2098     /// but non-ASCII letters are unchanged.
2099     ///
2100     /// To uppercase the value in-place, use [`make_ascii_uppercase`].
2101     ///
2102     /// To uppercase ASCII characters in addition to non-ASCII characters, use
2103     /// [`to_uppercase`].
2104     ///
2105     /// # Examples
2106     ///
2107     /// ```
2108     /// let s = "Grüße, Jürgen ❤";
2109     ///
2110     /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
2111     /// ```
2112     ///
2113     /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
2114     /// [`to_uppercase`]: #method.to_uppercase
2115     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2116     #[inline]
2117     #[cfg(not(stage0))]
2118     pub fn to_ascii_uppercase(&self) -> String {
2119         let mut bytes = self.as_bytes().to_vec();
2120         bytes.make_ascii_uppercase();
2121         // make_ascii_uppercase() preserves the UTF-8 invariant.
2122         unsafe { String::from_utf8_unchecked(bytes) }
2123     }
2124
2125     /// Returns a copy of this string where each character is mapped to its
2126     /// ASCII lower case equivalent.
2127     ///
2128     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2129     /// but non-ASCII letters are unchanged.
2130     ///
2131     /// To lowercase the value in-place, use [`make_ascii_lowercase`].
2132     ///
2133     /// To lowercase ASCII characters in addition to non-ASCII characters, use
2134     /// [`to_lowercase`].
2135     ///
2136     /// # Examples
2137     ///
2138     /// ```
2139     /// let s = "Grüße, Jürgen ❤";
2140     ///
2141     /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
2142     /// ```
2143     ///
2144     /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
2145     /// [`to_lowercase`]: #method.to_lowercase
2146     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2147     #[inline]
2148     #[cfg(not(stage0))]
2149     pub fn to_ascii_lowercase(&self) -> String {
2150         let mut bytes = self.as_bytes().to_vec();
2151         bytes.make_ascii_lowercase();
2152         // make_ascii_lowercase() preserves the UTF-8 invariant.
2153         unsafe { String::from_utf8_unchecked(bytes) }
2154     }
2155
2156     /// Checks that two strings are an ASCII case-insensitive match.
2157     ///
2158     /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2159     /// but without allocating and copying temporaries.
2160     ///
2161     /// # Examples
2162     ///
2163     /// ```
2164     /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2165     /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2166     /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2167     /// ```
2168     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2169     #[inline]
2170     #[cfg(not(stage0))]
2171     pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
2172         self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
2173     }
2174
2175     /// Converts this string to its ASCII upper case equivalent in-place.
2176     ///
2177     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2178     /// but non-ASCII letters are unchanged.
2179     ///
2180     /// To return a new uppercased value without modifying the existing one, use
2181     /// [`to_ascii_uppercase`].
2182     ///
2183     /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2184     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2185     #[cfg(not(stage0))]
2186     pub fn make_ascii_uppercase(&mut self) {
2187         let me = unsafe { self.as_bytes_mut() };
2188         me.make_ascii_uppercase()
2189     }
2190
2191     /// Converts this string to its ASCII lower case equivalent in-place.
2192     ///
2193     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2194     /// but non-ASCII letters are unchanged.
2195     ///
2196     /// To return a new lowercased value without modifying the existing one, use
2197     /// [`to_ascii_lowercase`].
2198     ///
2199     /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2200     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2201     #[cfg(not(stage0))]
2202     pub fn make_ascii_lowercase(&mut self) {
2203         let me = unsafe { self.as_bytes_mut() };
2204         me.make_ascii_lowercase()
2205     }
2206
2207     /// Checks if all characters of this string are ASCII alphabetic
2208     /// characters:
2209     ///
2210     /// - U+0041 'A' ... U+005A 'Z', or
2211     /// - U+0061 'a' ... U+007A 'z'.
2212     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2213     #[inline]
2214     pub fn is_ascii_alphabetic(&self) -> bool {
2215         self.bytes().all(|b| b.is_ascii_alphabetic())
2216     }
2217
2218     /// Checks if all characters of this string are ASCII uppercase characters:
2219     /// U+0041 'A' ... U+005A 'Z'.
2220     ///
2221     /// # Example
2222     ///
2223     /// ```
2224     /// // Only ascii uppercase characters
2225     /// assert!("HELLO".is_ascii_uppercase());
2226     ///
2227     /// // While all characters are ascii, 'y' and 'e' are not uppercase
2228     /// assert!(!"Bye".is_ascii_uppercase());
2229     ///
2230     /// // While all characters are uppercase, 'Ü' is not ascii
2231     /// assert!(!"TSCHÜSS".is_ascii_uppercase());
2232     /// ```
2233     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2234     #[inline]
2235     pub fn is_ascii_uppercase(&self) -> bool {
2236         self.bytes().all(|b| b.is_ascii_uppercase())
2237     }
2238
2239     /// Checks if all characters of this string are ASCII lowercase characters:
2240     /// U+0061 'a' ... U+007A 'z'.
2241     ///
2242     /// # Example
2243     ///
2244     /// ```
2245     /// // Only ascii uppercase characters
2246     /// assert!("hello".is_ascii_lowercase());
2247     ///
2248     /// // While all characters are ascii, 'B' is not lowercase
2249     /// assert!(!"Bye".is_ascii_lowercase());
2250     ///
2251     /// // While all characters are lowercase, 'Ü' is not ascii
2252     /// assert!(!"tschüss".is_ascii_lowercase());
2253     /// ```
2254     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2255     #[inline]
2256     pub fn is_ascii_lowercase(&self) -> bool {
2257         self.bytes().all(|b| b.is_ascii_lowercase())
2258     }
2259
2260     /// Checks if all characters of this string are ASCII alphanumeric
2261     /// characters:
2262     ///
2263     /// - U+0041 'A' ... U+005A 'Z', or
2264     /// - U+0061 'a' ... U+007A 'z', or
2265     /// - U+0030 '0' ... U+0039 '9'.
2266     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2267     #[inline]
2268     pub fn is_ascii_alphanumeric(&self) -> bool {
2269         self.bytes().all(|b| b.is_ascii_alphanumeric())
2270     }
2271
2272     /// Checks if all characters of this string are ASCII decimal digit:
2273     /// U+0030 '0' ... U+0039 '9'.
2274     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2275     #[inline]
2276     pub fn is_ascii_digit(&self) -> bool {
2277         self.bytes().all(|b| b.is_ascii_digit())
2278     }
2279
2280     /// Checks if all characters of this string are ASCII hexadecimal digits:
2281     ///
2282     /// - U+0030 '0' ... U+0039 '9', or
2283     /// - U+0041 'A' ... U+0046 'F', or
2284     /// - U+0061 'a' ... U+0066 'f'.
2285     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2286     #[inline]
2287     pub fn is_ascii_hexdigit(&self) -> bool {
2288         self.bytes().all(|b| b.is_ascii_hexdigit())
2289     }
2290
2291     /// Checks if all characters of this string are ASCII punctuation
2292     /// characters:
2293     ///
2294     /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
2295     /// - U+003A ... U+0040 `: ; < = > ? @`, or
2296     /// - U+005B ... U+0060 `[ \\ ] ^ _ \``, or
2297     /// - U+007B ... U+007E `{ | } ~`
2298     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2299     #[inline]
2300     pub fn is_ascii_punctuation(&self) -> bool {
2301         self.bytes().all(|b| b.is_ascii_punctuation())
2302     }
2303
2304     /// Checks if all characters of this string are ASCII graphic characters:
2305     /// U+0021 '@' ... U+007E '~'.
2306     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2307     #[inline]
2308     pub fn is_ascii_graphic(&self) -> bool {
2309         self.bytes().all(|b| b.is_ascii_graphic())
2310     }
2311
2312     /// Checks if all characters of this string are ASCII whitespace characters:
2313     /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
2314     /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
2315     ///
2316     /// Rust uses the WhatWG Infra Standard's [definition of ASCII
2317     /// whitespace][infra-aw]. There are several other definitions in
2318     /// wide use. For instance, [the POSIX locale][pct] includes
2319     /// U+000B VERTICAL TAB as well as all the above characters,
2320     /// but—from the very same specification—[the default rule for
2321     /// "field splitting" in the Bourne shell][bfs] considers *only*
2322     /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
2323     ///
2324     /// If you are writing a program that will process an existing
2325     /// file format, check what that format's definition of whitespace is
2326     /// before using this function.
2327     ///
2328     /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
2329     /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
2330     /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
2331     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2332     #[inline]
2333     pub fn is_ascii_whitespace(&self) -> bool {
2334         self.bytes().all(|b| b.is_ascii_whitespace())
2335     }
2336
2337     /// Checks if all characters of this string are ASCII control characters:
2338     ///
2339     /// - U+0000 NUL ... U+001F UNIT SEPARATOR, or
2340     /// - U+007F DELETE.
2341     ///
2342     /// Note that most ASCII whitespace characters are control
2343     /// characters, but SPACE is not.
2344     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.21.0")]
2345     #[inline]
2346     pub fn is_ascii_control(&self) -> bool {
2347         self.bytes().all(|b| b.is_ascii_control())
2348     }
2349 }
2350
2351 /// Converts a boxed slice of bytes to a boxed string slice without checking
2352 /// that the string contains valid UTF-8.
2353 ///
2354 /// # Examples
2355 ///
2356 /// Basic usage:
2357 ///
2358 /// ```
2359 /// let smile_utf8 = Box::new([226, 152, 186]);
2360 /// let smile = unsafe { std::str::from_boxed_utf8_unchecked(smile_utf8) };
2361 ///
2362 /// assert_eq!("☺", &*smile);
2363 /// ```
2364 #[stable(feature = "str_box_extras", since = "1.20.0")]
2365 pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box<str> {
2366     Box::from_raw(Box::into_raw(v) as *mut str)
2367 }