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