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.
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.
11 //! String manipulation
13 //! For more details, see std::str
15 #![stable(feature = "rust1", since = "1.0.0")]
17 use self::pattern::Pattern;
18 use self::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
20 use char::{self, CharExt};
26 use iter::ExactSizeIterator;
27 use iter::{Map, Cloned, Iterator, DoubleEndedIterator};
30 use ops::{Fn, FnMut, FnOnce};
31 use option::Option::{self, None, Some};
32 use raw::{Repr, Slice};
33 use result::Result::{self, Ok, Err};
34 use slice::{self, SliceExt};
38 /// A trait to abstract the idea of creating a new instance of a type from a
40 #[stable(feature = "rust1", since = "1.0.0")]
41 pub trait FromStr: Sized {
42 /// The associated error which can be returned from parsing.
43 #[stable(feature = "rust1", since = "1.0.0")]
46 /// Parses a string `s` to return a value of this type.
48 /// If parsing succeeds, return the value inside `Ok`, otherwise
49 /// when the string is ill-formatted return an error specific to the
50 /// inside `Err`. The error type is specific to implementation of the trait.
54 /// Basic usage with [`i32`][ithirtytwo], a type that implements `FromStr`:
56 /// [ithirtytwo]: ../primitive.i32.html
59 /// use std::str::FromStr;
62 /// let x = i32::from_str(s).unwrap();
66 #[stable(feature = "rust1", since = "1.0.0")]
67 fn from_str(s: &str) -> Result<Self, Self::Err>;
70 #[stable(feature = "rust1", since = "1.0.0")]
71 impl FromStr for bool {
72 type Err = ParseBoolError;
74 /// Parse a `bool` from a string.
76 /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
77 /// actually be parseable.
82 /// use std::str::FromStr;
84 /// assert_eq!(FromStr::from_str("true"), Ok(true));
85 /// assert_eq!(FromStr::from_str("false"), Ok(false));
86 /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
89 /// Note, in many cases, the `.parse()` method on `str` is more proper.
92 /// assert_eq!("true".parse(), Ok(true));
93 /// assert_eq!("false".parse(), Ok(false));
94 /// assert!("not even a boolean".parse::<bool>().is_err());
97 fn from_str(s: &str) -> Result<bool, ParseBoolError> {
100 "false" => Ok(false),
101 _ => Err(ParseBoolError { _priv: () }),
106 /// An error returned when parsing a `bool` from a string fails.
107 #[derive(Debug, Clone, PartialEq)]
108 #[stable(feature = "rust1", since = "1.0.0")]
109 pub struct ParseBoolError { _priv: () }
111 #[stable(feature = "rust1", since = "1.0.0")]
112 impl fmt::Display for ParseBoolError {
113 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
114 "provided string was not `true` or `false`".fmt(f)
119 Section: Creating a string
122 /// Errors which can occur when attempting to interpret a sequence of `u8`
125 /// As such, the `from_utf8` family of functions and methods for both `String`s
126 /// and `&str`s make use of this error, for example.
127 #[derive(Copy, Eq, PartialEq, Clone, Debug)]
128 #[stable(feature = "rust1", since = "1.0.0")]
129 pub struct Utf8Error {
134 /// Returns the index in the given string up to which valid UTF-8 was
137 /// It is the maximum index such that `from_utf8(input[..index])`
138 /// would return `Some(_)`.
147 /// // some invalid bytes, in a vector
148 /// let sparkle_heart = vec![0, 159, 146, 150];
150 /// // std::str::from_utf8 returns a Utf8Error
151 /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
153 /// // the first byte is invalid here
154 /// assert_eq!(1, error.valid_up_to());
156 #[stable(feature = "utf8_error", since = "1.5.0")]
157 pub fn valid_up_to(&self) -> usize { self.valid_up_to }
160 /// Converts a slice of bytes to a string slice.
162 /// A string slice (`&str`) is made of bytes (`u8`), and a byte slice (`&[u8]`)
163 /// is made of bytes, so this function converts between the two. Not all byte
164 /// slices are valid string slices, however: `&str` requires that it is valid
165 /// UTF-8. `from_utf8()` checks to ensure that the bytes are valid UTF-8, and
166 /// then does the conversion.
168 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
169 /// incur the overhead of the validity check, there is an unsafe version of
170 /// this function, [`from_utf8_unchecked()`][fromutf8], which has the same
171 /// behavior but skips the check.
173 /// [fromutf8]: fn.from_utf8.html
175 /// If you need a `String` instead of a `&str`, consider
176 /// [`String::from_utf8()`][string].
178 /// [string]: ../string/struct.String.html#method.from_utf8
180 /// Because you can stack-allocate a `[u8; N]`, and you can take a `&[u8]` of
181 /// it, this function is one way to have a stack-allocated string. There is
182 /// an example of this in the examples section below.
186 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
187 /// provided slice is not UTF-8.
196 /// // some bytes, in a vector
197 /// let sparkle_heart = vec![240, 159, 146, 150];
199 /// // We know these bytes are valid, so just use `unwrap()`.
200 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
202 /// assert_eq!("💖", sparkle_heart);
210 /// // some invalid bytes, in a vector
211 /// let sparkle_heart = vec![0, 159, 146, 150];
213 /// assert!(str::from_utf8(&sparkle_heart).is_err());
216 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
217 /// errors that can be returned.
219 /// [error]: struct.Utf8Error.html
221 /// A "stack allocated string":
226 /// // some bytes, in a stack-allocated array
227 /// let sparkle_heart = [240, 159, 146, 150];
229 /// // We know these bytes are valid, so just use `unwrap()`.
230 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
232 /// assert_eq!("💖", sparkle_heart);
234 #[stable(feature = "rust1", since = "1.0.0")]
235 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
236 try!(run_utf8_validation_iterator(&mut v.iter()));
237 Ok(unsafe { from_utf8_unchecked(v) })
240 /// Converts a slice of bytes to a string slice without checking
241 /// that the string contains valid UTF-8.
243 /// See the safe version, [`from_utf8()`][fromutf8], for more.
245 /// [fromutf8]: fn.from_utf8.html
249 /// This function is unsafe because it does not check that the bytes passed to
250 /// it are valid UTF-8. If this constraint is violated, undefined behavior
251 /// results, as the rest of Rust assumes that `&str`s are valid UTF-8.
260 /// // some bytes, in a vector
261 /// let sparkle_heart = vec![240, 159, 146, 150];
263 /// let sparkle_heart = unsafe {
264 /// str::from_utf8_unchecked(&sparkle_heart)
267 /// assert_eq!("💖", sparkle_heart);
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
275 #[stable(feature = "rust1", since = "1.0.0")]
276 impl fmt::Display for Utf8Error {
277 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
278 write!(f, "invalid utf-8: invalid byte near index {}", self.valid_up_to)
286 /// Iterator for the char (representing *Unicode Scalar Values*) of a string
288 /// Created with the method `.chars()`.
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub struct Chars<'a> {
292 iter: slice::Iter<'a, u8>
295 /// Return the initial codepoint accumulator for the first byte.
296 /// The first byte is special, only want bottom 5 bits for width 2, 4 bits
297 /// for width 3, and 3 bits for width 4.
299 fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
301 /// Return the value of `ch` updated with continuation byte `byte`.
303 fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
305 /// Checks whether the byte is a UTF-8 continuation byte (i.e. starts with the
308 fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
311 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
318 /// Reads the next code point out of a byte iterator (assuming a
319 /// UTF-8-like encoding).
320 #[unstable(feature = "str_internals", issue = "0")]
322 pub fn next_code_point(bytes: &mut slice::Iter<u8>) -> Option<u32> {
324 let x = match bytes.next() {
326 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
327 Some(&next_byte) => next_byte,
330 // Multibyte case follows
331 // Decode from a byte combination out of: [[[x y] z] w]
332 // NOTE: Performance is sensitive to the exact formulation here
333 let init = utf8_first_byte(x, 2);
334 let y = unwrap_or_0(bytes.next());
335 let mut ch = utf8_acc_cont_byte(init, y);
338 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
339 let z = unwrap_or_0(bytes.next());
340 let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
341 ch = init << 12 | y_z;
344 // use only the lower 3 bits of `init`
345 let w = unwrap_or_0(bytes.next());
346 ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
353 /// Reads the last code point out of a byte iterator (assuming a
354 /// UTF-8-like encoding).
356 fn next_code_point_reverse(bytes: &mut slice::Iter<u8>) -> Option<u32> {
358 let w = match bytes.next_back() {
360 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
361 Some(&back_byte) => back_byte,
364 // Multibyte case follows
365 // Decode from a byte combination out of: [x [y [z w]]]
367 let z = unwrap_or_0(bytes.next_back());
368 ch = utf8_first_byte(z, 2);
369 if utf8_is_cont_byte(z) {
370 let y = unwrap_or_0(bytes.next_back());
371 ch = utf8_first_byte(y, 3);
372 if utf8_is_cont_byte(y) {
373 let x = unwrap_or_0(bytes.next_back());
374 ch = utf8_first_byte(x, 4);
375 ch = utf8_acc_cont_byte(ch, y);
377 ch = utf8_acc_cont_byte(ch, z);
379 ch = utf8_acc_cont_byte(ch, w);
384 #[stable(feature = "rust1", since = "1.0.0")]
385 impl<'a> Iterator for Chars<'a> {
389 fn next(&mut self) -> Option<char> {
390 next_code_point(&mut self.iter).map(|ch| {
391 // str invariant says `ch` is a valid Unicode Scalar Value
393 char::from_u32_unchecked(ch)
399 fn size_hint(&self) -> (usize, Option<usize>) {
400 let (len, _) = self.iter.size_hint();
401 // `(len + 3)` can't overflow, because we know that the `slice::Iter`
402 // belongs to a slice in memory which has a maximum length of
403 // `isize::MAX` (that's well below `usize::MAX`).
404 ((len + 3) / 4, Some(len))
408 #[stable(feature = "rust1", since = "1.0.0")]
409 impl<'a> DoubleEndedIterator for Chars<'a> {
411 fn next_back(&mut self) -> Option<char> {
412 next_code_point_reverse(&mut self.iter).map(|ch| {
413 // str invariant says `ch` is a valid Unicode Scalar Value
415 char::from_u32_unchecked(ch)
422 /// View the underlying data as a subslice of the original data.
424 /// This has the same lifetime as the original slice, and so the
425 /// iterator can continue to be used while this exists.
426 #[stable(feature = "iter_to_slice", since = "1.4.0")]
428 pub fn as_str(&self) -> &'a str {
429 unsafe { from_utf8_unchecked(self.iter.as_slice()) }
433 /// Iterator for a string's characters and their byte offsets.
435 #[stable(feature = "rust1", since = "1.0.0")]
436 pub struct CharIndices<'a> {
441 #[stable(feature = "rust1", since = "1.0.0")]
442 impl<'a> Iterator for CharIndices<'a> {
443 type Item = (usize, char);
446 fn next(&mut self) -> Option<(usize, char)> {
447 let (pre_len, _) = self.iter.iter.size_hint();
448 match self.iter.next() {
451 let index = self.front_offset;
452 let (len, _) = self.iter.iter.size_hint();
453 self.front_offset += pre_len - len;
460 fn size_hint(&self) -> (usize, Option<usize>) {
461 self.iter.size_hint()
465 #[stable(feature = "rust1", since = "1.0.0")]
466 impl<'a> DoubleEndedIterator for CharIndices<'a> {
468 fn next_back(&mut self) -> Option<(usize, char)> {
469 match self.iter.next_back() {
472 let (len, _) = self.iter.iter.size_hint();
473 let index = self.front_offset + len;
480 impl<'a> CharIndices<'a> {
481 /// View the underlying data as a subslice of the original data.
483 /// This has the same lifetime as the original slice, and so the
484 /// iterator can continue to be used while this exists.
485 #[stable(feature = "iter_to_slice", since = "1.4.0")]
487 pub fn as_str(&self) -> &'a str {
492 /// External iterator for a string's bytes.
493 /// Use with the `std::iter` module.
495 /// Created with the method `.bytes()`.
496 #[stable(feature = "rust1", since = "1.0.0")]
498 pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>);
500 #[stable(feature = "rust1", since = "1.0.0")]
501 impl<'a> Iterator for Bytes<'a> {
505 fn next(&mut self) -> Option<u8> {
510 fn size_hint(&self) -> (usize, Option<usize>) {
515 fn count(self) -> usize {
520 fn last(self) -> Option<Self::Item> {
525 fn nth(&mut self, n: usize) -> Option<Self::Item> {
530 #[stable(feature = "rust1", since = "1.0.0")]
531 impl<'a> DoubleEndedIterator for Bytes<'a> {
533 fn next_back(&mut self) -> Option<u8> {
538 #[stable(feature = "rust1", since = "1.0.0")]
539 impl<'a> ExactSizeIterator for Bytes<'a> {
541 fn len(&self) -> usize {
546 /// This macro generates a Clone impl for string pattern API
547 /// wrapper types of the form X<'a, P>
548 macro_rules! derive_pattern_clone {
549 (clone $t:ident with |$s:ident| $e:expr) => {
550 impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
551 where P::Searcher: Clone
553 fn clone(&self) -> Self {
561 /// This macro generates two public iterator structs
562 /// wrapping a private internal one that makes use of the `Pattern` API.
564 /// For all patterns `P: Pattern<'a>` the following items will be
565 /// generated (generics omitted):
567 /// struct $forward_iterator($internal_iterator);
568 /// struct $reverse_iterator($internal_iterator);
570 /// impl Iterator for $forward_iterator
571 /// { /* internal ends up calling Searcher::next_match() */ }
573 /// impl DoubleEndedIterator for $forward_iterator
574 /// where P::Searcher: DoubleEndedSearcher
575 /// { /* internal ends up calling Searcher::next_match_back() */ }
577 /// impl Iterator for $reverse_iterator
578 /// where P::Searcher: ReverseSearcher
579 /// { /* internal ends up calling Searcher::next_match_back() */ }
581 /// impl DoubleEndedIterator for $reverse_iterator
582 /// where P::Searcher: DoubleEndedSearcher
583 /// { /* internal ends up calling Searcher::next_match() */ }
585 /// The internal one is defined outside the macro, and has almost the same
586 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
587 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
589 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
590 /// `Pattern` might not return the same elements, so actually implementing
591 /// `DoubleEndedIterator` for it would be incorrect.
592 /// (See the docs in `str::pattern` for more details)
594 /// However, the internal struct still represents a single ended iterator from
595 /// either end, and depending on pattern is also a valid double ended iterator,
596 /// so the two wrapper structs implement `Iterator`
597 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
598 /// to the complex impls seen above.
599 macro_rules! generate_pattern_iterators {
603 $(#[$forward_iterator_attribute:meta])*
604 struct $forward_iterator:ident;
608 $(#[$reverse_iterator_attribute:meta])*
609 struct $reverse_iterator:ident;
611 // Stability of all generated items
613 $(#[$common_stability_attribute:meta])*
615 // Internal almost-iterator that is being delegated to
617 $internal_iterator:ident yielding ($iterty:ty);
619 // Kind of delgation - either single ended or double ended
622 $(#[$forward_iterator_attribute])*
623 $(#[$common_stability_attribute])*
624 pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
626 $(#[$common_stability_attribute])*
627 impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
631 fn next(&mut self) -> Option<$iterty> {
636 $(#[$common_stability_attribute])*
637 impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
638 where P::Searcher: Clone
640 fn clone(&self) -> Self {
641 $forward_iterator(self.0.clone())
645 $(#[$reverse_iterator_attribute])*
646 $(#[$common_stability_attribute])*
647 pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
649 $(#[$common_stability_attribute])*
650 impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
651 where P::Searcher: ReverseSearcher<'a>
656 fn next(&mut self) -> Option<$iterty> {
661 $(#[$common_stability_attribute])*
662 impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
663 where P::Searcher: Clone
665 fn clone(&self) -> Self {
666 $reverse_iterator(self.0.clone())
670 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
672 $reverse_iterator, $iterty);
675 double ended; with $(#[$common_stability_attribute:meta])*,
676 $forward_iterator:ident,
677 $reverse_iterator:ident, $iterty:ty
679 $(#[$common_stability_attribute])*
680 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
681 where P::Searcher: DoubleEndedSearcher<'a>
684 fn next_back(&mut self) -> Option<$iterty> {
689 $(#[$common_stability_attribute])*
690 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
691 where P::Searcher: DoubleEndedSearcher<'a>
694 fn next_back(&mut self) -> Option<$iterty> {
700 single ended; with $(#[$common_stability_attribute:meta])*,
701 $forward_iterator:ident,
702 $reverse_iterator:ident, $iterty:ty
706 derive_pattern_clone!{
708 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
710 struct SplitInternal<'a, P: Pattern<'a>> {
713 matcher: P::Searcher,
714 allow_trailing_empty: bool,
718 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
720 fn get_end(&mut self) -> Option<&'a str> {
721 if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
722 self.finished = true;
724 let string = self.matcher.haystack().slice_unchecked(self.start, self.end);
733 fn next(&mut self) -> Option<&'a str> {
734 if self.finished { return None }
736 let haystack = self.matcher.haystack();
737 match self.matcher.next_match() {
738 Some((a, b)) => unsafe {
739 let elt = haystack.slice_unchecked(self.start, a);
743 None => self.get_end(),
748 fn next_back(&mut self) -> Option<&'a str>
749 where P::Searcher: ReverseSearcher<'a>
751 if self.finished { return None }
753 if !self.allow_trailing_empty {
754 self.allow_trailing_empty = true;
755 match self.next_back() {
756 Some(elt) if !elt.is_empty() => return Some(elt),
757 _ => if self.finished { return None }
761 let haystack = self.matcher.haystack();
762 match self.matcher.next_match_back() {
763 Some((a, b)) => unsafe {
764 let elt = haystack.slice_unchecked(b, self.end);
769 self.finished = true;
770 Some(haystack.slice_unchecked(self.start, self.end))
776 generate_pattern_iterators! {
778 /// Created with the method `.split()`.
781 /// Created with the method `.rsplit()`.
784 #[stable(feature = "rust1", since = "1.0.0")]
786 SplitInternal yielding (&'a str);
787 delegate double ended;
790 generate_pattern_iterators! {
792 /// Created with the method `.split_terminator()`.
793 struct SplitTerminator;
795 /// Created with the method `.rsplit_terminator()`.
796 struct RSplitTerminator;
798 #[stable(feature = "rust1", since = "1.0.0")]
800 SplitInternal yielding (&'a str);
801 delegate double ended;
804 derive_pattern_clone!{
806 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
808 struct SplitNInternal<'a, P: Pattern<'a>> {
809 iter: SplitInternal<'a, P>,
810 /// The number of splits remaining
814 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
816 fn next(&mut self) -> Option<&'a str> {
819 1 => { self.count = 0; self.iter.get_end() }
820 _ => { self.count -= 1; self.iter.next() }
825 fn next_back(&mut self) -> Option<&'a str>
826 where P::Searcher: ReverseSearcher<'a>
830 1 => { self.count = 0; self.iter.get_end() }
831 _ => { self.count -= 1; self.iter.next_back() }
836 generate_pattern_iterators! {
838 /// Created with the method `.splitn()`.
841 /// Created with the method `.rsplitn()`.
844 #[stable(feature = "rust1", since = "1.0.0")]
846 SplitNInternal yielding (&'a str);
847 delegate single ended;
850 derive_pattern_clone!{
851 clone MatchIndicesInternal
852 with |s| MatchIndicesInternal(s.0.clone())
854 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
856 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
858 fn next(&mut self) -> Option<(usize, &'a str)> {
859 self.0.next_match().map(|(start, end)| unsafe {
860 (start, self.0.haystack().slice_unchecked(start, end))
865 fn next_back(&mut self) -> Option<(usize, &'a str)>
866 where P::Searcher: ReverseSearcher<'a>
868 self.0.next_match_back().map(|(start, end)| unsafe {
869 (start, self.0.haystack().slice_unchecked(start, end))
874 generate_pattern_iterators! {
876 /// Created with the method `.match_indices()`.
879 /// Created with the method `.rmatch_indices()`.
880 struct RMatchIndices;
882 #[stable(feature = "str_match_indices", since = "1.5.0")]
884 MatchIndicesInternal yielding ((usize, &'a str));
885 delegate double ended;
888 derive_pattern_clone!{
889 clone MatchesInternal
890 with |s| MatchesInternal(s.0.clone())
892 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
894 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
896 fn next(&mut self) -> Option<&'a str> {
897 self.0.next_match().map(|(a, b)| unsafe {
898 // Indices are known to be on utf8 boundaries
899 self.0.haystack().slice_unchecked(a, b)
904 fn next_back(&mut self) -> Option<&'a str>
905 where P::Searcher: ReverseSearcher<'a>
907 self.0.next_match_back().map(|(a, b)| unsafe {
908 // Indices are known to be on utf8 boundaries
909 self.0.haystack().slice_unchecked(a, b)
914 generate_pattern_iterators! {
916 /// Created with the method `.matches()`.
919 /// Created with the method `.rmatches()`.
922 #[stable(feature = "str_matches", since = "1.2.0")]
924 MatchesInternal yielding (&'a str);
925 delegate double ended;
928 /// Created with the method `.lines()`.
929 #[stable(feature = "rust1", since = "1.0.0")]
931 pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>);
933 #[stable(feature = "rust1", since = "1.0.0")]
934 impl<'a> Iterator for Lines<'a> {
938 fn next(&mut self) -> Option<&'a str> {
943 fn size_hint(&self) -> (usize, Option<usize>) {
948 #[stable(feature = "rust1", since = "1.0.0")]
949 impl<'a> DoubleEndedIterator for Lines<'a> {
951 fn next_back(&mut self) -> Option<&'a str> {
956 /// Created with the method `.lines_any()`.
957 #[stable(feature = "rust1", since = "1.0.0")]
958 #[deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")]
961 pub struct LinesAny<'a>(Lines<'a>);
963 /// A nameable, cloneable fn type
967 impl<'a> Fn<(&'a str,)> for LinesAnyMap {
969 extern "rust-call" fn call(&self, (line,): (&'a str,)) -> &'a str {
971 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
976 impl<'a> FnMut<(&'a str,)> for LinesAnyMap {
978 extern "rust-call" fn call_mut(&mut self, (line,): (&'a str,)) -> &'a str {
979 Fn::call(&*self, (line,))
983 impl<'a> FnOnce<(&'a str,)> for LinesAnyMap {
984 type Output = &'a str;
987 extern "rust-call" fn call_once(self, (line,): (&'a str,)) -> &'a str {
988 Fn::call(&self, (line,))
992 #[stable(feature = "rust1", since = "1.0.0")]
994 impl<'a> Iterator for LinesAny<'a> {
998 fn next(&mut self) -> Option<&'a str> {
1003 fn size_hint(&self) -> (usize, Option<usize>) {
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 #[allow(deprecated)]
1010 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1012 fn next_back(&mut self) -> Option<&'a str> {
1018 Section: Comparing strings
1021 /// Bytewise slice equality
1022 /// NOTE: This function is (ab)used in rustc::middle::trans::_match
1023 /// to compare &[u8] byte slices that are not necessarily valid UTF-8.
1026 fn eq_slice(a: &str, b: &str) -> bool {
1027 a.len() == b.len() && unsafe { cmp_slice(a, b, a.len()) == 0 }
1030 /// Bytewise slice comparison.
1031 /// NOTE: This uses the system's memcmp, which is currently dramatically
1032 /// faster than comparing each byte in a loop.
1034 unsafe fn cmp_slice(a: &str, b: &str, len: usize) -> i32 {
1035 // NOTE: In theory n should be libc::size_t and not usize, but libc is not available here
1036 #[allow(improper_ctypes)]
1037 extern { fn memcmp(s1: *const i8, s2: *const i8, n: usize) -> i32; }
1038 memcmp(a.as_ptr() as *const i8, b.as_ptr() as *const i8, len)
1045 /// Walk through `iter` checking that it's a valid UTF-8 sequence,
1046 /// returning `true` in that case, or, if it is invalid, `false` with
1047 /// `iter` reset such that it is pointing at the first byte in the
1048 /// invalid sequence.
1050 fn run_utf8_validation_iterator(iter: &mut slice::Iter<u8>)
1051 -> Result<(), Utf8Error> {
1052 let whole = iter.as_slice();
1054 // save the current thing we're pointing at.
1055 let old = iter.clone();
1057 // restore the iterator we had at the start of this codepoint.
1058 macro_rules! err { () => {{
1059 *iter = old.clone();
1060 return Err(Utf8Error {
1061 valid_up_to: whole.len() - iter.as_slice().len()
1065 macro_rules! next { () => {
1068 // we needed data, but there was none: error!
1073 let first = match iter.next() {
1075 // we're at the end of the iterator and a codepoint
1076 // boundary at the same time, so this string is valid.
1077 None => return Ok(())
1080 // ASCII characters are always valid, so only large
1081 // bytes need more examination.
1083 let w = UTF8_CHAR_WIDTH[first as usize];
1084 let second = next!();
1085 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
1086 // first C2 80 last DF BF
1087 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
1088 // first E0 A0 80 last EF BF BF
1089 // excluding surrogates codepoints \u{d800} to \u{dfff}
1090 // ED A0 80 to ED BF BF
1091 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1092 // first F0 90 80 80 last F4 8F BF BF
1094 // Use the UTF-8 syntax from the RFC
1096 // https://tools.ietf.org/html/rfc3629
1098 // UTF8-2 = %xC2-DF UTF8-tail
1099 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1100 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1101 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1102 // %xF4 %x80-8F 2( UTF8-tail )
1104 2 => if second & !CONT_MASK != TAG_CONT_U8 {err!()},
1106 match (first, second, next!() & !CONT_MASK) {
1107 (0xE0 , 0xA0 ... 0xBF, TAG_CONT_U8) |
1108 (0xE1 ... 0xEC, 0x80 ... 0xBF, TAG_CONT_U8) |
1109 (0xED , 0x80 ... 0x9F, TAG_CONT_U8) |
1110 (0xEE ... 0xEF, 0x80 ... 0xBF, TAG_CONT_U8) => {}
1115 match (first, second, next!() & !CONT_MASK, next!() & !CONT_MASK) {
1116 (0xF0 , 0x90 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
1117 (0xF1 ... 0xF3, 0x80 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
1118 (0xF4 , 0x80 ... 0x8F, TAG_CONT_U8, TAG_CONT_U8) => {}
1128 // https://tools.ietf.org/html/rfc3629
1129 static UTF8_CHAR_WIDTH: [u8; 256] = [
1130 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1131 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1132 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1133 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1134 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1135 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1136 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1137 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1138 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1139 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1140 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1141 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1142 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1143 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1144 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1145 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1148 /// Struct that contains a `char` and the index of the first byte of
1149 /// the next `char` in a string. This can be used as a data structure
1150 /// for iterating over the UTF-8 bytes of a string.
1151 #[derive(Copy, Clone)]
1152 #[unstable(feature = "str_char",
1153 reason = "existence of this struct is uncertain as it is frequently \
1154 able to be replaced with char.len_utf8() and/or \
1155 char/char_indices iterators",
1157 pub struct CharRange {
1160 /// Index of the first byte of the next `char`
1164 /// Mask of the value bits of a continuation byte
1165 const CONT_MASK: u8 = 0b0011_1111;
1166 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte
1167 const TAG_CONT_U8: u8 = 0b1000_0000;
1170 Section: Trait implementations
1174 use cmp::{self, Ordering, Ord, PartialEq, PartialOrd, Eq};
1175 use cmp::Ordering::{Less, Greater};
1178 use option::Option::Some;
1180 use str::{StrExt, eq_slice};
1182 #[stable(feature = "rust1", since = "1.0.0")]
1185 fn cmp(&self, other: &str) -> Ordering {
1187 super::cmp_slice(self, other, cmp::min(self.len(), other.len()))
1190 self.len().cmp(&other.len())
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 impl PartialEq for str {
1202 fn eq(&self, other: &str) -> bool {
1203 eq_slice(self, other)
1206 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1209 #[stable(feature = "rust1", since = "1.0.0")]
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 impl PartialOrd for str {
1215 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1216 Some(self.cmp(other))
1220 /// Returns a slice of the given string from the byte range
1221 /// [`begin`..`end`).
1223 /// This operation is `O(1)`.
1225 /// Panics when `begin` and `end` do not point to valid characters
1226 /// or point beyond the last character of the string.
1231 /// let s = "Löwe 老虎 Léopard";
1232 /// assert_eq!(&s[0 .. 1], "L");
1234 /// assert_eq!(&s[1 .. 9], "öwe 老");
1236 /// // these will panic:
1237 /// // byte 2 lies within `ö`:
1240 /// // byte 8 lies within `老`
1243 /// // byte 100 is outside the string
1244 /// // &s[3 .. 100];
1246 #[stable(feature = "rust1", since = "1.0.0")]
1247 impl ops::Index<ops::Range<usize>> for str {
1250 fn index(&self, index: ops::Range<usize>) -> &str {
1251 // is_char_boundary checks that the index is in [0, .len()]
1252 if index.start <= index.end &&
1253 self.is_char_boundary(index.start) &&
1254 self.is_char_boundary(index.end) {
1255 unsafe { self.slice_unchecked(index.start, index.end) }
1257 super::slice_error_fail(self, index.start, index.end)
1262 /// Returns a mutable slice of the given string from the byte range
1263 /// [`begin`..`end`).
1264 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1265 impl ops::IndexMut<ops::Range<usize>> for str {
1267 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1268 // is_char_boundary checks that the index is in [0, .len()]
1269 if index.start <= index.end &&
1270 self.is_char_boundary(index.start) &&
1271 self.is_char_boundary(index.end) {
1272 unsafe { self.slice_mut_unchecked(index.start, index.end) }
1274 super::slice_error_fail(self, index.start, index.end)
1279 /// Returns a slice of the string from the beginning to byte
1282 /// Equivalent to `self[0 .. end]`.
1284 /// Panics when `end` does not point to a valid character, or is
1286 #[stable(feature = "rust1", since = "1.0.0")]
1287 impl ops::Index<ops::RangeTo<usize>> for str {
1291 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1292 // is_char_boundary checks that the index is in [0, .len()]
1293 if self.is_char_boundary(index.end) {
1294 unsafe { self.slice_unchecked(0, index.end) }
1296 super::slice_error_fail(self, 0, index.end)
1301 /// Returns a mutable slice of the string from the beginning to byte
1303 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1304 impl ops::IndexMut<ops::RangeTo<usize>> for str {
1306 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1307 // is_char_boundary checks that the index is in [0, .len()]
1308 if self.is_char_boundary(index.end) {
1309 unsafe { self.slice_mut_unchecked(0, index.end) }
1311 super::slice_error_fail(self, 0, index.end)
1316 /// Returns a slice of the string from `begin` to its end.
1318 /// Equivalent to `self[begin .. self.len()]`.
1320 /// Panics when `begin` does not point to a valid character, or is
1322 #[stable(feature = "rust1", since = "1.0.0")]
1323 impl ops::Index<ops::RangeFrom<usize>> for str {
1327 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1328 // is_char_boundary checks that the index is in [0, .len()]
1329 if self.is_char_boundary(index.start) {
1330 unsafe { self.slice_unchecked(index.start, self.len()) }
1332 super::slice_error_fail(self, index.start, self.len())
1337 /// Returns a slice of the string from `begin` to its end.
1338 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1339 impl ops::IndexMut<ops::RangeFrom<usize>> for str {
1341 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1342 // is_char_boundary checks that the index is in [0, .len()]
1343 if self.is_char_boundary(index.start) {
1344 let len = self.len();
1345 unsafe { self.slice_mut_unchecked(index.start, len) }
1347 super::slice_error_fail(self, index.start, self.len())
1352 #[stable(feature = "rust1", since = "1.0.0")]
1353 impl ops::Index<ops::RangeFull> for str {
1357 fn index(&self, _index: ops::RangeFull) -> &str {
1362 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1363 impl ops::IndexMut<ops::RangeFull> for str {
1365 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1371 /// Methods for string slices
1372 #[allow(missing_docs)]
1374 #[unstable(feature = "core_str_ext",
1375 reason = "stable interface provided by `impl str` in later crates",
1378 // NB there are no docs here are they're all located on the StrExt trait in
1379 // libcollections, not here.
1381 fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
1382 fn contains_char<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
1383 fn chars(&self) -> Chars;
1384 fn bytes(&self) -> Bytes;
1385 fn char_indices(&self) -> CharIndices;
1386 fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P>;
1387 fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1388 where P::Searcher: ReverseSearcher<'a>;
1389 fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P>;
1390 fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
1391 where P::Searcher: ReverseSearcher<'a>;
1392 fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P>;
1393 fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1394 where P::Searcher: ReverseSearcher<'a>;
1395 fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P>;
1396 fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1397 where P::Searcher: ReverseSearcher<'a>;
1398 fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P>;
1399 fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1400 where P::Searcher: ReverseSearcher<'a>;
1401 fn lines(&self) -> Lines;
1402 #[allow(deprecated)]
1403 fn lines_any(&self) -> LinesAny;
1404 fn char_len(&self) -> usize;
1405 fn slice_chars(&self, begin: usize, end: usize) -> &str;
1406 unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str;
1407 unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str;
1408 fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
1409 fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
1410 where P::Searcher: ReverseSearcher<'a>;
1411 fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1412 where P::Searcher: DoubleEndedSearcher<'a>;
1413 fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str;
1414 fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1415 where P::Searcher: ReverseSearcher<'a>;
1416 fn is_char_boundary(&self, index: usize) -> bool;
1417 fn char_range_at(&self, start: usize) -> CharRange;
1418 fn char_range_at_reverse(&self, start: usize) -> CharRange;
1419 fn char_at(&self, i: usize) -> char;
1420 fn char_at_reverse(&self, i: usize) -> char;
1421 fn as_bytes(&self) -> &[u8];
1422 fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
1423 fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1424 where P::Searcher: ReverseSearcher<'a>;
1425 fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
1426 fn split_at(&self, mid: usize) -> (&str, &str);
1427 fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str);
1428 fn slice_shift_char(&self) -> Option<(char, &str)>;
1429 fn subslice_offset(&self, inner: &str) -> usize;
1430 fn as_ptr(&self) -> *const u8;
1431 fn len(&self) -> usize;
1432 fn is_empty(&self) -> bool;
1433 fn parse<T: FromStr>(&self) -> Result<T, T::Err>;
1437 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
1438 assert!(begin <= end);
1439 panic!("index {} and/or {} in `{}` do not lie on character boundary",
1443 #[unstable(feature = "core_str_ext",
1444 reason = "stable interface provided by `impl str` in later crates",
1446 impl StrExt for str {
1448 fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1449 pat.is_contained_in(self)
1453 fn contains_char<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1454 pat.is_contained_in(self)
1458 fn chars(&self) -> Chars {
1459 Chars{iter: self.as_bytes().iter()}
1463 fn bytes(&self) -> Bytes {
1464 Bytes(self.as_bytes().iter().cloned())
1468 fn char_indices(&self) -> CharIndices {
1469 CharIndices { front_offset: 0, iter: self.chars() }
1473 fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1474 Split(SplitInternal {
1477 matcher: pat.into_searcher(self),
1478 allow_trailing_empty: true,
1484 fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1485 where P::Searcher: ReverseSearcher<'a>
1487 RSplit(self.split(pat).0)
1491 fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
1492 SplitN(SplitNInternal {
1493 iter: self.split(pat).0,
1499 fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
1500 where P::Searcher: ReverseSearcher<'a>
1502 RSplitN(self.splitn(count, pat).0)
1506 fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1507 SplitTerminator(SplitInternal {
1508 allow_trailing_empty: false,
1514 fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1515 where P::Searcher: ReverseSearcher<'a>
1517 RSplitTerminator(self.split_terminator(pat).0)
1521 fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1522 Matches(MatchesInternal(pat.into_searcher(self)))
1526 fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1527 where P::Searcher: ReverseSearcher<'a>
1529 RMatches(self.matches(pat).0)
1533 fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1534 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
1538 fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1539 where P::Searcher: ReverseSearcher<'a>
1541 RMatchIndices(self.match_indices(pat).0)
1544 fn lines(&self) -> Lines {
1545 Lines(self.split_terminator('\n').map(LinesAnyMap))
1549 #[allow(deprecated)]
1550 fn lines_any(&self) -> LinesAny {
1551 LinesAny(self.lines())
1555 fn char_len(&self) -> usize { self.chars().count() }
1557 fn slice_chars(&self, begin: usize, end: usize) -> &str {
1558 assert!(begin <= end);
1560 let mut begin_byte = None;
1561 let mut end_byte = None;
1563 // This could be even more efficient by not decoding,
1564 // only finding the char boundaries
1565 for (idx, _) in self.char_indices() {
1566 if count == begin { begin_byte = Some(idx); }
1567 if count == end { end_byte = Some(idx); break; }
1570 if begin_byte.is_none() && count == begin { begin_byte = Some(self.len()) }
1571 if end_byte.is_none() && count == end { end_byte = Some(self.len()) }
1573 match (begin_byte, end_byte) {
1574 (None, _) => panic!("slice_chars: `begin` is beyond end of string"),
1575 (_, None) => panic!("slice_chars: `end` is beyond end of string"),
1576 (Some(a), Some(b)) => unsafe { self.slice_unchecked(a, b) }
1581 unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
1582 mem::transmute(Slice {
1583 data: self.as_ptr().offset(begin as isize),
1589 unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
1590 mem::transmute(Slice {
1591 data: self.as_ptr().offset(begin as isize),
1597 fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1598 pat.is_prefix_of(self)
1602 fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
1603 where P::Searcher: ReverseSearcher<'a>
1605 pat.is_suffix_of(self)
1609 fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1610 where P::Searcher: DoubleEndedSearcher<'a>
1614 let mut matcher = pat.into_searcher(self);
1615 if let Some((a, b)) = matcher.next_reject() {
1617 j = b; // Rember earliest known match, correct it below if
1618 // last match is different
1620 if let Some((_, b)) = matcher.next_reject_back() {
1624 // Searcher is known to return valid indices
1625 self.slice_unchecked(i, j)
1630 fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1631 let mut i = self.len();
1632 let mut matcher = pat.into_searcher(self);
1633 if let Some((a, _)) = matcher.next_reject() {
1637 // Searcher is known to return valid indices
1638 self.slice_unchecked(i, self.len())
1643 fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1644 where P::Searcher: ReverseSearcher<'a>
1647 let mut matcher = pat.into_searcher(self);
1648 if let Some((_, b)) = matcher.next_reject_back() {
1652 // Searcher is known to return valid indices
1653 self.slice_unchecked(0, j)
1658 fn is_char_boundary(&self, index: usize) -> bool {
1659 if index == self.len() { return true; }
1660 match self.as_bytes().get(index) {
1662 Some(&b) => b < 128 || b >= 192,
1667 fn char_range_at(&self, i: usize) -> CharRange {
1668 let (c, n) = char_range_at_raw(self.as_bytes(), i);
1669 CharRange { ch: unsafe { char::from_u32_unchecked(c) }, next: n }
1673 fn char_range_at_reverse(&self, start: usize) -> CharRange {
1674 let mut prev = start;
1676 prev = prev.saturating_sub(1);
1677 if self.as_bytes()[prev] < 128 {
1678 return CharRange{ch: self.as_bytes()[prev] as char, next: prev}
1681 // Multibyte case is a fn to allow char_range_at_reverse to inline cleanly
1682 fn multibyte_char_range_at_reverse(s: &str, mut i: usize) -> CharRange {
1683 // while there is a previous byte == 10......
1684 while i > 0 && s.as_bytes()[i] & !CONT_MASK == TAG_CONT_U8 {
1688 let first= s.as_bytes()[i];
1689 let w = UTF8_CHAR_WIDTH[first as usize];
1692 let mut val = utf8_first_byte(first, w as u32);
1693 val = utf8_acc_cont_byte(val, s.as_bytes()[i + 1]);
1694 if w > 2 { val = utf8_acc_cont_byte(val, s.as_bytes()[i + 2]); }
1695 if w > 3 { val = utf8_acc_cont_byte(val, s.as_bytes()[i + 3]); }
1697 CharRange {ch: unsafe { char::from_u32_unchecked(val) }, next: i}
1700 multibyte_char_range_at_reverse(self, prev)
1704 fn char_at(&self, i: usize) -> char {
1705 self.char_range_at(i).ch
1709 fn char_at_reverse(&self, i: usize) -> char {
1710 self.char_range_at_reverse(i).ch
1714 fn as_bytes(&self) -> &[u8] {
1715 unsafe { mem::transmute(self) }
1718 fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1719 pat.into_searcher(self).next_match().map(|(i, _)| i)
1722 fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1723 where P::Searcher: ReverseSearcher<'a>
1725 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1728 fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1732 fn split_at(&self, mid: usize) -> (&str, &str) {
1733 // is_char_boundary checks that the index is in [0, .len()]
1734 if self.is_char_boundary(mid) {
1736 (self.slice_unchecked(0, mid),
1737 self.slice_unchecked(mid, self.len()))
1740 slice_error_fail(self, 0, mid)
1744 fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
1745 // is_char_boundary checks that the index is in [0, .len()]
1746 if self.is_char_boundary(mid) {
1747 let len = self.len();
1749 let self2: &mut str = mem::transmute_copy(&self);
1750 (self.slice_mut_unchecked(0, mid),
1751 self2.slice_mut_unchecked(mid, len))
1754 slice_error_fail(self, 0, mid)
1759 fn slice_shift_char(&self) -> Option<(char, &str)> {
1760 if self.is_empty() {
1763 let ch = self.char_at(0);
1764 let next_s = unsafe { self.slice_unchecked(ch.len_utf8(), self.len()) };
1769 fn subslice_offset(&self, inner: &str) -> usize {
1770 let a_start = self.as_ptr() as usize;
1771 let a_end = a_start + self.len();
1772 let b_start = inner.as_ptr() as usize;
1773 let b_end = b_start + inner.len();
1775 assert!(a_start <= b_start);
1776 assert!(b_end <= a_end);
1781 fn as_ptr(&self) -> *const u8 {
1786 fn len(&self) -> usize { self.repr().len }
1789 fn is_empty(&self) -> bool { self.len() == 0 }
1792 fn parse<T: FromStr>(&self) -> Result<T, T::Err> { FromStr::from_str(self) }
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 impl AsRef<[u8]> for str {
1798 fn as_ref(&self) -> &[u8] {
1803 /// Pluck a code point out of a UTF-8-like byte slice and return the
1804 /// index of the next code point.
1806 fn char_range_at_raw(bytes: &[u8], i: usize) -> (u32, usize) {
1808 return (bytes[i] as u32, i + 1);
1811 // Multibyte case is a fn to allow char_range_at to inline cleanly
1812 fn multibyte_char_range_at(bytes: &[u8], i: usize) -> (u32, usize) {
1813 let first = bytes[i];
1814 let w = UTF8_CHAR_WIDTH[first as usize];
1817 let mut val = utf8_first_byte(first, w as u32);
1818 val = utf8_acc_cont_byte(val, bytes[i + 1]);
1819 if w > 2 { val = utf8_acc_cont_byte(val, bytes[i + 2]); }
1820 if w > 3 { val = utf8_acc_cont_byte(val, bytes[i + 3]); }
1822 (val, i + w as usize)
1825 multibyte_char_range_at(bytes, i)
1828 #[stable(feature = "rust1", since = "1.0.0")]
1829 impl<'a> Default for &'a str {
1830 fn default() -> &'a str { "" }