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