]> git.lizzy.rs Git - rust.git/blob - src/libcollections/str.rs
rollup merge of #23901: steveklabnik/fix_links_str
[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 // ignore-lexer-test FIXME #15679
12
13 //! Unicode string manipulation (the `str` type).
14 //!
15 //! Rust's `str` type is one of the core primitive types of the language. `&str` is the borrowed
16 //! string type. This type of string can only be created from other strings, unless it is a
17 //! `&'static str` (see below). It is not possible to move out of borrowed strings because they are
18 //! owned elsewhere.
19 //!
20 //! # Examples
21 //!
22 //! Here's some code that uses a `&str`:
23 //!
24 //! ```
25 //! let s = "Hello, world.";
26 //! ```
27 //!
28 //! This `&str` is a `&'static str`, which is the type of string literals. They're `'static`
29 //! because literals are available for the entire lifetime of the program.
30 //!
31 //! You can get a non-`'static` `&str` by taking a slice of a `String`:
32 //!
33 //! ```
34 //! # let some_string = "Hello, world.".to_string();
35 //! let s = &some_string;
36 //! ```
37 //!
38 //! # Representation
39 //!
40 //! Rust's string type, `str`, is a sequence of Unicode scalar values encoded as a stream of UTF-8
41 //! bytes. All [strings](../../reference.html#literals) are guaranteed to be validly encoded UTF-8
42 //! sequences. Additionally, strings are not null-terminated and can thus contain null bytes.
43 //!
44 //! The actual representation of `str`s have direct mappings to slices: `&str` is the same as
45 //! `&[u8]`.
46
47 #![doc(primitive = "str")]
48 #![stable(feature = "rust1", since = "1.0.0")]
49
50 use self::RecompositionState::*;
51 use self::DecompositionType::*;
52
53 use core::clone::Clone;
54 use core::iter::AdditiveIterator;
55 use core::iter::{Iterator, Extend};
56 use core::option::Option::{self, Some, None};
57 use core::result::Result;
58 use core::str as core_str;
59 use unicode::str::{UnicodeStr, Utf16Encoder};
60
61 use core::convert::AsRef;
62 use vec_deque::VecDeque;
63 use borrow::{Borrow, ToOwned};
64 use string::String;
65 use unicode;
66 use vec::Vec;
67 use slice::SliceConcatExt;
68
69 pub use core::str::{FromStr, Utf8Error, Str};
70 pub use core::str::{Lines, LinesAny, MatchIndices, CharRange};
71 pub use core::str::{Split, SplitTerminator, SplitN};
72 pub use core::str::{RSplit, RSplitN};
73 pub use core::str::{from_utf8, Chars, CharIndices, Bytes};
74 pub use core::str::{from_utf8_unchecked, ParseBoolError};
75 pub use unicode::str::{Words, Graphemes, GraphemeIndices};
76 pub use core::str::Pattern;
77 pub use core::str::{Searcher, ReverseSearcher, DoubleEndedSearcher, SearchStep};
78
79 /*
80 Section: Creating a string
81 */
82
83 impl<S: AsRef<str>> SliceConcatExt<str, String> for [S] {
84     fn concat(&self) -> String {
85         if self.is_empty() {
86             return String::new();
87         }
88
89         // `len` calculation may overflow but push_str will check boundaries
90         let len = self.iter().map(|s| s.as_ref().len()).sum();
91         let mut result = String::with_capacity(len);
92
93         for s in self {
94             result.push_str(s.as_ref())
95         }
96
97         result
98     }
99
100     fn connect(&self, sep: &str) -> String {
101         if self.is_empty() {
102             return String::new();
103         }
104
105         // concat is faster
106         if sep.is_empty() {
107             return self.concat();
108         }
109
110         // this is wrong without the guarantee that `self` is non-empty
111         // `len` calculation may overflow but push_str but will check boundaries
112         let len = sep.len() * (self.len() - 1)
113             + self.iter().map(|s| s.as_ref().len()).sum();
114         let mut result = String::with_capacity(len);
115         let mut first = true;
116
117         for s in self {
118             if first {
119                 first = false;
120             } else {
121                 result.push_str(sep);
122             }
123             result.push_str(s.as_ref());
124         }
125         result
126     }
127 }
128
129 /*
130 Section: Iterators
131 */
132
133 // Helper functions used for Unicode normalization
134 fn canonical_sort(comb: &mut [(char, u8)]) {
135     let len = comb.len();
136     for i in 0..len {
137         let mut swapped = false;
138         for j in 1..len-i {
139             let class_a = comb[j-1].1;
140             let class_b = comb[j].1;
141             if class_a != 0 && class_b != 0 && class_a > class_b {
142                 comb.swap(j-1, j);
143                 swapped = true;
144             }
145         }
146         if !swapped { break; }
147     }
148 }
149
150 #[derive(Clone)]
151 enum DecompositionType {
152     Canonical,
153     Compatible
154 }
155
156 /// External iterator for a string decomposition's characters.
157 ///
158 /// For use with the `std::iter` module.
159 #[derive(Clone)]
160 #[unstable(feature = "unicode",
161            reason = "this functionality may be replaced with a more generic \
162                      unicode crate on crates.io")]
163 pub struct Decompositions<'a> {
164     kind: DecompositionType,
165     iter: Chars<'a>,
166     buffer: Vec<(char, u8)>,
167     sorted: bool
168 }
169
170 #[stable(feature = "rust1", since = "1.0.0")]
171 impl<'a> Iterator for Decompositions<'a> {
172     type Item = char;
173
174     #[inline]
175     fn next(&mut self) -> Option<char> {
176         match self.buffer.first() {
177             Some(&(c, 0)) => {
178                 self.sorted = false;
179                 self.buffer.remove(0);
180                 return Some(c);
181             }
182             Some(&(c, _)) if self.sorted => {
183                 self.buffer.remove(0);
184                 return Some(c);
185             }
186             _ => self.sorted = false
187         }
188
189         if !self.sorted {
190             for ch in self.iter.by_ref() {
191                 let buffer = &mut self.buffer;
192                 let sorted = &mut self.sorted;
193                 {
194                     let callback = |d| {
195                         let class =
196                             unicode::char::canonical_combining_class(d);
197                         if class == 0 && !*sorted {
198                             canonical_sort(buffer);
199                             *sorted = true;
200                         }
201                         buffer.push((d, class));
202                     };
203                     match self.kind {
204                         Canonical => {
205                             unicode::char::decompose_canonical(ch, callback)
206                         }
207                         Compatible => {
208                             unicode::char::decompose_compatible(ch, callback)
209                         }
210                     }
211                 }
212                 if *sorted {
213                     break
214                 }
215             }
216         }
217
218         if !self.sorted {
219             canonical_sort(&mut self.buffer);
220             self.sorted = true;
221         }
222
223         if self.buffer.is_empty() {
224             None
225         } else {
226             match self.buffer.remove(0) {
227                 (c, 0) => {
228                     self.sorted = false;
229                     Some(c)
230                 }
231                 (c, _) => Some(c),
232             }
233         }
234     }
235
236     fn size_hint(&self) -> (usize, Option<usize>) {
237         let (lower, _) = self.iter.size_hint();
238         (lower, None)
239     }
240 }
241
242 #[derive(Clone)]
243 enum RecompositionState {
244     Composing,
245     Purging,
246     Finished
247 }
248
249 /// External iterator for a string recomposition's characters.
250 ///
251 /// For use with the `std::iter` module.
252 #[derive(Clone)]
253 #[unstable(feature = "unicode",
254            reason = "this functionality may be replaced with a more generic \
255                      unicode crate on crates.io")]
256 pub struct Recompositions<'a> {
257     iter: Decompositions<'a>,
258     state: RecompositionState,
259     buffer: VecDeque<char>,
260     composee: Option<char>,
261     last_ccc: Option<u8>
262 }
263
264 #[stable(feature = "rust1", since = "1.0.0")]
265 impl<'a> Iterator for Recompositions<'a> {
266     type Item = char;
267
268     #[inline]
269     fn next(&mut self) -> Option<char> {
270         loop {
271             match self.state {
272                 Composing => {
273                     for ch in self.iter.by_ref() {
274                         let ch_class = unicode::char::canonical_combining_class(ch);
275                         if self.composee.is_none() {
276                             if ch_class != 0 {
277                                 return Some(ch);
278                             }
279                             self.composee = Some(ch);
280                             continue;
281                         }
282                         let k = self.composee.clone().unwrap();
283
284                         match self.last_ccc {
285                             None => {
286                                 match unicode::char::compose(k, ch) {
287                                     Some(r) => {
288                                         self.composee = Some(r);
289                                         continue;
290                                     }
291                                     None => {
292                                         if ch_class == 0 {
293                                             self.composee = Some(ch);
294                                             return Some(k);
295                                         }
296                                         self.buffer.push_back(ch);
297                                         self.last_ccc = Some(ch_class);
298                                     }
299                                 }
300                             }
301                             Some(l_class) => {
302                                 if l_class >= ch_class {
303                                     // `ch` is blocked from `composee`
304                                     if ch_class == 0 {
305                                         self.composee = Some(ch);
306                                         self.last_ccc = None;
307                                         self.state = Purging;
308                                         return Some(k);
309                                     }
310                                     self.buffer.push_back(ch);
311                                     self.last_ccc = Some(ch_class);
312                                     continue;
313                                 }
314                                 match unicode::char::compose(k, ch) {
315                                     Some(r) => {
316                                         self.composee = Some(r);
317                                         continue;
318                                     }
319                                     None => {
320                                         self.buffer.push_back(ch);
321                                         self.last_ccc = Some(ch_class);
322                                     }
323                                 }
324                             }
325                         }
326                     }
327                     self.state = Finished;
328                     if self.composee.is_some() {
329                         return self.composee.take();
330                     }
331                 }
332                 Purging => {
333                     match self.buffer.pop_front() {
334                         None => self.state = Composing,
335                         s => return s
336                     }
337                 }
338                 Finished => {
339                     match self.buffer.pop_front() {
340                         None => return self.composee.take(),
341                         s => return s
342                     }
343                 }
344             }
345         }
346     }
347 }
348
349 /// External iterator for a string's UTF16 codeunits.
350 ///
351 /// For use with the `std::iter` module.
352 #[derive(Clone)]
353 #[unstable(feature = "collections")]
354 pub struct Utf16Units<'a> {
355     encoder: Utf16Encoder<Chars<'a>>
356 }
357
358 #[stable(feature = "rust1", since = "1.0.0")]
359 impl<'a> Iterator for Utf16Units<'a> {
360     type Item = u16;
361
362     #[inline]
363     fn next(&mut self) -> Option<u16> { self.encoder.next() }
364
365     #[inline]
366     fn size_hint(&self) -> (usize, Option<usize>) { self.encoder.size_hint() }
367 }
368
369 /*
370 Section: Misc
371 */
372
373 // Return the initial codepoint accumulator for the first byte.
374 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
375 // for width 3, and 3 bits for width 4
376 macro_rules! utf8_first_byte {
377     ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
378 }
379
380 // return the value of $ch updated with continuation byte $byte
381 macro_rules! utf8_acc_cont_byte {
382     ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63) as u32)
383 }
384
385 #[stable(feature = "rust1", since = "1.0.0")]
386 impl Borrow<str> for String {
387     fn borrow(&self) -> &str { &self[..] }
388 }
389
390 #[stable(feature = "rust1", since = "1.0.0")]
391 impl ToOwned for str {
392     type Owned = String;
393     fn to_owned(&self) -> String {
394         unsafe {
395             String::from_utf8_unchecked(self.as_bytes().to_owned())
396         }
397     }
398 }
399
400 /*
401 Section: CowString
402 */
403
404 /*
405 Section: Trait implementations
406 */
407
408
409 /// Any string that can be represented as a slice.
410 #[lang = "str"]
411 #[cfg(not(test))]
412 #[stable(feature = "rust1", since = "1.0.0")]
413 impl str {
414     /// Escapes each char in `s` with `char::escape_default`.
415     #[unstable(feature = "collections",
416                reason = "return type may change to be an iterator")]
417     pub fn escape_default(&self) -> String {
418         self.chars().flat_map(|c| c.escape_default()).collect()
419     }
420
421     /// Escapes each char in `s` with `char::escape_unicode`.
422     #[unstable(feature = "collections",
423                reason = "return type may change to be an iterator")]
424     pub fn escape_unicode(&self) -> String {
425         self.chars().flat_map(|c| c.escape_unicode()).collect()
426     }
427
428     /// Replaces all occurrences of one string with another.
429     ///
430     /// `replace` takes two arguments, a sub-`&str` to find in `self`, and a second `&str` to
431     /// replace it with. If the original `&str` isn't found, no change occurs.
432     ///
433     /// # Examples
434     ///
435     /// ```
436     /// let s = "this is old";
437     ///
438     /// assert_eq!(s.replace("old", "new"), "this is new");
439     /// ```
440     ///
441     /// When a `&str` isn't found:
442     ///
443     /// ```
444     /// let s = "this is old";
445     /// assert_eq!(s.replace("cookie monster", "little lamb"), s);
446     /// ```
447     #[stable(feature = "rust1", since = "1.0.0")]
448     pub fn replace(&self, from: &str, to: &str) -> String {
449         let mut result = String::new();
450         let mut last_end = 0;
451         for (start, end) in self.match_indices(from) {
452             result.push_str(unsafe { self.slice_unchecked(last_end, start) });
453             result.push_str(to);
454             last_end = end;
455         }
456         result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
457         result
458     }
459
460     /// Returns an iterator over the string in Unicode Normalization Form D
461     /// (canonical decomposition).
462     #[inline]
463     #[unstable(feature = "unicode",
464                reason = "this functionality may be replaced with a more generic \
465                          unicode crate on crates.io")]
466     pub fn nfd_chars(&self) -> Decompositions {
467         Decompositions {
468             iter: self[..].chars(),
469             buffer: Vec::new(),
470             sorted: false,
471             kind: Canonical
472         }
473     }
474
475     /// Returns an iterator over the string in Unicode Normalization Form KD
476     /// (compatibility decomposition).
477     #[inline]
478     #[unstable(feature = "unicode",
479                reason = "this functionality may be replaced with a more generic \
480                          unicode crate on crates.io")]
481     pub fn nfkd_chars(&self) -> Decompositions {
482         Decompositions {
483             iter: self[..].chars(),
484             buffer: Vec::new(),
485             sorted: false,
486             kind: Compatible
487         }
488     }
489
490     /// An Iterator over the string in Unicode Normalization Form C
491     /// (canonical decomposition followed by canonical composition).
492     #[inline]
493     #[unstable(feature = "unicode",
494                reason = "this functionality may be replaced with a more generic \
495                          unicode crate on crates.io")]
496     pub fn nfc_chars(&self) -> Recompositions {
497         Recompositions {
498             iter: self.nfd_chars(),
499             state: Composing,
500             buffer: VecDeque::new(),
501             composee: None,
502             last_ccc: None
503         }
504     }
505
506     /// An Iterator over the string in Unicode Normalization Form KC
507     /// (compatibility decomposition followed by canonical composition).
508     #[inline]
509     #[unstable(feature = "unicode",
510                reason = "this functionality may be replaced with a more generic \
511                          unicode crate on crates.io")]
512     pub fn nfkc_chars(&self) -> Recompositions {
513         Recompositions {
514             iter: self.nfkd_chars(),
515             state: Composing,
516             buffer: VecDeque::new(),
517             composee: None,
518             last_ccc: None
519         }
520     }
521
522     /// Returns `true` if `self` contains another `&str`.
523     ///
524     /// # Examples
525     ///
526     /// ```
527     /// assert!("bananas".contains("nana"));
528     ///
529     /// assert!(!"bananas".contains("foobar"));
530     /// ```
531     #[stable(feature = "rust1", since = "1.0.0")]
532     pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
533         core_str::StrExt::contains(&self[..], pat)
534     }
535
536     /// An iterator over the codepoints of `self`.
537     ///
538     /// # Examples
539     ///
540     /// ```
541     /// let v: Vec<char> = "abc åäö".chars().collect();
542     ///
543     /// assert_eq!(v, ['a', 'b', 'c', ' ', 'å', 'ä', 'ö']);
544     /// ```
545     #[stable(feature = "rust1", since = "1.0.0")]
546     pub fn chars(&self) -> Chars {
547         core_str::StrExt::chars(&self[..])
548     }
549
550     /// An iterator over the bytes of `self`.
551     ///
552     /// # Examples
553     ///
554     /// ```
555     /// let v: Vec<u8> = "bors".bytes().collect();
556     ///
557     /// assert_eq!(v, b"bors".to_vec());
558     /// ```
559     #[stable(feature = "rust1", since = "1.0.0")]
560     pub fn bytes(&self) -> Bytes {
561         core_str::StrExt::bytes(&self[..])
562     }
563
564     /// An iterator over the characters of `self` and their byte offsets.
565     ///
566     /// # Examples
567     ///
568     /// ```
569     /// let v: Vec<(usize, char)> = "abc".char_indices().collect();
570     /// let b = vec![(0, 'a'), (1, 'b'), (2, 'c')];
571     ///
572     /// assert_eq!(v, b);
573     /// ```
574     #[stable(feature = "rust1", since = "1.0.0")]
575     pub fn char_indices(&self) -> CharIndices {
576         core_str::StrExt::char_indices(&self[..])
577     }
578
579     /// An iterator over substrings of `self`, separated by characters
580     /// matched by a pattern.
581     ///
582     /// The pattern can be a simple `&str`, or a closure that determines
583     /// the split.
584     ///
585     /// # Examples
586     ///
587     /// Simple `&str` patterns:
588     ///
589     /// ```
590     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
591     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
592     ///
593     /// let v: Vec<&str> = "".split('X').collect();
594     /// assert_eq!(v, [""]);
595     /// ```
596     ///
597     /// More complex patterns with a lambda:
598     ///
599     /// ```
600     /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
601     /// assert_eq!(v, ["abc", "def", "ghi"]);
602     ///
603     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
604     /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
605     /// ```
606     #[stable(feature = "rust1", since = "1.0.0")]
607     pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
608         core_str::StrExt::split(&self[..], pat)
609     }
610
611     /// An iterator over substrings of `self`, separated by characters matched by a pattern,
612     /// restricted to splitting at most `count` times.
613     ///
614     /// The pattern can be a simple `&str`, or a closure that determines
615     /// the split.
616     ///
617     /// # Examples
618     ///
619     /// Simple `&str` patterns:
620     ///
621     /// ```
622     /// let v: Vec<&str> = "Mary had a little lambda".splitn(2, ' ').collect();
623     /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
624     ///
625     /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(2, 'X').collect();
626     /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
627     ///
628     /// let v: Vec<&str> = "abcXdef".splitn(0, 'X').collect();
629     /// assert_eq!(v, ["abcXdef"]);
630     ///
631     /// let v: Vec<&str> = "".splitn(1, 'X').collect();
632     /// assert_eq!(v, [""]);
633     /// ```
634     ///
635     /// More complex patterns with a lambda:
636     ///
637     /// ```
638     /// let v: Vec<&str> = "abc1def2ghi".splitn(1, |c: char| c.is_numeric()).collect();
639     /// assert_eq!(v, ["abc", "def2ghi"]);
640     /// ```
641     #[stable(feature = "rust1", since = "1.0.0")]
642     pub fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
643         core_str::StrExt::splitn(&self[..], count, pat)
644     }
645
646     /// An iterator over substrings of `self`, separated by characters
647     /// matched by a pattern.
648     ///
649     /// Equivalent to `split`, except that the trailing substring is skipped if empty.
650     ///
651     /// The pattern can be a simple `&str`, or a closure that determines
652     /// the split.
653     ///
654     /// # Examples
655     ///
656     /// Simple `&str` patterns:
657     ///
658     /// ```
659     /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
660     /// assert_eq!(v, ["A", "B"]);
661     ///
662     /// let v: Vec<&str> = "A..B..".split_terminator('.').collect();
663     /// assert_eq!(v, ["A", "", "B", ""]);
664     /// ```
665     ///
666     /// More complex patterns with a lambda:
667     ///
668     /// ```
669     /// let v: Vec<&str> = "abc1def2ghi3".split_terminator(|c: char| c.is_numeric()).collect();
670     /// assert_eq!(v, ["abc", "def", "ghi"]);
671     /// ```
672     #[stable(feature = "rust1", since = "1.0.0")]
673     pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
674         core_str::StrExt::split_terminator(&self[..], pat)
675     }
676
677     /// An iterator over substrings of `self`, separated by a pattern,
678     /// starting from the end of the string.
679     ///
680     /// # Examples
681     ///
682     /// Simple patterns:
683     ///
684     /// ```
685     /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
686     /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
687     ///
688     /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
689     /// assert_eq!(v, ["leopard", "tiger", "lion"]);
690     /// ```
691     ///
692     /// More complex patterns with a lambda:
693     ///
694     /// ```
695     /// let v: Vec<&str> = "abc1def2ghi".rsplit(|c: char| c.is_numeric()).collect();
696     /// assert_eq!(v, ["ghi", "def", "abc"]);
697     /// ```
698     #[stable(feature = "rust1", since = "1.0.0")]
699     pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
700         where P::Searcher: ReverseSearcher<'a>
701     {
702         core_str::StrExt::rsplit(&self[..], pat)
703     }
704
705     /// An iterator over substrings of `self`, separated by a pattern,
706     /// starting from the end of the string, restricted to splitting
707     /// at most `count` times.
708     ///
709     /// # Examples
710     ///
711     /// Simple patterns:
712     ///
713     /// ```
714     /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(2, ' ').collect();
715     /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
716     ///
717     /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(1, "::").collect();
718     /// assert_eq!(v, ["leopard", "lion::tiger"]);
719     /// ```
720     ///
721     /// More complex patterns with a lambda:
722     ///
723     /// ```
724     /// let v: Vec<&str> = "abc1def2ghi".rsplitn(1, |c: char| c.is_numeric()).collect();
725     /// assert_eq!(v, ["ghi", "abc1def"]);
726     /// ```
727     #[stable(feature = "rust1", since = "1.0.0")]
728     pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
729         where P::Searcher: ReverseSearcher<'a>
730     {
731         core_str::StrExt::rsplitn(&self[..], count, pat)
732     }
733
734     /// An iterator over the start and end indices of the disjoint matches of a `&str` within
735     /// `self`.
736     ///
737     /// That is, each returned value `(start, end)` satisfies `self.slice(start, end) == sep`. For
738     /// matches of `sep` within `self` that overlap, only the indices corresponding to the first
739     /// match are returned.
740     ///
741     /// # Examples
742     ///
743     /// ```
744     /// # #![feature(collections)]
745     /// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".match_indices("abc").collect();
746     /// assert_eq!(v, [(0,3), (6,9), (12,15)]);
747     ///
748     /// let v: Vec<(usize, usize)> = "1abcabc2".match_indices("abc").collect();
749     /// assert_eq!(v, [(1,4), (4,7)]);
750     ///
751     /// let v: Vec<(usize, usize)> = "ababa".match_indices("aba").collect();
752     /// assert_eq!(v, [(0, 3)]); // only the first `aba`
753     /// ```
754     #[unstable(feature = "collections",
755                reason = "might have its iterator type changed")]
756     // NB: Right now MatchIndices yields `(usize, usize)`,
757     // but it would be more consistent and useful to return `(usize, &str)`
758     pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
759         core_str::StrExt::match_indices(&self[..], pat)
760     }
761
762     /// An iterator over the lines of a string, separated by `\n`.
763     ///
764     /// This does not include the empty string after a trailing `\n`.
765     ///
766     /// # Examples
767     ///
768     /// ```
769     /// let four_lines = "foo\nbar\n\nbaz";
770     /// let v: Vec<&str> = four_lines.lines().collect();
771     ///
772     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
773     /// ```
774     ///
775     /// Leaving off the trailing character:
776     ///
777     /// ```
778     /// let four_lines = "foo\nbar\n\nbaz\n";
779     /// let v: Vec<&str> = four_lines.lines().collect();
780     ///
781     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
782     /// ```
783     #[stable(feature = "rust1", since = "1.0.0")]
784     pub fn lines(&self) -> Lines {
785         core_str::StrExt::lines(&self[..])
786     }
787
788     /// An iterator over the lines of a string, separated by either `\n` or `\r\n`.
789     ///
790     /// As with `.lines()`, this does not include an empty trailing line.
791     ///
792     /// # Examples
793     ///
794     /// ```
795     /// let four_lines = "foo\r\nbar\n\r\nbaz";
796     /// let v: Vec<&str> = four_lines.lines_any().collect();
797     ///
798     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
799     /// ```
800     ///
801     /// Leaving off the trailing character:
802     ///
803     /// ```
804     /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
805     /// let v: Vec<&str> = four_lines.lines_any().collect();
806     ///
807     /// assert_eq!(v, ["foo", "bar", "", "baz"]);
808     /// ```
809     #[stable(feature = "rust1", since = "1.0.0")]
810     pub fn lines_any(&self) -> LinesAny {
811         core_str::StrExt::lines_any(&self[..])
812     }
813     /// Returns a slice of the string from the character range [`begin`..`end`).
814     ///
815     /// That is, start at the `begin`-th code point of the string and continue
816     /// to the `end`-th code point. This does not detect or handle edge cases
817     /// such as leaving a combining character as the first code point of the
818     /// string.
819     ///
820     /// Due to the design of UTF-8, this operation is `O(end)`. See `slice`,
821     /// `slice_to` and `slice_from` for `O(1)` variants that use byte indices
822     /// rather than code point indices.
823     ///
824     /// # Panics
825     ///
826     /// Panics if `begin` > `end` or the either `begin` or `end` are beyond the
827     /// last character of the string.
828     ///
829     /// # Examples
830     ///
831     /// ```
832     /// # #![feature(collections)]
833     /// let s = "Löwe 老虎 Léopard";
834     ///
835     /// assert_eq!(s.slice_chars(0, 4), "Löwe");
836     /// assert_eq!(s.slice_chars(5, 7), "老虎");
837     /// ```
838     #[unstable(feature = "collections",
839                reason = "may have yet to prove its worth")]
840     pub fn slice_chars(&self, begin: usize, end: usize) -> &str {
841         core_str::StrExt::slice_chars(&self[..], begin, end)
842     }
843
844     /// Takes a bytewise slice from a string.
845     ///
846     /// Returns the substring from [`begin`..`end`).
847     ///
848     /// # Unsafety
849     ///
850     /// Caller must check both UTF-8 character boundaries and the boundaries of the entire slice as
851     /// well.
852     ///
853     /// # Examples
854     ///
855     /// ```
856     /// let s = "Löwe 老虎 Léopard";
857     ///
858     /// unsafe {
859     ///     assert_eq!(s.slice_unchecked(0, 21), "Löwe 老虎 Léopard");
860     /// }
861     /// ```
862     #[stable(feature = "rust1", since = "1.0.0")]
863     pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
864         core_str::StrExt::slice_unchecked(&self[..], begin, end)
865     }
866
867     /// Returns `true` if the given `&str` is a prefix of the string.
868     ///
869     /// # Examples
870     ///
871     /// ```
872     /// assert!("banana".starts_with("ba"));
873     /// ```
874     #[stable(feature = "rust1", since = "1.0.0")]
875     pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
876         core_str::StrExt::starts_with(&self[..], pat)
877     }
878
879     /// Returns true if the given `&str` is a suffix of the string.
880     ///
881     /// # Examples
882     ///
883     /// ```rust
884     /// assert!("banana".ends_with("nana"));
885     /// ```
886     #[stable(feature = "rust1", since = "1.0.0")]
887     pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
888         where P::Searcher: ReverseSearcher<'a>
889     {
890         core_str::StrExt::ends_with(&self[..], pat)
891     }
892
893     /// Returns a string with all pre- and suffixes that match a pattern repeatedly removed.
894     ///
895     /// The pattern can be a simple `&str`, or a closure that determines the split.
896     ///
897     /// # Examples
898     ///
899     /// Simple `&str` patterns:
900     ///
901     /// ```
902     /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
903     ///
904     /// let x: &[_] = &['1', '2'];
905     /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
906     /// ```
907     ///
908     /// More complex patterns with a lambda:
909     ///
910     /// ```
911     /// assert_eq!("123foo1bar123".trim_matches(|c: char| c.is_numeric()), "foo1bar");
912     /// ```
913     #[stable(feature = "rust1", since = "1.0.0")]
914     pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
915         where P::Searcher: DoubleEndedSearcher<'a>
916     {
917         core_str::StrExt::trim_matches(&self[..], pat)
918     }
919
920     /// Returns a string with all prefixes that match a pattern repeatedly removed.
921     ///
922     /// The pattern can be a simple `&str`, or a closure that determines the split.
923     ///
924     /// # Examples
925     ///
926     /// Simple `&str` patterns:
927     ///
928     /// ```
929     /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
930     ///
931     /// let x: &[_] = &['1', '2'];
932     /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
933     /// ```
934     ///
935     /// More complex patterns with a lambda:
936     ///
937     /// ```
938     /// assert_eq!("123foo1bar123".trim_left_matches(|c: char| c.is_numeric()), "foo1bar123");
939     /// ```
940     #[stable(feature = "rust1", since = "1.0.0")]
941     pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
942         core_str::StrExt::trim_left_matches(&self[..], pat)
943     }
944
945     /// Returns a string with all suffixes that match a pattern repeatedly removed.
946     ///
947     /// The pattern can be a simple `&str`, or a closure that determines the split.
948     ///
949     /// # Examples
950     ///
951     /// Simple `&str` patterns:
952     ///
953     /// ```
954     /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
955     /// let x: &[_] = &['1', '2'];
956     /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
957     /// ```
958     ///
959     /// More complex patterns with a lambda:
960     ///
961     /// ```
962     /// assert_eq!("123foo1bar123".trim_right_matches(|c: char| c.is_numeric()), "123foo1bar");
963     /// ```
964     #[stable(feature = "rust1", since = "1.0.0")]
965     pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
966         where P::Searcher: ReverseSearcher<'a>
967     {
968         core_str::StrExt::trim_right_matches(&self[..], pat)
969     }
970
971     /// Check that `index`-th byte lies at the start and/or end of a UTF-8 code point sequence.
972     ///
973     /// The start and end of the string (when `index == self.len()`) are considered to be
974     /// boundaries.
975     ///
976     /// # Panics
977     ///
978     /// Panics if `index` is greater than `self.len()`.
979     ///
980     /// # Examples
981     ///
982     /// ```
983     /// # #![feature(str_char)]
984     /// let s = "Löwe 老虎 Léopard";
985     /// assert!(s.is_char_boundary(0));
986     /// // start of `老`
987     /// assert!(s.is_char_boundary(6));
988     /// assert!(s.is_char_boundary(s.len()));
989     ///
990     /// // second byte of `ö`
991     /// assert!(!s.is_char_boundary(2));
992     ///
993     /// // third byte of `老`
994     /// assert!(!s.is_char_boundary(8));
995     /// ```
996     #[unstable(feature = "str_char",
997                reason = "it is unclear whether this method pulls its weight \
998                          with the existence of the char_indices iterator or \
999                          this method may want to be replaced with checked \
1000                          slicing")]
1001     pub fn is_char_boundary(&self, index: usize) -> bool {
1002         core_str::StrExt::is_char_boundary(&self[..], index)
1003     }
1004
1005     /// Given a byte position, return the next char and its index.
1006     ///
1007     /// This can be used to iterate over the Unicode characters of a string.
1008     ///
1009     /// # Panics
1010     ///
1011     /// If `i` is greater than or equal to the length of the string.
1012     /// If `i` is not the index of the beginning of a valid UTF-8 character.
1013     ///
1014     /// # Examples
1015     ///
1016     /// This example manually iterates through the characters of a string; this should normally be
1017     /// done by `.chars()` or `.char_indices()`.
1018     ///
1019     /// ```
1020     /// # #![feature(str_char, core)]
1021     /// use std::str::CharRange;
1022     ///
1023     /// let s = "中华Việt Nam";
1024     /// let mut i = 0;
1025     /// while i < s.len() {
1026     ///     let CharRange {ch, next} = s.char_range_at(i);
1027     ///     println!("{}: {}", i, ch);
1028     ///     i = next;
1029     /// }
1030     /// ```
1031     ///
1032     /// This outputs:
1033     ///
1034     /// ```text
1035     /// 0: 中
1036     /// 3: 华
1037     /// 6: V
1038     /// 7: i
1039     /// 8: ệ
1040     /// 11: t
1041     /// 12:
1042     /// 13: N
1043     /// 14: a
1044     /// 15: m
1045     /// ```
1046     #[unstable(feature = "str_char",
1047                reason = "often replaced by char_indices, this method may \
1048                          be removed in favor of just char_at() or eventually \
1049                          removed altogether")]
1050     pub fn char_range_at(&self, start: usize) -> CharRange {
1051         core_str::StrExt::char_range_at(&self[..], start)
1052     }
1053
1054     /// Given a byte position, return the previous `char` and its position.
1055     ///
1056     /// This function can be used to iterate over a Unicode string in reverse.
1057     ///
1058     /// Returns 0 for next index if called on start index 0.
1059     ///
1060     /// # Panics
1061     ///
1062     /// If `i` is greater than the length of the string.
1063     /// If `i` is not an index following a valid UTF-8 character.
1064     ///
1065     /// # Examples
1066     ///
1067     /// This example manually iterates through the characters of a string; this should normally be
1068     /// done by `.chars().rev()` or `.char_indices()`.
1069     ///
1070     /// ```
1071     /// # #![feature(str_char, core)]
1072     /// use std::str::CharRange;
1073     ///
1074     /// let s = "中华Việt Nam";
1075     /// let mut i = s.len();
1076     /// while i > 0 {
1077     ///     let CharRange {ch, next} = s.char_range_at_reverse(i);
1078     ///     println!("{}: {}", i, ch);
1079     ///     i = next;
1080     /// }
1081     /// ```
1082     ///
1083     /// This outputs:
1084     ///
1085     /// ```text
1086     /// 16: m
1087     /// 15: a
1088     /// 14: N
1089     /// 13:
1090     /// 12: t
1091     /// 11: ệ
1092     /// 8: i
1093     /// 7: V
1094     /// 6: 华
1095     /// 3: 中
1096     /// ```
1097     #[unstable(feature = "str_char",
1098                reason = "often replaced by char_indices, this method may \
1099                          be removed in favor of just char_at_reverse() or \
1100                          eventually removed altogether")]
1101     pub fn char_range_at_reverse(&self, start: usize) -> CharRange {
1102         core_str::StrExt::char_range_at_reverse(&self[..], start)
1103     }
1104
1105     /// Given a byte position, return the `char` at that position.
1106     ///
1107     /// # Panics
1108     ///
1109     /// If `i` is greater than or equal to the length of the string.
1110     /// If `i` is not the index of the beginning of a valid UTF-8 character.
1111     ///
1112     /// # Examples
1113     ///
1114     /// ```
1115     /// # #![feature(str_char)]
1116     /// let s = "abπc";
1117     /// assert_eq!(s.char_at(1), 'b');
1118     /// assert_eq!(s.char_at(2), 'π');
1119     /// ```
1120     #[unstable(feature = "str_char",
1121                reason = "frequently replaced by the chars() iterator, this \
1122                          method may be removed or possibly renamed in the \
1123                          future; it is normally replaced by chars/char_indices \
1124                          iterators or by getting the first char from a \
1125                          subslice")]
1126     pub fn char_at(&self, i: usize) -> char {
1127         core_str::StrExt::char_at(&self[..], i)
1128     }
1129
1130     /// Given a byte position, return the `char` at that position, counting from the end.
1131     ///
1132     /// # Panics
1133     ///
1134     /// If `i` is greater than the length of the string.
1135     /// If `i` is not an index following a valid UTF-8 character.
1136     ///
1137     /// # Examples
1138     ///
1139     /// ```
1140     /// # #![feature(str_char)]
1141     /// let s = "abπc";
1142     /// assert_eq!(s.char_at_reverse(1), 'a');
1143     /// assert_eq!(s.char_at_reverse(2), 'b');
1144     /// ```
1145     #[unstable(feature = "str_char",
1146                reason = "see char_at for more details, but reverse semantics \
1147                          are also somewhat unclear, especially with which \
1148                          cases generate panics")]
1149     pub fn char_at_reverse(&self, i: usize) -> char {
1150         core_str::StrExt::char_at_reverse(&self[..], i)
1151     }
1152
1153     /// Convert `self` to a byte slice.
1154     ///
1155     /// # Examples
1156     ///
1157     /// ```
1158     /// assert_eq!("bors".as_bytes(), b"bors");
1159     /// ```
1160     #[stable(feature = "rust1", since = "1.0.0")]
1161     pub fn as_bytes(&self) -> &[u8] {
1162         core_str::StrExt::as_bytes(&self[..])
1163     }
1164
1165     /// Returns the byte index of the first character of `self` that matches the pattern, if it
1166     /// exists.
1167     ///
1168     /// Returns `None` if it doesn't exist.
1169     ///
1170     /// The pattern can be a simple `&str`, or a closure that determines the split.
1171     ///
1172     /// # Examples
1173     ///
1174     /// Simple `&str` patterns:
1175     ///
1176     /// ```
1177     /// let s = "Löwe 老虎 Léopard";
1178     ///
1179     /// assert_eq!(s.find('L'), Some(0));
1180     /// assert_eq!(s.find('é'), Some(14));
1181     ///
1182     /// ```
1183     ///
1184     /// More complex patterns with a lambda:
1185     ///
1186     /// ```
1187     /// let s = "Löwe 老虎 Léopard";
1188     ///
1189     /// assert_eq!(s.find(|c: char| c.is_whitespace()), Some(5));
1190     /// ```
1191     ///
1192     /// Not finding the pattern:
1193     ///
1194     /// ```
1195     /// let s = "Löwe 老虎 Léopard";
1196     /// let x: &[_] = &['1', '2'];
1197     ///
1198     /// assert_eq!(s.find(x), None);
1199     /// ```
1200     #[stable(feature = "rust1", since = "1.0.0")]
1201     pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1202         core_str::StrExt::find(&self[..], pat)
1203     }
1204
1205     /// Returns the byte index of the last character of `self` that matches the pattern, if it
1206     /// exists.
1207     ///
1208     /// Returns `None` if it doesn't exist.
1209     ///
1210     /// The pattern can be a simple `&str`, or a closure that determines the split.
1211     ///
1212     /// # Examples
1213     ///
1214     /// Simple `&str` patterns:
1215     ///
1216     /// ```
1217     /// let s = "Löwe 老虎 Léopard";
1218     ///
1219     /// assert_eq!(s.rfind('L'), Some(13));
1220     /// assert_eq!(s.rfind('é'), Some(14));
1221     /// ```
1222     ///
1223     /// More complex patterns with a lambda:
1224     ///
1225     /// ```
1226     /// let s = "Löwe 老虎 Léopard";
1227     ///
1228     /// assert_eq!(s.rfind(|c: char| c.is_whitespace()), Some(12));
1229     /// ```
1230     ///
1231     /// Not finding the pattern:
1232     ///
1233     /// ```
1234     /// let s = "Löwe 老虎 Léopard";
1235     /// let x: &[_] = &['1', '2'];
1236     ///
1237     /// assert_eq!(s.rfind(x), None);
1238     /// ```
1239     #[stable(feature = "rust1", since = "1.0.0")]
1240     pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1241         where P::Searcher: ReverseSearcher<'a>
1242     {
1243         core_str::StrExt::rfind(&self[..], pat)
1244     }
1245
1246     /// Retrieves the first character from a `&str` and returns it.
1247     ///
1248     /// This does not allocate a new string; instead, it returns a slice that points one character
1249     /// beyond the character that was shifted.
1250     ///
1251     /// If the slice does not contain any characters, None is returned instead.
1252     ///
1253     /// # Examples
1254     ///
1255     /// ```
1256     /// # #![feature(str_char)]
1257     /// let s = "Löwe 老虎 Léopard";
1258     /// let (c, s1) = s.slice_shift_char().unwrap();
1259     ///
1260     /// assert_eq!(c, 'L');
1261     /// assert_eq!(s1, "öwe 老虎 Léopard");
1262     ///
1263     /// let (c, s2) = s1.slice_shift_char().unwrap();
1264     ///
1265     /// assert_eq!(c, 'ö');
1266     /// assert_eq!(s2, "we 老虎 Léopard");
1267     /// ```
1268     #[unstable(feature = "str_char",
1269                reason = "awaiting conventions about shifting and slices and \
1270                          may not be warranted with the existence of the chars \
1271                          and/or char_indices iterators")]
1272     pub fn slice_shift_char(&self) -> Option<(char, &str)> {
1273         core_str::StrExt::slice_shift_char(&self[..])
1274     }
1275
1276     /// Returns the byte offset of an inner slice relative to an enclosing outer slice.
1277     ///
1278     /// # Panics
1279     ///
1280     /// Panics if `inner` is not a direct slice contained within self.
1281     ///
1282     /// # Examples
1283     ///
1284     /// ```
1285     /// # #![feature(collections)]
1286     /// let string = "a\nb\nc";
1287     /// let lines: Vec<&str> = string.lines().collect();
1288     ///
1289     /// assert!(string.subslice_offset(lines[0]) == 0); // &"a"
1290     /// assert!(string.subslice_offset(lines[1]) == 2); // &"b"
1291     /// assert!(string.subslice_offset(lines[2]) == 4); // &"c"
1292     /// ```
1293     #[unstable(feature = "collections",
1294                reason = "awaiting convention about comparability of arbitrary slices")]
1295     pub fn subslice_offset(&self, inner: &str) -> usize {
1296         core_str::StrExt::subslice_offset(&self[..], inner)
1297     }
1298
1299     /// Return an unsafe pointer to the `&str`'s buffer.
1300     ///
1301     /// The caller must ensure that the string outlives this pointer, and that it is not
1302     /// reallocated (e.g. by pushing to the string).
1303     ///
1304     /// # Examples
1305     ///
1306     /// ```
1307     /// let s = "Hello";
1308     /// let p = s.as_ptr();
1309     /// ```
1310     #[stable(feature = "rust1", since = "1.0.0")]
1311     #[inline]
1312     pub fn as_ptr(&self) -> *const u8 {
1313         core_str::StrExt::as_ptr(&self[..])
1314     }
1315
1316     /// Return an iterator of `u16` over the string encoded as UTF-16.
1317     #[unstable(feature = "collections",
1318                reason = "this functionality may only be provided by libunicode")]
1319     pub fn utf16_units(&self) -> Utf16Units {
1320         Utf16Units { encoder: Utf16Encoder::new(self[..].chars()) }
1321     }
1322
1323     /// Returns the length of `self` in bytes.
1324     ///
1325     /// # Examples
1326     ///
1327     /// ```
1328     /// assert_eq!("foo".len(), 3);
1329     /// assert_eq!("ƒoo".len(), 4); // fancy f!
1330     /// ```
1331     #[stable(feature = "rust1", since = "1.0.0")]
1332     #[inline]
1333     pub fn len(&self) -> usize {
1334         core_str::StrExt::len(&self[..])
1335     }
1336
1337     /// Returns true if this slice has a length of zero bytes.
1338     ///
1339     /// # Examples
1340     ///
1341     /// ```
1342     /// assert!("".is_empty());
1343     /// ```
1344     #[inline]
1345     #[stable(feature = "rust1", since = "1.0.0")]
1346     pub fn is_empty(&self) -> bool {
1347         core_str::StrExt::is_empty(&self[..])
1348     }
1349
1350     /// Parses `self` into the specified type.
1351     ///
1352     /// # Failure
1353     ///
1354     /// Will return `Err` if it's not possible to parse `self` into the type.
1355     ///
1356     /// # Example
1357     ///
1358     /// ```
1359     /// assert_eq!("4".parse::<u32>(), Ok(4));
1360     /// ```
1361     ///
1362     /// Failing:
1363     ///
1364     /// ```
1365     /// assert!("j".parse::<u32>().is_err());
1366     /// ```
1367     #[inline]
1368     #[stable(feature = "rust1", since = "1.0.0")]
1369     pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1370         core_str::StrExt::parse(&self[..])
1371     }
1372
1373     /// Returns an iterator over the [grapheme clusters][graphemes] of `self`.
1374     ///
1375     /// [graphemes]: http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
1376     ///
1377     /// If `is_extended` is true, the iterator is over the *extended grapheme clusters*;
1378     /// otherwise, the iterator is over the *legacy grapheme clusters*.
1379     /// [UAX#29](http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)
1380     /// recommends extended grapheme cluster boundaries for general processing.
1381     ///
1382     /// # Examples
1383     ///
1384     /// ```
1385     /// # #![feature(unicode, core)]
1386     /// let gr1 = "a\u{310}e\u{301}o\u{308}\u{332}".graphemes(true).collect::<Vec<&str>>();
1387     /// let b: &[_] = &["a\u{310}", "e\u{301}", "o\u{308}\u{332}"];
1388     ///
1389     /// assert_eq!(&gr1[..], b);
1390     ///
1391     /// let gr2 = "a\r\nb🇷🇺🇸🇹".graphemes(true).collect::<Vec<&str>>();
1392     /// let b: &[_] = &["a", "\r\n", "b", "🇷🇺🇸🇹"];
1393     ///
1394     /// assert_eq!(&gr2[..], b);
1395     /// ```
1396     #[unstable(feature = "unicode",
1397                reason = "this functionality may only be provided by libunicode")]
1398     pub fn graphemes(&self, is_extended: bool) -> Graphemes {
1399         UnicodeStr::graphemes(&self[..], is_extended)
1400     }
1401
1402     /// Returns an iterator over the grapheme clusters of `self` and their byte offsets. See
1403     /// `graphemes()` for more information.
1404     ///
1405     /// # Examples
1406     ///
1407     /// ```
1408     /// # #![feature(unicode, core)]
1409     /// let gr_inds = "a̐éö̲\r\n".grapheme_indices(true).collect::<Vec<(usize, &str)>>();
1410     /// let b: &[_] = &[(0, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
1411     ///
1412     /// assert_eq!(&gr_inds[..], b);
1413     /// ```
1414     #[unstable(feature = "unicode",
1415                reason = "this functionality may only be provided by libunicode")]
1416     pub fn grapheme_indices(&self, is_extended: bool) -> GraphemeIndices {
1417         UnicodeStr::grapheme_indices(&self[..], is_extended)
1418     }
1419
1420     /// An iterator over the non-empty words of `self`.
1421     ///
1422     /// A 'word' is a subsequence separated by any sequence of whitespace. Sequences of whitespace
1423     /// are collapsed, so empty "words" are not included.
1424     ///
1425     /// # Examples
1426     ///
1427     /// ```
1428     /// # #![feature(str_words)]
1429     /// let some_words = " Mary   had\ta little  \n\t lamb";
1430     /// let v: Vec<&str> = some_words.words().collect();
1431     ///
1432     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1433     /// ```
1434     #[unstable(feature = "str_words",
1435                reason = "the precise algorithm to use is unclear")]
1436     pub fn words(&self) -> Words {
1437         UnicodeStr::words(&self[..])
1438     }
1439
1440     /// Returns a string's displayed width in columns.
1441     ///
1442     /// Control characters have zero width.
1443     ///
1444     /// `is_cjk` determines behavior for characters in the Ambiguous category: if `is_cjk` is
1445     /// `true`, these are 2 columns wide; otherwise, they are 1. In CJK locales, `is_cjk` should be
1446     /// `true`, else it should be `false`.
1447     /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) recommends that these
1448     /// characters be treated as 1 column (i.e., `is_cjk = false`) if the locale is unknown.
1449     #[unstable(feature = "unicode",
1450                reason = "this functionality may only be provided by libunicode")]
1451     pub fn width(&self, is_cjk: bool) -> usize {
1452         UnicodeStr::width(&self[..], is_cjk)
1453     }
1454
1455     /// Returns a `&str` with leading and trailing whitespace removed.
1456     ///
1457     /// # Examples
1458     ///
1459     /// ```
1460     /// let s = " Hello\tworld\t";
1461     /// assert_eq!(s.trim(), "Hello\tworld");
1462     /// ```
1463     #[stable(feature = "rust1", since = "1.0.0")]
1464     pub fn trim(&self) -> &str {
1465         UnicodeStr::trim(&self[..])
1466     }
1467
1468     /// Returns a `&str` with leading whitespace removed.
1469     ///
1470     /// # Examples
1471     ///
1472     /// ```
1473     /// let s = " Hello\tworld\t";
1474     /// assert_eq!(s.trim_left(), "Hello\tworld\t");
1475     /// ```
1476     #[stable(feature = "rust1", since = "1.0.0")]
1477     pub fn trim_left(&self) -> &str {
1478         UnicodeStr::trim_left(&self[..])
1479     }
1480
1481     /// Returns a `&str` with trailing whitespace removed.
1482     ///
1483     /// # Examples
1484     ///
1485     /// ```
1486     /// let s = " Hello\tworld\t";
1487     /// assert_eq!(s.trim_right(), " Hello\tworld");
1488     /// ```
1489     #[stable(feature = "rust1", since = "1.0.0")]
1490     pub fn trim_right(&self) -> &str {
1491         UnicodeStr::trim_right(&self[..])
1492     }
1493
1494     /// Returns the lowercase equivalent of this string.
1495     ///
1496     /// # Examples
1497     ///
1498     /// let s = "HELLO";
1499     /// assert_eq!(s.to_lowercase(), "hello");
1500     #[unstable(feature = "collections")]
1501     pub fn to_lowercase(&self) -> String {
1502         let mut s = String::with_capacity(self.len());
1503         s.extend(self[..].chars().flat_map(|c| c.to_lowercase()));
1504         return s;
1505     }
1506
1507     /// Returns the uppercase equivalent of this string.
1508     ///
1509     /// # Examples
1510     ///
1511     /// let s = "hello";
1512     /// assert_eq!(s.to_uppercase(), "HELLO");
1513     #[unstable(feature = "collections")]
1514     pub fn to_uppercase(&self) -> String {
1515         let mut s = String::with_capacity(self.len());
1516         s.extend(self[..].chars().flat_map(|c| c.to_uppercase()));
1517         return s;
1518     }
1519 }