]> git.lizzy.rs Git - rust.git/blob - src/libcollections/str.rs
libcollections: deny warnings in doctests
[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 #[allow(deprecated)]
42 pub use core::str::{Lines, LinesAny, CharRange};
43 pub use core::str::{Split, RSplit};
44 pub use core::str::{SplitN, RSplitN};
45 pub use core::str::{SplitTerminator, RSplitTerminator};
46 pub use core::str::{Matches, RMatches};
47 pub use core::str::{MatchIndices, RMatchIndices};
48 pub use core::str::{from_utf8, Chars, CharIndices, Bytes};
49 pub use core::str::{from_utf8_unchecked, ParseBoolError};
50 pub use rustc_unicode::str::{SplitWhitespace};
51 pub use core::str::pattern;
52
53 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
54     type Output = String;
55
56     fn concat(&self) -> String {
57         if self.is_empty() {
58             return String::new();
59         }
60
61         // `len` calculation may overflow but push_str will check boundaries
62         let len = self.iter().map(|s| s.borrow().len()).sum();
63         let mut result = String::with_capacity(len);
64
65         for s in self {
66             result.push_str(s.borrow())
67         }
68
69         result
70     }
71
72     fn join(&self, sep: &str) -> String {
73         if self.is_empty() {
74             return String::new();
75         }
76
77         // concat is faster
78         if sep.is_empty() {
79             return self.concat();
80         }
81
82         // this is wrong without the guarantee that `self` is non-empty
83         // `len` calculation may overflow but push_str but will check boundaries
84         let len = sep.len() * (self.len() - 1)
85             + self.iter().map(|s| s.borrow().len()).sum::<usize>();
86         let mut result = String::with_capacity(len);
87         let mut first = true;
88
89         for s in self {
90             if first {
91                 first = false;
92             } else {
93                 result.push_str(sep);
94             }
95             result.push_str(s.borrow());
96         }
97         result
98     }
99
100     fn connect(&self, sep: &str) -> String {
101         self.join(sep)
102     }
103 }
104
105 /// External iterator for a string's UTF-16 code units.
106 ///
107 /// For use with the `std::iter` module.
108 #[derive(Clone)]
109 #[unstable(feature = "str_utf16", issue = "27714")]
110 pub struct Utf16Units<'a> {
111     encoder: Utf16Encoder<Chars<'a>>
112 }
113
114 #[stable(feature = "rust1", since = "1.0.0")]
115 impl<'a> Iterator for Utf16Units<'a> {
116     type Item = u16;
117
118     #[inline]
119     fn next(&mut self) -> Option<u16> { self.encoder.next() }
120
121     #[inline]
122     fn size_hint(&self) -> (usize, Option<usize>) { self.encoder.size_hint() }
123 }
124
125 // Return the initial codepoint accumulator for the first byte.
126 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
127 // for width 3, and 3 bits for width 4
128 macro_rules! utf8_first_byte {
129     ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
130 }
131
132 // return the value of $ch updated with continuation byte $byte
133 macro_rules! utf8_acc_cont_byte {
134     ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63) as u32)
135 }
136
137 #[stable(feature = "rust1", since = "1.0.0")]
138 impl Borrow<str> for String {
139     #[inline]
140     fn borrow(&self) -> &str { &self[..] }
141 }
142
143 #[stable(feature = "rust1", since = "1.0.0")]
144 impl ToOwned for str {
145     type Owned = String;
146     fn to_owned(&self) -> String {
147         unsafe {
148             String::from_utf8_unchecked(self.as_bytes().to_owned())
149         }
150     }
151 }
152
153 /// Any string that can be represented as a slice.
154 #[lang = "str"]
155 #[cfg(not(test))]
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     /// # Safety
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     #[stable(feature = "str_slice_mut", since = "1.5.0")]
280     #[inline]
281     pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
282         core_str::StrExt::slice_mut_unchecked(self, begin, end)
283     }
284
285     /// Given a byte position, return the next code point and its index.
286     ///
287     /// This can be used to iterate over the Unicode code points of a string.
288     ///
289     /// # Panics
290     ///
291     /// If `i` is greater than or equal to the length of the string.
292     /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
293     ///
294     /// # Examples
295     ///
296     /// This example manually iterates through the code points of a string;
297     /// this should normally be
298     /// done by `.chars()` or `.char_indices()`.
299     ///
300     /// ```
301     /// #![feature(str_char)]
302     ///
303     /// use std::str::CharRange;
304     ///
305     /// let s = "中华Việt Nam";
306     /// let mut i = 0;
307     /// while i < s.len() {
308     ///     let CharRange {ch, next} = s.char_range_at(i);
309     ///     println!("{}: {}", i, ch);
310     ///     i = next;
311     /// }
312     /// ```
313     ///
314     /// This outputs:
315     ///
316     /// ```text
317     /// 0: 中
318     /// 3: 华
319     /// 6: V
320     /// 7: i
321     /// 8: e
322     /// 9:
323     /// 11:
324     /// 13: t
325     /// 14:
326     /// 15: N
327     /// 16: a
328     /// 17: m
329     /// ```
330     #[unstable(feature = "str_char",
331                reason = "often replaced by char_indices, this method may \
332                          be removed in favor of just char_at() or eventually \
333                          removed altogether",
334                issue = "27754")]
335     #[inline]
336     pub fn char_range_at(&self, start: usize) -> CharRange {
337         core_str::StrExt::char_range_at(self, start)
338     }
339
340     /// Given a byte position, return the previous `char` and its position.
341     ///
342     /// This function can be used to iterate over a Unicode code points in reverse.
343     ///
344     /// Note that Unicode has many features, such as combining marks, ligatures,
345     /// and direction marks, that need to be taken into account to correctly reverse a string.
346     ///
347     /// Returns 0 for next index if called on start index 0.
348     ///
349     /// # Panics
350     ///
351     /// If `i` is greater than the length of the string.
352     /// If `i` is not an index following a valid UTF-8 sequence.
353     ///
354     /// # Examples
355     ///
356     /// This example manually iterates through the code points of a string;
357     /// this should normally be
358     /// done by `.chars().rev()` or `.char_indices()`.
359     ///
360     /// ```
361     /// #![feature(str_char)]
362     ///
363     /// use std::str::CharRange;
364     ///
365     /// let s = "中华Việt Nam";
366     /// let mut i = s.len();
367     /// while i > 0 {
368     ///     let CharRange {ch, next} = s.char_range_at_reverse(i);
369     ///     println!("{}: {}", i, ch);
370     ///     i = next;
371     /// }
372     /// ```
373     ///
374     /// This outputs:
375     ///
376     /// ```text
377     /// 18: m
378     /// 17: a
379     /// 16: N
380     /// 15:
381     /// 14: t
382     /// 13:
383     /// 11:
384     /// 9: e
385     /// 8: i
386     /// 7: V
387     /// 6: 华
388     /// 3: 中
389     /// ```
390     #[unstable(feature = "str_char",
391                reason = "often replaced by char_indices, this method may \
392                          be removed in favor of just char_at_reverse() or \
393                          eventually removed altogether",
394                issue = "27754")]
395     #[inline]
396     pub fn char_range_at_reverse(&self, start: usize) -> CharRange {
397         core_str::StrExt::char_range_at_reverse(self, start)
398     }
399
400     /// Given a byte position, return the `char` at that position.
401     ///
402     /// # Panics
403     ///
404     /// If `i` is greater than or equal to the length of the string.
405     /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
406     ///
407     /// # Examples
408     ///
409     /// ```
410     /// #![feature(str_char)]
411     ///
412     /// let s = "abπc";
413     /// assert_eq!(s.char_at(1), 'b');
414     /// assert_eq!(s.char_at(2), 'π');
415     /// assert_eq!(s.char_at(4), 'c');
416     /// ```
417     #[unstable(feature = "str_char",
418                reason = "frequently replaced by the chars() iterator, this \
419                          method may be removed or possibly renamed in the \
420                          future; it is normally replaced by chars/char_indices \
421                          iterators or by getting the first char from a \
422                          subslice",
423                issue = "27754")]
424     #[inline]
425     pub fn char_at(&self, i: usize) -> char {
426         core_str::StrExt::char_at(self, i)
427     }
428
429     /// Given a byte position, return the `char` at that position, counting
430     /// from the end.
431     ///
432     /// # Panics
433     ///
434     /// If `i` is greater than the length of the string.
435     /// If `i` is not an index following a valid UTF-8 sequence.
436     ///
437     /// # Examples
438     ///
439     /// ```
440     /// #![feature(str_char)]
441     ///
442     /// let s = "abπc";
443     /// assert_eq!(s.char_at_reverse(1), 'a');
444     /// assert_eq!(s.char_at_reverse(2), 'b');
445     /// assert_eq!(s.char_at_reverse(3), 'π');
446     /// ```
447     #[unstable(feature = "str_char",
448                reason = "see char_at for more details, but reverse semantics \
449                          are also somewhat unclear, especially with which \
450                          cases generate panics",
451                issue = "27754")]
452     #[inline]
453     pub fn char_at_reverse(&self, i: usize) -> char {
454         core_str::StrExt::char_at_reverse(self, i)
455     }
456
457     /// Retrieves the first code point from a `&str` and returns it.
458     ///
459     /// Note that a single Unicode character (grapheme cluster)
460     /// can be composed of multiple `char`s.
461     ///
462     /// This does not allocate a new string; instead, it returns a slice that
463     /// points one code point beyond the code point that was shifted.
464     ///
465     /// `None` is returned if the slice is empty.
466     ///
467     /// # Examples
468     ///
469     /// ```
470     /// #![feature(str_char)]
471     ///
472     /// let s = "Łódź"; // \u{141}o\u{301}dz\u{301}
473     /// let (c, s1) = s.slice_shift_char().unwrap();
474     ///
475     /// assert_eq!(c, 'Ł');
476     /// assert_eq!(s1, "ódź");
477     ///
478     /// let (c, s2) = s1.slice_shift_char().unwrap();
479     ///
480     /// assert_eq!(c, 'o');
481     /// assert_eq!(s2, "\u{301}dz\u{301}");
482     /// ```
483     #[unstable(feature = "str_char",
484                reason = "awaiting conventions about shifting and slices and \
485                          may not be warranted with the existence of the chars \
486                          and/or char_indices iterators",
487                issue = "27754")]
488     #[inline]
489     pub fn slice_shift_char(&self) -> Option<(char, &str)> {
490         core_str::StrExt::slice_shift_char(self)
491     }
492
493     /// Divide one string slice into two at an index.
494     ///
495     /// The index `mid` is a byte offset from the start of the string
496     /// that must be on a `char` boundary.
497     ///
498     /// Return slices `&self[..mid]` and `&self[mid..]`.
499     ///
500     /// # Panics
501     ///
502     /// Panics if `mid` is beyond the last code point of the string,
503     /// or if it is not on a `char` boundary.
504     ///
505     /// # Examples
506     /// ```
507     /// let s = "Löwe 老虎 Léopard";
508     /// let first_space = s.find(' ').unwrap_or(s.len());
509     /// let (a, b) = s.split_at(first_space);
510     ///
511     /// assert_eq!(a, "Löwe");
512     /// assert_eq!(b, " 老虎 Léopard");
513     /// ```
514     #[inline]
515     #[stable(feature = "str_split_at", since = "1.4.0")]
516     pub fn split_at(&self, mid: usize) -> (&str, &str) {
517         core_str::StrExt::split_at(self, mid)
518     }
519
520     /// Divide one mutable string slice into two at an index.
521     #[inline]
522     #[stable(feature = "str_split_at", since = "1.4.0")]
523     pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
524         core_str::StrExt::split_at_mut(self, mid)
525     }
526
527     /// An iterator over the code points of `self`.
528     ///
529     /// In Unicode relationship between code points and characters is complex.
530     /// A single character may be composed of multiple code points
531     /// (e.g. diacritical marks added to a letter), and a single code point
532     /// (e.g. Hangul syllable) may contain multiple characters.
533     ///
534     /// For iteration over human-readable characters a grapheme cluster iterator
535     /// may be more appropriate. See the [unicode-segmentation crate][1].
536     ///
537     /// [1]: https://crates.io/crates/unicode-segmentation
538     ///
539     /// # Examples
540     ///
541     /// ```
542     /// let v: Vec<char> = "ASCII żółć 🇨🇭 한".chars().collect();
543     ///
544     /// assert_eq!(v, ['A', 'S', 'C', 'I', 'I', ' ',
545     ///     'z', '\u{307}', 'o', '\u{301}', 'ł', 'c', '\u{301}', ' ',
546     ///     '\u{1f1e8}', '\u{1f1ed}', ' ', '한']);
547     /// ```
548     #[stable(feature = "rust1", since = "1.0.0")]
549     #[inline]
550     pub fn chars(&self) -> Chars {
551         core_str::StrExt::chars(self)
552     }
553
554     /// An iterator over the `char`s of `self` and their byte offsets.
555     ///
556     /// # Examples
557     ///
558     /// ```
559     /// let v: Vec<(usize, char)> = "A🇨🇭".char_indices().collect();
560     /// let b = vec![(0, 'A'), (1, '\u{1f1e8}'), (5, '\u{1f1ed}')];
561     ///
562     /// assert_eq!(v, b);
563     /// ```
564     #[stable(feature = "rust1", since = "1.0.0")]
565     #[inline]
566     pub fn char_indices(&self) -> CharIndices {
567         core_str::StrExt::char_indices(self)
568     }
569
570     /// An iterator over the bytes of `self`.
571     ///
572     /// # Examples
573     ///
574     /// ```
575     /// let v: Vec<u8> = "bors".bytes().collect();
576     ///
577     /// assert_eq!(v, b"bors".to_vec());
578     /// ```
579     #[stable(feature = "rust1", since = "1.0.0")]
580     #[inline]
581     pub fn bytes(&self) -> Bytes {
582         core_str::StrExt::bytes(self)
583     }
584
585     /// An iterator over the non-empty substrings of `self` which contain no whitespace,
586     /// and which are separated by any amount of whitespace.
587     ///
588     /// # Examples
589     ///
590     /// ```
591     /// let some_words = " Mary   had\ta\u{2009}little  \n\t lamb";
592     /// let v: Vec<&str> = some_words.split_whitespace().collect();
593     ///
594     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
595     /// ```
596     #[stable(feature = "split_whitespace", since = "1.1.0")]
597     #[inline]
598     pub fn split_whitespace(&self) -> SplitWhitespace {
599         UnicodeStr::split_whitespace(self)
600     }
601
602     /// An iterator over the lines of a string, separated by `\n` or `\r\n`.
603     ///
604     /// This does not include the empty string after a trailing newline or CRLF.
605     ///
606     /// # Examples
607     ///
608     /// ```
609     /// let four_lines = "foo\nbar\n\r\nbaz";
610     /// let v: Vec<&str> = four_lines.lines().collect();
611     ///
612     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
613     /// ```
614     ///
615     /// Leaving off the trailing character:
616     ///
617     /// ```
618     /// let four_lines = "foo\r\nbar\n\nbaz\n";
619     /// let v: Vec<&str> = four_lines.lines().collect();
620     ///
621     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
622     /// ```
623     #[stable(feature = "rust1", since = "1.0.0")]
624     #[inline]
625     pub fn lines(&self) -> Lines {
626         core_str::StrExt::lines(self)
627     }
628
629     /// An iterator over the lines of a string, separated by either
630     /// `\n` or `\r\n`.
631     ///
632     /// As with `.lines()`, this does not include an empty trailing line.
633     ///
634     /// # Examples
635     ///
636     /// ```
637     /// # #![allow(deprecated)]
638     /// let four_lines = "foo\r\nbar\n\r\nbaz";
639     /// let v: Vec<&str> = four_lines.lines_any().collect();
640     ///
641     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
642     /// ```
643     ///
644     /// Leaving off the trailing character:
645     ///
646     /// ```
647     /// # #![allow(deprecated)]
648     /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
649     /// let v: Vec<&str> = four_lines.lines_any().collect();
650     ///
651     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
652     /// ```
653     #[stable(feature = "rust1", since = "1.0.0")]
654     #[deprecated(since = "1.4.0", reason = "use lines() instead now")]
655     #[inline]
656     #[allow(deprecated)]
657     pub fn lines_any(&self) -> LinesAny {
658         core_str::StrExt::lines_any(self)
659     }
660
661     /// Returns an iterator of `u16` over the string encoded as UTF-16.
662     #[unstable(feature = "str_utf16",
663                reason = "this functionality may only be provided by libunicode",
664                issue = "27714")]
665     pub fn utf16_units(&self) -> Utf16Units {
666         Utf16Units { encoder: Utf16Encoder::new(self[..].chars()) }
667     }
668
669     /// Returns `true` if `self` contains another `&str`.
670     ///
671     /// # Examples
672     ///
673     /// ```
674     /// assert!("bananas".contains("nana"));
675     ///
676     /// assert!(!"bananas".contains("foobar"));
677     /// ```
678     #[stable(feature = "rust1", since = "1.0.0")]
679     pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
680         core_str::StrExt::contains(self, pat)
681     }
682
683     /// Returns `true` if the given `&str` is a prefix of the string.
684     ///
685     /// # Examples
686     ///
687     /// ```
688     /// assert!("banana".starts_with("ba"));
689     /// ```
690     #[stable(feature = "rust1", since = "1.0.0")]
691     pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
692         core_str::StrExt::starts_with(self, pat)
693     }
694
695     /// Returns true if the given `&str` is a suffix of the string.
696     ///
697     /// # Examples
698     ///
699     /// ```rust
700     /// assert!("banana".ends_with("nana"));
701     /// ```
702     #[stable(feature = "rust1", since = "1.0.0")]
703     pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
704         where P::Searcher: ReverseSearcher<'a>
705     {
706         core_str::StrExt::ends_with(self, pat)
707     }
708
709     /// Returns the byte index of the first character of `self` that matches
710     /// the pattern, if it
711     /// exists.
712     ///
713     /// Returns `None` if it doesn't exist.
714     ///
715     /// The pattern can be a simple `&str`, `char`, or a closure that
716     /// determines if a character matches.
717     ///
718     /// # Examples
719     ///
720     /// Simple patterns:
721     ///
722     /// ```
723     /// let s = "Löwe 老虎 Léopard";
724     ///
725     /// assert_eq!(s.find('L'), Some(0));
726     /// assert_eq!(s.find('é'), Some(14));
727     /// assert_eq!(s.find("Léopard"), Some(13));
728     ///
729     /// ```
730     ///
731     /// More complex patterns with closures:
732     ///
733     /// ```
734     /// let s = "Löwe 老虎 Léopard";
735     ///
736     /// assert_eq!(s.find(char::is_whitespace), Some(5));
737     /// assert_eq!(s.find(char::is_lowercase), Some(1));
738     /// ```
739     ///
740     /// Not finding the pattern:
741     ///
742     /// ```
743     /// let s = "Löwe 老虎 Léopard";
744     /// let x: &[_] = &['1', '2'];
745     ///
746     /// assert_eq!(s.find(x), None);
747     /// ```
748     #[stable(feature = "rust1", since = "1.0.0")]
749     pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
750         core_str::StrExt::find(self, pat)
751     }
752
753     /// Returns the byte index of the last character of `self` that
754     /// matches the pattern, if it
755     /// exists.
756     ///
757     /// Returns `None` if it doesn't exist.
758     ///
759     /// The pattern can be a simple `&str`, `char`,
760     /// or a closure that determines if a character matches.
761     ///
762     /// # Examples
763     ///
764     /// Simple patterns:
765     ///
766     /// ```
767     /// let s = "Löwe 老虎 Léopard";
768     ///
769     /// assert_eq!(s.rfind('L'), Some(13));
770     /// assert_eq!(s.rfind('é'), Some(14));
771     /// ```
772     ///
773     /// More complex patterns with closures:
774     ///
775     /// ```
776     /// let s = "Löwe 老虎 Léopard";
777     ///
778     /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
779     /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
780     /// ```
781     ///
782     /// Not finding the pattern:
783     ///
784     /// ```
785     /// let s = "Löwe 老虎 Léopard";
786     /// let x: &[_] = &['1', '2'];
787     ///
788     /// assert_eq!(s.rfind(x), None);
789     /// ```
790     #[stable(feature = "rust1", since = "1.0.0")]
791     pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
792         where P::Searcher: ReverseSearcher<'a>
793     {
794         core_str::StrExt::rfind(self, pat)
795     }
796
797     /// An iterator over substrings of `self`, separated by characters
798     /// matched by a pattern.
799     ///
800     /// The pattern can be a simple `&str`, `char`, or a closure that
801     /// determines the split. Additional libraries might provide more complex
802     /// patterns like regular expressions.
803     ///
804     /// # Iterator behavior
805     ///
806     /// The returned iterator will be double ended if the pattern allows a
807     /// reverse search and forward/reverse search yields the same elements.
808     /// This is true for, eg, `char` but not
809     /// for `&str`.
810     ///
811     /// If the pattern allows a reverse search but its results might differ
812     /// from a forward search, `rsplit()` can be used.
813     ///
814     /// # Examples
815     ///
816     /// Simple patterns:
817     ///
818     /// ```
819     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
820     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
821     ///
822     /// let v: Vec<&str> = "".split('X').collect();
823     /// assert_eq!(v, [""]);
824     ///
825     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
826     /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
827     ///
828     /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
829     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
830     ///
831     /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
832     /// assert_eq!(v, ["abc", "def", "ghi"]);
833     ///
834     /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
835     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
836     /// ```
837     ///
838     /// A more complex pattern, using a closure:
839     ///
840     /// ```
841     /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
842     /// assert_eq!(v, ["abc", "def", "ghi"]);
843     /// ```
844     ///
845     /// If a string contains multiple contiguous separators, you will end up
846     /// with empty strings in the output:
847     ///
848     /// ```
849     /// let x = "||||a||b|c".to_string();
850     /// let d: Vec<_> = x.split('|').collect();
851     ///
852     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
853     /// ```
854     ///
855     /// This can lead to possibly surprising behavior when whitespace is used
856     /// as the separator. This code is correct:
857     ///
858     /// ```
859     /// let x = "    a  b c".to_string();
860     /// let d: Vec<_> = x.split(' ').collect();
861     ///
862     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
863     /// ```
864     ///
865     /// It does _not_ give you:
866     ///
867     /// ```rust,ignore
868     /// assert_eq!(d, &["a", "b", "c"]);
869     /// ```
870     ///
871     /// Use [`.split_whitespace()`][split_whitespace] for this behavior.
872     ///
873     /// [split_whitespace]: #method.split_whitespace
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 if a character matches.
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 if a character matches.
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 disjoint matches of a pattern within `self` as well
1163     /// as the index that the match starts at.
1164     ///
1165     /// For matches of `pat` within `self` that overlap, only the indices
1166     /// corresponding to the first match are returned.
1167     ///
1168     /// The pattern can be a simple `&str`, `char`, or a closure that determines
1169     /// if a character matches. Additional libraries might provide more complex
1170     /// patterns like regular expressions.
1171     ///
1172     /// # Iterator behavior
1173     ///
1174     /// The returned iterator will be double ended if the pattern allows a
1175     /// reverse search and forward/reverse search yields the same elements. This
1176     /// is true for, eg, `char` but not for `&str`.
1177     ///
1178     /// If the pattern allows a reverse search but its results might differ
1179     /// from a forward search, `rmatch_indices()` can be used.
1180     ///
1181     /// # Examples
1182     ///
1183     /// ```
1184     /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1185     /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1186     ///
1187     /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1188     /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1189     ///
1190     /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1191     /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1192     /// ```
1193     #[stable(feature = "str_match_indices", since = "1.5.0")]
1194     pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1195         core_str::StrExt::match_indices(self, pat)
1196     }
1197
1198     /// An iterator over the disjoint matches of a pattern within `self`,
1199     /// yielded in reverse order along with the index of the match.
1200     ///
1201     /// For matches of `pat` within `self` that overlap, only the indices
1202     /// corresponding to the last match are returned.
1203     ///
1204     /// The pattern can be a simple `&str`, `char`, or a closure that determines
1205     /// if a character matches. Additional libraries might provide more complex
1206     /// patterns like regular expressions.
1207     ///
1208     /// # Iterator behavior
1209     ///
1210     /// The returned iterator requires that the pattern supports a reverse
1211     /// search, and it will be double ended if a forward/reverse search yields
1212     /// the same elements.
1213     ///
1214     /// For iterating from the front, `match_indices()` can be used.
1215     ///
1216     /// # Examples
1217     ///
1218     /// ```
1219     /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1220     /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1221     ///
1222     /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1223     /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1224     ///
1225     /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1226     /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1227     /// ```
1228     #[stable(feature = "str_match_indices", since = "1.5.0")]
1229     pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1230         where P::Searcher: ReverseSearcher<'a>
1231     {
1232         core_str::StrExt::rmatch_indices(self, pat)
1233     }
1234
1235     /// Returns a `&str` with leading and trailing whitespace removed.
1236     ///
1237     /// # Examples
1238     ///
1239     /// ```
1240     /// let s = " Hello\tworld\t";
1241     /// assert_eq!(s.trim(), "Hello\tworld");
1242     /// ```
1243     #[stable(feature = "rust1", since = "1.0.0")]
1244     pub fn trim(&self) -> &str {
1245         UnicodeStr::trim(self)
1246     }
1247
1248     /// Returns a `&str` with leading whitespace removed.
1249     ///
1250     /// # Examples
1251     ///
1252     /// ```
1253     /// let s = " Hello\tworld\t";
1254     /// assert_eq!(s.trim_left(), "Hello\tworld\t");
1255     /// ```
1256     #[stable(feature = "rust1", since = "1.0.0")]
1257     pub fn trim_left(&self) -> &str {
1258         UnicodeStr::trim_left(self)
1259     }
1260
1261     /// Returns a `&str` with trailing whitespace removed.
1262     ///
1263     /// # Examples
1264     ///
1265     /// ```
1266     /// let s = " Hello\tworld\t";
1267     /// assert_eq!(s.trim_right(), " Hello\tworld");
1268     /// ```
1269     #[stable(feature = "rust1", since = "1.0.0")]
1270     pub fn trim_right(&self) -> &str {
1271         UnicodeStr::trim_right(self)
1272     }
1273
1274     /// Returns a string with all pre- and suffixes that match a pattern
1275     /// repeatedly removed.
1276     ///
1277     /// The pattern can be a simple `char`, or a closure that determines
1278     /// if a character matches.
1279     ///
1280     /// # Examples
1281     ///
1282     /// Simple patterns:
1283     ///
1284     /// ```
1285     /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1286     /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1287     ///
1288     /// let x: &[_] = &['1', '2'];
1289     /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1290     /// ```
1291     ///
1292     /// A more complex pattern, using a closure:
1293     ///
1294     /// ```
1295     /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1296     /// ```
1297     #[stable(feature = "rust1", since = "1.0.0")]
1298     pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1299         where P::Searcher: DoubleEndedSearcher<'a>
1300     {
1301         core_str::StrExt::trim_matches(self, pat)
1302     }
1303
1304     /// Returns a string with all prefixes that match a pattern
1305     /// repeatedly removed.
1306     ///
1307     /// The pattern can be a simple `&str`, `char`, or a closure that
1308     /// determines if a character matches.
1309     ///
1310     /// # Examples
1311     ///
1312     /// ```
1313     /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1314     /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1315     ///
1316     /// let x: &[_] = &['1', '2'];
1317     /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1318     /// ```
1319     #[stable(feature = "rust1", since = "1.0.0")]
1320     pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1321         core_str::StrExt::trim_left_matches(self, pat)
1322     }
1323
1324     /// Returns a string with all suffixes that match a pattern
1325     /// repeatedly removed.
1326     ///
1327     /// The pattern can be a simple `&str`, `char`, or a closure that
1328     /// determines if a character matches.
1329     ///
1330     /// # Examples
1331     ///
1332     /// Simple patterns:
1333     ///
1334     /// ```
1335     /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1336     /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1337     ///
1338     /// let x: &[_] = &['1', '2'];
1339     /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1340     /// ```
1341     ///
1342     /// A more complex pattern, using a closure:
1343     ///
1344     /// ```
1345     /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1346     /// ```
1347     #[stable(feature = "rust1", since = "1.0.0")]
1348     pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1349         where P::Searcher: ReverseSearcher<'a>
1350     {
1351         core_str::StrExt::trim_right_matches(self, pat)
1352     }
1353
1354     /// Parses `self` into the specified type.
1355     ///
1356     /// # Failure
1357     ///
1358     /// Will return `Err` if it's not possible to parse `self` into the type.
1359     ///
1360     /// # Example
1361     ///
1362     /// ```
1363     /// assert_eq!("4".parse::<u32>(), Ok(4));
1364     /// ```
1365     ///
1366     /// Failing:
1367     ///
1368     /// ```
1369     /// assert!("j".parse::<u32>().is_err());
1370     /// ```
1371     #[inline]
1372     #[stable(feature = "rust1", since = "1.0.0")]
1373     pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1374         core_str::StrExt::parse(self)
1375     }
1376
1377     /// Replaces all occurrences of one string with another.
1378     ///
1379     /// `replace` takes two arguments, a sub-`&str` to find in `self`, and a
1380     /// second `&str` to
1381     /// replace it with. If the original `&str` isn't found, no change occurs.
1382     ///
1383     /// # Examples
1384     ///
1385     /// ```
1386     /// let s = "this is old";
1387     ///
1388     /// assert_eq!(s.replace("old", "new"), "this is new");
1389     /// ```
1390     ///
1391     /// When a `&str` isn't found:
1392     ///
1393     /// ```
1394     /// let s = "this is old";
1395     /// assert_eq!(s.replace("cookie monster", "little lamb"), s);
1396     /// ```
1397     #[stable(feature = "rust1", since = "1.0.0")]
1398     pub fn replace(&self, from: &str, to: &str) -> String {
1399         let mut result = String::new();
1400         let mut last_end = 0;
1401         for (start, part) in self.match_indices(from) {
1402             result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1403             result.push_str(to);
1404             last_end = start + part.len();
1405         }
1406         result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1407         result
1408     }
1409
1410     /// Returns the lowercase equivalent of this string.
1411     ///
1412     /// # Examples
1413     ///
1414     /// ```
1415     /// let s = "HELLO";
1416     /// assert_eq!(s.to_lowercase(), "hello");
1417     /// ```
1418     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1419     pub fn to_lowercase(&self) -> String {
1420         let mut s = String::with_capacity(self.len());
1421         for (i, c) in self[..].char_indices() {
1422             if c == 'Σ' {
1423                 // Σ maps to σ, except at the end of a word where it maps to ς.
1424                 // This is the only conditional (contextual) but language-independent mapping
1425                 // in `SpecialCasing.txt`,
1426                 // so hard-code it rather than have a generic "condition" mechanim.
1427                 // See https://github.com/rust-lang/rust/issues/26035
1428                 map_uppercase_sigma(self, i, &mut s)
1429             } else {
1430                 s.extend(c.to_lowercase());
1431             }
1432         }
1433         return s;
1434
1435         fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1436             // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1437             // for the definition of `Final_Sigma`.
1438             debug_assert!('Σ'.len_utf8() == 2);
1439             let is_word_final =
1440                 case_ignoreable_then_cased(from[..i].chars().rev()) &&
1441                 !case_ignoreable_then_cased(from[i + 2..].chars());
1442             to.push_str(if is_word_final { "ς" } else { "σ" });
1443         }
1444
1445         fn case_ignoreable_then_cased<I: Iterator<Item=char>>(iter: I) -> bool {
1446             use rustc_unicode::derived_property::{Cased, Case_Ignorable};
1447             match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1448                 Some(c) => Cased(c),
1449                 None => false,
1450             }
1451         }
1452     }
1453
1454     /// Returns the uppercase equivalent of this string.
1455     ///
1456     /// # Examples
1457     ///
1458     /// ```
1459     /// let s = "hello";
1460     /// assert_eq!(s.to_uppercase(), "HELLO");
1461     /// ```
1462     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1463     pub fn to_uppercase(&self) -> String {
1464         let mut s = String::with_capacity(self.len());
1465         s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1466         return s;
1467     }
1468
1469     /// Escapes each char in `s` with `char::escape_default`.
1470     #[unstable(feature = "str_escape",
1471                reason = "return type may change to be an iterator",
1472                issue = "27791")]
1473     pub fn escape_default(&self) -> String {
1474         self.chars().flat_map(|c| c.escape_default()).collect()
1475     }
1476
1477     /// Escapes each char in `s` with `char::escape_unicode`.
1478     #[unstable(feature = "str_escape",
1479                reason = "return type may change to be an iterator",
1480                issue = "27791")]
1481     pub fn escape_unicode(&self) -> String {
1482         self.chars().flat_map(|c| c.escape_unicode()).collect()
1483     }
1484
1485     /// Converts the `Box<str>` into a `String` without copying or allocating.
1486     #[stable(feature = "box_str", since = "1.4.0")]
1487     pub fn into_string(self: Box<str>) -> String {
1488         unsafe {
1489             let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1490             String::from_utf8_unchecked(slice.into_vec())
1491         }
1492     }
1493 }