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};
25 use iter::ExactSizeIterator;
26 use iter::{Map, Cloned, Iterator, DoubleEndedIterator};
29 use ops::{Fn, FnMut, FnOnce};
30 use option::Option::{self, None, Some};
31 use result::Result::{self, Ok, Err};
32 use slice::{self, SliceExt};
36 /// A trait to abstract the idea of creating a new instance of a type from a
39 /// `FromStr`'s [`from_str()`] method is often used implicitly, through
40 /// [`str`]'s [`parse()`] method. See [`parse()`]'s documentation for examples.
42 /// [`from_str()`]: #tymethod.from_str
43 /// [`str`]: ../../std/primitive.str.html
44 /// [`parse()`]: ../../std/primitive.str.html#method.parse
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub trait FromStr: Sized {
47 /// The associated error which can be returned from parsing.
48 #[stable(feature = "rust1", since = "1.0.0")]
51 /// Parses a string `s` to return a value of this type.
53 /// If parsing succeeds, return the value inside `Ok`, otherwise
54 /// when the string is ill-formatted return an error specific to the
55 /// inside `Err`. The error type is specific to implementation of the trait.
59 /// Basic usage with [`i32`][ithirtytwo], a type that implements `FromStr`:
61 /// [ithirtytwo]: ../../std/primitive.i32.html
64 /// use std::str::FromStr;
67 /// let x = i32::from_str(s).unwrap();
71 #[stable(feature = "rust1", since = "1.0.0")]
72 fn from_str(s: &str) -> Result<Self, Self::Err>;
75 #[stable(feature = "rust1", since = "1.0.0")]
76 impl FromStr for bool {
77 type Err = ParseBoolError;
79 /// Parse a `bool` from a string.
81 /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
82 /// actually be parseable.
87 /// use std::str::FromStr;
89 /// assert_eq!(FromStr::from_str("true"), Ok(true));
90 /// assert_eq!(FromStr::from_str("false"), Ok(false));
91 /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
94 /// Note, in many cases, the `.parse()` method on `str` is more proper.
97 /// assert_eq!("true".parse(), Ok(true));
98 /// assert_eq!("false".parse(), Ok(false));
99 /// assert!("not even a boolean".parse::<bool>().is_err());
102 fn from_str(s: &str) -> Result<bool, ParseBoolError> {
105 "false" => Ok(false),
106 _ => Err(ParseBoolError { _priv: () }),
111 /// An error returned when parsing a `bool` from a string fails.
112 #[derive(Debug, Clone, PartialEq)]
113 #[stable(feature = "rust1", since = "1.0.0")]
114 pub struct ParseBoolError { _priv: () }
116 #[stable(feature = "rust1", since = "1.0.0")]
117 impl fmt::Display for ParseBoolError {
118 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
119 "provided string was not `true` or `false`".fmt(f)
124 Section: Creating a string
127 /// Errors which can occur when attempting to interpret a sequence of `u8`
130 /// As such, the `from_utf8` family of functions and methods for both `String`s
131 /// and `&str`s make use of this error, for example.
132 #[derive(Copy, Eq, PartialEq, Clone, Debug)]
133 #[stable(feature = "rust1", since = "1.0.0")]
134 pub struct Utf8Error {
139 /// Returns the index in the given string up to which valid UTF-8 was
142 /// It is the maximum index such that `from_utf8(input[..index])`
143 /// would return `Some(_)`.
152 /// // some invalid bytes, in a vector
153 /// let sparkle_heart = vec![0, 159, 146, 150];
155 /// // std::str::from_utf8 returns a Utf8Error
156 /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
158 /// // the second byte is invalid here
159 /// assert_eq!(1, error.valid_up_to());
161 #[stable(feature = "utf8_error", since = "1.5.0")]
162 pub fn valid_up_to(&self) -> usize { self.valid_up_to }
165 /// Converts a slice of bytes to a string slice.
167 /// A string slice (`&str`) is made of bytes (`u8`), and a byte slice (`&[u8]`)
168 /// is made of bytes, so this function converts between the two. Not all byte
169 /// slices are valid string slices, however: `&str` requires that it is valid
170 /// UTF-8. `from_utf8()` checks to ensure that the bytes are valid UTF-8, and
171 /// then does the conversion.
173 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
174 /// incur the overhead of the validity check, there is an unsafe version of
175 /// this function, [`from_utf8_unchecked()`][fromutf8u], which has the same
176 /// behavior but skips the check.
178 /// [fromutf8u]: fn.from_utf8_unchecked.html
180 /// If you need a `String` instead of a `&str`, consider
181 /// [`String::from_utf8()`][string].
183 /// [string]: ../../std/string/struct.String.html#method.from_utf8
185 /// Because you can stack-allocate a `[u8; N]`, and you can take a `&[u8]` of
186 /// it, this function is one way to have a stack-allocated string. There is
187 /// an example of this in the examples section below.
191 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
192 /// provided slice is not UTF-8.
201 /// // some bytes, in a vector
202 /// let sparkle_heart = vec![240, 159, 146, 150];
204 /// // We know these bytes are valid, so just use `unwrap()`.
205 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
207 /// assert_eq!("💖", sparkle_heart);
215 /// // some invalid bytes, in a vector
216 /// let sparkle_heart = vec![0, 159, 146, 150];
218 /// assert!(str::from_utf8(&sparkle_heart).is_err());
221 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
222 /// errors that can be returned.
224 /// [error]: struct.Utf8Error.html
226 /// A "stack allocated string":
231 /// // some bytes, in a stack-allocated array
232 /// let sparkle_heart = [240, 159, 146, 150];
234 /// // We know these bytes are valid, so just use `unwrap()`.
235 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
237 /// assert_eq!("💖", sparkle_heart);
239 #[stable(feature = "rust1", since = "1.0.0")]
240 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
241 run_utf8_validation(v)?;
242 Ok(unsafe { from_utf8_unchecked(v) })
245 /// Forms a str from a pointer and a length.
247 /// The `len` argument is the number of bytes in the string.
251 /// This function is unsafe as there is no guarantee that the given pointer is
252 /// valid for `len` bytes, nor whether the lifetime inferred is a suitable
253 /// lifetime for the returned str.
255 /// The data must be valid UTF-8
257 /// `p` must be non-null, even for zero-length str.
261 /// The lifetime for the returned str is inferred from its usage. To
262 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
263 /// source lifetime is safe in the context, such as by providing a helper
264 /// function taking the lifetime of a host value for the str, or by explicit
266 /// Performs the same functionality as `from_raw_parts`, except that a mutable
269 unsafe fn from_raw_parts_mut<'a>(p: *mut u8, len: usize) -> &'a mut str {
270 mem::transmute::<&mut [u8], &mut str>(slice::from_raw_parts_mut(p, len))
273 /// Converts a slice of bytes to a string slice without checking
274 /// that the string contains valid UTF-8.
276 /// See the safe version, [`from_utf8()`][fromutf8], for more information.
278 /// [fromutf8]: fn.from_utf8.html
282 /// This function is unsafe because it does not check that the bytes passed to
283 /// it are valid UTF-8. If this constraint is violated, undefined behavior
284 /// results, as the rest of Rust assumes that `&str`s are valid UTF-8.
293 /// // some bytes, in a vector
294 /// let sparkle_heart = vec![240, 159, 146, 150];
296 /// let sparkle_heart = unsafe {
297 /// str::from_utf8_unchecked(&sparkle_heart)
300 /// assert_eq!("💖", sparkle_heart);
303 #[stable(feature = "rust1", since = "1.0.0")]
304 pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
308 #[stable(feature = "rust1", since = "1.0.0")]
309 impl fmt::Display for Utf8Error {
310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
311 write!(f, "invalid utf-8: invalid byte near index {}", self.valid_up_to)
319 /// Iterator for the char (representing *Unicode Scalar Values*) of a string
321 /// Created with the method [`chars()`].
323 /// [`chars()`]: ../../std/primitive.str.html#method.chars
324 #[derive(Clone, Debug)]
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub struct Chars<'a> {
327 iter: slice::Iter<'a, u8>
330 /// Return the initial codepoint accumulator for the first byte.
331 /// The first byte is special, only want bottom 5 bits for width 2, 4 bits
332 /// for width 3, and 3 bits for width 4.
334 fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
336 /// Return the value of `ch` updated with continuation byte `byte`.
338 fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
340 /// Checks whether the byte is a UTF-8 continuation byte (i.e. starts with the
343 fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
346 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
353 /// Reads the next code point out of a byte iterator (assuming a
354 /// UTF-8-like encoding).
355 #[unstable(feature = "str_internals", issue = "0")]
357 pub fn next_code_point(bytes: &mut slice::Iter<u8>) -> Option<u32> {
359 let x = match bytes.next() {
361 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
362 Some(&next_byte) => next_byte,
365 // Multibyte case follows
366 // Decode from a byte combination out of: [[[x y] z] w]
367 // NOTE: Performance is sensitive to the exact formulation here
368 let init = utf8_first_byte(x, 2);
369 let y = unwrap_or_0(bytes.next());
370 let mut ch = utf8_acc_cont_byte(init, y);
373 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
374 let z = unwrap_or_0(bytes.next());
375 let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
376 ch = init << 12 | y_z;
379 // use only the lower 3 bits of `init`
380 let w = unwrap_or_0(bytes.next());
381 ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
388 /// Reads the last code point out of a byte iterator (assuming a
389 /// UTF-8-like encoding).
391 fn next_code_point_reverse(bytes: &mut slice::Iter<u8>) -> Option<u32> {
393 let w = match bytes.next_back() {
395 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
396 Some(&back_byte) => back_byte,
399 // Multibyte case follows
400 // Decode from a byte combination out of: [x [y [z w]]]
402 let z = unwrap_or_0(bytes.next_back());
403 ch = utf8_first_byte(z, 2);
404 if utf8_is_cont_byte(z) {
405 let y = unwrap_or_0(bytes.next_back());
406 ch = utf8_first_byte(y, 3);
407 if utf8_is_cont_byte(y) {
408 let x = unwrap_or_0(bytes.next_back());
409 ch = utf8_first_byte(x, 4);
410 ch = utf8_acc_cont_byte(ch, y);
412 ch = utf8_acc_cont_byte(ch, z);
414 ch = utf8_acc_cont_byte(ch, w);
419 #[stable(feature = "rust1", since = "1.0.0")]
420 impl<'a> Iterator for Chars<'a> {
424 fn next(&mut self) -> Option<char> {
425 next_code_point(&mut self.iter).map(|ch| {
426 // str invariant says `ch` is a valid Unicode Scalar Value
428 char::from_u32_unchecked(ch)
434 fn size_hint(&self) -> (usize, Option<usize>) {
435 let (len, _) = self.iter.size_hint();
436 // `(len + 3)` can't overflow, because we know that the `slice::Iter`
437 // belongs to a slice in memory which has a maximum length of
438 // `isize::MAX` (that's well below `usize::MAX`).
439 ((len + 3) / 4, Some(len))
443 #[stable(feature = "rust1", since = "1.0.0")]
444 impl<'a> DoubleEndedIterator for Chars<'a> {
446 fn next_back(&mut self) -> Option<char> {
447 next_code_point_reverse(&mut self.iter).map(|ch| {
448 // str invariant says `ch` is a valid Unicode Scalar Value
450 char::from_u32_unchecked(ch)
457 /// View the underlying data as a subslice of the original data.
459 /// This has the same lifetime as the original slice, and so the
460 /// iterator can continue to be used while this exists.
461 #[stable(feature = "iter_to_slice", since = "1.4.0")]
463 pub fn as_str(&self) -> &'a str {
464 unsafe { from_utf8_unchecked(self.iter.as_slice()) }
468 /// Iterator for a string's characters and their byte offsets.
469 #[derive(Clone, Debug)]
470 #[stable(feature = "rust1", since = "1.0.0")]
471 pub struct CharIndices<'a> {
476 #[stable(feature = "rust1", since = "1.0.0")]
477 impl<'a> Iterator for CharIndices<'a> {
478 type Item = (usize, char);
481 fn next(&mut self) -> Option<(usize, char)> {
482 let (pre_len, _) = self.iter.iter.size_hint();
483 match self.iter.next() {
486 let index = self.front_offset;
487 let (len, _) = self.iter.iter.size_hint();
488 self.front_offset += pre_len - len;
495 fn size_hint(&self) -> (usize, Option<usize>) {
496 self.iter.size_hint()
500 #[stable(feature = "rust1", since = "1.0.0")]
501 impl<'a> DoubleEndedIterator for CharIndices<'a> {
503 fn next_back(&mut self) -> Option<(usize, char)> {
504 match self.iter.next_back() {
507 let (len, _) = self.iter.iter.size_hint();
508 let index = self.front_offset + len;
515 impl<'a> CharIndices<'a> {
516 /// View the underlying data as a subslice of the original data.
518 /// This has the same lifetime as the original slice, and so the
519 /// iterator can continue to be used while this exists.
520 #[stable(feature = "iter_to_slice", since = "1.4.0")]
522 pub fn as_str(&self) -> &'a str {
527 /// External iterator for a string's bytes.
528 /// Use with the `std::iter` module.
530 /// Created with the method [`bytes()`].
532 /// [`bytes()`]: ../../std/primitive.str.html#method.bytes
533 #[stable(feature = "rust1", since = "1.0.0")]
534 #[derive(Clone, Debug)]
535 pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>);
537 #[stable(feature = "rust1", since = "1.0.0")]
538 impl<'a> Iterator for Bytes<'a> {
542 fn next(&mut self) -> Option<u8> {
547 fn size_hint(&self) -> (usize, Option<usize>) {
552 fn count(self) -> usize {
557 fn last(self) -> Option<Self::Item> {
562 fn nth(&mut self, n: usize) -> Option<Self::Item> {
567 #[stable(feature = "rust1", since = "1.0.0")]
568 impl<'a> DoubleEndedIterator for Bytes<'a> {
570 fn next_back(&mut self) -> Option<u8> {
575 #[stable(feature = "rust1", since = "1.0.0")]
576 impl<'a> ExactSizeIterator for Bytes<'a> {
578 fn len(&self) -> usize {
583 /// This macro generates a Clone impl for string pattern API
584 /// wrapper types of the form X<'a, P>
585 macro_rules! derive_pattern_clone {
586 (clone $t:ident with |$s:ident| $e:expr) => {
587 impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
588 where P::Searcher: Clone
590 fn clone(&self) -> Self {
598 /// This macro generates two public iterator structs
599 /// wrapping a private internal one that makes use of the `Pattern` API.
601 /// For all patterns `P: Pattern<'a>` the following items will be
602 /// generated (generics omitted):
604 /// struct $forward_iterator($internal_iterator);
605 /// struct $reverse_iterator($internal_iterator);
607 /// impl Iterator for $forward_iterator
608 /// { /* internal ends up calling Searcher::next_match() */ }
610 /// impl DoubleEndedIterator for $forward_iterator
611 /// where P::Searcher: DoubleEndedSearcher
612 /// { /* internal ends up calling Searcher::next_match_back() */ }
614 /// impl Iterator for $reverse_iterator
615 /// where P::Searcher: ReverseSearcher
616 /// { /* internal ends up calling Searcher::next_match_back() */ }
618 /// impl DoubleEndedIterator for $reverse_iterator
619 /// where P::Searcher: DoubleEndedSearcher
620 /// { /* internal ends up calling Searcher::next_match() */ }
622 /// The internal one is defined outside the macro, and has almost the same
623 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
624 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
626 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
627 /// `Pattern` might not return the same elements, so actually implementing
628 /// `DoubleEndedIterator` for it would be incorrect.
629 /// (See the docs in `str::pattern` for more details)
631 /// However, the internal struct still represents a single ended iterator from
632 /// either end, and depending on pattern is also a valid double ended iterator,
633 /// so the two wrapper structs implement `Iterator`
634 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
635 /// to the complex impls seen above.
636 macro_rules! generate_pattern_iterators {
640 $(#[$forward_iterator_attribute:meta])*
641 struct $forward_iterator:ident;
645 $(#[$reverse_iterator_attribute:meta])*
646 struct $reverse_iterator:ident;
648 // Stability of all generated items
650 $(#[$common_stability_attribute:meta])*
652 // Internal almost-iterator that is being delegated to
654 $internal_iterator:ident yielding ($iterty:ty);
656 // Kind of delgation - either single ended or double ended
659 $(#[$forward_iterator_attribute])*
660 $(#[$common_stability_attribute])*
661 pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
663 $(#[$common_stability_attribute])*
664 impl<'a, P: Pattern<'a>> fmt::Debug for $forward_iterator<'a, P>
665 where P::Searcher: fmt::Debug
667 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
668 f.debug_tuple(stringify!($forward_iterator))
674 $(#[$common_stability_attribute])*
675 impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
679 fn next(&mut self) -> Option<$iterty> {
684 $(#[$common_stability_attribute])*
685 impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
686 where P::Searcher: Clone
688 fn clone(&self) -> Self {
689 $forward_iterator(self.0.clone())
693 $(#[$reverse_iterator_attribute])*
694 $(#[$common_stability_attribute])*
695 pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
697 $(#[$common_stability_attribute])*
698 impl<'a, P: Pattern<'a>> fmt::Debug for $reverse_iterator<'a, P>
699 where P::Searcher: fmt::Debug
701 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
702 f.debug_tuple(stringify!($reverse_iterator))
708 $(#[$common_stability_attribute])*
709 impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
710 where P::Searcher: ReverseSearcher<'a>
715 fn next(&mut self) -> Option<$iterty> {
720 $(#[$common_stability_attribute])*
721 impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
722 where P::Searcher: Clone
724 fn clone(&self) -> Self {
725 $reverse_iterator(self.0.clone())
729 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
731 $reverse_iterator, $iterty);
734 double ended; with $(#[$common_stability_attribute:meta])*,
735 $forward_iterator:ident,
736 $reverse_iterator:ident, $iterty:ty
738 $(#[$common_stability_attribute])*
739 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
740 where P::Searcher: DoubleEndedSearcher<'a>
743 fn next_back(&mut self) -> Option<$iterty> {
748 $(#[$common_stability_attribute])*
749 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
750 where P::Searcher: DoubleEndedSearcher<'a>
753 fn next_back(&mut self) -> Option<$iterty> {
759 single ended; with $(#[$common_stability_attribute:meta])*,
760 $forward_iterator:ident,
761 $reverse_iterator:ident, $iterty:ty
765 derive_pattern_clone!{
767 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
770 struct SplitInternal<'a, P: Pattern<'a>> {
773 matcher: P::Searcher,
774 allow_trailing_empty: bool,
778 impl<'a, P: Pattern<'a>> fmt::Debug for SplitInternal<'a, P> where P::Searcher: fmt::Debug {
779 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
780 f.debug_struct("SplitInternal")
781 .field("start", &self.start)
782 .field("end", &self.end)
783 .field("matcher", &self.matcher)
784 .field("allow_trailing_empty", &self.allow_trailing_empty)
785 .field("finished", &self.finished)
790 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
792 fn get_end(&mut self) -> Option<&'a str> {
793 if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
794 self.finished = true;
796 let string = self.matcher.haystack().slice_unchecked(self.start, self.end);
805 fn next(&mut self) -> Option<&'a str> {
806 if self.finished { return None }
808 let haystack = self.matcher.haystack();
809 match self.matcher.next_match() {
810 Some((a, b)) => unsafe {
811 let elt = haystack.slice_unchecked(self.start, a);
815 None => self.get_end(),
820 fn next_back(&mut self) -> Option<&'a str>
821 where P::Searcher: ReverseSearcher<'a>
823 if self.finished { return None }
825 if !self.allow_trailing_empty {
826 self.allow_trailing_empty = true;
827 match self.next_back() {
828 Some(elt) if !elt.is_empty() => return Some(elt),
829 _ => if self.finished { return None }
833 let haystack = self.matcher.haystack();
834 match self.matcher.next_match_back() {
835 Some((a, b)) => unsafe {
836 let elt = haystack.slice_unchecked(b, self.end);
841 self.finished = true;
842 Some(haystack.slice_unchecked(self.start, self.end))
848 generate_pattern_iterators! {
850 /// Created with the method [`split()`].
852 /// [`split()`]: ../../std/primitive.str.html#method.split
855 /// Created with the method [`rsplit()`].
857 /// [`rsplit()`]: ../../std/primitive.str.html#method.rsplit
860 #[stable(feature = "rust1", since = "1.0.0")]
862 SplitInternal yielding (&'a str);
863 delegate double ended;
866 generate_pattern_iterators! {
868 /// Created with the method [`split_terminator()`].
870 /// [`split_terminator()`]: ../../std/primitive.str.html#method.split_terminator
871 struct SplitTerminator;
873 /// Created with the method [`rsplit_terminator()`].
875 /// [`rsplit_terminator()`]: ../../std/primitive.str.html#method.rsplit_terminator
876 struct RSplitTerminator;
878 #[stable(feature = "rust1", since = "1.0.0")]
880 SplitInternal yielding (&'a str);
881 delegate double ended;
884 derive_pattern_clone!{
886 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
889 struct SplitNInternal<'a, P: Pattern<'a>> {
890 iter: SplitInternal<'a, P>,
891 /// The number of splits remaining
895 impl<'a, P: Pattern<'a>> fmt::Debug for SplitNInternal<'a, P> where P::Searcher: fmt::Debug {
896 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
897 f.debug_struct("SplitNInternal")
898 .field("iter", &self.iter)
899 .field("count", &self.count)
904 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
906 fn next(&mut self) -> Option<&'a str> {
909 1 => { self.count = 0; self.iter.get_end() }
910 _ => { self.count -= 1; self.iter.next() }
915 fn next_back(&mut self) -> Option<&'a str>
916 where P::Searcher: ReverseSearcher<'a>
920 1 => { self.count = 0; self.iter.get_end() }
921 _ => { self.count -= 1; self.iter.next_back() }
926 generate_pattern_iterators! {
928 /// Created with the method [`splitn()`].
930 /// [`splitn()`]: ../../std/primitive.str.html#method.splitn
933 /// Created with the method [`rsplitn()`].
935 /// [`rsplitn()`]: ../../std/primitive.str.html#method.rsplitn
938 #[stable(feature = "rust1", since = "1.0.0")]
940 SplitNInternal yielding (&'a str);
941 delegate single ended;
944 derive_pattern_clone!{
945 clone MatchIndicesInternal
946 with |s| MatchIndicesInternal(s.0.clone())
949 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
951 impl<'a, P: Pattern<'a>> fmt::Debug for MatchIndicesInternal<'a, P> where P::Searcher: fmt::Debug {
952 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
953 f.debug_tuple("MatchIndicesInternal")
959 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
961 fn next(&mut self) -> Option<(usize, &'a str)> {
962 self.0.next_match().map(|(start, end)| unsafe {
963 (start, self.0.haystack().slice_unchecked(start, end))
968 fn next_back(&mut self) -> Option<(usize, &'a str)>
969 where P::Searcher: ReverseSearcher<'a>
971 self.0.next_match_back().map(|(start, end)| unsafe {
972 (start, self.0.haystack().slice_unchecked(start, end))
977 generate_pattern_iterators! {
979 /// Created with the method [`match_indices()`].
981 /// [`match_indices()`]: ../../std/primitive.str.html#method.match_indices
984 /// Created with the method [`rmatch_indices()`].
986 /// [`rmatch_indices()`]: ../../std/primitive.str.html#method.rmatch_indices
987 struct RMatchIndices;
989 #[stable(feature = "str_match_indices", since = "1.5.0")]
991 MatchIndicesInternal yielding ((usize, &'a str));
992 delegate double ended;
995 derive_pattern_clone!{
996 clone MatchesInternal
997 with |s| MatchesInternal(s.0.clone())
1000 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
1002 impl<'a, P: Pattern<'a>> fmt::Debug for MatchesInternal<'a, P> where P::Searcher: fmt::Debug {
1003 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1004 f.debug_tuple("MatchesInternal")
1010 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
1012 fn next(&mut self) -> Option<&'a str> {
1013 self.0.next_match().map(|(a, b)| unsafe {
1014 // Indices are known to be on utf8 boundaries
1015 self.0.haystack().slice_unchecked(a, b)
1020 fn next_back(&mut self) -> Option<&'a str>
1021 where P::Searcher: ReverseSearcher<'a>
1023 self.0.next_match_back().map(|(a, b)| unsafe {
1024 // Indices are known to be on utf8 boundaries
1025 self.0.haystack().slice_unchecked(a, b)
1030 generate_pattern_iterators! {
1032 /// Created with the method [`matches()`].
1034 /// [`matches()`]: ../../std/primitive.str.html#method.matches
1037 /// Created with the method [`rmatches()`].
1039 /// [`rmatches()`]: ../../std/primitive.str.html#method.rmatches
1042 #[stable(feature = "str_matches", since = "1.2.0")]
1044 MatchesInternal yielding (&'a str);
1045 delegate double ended;
1048 /// Created with the method [`lines()`].
1050 /// [`lines()`]: ../../std/primitive.str.html#method.lines
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 #[derive(Clone, Debug)]
1053 pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>);
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 impl<'a> Iterator for Lines<'a> {
1057 type Item = &'a str;
1060 fn next(&mut self) -> Option<&'a str> {
1065 fn size_hint(&self) -> (usize, Option<usize>) {
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 impl<'a> DoubleEndedIterator for Lines<'a> {
1073 fn next_back(&mut self) -> Option<&'a str> {
1078 /// Created with the method [`lines_any()`].
1080 /// [`lines_any()`]: ../../std/primitive.str.html#method.lines_any
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 #[rustc_deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")]
1083 #[derive(Clone, Debug)]
1084 #[allow(deprecated)]
1085 pub struct LinesAny<'a>(Lines<'a>);
1087 /// A nameable, cloneable fn type
1091 impl<'a> Fn<(&'a str,)> for LinesAnyMap {
1093 extern "rust-call" fn call(&self, (line,): (&'a str,)) -> &'a str {
1095 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
1100 impl<'a> FnMut<(&'a str,)> for LinesAnyMap {
1102 extern "rust-call" fn call_mut(&mut self, (line,): (&'a str,)) -> &'a str {
1103 Fn::call(&*self, (line,))
1107 impl<'a> FnOnce<(&'a str,)> for LinesAnyMap {
1108 type Output = &'a str;
1111 extern "rust-call" fn call_once(self, (line,): (&'a str,)) -> &'a str {
1112 Fn::call(&self, (line,))
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 #[allow(deprecated)]
1118 impl<'a> Iterator for LinesAny<'a> {
1119 type Item = &'a str;
1122 fn next(&mut self) -> Option<&'a str> {
1127 fn size_hint(&self) -> (usize, Option<usize>) {
1132 #[stable(feature = "rust1", since = "1.0.0")]
1133 #[allow(deprecated)]
1134 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1136 fn next_back(&mut self) -> Option<&'a str> {
1142 Section: Comparing strings
1145 /// Bytewise slice equality
1146 /// NOTE: This function is (ab)used in rustc::middle::trans::_match
1147 /// to compare &[u8] byte slices that are not necessarily valid UTF-8.
1150 fn eq_slice(a: &str, b: &str) -> bool {
1151 a.as_bytes() == b.as_bytes()
1155 Section: UTF-8 validation
1158 // use truncation to fit u64 into usize
1159 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
1161 /// Return `true` if any byte in the word `x` is nonascii (>= 128).
1163 fn contains_nonascii(x: usize) -> bool {
1164 (x & NONASCII_MASK) != 0
1167 /// Walk through `iter` checking that it's a valid UTF-8 sequence,
1168 /// returning `true` in that case, or, if it is invalid, `false` with
1169 /// `iter` reset such that it is pointing at the first byte in the
1170 /// invalid sequence.
1172 fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
1175 while offset < len {
1176 let old_offset = offset;
1177 macro_rules! err { () => {{
1178 return Err(Utf8Error {
1179 valid_up_to: old_offset
1183 macro_rules! next { () => {{
1185 // we needed data, but there was none: error!
1192 let first = v[offset];
1194 let w = UTF8_CHAR_WIDTH[first as usize];
1195 let second = next!();
1196 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
1197 // first C2 80 last DF BF
1198 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
1199 // first E0 A0 80 last EF BF BF
1200 // excluding surrogates codepoints \u{d800} to \u{dfff}
1201 // ED A0 80 to ED BF BF
1202 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1203 // first F0 90 80 80 last F4 8F BF BF
1205 // Use the UTF-8 syntax from the RFC
1207 // https://tools.ietf.org/html/rfc3629
1209 // UTF8-2 = %xC2-DF UTF8-tail
1210 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1211 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1212 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1213 // %xF4 %x80-8F 2( UTF8-tail )
1215 2 => if second & !CONT_MASK != TAG_CONT_U8 {err!()},
1217 match (first, second, next!() & !CONT_MASK) {
1218 (0xE0 , 0xA0 ... 0xBF, TAG_CONT_U8) |
1219 (0xE1 ... 0xEC, 0x80 ... 0xBF, TAG_CONT_U8) |
1220 (0xED , 0x80 ... 0x9F, TAG_CONT_U8) |
1221 (0xEE ... 0xEF, 0x80 ... 0xBF, TAG_CONT_U8) => {}
1226 match (first, second, next!() & !CONT_MASK, next!() & !CONT_MASK) {
1227 (0xF0 , 0x90 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
1228 (0xF1 ... 0xF3, 0x80 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
1229 (0xF4 , 0x80 ... 0x8F, TAG_CONT_U8, TAG_CONT_U8) => {}
1237 // Ascii case, try to skip forward quickly.
1238 // When the pointer is aligned, read 2 words of data per iteration
1239 // until we find a word containing a non-ascii byte.
1240 let usize_bytes = mem::size_of::<usize>();
1241 let bytes_per_iteration = 2 * usize_bytes;
1242 let ptr = v.as_ptr();
1243 let align = (ptr as usize + offset) & (usize_bytes - 1);
1245 if len >= bytes_per_iteration {
1246 while offset <= len - bytes_per_iteration {
1248 let u = *(ptr.offset(offset as isize) as *const usize);
1249 let v = *(ptr.offset((offset + usize_bytes) as isize) as *const usize);
1251 // break if there is a nonascii byte
1252 let zu = contains_nonascii(u);
1253 let zv = contains_nonascii(v);
1258 offset += bytes_per_iteration;
1261 // step from the point where the wordwise loop stopped
1262 while offset < len && v[offset] < 128 {
1274 // https://tools.ietf.org/html/rfc3629
1275 static UTF8_CHAR_WIDTH: [u8; 256] = [
1276 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1277 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1278 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1279 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1280 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1281 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1282 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1283 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1284 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1285 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1286 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1287 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1288 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1289 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1290 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1291 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1294 /// Struct that contains a `char` and the index of the first byte of
1295 /// the next `char` in a string. This can be used as a data structure
1296 /// for iterating over the UTF-8 bytes of a string.
1297 #[derive(Copy, Clone, Debug)]
1298 #[unstable(feature = "str_char",
1299 reason = "existence of this struct is uncertain as it is frequently \
1300 able to be replaced with char.len_utf8() and/or \
1301 char/char_indices iterators",
1303 pub struct CharRange {
1306 /// Index of the first byte of the next `char`
1310 /// Mask of the value bits of a continuation byte
1311 const CONT_MASK: u8 = 0b0011_1111;
1312 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte
1313 const TAG_CONT_U8: u8 = 0b1000_0000;
1316 Section: Trait implementations
1320 use cmp::{Ord, Ordering, PartialEq, PartialOrd, Eq};
1322 use option::Option::Some;
1324 use str::{StrExt, eq_slice};
1326 #[stable(feature = "rust1", since = "1.0.0")]
1329 fn cmp(&self, other: &str) -> Ordering {
1330 self.as_bytes().cmp(other.as_bytes())
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 impl PartialEq for str {
1337 fn eq(&self, other: &str) -> bool {
1338 eq_slice(self, other)
1341 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1344 #[stable(feature = "rust1", since = "1.0.0")]
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 impl PartialOrd for str {
1350 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1351 Some(self.cmp(other))
1355 /// Implements substring slicing with syntax `&self[begin .. end]`.
1357 /// Returns a slice of the given string from the byte range
1358 /// [`begin`..`end`).
1360 /// This operation is `O(1)`.
1364 /// Panics if `begin` or `end` does not point to the starting
1365 /// byte offset of a character (as defined by `is_char_boundary`).
1366 /// Requires that `begin <= end` and `end <= len` where `len` is the
1367 /// length of the string.
1372 /// let s = "Löwe 老虎 Léopard";
1373 /// assert_eq!(&s[0 .. 1], "L");
1375 /// assert_eq!(&s[1 .. 9], "öwe 老");
1377 /// // these will panic:
1378 /// // byte 2 lies within `ö`:
1381 /// // byte 8 lies within `老`
1384 /// // byte 100 is outside the string
1385 /// // &s[3 .. 100];
1387 #[stable(feature = "rust1", since = "1.0.0")]
1388 impl ops::Index<ops::Range<usize>> for str {
1391 fn index(&self, index: ops::Range<usize>) -> &str {
1392 // is_char_boundary checks that the index is in [0, .len()]
1393 if index.start <= index.end &&
1394 self.is_char_boundary(index.start) &&
1395 self.is_char_boundary(index.end) {
1396 unsafe { self.slice_unchecked(index.start, index.end) }
1398 super::slice_error_fail(self, index.start, index.end)
1403 /// Implements mutable substring slicing with syntax
1404 /// `&mut self[begin .. end]`.
1406 /// Returns a mutable slice of the given string from the byte range
1407 /// [`begin`..`end`).
1409 /// This operation is `O(1)`.
1413 /// Panics if `begin` or `end` does not point to the starting
1414 /// byte offset of a character (as defined by `is_char_boundary`).
1415 /// Requires that `begin <= end` and `end <= len` where `len` is the
1416 /// length of the string.
1417 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1418 impl ops::IndexMut<ops::Range<usize>> for str {
1420 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1421 // is_char_boundary checks that the index is in [0, .len()]
1422 if index.start <= index.end &&
1423 self.is_char_boundary(index.start) &&
1424 self.is_char_boundary(index.end) {
1425 unsafe { self.slice_mut_unchecked(index.start, index.end) }
1427 super::slice_error_fail(self, index.start, index.end)
1432 /// Implements substring slicing with syntax `&self[.. end]`.
1434 /// Returns a slice of the string from the beginning to byte offset
1437 /// Equivalent to `&self[0 .. end]`.
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 impl ops::Index<ops::RangeTo<usize>> for str {
1443 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1444 // is_char_boundary checks that the index is in [0, .len()]
1445 if self.is_char_boundary(index.end) {
1446 unsafe { self.slice_unchecked(0, index.end) }
1448 super::slice_error_fail(self, 0, index.end)
1453 /// Implements mutable substring slicing with syntax `&mut self[.. end]`.
1455 /// Returns a mutable slice of the string from the beginning to byte offset
1458 /// Equivalent to `&mut self[0 .. end]`.
1459 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1460 impl ops::IndexMut<ops::RangeTo<usize>> for str {
1462 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1463 // is_char_boundary checks that the index is in [0, .len()]
1464 if self.is_char_boundary(index.end) {
1465 unsafe { self.slice_mut_unchecked(0, index.end) }
1467 super::slice_error_fail(self, 0, index.end)
1472 /// Implements substring slicing with syntax `&self[begin ..]`.
1474 /// Returns a slice of the string from byte offset `begin`
1475 /// to the end of the string.
1477 /// Equivalent to `&self[begin .. len]`.
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 impl ops::Index<ops::RangeFrom<usize>> for str {
1483 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1484 // is_char_boundary checks that the index is in [0, .len()]
1485 if self.is_char_boundary(index.start) {
1486 unsafe { self.slice_unchecked(index.start, self.len()) }
1488 super::slice_error_fail(self, index.start, self.len())
1493 /// Implements mutable substring slicing with syntax `&mut self[begin ..]`.
1495 /// Returns a mutable slice of the string from byte offset `begin`
1496 /// to the end of the string.
1498 /// Equivalent to `&mut self[begin .. len]`.
1499 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1500 impl ops::IndexMut<ops::RangeFrom<usize>> for str {
1502 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1503 // is_char_boundary checks that the index is in [0, .len()]
1504 if self.is_char_boundary(index.start) {
1505 let len = self.len();
1506 unsafe { self.slice_mut_unchecked(index.start, len) }
1508 super::slice_error_fail(self, index.start, self.len())
1513 /// Implements substring slicing with syntax `&self[..]`.
1515 /// Returns a slice of the whole string. This operation can
1518 /// Equivalent to `&self[0 .. len]`.
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 impl ops::Index<ops::RangeFull> for str {
1524 fn index(&self, _index: ops::RangeFull) -> &str {
1529 /// Implements mutable substring slicing with syntax `&mut self[..]`.
1531 /// Returns a mutable slice of the whole string. This operation can
1534 /// Equivalent to `&mut self[0 .. len]`.
1535 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1536 impl ops::IndexMut<ops::RangeFull> for str {
1538 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1543 #[unstable(feature = "inclusive_range",
1544 reason = "recently added, follows RFC",
1546 impl ops::Index<ops::RangeInclusive<usize>> for str {
1550 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1552 ops::RangeInclusive::Empty { .. } => "",
1553 ops::RangeInclusive::NonEmpty { end, .. } if end == usize::max_value() =>
1554 panic!("attempted to index slice up to maximum usize"),
1555 ops::RangeInclusive::NonEmpty { start, end } =>
1556 self.index(start .. end+1)
1560 #[unstable(feature = "inclusive_range",
1561 reason = "recently added, follows RFC",
1563 impl ops::Index<ops::RangeToInclusive<usize>> for str {
1567 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1568 self.index(0...index.end)
1572 #[unstable(feature = "inclusive_range",
1573 reason = "recently added, follows RFC",
1575 impl ops::IndexMut<ops::RangeInclusive<usize>> for str {
1577 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1579 ops::RangeInclusive::Empty { .. } => &mut self[0..0], // `&mut ""` doesn't work
1580 ops::RangeInclusive::NonEmpty { end, .. } if end == usize::max_value() =>
1581 panic!("attempted to index str up to maximum usize"),
1582 ops::RangeInclusive::NonEmpty { start, end } =>
1583 self.index_mut(start .. end+1)
1587 #[unstable(feature = "inclusive_range",
1588 reason = "recently added, follows RFC",
1590 impl ops::IndexMut<ops::RangeToInclusive<usize>> for str {
1592 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1593 self.index_mut(0...index.end)
1598 /// Methods for string slices
1599 #[allow(missing_docs)]
1601 #[unstable(feature = "core_str_ext",
1602 reason = "stable interface provided by `impl str` in later crates",
1605 // NB there are no docs here are they're all located on the StrExt trait in
1606 // libcollections, not here.
1608 #[stable(feature = "core", since = "1.6.0")]
1609 fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
1610 #[stable(feature = "core", since = "1.6.0")]
1611 fn chars(&self) -> Chars;
1612 #[stable(feature = "core", since = "1.6.0")]
1613 fn bytes(&self) -> Bytes;
1614 #[stable(feature = "core", since = "1.6.0")]
1615 fn char_indices(&self) -> CharIndices;
1616 #[stable(feature = "core", since = "1.6.0")]
1617 fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P>;
1618 #[stable(feature = "core", since = "1.6.0")]
1619 fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1620 where P::Searcher: ReverseSearcher<'a>;
1621 #[stable(feature = "core", since = "1.6.0")]
1622 fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P>;
1623 #[stable(feature = "core", since = "1.6.0")]
1624 fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
1625 where P::Searcher: ReverseSearcher<'a>;
1626 #[stable(feature = "core", since = "1.6.0")]
1627 fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P>;
1628 #[stable(feature = "core", since = "1.6.0")]
1629 fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1630 where P::Searcher: ReverseSearcher<'a>;
1631 #[stable(feature = "core", since = "1.6.0")]
1632 fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P>;
1633 #[stable(feature = "core", since = "1.6.0")]
1634 fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1635 where P::Searcher: ReverseSearcher<'a>;
1636 #[stable(feature = "core", since = "1.6.0")]
1637 fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P>;
1638 #[stable(feature = "core", since = "1.6.0")]
1639 fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1640 where P::Searcher: ReverseSearcher<'a>;
1641 #[stable(feature = "core", since = "1.6.0")]
1642 fn lines(&self) -> Lines;
1643 #[stable(feature = "core", since = "1.6.0")]
1644 #[rustc_deprecated(since = "1.6.0", reason = "use lines() instead now")]
1645 #[allow(deprecated)]
1646 fn lines_any(&self) -> LinesAny;
1647 #[stable(feature = "core", since = "1.6.0")]
1648 unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str;
1649 #[stable(feature = "core", since = "1.6.0")]
1650 unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str;
1651 #[stable(feature = "core", since = "1.6.0")]
1652 fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
1653 #[stable(feature = "core", since = "1.6.0")]
1654 fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
1655 where P::Searcher: ReverseSearcher<'a>;
1656 #[stable(feature = "core", since = "1.6.0")]
1657 fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1658 where P::Searcher: DoubleEndedSearcher<'a>;
1659 #[stable(feature = "core", since = "1.6.0")]
1660 fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str;
1661 #[stable(feature = "core", since = "1.6.0")]
1662 fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1663 where P::Searcher: ReverseSearcher<'a>;
1664 #[stable(feature = "is_char_boundary", since = "1.9.0")]
1665 fn is_char_boundary(&self, index: usize) -> bool;
1666 #[stable(feature = "core", since = "1.6.0")]
1667 fn as_bytes(&self) -> &[u8];
1668 #[stable(feature = "core", since = "1.6.0")]
1669 fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
1670 #[stable(feature = "core", since = "1.6.0")]
1671 fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1672 where P::Searcher: ReverseSearcher<'a>;
1673 fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
1674 #[stable(feature = "core", since = "1.6.0")]
1675 fn split_at(&self, mid: usize) -> (&str, &str);
1676 #[stable(feature = "core", since = "1.6.0")]
1677 fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str);
1678 #[stable(feature = "core", since = "1.6.0")]
1679 fn as_ptr(&self) -> *const u8;
1680 #[stable(feature = "core", since = "1.6.0")]
1681 fn len(&self) -> usize;
1682 #[stable(feature = "core", since = "1.6.0")]
1683 fn is_empty(&self) -> bool;
1684 #[stable(feature = "core", since = "1.6.0")]
1685 fn parse<T: FromStr>(&self) -> Result<T, T::Err>;
1688 // truncate `&str` to length at most equal to `max`
1689 // return `true` if it were truncated, and the new str.
1690 fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
1694 while !s.is_char_boundary(max) {
1703 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
1704 const MAX_DISPLAY_LENGTH: usize = 256;
1705 let (truncated, s) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
1706 let ellipsis = if truncated { "[...]" } else { "" };
1708 assert!(begin <= end, "begin <= end ({} <= {}) when slicing `{}`{}",
1709 begin, end, s, ellipsis);
1710 panic!("index {} and/or {} in `{}`{} do not lie on character boundary",
1711 begin, end, s, ellipsis);
1714 #[stable(feature = "core", since = "1.6.0")]
1715 impl StrExt for str {
1717 fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1718 pat.is_contained_in(self)
1722 fn chars(&self) -> Chars {
1723 Chars{iter: self.as_bytes().iter()}
1727 fn bytes(&self) -> Bytes {
1728 Bytes(self.as_bytes().iter().cloned())
1732 fn char_indices(&self) -> CharIndices {
1733 CharIndices { front_offset: 0, iter: self.chars() }
1737 fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1738 Split(SplitInternal {
1741 matcher: pat.into_searcher(self),
1742 allow_trailing_empty: true,
1748 fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1749 where P::Searcher: ReverseSearcher<'a>
1751 RSplit(self.split(pat).0)
1755 fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
1756 SplitN(SplitNInternal {
1757 iter: self.split(pat).0,
1763 fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
1764 where P::Searcher: ReverseSearcher<'a>
1766 RSplitN(self.splitn(count, pat).0)
1770 fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1771 SplitTerminator(SplitInternal {
1772 allow_trailing_empty: false,
1778 fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1779 where P::Searcher: ReverseSearcher<'a>
1781 RSplitTerminator(self.split_terminator(pat).0)
1785 fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1786 Matches(MatchesInternal(pat.into_searcher(self)))
1790 fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1791 where P::Searcher: ReverseSearcher<'a>
1793 RMatches(self.matches(pat).0)
1797 fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1798 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
1802 fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1803 where P::Searcher: ReverseSearcher<'a>
1805 RMatchIndices(self.match_indices(pat).0)
1808 fn lines(&self) -> Lines {
1809 Lines(self.split_terminator('\n').map(LinesAnyMap))
1813 #[allow(deprecated)]
1814 fn lines_any(&self) -> LinesAny {
1815 LinesAny(self.lines())
1819 unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
1820 let ptr = self.as_ptr().offset(begin as isize);
1821 let len = end - begin;
1822 from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1826 unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
1827 let ptr = self.as_ptr().offset(begin as isize);
1828 let len = end - begin;
1829 mem::transmute(slice::from_raw_parts_mut(ptr as *mut u8, len))
1833 fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1834 pat.is_prefix_of(self)
1838 fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
1839 where P::Searcher: ReverseSearcher<'a>
1841 pat.is_suffix_of(self)
1845 fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1846 where P::Searcher: DoubleEndedSearcher<'a>
1850 let mut matcher = pat.into_searcher(self);
1851 if let Some((a, b)) = matcher.next_reject() {
1853 j = b; // Remember earliest known match, correct it below if
1854 // last match is different
1856 if let Some((_, b)) = matcher.next_reject_back() {
1860 // Searcher is known to return valid indices
1861 self.slice_unchecked(i, j)
1866 fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1867 let mut i = self.len();
1868 let mut matcher = pat.into_searcher(self);
1869 if let Some((a, _)) = matcher.next_reject() {
1873 // Searcher is known to return valid indices
1874 self.slice_unchecked(i, self.len())
1879 fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1880 where P::Searcher: ReverseSearcher<'a>
1883 let mut matcher = pat.into_searcher(self);
1884 if let Some((_, b)) = matcher.next_reject_back() {
1888 // Searcher is known to return valid indices
1889 self.slice_unchecked(0, j)
1894 fn is_char_boundary(&self, index: usize) -> bool {
1895 // 0 and len are always ok.
1896 // Test for 0 explicitly so that it can optimize out the check
1897 // easily and skip reading string data for that case.
1898 if index == 0 || index == self.len() { return true; }
1899 match self.as_bytes().get(index) {
1901 // This is bit magic equivalent to: b < 128 || b >= 192
1902 Some(&b) => (b as i8) >= -0x40,
1907 fn as_bytes(&self) -> &[u8] {
1908 unsafe { mem::transmute(self) }
1911 fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1912 pat.into_searcher(self).next_match().map(|(i, _)| i)
1915 fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1916 where P::Searcher: ReverseSearcher<'a>
1918 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1921 fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1926 fn split_at(&self, mid: usize) -> (&str, &str) {
1927 // is_char_boundary checks that the index is in [0, .len()]
1928 if self.is_char_boundary(mid) {
1930 (self.slice_unchecked(0, mid),
1931 self.slice_unchecked(mid, self.len()))
1934 slice_error_fail(self, 0, mid)
1938 fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
1939 // is_char_boundary checks that the index is in [0, .len()]
1940 if self.is_char_boundary(mid) {
1941 let len = self.len();
1942 let ptr = self.as_ptr() as *mut u8;
1944 (from_raw_parts_mut(ptr, mid),
1945 from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
1948 slice_error_fail(self, 0, mid)
1953 fn as_ptr(&self) -> *const u8 {
1954 self as *const str as *const u8
1958 fn len(&self) -> usize {
1959 self.as_bytes().len()
1963 fn is_empty(&self) -> bool { self.len() == 0 }
1966 fn parse<T: FromStr>(&self) -> Result<T, T::Err> { FromStr::from_str(self) }
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 impl AsRef<[u8]> for str {
1972 fn as_ref(&self) -> &[u8] {
1977 #[stable(feature = "rust1", since = "1.0.0")]
1978 impl<'a> Default for &'a str {
1979 fn default() -> &'a str { "" }