]> git.lizzy.rs Git - rust.git/blob - src/libcollections/str.rs
7d1ed13d7640ecdcb571d4ee6014f4cc7348bc87
[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::clone::Clone;
23 use core::iter::{Iterator, Extend};
24 use core::option::Option::{self, Some, None};
25 use core::result::Result;
26 use core::str as core_str;
27 use core::str::pattern::Pattern;
28 use core::str::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
29 use core::mem;
30 use rustc_unicode::str::{UnicodeStr, Utf16Encoder};
31
32 use vec_deque::VecDeque;
33 use borrow::{Borrow, ToOwned};
34 use string::String;
35 use rustc_unicode;
36 use vec::Vec;
37 use slice::SliceConcatExt;
38 use boxed::Box;
39
40 pub use core::str::{FromStr, Utf8Error};
41 pub use core::str::{Lines, LinesAny, CharRange};
42 pub use core::str::{Split, RSplit};
43 pub use core::str::{SplitN, RSplitN};
44 pub use core::str::{SplitTerminator, RSplitTerminator};
45 pub use core::str::{Matches, RMatches};
46 pub use core::str::{MatchIndices, RMatchIndices};
47 pub use core::str::{from_utf8, Chars, CharIndices, Bytes};
48 pub use core::str::{from_utf8_unchecked, ParseBoolError};
49 pub use rustc_unicode::str::{SplitWhitespace};
50 pub use core::str::pattern;
51
52 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
53     type Output = String;
54
55     fn concat(&self) -> String {
56         if self.is_empty() {
57             return String::new();
58         }
59
60         // `len` calculation may overflow but push_str will check boundaries
61         let len = self.iter().map(|s| s.borrow().len()).sum();
62         let mut result = String::with_capacity(len);
63
64         for s in self {
65             result.push_str(s.borrow())
66         }
67
68         result
69     }
70
71     fn join(&self, sep: &str) -> String {
72         if self.is_empty() {
73             return String::new();
74         }
75
76         // concat is faster
77         if sep.is_empty() {
78             return self.concat();
79         }
80
81         // this is wrong without the guarantee that `self` is non-empty
82         // `len` calculation may overflow but push_str but will check boundaries
83         let len = sep.len() * (self.len() - 1)
84             + self.iter().map(|s| s.borrow().len()).sum::<usize>();
85         let mut result = String::with_capacity(len);
86         let mut first = true;
87
88         for s in self {
89             if first {
90                 first = false;
91             } else {
92                 result.push_str(sep);
93             }
94             result.push_str(s.borrow());
95         }
96         result
97     }
98
99     fn connect(&self, sep: &str) -> String {
100         self.join(sep)
101     }
102 }
103
104 /// External iterator for a string's UTF16 codeunits.
105 ///
106 /// For use with the `std::iter` module.
107 #[derive(Clone)]
108 #[unstable(feature = "str_utf16", issue = "27714")]
109 pub struct Utf16Units<'a> {
110     encoder: Utf16Encoder<Chars<'a>>
111 }
112
113 #[stable(feature = "rust1", since = "1.0.0")]
114 impl<'a> Iterator for Utf16Units<'a> {
115     type Item = u16;
116
117     #[inline]
118     fn next(&mut self) -> Option<u16> { self.encoder.next() }
119
120     #[inline]
121     fn size_hint(&self) -> (usize, Option<usize>) { self.encoder.size_hint() }
122 }
123
124 // Return the initial codepoint accumulator for the first byte.
125 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
126 // for width 3, and 3 bits for width 4
127 macro_rules! utf8_first_byte {
128     ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
129 }
130
131 // return the value of $ch updated with continuation byte $byte
132 macro_rules! utf8_acc_cont_byte {
133     ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63) as u32)
134 }
135
136 #[stable(feature = "rust1", since = "1.0.0")]
137 impl Borrow<str> for String {
138     #[inline]
139     fn borrow(&self) -> &str { &self[..] }
140 }
141
142 #[stable(feature = "rust1", since = "1.0.0")]
143 impl ToOwned for str {
144     type Owned = String;
145     fn to_owned(&self) -> String {
146         unsafe {
147             String::from_utf8_unchecked(self.as_bytes().to_owned())
148         }
149     }
150 }
151
152 /// Any string that can be represented as a slice.
153 #[lang = "str"]
154 #[cfg(not(test))]
155 #[stable(feature = "rust1", since = "1.0.0")]
156 impl str {
157     /// Returns the length of `self` in bytes.
158     ///
159     /// # Examples
160     ///
161     /// ```
162     /// assert_eq!("foo".len(), 3);
163     /// assert_eq!("ƒoo".len(), 4); // fancy f!
164     /// ```
165     #[stable(feature = "rust1", since = "1.0.0")]
166     #[inline]
167     pub fn len(&self) -> usize {
168         core_str::StrExt::len(self)
169     }
170
171     /// Returns true if this slice has a length of zero bytes.
172     ///
173     /// # Examples
174     ///
175     /// ```
176     /// assert!("".is_empty());
177     /// ```
178     #[inline]
179     #[stable(feature = "rust1", since = "1.0.0")]
180     pub fn is_empty(&self) -> bool {
181         core_str::StrExt::is_empty(self)
182     }
183
184     /// Checks that `index`-th byte lies at the start and/or end of a
185     /// UTF-8 code point sequence.
186     ///
187     /// The start and end of the string (when `index == self.len()`) are
188     /// considered to be
189     /// boundaries.
190     ///
191     /// Returns `false` if `index` is greater than `self.len()`.
192     ///
193     /// # Examples
194     ///
195     /// ```
196     /// #![feature(str_char)]
197     ///
198     /// let s = "Löwe 老虎 Léopard";
199     /// assert!(s.is_char_boundary(0));
200     /// // start of `老`
201     /// assert!(s.is_char_boundary(6));
202     /// assert!(s.is_char_boundary(s.len()));
203     ///
204     /// // second byte of `ö`
205     /// assert!(!s.is_char_boundary(2));
206     ///
207     /// // third byte of `老`
208     /// assert!(!s.is_char_boundary(8));
209     /// ```
210     #[unstable(feature = "str_char",
211                reason = "it is unclear whether this method pulls its weight \
212                          with the existence of the char_indices iterator or \
213                          this method may want to be replaced with checked \
214                          slicing",
215                issue = "27754")]
216     #[inline]
217     pub fn is_char_boundary(&self, index: usize) -> bool {
218         core_str::StrExt::is_char_boundary(self, index)
219     }
220
221     /// Converts `self` to a byte slice.
222     ///
223     /// # Examples
224     ///
225     /// ```
226     /// assert_eq!("bors".as_bytes(), b"bors");
227     /// ```
228     #[stable(feature = "rust1", since = "1.0.0")]
229     #[inline(always)]
230     pub fn as_bytes(&self) -> &[u8] {
231         core_str::StrExt::as_bytes(self)
232     }
233
234     /// Returns a raw pointer to the `&str`'s buffer.
235     ///
236     /// The caller must ensure that the string outlives this pointer, and
237     /// that it is not
238     /// reallocated (e.g. by pushing to the string).
239     ///
240     /// # Examples
241     ///
242     /// ```
243     /// let s = "Hello";
244     /// let p = s.as_ptr();
245     /// ```
246     #[stable(feature = "rust1", since = "1.0.0")]
247     #[inline]
248     pub fn as_ptr(&self) -> *const u8 {
249         core_str::StrExt::as_ptr(self)
250     }
251
252     /// Takes a bytewise slice from a string.
253     ///
254     /// Returns the substring from [`begin`..`end`).
255     ///
256     /// # Unsafety
257     ///
258     /// Caller must check both UTF-8 sequence boundaries and the boundaries
259     /// of the entire slice as well.
260     ///
261     /// # Examples
262     ///
263     /// ```
264     /// let s = "Löwe 老虎 Léopard";
265     ///
266     /// unsafe {
267     ///     assert_eq!(s.slice_unchecked(0, 21), "Löwe 老虎 Léopard");
268     /// }
269     /// ```
270     #[stable(feature = "rust1", since = "1.0.0")]
271     #[inline]
272     pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
273         core_str::StrExt::slice_unchecked(self, begin, end)
274     }
275
276     /// Takes a bytewise mutable slice from a string.
277     ///
278     /// Same as `slice_unchecked`, but works with `&mut str` instead of `&str`.
279     #[unstable(feature = "str_slice_mut", reason = "recently added",
280                issue = "27793")]
281     #[inline]
282     pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
283         core_str::StrExt::slice_mut_unchecked(self, begin, end)
284     }
285
286     /// Given a byte position, return the next code point and its index.
287     ///
288     /// This can be used to iterate over the Unicode code points of a string.
289     ///
290     /// # Panics
291     ///
292     /// If `i` is greater than or equal to the length of the string.
293     /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
294     ///
295     /// # Examples
296     ///
297     /// This example manually iterates through the code points of a string;
298     /// this should normally be
299     /// done by `.chars()` or `.char_indices()`.
300     ///
301     /// ```
302     /// #![feature(str_char, core)]
303     ///
304     /// use std::str::CharRange;
305     ///
306     /// let s = "中华Việt Nam";
307     /// let mut i = 0;
308     /// while i < s.len() {
309     ///     let CharRange {ch, next} = s.char_range_at(i);
310     ///     println!("{}: {}", i, ch);
311     ///     i = next;
312     /// }
313     /// ```
314     ///
315     /// This outputs:
316     ///
317     /// ```text
318     /// 0: 中
319     /// 3: 华
320     /// 6: V
321     /// 7: i
322     /// 8: e
323     /// 9:
324     /// 11:
325     /// 13: t
326     /// 14:
327     /// 15: N
328     /// 16: a
329     /// 17: m
330     /// ```
331     #[unstable(feature = "str_char",
332                reason = "often replaced by char_indices, this method may \
333                          be removed in favor of just char_at() or eventually \
334                          removed altogether",
335                issue = "27754")]
336     #[inline]
337     pub fn char_range_at(&self, start: usize) -> CharRange {
338         core_str::StrExt::char_range_at(self, start)
339     }
340
341     /// Given a byte position, return the previous `char` and its position.
342     ///
343     /// This function can be used to iterate over a Unicode code points in reverse.
344     ///
345     /// Note that Unicode has many features, such as combining marks, ligatures,
346     /// and direction marks, that need to be taken into account to correctly reverse a string.
347     ///
348     /// Returns 0 for next index if called on start index 0.
349     ///
350     /// # Panics
351     ///
352     /// If `i` is greater than the length of the string.
353     /// If `i` is not an index following a valid UTF-8 sequence.
354     ///
355     /// # Examples
356     ///
357     /// This example manually iterates through the code points of a string;
358     /// this should normally be
359     /// done by `.chars().rev()` or `.char_indices()`.
360     ///
361     /// ```
362     /// #![feature(str_char, core)]
363     ///
364     /// use std::str::CharRange;
365     ///
366     /// let s = "中华Việt Nam";
367     /// let mut i = s.len();
368     /// while i > 0 {
369     ///     let CharRange {ch, next} = s.char_range_at_reverse(i);
370     ///     println!("{}: {}", i, ch);
371     ///     i = next;
372     /// }
373     /// ```
374     ///
375     /// This outputs:
376     ///
377     /// ```text
378     /// 18: m
379     /// 17: a
380     /// 16: N
381     /// 15:
382     /// 14: t
383     /// 13:
384     /// 11:
385     /// 9: e
386     /// 8: i
387     /// 7: V
388     /// 6: 华
389     /// 3: 中
390     /// ```
391     #[unstable(feature = "str_char",
392                reason = "often replaced by char_indices, this method may \
393                          be removed in favor of just char_at_reverse() or \
394                          eventually removed altogether",
395                issue = "27754")]
396     #[inline]
397     pub fn char_range_at_reverse(&self, start: usize) -> CharRange {
398         core_str::StrExt::char_range_at_reverse(self, start)
399     }
400
401     /// Given a byte position, return the `char` at that position.
402     ///
403     /// # Panics
404     ///
405     /// If `i` is greater than or equal to the length of the string.
406     /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
407     ///
408     /// # Examples
409     ///
410     /// ```
411     /// #![feature(str_char)]
412     ///
413     /// let s = "abπc";
414     /// assert_eq!(s.char_at(1), 'b');
415     /// assert_eq!(s.char_at(2), 'π');
416     /// assert_eq!(s.char_at(4), 'c');
417     /// ```
418     #[unstable(feature = "str_char",
419                reason = "frequently replaced by the chars() iterator, this \
420                          method may be removed or possibly renamed in the \
421                          future; it is normally replaced by chars/char_indices \
422                          iterators or by getting the first char from a \
423                          subslice",
424                issue = "27754")]
425     #[inline]
426     pub fn char_at(&self, i: usize) -> char {
427         core_str::StrExt::char_at(self, i)
428     }
429
430     /// Given a byte position, return the `char` at that position, counting
431     /// from the end.
432     ///
433     /// # Panics
434     ///
435     /// If `i` is greater than the length of the string.
436     /// If `i` is not an index following a valid UTF-8 sequence.
437     ///
438     /// # Examples
439     ///
440     /// ```
441     /// #![feature(str_char)]
442     ///
443     /// let s = "abπc";
444     /// assert_eq!(s.char_at_reverse(1), 'a');
445     /// assert_eq!(s.char_at_reverse(2), 'b');
446     /// assert_eq!(s.char_at_reverse(3), 'π');
447     /// ```
448     #[unstable(feature = "str_char",
449                reason = "see char_at for more details, but reverse semantics \
450                          are also somewhat unclear, especially with which \
451                          cases generate panics",
452                issue = "27754")]
453     #[inline]
454     pub fn char_at_reverse(&self, i: usize) -> char {
455         core_str::StrExt::char_at_reverse(self, i)
456     }
457
458     /// Retrieves the first code point from a `&str` and returns it.
459     ///
460     /// Note that a single Unicode character (grapheme cluster)
461     /// can be composed of multiple `char`s.
462     ///
463     /// This does not allocate a new string; instead, it returns a slice that
464     /// points one code point beyond the code point that was shifted.
465     ///
466     /// `None` is returned if the slice is empty.
467     ///
468     /// # Examples
469     ///
470     /// ```
471     /// #![feature(str_char)]
472     ///
473     /// let s = "Łódź"; // \u{141}o\u{301}dz\u{301}
474     /// let (c, s1) = s.slice_shift_char().unwrap();
475     ///
476     /// assert_eq!(c, 'Ł');
477     /// assert_eq!(s1, "ódź");
478     ///
479     /// let (c, s2) = s1.slice_shift_char().unwrap();
480     ///
481     /// assert_eq!(c, 'o');
482     /// assert_eq!(s2, "\u{301}dz\u{301}");
483     /// ```
484     #[unstable(feature = "str_char",
485                reason = "awaiting conventions about shifting and slices and \
486                          may not be warranted with the existence of the chars \
487                          and/or char_indices iterators",
488                issue = "27754")]
489     #[inline]
490     pub fn slice_shift_char(&self) -> Option<(char, &str)> {
491         core_str::StrExt::slice_shift_char(self)
492     }
493
494     /// Divide one string slice into two at an index.
495     ///
496     /// The index `mid` is a byte offset from the start of the string
497     /// that must be on a `char` boundary.
498     ///
499     /// Return slices `&self[..mid]` and `&self[mid..]`.
500     ///
501     /// # Panics
502     ///
503     /// Panics if `mid` is beyond the last code point of the string,
504     /// or if it is not on a `char` boundary.
505     ///
506     /// # Examples
507     /// ```
508     /// #![feature(str_split_at)]
509     ///
510     /// let s = "Löwe 老虎 Léopard";
511     /// let first_space = s.find(' ').unwrap_or(s.len());
512     /// let (a, b) = s.split_at(first_space);
513     ///
514     /// assert_eq!(a, "Löwe");
515     /// assert_eq!(b, " 老虎 Léopard");
516     /// ```
517     #[inline]
518     #[unstable(feature = "str_split_at", reason = "recently added",
519                issue = "27792")]
520     pub fn split_at(&self, mid: usize) -> (&str, &str) {
521         core_str::StrExt::split_at(self, mid)
522     }
523
524     /// Divide one mutable string slice into two at an index.
525     #[inline]
526     #[unstable(feature = "str_split_at", reason = "recently added",
527                issue = "27792")]
528     pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
529         core_str::StrExt::split_at_mut(self, mid)
530     }
531
532     /// An iterator over the code points of `self`.
533     ///
534     /// In Unicode relationship between code points and characters is complex.
535     /// A single character may be composed of multiple code points
536     /// (e.g. diacritical marks added to a letter), and a single code point
537     /// (e.g. Hangul syllable) may contain multiple characters.
538     ///
539     /// For iteration over human-readable characters a grapheme cluster iterator
540     /// may be more appropriate. See the [unicode-segmentation crate][1].
541     ///
542     /// [1]: https://crates.io/crates/unicode-segmentation
543     ///
544     /// # Examples
545     ///
546     /// ```
547     /// let v: Vec<char> = "ASCII żółć 🇨🇭 한".chars().collect();
548     ///
549     /// assert_eq!(v, ['A', 'S', 'C', 'I', 'I', ' ',
550     ///     'z', '\u{307}', 'o', '\u{301}', 'ł', 'c', '\u{301}', ' ',
551     ///     '\u{1f1e8}', '\u{1f1ed}', ' ', '한']);
552     /// ```
553     #[stable(feature = "rust1", since = "1.0.0")]
554     #[inline]
555     pub fn chars(&self) -> Chars {
556         core_str::StrExt::chars(self)
557     }
558
559     /// An iterator over the `char`s of `self` and their byte offsets.
560     ///
561     /// # Examples
562     ///
563     /// ```
564     /// let v: Vec<(usize, char)> = "A🇨🇭".char_indices().collect();
565     /// let b = vec![(0, 'A'), (1, '\u{1f1e8}'), (5, '\u{1f1ed}')];
566     ///
567     /// assert_eq!(v, b);
568     /// ```
569     #[stable(feature = "rust1", since = "1.0.0")]
570     #[inline]
571     pub fn char_indices(&self) -> CharIndices {
572         core_str::StrExt::char_indices(self)
573     }
574
575     /// An iterator over the bytes of `self`.
576     ///
577     /// # Examples
578     ///
579     /// ```
580     /// let v: Vec<u8> = "bors".bytes().collect();
581     ///
582     /// assert_eq!(v, b"bors".to_vec());
583     /// ```
584     #[stable(feature = "rust1", since = "1.0.0")]
585     #[inline]
586     pub fn bytes(&self) -> Bytes {
587         core_str::StrExt::bytes(self)
588     }
589
590     /// An iterator over the non-empty substrings of `self` which contain no whitespace,
591     /// and which are separated by any amount of whitespace.
592     ///
593     /// # Examples
594     ///
595     /// ```
596     /// let some_words = " Mary   had\ta\u{2009}little  \n\t lamb";
597     /// let v: Vec<&str> = some_words.split_whitespace().collect();
598     ///
599     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
600     /// ```
601     #[stable(feature = "split_whitespace", since = "1.1.0")]
602     #[inline]
603     pub fn split_whitespace(&self) -> SplitWhitespace {
604         UnicodeStr::split_whitespace(self)
605     }
606
607     /// An iterator over the lines of a string, separated by `\n` or `\r\n`.
608     ///
609     /// This does not include the empty string after a trailing newline or CRLF.
610     ///
611     /// # Examples
612     ///
613     /// ```
614     /// let four_lines = "foo\nbar\n\r\nbaz";
615     /// let v: Vec<&str> = four_lines.lines().collect();
616     ///
617     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
618     /// ```
619     ///
620     /// Leaving off the trailing character:
621     ///
622     /// ```
623     /// let four_lines = "foo\r\nbar\n\nbaz\n";
624     /// let v: Vec<&str> = four_lines.lines().collect();
625     ///
626     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
627     /// ```
628     #[stable(feature = "rust1", since = "1.0.0")]
629     #[inline]
630     pub fn lines(&self) -> Lines {
631         core_str::StrExt::lines(self)
632     }
633
634     /// An iterator over the lines of a string, separated by either
635     /// `\n` or `\r\n`.
636     ///
637     /// As with `.lines()`, this does not include an empty trailing line.
638     ///
639     /// # Examples
640     ///
641     /// ```
642     /// let four_lines = "foo\r\nbar\n\r\nbaz";
643     /// let v: Vec<&str> = four_lines.lines_any().collect();
644     ///
645     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
646     /// ```
647     ///
648     /// Leaving off the trailing character:
649     ///
650     /// ```
651     /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
652     /// let v: Vec<&str> = four_lines.lines_any().collect();
653     ///
654     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
655     /// ```
656     #[stable(feature = "rust1", since = "1.0.0")]
657     #[deprecated(since = "1.4.0", reason = "use lines() instead now")]
658     #[inline]
659     #[allow(deprecated)]
660     pub fn lines_any(&self) -> LinesAny {
661         core_str::StrExt::lines_any(self)
662     }
663
664     /// Returns an iterator of `u16` over the string encoded as UTF-16.
665     #[unstable(feature = "str_utf16",
666                reason = "this functionality may only be provided by libunicode",
667                issue = "27714")]
668     pub fn utf16_units(&self) -> Utf16Units {
669         Utf16Units { encoder: Utf16Encoder::new(self[..].chars()) }
670     }
671
672     /// Returns `true` if `self` contains another `&str`.
673     ///
674     /// # Examples
675     ///
676     /// ```
677     /// assert!("bananas".contains("nana"));
678     ///
679     /// assert!(!"bananas".contains("foobar"));
680     /// ```
681     #[stable(feature = "rust1", since = "1.0.0")]
682     pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
683         core_str::StrExt::contains(self, pat)
684     }
685
686     /// Returns `true` if the given `&str` is a prefix of the string.
687     ///
688     /// # Examples
689     ///
690     /// ```
691     /// assert!("banana".starts_with("ba"));
692     /// ```
693     #[stable(feature = "rust1", since = "1.0.0")]
694     pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
695         core_str::StrExt::starts_with(self, pat)
696     }
697
698     /// Returns true if the given `&str` is a suffix of the string.
699     ///
700     /// # Examples
701     ///
702     /// ```rust
703     /// assert!("banana".ends_with("nana"));
704     /// ```
705     #[stable(feature = "rust1", since = "1.0.0")]
706     pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
707         where P::Searcher: ReverseSearcher<'a>
708     {
709         core_str::StrExt::ends_with(self, pat)
710     }
711
712     /// Returns the byte index of the first character of `self` that matches
713     /// the pattern, if it
714     /// exists.
715     ///
716     /// Returns `None` if it doesn't exist.
717     ///
718     /// The pattern can be a simple `&str`, `char`, or a closure that
719     /// determines the
720     /// split.
721     ///
722     /// # Examples
723     ///
724     /// Simple patterns:
725     ///
726     /// ```
727     /// let s = "Löwe 老虎 Léopard";
728     ///
729     /// assert_eq!(s.find('L'), Some(0));
730     /// assert_eq!(s.find('é'), Some(14));
731     /// assert_eq!(s.find("Léopard"), Some(13));
732     ///
733     /// ```
734     ///
735     /// More complex patterns with closures:
736     ///
737     /// ```
738     /// let s = "Löwe 老虎 Léopard";
739     ///
740     /// assert_eq!(s.find(char::is_whitespace), Some(5));
741     /// assert_eq!(s.find(char::is_lowercase), Some(1));
742     /// ```
743     ///
744     /// Not finding the pattern:
745     ///
746     /// ```
747     /// let s = "Löwe 老虎 Léopard";
748     /// let x: &[_] = &['1', '2'];
749     ///
750     /// assert_eq!(s.find(x), None);
751     /// ```
752     #[stable(feature = "rust1", since = "1.0.0")]
753     pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
754         core_str::StrExt::find(self, pat)
755     }
756
757     /// Returns the byte index of the last character of `self` that
758     /// matches the pattern, if it
759     /// exists.
760     ///
761     /// Returns `None` if it doesn't exist.
762     ///
763     /// The pattern can be a simple `&str`, `char`,
764     /// or a closure that determines the split.
765     ///
766     /// # Examples
767     ///
768     /// Simple patterns:
769     ///
770     /// ```
771     /// let s = "Löwe 老虎 Léopard";
772     ///
773     /// assert_eq!(s.rfind('L'), Some(13));
774     /// assert_eq!(s.rfind('é'), Some(14));
775     /// ```
776     ///
777     /// More complex patterns with closures:
778     ///
779     /// ```
780     /// let s = "Löwe 老虎 Léopard";
781     ///
782     /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
783     /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
784     /// ```
785     ///
786     /// Not finding the pattern:
787     ///
788     /// ```
789     /// let s = "Löwe 老虎 Léopard";
790     /// let x: &[_] = &['1', '2'];
791     ///
792     /// assert_eq!(s.rfind(x), None);
793     /// ```
794     #[stable(feature = "rust1", since = "1.0.0")]
795     pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
796         where P::Searcher: ReverseSearcher<'a>
797     {
798         core_str::StrExt::rfind(self, pat)
799     }
800
801     /// An iterator over substrings of `self`, separated by characters
802     /// matched by a pattern.
803     ///
804     /// The pattern can be a simple `&str`, `char`, or a closure that
805     /// determines the split. Additional libraries might provide more complex
806     /// patterns like regular expressions.
807     ///
808     /// # Iterator behavior
809     ///
810     /// The returned iterator will be double ended if the pattern allows a
811     /// reverse search and forward/reverse search yields the same elements.
812     /// This is true for, eg, `char` but not
813     /// for `&str`.
814     ///
815     /// If the pattern allows a reverse search but its results might differ
816     /// from a forward search, `rsplit()` can be used.
817     ///
818     /// # Examples
819     ///
820     /// Simple patterns:
821     ///
822     /// ```
823     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
824     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
825     ///
826     /// let v: Vec<&str> = "".split('X').collect();
827     /// assert_eq!(v, [""]);
828     ///
829     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
830     /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
831     ///
832     /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
833     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
834     ///
835     /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
836     /// assert_eq!(v, ["abc", "def", "ghi"]);
837     ///
838     /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
839     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
840     /// ```
841     ///
842     /// A more complex pattern, using a closure:
843     ///
844     /// ```
845     /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
846     /// assert_eq!(v, ["abc", "def", "ghi"]);
847     /// ```
848     ///
849     /// If a string contains multiple contiguous separators, you will end up
850     /// with empty strings in the output:
851     ///
852     /// ```
853     /// let x = "||||a||b|c".to_string();
854     /// let d: Vec<_> = x.split('|').collect();
855     ///
856     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
857     /// ```
858     ///
859     /// This can lead to possibly surprising behavior when whitespace is used
860     /// as the separator. This code is correct:
861     ///
862     /// ```
863     /// let x = "    a  b c".to_string();
864     /// let d: Vec<_> = x.split(' ').collect();
865     ///
866     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
867     /// ```
868     ///
869     /// It does _not_ give you:
870     ///
871     /// ```rust,ignore
872     /// assert_eq!(d, &["a", "b", "c"]);
873     /// ```
874     #[stable(feature = "rust1", since = "1.0.0")]
875     pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
876         core_str::StrExt::split(self, pat)
877     }
878
879     /// An iterator over substrings of `self`, separated by characters
880     /// matched by a pattern and yielded in reverse order.
881     ///
882     /// The pattern can be a simple `&str`, `char`, or a closure that
883     /// determines the split.
884     /// Additional libraries might provide more complex patterns like
885     /// regular expressions.
886     ///
887     /// # Iterator behavior
888     ///
889     /// The returned iterator requires that the pattern supports a
890     /// reverse search,
891     /// and it will be double ended if a forward/reverse search yields
892     /// the same elements.
893     ///
894     /// For iterating from the front, `split()` can be used.
895     ///
896     /// # Examples
897     ///
898     /// Simple patterns:
899     ///
900     /// ```rust
901     /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
902     /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
903     ///
904     /// let v: Vec<&str> = "".rsplit('X').collect();
905     /// assert_eq!(v, [""]);
906     ///
907     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
908     /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
909     ///
910     /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
911     /// assert_eq!(v, ["leopard", "tiger", "lion"]);
912     /// ```
913     ///
914     /// A more complex pattern, using a closure:
915     ///
916     /// ```
917     /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
918     /// assert_eq!(v, ["ghi", "def", "abc"]);
919     /// ```
920     #[stable(feature = "rust1", since = "1.0.0")]
921     pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
922         where P::Searcher: ReverseSearcher<'a>
923     {
924         core_str::StrExt::rsplit(self, pat)
925     }
926
927     /// An iterator over substrings of `self`, separated by characters
928     /// matched by a pattern.
929     ///
930     /// The pattern can be a simple `&str`, `char`, or a closure that
931     /// determines the split.
932     /// Additional libraries might provide more complex patterns
933     /// like regular expressions.
934     ///
935     /// Equivalent to `split`, except that the trailing substring
936     /// is skipped if empty.
937     ///
938     /// This method can be used for string data that is _terminated_,
939     /// rather than _separated_ by a pattern.
940     ///
941     /// # Iterator behavior
942     ///
943     /// The returned iterator will be double ended if the pattern allows a
944     /// reverse search
945     /// and forward/reverse search yields the same elements. This is true
946     /// for, eg, `char` but not for `&str`.
947     ///
948     /// If the pattern allows a reverse search but its results might differ
949     /// from a forward search, `rsplit_terminator()` can be used.
950     ///
951     /// # Examples
952     ///
953     /// ```
954     /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
955     /// assert_eq!(v, ["A", "B"]);
956     ///
957     /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
958     /// assert_eq!(v, ["A", "", "B", ""]);
959     /// ```
960     #[stable(feature = "rust1", since = "1.0.0")]
961     pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
962         core_str::StrExt::split_terminator(self, pat)
963     }
964
965     /// An iterator over substrings of `self`, separated by characters
966     /// matched by a pattern and yielded in reverse order.
967     ///
968     /// The pattern can be a simple `&str`, `char`, or a closure that
969     /// determines the split.
970     /// Additional libraries might provide more complex patterns like
971     /// regular expressions.
972     ///
973     /// Equivalent to `split`, except that the trailing substring is
974     /// skipped if empty.
975     ///
976     /// This method can be used for string data that is _terminated_,
977     /// rather than _separated_ by a pattern.
978     ///
979     /// # Iterator behavior
980     ///
981     /// The returned iterator requires that the pattern supports a
982     /// reverse search, and it will be double ended if a forward/reverse
983     /// search yields the same elements.
984     ///
985     /// For iterating from the front, `split_terminator()` can be used.
986     ///
987     /// # Examples
988     ///
989     /// ```
990     /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
991     /// assert_eq!(v, ["B", "A"]);
992     ///
993     /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
994     /// assert_eq!(v, ["", "B", "", "A"]);
995     /// ```
996     #[stable(feature = "rust1", since = "1.0.0")]
997     pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
998         where P::Searcher: ReverseSearcher<'a>
999     {
1000         core_str::StrExt::rsplit_terminator(self, pat)
1001     }
1002
1003     /// An iterator over substrings of `self`, separated by a pattern,
1004     /// restricted to returning
1005     /// at most `count` items.
1006     ///
1007     /// The last element returned, if any, will contain the remainder of the
1008     /// string.
1009     /// The pattern can be a simple `&str`, `char`, or a closure that
1010     /// determines the split.
1011     /// Additional libraries might provide more complex patterns like
1012     /// regular expressions.
1013     ///
1014     /// # Iterator behavior
1015     ///
1016     /// The returned iterator will not be double ended, because it is
1017     /// not efficient to support.
1018     ///
1019     /// If the pattern allows a reverse search, `rsplitn()` can be used.
1020     ///
1021     /// # Examples
1022     ///
1023     /// Simple patterns:
1024     ///
1025     /// ```
1026     /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1027     /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1028     ///
1029     /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1030     /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1031     ///
1032     /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1033     /// assert_eq!(v, ["abcXdef"]);
1034     ///
1035     /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1036     /// assert_eq!(v, [""]);
1037     /// ```
1038     ///
1039     /// A more complex pattern, using a closure:
1040     ///
1041     /// ```
1042     /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1043     /// assert_eq!(v, ["abc", "defXghi"]);
1044     /// ```
1045     #[stable(feature = "rust1", since = "1.0.0")]
1046     pub fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
1047         core_str::StrExt::splitn(self, count, pat)
1048     }
1049
1050     /// An iterator over substrings of `self`, separated by a pattern,
1051     /// starting from the end of the string, restricted to returning
1052     /// at most `count` items.
1053     ///
1054     /// The last element returned, if any, will contain the remainder of the
1055     /// string.
1056     ///
1057     /// The pattern can be a simple `&str`, `char`, or a closure that
1058     /// determines the split.
1059     /// Additional libraries might provide more complex patterns like
1060     /// regular expressions.
1061     ///
1062     /// # Iterator behavior
1063     ///
1064     /// The returned iterator will not be double ended, because it is not
1065     /// efficient to support.
1066     ///
1067     /// `splitn()` can be used for splitting from the front.
1068     ///
1069     /// # Examples
1070     ///
1071     /// Simple patterns:
1072     ///
1073     /// ```
1074     /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1075     /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1076     ///
1077     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1078     /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1079     ///
1080     /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1081     /// assert_eq!(v, ["leopard", "lion::tiger"]);
1082     /// ```
1083     ///
1084     /// A more complex pattern, using a closure:
1085     ///
1086     /// ```
1087     /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1088     /// assert_eq!(v, ["ghi", "abc1def"]);
1089     /// ```
1090     #[stable(feature = "rust1", since = "1.0.0")]
1091     pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
1092         where P::Searcher: ReverseSearcher<'a>
1093     {
1094         core_str::StrExt::rsplitn(self, count, pat)
1095     }
1096
1097     /// An iterator over the matches of a pattern within `self`.
1098     ///
1099     /// The pattern can be a simple `&str`, `char`, or a closure that
1100     /// determines the split.
1101     /// Additional libraries might provide more complex patterns like
1102     /// regular expressions.
1103     ///
1104     /// # Iterator behavior
1105     ///
1106     /// The returned iterator will be double ended if the pattern allows
1107     /// a reverse search
1108     /// and forward/reverse search yields the same elements. This is true
1109     /// for, eg, `char` but not
1110     /// for `&str`.
1111     ///
1112     /// If the pattern allows a reverse search but its results might differ
1113     /// from a forward search, `rmatches()` can be used.
1114     ///
1115     /// # Examples
1116     ///
1117     /// ```
1118     /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1119     /// assert_eq!(v, ["abc", "abc", "abc"]);
1120     ///
1121     /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1122     /// assert_eq!(v, ["1", "2", "3"]);
1123     /// ```
1124     #[stable(feature = "str_matches", since = "1.2.0")]
1125     pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1126         core_str::StrExt::matches(self, pat)
1127     }
1128
1129     /// An iterator over the matches of a pattern within `self`, yielded in
1130     /// reverse order.
1131     ///
1132     /// The pattern can be a simple `&str`, `char`, or a closure that
1133     /// determines the split.
1134     /// Additional libraries might provide more complex patterns like
1135     /// regular expressions.
1136     ///
1137     /// # Iterator behavior
1138     ///
1139     /// The returned iterator requires that the pattern supports a
1140     /// reverse search,
1141     /// and it will be double ended if a forward/reverse search yields
1142     /// the same elements.
1143     ///
1144     /// For iterating from the front, `matches()` can be used.
1145     ///
1146     /// # Examples
1147     ///
1148     /// ```
1149     /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1150     /// assert_eq!(v, ["abc", "abc", "abc"]);
1151     ///
1152     /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1153     /// assert_eq!(v, ["3", "2", "1"]);
1154     /// ```
1155     #[stable(feature = "str_matches", since = "1.2.0")]
1156     pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1157         where P::Searcher: ReverseSearcher<'a>
1158     {
1159         core_str::StrExt::rmatches(self, pat)
1160     }
1161
1162     /// An iterator over the start and end indices of the disjoint matches
1163     /// of a pattern within `self`.
1164     ///
1165     /// For matches of `pat` within `self` that overlap, only the indices
1166     /// corresponding to the first
1167     /// match are returned.
1168     ///
1169     /// The pattern can be a simple `&str`, `char`, or a closure that
1170     /// determines
1171     /// the split.
1172     /// Additional libraries might provide more complex patterns like
1173     /// regular expressions.
1174     ///
1175     /// # Iterator behavior
1176     ///
1177     /// The returned iterator will be double ended if the pattern allows a
1178     /// reverse search
1179     /// and forward/reverse search yields the same elements. This is true for,
1180     /// eg, `char` but not
1181     /// for `&str`.
1182     ///
1183     /// If the pattern allows a reverse search but its results might differ
1184     /// from a forward search, `rmatch_indices()` can be used.
1185     ///
1186     /// # Examples
1187     ///
1188     /// ```
1189     /// #![feature(str_match_indices)]
1190     ///
1191     /// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".match_indices("abc").collect();
1192     /// assert_eq!(v, [(0, 3), (6, 9), (12, 15)]);
1193     ///
1194     /// let v: Vec<(usize, usize)> = "1abcabc2".match_indices("abc").collect();
1195     /// assert_eq!(v, [(1, 4), (4, 7)]);
1196     ///
1197     /// let v: Vec<(usize, usize)> = "ababa".match_indices("aba").collect();
1198     /// assert_eq!(v, [(0, 3)]); // only the first `aba`
1199     /// ```
1200     #[unstable(feature = "str_match_indices",
1201                reason = "might have its iterator type changed",
1202                issue = "27743")]
1203     // NB: Right now MatchIndices yields `(usize, usize)`, but it would
1204     // be more consistent with `matches` and `char_indices` to return `(usize, &str)`
1205     pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1206         core_str::StrExt::match_indices(self, pat)
1207     }
1208
1209     /// An iterator over the start and end indices of the disjoint matches of
1210     /// a pattern within
1211     /// `self`, yielded in reverse order.
1212     ///
1213     /// For matches of `pat` within `self` that overlap, only the indices
1214     /// corresponding to the last
1215     /// match are returned.
1216     ///
1217     /// The pattern can be a simple `&str`, `char`, or a closure that
1218     /// determines
1219     /// the split.
1220     /// Additional libraries might provide more complex patterns like
1221     /// regular expressions.
1222     ///
1223     /// # Iterator behavior
1224     ///
1225     /// The returned iterator requires that the pattern supports a
1226     /// reverse search,
1227     /// and it will be double ended if a forward/reverse search yields
1228     /// the same elements.
1229     ///
1230     /// For iterating from the front, `match_indices()` can be used.
1231     ///
1232     /// # Examples
1233     ///
1234     /// ```
1235     /// #![feature(str_match_indices)]
1236     ///
1237     /// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1238     /// assert_eq!(v, [(12, 15), (6, 9), (0, 3)]);
1239     ///
1240     /// let v: Vec<(usize, usize)> = "1abcabc2".rmatch_indices("abc").collect();
1241     /// assert_eq!(v, [(4, 7), (1, 4)]);
1242     ///
1243     /// let v: Vec<(usize, usize)> = "ababa".rmatch_indices("aba").collect();
1244     /// assert_eq!(v, [(2, 5)]); // only the last `aba`
1245     /// ```
1246     #[unstable(feature = "str_match_indices",
1247                reason = "might have its iterator type changed",
1248                issue = "27743")]
1249     // NB: Right now RMatchIndices yields `(usize, usize)`, but it would
1250     // be more consistent with `rmatches` and `char_indices` to return `(usize, &str)`
1251     pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1252         where P::Searcher: ReverseSearcher<'a>
1253     {
1254         core_str::StrExt::rmatch_indices(self, pat)
1255     }
1256
1257     /// Returns a `&str` with leading and trailing whitespace removed.
1258     ///
1259     /// # Examples
1260     ///
1261     /// ```
1262     /// let s = " Hello\tworld\t";
1263     /// assert_eq!(s.trim(), "Hello\tworld");
1264     /// ```
1265     #[stable(feature = "rust1", since = "1.0.0")]
1266     pub fn trim(&self) -> &str {
1267         UnicodeStr::trim(self)
1268     }
1269
1270     /// Returns a `&str` with leading whitespace removed.
1271     ///
1272     /// # Examples
1273     ///
1274     /// ```
1275     /// let s = " Hello\tworld\t";
1276     /// assert_eq!(s.trim_left(), "Hello\tworld\t");
1277     /// ```
1278     #[stable(feature = "rust1", since = "1.0.0")]
1279     pub fn trim_left(&self) -> &str {
1280         UnicodeStr::trim_left(self)
1281     }
1282
1283     /// Returns a `&str` with trailing whitespace removed.
1284     ///
1285     /// # Examples
1286     ///
1287     /// ```
1288     /// let s = " Hello\tworld\t";
1289     /// assert_eq!(s.trim_right(), " Hello\tworld");
1290     /// ```
1291     #[stable(feature = "rust1", since = "1.0.0")]
1292     pub fn trim_right(&self) -> &str {
1293         UnicodeStr::trim_right(self)
1294     }
1295
1296     /// Returns a string with all pre- and suffixes that match a pattern
1297     /// repeatedly removed.
1298     ///
1299     /// The pattern can be a simple `char`, or a closure that determines
1300     /// the split.
1301     ///
1302     /// # Examples
1303     ///
1304     /// Simple patterns:
1305     ///
1306     /// ```
1307     /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1308     /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1309     ///
1310     /// let x: &[_] = &['1', '2'];
1311     /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1312     /// ```
1313     ///
1314     /// A more complex pattern, using a closure:
1315     ///
1316     /// ```
1317     /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1318     /// ```
1319     #[stable(feature = "rust1", since = "1.0.0")]
1320     pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1321         where P::Searcher: DoubleEndedSearcher<'a>
1322     {
1323         core_str::StrExt::trim_matches(self, pat)
1324     }
1325
1326     /// Returns a string with all prefixes that match a pattern
1327     /// repeatedly removed.
1328     ///
1329     /// The pattern can be a simple `&str`, `char`, or a closure that
1330     /// determines the split.
1331     ///
1332     /// # Examples
1333     ///
1334     /// ```
1335     /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1336     /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1337     ///
1338     /// let x: &[_] = &['1', '2'];
1339     /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1340     /// ```
1341     #[stable(feature = "rust1", since = "1.0.0")]
1342     pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1343         core_str::StrExt::trim_left_matches(self, pat)
1344     }
1345
1346     /// Returns a string with all suffixes that match a pattern
1347     /// repeatedly removed.
1348     ///
1349     /// The pattern can be a simple `&str`, `char`, or a closure that
1350     /// determines the split.
1351     ///
1352     /// # Examples
1353     ///
1354     /// Simple patterns:
1355     ///
1356     /// ```
1357     /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1358     /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1359     ///
1360     /// let x: &[_] = &['1', '2'];
1361     /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1362     /// ```
1363     ///
1364     /// A more complex pattern, using a closure:
1365     ///
1366     /// ```
1367     /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1368     /// ```
1369     #[stable(feature = "rust1", since = "1.0.0")]
1370     pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1371         where P::Searcher: ReverseSearcher<'a>
1372     {
1373         core_str::StrExt::trim_right_matches(self, pat)
1374     }
1375
1376     /// Parses `self` into the specified type.
1377     ///
1378     /// # Failure
1379     ///
1380     /// Will return `Err` if it's not possible to parse `self` into the type.
1381     ///
1382     /// # Example
1383     ///
1384     /// ```
1385     /// assert_eq!("4".parse::<u32>(), Ok(4));
1386     /// ```
1387     ///
1388     /// Failing:
1389     ///
1390     /// ```
1391     /// assert!("j".parse::<u32>().is_err());
1392     /// ```
1393     #[inline]
1394     #[stable(feature = "rust1", since = "1.0.0")]
1395     pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1396         core_str::StrExt::parse(self)
1397     }
1398
1399     /// Replaces all occurrences of one string with another.
1400     ///
1401     /// `replace` takes two arguments, a sub-`&str` to find in `self`, and a
1402     /// second `&str` to
1403     /// replace it with. If the original `&str` isn't found, no change occurs.
1404     ///
1405     /// # Examples
1406     ///
1407     /// ```
1408     /// let s = "this is old";
1409     ///
1410     /// assert_eq!(s.replace("old", "new"), "this is new");
1411     /// ```
1412     ///
1413     /// When a `&str` isn't found:
1414     ///
1415     /// ```
1416     /// let s = "this is old";
1417     /// assert_eq!(s.replace("cookie monster", "little lamb"), s);
1418     /// ```
1419     #[stable(feature = "rust1", since = "1.0.0")]
1420     pub fn replace(&self, from: &str, to: &str) -> String {
1421         let mut result = String::new();
1422         let mut last_end = 0;
1423         for (start, end) in self.match_indices(from) {
1424             result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1425             result.push_str(to);
1426             last_end = end;
1427         }
1428         result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1429         result
1430     }
1431
1432     /// Returns the lowercase equivalent of this string.
1433     ///
1434     /// # Examples
1435     ///
1436     /// ```
1437     /// let s = "HELLO";
1438     /// assert_eq!(s.to_lowercase(), "hello");
1439     /// ```
1440     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1441     pub fn to_lowercase(&self) -> String {
1442         let mut s = String::with_capacity(self.len());
1443         for (i, c) in self[..].char_indices() {
1444             if c == 'Σ' {
1445                 // Σ maps to σ, except at the end of a word where it maps to ς.
1446                 // This is the only conditional (contextual) but language-independent mapping
1447                 // in `SpecialCasing.txt`,
1448                 // so hard-code it rather than have a generic "condition" mechanim.
1449                 // See https://github.com/rust-lang/rust/issues/26035
1450                 map_uppercase_sigma(self, i, &mut s)
1451             } else {
1452                 s.extend(c.to_lowercase());
1453             }
1454         }
1455         return s;
1456
1457         fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1458             // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1459             // for the definition of `Final_Sigma`.
1460             debug_assert!('Σ'.len_utf8() == 2);
1461             let is_word_final =
1462                 case_ignoreable_then_cased(from[..i].chars().rev()) &&
1463                 !case_ignoreable_then_cased(from[i + 2..].chars());
1464             to.push_str(if is_word_final { "ς" } else { "σ" });
1465         }
1466
1467         fn case_ignoreable_then_cased<I: Iterator<Item=char>>(iter: I) -> bool {
1468             use rustc_unicode::derived_property::{Cased, Case_Ignorable};
1469             match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1470                 Some(c) => Cased(c),
1471                 None => false,
1472             }
1473         }
1474     }
1475
1476     /// Returns the uppercase equivalent of this string.
1477     ///
1478     /// # Examples
1479     ///
1480     /// ```
1481     /// let s = "hello";
1482     /// assert_eq!(s.to_uppercase(), "HELLO");
1483     /// ```
1484     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1485     pub fn to_uppercase(&self) -> String {
1486         let mut s = String::with_capacity(self.len());
1487         s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1488         return s;
1489     }
1490
1491     /// Escapes each char in `s` with `char::escape_default`.
1492     #[unstable(feature = "str_escape",
1493                reason = "return type may change to be an iterator",
1494                issue = "27791")]
1495     pub fn escape_default(&self) -> String {
1496         self.chars().flat_map(|c| c.escape_default()).collect()
1497     }
1498
1499     /// Escapes each char in `s` with `char::escape_unicode`.
1500     #[unstable(feature = "str_escape",
1501                reason = "return type may change to be an iterator",
1502                issue = "27791")]
1503     pub fn escape_unicode(&self) -> String {
1504         self.chars().flat_map(|c| c.escape_unicode()).collect()
1505     }
1506
1507     /// Converts the `Box<str>` into a `String` without copying or allocating.
1508     #[unstable(feature = "box_str",
1509                reason = "recently added, matches RFC",
1510                issue = "27785")]
1511     pub fn into_string(self: Box<str>) -> String {
1512         unsafe {
1513             let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1514             String::from_utf8_unchecked(slice.into_vec())
1515         }
1516     }
1517 }