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