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 #![doc(primitive = "str")]
16 #![stable(feature = "rust1", since = "1.0.0")]
18 use self::OldSearcher::{TwoWay, TwoWayLong};
19 use self::pattern::Pattern;
20 use self::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
28 use iter::ExactSizeIterator;
29 use iter::{Map, Iterator, DoubleEndedIterator};
31 use ops::{Fn, FnMut, FnOnce};
32 use option::Option::{self, None, Some};
33 use raw::{Repr, Slice};
34 use result::Result::{self, Ok, Err};
35 use slice::{self, SliceExt};
40 /// A trait to abstract the idea of creating a new instance of a type from a
42 #[stable(feature = "rust1", since = "1.0.0")]
44 /// The associated error which can be returned from parsing.
45 #[stable(feature = "rust1", since = "1.0.0")]
48 /// Parses a string `s` to return a value of this type.
50 /// If parsing succeeds, return the value inside `Ok`, otherwise
51 /// when the string is ill-formatted return an error specific to the
52 /// inside `Err`. The error type is specific to implementation of the trait.
53 #[stable(feature = "rust1", since = "1.0.0")]
54 fn from_str(s: &str) -> Result<Self, Self::Err>;
57 #[stable(feature = "rust1", since = "1.0.0")]
58 impl FromStr for bool {
59 type Err = ParseBoolError;
61 /// Parse a `bool` from a string.
63 /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
64 /// actually be parseable.
69 /// use std::str::FromStr;
71 /// assert_eq!(FromStr::from_str("true"), Ok(true));
72 /// assert_eq!(FromStr::from_str("false"), Ok(false));
73 /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
76 /// Note, in many cases, the `.parse()` method on `str` is more proper.
79 /// assert_eq!("true".parse(), Ok(true));
80 /// assert_eq!("false".parse(), Ok(false));
81 /// assert!("not even a boolean".parse::<bool>().is_err());
84 fn from_str(s: &str) -> Result<bool, ParseBoolError> {
88 _ => Err(ParseBoolError { _priv: () }),
93 /// An error returned when parsing a `bool` from a string fails.
94 #[derive(Debug, Clone, PartialEq)]
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub struct ParseBoolError { _priv: () }
98 #[stable(feature = "rust1", since = "1.0.0")]
99 impl fmt::Display for ParseBoolError {
100 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
101 "provided string was not `true` or `false`".fmt(f)
106 Section: Creating a string
109 /// Errors which can occur when attempting to interpret a byte slice as a `str`.
110 #[derive(Copy, Eq, PartialEq, Clone, Debug)]
111 #[stable(feature = "rust1", since = "1.0.0")]
112 pub struct Utf8Error {
117 /// Returns the index in the given string up to which valid UTF-8 was
120 /// Starting at the index provided, but not necessarily at it precisely, an
121 /// invalid UTF-8 encoding sequence was found.
122 #[unstable(feature = "utf8_error", reason = "method just added")]
123 pub fn valid_up_to(&self) -> usize { self.valid_up_to }
126 /// Converts a slice of bytes to a string slice without performing any
129 /// Once the slice has been validated as utf-8, it is transmuted in-place and
130 /// returned as a '&str' instead of a '&[u8]'
134 /// Returns `Err` if the slice is not utf-8 with a description as to why the
135 /// provided slice is not utf-8.
136 #[stable(feature = "rust1", since = "1.0.0")]
137 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
138 try!(run_utf8_validation_iterator(&mut v.iter()));
139 Ok(unsafe { from_utf8_unchecked(v) })
142 /// Converts a slice of bytes to a string slice without checking
143 /// that the string contains valid UTF-8.
145 #[stable(feature = "rust1", since = "1.0.0")]
146 pub unsafe fn from_utf8_unchecked<'a>(v: &'a [u8]) -> &'a str {
150 #[stable(feature = "rust1", since = "1.0.0")]
151 impl fmt::Display for Utf8Error {
152 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
153 write!(f, "invalid utf-8: invalid byte near index {}", self.valid_up_to)
161 /// Iterator for the char (representing *Unicode Scalar Values*) of a string
163 /// Created with the method `.chars()`.
165 #[stable(feature = "rust1", since = "1.0.0")]
166 pub struct Chars<'a> {
167 iter: slice::Iter<'a, u8>
170 /// Return the initial codepoint accumulator for the first byte.
171 /// The first byte is special, only want bottom 5 bits for width 2, 4 bits
172 /// for width 3, and 3 bits for width 4.
174 fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
176 /// Return the value of `ch` updated with continuation byte `byte`.
178 fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
180 /// Checks whether the byte is a UTF-8 continuation byte (i.e. starts with the
183 fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
186 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
193 /// Reads the next code point out of a byte iterator (assuming a
194 /// UTF-8-like encoding).
195 #[unstable(feature = "str_internals")]
197 pub fn next_code_point(bytes: &mut slice::Iter<u8>) -> Option<u32> {
199 let x = match bytes.next() {
201 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
202 Some(&next_byte) => next_byte,
205 // Multibyte case follows
206 // Decode from a byte combination out of: [[[x y] z] w]
207 // NOTE: Performance is sensitive to the exact formulation here
208 let init = utf8_first_byte(x, 2);
209 let y = unwrap_or_0(bytes.next());
210 let mut ch = utf8_acc_cont_byte(init, y);
213 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
214 let z = unwrap_or_0(bytes.next());
215 let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
216 ch = init << 12 | y_z;
219 // use only the lower 3 bits of `init`
220 let w = unwrap_or_0(bytes.next());
221 ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
228 /// Reads the last code point out of a byte iterator (assuming a
229 /// UTF-8-like encoding).
230 #[unstable(feature = "str_internals")]
232 pub fn next_code_point_reverse(bytes: &mut slice::Iter<u8>) -> Option<u32> {
234 let w = match bytes.next_back() {
236 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
237 Some(&back_byte) => back_byte,
240 // Multibyte case follows
241 // Decode from a byte combination out of: [x [y [z w]]]
243 let z = unwrap_or_0(bytes.next_back());
244 ch = utf8_first_byte(z, 2);
245 if utf8_is_cont_byte(z) {
246 let y = unwrap_or_0(bytes.next_back());
247 ch = utf8_first_byte(y, 3);
248 if utf8_is_cont_byte(y) {
249 let x = unwrap_or_0(bytes.next_back());
250 ch = utf8_first_byte(x, 4);
251 ch = utf8_acc_cont_byte(ch, y);
253 ch = utf8_acc_cont_byte(ch, z);
255 ch = utf8_acc_cont_byte(ch, w);
260 #[stable(feature = "rust1", since = "1.0.0")]
261 impl<'a> Iterator for Chars<'a> {
265 fn next(&mut self) -> Option<char> {
266 next_code_point(&mut self.iter).map(|ch| {
267 // str invariant says `ch` is a valid Unicode Scalar Value
275 fn size_hint(&self) -> (usize, Option<usize>) {
276 let (len, _) = self.iter.size_hint();
277 // `(len + 3)` can't overflow, because we know that the `slice::Iter`
278 // belongs to a slice in memory which has a maximum length of
279 // `isize::MAX` (that's well below `usize::MAX`).
280 ((len + 3) / 4, Some(len))
284 #[stable(feature = "rust1", since = "1.0.0")]
285 impl<'a> DoubleEndedIterator for Chars<'a> {
287 fn next_back(&mut self) -> Option<char> {
288 next_code_point_reverse(&mut self.iter).map(|ch| {
289 // str invariant says `ch` is a valid Unicode Scalar Value
297 /// Iterator for a string's characters and their byte offsets.
299 #[stable(feature = "rust1", since = "1.0.0")]
300 pub struct CharIndices<'a> {
305 #[stable(feature = "rust1", since = "1.0.0")]
306 impl<'a> Iterator for CharIndices<'a> {
307 type Item = (usize, char);
310 fn next(&mut self) -> Option<(usize, char)> {
311 let (pre_len, _) = self.iter.iter.size_hint();
312 match self.iter.next() {
315 let index = self.front_offset;
316 let (len, _) = self.iter.iter.size_hint();
317 self.front_offset += pre_len - len;
324 fn size_hint(&self) -> (usize, Option<usize>) {
325 self.iter.size_hint()
329 #[stable(feature = "rust1", since = "1.0.0")]
330 impl<'a> DoubleEndedIterator for CharIndices<'a> {
332 fn next_back(&mut self) -> Option<(usize, char)> {
333 match self.iter.next_back() {
336 let (len, _) = self.iter.iter.size_hint();
337 let index = self.front_offset + len;
344 /// External iterator for a string's bytes.
345 /// Use with the `std::iter` module.
347 /// Created with the method `.bytes()`.
348 #[stable(feature = "rust1", since = "1.0.0")]
350 pub struct Bytes<'a>(Map<slice::Iter<'a, u8>, BytesDeref>);
352 /// A nameable, clonable fn type
356 impl<'a> Fn<(&'a u8,)> for BytesDeref {
358 extern "rust-call" fn call(&self, (ptr,): (&'a u8,)) -> u8 {
363 impl<'a> FnMut<(&'a u8,)> for BytesDeref {
365 extern "rust-call" fn call_mut(&mut self, (ptr,): (&'a u8,)) -> u8 {
366 Fn::call(&*self, (ptr,))
370 impl<'a> FnOnce<(&'a u8,)> for BytesDeref {
374 extern "rust-call" fn call_once(self, (ptr,): (&'a u8,)) -> u8 {
375 Fn::call(&self, (ptr,))
379 #[stable(feature = "rust1", since = "1.0.0")]
380 impl<'a> Iterator for Bytes<'a> {
384 fn next(&mut self) -> Option<u8> {
389 fn size_hint(&self) -> (usize, Option<usize>) {
394 #[stable(feature = "rust1", since = "1.0.0")]
395 impl<'a> DoubleEndedIterator for Bytes<'a> {
397 fn next_back(&mut self) -> Option<u8> {
402 #[stable(feature = "rust1", since = "1.0.0")]
403 impl<'a> ExactSizeIterator for Bytes<'a> {
405 fn len(&self) -> usize {
410 /// This macro generates a Clone impl for string pattern API
411 /// wrapper types of the form X<'a, P>
412 macro_rules! derive_pattern_clone {
413 (clone $t:ident with |$s:ident| $e:expr) => {
414 impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
415 where P::Searcher: Clone
417 fn clone(&self) -> Self {
425 /// This macro generates two public iterator structs
426 /// wrapping an private internal one that makes use of the `Pattern` API.
428 /// For all patterns `P: Pattern<'a>` the following items will be
429 /// generated (generics omitted):
431 /// struct $forward_iterator($internal_iterator);
432 /// struct $reverse_iterator($internal_iterator);
434 /// impl Iterator for $forward_iterator
435 /// { /* internal ends up calling Searcher::next_match() */ }
437 /// impl DoubleEndedIterator for $forward_iterator
438 /// where P::Searcher: DoubleEndedSearcher
439 /// { /* internal ends up calling Searcher::next_match_back() */ }
441 /// impl Iterator for $reverse_iterator
442 /// where P::Searcher: ReverseSearcher
443 /// { /* internal ends up calling Searcher::next_match_back() */ }
445 /// impl DoubleEndedIterator for $reverse_iterator
446 /// where P::Searcher: DoubleEndedSearcher
447 /// { /* internal ends up calling Searcher::next_match() */ }
449 /// The internal one is defined outside the macro, and has almost the same
450 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
451 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
453 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
454 /// `Pattern` might not return the same elements, so actually implementing
455 /// `DoubleEndedIterator` for it would be incorrect.
456 /// (See the docs in `str::pattern` for more details)
458 /// However, the internal struct still represents a single ended iterator from
459 /// either end, and depending on pattern is also a valid double ended iterator,
460 /// so the two wrapper structs implement `Iterator`
461 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
462 /// to the complex impls seen above.
463 macro_rules! generate_pattern_iterators {
467 $(#[$forward_iterator_attribute:meta])*
468 struct $forward_iterator:ident;
472 $(#[$reverse_iterator_attribute:meta])*
473 struct $reverse_iterator:ident;
475 // Stability of all generated items
477 $(#[$common_stability_attribute:meta])*
479 // Internal almost-iterator that is being delegated to
481 $internal_iterator:ident yielding ($iterty:ty);
483 // Kind of delgation - either single ended or double ended
486 $(#[$forward_iterator_attribute])*
487 $(#[$common_stability_attribute])*
488 pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
490 $(#[$common_stability_attribute])*
491 impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
495 fn next(&mut self) -> Option<$iterty> {
500 $(#[$common_stability_attribute])*
501 impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
502 where P::Searcher: Clone
504 fn clone(&self) -> Self {
505 $forward_iterator(self.0.clone())
509 $(#[$reverse_iterator_attribute])*
510 $(#[$common_stability_attribute])*
511 pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
513 $(#[$common_stability_attribute])*
514 impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
515 where P::Searcher: ReverseSearcher<'a>
520 fn next(&mut self) -> Option<$iterty> {
525 $(#[$common_stability_attribute])*
526 impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
527 where P::Searcher: Clone
529 fn clone(&self) -> Self {
530 $reverse_iterator(self.0.clone())
534 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
536 $reverse_iterator, $iterty);
539 double ended; with $(#[$common_stability_attribute:meta])*,
540 $forward_iterator:ident,
541 $reverse_iterator:ident, $iterty:ty
543 $(#[$common_stability_attribute])*
544 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
545 where P::Searcher: DoubleEndedSearcher<'a>
548 fn next_back(&mut self) -> Option<$iterty> {
553 $(#[$common_stability_attribute])*
554 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
555 where P::Searcher: DoubleEndedSearcher<'a>
558 fn next_back(&mut self) -> Option<$iterty> {
564 single ended; with $(#[$common_stability_attribute:meta])*,
565 $forward_iterator:ident,
566 $reverse_iterator:ident, $iterty:ty
570 derive_pattern_clone!{
572 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
574 struct SplitInternal<'a, P: Pattern<'a>> {
577 matcher: P::Searcher,
578 allow_trailing_empty: bool,
582 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
584 fn get_end(&mut self) -> Option<&'a str> {
585 if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
586 self.finished = true;
588 let string = self.matcher.haystack().slice_unchecked(self.start, self.end);
597 fn next(&mut self) -> Option<&'a str> {
598 if self.finished { return None }
600 let haystack = self.matcher.haystack();
601 match self.matcher.next_match() {
602 Some((a, b)) => unsafe {
603 let elt = haystack.slice_unchecked(self.start, a);
607 None => self.get_end(),
612 fn next_back(&mut self) -> Option<&'a str>
613 where P::Searcher: ReverseSearcher<'a>
615 if self.finished { return None }
617 if !self.allow_trailing_empty {
618 self.allow_trailing_empty = true;
619 match self.next_back() {
620 Some(elt) if !elt.is_empty() => return Some(elt),
621 _ => if self.finished { return None }
625 let haystack = self.matcher.haystack();
626 match self.matcher.next_match_back() {
627 Some((a, b)) => unsafe {
628 let elt = haystack.slice_unchecked(b, self.end);
633 self.finished = true;
634 Some(haystack.slice_unchecked(self.start, self.end))
640 generate_pattern_iterators! {
642 #[doc="Created with the method `.split()`."]
645 #[doc="Created with the method `.rsplit()`."]
648 #[stable(feature = "rust1", since = "1.0.0")]
650 SplitInternal yielding (&'a str);
651 delegate double ended;
654 generate_pattern_iterators! {
656 #[doc="Created with the method `.split_terminator()`."]
657 struct SplitTerminator;
659 #[doc="Created with the method `.rsplit_terminator()`."]
660 struct RSplitTerminator;
662 #[stable(feature = "rust1", since = "1.0.0")]
664 SplitInternal yielding (&'a str);
665 delegate double ended;
668 derive_pattern_clone!{
670 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
672 struct SplitNInternal<'a, P: Pattern<'a>> {
673 iter: SplitInternal<'a, P>,
674 /// The number of splits remaining
678 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
680 fn next(&mut self) -> Option<&'a str> {
683 1 => { self.count = 0; self.iter.get_end() }
684 _ => { self.count -= 1; self.iter.next() }
689 fn next_back(&mut self) -> Option<&'a str>
690 where P::Searcher: ReverseSearcher<'a>
694 1 => { self.count = 0; self.iter.get_end() }
695 _ => { self.count -= 1; self.iter.next_back() }
700 generate_pattern_iterators! {
702 #[doc="Created with the method `.splitn()`."]
705 #[doc="Created with the method `.rsplitn()`."]
708 #[stable(feature = "rust1", since = "1.0.0")]
710 SplitNInternal yielding (&'a str);
711 delegate single ended;
714 derive_pattern_clone!{
715 clone MatchIndicesInternal
716 with |s| MatchIndicesInternal(s.0.clone())
718 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
720 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
722 fn next(&mut self) -> Option<(usize, usize)> {
727 fn next_back(&mut self) -> Option<(usize, usize)>
728 where P::Searcher: ReverseSearcher<'a>
730 self.0.next_match_back()
734 generate_pattern_iterators! {
736 #[doc="Created with the method `.match_indices()`."]
739 #[doc="Created with the method `.rmatch_indices()`."]
740 struct RMatchIndices;
742 #[unstable(feature = "str_internals",
743 reason = "type may be removed or have its iterator impl changed")]
745 MatchIndicesInternal yielding ((usize, usize));
746 delegate double ended;
749 derive_pattern_clone!{
750 clone MatchesInternal
751 with |s| MatchesInternal(s.0.clone())
753 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
755 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
757 fn next(&mut self) -> Option<&'a str> {
758 self.0.next_match().map(|(a, b)| unsafe {
759 // Indices are known to be on utf8 boundaries
760 self.0.haystack().slice_unchecked(a, b)
765 fn next_back(&mut self) -> Option<&'a str>
766 where P::Searcher: ReverseSearcher<'a>
768 self.0.next_match_back().map(|(a, b)| unsafe {
769 // Indices are known to be on utf8 boundaries
770 self.0.haystack().slice_unchecked(a, b)
775 generate_pattern_iterators! {
777 #[doc="Created with the method `.matches()`."]
780 #[doc="Created with the method `.rmatches()`."]
783 #[unstable(feature = "str_internals", reason = "type got recently added")]
785 MatchesInternal yielding (&'a str);
786 delegate double ended;
789 /// Created with the method `.lines()`.
790 #[stable(feature = "rust1", since = "1.0.0")]
792 pub struct Lines<'a>(SplitTerminator<'a, char>);
794 #[stable(feature = "rust1", since = "1.0.0")]
795 impl<'a> Iterator for Lines<'a> {
799 fn next(&mut self) -> Option<&'a str> {
804 fn size_hint(&self) -> (usize, Option<usize>) {
809 #[stable(feature = "rust1", since = "1.0.0")]
810 impl<'a> DoubleEndedIterator for Lines<'a> {
812 fn next_back(&mut self) -> Option<&'a str> {
817 /// Created with the method `.lines_any()`.
818 #[stable(feature = "rust1", since = "1.0.0")]
820 pub struct LinesAny<'a>(Map<Lines<'a>, LinesAnyMap>);
822 /// A nameable, clonable fn type
826 impl<'a> Fn<(&'a str,)> for LinesAnyMap {
828 extern "rust-call" fn call(&self, (line,): (&'a str,)) -> &'a str {
830 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
835 impl<'a> FnMut<(&'a str,)> for LinesAnyMap {
837 extern "rust-call" fn call_mut(&mut self, (line,): (&'a str,)) -> &'a str {
838 Fn::call(&*self, (line,))
842 impl<'a> FnOnce<(&'a str,)> for LinesAnyMap {
843 type Output = &'a str;
846 extern "rust-call" fn call_once(self, (line,): (&'a str,)) -> &'a str {
847 Fn::call(&self, (line,))
851 #[stable(feature = "rust1", since = "1.0.0")]
852 impl<'a> Iterator for LinesAny<'a> {
856 fn next(&mut self) -> Option<&'a str> {
861 fn size_hint(&self) -> (usize, Option<usize>) {
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl<'a> DoubleEndedIterator for LinesAny<'a> {
869 fn next_back(&mut self) -> Option<&'a str> {
874 /// The internal state of an iterator that searches for matches of a substring
875 /// within a larger string using two-way search
877 struct TwoWaySearcher {
889 This is the Two-Way search algorithm, which was introduced in the paper:
890 Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675.
892 Here's some background information.
894 A *word* is a string of symbols. The *length* of a word should be a familiar
895 notion, and here we denote it for any word x by |x|.
896 (We also allow for the possibility of the *empty word*, a word of length zero).
898 If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a
899 *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p].
900 For example, both 1 and 2 are periods for the string "aa". As another example,
901 the only period of the string "abcd" is 4.
903 We denote by period(x) the *smallest* period of x (provided that x is non-empty).
904 This is always well-defined since every non-empty word x has at least one period,
905 |x|. We sometimes call this *the period* of x.
907 If u, v and x are words such that x = uv, where uv is the concatenation of u and
908 v, then we say that (u, v) is a *factorization* of x.
910 Let (u, v) be a factorization for a word x. Then if w is a non-empty word such
911 that both of the following hold
913 - either w is a suffix of u or u is a suffix of w
914 - either w is a prefix of v or v is a prefix of w
916 then w is said to be a *repetition* for the factorization (u, v).
918 Just to unpack this, there are four possibilities here. Let w = "abc". Then we
921 - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde")
922 - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab")
923 - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi")
924 - u is a suffix of w and v is a prefix of w. ex: ("bc", "a")
926 Note that the word vu is a repetition for any factorization (u,v) of x = uv,
927 so every factorization has at least one repetition.
929 If x is a string and (u, v) is a factorization for x, then a *local period* for
930 (u, v) is an integer r such that there is some word w such that |w| = r and w is
931 a repetition for (u, v).
933 We denote by local_period(u, v) the smallest local period of (u, v). We sometimes
934 call this *the local period* of (u, v). Provided that x = uv is non-empty, this
935 is well-defined (because each non-empty word has at least one factorization, as
938 It can be proven that the following is an equivalent definition of a local period
939 for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
940 all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
941 defined. (i.e. i > 0 and i + r < |x|).
943 Using the above reformulation, it is easy to prove that
945 1 <= local_period(u, v) <= period(uv)
947 A factorization (u, v) of x such that local_period(u,v) = period(x) is called a
948 *critical factorization*.
950 The algorithm hinges on the following theorem, which is stated without proof:
952 **Critical Factorization Theorem** Any word x has at least one critical
953 factorization (u, v) such that |u| < period(x).
955 The purpose of maximal_suffix is to find such a critical factorization.
958 impl TwoWaySearcher {
960 fn new(needle: &[u8]) -> TwoWaySearcher {
961 let (crit_pos_false, period_false) = TwoWaySearcher::maximal_suffix(needle, false);
962 let (crit_pos_true, period_true) = TwoWaySearcher::maximal_suffix(needle, true);
964 let (crit_pos, period) =
965 if crit_pos_false > crit_pos_true {
966 (crit_pos_false, period_false)
968 (crit_pos_true, period_true)
971 // This isn't in the original algorithm, as far as I'm aware.
972 let byteset = needle.iter()
973 .fold(0, |a, &b| (1 << ((b & 0x3f) as usize)) | a);
975 // A particularly readable explanation of what's going on here can be found
976 // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically
977 // see the code for "Algorithm CP" on p. 323.
979 // What's going on is we have some critical factorization (u, v) of the
980 // needle, and we want to determine whether u is a suffix of
981 // &v[..period]. If it is, we use "Algorithm CP1". Otherwise we use
982 // "Algorithm CP2", which is optimized for when the period of the needle
984 if &needle[..crit_pos] == &needle[period.. period + crit_pos] {
996 period: cmp::max(crit_pos, needle.len() - crit_pos) + 1,
1000 memory: usize::MAX // Dummy value to signify that the period is long
1005 // One of the main ideas of Two-Way is that we factorize the needle into
1006 // two halves, (u, v), and begin trying to find v in the haystack by scanning
1007 // left to right. If v matches, we try to match u by scanning right to left.
1008 // How far we can jump when we encounter a mismatch is all based on the fact
1009 // that (u, v) is a critical factorization for the needle.
1011 fn next(&mut self, haystack: &[u8], needle: &[u8], long_period: bool)
1012 -> Option<(usize, usize)> {
1014 // Check that we have room to search in
1015 if self.position + needle.len() > haystack.len() {
1019 // Quickly skip by large portions unrelated to our substring
1021 ((haystack[self.position + needle.len() - 1] & 0x3f)
1022 as usize)) & 1 == 0 {
1023 self.position += needle.len();
1030 // See if the right part of the needle matches
1031 let start = if long_period { self.crit_pos }
1032 else { cmp::max(self.crit_pos, self.memory) };
1033 for i in start..needle.len() {
1034 if needle[i] != haystack[self.position + i] {
1035 self.position += i - self.crit_pos + 1;
1043 // See if the left part of the needle matches
1044 let start = if long_period { 0 } else { self.memory };
1045 for i in (start..self.crit_pos).rev() {
1046 if needle[i] != haystack[self.position + i] {
1047 self.position += self.period;
1049 self.memory = needle.len() - self.period;
1055 // We have found a match!
1056 let match_pos = self.position;
1057 self.position += needle.len(); // add self.period for all matches
1059 self.memory = 0; // set to needle.len() - self.period for all matches
1061 return Some((match_pos, match_pos + needle.len()));
1065 // Computes a critical factorization (u, v) of `arr`.
1066 // Specifically, returns (i, p), where i is the starting index of v in some
1067 // critical factorization (u, v) and p = period(v)
1070 #[allow(deprecated)]
1071 fn maximal_suffix(arr: &[u8], reversed: bool) -> (usize, usize) {
1072 let mut left: usize = !0; // Corresponds to i in the paper
1073 let mut right = 0; // Corresponds to j in the paper
1074 let mut offset = 1; // Corresponds to k in the paper
1075 let mut period = 1; // Corresponds to p in the paper
1077 while right + offset < arr.len() {
1081 a = arr[left.wrapping_add(offset)];
1082 b = arr[right + offset];
1084 a = arr[right + offset];
1085 b = arr[left.wrapping_add(offset)];
1088 // Suffix is smaller, period is entire prefix so far.
1091 period = right.wrapping_sub(left);
1093 // Advance through repetition of the current period.
1094 if offset == period {
1101 // Suffix is larger, start over from current location.
1108 (left.wrapping_add(1), period)
1112 /// The internal state of an iterator that searches for matches of a substring
1113 /// within a larger string using a dynamically chosen search algorithm
1115 // NB: This is kept around for convenience because
1116 // it is planned to be used again in the future
1118 TwoWay(TwoWaySearcher),
1119 TwoWayLong(TwoWaySearcher),
1124 fn new(haystack: &[u8], needle: &[u8]) -> OldSearcher {
1125 if needle.is_empty() {
1128 // FIXME: Tune this.
1129 // FIXME(#16715): This unsigned integer addition will probably not
1130 // overflow because that would mean that the memory almost solely
1131 // consists of the needle. Needs #16715 to be formally fixed.
1132 } else if needle.len() + 20 > haystack.len() {
1133 // Use naive searcher
1136 let searcher = TwoWaySearcher::new(needle);
1137 if searcher.memory == usize::MAX { // If the period is long
1138 TwoWayLong(searcher)
1147 // NB: This is kept around for convenience because
1148 // it is planned to be used again in the future
1149 struct OldMatchIndices<'a, 'b> {
1153 searcher: OldSearcher
1156 impl<'a, 'b> OldMatchIndices<'a, 'b> {
1159 fn next(&mut self) -> Option<(usize, usize)> {
1160 match self.searcher {
1161 TwoWay(ref mut searcher)
1162 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes(), false),
1163 TwoWayLong(ref mut searcher)
1164 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes(), true),
1170 Section: Comparing strings
1173 // share the implementation of the lang-item vs. non-lang-item
1175 /// NOTE: This function is (ab)used in rustc::middle::trans::_match
1176 /// to compare &[u8] byte slices that are not necessarily valid UTF-8.
1178 fn eq_slice_(a: &str, b: &str) -> bool {
1179 // NOTE: In theory n should be libc::size_t and not usize, but libc is not available here
1180 #[allow(improper_ctypes)]
1181 extern { fn memcmp(s1: *const i8, s2: *const i8, n: usize) -> i32; }
1182 a.len() == b.len() && unsafe {
1183 memcmp(a.as_ptr() as *const i8,
1184 b.as_ptr() as *const i8,
1189 /// Bytewise slice equality
1190 /// NOTE: This function is (ab)used in rustc::middle::trans::_match
1191 /// to compare &[u8] byte slices that are not necessarily valid UTF-8.
1194 fn eq_slice(a: &str, b: &str) -> bool {
1202 /// Walk through `iter` checking that it's a valid UTF-8 sequence,
1203 /// returning `true` in that case, or, if it is invalid, `false` with
1204 /// `iter` reset such that it is pointing at the first byte in the
1205 /// invalid sequence.
1207 fn run_utf8_validation_iterator(iter: &mut slice::Iter<u8>)
1208 -> Result<(), Utf8Error> {
1209 let whole = iter.as_slice();
1211 // save the current thing we're pointing at.
1212 let old = iter.clone();
1214 // restore the iterator we had at the start of this codepoint.
1215 macro_rules! err { () => {{
1216 *iter = old.clone();
1217 return Err(Utf8Error {
1218 valid_up_to: whole.len() - iter.as_slice().len()
1222 macro_rules! next { () => {
1225 // we needed data, but there was none: error!
1230 let first = match iter.next() {
1232 // we're at the end of the iterator and a codepoint
1233 // boundary at the same time, so this string is valid.
1234 None => return Ok(())
1237 // ASCII characters are always valid, so only large
1238 // bytes need more examination.
1240 let w = UTF8_CHAR_WIDTH[first as usize];
1241 let second = next!();
1242 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
1243 // first C2 80 last DF BF
1244 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
1245 // first E0 A0 80 last EF BF BF
1246 // excluding surrogates codepoints \u{d800} to \u{dfff}
1247 // ED A0 80 to ED BF BF
1248 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1249 // first F0 90 80 80 last F4 8F BF BF
1251 // Use the UTF-8 syntax from the RFC
1253 // https://tools.ietf.org/html/rfc3629
1255 // UTF8-2 = %xC2-DF UTF8-tail
1256 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1257 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1258 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1259 // %xF4 %x80-8F 2( UTF8-tail )
1261 2 => if second & !CONT_MASK != TAG_CONT_U8 {err!()},
1263 match (first, second, next!() & !CONT_MASK) {
1264 (0xE0 , 0xA0 ... 0xBF, TAG_CONT_U8) |
1265 (0xE1 ... 0xEC, 0x80 ... 0xBF, TAG_CONT_U8) |
1266 (0xED , 0x80 ... 0x9F, TAG_CONT_U8) |
1267 (0xEE ... 0xEF, 0x80 ... 0xBF, TAG_CONT_U8) => {}
1272 match (first, second, next!() & !CONT_MASK, next!() & !CONT_MASK) {
1273 (0xF0 , 0x90 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
1274 (0xF1 ... 0xF3, 0x80 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
1275 (0xF4 , 0x80 ... 0x8F, TAG_CONT_U8, TAG_CONT_U8) => {}
1285 // https://tools.ietf.org/html/rfc3629
1286 static UTF8_CHAR_WIDTH: [u8; 256] = [
1287 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1288 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1289 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1290 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1291 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1292 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1293 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1294 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1295 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1296 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1297 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1298 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1299 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1300 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1301 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1302 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1305 /// Struct that contains a `char` and the index of the first byte of
1306 /// the next `char` in a string. This can be used as a data structure
1307 /// for iterating over the UTF-8 bytes of a string.
1308 #[derive(Copy, Clone)]
1309 #[unstable(feature = "str_char",
1310 reason = "existence of this struct is uncertain as it is frequently \
1311 able to be replaced with char.len_utf8() and/or \
1312 char/char_indices iterators")]
1313 pub struct CharRange {
1316 /// Index of the first byte of the next `char`
1320 /// Mask of the value bits of a continuation byte
1321 const CONT_MASK: u8 = 0b0011_1111;
1322 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte
1323 const TAG_CONT_U8: u8 = 0b1000_0000;
1326 Section: Trait implementations
1330 use cmp::{Ordering, Ord, PartialEq, PartialOrd, Eq};
1331 use cmp::Ordering::{Less, Equal, Greater};
1334 use option::Option::Some;
1336 use str::{StrExt, eq_slice};
1338 #[stable(feature = "rust1", since = "1.0.0")]
1341 fn cmp(&self, other: &str) -> Ordering {
1342 for (s_b, o_b) in self.bytes().zip(other.bytes()) {
1343 match s_b.cmp(&o_b) {
1344 Greater => return Greater,
1345 Less => return Less,
1350 self.len().cmp(&other.len())
1354 #[stable(feature = "rust1", since = "1.0.0")]
1355 impl PartialEq for str {
1357 fn eq(&self, other: &str) -> bool {
1358 eq_slice(self, other)
1361 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1364 #[stable(feature = "rust1", since = "1.0.0")]
1367 #[stable(feature = "rust1", since = "1.0.0")]
1368 impl PartialOrd for str {
1370 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1371 Some(self.cmp(other))
1375 /// Returns a slice of the given string from the byte range
1376 /// [`begin`..`end`).
1378 /// This operation is `O(1)`.
1380 /// Panics when `begin` and `end` do not point to valid characters
1381 /// or point beyond the last character of the string.
1386 /// let s = "Löwe 老虎 Léopard";
1387 /// assert_eq!(&s[0 .. 1], "L");
1389 /// assert_eq!(&s[1 .. 9], "öwe 老");
1391 /// // these will panic:
1392 /// // byte 2 lies within `ö`:
1395 /// // byte 8 lies within `老`
1398 /// // byte 100 is outside the string
1399 /// // &s[3 .. 100];
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 impl ops::Index<ops::Range<usize>> for str {
1405 fn index(&self, index: ops::Range<usize>) -> &str {
1406 // is_char_boundary checks that the index is in [0, .len()]
1407 if index.start <= index.end &&
1408 self.is_char_boundary(index.start) &&
1409 self.is_char_boundary(index.end) {
1410 unsafe { self.slice_unchecked(index.start, index.end) }
1412 super::slice_error_fail(self, index.start, index.end)
1417 /// Returns a slice of the string from the beginning to byte
1420 /// Equivalent to `self[0 .. end]`.
1422 /// Panics when `end` does not point to a valid character, or is
1424 #[stable(feature = "rust1", since = "1.0.0")]
1425 impl ops::Index<ops::RangeTo<usize>> for str {
1429 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1430 // is_char_boundary checks that the index is in [0, .len()]
1431 if self.is_char_boundary(index.end) {
1432 unsafe { self.slice_unchecked(0, index.end) }
1434 super::slice_error_fail(self, 0, index.end)
1439 /// Returns a slice of the string from `begin` to its end.
1441 /// Equivalent to `self[begin .. self.len()]`.
1443 /// Panics when `begin` does not point to a valid character, or is
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 impl ops::Index<ops::RangeFrom<usize>> for str {
1450 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1451 // is_char_boundary checks that the index is in [0, .len()]
1452 if self.is_char_boundary(index.start) {
1453 unsafe { self.slice_unchecked(index.start, self.len()) }
1455 super::slice_error_fail(self, index.start, self.len())
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 impl ops::Index<ops::RangeFull> for str {
1465 fn index(&self, _index: ops::RangeFull) -> &str {
1471 /// Methods for string slices
1472 #[allow(missing_docs)]
1474 #[unstable(feature = "core_str_ext",
1475 reason = "stable interface provided by `impl str` in later crates")]
1477 // NB there are no docs here are they're all located on the StrExt trait in
1478 // libcollections, not here.
1480 fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
1481 fn contains_char<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
1482 fn chars<'a>(&'a self) -> Chars<'a>;
1483 fn bytes<'a>(&'a self) -> Bytes<'a>;
1484 fn char_indices<'a>(&'a self) -> CharIndices<'a>;
1485 fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P>;
1486 fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1487 where P::Searcher: ReverseSearcher<'a>;
1488 fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P>;
1489 fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
1490 where P::Searcher: ReverseSearcher<'a>;
1491 fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P>;
1492 fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1493 where P::Searcher: ReverseSearcher<'a>;
1494 fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P>;
1495 fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1496 where P::Searcher: ReverseSearcher<'a>;
1497 fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P>;
1498 fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1499 where P::Searcher: ReverseSearcher<'a>;
1500 fn lines<'a>(&'a self) -> Lines<'a>;
1501 fn lines_any<'a>(&'a self) -> LinesAny<'a>;
1502 fn char_len(&self) -> usize;
1503 fn slice_chars<'a>(&'a self, begin: usize, end: usize) -> &'a str;
1504 unsafe fn slice_unchecked<'a>(&'a self, begin: usize, end: usize) -> &'a str;
1505 fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
1506 fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
1507 where P::Searcher: ReverseSearcher<'a>;
1508 fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1509 where P::Searcher: DoubleEndedSearcher<'a>;
1510 fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str;
1511 fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1512 where P::Searcher: ReverseSearcher<'a>;
1513 fn is_char_boundary(&self, index: usize) -> bool;
1514 fn char_range_at(&self, start: usize) -> CharRange;
1515 fn char_range_at_reverse(&self, start: usize) -> CharRange;
1516 fn char_at(&self, i: usize) -> char;
1517 fn char_at_reverse(&self, i: usize) -> char;
1518 fn as_bytes<'a>(&'a self) -> &'a [u8];
1519 fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
1520 fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1521 where P::Searcher: ReverseSearcher<'a>;
1522 fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
1523 fn split_at(&self, mid: usize) -> (&str, &str);
1524 fn slice_shift_char<'a>(&'a self) -> Option<(char, &'a str)>;
1525 fn subslice_offset(&self, inner: &str) -> usize;
1526 fn as_ptr(&self) -> *const u8;
1527 fn len(&self) -> usize;
1528 fn is_empty(&self) -> bool;
1529 fn parse<T: FromStr>(&self) -> Result<T, T::Err>;
1533 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
1534 assert!(begin <= end);
1535 panic!("index {} and/or {} in `{}` do not lie on character boundary",
1539 impl StrExt for str {
1541 fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1542 pat.is_contained_in(self)
1546 fn contains_char<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1547 pat.is_contained_in(self)
1551 fn chars(&self) -> Chars {
1552 Chars{iter: self.as_bytes().iter()}
1556 fn bytes(&self) -> Bytes {
1557 Bytes(self.as_bytes().iter().map(BytesDeref))
1561 fn char_indices(&self) -> CharIndices {
1562 CharIndices { front_offset: 0, iter: self.chars() }
1566 fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1567 Split(SplitInternal {
1570 matcher: pat.into_searcher(self),
1571 allow_trailing_empty: true,
1577 fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1578 where P::Searcher: ReverseSearcher<'a>
1580 RSplit(self.split(pat).0)
1584 fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
1585 SplitN(SplitNInternal {
1586 iter: self.split(pat).0,
1592 fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
1593 where P::Searcher: ReverseSearcher<'a>
1595 RSplitN(self.splitn(count, pat).0)
1599 fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1600 SplitTerminator(SplitInternal {
1601 allow_trailing_empty: false,
1607 fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1608 where P::Searcher: ReverseSearcher<'a>
1610 RSplitTerminator(self.split_terminator(pat).0)
1614 fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1615 Matches(MatchesInternal(pat.into_searcher(self)))
1619 fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1620 where P::Searcher: ReverseSearcher<'a>
1622 RMatches(self.matches(pat).0)
1626 fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1627 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
1631 fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1632 where P::Searcher: ReverseSearcher<'a>
1634 RMatchIndices(self.match_indices(pat).0)
1637 fn lines(&self) -> Lines {
1638 Lines(self.split_terminator('\n'))
1642 fn lines_any(&self) -> LinesAny {
1643 LinesAny(self.lines().map(LinesAnyMap))
1647 fn char_len(&self) -> usize { self.chars().count() }
1649 fn slice_chars(&self, begin: usize, end: usize) -> &str {
1650 assert!(begin <= end);
1652 let mut begin_byte = None;
1653 let mut end_byte = None;
1655 // This could be even more efficient by not decoding,
1656 // only finding the char boundaries
1657 for (idx, _) in self.char_indices() {
1658 if count == begin { begin_byte = Some(idx); }
1659 if count == end { end_byte = Some(idx); break; }
1662 if begin_byte.is_none() && count == begin { begin_byte = Some(self.len()) }
1663 if end_byte.is_none() && count == end { end_byte = Some(self.len()) }
1665 match (begin_byte, end_byte) {
1666 (None, _) => panic!("slice_chars: `begin` is beyond end of string"),
1667 (_, None) => panic!("slice_chars: `end` is beyond end of string"),
1668 (Some(a), Some(b)) => unsafe { self.slice_unchecked(a, b) }
1673 unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
1674 mem::transmute(Slice {
1675 data: self.as_ptr().offset(begin as isize),
1681 fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1682 pat.is_prefix_of(self)
1686 fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
1687 where P::Searcher: ReverseSearcher<'a>
1689 pat.is_suffix_of(self)
1693 fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1694 where P::Searcher: DoubleEndedSearcher<'a>
1698 let mut matcher = pat.into_searcher(self);
1699 if let Some((a, b)) = matcher.next_reject() {
1701 j = b; // Rember earliest known match, correct it below if
1702 // last match is different
1704 if let Some((_, b)) = matcher.next_reject_back() {
1708 // Searcher is known to return valid indices
1709 self.slice_unchecked(i, j)
1714 fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1715 let mut i = self.len();
1716 let mut matcher = pat.into_searcher(self);
1717 if let Some((a, _)) = matcher.next_reject() {
1721 // Searcher is known to return valid indices
1722 self.slice_unchecked(i, self.len())
1727 fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1728 where P::Searcher: ReverseSearcher<'a>
1731 let mut matcher = pat.into_searcher(self);
1732 if let Some((_, b)) = matcher.next_reject_back() {
1736 // Searcher is known to return valid indices
1737 self.slice_unchecked(0, j)
1742 fn is_char_boundary(&self, index: usize) -> bool {
1743 if index == self.len() { return true; }
1744 match self.as_bytes().get(index) {
1746 Some(&b) => b < 128 || b >= 192,
1751 fn char_range_at(&self, i: usize) -> CharRange {
1752 let (c, n) = char_range_at_raw(self.as_bytes(), i);
1753 CharRange { ch: unsafe { mem::transmute(c) }, next: n }
1757 fn char_range_at_reverse(&self, start: usize) -> CharRange {
1758 let mut prev = start;
1760 prev = prev.saturating_sub(1);
1761 if self.as_bytes()[prev] < 128 {
1762 return CharRange{ch: self.as_bytes()[prev] as char, next: prev}
1765 // Multibyte case is a fn to allow char_range_at_reverse to inline cleanly
1766 fn multibyte_char_range_at_reverse(s: &str, mut i: usize) -> CharRange {
1767 // while there is a previous byte == 10......
1768 while i > 0 && s.as_bytes()[i] & !CONT_MASK == TAG_CONT_U8 {
1772 let first= s.as_bytes()[i];
1773 let w = UTF8_CHAR_WIDTH[first as usize];
1776 let mut val = utf8_first_byte(first, w as u32);
1777 val = utf8_acc_cont_byte(val, s.as_bytes()[i + 1]);
1778 if w > 2 { val = utf8_acc_cont_byte(val, s.as_bytes()[i + 2]); }
1779 if w > 3 { val = utf8_acc_cont_byte(val, s.as_bytes()[i + 3]); }
1781 return CharRange {ch: unsafe { mem::transmute(val) }, next: i};
1784 return multibyte_char_range_at_reverse(self, prev);
1788 fn char_at(&self, i: usize) -> char {
1789 self.char_range_at(i).ch
1793 fn char_at_reverse(&self, i: usize) -> char {
1794 self.char_range_at_reverse(i).ch
1798 fn as_bytes(&self) -> &[u8] {
1799 unsafe { mem::transmute(self) }
1802 fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1803 pat.into_searcher(self).next_match().map(|(i, _)| i)
1806 fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1807 where P::Searcher: ReverseSearcher<'a>
1809 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1812 fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1816 fn split_at(&self, mid: usize) -> (&str, &str) {
1817 // is_char_boundary checks that the index is in [0, .len()]
1818 if self.is_char_boundary(mid) {
1820 (self.slice_unchecked(0, mid),
1821 self.slice_unchecked(mid, self.len()))
1824 slice_error_fail(self, 0, mid)
1829 fn slice_shift_char(&self) -> Option<(char, &str)> {
1830 if self.is_empty() {
1833 let ch = self.char_at(0);
1834 let next_s = unsafe { self.slice_unchecked(ch.len_utf8(), self.len()) };
1839 fn subslice_offset(&self, inner: &str) -> usize {
1840 let a_start = self.as_ptr() as usize;
1841 let a_end = a_start + self.len();
1842 let b_start = inner.as_ptr() as usize;
1843 let b_end = b_start + inner.len();
1845 assert!(a_start <= b_start);
1846 assert!(b_end <= a_end);
1851 fn as_ptr(&self) -> *const u8 {
1856 fn len(&self) -> usize { self.repr().len }
1859 fn is_empty(&self) -> bool { self.len() == 0 }
1862 fn parse<T: FromStr>(&self) -> Result<T, T::Err> { FromStr::from_str(self) }
1865 #[stable(feature = "rust1", since = "1.0.0")]
1866 impl AsRef<[u8]> for str {
1868 fn as_ref(&self) -> &[u8] {
1873 /// Pluck a code point out of a UTF-8-like byte slice and return the
1874 /// index of the next code point.
1876 #[unstable(feature = "str_internals")]
1877 pub fn char_range_at_raw(bytes: &[u8], i: usize) -> (u32, usize) {
1879 return (bytes[i] as u32, i + 1);
1882 // Multibyte case is a fn to allow char_range_at to inline cleanly
1883 fn multibyte_char_range_at(bytes: &[u8], i: usize) -> (u32, usize) {
1884 let first = bytes[i];
1885 let w = UTF8_CHAR_WIDTH[first as usize];
1888 let mut val = utf8_first_byte(first, w as u32);
1889 val = utf8_acc_cont_byte(val, bytes[i + 1]);
1890 if w > 2 { val = utf8_acc_cont_byte(val, bytes[i + 2]); }
1891 if w > 3 { val = utf8_acc_cont_byte(val, bytes[i + 3]); }
1893 return (val, i + w as usize);
1896 multibyte_char_range_at(bytes, i)
1899 #[stable(feature = "rust1", since = "1.0.0")]
1900 impl<'a> Default for &'a str {
1901 #[stable(feature = "rust1", since = "1.0.0")]
1902 fn default() -> &'a str { "" }