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};
23 use iter::{Map, Cloned, FusedIterator};
29 /// A trait to abstract the idea of creating a new instance of a type from a
32 /// `FromStr`'s [`from_str`] method is often used implicitly, through
33 /// [`str`]'s [`parse`] method. See [`parse`]'s documentation for examples.
35 /// [`from_str`]: #tymethod.from_str
36 /// [`str`]: ../../std/primitive.str.html
37 /// [`parse`]: ../../std/primitive.str.html#method.parse
38 #[stable(feature = "rust1", since = "1.0.0")]
39 pub trait FromStr: Sized {
40 /// The associated error which can be returned from parsing.
41 #[stable(feature = "rust1", since = "1.0.0")]
44 /// Parses a string `s` to return a value of this type.
46 /// If parsing succeeds, return the value inside `Ok`, otherwise
47 /// when the string is ill-formatted return an error specific to the
48 /// inside `Err`. The error type is specific to implementation of the trait.
52 /// Basic usage with [`i32`][ithirtytwo], a type that implements `FromStr`:
54 /// [ithirtytwo]: ../../std/primitive.i32.html
57 /// use std::str::FromStr;
60 /// let x = i32::from_str(s).unwrap();
64 #[stable(feature = "rust1", since = "1.0.0")]
65 fn from_str(s: &str) -> Result<Self, Self::Err>;
68 #[stable(feature = "rust1", since = "1.0.0")]
69 impl FromStr for bool {
70 type Err = ParseBoolError;
72 /// Parse a `bool` from a string.
74 /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
75 /// actually be parseable.
80 /// use std::str::FromStr;
82 /// assert_eq!(FromStr::from_str("true"), Ok(true));
83 /// assert_eq!(FromStr::from_str("false"), Ok(false));
84 /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
87 /// Note, in many cases, the `.parse()` method on `str` is more proper.
90 /// assert_eq!("true".parse(), Ok(true));
91 /// assert_eq!("false".parse(), Ok(false));
92 /// assert!("not even a boolean".parse::<bool>().is_err());
95 fn from_str(s: &str) -> Result<bool, ParseBoolError> {
99 _ => Err(ParseBoolError { _priv: () }),
104 /// An error returned when parsing a `bool` from a string fails.
105 #[derive(Debug, Clone, PartialEq, Eq)]
106 #[stable(feature = "rust1", since = "1.0.0")]
107 pub struct ParseBoolError { _priv: () }
109 #[stable(feature = "rust1", since = "1.0.0")]
110 impl fmt::Display for ParseBoolError {
111 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
112 "provided string was not `true` or `false`".fmt(f)
117 Section: Creating a string
120 /// Errors which can occur when attempting to interpret a sequence of `u8`
123 /// As such, the `from_utf8` family of functions and methods for both `String`s
124 /// and `&str`s make use of this error, for example.
125 #[derive(Copy, Eq, PartialEq, Clone, Debug)]
126 #[stable(feature = "rust1", since = "1.0.0")]
127 pub struct Utf8Error {
129 error_len: Option<u8>,
133 /// Returns the index in the given string up to which valid UTF-8 was
136 /// It is the maximum index such that `from_utf8(&input[..index])`
137 /// would return `Ok(_)`.
146 /// // some invalid bytes, in a vector
147 /// let sparkle_heart = vec![0, 159, 146, 150];
149 /// // std::str::from_utf8 returns a Utf8Error
150 /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
152 /// // the second byte is invalid here
153 /// assert_eq!(1, error.valid_up_to());
155 #[stable(feature = "utf8_error", since = "1.5.0")]
156 pub fn valid_up_to(&self) -> usize { self.valid_up_to }
158 /// Provide more information about the failure:
160 /// * `None`: the end of the input was reached unexpectedly.
161 /// `self.valid_up_to()` is 1 to 3 bytes from the end of the input.
162 /// If a byte stream (such as a file or a network socket) is being decoded incrementally,
163 /// this could be a valid `char` whose UTF-8 byte sequence is spanning multiple chunks.
165 /// * `Some(len)`: an unexpected byte was encountered.
166 /// The length provided is that of the invalid byte sequence
167 /// that starts at the index given by `valid_up_to()`.
168 /// Decoding should resume after that sequence
169 /// (after inserting a U+FFFD REPLACEMENT CHARACTER) in case of lossy decoding.
170 #[unstable(feature = "utf8_error_error_len", reason ="new", issue = "40494")]
171 pub fn error_len(&self) -> Option<usize> {
172 self.error_len.map(|len| len as usize)
176 /// Converts a slice of bytes to a string slice.
178 /// A string slice (`&str`) is made of bytes (`u8`), and a byte slice (`&[u8]`)
179 /// is made of bytes, so this function converts between the two. Not all byte
180 /// slices are valid string slices, however: `&str` requires that it is valid
181 /// UTF-8. `from_utf8()` checks to ensure that the bytes are valid UTF-8, and
182 /// then does the conversion.
184 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
185 /// incur the overhead of the validity check, there is an unsafe version of
186 /// this function, [`from_utf8_unchecked`][fromutf8u], which has the same
187 /// behavior but skips the check.
189 /// [fromutf8u]: fn.from_utf8_unchecked.html
191 /// If you need a `String` instead of a `&str`, consider
192 /// [`String::from_utf8`][string].
194 /// [string]: ../../std/string/struct.String.html#method.from_utf8
196 /// Because you can stack-allocate a `[u8; N]`, and you can take a `&[u8]` of
197 /// it, this function is one way to have a stack-allocated string. There is
198 /// an example of this in the examples section below.
202 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
203 /// provided slice is not UTF-8.
212 /// // some bytes, in a vector
213 /// let sparkle_heart = vec![240, 159, 146, 150];
215 /// // We know these bytes are valid, so just use `unwrap()`.
216 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
218 /// assert_eq!("💖", sparkle_heart);
226 /// // some invalid bytes, in a vector
227 /// let sparkle_heart = vec![0, 159, 146, 150];
229 /// assert!(str::from_utf8(&sparkle_heart).is_err());
232 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
233 /// errors that can be returned.
235 /// [error]: struct.Utf8Error.html
237 /// A "stack allocated string":
242 /// // some bytes, in a stack-allocated array
243 /// let sparkle_heart = [240, 159, 146, 150];
245 /// // We know these bytes are valid, so just use `unwrap()`.
246 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
248 /// assert_eq!("💖", sparkle_heart);
250 #[stable(feature = "rust1", since = "1.0.0")]
251 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
252 run_utf8_validation(v)?;
253 Ok(unsafe { from_utf8_unchecked(v) })
256 /// Forms a str from a pointer and a length.
258 /// The `len` argument is the number of bytes in the string.
262 /// This function is unsafe as there is no guarantee that the given pointer is
263 /// valid for `len` bytes, nor whether the lifetime inferred is a suitable
264 /// lifetime for the returned str.
266 /// The data must be valid UTF-8
268 /// `p` must be non-null, even for zero-length str.
272 /// The lifetime for the returned str is inferred from its usage. To
273 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
274 /// source lifetime is safe in the context, such as by providing a helper
275 /// function taking the lifetime of a host value for the str, or by explicit
277 /// Performs the same functionality as `from_raw_parts`, except that a mutable
280 unsafe fn from_raw_parts_mut<'a>(p: *mut u8, len: usize) -> &'a mut str {
281 mem::transmute::<&mut [u8], &mut str>(slice::from_raw_parts_mut(p, len))
284 /// Converts a slice of bytes to a string slice without checking
285 /// that the string contains valid UTF-8.
287 /// See the safe version, [`from_utf8`][fromutf8], for more information.
289 /// [fromutf8]: fn.from_utf8.html
293 /// This function is unsafe because it does not check that the bytes passed to
294 /// it are valid UTF-8. If this constraint is violated, undefined behavior
295 /// results, as the rest of Rust assumes that `&str`s are valid UTF-8.
304 /// // some bytes, in a vector
305 /// let sparkle_heart = vec![240, 159, 146, 150];
307 /// let sparkle_heart = unsafe {
308 /// str::from_utf8_unchecked(&sparkle_heart)
311 /// assert_eq!("💖", sparkle_heart);
314 #[stable(feature = "rust1", since = "1.0.0")]
315 pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
319 #[stable(feature = "rust1", since = "1.0.0")]
320 impl fmt::Display for Utf8Error {
321 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
322 if let Some(error_len) = self.error_len {
323 write!(f, "invalid utf-8 sequence of {} bytes from index {}",
324 error_len, self.valid_up_to)
326 write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to)
335 /// Iterator for the char (representing *Unicode Scalar Values*) of a string
337 /// Created with the method [`chars`].
339 /// [`chars`]: ../../std/primitive.str.html#method.chars
340 #[derive(Clone, Debug)]
341 #[stable(feature = "rust1", since = "1.0.0")]
342 pub struct Chars<'a> {
343 iter: slice::Iter<'a, u8>
346 /// Return the initial codepoint accumulator for the first byte.
347 /// The first byte is special, only want bottom 5 bits for width 2, 4 bits
348 /// for width 3, and 3 bits for width 4.
350 fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
352 /// Return the value of `ch` updated with continuation byte `byte`.
354 fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
356 /// Checks whether the byte is a UTF-8 continuation byte (i.e. starts with the
359 fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
362 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
369 /// Reads the next code point out of a byte iterator (assuming a
370 /// UTF-8-like encoding).
371 #[unstable(feature = "str_internals", issue = "0")]
373 pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
375 let x = match bytes.next() {
377 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
378 Some(&next_byte) => next_byte,
381 // Multibyte case follows
382 // Decode from a byte combination out of: [[[x y] z] w]
383 // NOTE: Performance is sensitive to the exact formulation here
384 let init = utf8_first_byte(x, 2);
385 let y = unwrap_or_0(bytes.next());
386 let mut ch = utf8_acc_cont_byte(init, y);
389 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
390 let z = unwrap_or_0(bytes.next());
391 let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
392 ch = init << 12 | y_z;
395 // use only the lower 3 bits of `init`
396 let w = unwrap_or_0(bytes.next());
397 ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
404 /// Reads the last code point out of a byte iterator (assuming a
405 /// UTF-8-like encoding).
407 fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
408 where I: DoubleEndedIterator<Item = &'a u8>,
411 let w = match bytes.next_back() {
413 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
414 Some(&back_byte) => back_byte,
417 // Multibyte case follows
418 // Decode from a byte combination out of: [x [y [z w]]]
420 let z = unwrap_or_0(bytes.next_back());
421 ch = utf8_first_byte(z, 2);
422 if utf8_is_cont_byte(z) {
423 let y = unwrap_or_0(bytes.next_back());
424 ch = utf8_first_byte(y, 3);
425 if utf8_is_cont_byte(y) {
426 let x = unwrap_or_0(bytes.next_back());
427 ch = utf8_first_byte(x, 4);
428 ch = utf8_acc_cont_byte(ch, y);
430 ch = utf8_acc_cont_byte(ch, z);
432 ch = utf8_acc_cont_byte(ch, w);
437 #[stable(feature = "rust1", since = "1.0.0")]
438 impl<'a> Iterator for Chars<'a> {
442 fn next(&mut self) -> Option<char> {
443 next_code_point(&mut self.iter).map(|ch| {
444 // str invariant says `ch` is a valid Unicode Scalar Value
446 char::from_u32_unchecked(ch)
452 fn count(self) -> usize {
453 // length in `char` is equal to the number of non-continuation bytes
454 let bytes_len = self.iter.len();
455 let mut cont_bytes = 0;
456 for &byte in self.iter {
457 cont_bytes += utf8_is_cont_byte(byte) as usize;
459 bytes_len - cont_bytes
463 fn size_hint(&self) -> (usize, Option<usize>) {
464 let len = self.iter.len();
465 // `(len + 3)` can't overflow, because we know that the `slice::Iter`
466 // belongs to a slice in memory which has a maximum length of
467 // `isize::MAX` (that's well below `usize::MAX`).
468 ((len + 3) / 4, Some(len))
472 fn last(mut self) -> Option<char> {
473 // No need to go through the entire string.
478 #[stable(feature = "rust1", since = "1.0.0")]
479 impl<'a> DoubleEndedIterator for Chars<'a> {
481 fn next_back(&mut self) -> Option<char> {
482 next_code_point_reverse(&mut self.iter).map(|ch| {
483 // str invariant says `ch` is a valid Unicode Scalar Value
485 char::from_u32_unchecked(ch)
491 #[unstable(feature = "fused", issue = "35602")]
492 impl<'a> FusedIterator for Chars<'a> {}
495 /// View the underlying data as a subslice of the original data.
497 /// This has the same lifetime as the original slice, and so the
498 /// iterator can continue to be used while this exists.
503 /// let mut chars = "abc".chars();
505 /// assert_eq!(chars.as_str(), "abc");
507 /// assert_eq!(chars.as_str(), "bc");
510 /// assert_eq!(chars.as_str(), "");
512 #[stable(feature = "iter_to_slice", since = "1.4.0")]
514 pub fn as_str(&self) -> &'a str {
515 unsafe { from_utf8_unchecked(self.iter.as_slice()) }
519 /// Iterator for a string's characters and their byte offsets.
520 #[derive(Clone, Debug)]
521 #[stable(feature = "rust1", since = "1.0.0")]
522 pub struct CharIndices<'a> {
527 #[stable(feature = "rust1", since = "1.0.0")]
528 impl<'a> Iterator for CharIndices<'a> {
529 type Item = (usize, char);
532 fn next(&mut self) -> Option<(usize, char)> {
533 let pre_len = self.iter.iter.len();
534 match self.iter.next() {
537 let index = self.front_offset;
538 let len = self.iter.iter.len();
539 self.front_offset += pre_len - len;
546 fn count(self) -> usize {
551 fn size_hint(&self) -> (usize, Option<usize>) {
552 self.iter.size_hint()
556 fn last(mut self) -> Option<(usize, char)> {
557 // No need to go through the entire string.
562 #[stable(feature = "rust1", since = "1.0.0")]
563 impl<'a> DoubleEndedIterator for CharIndices<'a> {
565 fn next_back(&mut self) -> Option<(usize, char)> {
566 match self.iter.next_back() {
569 let index = self.front_offset + self.iter.iter.len();
576 #[unstable(feature = "fused", issue = "35602")]
577 impl<'a> FusedIterator for CharIndices<'a> {}
579 impl<'a> CharIndices<'a> {
580 /// View the underlying data as a subslice of the original data.
582 /// This has the same lifetime as the original slice, and so the
583 /// iterator can continue to be used while this exists.
584 #[stable(feature = "iter_to_slice", since = "1.4.0")]
586 pub fn as_str(&self) -> &'a str {
591 /// External iterator for a string's bytes.
592 /// Use with the `std::iter` module.
594 /// Created with the method [`bytes`].
596 /// [`bytes`]: ../../std/primitive.str.html#method.bytes
597 #[stable(feature = "rust1", since = "1.0.0")]
598 #[derive(Clone, Debug)]
599 pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>);
601 #[stable(feature = "rust1", since = "1.0.0")]
602 impl<'a> Iterator for Bytes<'a> {
606 fn next(&mut self) -> Option<u8> {
611 fn size_hint(&self) -> (usize, Option<usize>) {
616 fn count(self) -> usize {
621 fn last(self) -> Option<Self::Item> {
626 fn nth(&mut self, n: usize) -> Option<Self::Item> {
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl<'a> DoubleEndedIterator for Bytes<'a> {
634 fn next_back(&mut self) -> Option<u8> {
639 #[stable(feature = "rust1", since = "1.0.0")]
640 impl<'a> ExactSizeIterator for Bytes<'a> {
642 fn len(&self) -> usize {
647 fn is_empty(&self) -> bool {
652 #[unstable(feature = "fused", issue = "35602")]
653 impl<'a> FusedIterator for Bytes<'a> {}
655 /// This macro generates a Clone impl for string pattern API
656 /// wrapper types of the form X<'a, P>
657 macro_rules! derive_pattern_clone {
658 (clone $t:ident with |$s:ident| $e:expr) => {
659 impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
660 where P::Searcher: Clone
662 fn clone(&self) -> Self {
670 /// This macro generates two public iterator structs
671 /// wrapping a private internal one that makes use of the `Pattern` API.
673 /// For all patterns `P: Pattern<'a>` the following items will be
674 /// generated (generics omitted):
676 /// struct $forward_iterator($internal_iterator);
677 /// struct $reverse_iterator($internal_iterator);
679 /// impl Iterator for $forward_iterator
680 /// { /* internal ends up calling Searcher::next_match() */ }
682 /// impl DoubleEndedIterator for $forward_iterator
683 /// where P::Searcher: DoubleEndedSearcher
684 /// { /* internal ends up calling Searcher::next_match_back() */ }
686 /// impl Iterator for $reverse_iterator
687 /// where P::Searcher: ReverseSearcher
688 /// { /* internal ends up calling Searcher::next_match_back() */ }
690 /// impl DoubleEndedIterator for $reverse_iterator
691 /// where P::Searcher: DoubleEndedSearcher
692 /// { /* internal ends up calling Searcher::next_match() */ }
694 /// The internal one is defined outside the macro, and has almost the same
695 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
696 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
698 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
699 /// `Pattern` might not return the same elements, so actually implementing
700 /// `DoubleEndedIterator` for it would be incorrect.
701 /// (See the docs in `str::pattern` for more details)
703 /// However, the internal struct still represents a single ended iterator from
704 /// either end, and depending on pattern is also a valid double ended iterator,
705 /// so the two wrapper structs implement `Iterator`
706 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
707 /// to the complex impls seen above.
708 macro_rules! generate_pattern_iterators {
712 $(#[$forward_iterator_attribute:meta])*
713 struct $forward_iterator:ident;
717 $(#[$reverse_iterator_attribute:meta])*
718 struct $reverse_iterator:ident;
720 // Stability of all generated items
722 $(#[$common_stability_attribute:meta])*
724 // Internal almost-iterator that is being delegated to
726 $internal_iterator:ident yielding ($iterty:ty);
728 // Kind of delgation - either single ended or double ended
731 $(#[$forward_iterator_attribute])*
732 $(#[$common_stability_attribute])*
733 pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
735 $(#[$common_stability_attribute])*
736 impl<'a, P: Pattern<'a>> fmt::Debug for $forward_iterator<'a, P>
737 where P::Searcher: fmt::Debug
739 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
740 f.debug_tuple(stringify!($forward_iterator))
746 $(#[$common_stability_attribute])*
747 impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
751 fn next(&mut self) -> Option<$iterty> {
756 $(#[$common_stability_attribute])*
757 impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
758 where P::Searcher: Clone
760 fn clone(&self) -> Self {
761 $forward_iterator(self.0.clone())
765 $(#[$reverse_iterator_attribute])*
766 $(#[$common_stability_attribute])*
767 pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
769 $(#[$common_stability_attribute])*
770 impl<'a, P: Pattern<'a>> fmt::Debug for $reverse_iterator<'a, P>
771 where P::Searcher: fmt::Debug
773 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
774 f.debug_tuple(stringify!($reverse_iterator))
780 $(#[$common_stability_attribute])*
781 impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
782 where P::Searcher: ReverseSearcher<'a>
787 fn next(&mut self) -> Option<$iterty> {
792 $(#[$common_stability_attribute])*
793 impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
794 where P::Searcher: Clone
796 fn clone(&self) -> Self {
797 $reverse_iterator(self.0.clone())
801 #[unstable(feature = "fused", issue = "35602")]
802 impl<'a, P: Pattern<'a>> FusedIterator for $forward_iterator<'a, P> {}
804 #[unstable(feature = "fused", issue = "35602")]
805 impl<'a, P: Pattern<'a>> FusedIterator for $reverse_iterator<'a, P>
806 where P::Searcher: ReverseSearcher<'a> {}
808 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
810 $reverse_iterator, $iterty);
813 double ended; with $(#[$common_stability_attribute:meta])*,
814 $forward_iterator:ident,
815 $reverse_iterator:ident, $iterty:ty
817 $(#[$common_stability_attribute])*
818 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
819 where P::Searcher: DoubleEndedSearcher<'a>
822 fn next_back(&mut self) -> Option<$iterty> {
827 $(#[$common_stability_attribute])*
828 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
829 where P::Searcher: DoubleEndedSearcher<'a>
832 fn next_back(&mut self) -> Option<$iterty> {
838 single ended; with $(#[$common_stability_attribute:meta])*,
839 $forward_iterator:ident,
840 $reverse_iterator:ident, $iterty:ty
844 derive_pattern_clone!{
846 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
849 struct SplitInternal<'a, P: Pattern<'a>> {
852 matcher: P::Searcher,
853 allow_trailing_empty: bool,
857 impl<'a, P: Pattern<'a>> fmt::Debug for SplitInternal<'a, P> where P::Searcher: fmt::Debug {
858 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
859 f.debug_struct("SplitInternal")
860 .field("start", &self.start)
861 .field("end", &self.end)
862 .field("matcher", &self.matcher)
863 .field("allow_trailing_empty", &self.allow_trailing_empty)
864 .field("finished", &self.finished)
869 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
871 fn get_end(&mut self) -> Option<&'a str> {
872 if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
873 self.finished = true;
875 let string = self.matcher.haystack().slice_unchecked(self.start, self.end);
884 fn next(&mut self) -> Option<&'a str> {
885 if self.finished { return None }
887 let haystack = self.matcher.haystack();
888 match self.matcher.next_match() {
889 Some((a, b)) => unsafe {
890 let elt = haystack.slice_unchecked(self.start, a);
894 None => self.get_end(),
899 fn next_back(&mut self) -> Option<&'a str>
900 where P::Searcher: ReverseSearcher<'a>
902 if self.finished { return None }
904 if !self.allow_trailing_empty {
905 self.allow_trailing_empty = true;
906 match self.next_back() {
907 Some(elt) if !elt.is_empty() => return Some(elt),
908 _ => if self.finished { return None }
912 let haystack = self.matcher.haystack();
913 match self.matcher.next_match_back() {
914 Some((a, b)) => unsafe {
915 let elt = haystack.slice_unchecked(b, self.end);
920 self.finished = true;
921 Some(haystack.slice_unchecked(self.start, self.end))
927 generate_pattern_iterators! {
929 /// Created with the method [`split`].
931 /// [`split`]: ../../std/primitive.str.html#method.split
934 /// Created with the method [`rsplit`].
936 /// [`rsplit`]: ../../std/primitive.str.html#method.rsplit
939 #[stable(feature = "rust1", since = "1.0.0")]
941 SplitInternal yielding (&'a str);
942 delegate double ended;
945 generate_pattern_iterators! {
947 /// Created with the method [`split_terminator`].
949 /// [`split_terminator`]: ../../std/primitive.str.html#method.split_terminator
950 struct SplitTerminator;
952 /// Created with the method [`rsplit_terminator`].
954 /// [`rsplit_terminator`]: ../../std/primitive.str.html#method.rsplit_terminator
955 struct RSplitTerminator;
957 #[stable(feature = "rust1", since = "1.0.0")]
959 SplitInternal yielding (&'a str);
960 delegate double ended;
963 derive_pattern_clone!{
965 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
968 struct SplitNInternal<'a, P: Pattern<'a>> {
969 iter: SplitInternal<'a, P>,
970 /// The number of splits remaining
974 impl<'a, P: Pattern<'a>> fmt::Debug for SplitNInternal<'a, P> where P::Searcher: fmt::Debug {
975 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
976 f.debug_struct("SplitNInternal")
977 .field("iter", &self.iter)
978 .field("count", &self.count)
983 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
985 fn next(&mut self) -> Option<&'a str> {
988 1 => { self.count = 0; self.iter.get_end() }
989 _ => { self.count -= 1; self.iter.next() }
994 fn next_back(&mut self) -> Option<&'a str>
995 where P::Searcher: ReverseSearcher<'a>
999 1 => { self.count = 0; self.iter.get_end() }
1000 _ => { self.count -= 1; self.iter.next_back() }
1005 generate_pattern_iterators! {
1007 /// Created with the method [`splitn`].
1009 /// [`splitn`]: ../../std/primitive.str.html#method.splitn
1012 /// Created with the method [`rsplitn`].
1014 /// [`rsplitn`]: ../../std/primitive.str.html#method.rsplitn
1017 #[stable(feature = "rust1", since = "1.0.0")]
1019 SplitNInternal yielding (&'a str);
1020 delegate single ended;
1023 derive_pattern_clone!{
1024 clone MatchIndicesInternal
1025 with |s| MatchIndicesInternal(s.0.clone())
1028 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
1030 impl<'a, P: Pattern<'a>> fmt::Debug for MatchIndicesInternal<'a, P> where P::Searcher: fmt::Debug {
1031 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1032 f.debug_tuple("MatchIndicesInternal")
1038 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
1040 fn next(&mut self) -> Option<(usize, &'a str)> {
1041 self.0.next_match().map(|(start, end)| unsafe {
1042 (start, self.0.haystack().slice_unchecked(start, end))
1047 fn next_back(&mut self) -> Option<(usize, &'a str)>
1048 where P::Searcher: ReverseSearcher<'a>
1050 self.0.next_match_back().map(|(start, end)| unsafe {
1051 (start, self.0.haystack().slice_unchecked(start, end))
1056 generate_pattern_iterators! {
1058 /// Created with the method [`match_indices`].
1060 /// [`match_indices`]: ../../std/primitive.str.html#method.match_indices
1061 struct MatchIndices;
1063 /// Created with the method [`rmatch_indices`].
1065 /// [`rmatch_indices`]: ../../std/primitive.str.html#method.rmatch_indices
1066 struct RMatchIndices;
1068 #[stable(feature = "str_match_indices", since = "1.5.0")]
1070 MatchIndicesInternal yielding ((usize, &'a str));
1071 delegate double ended;
1074 derive_pattern_clone!{
1075 clone MatchesInternal
1076 with |s| MatchesInternal(s.0.clone())
1079 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
1081 impl<'a, P: Pattern<'a>> fmt::Debug for MatchesInternal<'a, P> where P::Searcher: fmt::Debug {
1082 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1083 f.debug_tuple("MatchesInternal")
1089 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
1091 fn next(&mut self) -> Option<&'a str> {
1092 self.0.next_match().map(|(a, b)| unsafe {
1093 // Indices are known to be on utf8 boundaries
1094 self.0.haystack().slice_unchecked(a, b)
1099 fn next_back(&mut self) -> Option<&'a str>
1100 where P::Searcher: ReverseSearcher<'a>
1102 self.0.next_match_back().map(|(a, b)| unsafe {
1103 // Indices are known to be on utf8 boundaries
1104 self.0.haystack().slice_unchecked(a, b)
1109 generate_pattern_iterators! {
1111 /// Created with the method [`matches`].
1113 /// [`matches`]: ../../std/primitive.str.html#method.matches
1116 /// Created with the method [`rmatches`].
1118 /// [`rmatches`]: ../../std/primitive.str.html#method.rmatches
1121 #[stable(feature = "str_matches", since = "1.2.0")]
1123 MatchesInternal yielding (&'a str);
1124 delegate double ended;
1127 /// Created with the method [`lines`].
1129 /// [`lines`]: ../../std/primitive.str.html#method.lines
1130 #[stable(feature = "rust1", since = "1.0.0")]
1131 #[derive(Clone, Debug)]
1132 pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>);
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 impl<'a> Iterator for Lines<'a> {
1136 type Item = &'a str;
1139 fn next(&mut self) -> Option<&'a str> {
1144 fn size_hint(&self) -> (usize, Option<usize>) {
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 impl<'a> DoubleEndedIterator for Lines<'a> {
1152 fn next_back(&mut self) -> Option<&'a str> {
1157 #[unstable(feature = "fused", issue = "35602")]
1158 impl<'a> FusedIterator for Lines<'a> {}
1160 /// Created with the method [`lines_any`].
1162 /// [`lines_any`]: ../../std/primitive.str.html#method.lines_any
1163 #[stable(feature = "rust1", since = "1.0.0")]
1164 #[rustc_deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")]
1165 #[derive(Clone, Debug)]
1166 #[allow(deprecated)]
1167 pub struct LinesAny<'a>(Lines<'a>);
1169 /// A nameable, cloneable fn type
1173 impl<'a> Fn<(&'a str,)> for LinesAnyMap {
1175 extern "rust-call" fn call(&self, (line,): (&'a str,)) -> &'a str {
1177 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
1182 impl<'a> FnMut<(&'a str,)> for LinesAnyMap {
1184 extern "rust-call" fn call_mut(&mut self, (line,): (&'a str,)) -> &'a str {
1185 Fn::call(&*self, (line,))
1189 impl<'a> FnOnce<(&'a str,)> for LinesAnyMap {
1190 type Output = &'a str;
1193 extern "rust-call" fn call_once(self, (line,): (&'a str,)) -> &'a str {
1194 Fn::call(&self, (line,))
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 #[allow(deprecated)]
1200 impl<'a> Iterator for LinesAny<'a> {
1201 type Item = &'a str;
1204 fn next(&mut self) -> Option<&'a str> {
1209 fn size_hint(&self) -> (usize, Option<usize>) {
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 #[allow(deprecated)]
1216 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1218 fn next_back(&mut self) -> Option<&'a str> {
1223 #[unstable(feature = "fused", issue = "35602")]
1224 #[allow(deprecated)]
1225 impl<'a> FusedIterator for LinesAny<'a> {}
1228 Section: Comparing strings
1231 /// Bytewise slice equality
1232 /// NOTE: This function is (ab)used in rustc::middle::trans::_match
1233 /// to compare &[u8] byte slices that are not necessarily valid UTF-8.
1236 fn eq_slice(a: &str, b: &str) -> bool {
1237 a.as_bytes() == b.as_bytes()
1241 Section: UTF-8 validation
1244 // use truncation to fit u64 into usize
1245 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
1247 /// Return `true` if any byte in the word `x` is nonascii (>= 128).
1249 fn contains_nonascii(x: usize) -> bool {
1250 (x & NONASCII_MASK) != 0
1253 /// Walk through `iter` checking that it's a valid UTF-8 sequence,
1254 /// returning `true` in that case, or, if it is invalid, `false` with
1255 /// `iter` reset such that it is pointing at the first byte in the
1256 /// invalid sequence.
1258 fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
1262 let usize_bytes = mem::size_of::<usize>();
1263 let ascii_block_size = 2 * usize_bytes;
1264 let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
1267 let old_offset = index;
1269 ($error_len: expr) => {
1270 return Err(Utf8Error {
1271 valid_up_to: old_offset,
1272 error_len: $error_len,
1277 macro_rules! next { () => {{
1279 // we needed data, but there was none: error!
1286 let first = v[index];
1288 let w = UTF8_CHAR_WIDTH[first as usize];
1289 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
1290 // first C2 80 last DF BF
1291 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
1292 // first E0 A0 80 last EF BF BF
1293 // excluding surrogates codepoints \u{d800} to \u{dfff}
1294 // ED A0 80 to ED BF BF
1295 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1296 // first F0 90 80 80 last F4 8F BF BF
1298 // Use the UTF-8 syntax from the RFC
1300 // https://tools.ietf.org/html/rfc3629
1302 // UTF8-2 = %xC2-DF UTF8-tail
1303 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1304 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1305 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1306 // %xF4 %x80-8F 2( UTF8-tail )
1308 2 => if next!() & !CONT_MASK != TAG_CONT_U8 {
1312 match (first, next!()) {
1313 (0xE0 , 0xA0 ... 0xBF) |
1314 (0xE1 ... 0xEC, 0x80 ... 0xBF) |
1315 (0xED , 0x80 ... 0x9F) |
1316 (0xEE ... 0xEF, 0x80 ... 0xBF) => {}
1319 if next!() & !CONT_MASK != TAG_CONT_U8 {
1324 match (first, next!()) {
1325 (0xF0 , 0x90 ... 0xBF) |
1326 (0xF1 ... 0xF3, 0x80 ... 0xBF) |
1327 (0xF4 , 0x80 ... 0x8F) => {}
1330 if next!() & !CONT_MASK != TAG_CONT_U8 {
1333 if next!() & !CONT_MASK != TAG_CONT_U8 {
1341 // Ascii case, try to skip forward quickly.
1342 // When the pointer is aligned, read 2 words of data per iteration
1343 // until we find a word containing a non-ascii byte.
1344 let ptr = v.as_ptr();
1345 let align = (ptr as usize + index) & (usize_bytes - 1);
1347 while index < blocks_end {
1349 let block = ptr.offset(index as isize) as *const usize;
1350 // break if there is a nonascii byte
1351 let zu = contains_nonascii(*block);
1352 let zv = contains_nonascii(*block.offset(1));
1357 index += ascii_block_size;
1359 // step from the point where the wordwise loop stopped
1360 while index < len && v[index] < 128 {
1372 // https://tools.ietf.org/html/rfc3629
1373 static UTF8_CHAR_WIDTH: [u8; 256] = [
1374 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1375 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1376 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1377 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1378 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1379 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1380 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1381 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1382 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1383 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1384 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1385 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1386 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1387 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1388 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1389 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1392 /// Given a first byte, determine how many bytes are in this UTF-8 character
1393 #[unstable(feature = "str_internals", issue = "0")]
1395 pub fn utf8_char_width(b: u8) -> usize {
1396 return UTF8_CHAR_WIDTH[b as usize] as usize;
1399 /// Mask of the value bits of a continuation byte
1400 const CONT_MASK: u8 = 0b0011_1111;
1401 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte
1402 const TAG_CONT_U8: u8 = 0b1000_0000;
1405 Section: Trait implementations
1413 /// Implements ordering of strings.
1415 /// Strings are ordered lexicographically by their byte values. This orders Unicode code
1416 /// points based on their positions in the code charts. This is not necessarily the same as
1417 /// "alphabetical" order, which varies by language and locale. Sorting strings according to
1418 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1420 #[stable(feature = "rust1", since = "1.0.0")]
1423 fn cmp(&self, other: &str) -> Ordering {
1424 self.as_bytes().cmp(other.as_bytes())
1428 #[stable(feature = "rust1", since = "1.0.0")]
1429 impl PartialEq for str {
1431 fn eq(&self, other: &str) -> bool {
1432 eq_slice(self, other)
1435 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1438 #[stable(feature = "rust1", since = "1.0.0")]
1441 /// Implements comparison operations on strings.
1443 /// Strings are compared lexicographically by their byte values. This compares Unicode code
1444 /// points based on their positions in the code charts. This is not necessarily the same as
1445 /// "alphabetical" order, which varies by language and locale. Comparing strings according to
1446 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1448 #[stable(feature = "rust1", since = "1.0.0")]
1449 impl PartialOrd for str {
1451 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1452 Some(self.cmp(other))
1456 /// Implements substring slicing with syntax `&self[begin .. end]`.
1458 /// Returns a slice of the given string from the byte range
1459 /// [`begin`..`end`).
1461 /// This operation is `O(1)`.
1465 /// Panics if `begin` or `end` does not point to the starting
1466 /// byte offset of a character (as defined by `is_char_boundary`).
1467 /// Requires that `begin <= end` and `end <= len` where `len` is the
1468 /// length of the string.
1473 /// let s = "Löwe 老虎 Léopard";
1474 /// assert_eq!(&s[0 .. 1], "L");
1476 /// assert_eq!(&s[1 .. 9], "öwe 老");
1478 /// // these will panic:
1479 /// // byte 2 lies within `ö`:
1482 /// // byte 8 lies within `老`
1485 /// // byte 100 is outside the string
1486 /// // &s[3 .. 100];
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 impl ops::Index<ops::Range<usize>> for str {
1492 fn index(&self, index: ops::Range<usize>) -> &str {
1493 // is_char_boundary checks that the index is in [0, .len()]
1494 if index.start <= index.end &&
1495 self.is_char_boundary(index.start) &&
1496 self.is_char_boundary(index.end) {
1497 unsafe { self.slice_unchecked(index.start, index.end) }
1499 super::slice_error_fail(self, index.start, index.end)
1504 /// Implements mutable substring slicing with syntax
1505 /// `&mut self[begin .. end]`.
1507 /// Returns a mutable slice of the given string from the byte range
1508 /// [`begin`..`end`).
1510 /// This operation is `O(1)`.
1514 /// Panics if `begin` or `end` does not point to the starting
1515 /// byte offset of a character (as defined by `is_char_boundary`).
1516 /// Requires that `begin <= end` and `end <= len` where `len` is the
1517 /// length of the string.
1518 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1519 impl ops::IndexMut<ops::Range<usize>> for str {
1521 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1522 // is_char_boundary checks that the index is in [0, .len()]
1523 if index.start <= index.end &&
1524 self.is_char_boundary(index.start) &&
1525 self.is_char_boundary(index.end) {
1526 unsafe { self.slice_mut_unchecked(index.start, index.end) }
1528 super::slice_error_fail(self, index.start, index.end)
1533 /// Implements substring slicing with syntax `&self[.. end]`.
1535 /// Returns a slice of the string from the beginning to byte offset
1538 /// Equivalent to `&self[0 .. end]`.
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 impl ops::Index<ops::RangeTo<usize>> for str {
1544 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1545 // is_char_boundary checks that the index is in [0, .len()]
1546 if self.is_char_boundary(index.end) {
1547 unsafe { self.slice_unchecked(0, index.end) }
1549 super::slice_error_fail(self, 0, index.end)
1554 /// Implements mutable substring slicing with syntax `&mut self[.. end]`.
1556 /// Returns a mutable slice of the string from the beginning to byte offset
1559 /// Equivalent to `&mut self[0 .. end]`.
1560 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1561 impl ops::IndexMut<ops::RangeTo<usize>> for str {
1563 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1564 // is_char_boundary checks that the index is in [0, .len()]
1565 if self.is_char_boundary(index.end) {
1566 unsafe { self.slice_mut_unchecked(0, index.end) }
1568 super::slice_error_fail(self, 0, index.end)
1573 /// Implements substring slicing with syntax `&self[begin ..]`.
1575 /// Returns a slice of the string from byte offset `begin`
1576 /// to the end of the string.
1578 /// Equivalent to `&self[begin .. len]`.
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 impl ops::Index<ops::RangeFrom<usize>> for str {
1584 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1585 // is_char_boundary checks that the index is in [0, .len()]
1586 if self.is_char_boundary(index.start) {
1587 unsafe { self.slice_unchecked(index.start, self.len()) }
1589 super::slice_error_fail(self, index.start, self.len())
1594 /// Implements mutable substring slicing with syntax `&mut self[begin ..]`.
1596 /// Returns a mutable slice of the string from byte offset `begin`
1597 /// to the end of the string.
1599 /// Equivalent to `&mut self[begin .. len]`.
1600 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1601 impl ops::IndexMut<ops::RangeFrom<usize>> for str {
1603 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1604 // is_char_boundary checks that the index is in [0, .len()]
1605 if self.is_char_boundary(index.start) {
1606 let len = self.len();
1607 unsafe { self.slice_mut_unchecked(index.start, len) }
1609 super::slice_error_fail(self, index.start, self.len())
1614 /// Implements substring slicing with syntax `&self[..]`.
1616 /// Returns a slice of the whole string. This operation can
1619 /// Equivalent to `&self[0 .. len]`.
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 impl ops::Index<ops::RangeFull> for str {
1625 fn index(&self, _index: ops::RangeFull) -> &str {
1630 /// Implements mutable substring slicing with syntax `&mut self[..]`.
1632 /// Returns a mutable slice of the whole string. This operation can
1635 /// Equivalent to `&mut self[0 .. len]`.
1636 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1637 impl ops::IndexMut<ops::RangeFull> for str {
1639 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1644 #[unstable(feature = "inclusive_range",
1645 reason = "recently added, follows RFC",
1647 impl ops::Index<ops::RangeInclusive<usize>> for str {
1651 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1653 ops::RangeInclusive::Empty { .. } => "",
1654 ops::RangeInclusive::NonEmpty { end, .. } if end == usize::max_value() =>
1655 panic!("attempted to index slice up to maximum usize"),
1656 ops::RangeInclusive::NonEmpty { start, end } =>
1657 self.index(start .. end+1)
1661 #[unstable(feature = "inclusive_range",
1662 reason = "recently added, follows RFC",
1664 impl ops::Index<ops::RangeToInclusive<usize>> for str {
1668 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1669 self.index(0...index.end)
1673 #[unstable(feature = "inclusive_range",
1674 reason = "recently added, follows RFC",
1676 impl ops::IndexMut<ops::RangeInclusive<usize>> for str {
1678 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1680 ops::RangeInclusive::Empty { .. } => &mut self[0..0], // `&mut ""` doesn't work
1681 ops::RangeInclusive::NonEmpty { end, .. } if end == usize::max_value() =>
1682 panic!("attempted to index str up to maximum usize"),
1683 ops::RangeInclusive::NonEmpty { start, end } =>
1684 self.index_mut(start .. end+1)
1688 #[unstable(feature = "inclusive_range",
1689 reason = "recently added, follows RFC",
1691 impl ops::IndexMut<ops::RangeToInclusive<usize>> for str {
1693 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1694 self.index_mut(0...index.end)
1699 /// Methods for string slices
1700 #[allow(missing_docs)]
1702 #[unstable(feature = "core_str_ext",
1703 reason = "stable interface provided by `impl str` in later crates",
1706 // NB there are no docs here are they're all located on the StrExt trait in
1707 // libcollections, not here.
1709 #[stable(feature = "core", since = "1.6.0")]
1710 fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
1711 #[stable(feature = "core", since = "1.6.0")]
1712 fn chars(&self) -> Chars;
1713 #[stable(feature = "core", since = "1.6.0")]
1714 fn bytes(&self) -> Bytes;
1715 #[stable(feature = "core", since = "1.6.0")]
1716 fn char_indices(&self) -> CharIndices;
1717 #[stable(feature = "core", since = "1.6.0")]
1718 fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P>;
1719 #[stable(feature = "core", since = "1.6.0")]
1720 fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1721 where P::Searcher: ReverseSearcher<'a>;
1722 #[stable(feature = "core", since = "1.6.0")]
1723 fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P>;
1724 #[stable(feature = "core", since = "1.6.0")]
1725 fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
1726 where P::Searcher: ReverseSearcher<'a>;
1727 #[stable(feature = "core", since = "1.6.0")]
1728 fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P>;
1729 #[stable(feature = "core", since = "1.6.0")]
1730 fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1731 where P::Searcher: ReverseSearcher<'a>;
1732 #[stable(feature = "core", since = "1.6.0")]
1733 fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P>;
1734 #[stable(feature = "core", since = "1.6.0")]
1735 fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1736 where P::Searcher: ReverseSearcher<'a>;
1737 #[stable(feature = "core", since = "1.6.0")]
1738 fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P>;
1739 #[stable(feature = "core", since = "1.6.0")]
1740 fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1741 where P::Searcher: ReverseSearcher<'a>;
1742 #[stable(feature = "core", since = "1.6.0")]
1743 fn lines(&self) -> Lines;
1744 #[stable(feature = "core", since = "1.6.0")]
1745 #[rustc_deprecated(since = "1.6.0", reason = "use lines() instead now")]
1746 #[allow(deprecated)]
1747 fn lines_any(&self) -> LinesAny;
1748 #[stable(feature = "core", since = "1.6.0")]
1749 unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str;
1750 #[stable(feature = "core", since = "1.6.0")]
1751 unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str;
1752 #[stable(feature = "core", since = "1.6.0")]
1753 fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
1754 #[stable(feature = "core", since = "1.6.0")]
1755 fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
1756 where P::Searcher: ReverseSearcher<'a>;
1757 #[stable(feature = "core", since = "1.6.0")]
1758 fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1759 where P::Searcher: DoubleEndedSearcher<'a>;
1760 #[stable(feature = "core", since = "1.6.0")]
1761 fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str;
1762 #[stable(feature = "core", since = "1.6.0")]
1763 fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1764 where P::Searcher: ReverseSearcher<'a>;
1765 #[stable(feature = "is_char_boundary", since = "1.9.0")]
1766 fn is_char_boundary(&self, index: usize) -> bool;
1767 #[stable(feature = "core", since = "1.6.0")]
1768 fn as_bytes(&self) -> &[u8];
1769 #[stable(feature = "core", since = "1.6.0")]
1770 fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
1771 #[stable(feature = "core", since = "1.6.0")]
1772 fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1773 where P::Searcher: ReverseSearcher<'a>;
1774 fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
1775 #[stable(feature = "core", since = "1.6.0")]
1776 fn split_at(&self, mid: usize) -> (&str, &str);
1777 #[stable(feature = "core", since = "1.6.0")]
1778 fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str);
1779 #[stable(feature = "core", since = "1.6.0")]
1780 fn as_ptr(&self) -> *const u8;
1781 #[stable(feature = "core", since = "1.6.0")]
1782 fn len(&self) -> usize;
1783 #[stable(feature = "core", since = "1.6.0")]
1784 fn is_empty(&self) -> bool;
1785 #[stable(feature = "core", since = "1.6.0")]
1786 fn parse<'a, T: TryFrom<&'a str>>(&'a self) -> Result<T, T::Error>;
1789 // truncate `&str` to length at most equal to `max`
1790 // return `true` if it were truncated, and the new str.
1791 fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
1795 while !s.is_char_boundary(max) {
1804 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
1805 const MAX_DISPLAY_LENGTH: usize = 256;
1806 let (truncated, s_trunc) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
1807 let ellipsis = if truncated { "[...]" } else { "" };
1810 if begin > s.len() || end > s.len() {
1811 let oob_index = if begin > s.len() { begin } else { end };
1812 panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
1816 assert!(begin <= end, "begin <= end ({} <= {}) when slicing `{}`{}",
1817 begin, end, s_trunc, ellipsis);
1819 // 3. character boundary
1820 let index = if !s.is_char_boundary(begin) { begin } else { end };
1821 // find the character
1822 let mut char_start = index;
1823 while !s.is_char_boundary(char_start) {
1826 // `char_start` must be less than len and a char boundary
1827 let ch = s[char_start..].chars().next().unwrap();
1828 let char_range = char_start .. char_start + ch.len_utf8();
1829 panic!("byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
1830 index, ch, char_range, s_trunc, ellipsis);
1833 #[stable(feature = "core", since = "1.6.0")]
1834 impl StrExt for str {
1836 fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1837 pat.is_contained_in(self)
1841 fn chars(&self) -> Chars {
1842 Chars{iter: self.as_bytes().iter()}
1846 fn bytes(&self) -> Bytes {
1847 Bytes(self.as_bytes().iter().cloned())
1851 fn char_indices(&self) -> CharIndices {
1852 CharIndices { front_offset: 0, iter: self.chars() }
1856 fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1857 Split(SplitInternal {
1860 matcher: pat.into_searcher(self),
1861 allow_trailing_empty: true,
1867 fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1868 where P::Searcher: ReverseSearcher<'a>
1870 RSplit(self.split(pat).0)
1874 fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
1875 SplitN(SplitNInternal {
1876 iter: self.split(pat).0,
1882 fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
1883 where P::Searcher: ReverseSearcher<'a>
1885 RSplitN(self.splitn(count, pat).0)
1889 fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1890 SplitTerminator(SplitInternal {
1891 allow_trailing_empty: false,
1897 fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1898 where P::Searcher: ReverseSearcher<'a>
1900 RSplitTerminator(self.split_terminator(pat).0)
1904 fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1905 Matches(MatchesInternal(pat.into_searcher(self)))
1909 fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1910 where P::Searcher: ReverseSearcher<'a>
1912 RMatches(self.matches(pat).0)
1916 fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1917 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
1921 fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1922 where P::Searcher: ReverseSearcher<'a>
1924 RMatchIndices(self.match_indices(pat).0)
1927 fn lines(&self) -> Lines {
1928 Lines(self.split_terminator('\n').map(LinesAnyMap))
1932 #[allow(deprecated)]
1933 fn lines_any(&self) -> LinesAny {
1934 LinesAny(self.lines())
1938 unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
1939 let ptr = self.as_ptr().offset(begin as isize);
1940 let len = end - begin;
1941 from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1945 unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
1946 let ptr = self.as_ptr().offset(begin as isize);
1947 let len = end - begin;
1948 mem::transmute(slice::from_raw_parts_mut(ptr as *mut u8, len))
1952 fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1953 pat.is_prefix_of(self)
1957 fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
1958 where P::Searcher: ReverseSearcher<'a>
1960 pat.is_suffix_of(self)
1964 fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1965 where P::Searcher: DoubleEndedSearcher<'a>
1969 let mut matcher = pat.into_searcher(self);
1970 if let Some((a, b)) = matcher.next_reject() {
1972 j = b; // Remember earliest known match, correct it below if
1973 // last match is different
1975 if let Some((_, b)) = matcher.next_reject_back() {
1979 // Searcher is known to return valid indices
1980 self.slice_unchecked(i, j)
1985 fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1986 let mut i = self.len();
1987 let mut matcher = pat.into_searcher(self);
1988 if let Some((a, _)) = matcher.next_reject() {
1992 // Searcher is known to return valid indices
1993 self.slice_unchecked(i, self.len())
1998 fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1999 where P::Searcher: ReverseSearcher<'a>
2002 let mut matcher = pat.into_searcher(self);
2003 if let Some((_, b)) = matcher.next_reject_back() {
2007 // Searcher is known to return valid indices
2008 self.slice_unchecked(0, j)
2013 fn is_char_boundary(&self, index: usize) -> bool {
2014 // 0 and len are always ok.
2015 // Test for 0 explicitly so that it can optimize out the check
2016 // easily and skip reading string data for that case.
2017 if index == 0 || index == self.len() { return true; }
2018 match self.as_bytes().get(index) {
2020 // This is bit magic equivalent to: b < 128 || b >= 192
2021 Some(&b) => (b as i8) >= -0x40,
2026 fn as_bytes(&self) -> &[u8] {
2027 unsafe { mem::transmute(self) }
2030 fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2031 pat.into_searcher(self).next_match().map(|(i, _)| i)
2034 fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
2035 where P::Searcher: ReverseSearcher<'a>
2037 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
2040 fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2045 fn split_at(&self, mid: usize) -> (&str, &str) {
2046 // is_char_boundary checks that the index is in [0, .len()]
2047 if self.is_char_boundary(mid) {
2049 (self.slice_unchecked(0, mid),
2050 self.slice_unchecked(mid, self.len()))
2053 slice_error_fail(self, 0, mid)
2057 fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
2058 // is_char_boundary checks that the index is in [0, .len()]
2059 if self.is_char_boundary(mid) {
2060 let len = self.len();
2061 let ptr = self.as_ptr() as *mut u8;
2063 (from_raw_parts_mut(ptr, mid),
2064 from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
2067 slice_error_fail(self, 0, mid)
2072 fn as_ptr(&self) -> *const u8 {
2073 self as *const str as *const u8
2077 fn len(&self) -> usize {
2078 self.as_bytes().len()
2082 fn is_empty(&self) -> bool { self.len() == 0 }
2085 fn parse<'a, T>(&'a self) -> Result<T, T::Error> where T: TryFrom<&'a str> {
2090 #[stable(feature = "rust1", since = "1.0.0")]
2091 impl AsRef<[u8]> for str {
2093 fn as_ref(&self) -> &[u8] {
2098 #[stable(feature = "rust1", since = "1.0.0")]
2099 impl<'a> Default for &'a str {
2100 /// Creates an empty str
2101 fn default() -> &'a str { "" }