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