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