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