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