]> git.lizzy.rs Git - rust.git/blob - src/libcollections/str.rs
Make `str::as_bytes_mut` private
[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     /// Returns a raw pointer to the `&str`'s buffer.
483     ///
484     /// The caller must ensure that the string outlives this pointer, and
485     /// that it is not
486     /// reallocated (e.g. by pushing to the string).
487     ///
488     /// # Examples
489     ///
490     /// ```
491     /// let s = "Hello";
492     /// let p = s.as_ptr();
493     /// ```
494     #[stable(feature = "rust1", since = "1.0.0")]
495     #[inline]
496     pub fn as_ptr(&self) -> *const u8 {
497         core_str::StrExt::as_ptr(self)
498     }
499
500     /// Takes a bytewise slice from a string.
501     ///
502     /// Returns the substring from [`begin`..`end`).
503     ///
504     /// # Unsafety
505     ///
506     /// Caller must check both UTF-8 sequence boundaries and the boundaries
507     /// of the entire slice as well.
508     ///
509     /// # Examples
510     ///
511     /// ```
512     /// let s = "Löwe 老虎 Léopard";
513     ///
514     /// unsafe {
515     ///     assert_eq!(s.slice_unchecked(0, 21), "Löwe 老虎 Léopard");
516     /// }
517     /// ```
518     #[stable(feature = "rust1", since = "1.0.0")]
519     #[inline]
520     pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
521         core_str::StrExt::slice_unchecked(self, begin, end)
522     }
523
524     /// Takes a bytewise mutable slice from a string.
525     ///
526     /// Same as `slice_unchecked`, but works with `&mut str` instead of `&str`.
527     #[unstable(feature = "str_slice_mut", reason = "recently added")]
528     #[inline]
529     pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
530         core_str::StrExt::slice_mut_unchecked(self, begin, end)
531     }
532
533     /// Returns a slice of the string from the range [`begin`..`end`) where indices
534     /// are counted in code points.
535     ///
536     /// That is, start at the `begin`-th code point of the string and continue
537     /// to the `end`-th code point. This does not detect or handle edge cases
538     /// such as leaving a combining character as the first `char` of the
539     /// string.
540     ///
541     /// Due to the design of UTF-8, this operation is `O(end)`. Use slicing
542     /// syntax if you want to use `O(1)` byte indices instead.
543     ///
544     /// # Panics
545     ///
546     /// Panics if `begin` > `end` or the either `begin` or `end` are beyond the
547     /// last character of the string.
548     ///
549     /// # Examples
550     ///
551     /// ```
552     /// #![feature(slice_chars)]
553     ///
554     /// let s = "Löwe 老虎 Léopard";
555     ///
556     /// assert_eq!(s.slice_chars(0, 4), "Löwe");
557     /// assert_eq!(s.slice_chars(5, 7), "老虎");
558     /// ```
559     #[unstable(feature = "slice_chars",
560                reason = "may have yet to prove its worth")]
561     #[deprecated(since = "1.3.0",
562                  reason = "can be implemented with char_indices and \
563                            hasn't seen enough use to justify inclusion")]
564     #[inline]
565     pub fn slice_chars(&self, begin: usize, end: usize) -> &str {
566         core_str::StrExt::slice_chars(self, begin, end)
567     }
568
569     /// Given a byte position, return the next code point and its index.
570     ///
571     /// This can be used to iterate over the Unicode code points of a string.
572     ///
573     /// # Panics
574     ///
575     /// If `i` is greater than or equal to the length of the string.
576     /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
577     ///
578     /// # Examples
579     ///
580     /// This example manually iterates through the code points of a string;
581     /// this should normally be
582     /// done by `.chars()` or `.char_indices()`.
583     ///
584     /// ```
585     /// #![feature(str_char, core)]
586     ///
587     /// use std::str::CharRange;
588     ///
589     /// let s = "中华Việt Nam";
590     /// let mut i = 0;
591     /// while i < s.len() {
592     ///     let CharRange {ch, next} = s.char_range_at(i);
593     ///     println!("{}: {}", i, ch);
594     ///     i = next;
595     /// }
596     /// ```
597     ///
598     /// This outputs:
599     ///
600     /// ```text
601     /// 0: 中
602     /// 3: 华
603     /// 6: V
604     /// 7: i
605     /// 8: e
606     /// 9: ̣
607     /// 11: ̂
608     /// 13: t
609     /// 14:
610     /// 15: N
611     /// 16: a
612     /// 17: m
613     /// ```
614     #[unstable(feature = "str_char",
615                reason = "often replaced by char_indices, this method may \
616                          be removed in favor of just char_at() or eventually \
617                          removed altogether")]
618     #[inline]
619     pub fn char_range_at(&self, start: usize) -> CharRange {
620         core_str::StrExt::char_range_at(self, start)
621     }
622
623     /// Given a byte position, return the previous `char` and its position.
624     ///
625     /// This function can be used to iterate over a Unicode code points in reverse.
626     ///
627     /// Note that Unicode has many features, such as combining marks, ligatures,
628     /// and direction marks, that need to be taken into account to correctly reverse a string.
629     ///
630     /// Returns 0 for next index if called on start index 0.
631     ///
632     /// # Panics
633     ///
634     /// If `i` is greater than the length of the string.
635     /// If `i` is not an index following a valid UTF-8 sequence.
636     ///
637     /// # Examples
638     ///
639     /// This example manually iterates through the code points of a string;
640     /// this should normally be
641     /// done by `.chars().rev()` or `.char_indices()`.
642     ///
643     /// ```
644     /// #![feature(str_char, core)]
645     ///
646     /// use std::str::CharRange;
647     ///
648     /// let s = "中华Việt Nam";
649     /// let mut i = s.len();
650     /// while i > 0 {
651     ///     let CharRange {ch, next} = s.char_range_at_reverse(i);
652     ///     println!("{}: {}", i, ch);
653     ///     i = next;
654     /// }
655     /// ```
656     ///
657     /// This outputs:
658     ///
659     /// ```text
660     /// 18: m
661     /// 17: a
662     /// 16: N
663     /// 15:
664     /// 14: t
665     /// 13: ̂
666     /// 11: ̣
667     /// 9: e
668     /// 8: i
669     /// 7: V
670     /// 6: 华
671     /// 3: 中
672     /// ```
673     #[unstable(feature = "str_char",
674                reason = "often replaced by char_indices, this method may \
675                          be removed in favor of just char_at_reverse() or \
676                          eventually removed altogether")]
677     #[inline]
678     pub fn char_range_at_reverse(&self, start: usize) -> CharRange {
679         core_str::StrExt::char_range_at_reverse(self, start)
680     }
681
682     /// Given a byte position, return the `char` at that position.
683     ///
684     /// # Panics
685     ///
686     /// If `i` is greater than or equal to the length of the string.
687     /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
688     ///
689     /// # Examples
690     ///
691     /// ```
692     /// #![feature(str_char)]
693     ///
694     /// let s = "abπc";
695     /// assert_eq!(s.char_at(1), 'b');
696     /// assert_eq!(s.char_at(2), 'π');
697     /// assert_eq!(s.char_at(4), 'c');
698     /// ```
699     #[unstable(feature = "str_char",
700                reason = "frequently replaced by the chars() iterator, this \
701                          method may be removed or possibly renamed in the \
702                          future; it is normally replaced by chars/char_indices \
703                          iterators or by getting the first char from a \
704                          subslice")]
705     #[inline]
706     pub fn char_at(&self, i: usize) -> char {
707         core_str::StrExt::char_at(self, i)
708     }
709
710     /// Given a byte position, return the `char` at that position, counting
711     /// from the end.
712     ///
713     /// # Panics
714     ///
715     /// If `i` is greater than the length of the string.
716     /// If `i` is not an index following a valid UTF-8 sequence.
717     ///
718     /// # Examples
719     ///
720     /// ```
721     /// #![feature(str_char)]
722     ///
723     /// let s = "abπc";
724     /// assert_eq!(s.char_at_reverse(1), 'a');
725     /// assert_eq!(s.char_at_reverse(2), 'b');
726     /// assert_eq!(s.char_at_reverse(3), 'π');
727     /// ```
728     #[unstable(feature = "str_char",
729                reason = "see char_at for more details, but reverse semantics \
730                          are also somewhat unclear, especially with which \
731                          cases generate panics")]
732     #[inline]
733     pub fn char_at_reverse(&self, i: usize) -> char {
734         core_str::StrExt::char_at_reverse(self, i)
735     }
736
737     /// Retrieves the first code point from a `&str` and returns it.
738     ///
739     /// Note that a single Unicode character (grapheme cluster)
740     /// can be composed of multiple `char`s.
741     ///
742     /// This does not allocate a new string; instead, it returns a slice that
743     /// points one code point beyond the code point that was shifted.
744     ///
745     /// `None` is returned if the slice is empty.
746     ///
747     /// # Examples
748     ///
749     /// ```
750     /// #![feature(str_char)]
751     ///
752     /// let s = "Łódź"; // \u{141}o\u{301}dz\u{301}
753     /// let (c, s1) = s.slice_shift_char().unwrap();
754     ///
755     /// assert_eq!(c, 'Ł');
756     /// assert_eq!(s1, "ódź");
757     ///
758     /// let (c, s2) = s1.slice_shift_char().unwrap();
759     ///
760     /// assert_eq!(c, 'o');
761     /// assert_eq!(s2, "\u{301}dz\u{301}");
762     /// ```
763     #[unstable(feature = "str_char",
764                reason = "awaiting conventions about shifting and slices and \
765                          may not be warranted with the existence of the chars \
766                          and/or char_indices iterators")]
767     #[inline]
768     pub fn slice_shift_char(&self) -> Option<(char, &str)> {
769         core_str::StrExt::slice_shift_char(self)
770     }
771
772     /// Divide one string slice into two at an index.
773     ///
774     /// The index `mid` is a byte offset from the start of the string
775     /// that must be on a `char` boundary.
776     ///
777     /// Return slices `&self[..mid]` and `&self[mid..]`.
778     ///
779     /// # Panics
780     ///
781     /// Panics if `mid` is beyond the last code point of the string,
782     /// or if it is not on a `char` boundary.
783     ///
784     /// # Examples
785     /// ```
786     /// #![feature(str_split_at)]
787     ///
788     /// let s = "Löwe 老虎 Léopard";
789     /// let first_space = s.find(' ').unwrap_or(s.len());
790     /// let (a, b) = s.split_at(first_space);
791     ///
792     /// assert_eq!(a, "Löwe");
793     /// assert_eq!(b, " 老虎 Léopard");
794     /// ```
795     #[inline]
796     #[unstable(feature = "str_split_at", reason = "recently added")]
797     pub fn split_at(&self, mid: usize) -> (&str, &str) {
798         core_str::StrExt::split_at(self, mid)
799     }
800
801     /// Divide one mutable string slice into two at an index.
802     #[inline]
803     #[unstable(feature = "str_split_at", reason = "recently added")]
804     pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
805         core_str::StrExt::split_at_mut(self, mid)
806     }
807
808     /// An iterator over the code points of `self`.
809     ///
810     /// In Unicode relationship between code points and characters is complex.
811     /// A single character may be composed of multiple code points
812     /// (e.g. diacritical marks added to a letter), and a single code point
813     /// (e.g. Hangul syllable) may contain multiple characters.
814     ///
815     /// For iteration over human-readable characters a grapheme cluster iterator
816     /// may be more appropriate. See the [unicode-segmentation crate][1].
817     ///
818     /// [1]: https://crates.io/crates/unicode-segmentation
819     ///
820     /// # Examples
821     ///
822     /// ```
823     /// let v: Vec<char> = "ASCII żółć 🇨🇭 한".chars().collect();
824     ///
825     /// assert_eq!(v, ['A', 'S', 'C', 'I', 'I', ' ',
826     ///     'z', '\u{307}', 'o', '\u{301}', 'ł', 'c', '\u{301}', ' ',
827     ///     '\u{1f1e8}', '\u{1f1ed}', ' ', '한']);
828     /// ```
829     #[stable(feature = "rust1", since = "1.0.0")]
830     #[inline]
831     pub fn chars(&self) -> Chars {
832         core_str::StrExt::chars(self)
833     }
834
835     /// An iterator over the `char`s of `self` and their byte offsets.
836     ///
837     /// # Examples
838     ///
839     /// ```
840     /// let v: Vec<(usize, char)> = "A🇨🇭".char_indices().collect();
841     /// let b = vec![(0, 'A'), (1, '\u{1f1e8}'), (5, '\u{1f1ed}')];
842     ///
843     /// assert_eq!(v, b);
844     /// ```
845     #[stable(feature = "rust1", since = "1.0.0")]
846     #[inline]
847     pub fn char_indices(&self) -> CharIndices {
848         core_str::StrExt::char_indices(self)
849     }
850
851     /// An iterator over the bytes of `self`.
852     ///
853     /// # Examples
854     ///
855     /// ```
856     /// let v: Vec<u8> = "bors".bytes().collect();
857     ///
858     /// assert_eq!(v, b"bors".to_vec());
859     /// ```
860     #[stable(feature = "rust1", since = "1.0.0")]
861     #[inline]
862     pub fn bytes(&self) -> Bytes {
863         core_str::StrExt::bytes(self)
864     }
865
866     /// An iterator over the non-empty substrings of `self` which contain no whitespace,
867     /// and which are separated by any amount of whitespace.
868     ///
869     /// # Examples
870     ///
871     /// ```
872     /// let some_words = " Mary   had\ta\u{2009}little  \n\t lamb";
873     /// let v: Vec<&str> = some_words.split_whitespace().collect();
874     ///
875     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
876     /// ```
877     #[stable(feature = "split_whitespace", since = "1.1.0")]
878     #[inline]
879     pub fn split_whitespace(&self) -> SplitWhitespace {
880         UnicodeStr::split_whitespace(self)
881     }
882
883     /// An iterator over the non-empty substrings of `self` which contain no whitespace,
884     /// and which are separated by any amount of whitespace.
885     ///
886     /// # Examples
887     ///
888     /// ```
889     /// #![feature(str_words)]
890     /// #![allow(deprecated)]
891     ///
892     /// let some_words = " Mary   had\ta\u{2009}little  \n\t lamb";
893     /// let v: Vec<&str> = some_words.words().collect();
894     ///
895     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
896     /// ```
897     #[deprecated(reason = "words() will be removed. Use split_whitespace() instead",
898                  since = "1.1.0")]
899     #[unstable(feature = "str_words",
900                reason = "the precise algorithm to use is unclear")]
901     #[allow(deprecated)]
902     #[inline]
903     pub fn words(&self) -> Words {
904         UnicodeStr::words(self)
905     }
906
907     /// An iterator over the lines of a string, separated by `\n`.
908     ///
909     /// This does not include the empty string after a trailing `\n`.
910     ///
911     /// # Examples
912     ///
913     /// ```
914     /// let four_lines = "foo\nbar\n\nbaz";
915     /// let v: Vec<&str> = four_lines.lines().collect();
916     ///
917     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
918     /// ```
919     ///
920     /// Leaving off the trailing character:
921     ///
922     /// ```
923     /// let four_lines = "foo\nbar\n\nbaz\n";
924     /// let v: Vec<&str> = four_lines.lines().collect();
925     ///
926     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
927     /// ```
928     #[stable(feature = "rust1", since = "1.0.0")]
929     #[inline]
930     pub fn lines(&self) -> Lines {
931         core_str::StrExt::lines(self)
932     }
933
934     /// An iterator over the lines of a string, separated by either
935     /// `\n` or `\r\n`.
936     ///
937     /// As with `.lines()`, this does not include an empty trailing line.
938     ///
939     /// # Examples
940     ///
941     /// ```
942     /// let four_lines = "foo\r\nbar\n\r\nbaz";
943     /// let v: Vec<&str> = four_lines.lines_any().collect();
944     ///
945     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
946     /// ```
947     ///
948     /// Leaving off the trailing character:
949     ///
950     /// ```
951     /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
952     /// let v: Vec<&str> = four_lines.lines_any().collect();
953     ///
954     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
955     /// ```
956     #[stable(feature = "rust1", since = "1.0.0")]
957     #[inline]
958     pub fn lines_any(&self) -> LinesAny {
959         core_str::StrExt::lines_any(self)
960     }
961
962     /// Returns an iterator over the string in Unicode Normalization Form D
963     /// (canonical decomposition).
964     #[allow(deprecated)]
965     #[deprecated(reason = "use the crates.io `unicode-normalization` library instead",
966              since = "1.0.0")]
967     #[inline]
968     #[unstable(feature = "unicode",
969                reason = "this functionality may be replaced with a more generic \
970                          unicode crate on crates.io")]
971     pub fn nfd_chars(&self) -> Decompositions {
972         Decompositions {
973             iter: self[..].chars(),
974             buffer: Vec::new(),
975             sorted: false,
976             kind: Canonical
977         }
978     }
979
980     /// Returns an iterator over the string in Unicode Normalization Form KD
981     /// (compatibility decomposition).
982     #[allow(deprecated)]
983     #[deprecated(reason = "use the crates.io `unicode-normalization` library instead",
984              since = "1.0.0")]
985     #[inline]
986     #[unstable(feature = "unicode",
987                reason = "this functionality may be replaced with a more generic \
988                          unicode crate on crates.io")]
989     pub fn nfkd_chars(&self) -> Decompositions {
990         Decompositions {
991             iter: self[..].chars(),
992             buffer: Vec::new(),
993             sorted: false,
994             kind: Compatible
995         }
996     }
997
998     /// An Iterator over the string in Unicode Normalization Form C
999     /// (canonical decomposition followed by canonical composition).
1000     #[allow(deprecated)]
1001     #[deprecated(reason = "use the crates.io `unicode-normalization` library instead",
1002              since = "1.0.0")]
1003     #[inline]
1004     #[unstable(feature = "unicode",
1005                reason = "this functionality may be replaced with a more generic \
1006                          unicode crate on crates.io")]
1007     pub fn nfc_chars(&self) -> Recompositions {
1008         Recompositions {
1009             iter: self.nfd_chars(),
1010             state: Composing,
1011             buffer: VecDeque::new(),
1012             composee: None,
1013             last_ccc: None
1014         }
1015     }
1016
1017     /// An Iterator over the string in Unicode Normalization Form KC
1018     /// (compatibility decomposition followed by canonical composition).
1019     #[allow(deprecated)]
1020     #[deprecated(reason = "use the crates.io `unicode-normalization` library instead",
1021              since = "1.0.0")]
1022     #[inline]
1023     #[unstable(feature = "unicode",
1024                reason = "this functionality may be replaced with a more generic \
1025                          unicode crate on crates.io")]
1026     pub fn nfkc_chars(&self) -> Recompositions {
1027         Recompositions {
1028             iter: self.nfkd_chars(),
1029             state: Composing,
1030             buffer: VecDeque::new(),
1031             composee: None,
1032             last_ccc: None
1033         }
1034     }
1035
1036     /// Returns an iterator over the [grapheme clusters][graphemes] of `self`.
1037     ///
1038     /// [graphemes]: http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
1039     ///
1040     /// If `is_extended` is true, the iterator is over the
1041     /// *extended grapheme clusters*;
1042     /// otherwise, the iterator is over the *legacy grapheme clusters*.
1043     /// [UAX#29](http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)
1044     /// recommends extended grapheme cluster boundaries for general processing.
1045     ///
1046     /// # Examples
1047     ///
1048     /// ```
1049     /// #![feature(unicode, core)]
1050     ///
1051     /// let gr1 = "a\u{310}e\u{301}o\u{308}\u{332}".graphemes(true).collect::<Vec<&str>>();
1052     /// let b: &[_] = &["a\u{310}", "e\u{301}", "o\u{308}\u{332}"];
1053     ///
1054     /// assert_eq!(&gr1[..], b);
1055     ///
1056     /// let gr2 = "a\r\nb🇷🇺🇸🇹".graphemes(true).collect::<Vec<&str>>();
1057     /// let b: &[_] = &["a", "\r\n", "b", "🇷🇺🇸🇹"];
1058     ///
1059     /// assert_eq!(&gr2[..], b);
1060     /// ```
1061     #[deprecated(reason = "use the crates.io `unicode-segmentation` library instead",
1062              since = "1.0.0")]
1063     #[unstable(feature = "unicode",
1064                reason = "this functionality may only be provided by libunicode")]
1065     pub fn graphemes(&self, is_extended: bool) -> Graphemes {
1066         UnicodeStr::graphemes(self, is_extended)
1067     }
1068
1069     /// Returns an iterator over the grapheme clusters of `self` and their
1070     /// byte offsets. See
1071     /// `graphemes()` for more information.
1072     ///
1073     /// # Examples
1074     ///
1075     /// ```
1076     /// #![feature(unicode, core)]
1077     ///
1078     /// let gr_inds = "a̐éö̲\r\n".grapheme_indices(true).collect::<Vec<(usize, &str)>>();
1079     /// let b: &[_] = &[(0, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
1080     ///
1081     /// assert_eq!(&gr_inds[..], b);
1082     /// ```
1083     #[deprecated(reason = "use the crates.io `unicode-segmentation` library instead",
1084              since = "1.0.0")]
1085     #[unstable(feature = "unicode",
1086                reason = "this functionality may only be provided by libunicode")]
1087     pub fn grapheme_indices(&self, is_extended: bool) -> GraphemeIndices {
1088         UnicodeStr::grapheme_indices(self, is_extended)
1089     }
1090
1091     /// Returns an iterator of `u16` over the string encoded as UTF-16.
1092     #[unstable(feature = "str_utf16",
1093                reason = "this functionality may only be provided by libunicode")]
1094     pub fn utf16_units(&self) -> Utf16Units {
1095         Utf16Units { encoder: Utf16Encoder::new(self[..].chars()) }
1096     }
1097
1098     /// Returns `true` if `self` contains another `&str`.
1099     ///
1100     /// # Examples
1101     ///
1102     /// ```
1103     /// assert!("bananas".contains("nana"));
1104     ///
1105     /// assert!(!"bananas".contains("foobar"));
1106     /// ```
1107     #[stable(feature = "rust1", since = "1.0.0")]
1108     pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1109         core_str::StrExt::contains(self, pat)
1110     }
1111
1112     /// Returns `true` if the given `&str` is a prefix of the string.
1113     ///
1114     /// # Examples
1115     ///
1116     /// ```
1117     /// assert!("banana".starts_with("ba"));
1118     /// ```
1119     #[stable(feature = "rust1", since = "1.0.0")]
1120     pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1121         core_str::StrExt::starts_with(self, pat)
1122     }
1123
1124     /// Returns true if the given `&str` is a suffix of the string.
1125     ///
1126     /// # Examples
1127     ///
1128     /// ```rust
1129     /// assert!("banana".ends_with("nana"));
1130     /// ```
1131     #[stable(feature = "rust1", since = "1.0.0")]
1132     pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
1133         where P::Searcher: ReverseSearcher<'a>
1134     {
1135         core_str::StrExt::ends_with(self, pat)
1136     }
1137
1138     /// Returns the byte index of the first character of `self` that matches
1139     /// the pattern, if it
1140     /// exists.
1141     ///
1142     /// Returns `None` if it doesn't exist.
1143     ///
1144     /// The pattern can be a simple `&str`, `char`, or a closure that
1145     /// determines the
1146     /// split.
1147     ///
1148     /// # Examples
1149     ///
1150     /// Simple patterns:
1151     ///
1152     /// ```
1153     /// let s = "Löwe 老虎 Léopard";
1154     ///
1155     /// assert_eq!(s.find('L'), Some(0));
1156     /// assert_eq!(s.find('é'), Some(14));
1157     /// assert_eq!(s.find("Léopard"), Some(13));
1158     ///
1159     /// ```
1160     ///
1161     /// More complex patterns with closures:
1162     ///
1163     /// ```
1164     /// let s = "Löwe 老虎 Léopard";
1165     ///
1166     /// assert_eq!(s.find(char::is_whitespace), Some(5));
1167     /// assert_eq!(s.find(char::is_lowercase), Some(1));
1168     /// ```
1169     ///
1170     /// Not finding the pattern:
1171     ///
1172     /// ```
1173     /// let s = "Löwe 老虎 Léopard";
1174     /// let x: &[_] = &['1', '2'];
1175     ///
1176     /// assert_eq!(s.find(x), None);
1177     /// ```
1178     #[stable(feature = "rust1", since = "1.0.0")]
1179     pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1180         core_str::StrExt::find(self, pat)
1181     }
1182
1183     /// Returns the byte index of the last character of `self` that
1184     /// matches the pattern, if it
1185     /// exists.
1186     ///
1187     /// Returns `None` if it doesn't exist.
1188     ///
1189     /// The pattern can be a simple `&str`, `char`,
1190     /// or a closure that determines the split.
1191     ///
1192     /// # Examples
1193     ///
1194     /// Simple patterns:
1195     ///
1196     /// ```
1197     /// let s = "Löwe 老虎 Léopard";
1198     ///
1199     /// assert_eq!(s.rfind('L'), Some(13));
1200     /// assert_eq!(s.rfind('é'), Some(14));
1201     /// ```
1202     ///
1203     /// More complex patterns with closures:
1204     ///
1205     /// ```
1206     /// let s = "Löwe 老虎 Léopard";
1207     ///
1208     /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1209     /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1210     /// ```
1211     ///
1212     /// Not finding the pattern:
1213     ///
1214     /// ```
1215     /// let s = "Löwe 老虎 Léopard";
1216     /// let x: &[_] = &['1', '2'];
1217     ///
1218     /// assert_eq!(s.rfind(x), None);
1219     /// ```
1220     #[stable(feature = "rust1", since = "1.0.0")]
1221     pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1222         where P::Searcher: ReverseSearcher<'a>
1223     {
1224         core_str::StrExt::rfind(self, pat)
1225     }
1226
1227     /// An iterator over substrings of `self`, separated by characters
1228     /// matched by a pattern.
1229     ///
1230     /// The pattern can be a simple `&str`, `char`, or a closure that
1231     /// determines the split. Additional libraries might provide more complex
1232     /// patterns like regular expressions.
1233     ///
1234     /// # Iterator behavior
1235     ///
1236     /// The returned iterator will be double ended if the pattern allows a
1237     /// reverse search and forward/reverse search yields the same elements.
1238     /// This is true for, eg, `char` but not
1239     /// for `&str`.
1240     ///
1241     /// If the pattern allows a reverse search but its results might differ
1242     /// from a forward search, `rsplit()` can be used.
1243     ///
1244     /// # Examples
1245     ///
1246     /// Simple patterns:
1247     ///
1248     /// ```
1249     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1250     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1251     ///
1252     /// let v: Vec<&str> = "".split('X').collect();
1253     /// assert_eq!(v, [""]);
1254     ///
1255     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1256     /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1257     ///
1258     /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1259     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1260     ///
1261     /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1262     /// assert_eq!(v, ["abc", "def", "ghi"]);
1263     ///
1264     /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1265     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1266     /// ```
1267     ///
1268     /// A more complex pattern, using a closure:
1269     ///
1270     /// ```
1271     /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1272     /// assert_eq!(v, ["abc", "def", "ghi"]);
1273     /// ```
1274     ///
1275     /// If a string contains multiple contiguous separators, you will end up
1276     /// with empty strings in the output:
1277     ///
1278     /// ```
1279     /// let x = "||||a||b|c".to_string();
1280     /// let d: Vec<_> = x.split('|').collect();
1281     ///
1282     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1283     /// ```
1284     ///
1285     /// This can lead to possibly surprising behavior when whitespace is used
1286     /// as the separator. This code is correct:
1287     ///
1288     /// ```
1289     /// let x = "    a  b c".to_string();
1290     /// let d: Vec<_> = x.split(' ').collect();
1291     ///
1292     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1293     /// ```
1294     ///
1295     /// It does _not_ give you:
1296     ///
1297     /// ```rust,ignore
1298     /// assert_eq!(d, &["a", "b", "c"]);
1299     /// ```
1300     #[stable(feature = "rust1", since = "1.0.0")]
1301     pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1302         core_str::StrExt::split(self, pat)
1303     }
1304
1305     /// An iterator over substrings of `self`, separated by characters
1306     /// matched by a pattern and yielded in reverse order.
1307     ///
1308     /// The pattern can be a simple `&str`, `char`, or a closure that
1309     /// determines the split.
1310     /// Additional libraries might provide more complex patterns like
1311     /// regular expressions.
1312     ///
1313     /// # Iterator behavior
1314     ///
1315     /// The returned iterator requires that the pattern supports a
1316     /// reverse search,
1317     /// and it will be double ended if a forward/reverse search yields
1318     /// the same elements.
1319     ///
1320     /// For iterating from the front, `split()` can be used.
1321     ///
1322     /// # Examples
1323     ///
1324     /// Simple patterns:
1325     ///
1326     /// ```rust
1327     /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1328     /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1329     ///
1330     /// let v: Vec<&str> = "".rsplit('X').collect();
1331     /// assert_eq!(v, [""]);
1332     ///
1333     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1334     /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1335     ///
1336     /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1337     /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1338     /// ```
1339     ///
1340     /// A more complex pattern, using a closure:
1341     ///
1342     /// ```
1343     /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1344     /// assert_eq!(v, ["ghi", "def", "abc"]);
1345     /// ```
1346     #[stable(feature = "rust1", since = "1.0.0")]
1347     pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1348         where P::Searcher: ReverseSearcher<'a>
1349     {
1350         core_str::StrExt::rsplit(self, pat)
1351     }
1352
1353     /// An iterator over substrings of `self`, separated by characters
1354     /// matched by a pattern.
1355     ///
1356     /// The pattern can be a simple `&str`, `char`, or a closure that
1357     /// determines the split.
1358     /// Additional libraries might provide more complex patterns
1359     /// like regular expressions.
1360     ///
1361     /// Equivalent to `split`, except that the trailing substring
1362     /// is skipped if empty.
1363     ///
1364     /// This method can be used for string data that is _terminated_,
1365     /// rather than _separated_ by a pattern.
1366     ///
1367     /// # Iterator behavior
1368     ///
1369     /// The returned iterator will be double ended if the pattern allows a
1370     /// reverse search
1371     /// and forward/reverse search yields the same elements. This is true
1372     /// for, eg, `char` but not for `&str`.
1373     ///
1374     /// If the pattern allows a reverse search but its results might differ
1375     /// from a forward search, `rsplit_terminator()` can be used.
1376     ///
1377     /// # Examples
1378     ///
1379     /// ```
1380     /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1381     /// assert_eq!(v, ["A", "B"]);
1382     ///
1383     /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1384     /// assert_eq!(v, ["A", "", "B", ""]);
1385     /// ```
1386     #[stable(feature = "rust1", since = "1.0.0")]
1387     pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1388         core_str::StrExt::split_terminator(self, pat)
1389     }
1390
1391     /// An iterator over substrings of `self`, separated by characters
1392     /// matched by a pattern and yielded in reverse order.
1393     ///
1394     /// The pattern can be a simple `&str`, `char`, or a closure that
1395     /// determines the split.
1396     /// Additional libraries might provide more complex patterns like
1397     /// regular expressions.
1398     ///
1399     /// Equivalent to `split`, except that the trailing substring is
1400     /// skipped if empty.
1401     ///
1402     /// This method can be used for string data that is _terminated_,
1403     /// rather than _separated_ by a pattern.
1404     ///
1405     /// # Iterator behavior
1406     ///
1407     /// The returned iterator requires that the pattern supports a
1408     /// reverse search, and it will be double ended if a forward/reverse
1409     /// search yields the same elements.
1410     ///
1411     /// For iterating from the front, `split_terminator()` can be used.
1412     ///
1413     /// # Examples
1414     ///
1415     /// ```
1416     /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1417     /// assert_eq!(v, ["B", "A"]);
1418     ///
1419     /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1420     /// assert_eq!(v, ["", "B", "", "A"]);
1421     /// ```
1422     #[stable(feature = "rust1", since = "1.0.0")]
1423     pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1424         where P::Searcher: ReverseSearcher<'a>
1425     {
1426         core_str::StrExt::rsplit_terminator(self, pat)
1427     }
1428
1429     /// An iterator over substrings of `self`, separated by a pattern,
1430     /// restricted to returning
1431     /// at most `count` items.
1432     ///
1433     /// The last element returned, if any, will contain the remainder of the
1434     /// string.
1435     /// The pattern can be a simple `&str`, `char`, or a closure that
1436     /// determines the split.
1437     /// Additional libraries might provide more complex patterns like
1438     /// regular expressions.
1439     ///
1440     /// # Iterator behavior
1441     ///
1442     /// The returned iterator will not be double ended, because it is
1443     /// not efficient to support.
1444     ///
1445     /// If the pattern allows a reverse search, `rsplitn()` can be used.
1446     ///
1447     /// # Examples
1448     ///
1449     /// Simple patterns:
1450     ///
1451     /// ```
1452     /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1453     /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1454     ///
1455     /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1456     /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1457     ///
1458     /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1459     /// assert_eq!(v, ["abcXdef"]);
1460     ///
1461     /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1462     /// assert_eq!(v, [""]);
1463     /// ```
1464     ///
1465     /// A more complex pattern, using a closure:
1466     ///
1467     /// ```
1468     /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1469     /// assert_eq!(v, ["abc", "defXghi"]);
1470     /// ```
1471     #[stable(feature = "rust1", since = "1.0.0")]
1472     pub fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
1473         core_str::StrExt::splitn(self, count, pat)
1474     }
1475
1476     /// An iterator over substrings of `self`, separated by a pattern,
1477     /// starting from the end of the string, restricted to returning
1478     /// at most `count` items.
1479     ///
1480     /// The last element returned, if any, will contain the remainder of the
1481     /// string.
1482     ///
1483     /// The pattern can be a simple `&str`, `char`, or a closure that
1484     /// determines the split.
1485     /// Additional libraries might provide more complex patterns like
1486     /// regular expressions.
1487     ///
1488     /// # Iterator behavior
1489     ///
1490     /// The returned iterator will not be double ended, because it is not
1491     /// efficient to support.
1492     ///
1493     /// `splitn()` can be used for splitting from the front.
1494     ///
1495     /// # Examples
1496     ///
1497     /// Simple patterns:
1498     ///
1499     /// ```
1500     /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1501     /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1502     ///
1503     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1504     /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1505     ///
1506     /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1507     /// assert_eq!(v, ["leopard", "lion::tiger"]);
1508     /// ```
1509     ///
1510     /// A more complex pattern, using a closure:
1511     ///
1512     /// ```
1513     /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1514     /// assert_eq!(v, ["ghi", "abc1def"]);
1515     /// ```
1516     #[stable(feature = "rust1", since = "1.0.0")]
1517     pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
1518         where P::Searcher: ReverseSearcher<'a>
1519     {
1520         core_str::StrExt::rsplitn(self, count, pat)
1521     }
1522
1523     /// An iterator over the matches of a pattern within `self`.
1524     ///
1525     /// The pattern can be a simple `&str`, `char`, or a closure that
1526     /// determines the split.
1527     /// Additional libraries might provide more complex patterns like
1528     /// regular expressions.
1529     ///
1530     /// # Iterator behavior
1531     ///
1532     /// The returned iterator will be double ended if the pattern allows
1533     /// a reverse search
1534     /// and forward/reverse search yields the same elements. This is true
1535     /// for, eg, `char` but not
1536     /// for `&str`.
1537     ///
1538     /// If the pattern allows a reverse search but its results might differ
1539     /// from a forward search, `rmatches()` can be used.
1540     ///
1541     /// # Examples
1542     ///
1543     /// ```
1544     /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1545     /// assert_eq!(v, ["abc", "abc", "abc"]);
1546     ///
1547     /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1548     /// assert_eq!(v, ["1", "2", "3"]);
1549     /// ```
1550     #[stable(feature = "str_matches", since = "1.2.0")]
1551     pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1552         core_str::StrExt::matches(self, pat)
1553     }
1554
1555     /// An iterator over the matches of a pattern within `self`, yielded in
1556     /// reverse order.
1557     ///
1558     /// The pattern can be a simple `&str`, `char`, or a closure that
1559     /// determines the split.
1560     /// Additional libraries might provide more complex patterns like
1561     /// regular expressions.
1562     ///
1563     /// # Iterator behavior
1564     ///
1565     /// The returned iterator requires that the pattern supports a
1566     /// reverse search,
1567     /// and it will be double ended if a forward/reverse search yields
1568     /// the same elements.
1569     ///
1570     /// For iterating from the front, `matches()` can be used.
1571     ///
1572     /// # Examples
1573     ///
1574     /// ```
1575     /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1576     /// assert_eq!(v, ["abc", "abc", "abc"]);
1577     ///
1578     /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1579     /// assert_eq!(v, ["3", "2", "1"]);
1580     /// ```
1581     #[stable(feature = "str_matches", since = "1.2.0")]
1582     pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1583         where P::Searcher: ReverseSearcher<'a>
1584     {
1585         core_str::StrExt::rmatches(self, pat)
1586     }
1587
1588     /// An iterator over the start and end indices of the disjoint matches
1589     /// of a pattern within `self`.
1590     ///
1591     /// For matches of `pat` within `self` that overlap, only the indices
1592     /// corresponding to the first
1593     /// match are returned.
1594     ///
1595     /// The pattern can be a simple `&str`, `char`, or a closure that
1596     /// determines
1597     /// the split.
1598     /// Additional libraries might provide more complex patterns like
1599     /// regular expressions.
1600     ///
1601     /// # Iterator behavior
1602     ///
1603     /// The returned iterator will be double ended if the pattern allows a
1604     /// reverse search
1605     /// and forward/reverse search yields the same elements. This is true for,
1606     /// eg, `char` but not
1607     /// for `&str`.
1608     ///
1609     /// If the pattern allows a reverse search but its results might differ
1610     /// from a forward search, `rmatch_indices()` can be used.
1611     ///
1612     /// # Examples
1613     ///
1614     /// ```
1615     /// #![feature(str_match_indices)]
1616     ///
1617     /// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".match_indices("abc").collect();
1618     /// assert_eq!(v, [(0, 3), (6, 9), (12, 15)]);
1619     ///
1620     /// let v: Vec<(usize, usize)> = "1abcabc2".match_indices("abc").collect();
1621     /// assert_eq!(v, [(1, 4), (4, 7)]);
1622     ///
1623     /// let v: Vec<(usize, usize)> = "ababa".match_indices("aba").collect();
1624     /// assert_eq!(v, [(0, 3)]); // only the first `aba`
1625     /// ```
1626     #[unstable(feature = "str_match_indices",
1627                reason = "might have its iterator type changed")]
1628     // NB: Right now MatchIndices yields `(usize, usize)`, but it would
1629     // be more consistent with `matches` and `char_indices` to return `(usize, &str)`
1630     pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1631         core_str::StrExt::match_indices(self, pat)
1632     }
1633
1634     /// An iterator over the start and end indices of the disjoint matches of
1635     /// a pattern within
1636     /// `self`, yielded in reverse order.
1637     ///
1638     /// For matches of `pat` within `self` that overlap, only the indices
1639     /// corresponding to the last
1640     /// match are returned.
1641     ///
1642     /// The pattern can be a simple `&str`, `char`, or a closure that
1643     /// determines
1644     /// the split.
1645     /// Additional libraries might provide more complex patterns like
1646     /// regular expressions.
1647     ///
1648     /// # Iterator behavior
1649     ///
1650     /// The returned iterator requires that the pattern supports a
1651     /// reverse search,
1652     /// and it will be double ended if a forward/reverse search yields
1653     /// the same elements.
1654     ///
1655     /// For iterating from the front, `match_indices()` can be used.
1656     ///
1657     /// # Examples
1658     ///
1659     /// ```
1660     /// #![feature(str_match_indices)]
1661     ///
1662     /// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1663     /// assert_eq!(v, [(12, 15), (6, 9), (0, 3)]);
1664     ///
1665     /// let v: Vec<(usize, usize)> = "1abcabc2".rmatch_indices("abc").collect();
1666     /// assert_eq!(v, [(4, 7), (1, 4)]);
1667     ///
1668     /// let v: Vec<(usize, usize)> = "ababa".rmatch_indices("aba").collect();
1669     /// assert_eq!(v, [(2, 5)]); // only the last `aba`
1670     /// ```
1671     #[unstable(feature = "str_match_indices",
1672                reason = "might have its iterator type changed")]
1673     // NB: Right now RMatchIndices yields `(usize, usize)`, but it would
1674     // be more consistent with `rmatches` and `char_indices` to return `(usize, &str)`
1675     pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1676         where P::Searcher: ReverseSearcher<'a>
1677     {
1678         core_str::StrExt::rmatch_indices(self, pat)
1679     }
1680
1681     /// Returns the byte offset of an inner slice relative to an enclosing
1682     /// outer slice.
1683     ///
1684     /// # Panics
1685     ///
1686     /// Panics if `inner` is not a direct slice contained within self.
1687     ///
1688     /// # Examples
1689     ///
1690     /// ```
1691     /// #![feature(subslice_offset)]
1692     ///
1693     /// let string = "a\nb\nc";
1694     /// let lines: Vec<&str> = string.lines().collect();
1695     ///
1696     /// assert!(string.subslice_offset(lines[0]) == 0); // &"a"
1697     /// assert!(string.subslice_offset(lines[1]) == 2); // &"b"
1698     /// assert!(string.subslice_offset(lines[2]) == 4); // &"c"
1699     /// ```
1700     #[unstable(feature = "subslice_offset",
1701                reason = "awaiting convention about comparability of arbitrary slices")]
1702     #[deprecated(since = "1.3.0",
1703                  reason = "replaced with other pattern-related methods")]
1704     pub fn subslice_offset(&self, inner: &str) -> usize {
1705         core_str::StrExt::subslice_offset(self, inner)
1706     }
1707
1708     /// Returns a `&str` with leading and trailing whitespace removed.
1709     ///
1710     /// # Examples
1711     ///
1712     /// ```
1713     /// let s = " Hello\tworld\t";
1714     /// assert_eq!(s.trim(), "Hello\tworld");
1715     /// ```
1716     #[stable(feature = "rust1", since = "1.0.0")]
1717     pub fn trim(&self) -> &str {
1718         UnicodeStr::trim(self)
1719     }
1720
1721     /// Returns a `&str` with leading whitespace removed.
1722     ///
1723     /// # Examples
1724     ///
1725     /// ```
1726     /// let s = " Hello\tworld\t";
1727     /// assert_eq!(s.trim_left(), "Hello\tworld\t");
1728     /// ```
1729     #[stable(feature = "rust1", since = "1.0.0")]
1730     pub fn trim_left(&self) -> &str {
1731         UnicodeStr::trim_left(self)
1732     }
1733
1734     /// Returns a `&str` with trailing whitespace removed.
1735     ///
1736     /// # Examples
1737     ///
1738     /// ```
1739     /// let s = " Hello\tworld\t";
1740     /// assert_eq!(s.trim_right(), " Hello\tworld");
1741     /// ```
1742     #[stable(feature = "rust1", since = "1.0.0")]
1743     pub fn trim_right(&self) -> &str {
1744         UnicodeStr::trim_right(self)
1745     }
1746
1747     /// Returns a string with all pre- and suffixes that match a pattern
1748     /// repeatedly removed.
1749     ///
1750     /// The pattern can be a simple `char`, or a closure that determines
1751     /// the split.
1752     ///
1753     /// # Examples
1754     ///
1755     /// Simple patterns:
1756     ///
1757     /// ```
1758     /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1759     /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1760     ///
1761     /// let x: &[_] = &['1', '2'];
1762     /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1763     /// ```
1764     ///
1765     /// A more complex pattern, using a closure:
1766     ///
1767     /// ```
1768     /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1769     /// ```
1770     #[stable(feature = "rust1", since = "1.0.0")]
1771     pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1772         where P::Searcher: DoubleEndedSearcher<'a>
1773     {
1774         core_str::StrExt::trim_matches(self, pat)
1775     }
1776
1777     /// Returns a string with all prefixes that match a pattern
1778     /// repeatedly removed.
1779     ///
1780     /// The pattern can be a simple `&str`, `char`, or a closure that
1781     /// determines the split.
1782     ///
1783     /// # Examples
1784     ///
1785     /// ```
1786     /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1787     /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1788     ///
1789     /// let x: &[_] = &['1', '2'];
1790     /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1791     /// ```
1792     #[stable(feature = "rust1", since = "1.0.0")]
1793     pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1794         core_str::StrExt::trim_left_matches(self, pat)
1795     }
1796
1797     /// Returns a string with all suffixes that match a pattern
1798     /// repeatedly removed.
1799     ///
1800     /// The pattern can be a simple `&str`, `char`, or a closure that
1801     /// determines the split.
1802     ///
1803     /// # Examples
1804     ///
1805     /// Simple patterns:
1806     ///
1807     /// ```
1808     /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1809     /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1810     ///
1811     /// let x: &[_] = &['1', '2'];
1812     /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1813     /// ```
1814     ///
1815     /// A more complex pattern, using a closure:
1816     ///
1817     /// ```
1818     /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1819     /// ```
1820     #[stable(feature = "rust1", since = "1.0.0")]
1821     pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1822         where P::Searcher: ReverseSearcher<'a>
1823     {
1824         core_str::StrExt::trim_right_matches(self, pat)
1825     }
1826
1827     /// Parses `self` into the specified type.
1828     ///
1829     /// # Failure
1830     ///
1831     /// Will return `Err` if it's not possible to parse `self` into the type.
1832     ///
1833     /// # Example
1834     ///
1835     /// ```
1836     /// assert_eq!("4".parse::<u32>(), Ok(4));
1837     /// ```
1838     ///
1839     /// Failing:
1840     ///
1841     /// ```
1842     /// assert!("j".parse::<u32>().is_err());
1843     /// ```
1844     #[inline]
1845     #[stable(feature = "rust1", since = "1.0.0")]
1846     pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1847         core_str::StrExt::parse(self)
1848     }
1849
1850     /// Replaces all occurrences of one string with another.
1851     ///
1852     /// `replace` takes two arguments, a sub-`&str` to find in `self`, and a
1853     /// second `&str` to
1854     /// replace it with. If the original `&str` isn't found, no change occurs.
1855     ///
1856     /// # Examples
1857     ///
1858     /// ```
1859     /// let s = "this is old";
1860     ///
1861     /// assert_eq!(s.replace("old", "new"), "this is new");
1862     /// ```
1863     ///
1864     /// When a `&str` isn't found:
1865     ///
1866     /// ```
1867     /// let s = "this is old";
1868     /// assert_eq!(s.replace("cookie monster", "little lamb"), s);
1869     /// ```
1870     #[stable(feature = "rust1", since = "1.0.0")]
1871     pub fn replace(&self, from: &str, to: &str) -> String {
1872         let mut result = String::new();
1873         let mut last_end = 0;
1874         for (start, end) in self.match_indices(from) {
1875             result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1876             result.push_str(to);
1877             last_end = end;
1878         }
1879         result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1880         result
1881     }
1882
1883     /// Returns the lowercase equivalent of this string.
1884     ///
1885     /// # Examples
1886     ///
1887     /// ```
1888     /// let s = "HELLO";
1889     /// assert_eq!(s.to_lowercase(), "hello");
1890     /// ```
1891     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1892     pub fn to_lowercase(&self) -> String {
1893         let mut s = String::with_capacity(self.len());
1894         for (i, c) in self[..].char_indices() {
1895             if c == 'Σ' {
1896                 // Σ maps to σ, except at the end of a word where it maps to ς.
1897                 // This is the only conditional (contextual) but language-independent mapping
1898                 // in `SpecialCasing.txt`,
1899                 // so hard-code it rather than have a generic "condition" mechanim.
1900                 // See https://github.com/rust-lang/rust/issues/26035
1901                 map_uppercase_sigma(self, i, &mut s)
1902             } else {
1903                 s.extend(c.to_lowercase());
1904             }
1905         }
1906         return s;
1907
1908         fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1909             // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1910             // for the definition of `Final_Sigma`.
1911             debug_assert!('Σ'.len_utf8() == 2);
1912             let is_word_final =
1913                 case_ignoreable_then_cased(from[..i].chars().rev()) &&
1914                 !case_ignoreable_then_cased(from[i + 2..].chars());
1915             to.push_str(if is_word_final { "ς" } else { "σ" });
1916         }
1917
1918         fn case_ignoreable_then_cased<I: Iterator<Item=char>>(iter: I) -> bool {
1919             use rustc_unicode::derived_property::{Cased, Case_Ignorable};
1920             match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1921                 Some(c) => Cased(c),
1922                 None => false,
1923             }
1924         }
1925     }
1926
1927     /// Returns the uppercase equivalent of this string.
1928     ///
1929     /// # Examples
1930     ///
1931     /// ```
1932     /// let s = "hello";
1933     /// assert_eq!(s.to_uppercase(), "HELLO");
1934     /// ```
1935     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1936     pub fn to_uppercase(&self) -> String {
1937         let mut s = String::with_capacity(self.len());
1938         s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1939         return s;
1940     }
1941
1942     /// Escapes each char in `s` with `char::escape_default`.
1943     #[unstable(feature = "str_escape",
1944                reason = "return type may change to be an iterator")]
1945     pub fn escape_default(&self) -> String {
1946         self.chars().flat_map(|c| c.escape_default()).collect()
1947     }
1948
1949     /// Escapes each char in `s` with `char::escape_unicode`.
1950     #[unstable(feature = "str_escape",
1951                reason = "return type may change to be an iterator")]
1952     pub fn escape_unicode(&self) -> String {
1953         self.chars().flat_map(|c| c.escape_unicode()).collect()
1954     }
1955
1956     /// Converts the `Box<str>` into a `String` without copying or allocating.
1957     #[unstable(feature = "box_str",
1958                reason = "recently added, matches RFC")]
1959     pub fn into_string(self: Box<str>) -> String {
1960         unsafe {
1961             let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1962             String::from_utf8_unchecked(slice.into_vec())
1963         }
1964     }
1965 }