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