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};
24 use slice::{self, SliceIndex};
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
41 /// Basic implementation of `FromStr` on an example `Point` type:
44 /// use std::str::FromStr;
45 /// use std::num::ParseIntError;
47 /// #[derive(Debug, PartialEq)]
53 /// impl FromStr for Point {
54 /// type Err = ParseIntError;
56 /// fn from_str(s: &str) -> Result<Self, Self::Err> {
57 /// let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
61 /// let x_fromstr = coords[0].parse::<i32>()?;
62 /// let y_fromstr = coords[1].parse::<i32>()?;
64 /// Ok(Point { x: x_fromstr, y: y_fromstr })
68 /// let p = Point::from_str("(1,2)");
69 /// assert_eq!(p.unwrap(), Point{ x: 1, y: 2} )
71 #[stable(feature = "rust1", since = "1.0.0")]
72 pub trait FromStr: Sized {
73 /// The associated error which can be returned from parsing.
74 #[stable(feature = "rust1", since = "1.0.0")]
77 /// Parses a string `s` to return a value of this type.
79 /// If parsing succeeds, return the value inside `Ok`, otherwise
80 /// when the string is ill-formatted return an error specific to the
81 /// inside `Err`. The error type is specific to implementation of the trait.
85 /// Basic usage with [`i32`][ithirtytwo], a type that implements `FromStr`:
87 /// [ithirtytwo]: ../../std/primitive.i32.html
90 /// use std::str::FromStr;
93 /// let x = i32::from_str(s).unwrap();
97 #[stable(feature = "rust1", since = "1.0.0")]
98 fn from_str(s: &str) -> Result<Self, Self::Err>;
101 #[stable(feature = "rust1", since = "1.0.0")]
102 impl FromStr for bool {
103 type Err = ParseBoolError;
105 /// Parse a `bool` from a string.
107 /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
108 /// actually be parseable.
113 /// use std::str::FromStr;
115 /// assert_eq!(FromStr::from_str("true"), Ok(true));
116 /// assert_eq!(FromStr::from_str("false"), Ok(false));
117 /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
120 /// Note, in many cases, the `.parse()` method on `str` is more proper.
123 /// assert_eq!("true".parse(), Ok(true));
124 /// assert_eq!("false".parse(), Ok(false));
125 /// assert!("not even a boolean".parse::<bool>().is_err());
128 fn from_str(s: &str) -> Result<bool, ParseBoolError> {
131 "false" => Ok(false),
132 _ => Err(ParseBoolError { _priv: () }),
137 /// An error returned when parsing a `bool` using [`from_str`] fails
139 /// [`from_str`]: ../../std/primitive.bool.html#method.from_str
140 #[derive(Debug, Clone, PartialEq, Eq)]
141 #[stable(feature = "rust1", since = "1.0.0")]
142 pub struct ParseBoolError { _priv: () }
144 #[stable(feature = "rust1", since = "1.0.0")]
145 impl fmt::Display for ParseBoolError {
146 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
147 "provided string was not `true` or `false`".fmt(f)
152 Section: Creating a string
155 /// Errors which can occur when attempting to interpret a sequence of [`u8`]
158 /// [`u8`]: ../../std/primitive.u8.html
160 /// As such, the `from_utf8` family of functions and methods for both [`String`]s
161 /// and [`&str`]s make use of this error, for example.
163 /// [`String`]: ../../std/string/struct.String.html#method.from_utf8
164 /// [`&str`]: ../../std/str/fn.from_utf8.html
165 #[derive(Copy, Eq, PartialEq, Clone, Debug)]
166 #[stable(feature = "rust1", since = "1.0.0")]
167 pub struct Utf8Error {
169 error_len: Option<u8>,
173 /// Returns the index in the given string up to which valid UTF-8 was
176 /// It is the maximum index such that `from_utf8(&input[..index])`
177 /// would return `Ok(_)`.
186 /// // some invalid bytes, in a vector
187 /// let sparkle_heart = vec![0, 159, 146, 150];
189 /// // std::str::from_utf8 returns a Utf8Error
190 /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
192 /// // the second byte is invalid here
193 /// assert_eq!(1, error.valid_up_to());
195 #[stable(feature = "utf8_error", since = "1.5.0")]
196 pub fn valid_up_to(&self) -> usize { self.valid_up_to }
198 /// Provide more information about the failure:
200 /// * `None`: the end of the input was reached unexpectedly.
201 /// `self.valid_up_to()` is 1 to 3 bytes from the end of the input.
202 /// If a byte stream (such as a file or a network socket) is being decoded incrementally,
203 /// this could be a valid `char` whose UTF-8 byte sequence is spanning multiple chunks.
205 /// * `Some(len)`: an unexpected byte was encountered.
206 /// The length provided is that of the invalid byte sequence
207 /// that starts at the index given by `valid_up_to()`.
208 /// Decoding should resume after that sequence
209 /// (after inserting a U+FFFD REPLACEMENT CHARACTER) in case of lossy decoding.
210 #[unstable(feature = "utf8_error_error_len", reason ="new", issue = "40494")]
211 pub fn error_len(&self) -> Option<usize> {
212 self.error_len.map(|len| len as usize)
216 /// Converts a slice of bytes to a string slice.
218 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
219 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
220 /// the two. Not all byte slices are valid string slices, however: [`&str`] requires
221 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
222 /// UTF-8, and then does the conversion.
224 /// [`&str`]: ../../std/primitive.str.html
225 /// [`u8`]: ../../std/primitive.u8.html
226 /// [byteslice]: ../../std/primitive.slice.html
228 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
229 /// incur the overhead of the validity check, there is an unsafe version of
230 /// this function, [`from_utf8_unchecked`][fromutf8u], which has the same
231 /// behavior but skips the check.
233 /// [fromutf8u]: fn.from_utf8_unchecked.html
235 /// If you need a `String` instead of a `&str`, consider
236 /// [`String::from_utf8`][string].
238 /// [string]: ../../std/string/struct.String.html#method.from_utf8
240 /// Because you can stack-allocate a `[u8; N]`, and you can take a
241 /// [`&[u8]`][byteslice] of it, this function is one way to have a
242 /// stack-allocated string. There is an example of this in the
243 /// examples section below.
245 /// [byteslice]: ../../std/primitive.slice.html
249 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
250 /// provided slice is not UTF-8.
259 /// // some bytes, in a vector
260 /// let sparkle_heart = vec![240, 159, 146, 150];
262 /// // We know these bytes are valid, so just use `unwrap()`.
263 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
265 /// assert_eq!("💖", sparkle_heart);
273 /// // some invalid bytes, in a vector
274 /// let sparkle_heart = vec![0, 159, 146, 150];
276 /// assert!(str::from_utf8(&sparkle_heart).is_err());
279 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
280 /// errors that can be returned.
282 /// [error]: struct.Utf8Error.html
284 /// A "stack allocated string":
289 /// // some bytes, in a stack-allocated array
290 /// let sparkle_heart = [240, 159, 146, 150];
292 /// // We know these bytes are valid, so just use `unwrap()`.
293 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
295 /// assert_eq!("💖", sparkle_heart);
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
299 run_utf8_validation(v)?;
300 Ok(unsafe { from_utf8_unchecked(v) })
303 /// Converts a mutable slice of bytes to a mutable string slice.
304 #[unstable(feature = "str_mut_extras", issue = "41119")]
305 pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
306 run_utf8_validation(v)?;
307 Ok(unsafe { from_utf8_unchecked_mut(v) })
310 /// Forms a str from a pointer and a length.
312 /// The `len` argument is the number of bytes in the string.
316 /// This function is unsafe as there is no guarantee that the given pointer is
317 /// valid for `len` bytes, nor whether the lifetime inferred is a suitable
318 /// lifetime for the returned str.
320 /// The data must be valid UTF-8
322 /// `p` must be non-null, even for zero-length strs, because non-zero bits
323 /// are required to distinguish between a zero-length str within `Some()`
324 /// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
325 /// for zero-length strs, though.
329 /// The lifetime for the returned str is inferred from its usage. To
330 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
331 /// source lifetime is safe in the context, such as by providing a helper
332 /// function taking the lifetime of a host value for the str, or by explicit
334 /// Performs the same functionality as `from_raw_parts`, except that a mutable
337 unsafe fn from_raw_parts_mut<'a>(p: *mut u8, len: usize) -> &'a mut str {
338 from_utf8_unchecked_mut(slice::from_raw_parts_mut(p, len))
341 /// Converts a slice of bytes to a string slice without checking
342 /// that the string contains valid UTF-8.
344 /// See the safe version, [`from_utf8`][fromutf8], for more information.
346 /// [fromutf8]: fn.from_utf8.html
350 /// This function is unsafe because it does not check that the bytes passed to
351 /// it are valid UTF-8. If this constraint is violated, undefined behavior
352 /// results, as the rest of Rust assumes that [`&str`]s are valid UTF-8.
354 /// [`&str`]: ../../std/primitive.str.html
363 /// // some bytes, in a vector
364 /// let sparkle_heart = vec![240, 159, 146, 150];
366 /// let sparkle_heart = unsafe {
367 /// str::from_utf8_unchecked(&sparkle_heart)
370 /// assert_eq!("💖", sparkle_heart);
373 #[stable(feature = "rust1", since = "1.0.0")]
374 pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
378 /// Converts a slice of bytes to a string slice without checking
379 /// that the string contains valid UTF-8; mutable version.
381 /// See the immutable version, [`from_utf8_unchecked()`][fromutf8], for more information.
383 /// [fromutf8]: fn.from_utf8_unchecked.html
385 #[unstable(feature = "str_mut_extras", issue = "41119")]
386 pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
390 #[stable(feature = "rust1", since = "1.0.0")]
391 impl fmt::Display for Utf8Error {
392 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
393 if let Some(error_len) = self.error_len {
394 write!(f, "invalid utf-8 sequence of {} bytes from index {}",
395 error_len, self.valid_up_to)
397 write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to)
406 /// An iterator over the [`char`]s of a string slice.
408 /// [`char`]: ../../std/primitive.char.html
410 /// This struct is created by the [`chars`] method on [`str`].
411 /// See its documentation for more.
413 /// [`chars`]: ../../std/primitive.str.html#method.chars
414 /// [`str`]: ../../std/primitive.str.html
415 #[derive(Clone, Debug)]
416 #[stable(feature = "rust1", since = "1.0.0")]
417 pub struct Chars<'a> {
418 iter: slice::Iter<'a, u8>
421 /// Returns the initial codepoint accumulator for the first byte.
422 /// The first byte is special, only want bottom 5 bits for width 2, 4 bits
423 /// for width 3, and 3 bits for width 4.
425 fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
427 /// Returns the value of `ch` updated with continuation byte `byte`.
429 fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
431 /// Checks whether the byte is a UTF-8 continuation byte (i.e. starts with the
434 fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
437 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
444 /// Reads the next code point out of a byte iterator (assuming a
445 /// UTF-8-like encoding).
446 #[unstable(feature = "str_internals", issue = "0")]
448 pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
450 let x = match bytes.next() {
452 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
453 Some(&next_byte) => next_byte,
456 // Multibyte case follows
457 // Decode from a byte combination out of: [[[x y] z] w]
458 // NOTE: Performance is sensitive to the exact formulation here
459 let init = utf8_first_byte(x, 2);
460 let y = unwrap_or_0(bytes.next());
461 let mut ch = utf8_acc_cont_byte(init, y);
464 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
465 let z = unwrap_or_0(bytes.next());
466 let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
467 ch = init << 12 | y_z;
470 // use only the lower 3 bits of `init`
471 let w = unwrap_or_0(bytes.next());
472 ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
479 /// Reads the last code point out of a byte iterator (assuming a
480 /// UTF-8-like encoding).
482 fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
483 where I: DoubleEndedIterator<Item = &'a u8>,
486 let w = match bytes.next_back() {
488 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
489 Some(&back_byte) => back_byte,
492 // Multibyte case follows
493 // Decode from a byte combination out of: [x [y [z w]]]
495 let z = unwrap_or_0(bytes.next_back());
496 ch = utf8_first_byte(z, 2);
497 if utf8_is_cont_byte(z) {
498 let y = unwrap_or_0(bytes.next_back());
499 ch = utf8_first_byte(y, 3);
500 if utf8_is_cont_byte(y) {
501 let x = unwrap_or_0(bytes.next_back());
502 ch = utf8_first_byte(x, 4);
503 ch = utf8_acc_cont_byte(ch, y);
505 ch = utf8_acc_cont_byte(ch, z);
507 ch = utf8_acc_cont_byte(ch, w);
512 #[stable(feature = "rust1", since = "1.0.0")]
513 impl<'a> Iterator for Chars<'a> {
517 fn next(&mut self) -> Option<char> {
518 next_code_point(&mut self.iter).map(|ch| {
519 // str invariant says `ch` is a valid Unicode Scalar Value
521 char::from_u32_unchecked(ch)
527 fn count(self) -> usize {
528 // length in `char` is equal to the number of non-continuation bytes
529 let bytes_len = self.iter.len();
530 let mut cont_bytes = 0;
531 for &byte in self.iter {
532 cont_bytes += utf8_is_cont_byte(byte) as usize;
534 bytes_len - cont_bytes
538 fn size_hint(&self) -> (usize, Option<usize>) {
539 let len = self.iter.len();
540 // `(len + 3)` can't overflow, because we know that the `slice::Iter`
541 // belongs to a slice in memory which has a maximum length of
542 // `isize::MAX` (that's well below `usize::MAX`).
543 ((len + 3) / 4, Some(len))
547 fn last(mut self) -> Option<char> {
548 // No need to go through the entire string.
553 #[stable(feature = "rust1", since = "1.0.0")]
554 impl<'a> DoubleEndedIterator for Chars<'a> {
556 fn next_back(&mut self) -> Option<char> {
557 next_code_point_reverse(&mut self.iter).map(|ch| {
558 // str invariant says `ch` is a valid Unicode Scalar Value
560 char::from_u32_unchecked(ch)
566 #[unstable(feature = "fused", issue = "35602")]
567 impl<'a> FusedIterator for Chars<'a> {}
570 /// View the underlying data as a subslice of the original data.
572 /// This has the same lifetime as the original slice, and so the
573 /// iterator can continue to be used while this exists.
578 /// let mut chars = "abc".chars();
580 /// assert_eq!(chars.as_str(), "abc");
582 /// assert_eq!(chars.as_str(), "bc");
585 /// assert_eq!(chars.as_str(), "");
587 #[stable(feature = "iter_to_slice", since = "1.4.0")]
589 pub fn as_str(&self) -> &'a str {
590 unsafe { from_utf8_unchecked(self.iter.as_slice()) }
594 /// An iterator over the [`char`]s of a string slice, and their positions.
596 /// [`char`]: ../../std/primitive.char.html
598 /// This struct is created by the [`char_indices`] method on [`str`].
599 /// See its documentation for more.
601 /// [`char_indices`]: ../../std/primitive.str.html#method.char_indices
602 /// [`str`]: ../../std/primitive.str.html
603 #[derive(Clone, Debug)]
604 #[stable(feature = "rust1", since = "1.0.0")]
605 pub struct CharIndices<'a> {
610 #[stable(feature = "rust1", since = "1.0.0")]
611 impl<'a> Iterator for CharIndices<'a> {
612 type Item = (usize, char);
615 fn next(&mut self) -> Option<(usize, char)> {
616 let pre_len = self.iter.iter.len();
617 match self.iter.next() {
620 let index = self.front_offset;
621 let len = self.iter.iter.len();
622 self.front_offset += pre_len - len;
629 fn count(self) -> usize {
634 fn size_hint(&self) -> (usize, Option<usize>) {
635 self.iter.size_hint()
639 fn last(mut self) -> Option<(usize, char)> {
640 // No need to go through the entire string.
645 #[stable(feature = "rust1", since = "1.0.0")]
646 impl<'a> DoubleEndedIterator for CharIndices<'a> {
648 fn next_back(&mut self) -> Option<(usize, char)> {
649 match self.iter.next_back() {
652 let index = self.front_offset + self.iter.iter.len();
659 #[unstable(feature = "fused", issue = "35602")]
660 impl<'a> FusedIterator for CharIndices<'a> {}
662 impl<'a> CharIndices<'a> {
663 /// View the underlying data as a subslice of the original data.
665 /// This has the same lifetime as the original slice, and so the
666 /// iterator can continue to be used while this exists.
667 #[stable(feature = "iter_to_slice", since = "1.4.0")]
669 pub fn as_str(&self) -> &'a str {
674 /// An iterator over the bytes of a string slice.
676 /// This struct is created by the [`bytes`] method on [`str`].
677 /// See its documentation for more.
679 /// [`bytes`]: ../../std/primitive.str.html#method.bytes
680 /// [`str`]: ../../std/primitive.str.html
681 #[stable(feature = "rust1", since = "1.0.0")]
682 #[derive(Clone, Debug)]
683 pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>);
685 #[stable(feature = "rust1", since = "1.0.0")]
686 impl<'a> Iterator for Bytes<'a> {
690 fn next(&mut self) -> Option<u8> {
695 fn size_hint(&self) -> (usize, Option<usize>) {
700 fn count(self) -> usize {
705 fn last(self) -> Option<Self::Item> {
710 fn nth(&mut self, n: usize) -> Option<Self::Item> {
715 #[stable(feature = "rust1", since = "1.0.0")]
716 impl<'a> DoubleEndedIterator for Bytes<'a> {
718 fn next_back(&mut self) -> Option<u8> {
723 #[stable(feature = "rust1", since = "1.0.0")]
724 impl<'a> ExactSizeIterator for Bytes<'a> {
726 fn len(&self) -> usize {
731 fn is_empty(&self) -> bool {
736 #[unstable(feature = "fused", issue = "35602")]
737 impl<'a> FusedIterator for Bytes<'a> {}
739 /// This macro generates a Clone impl for string pattern API
740 /// wrapper types of the form X<'a, P>
741 macro_rules! derive_pattern_clone {
742 (clone $t:ident with |$s:ident| $e:expr) => {
743 impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
744 where P::Searcher: Clone
746 fn clone(&self) -> Self {
754 /// This macro generates two public iterator structs
755 /// wrapping a private internal one that makes use of the `Pattern` API.
757 /// For all patterns `P: Pattern<'a>` the following items will be
758 /// generated (generics omitted):
760 /// struct $forward_iterator($internal_iterator);
761 /// struct $reverse_iterator($internal_iterator);
763 /// impl Iterator for $forward_iterator
764 /// { /* internal ends up calling Searcher::next_match() */ }
766 /// impl DoubleEndedIterator for $forward_iterator
767 /// where P::Searcher: DoubleEndedSearcher
768 /// { /* internal ends up calling Searcher::next_match_back() */ }
770 /// impl Iterator for $reverse_iterator
771 /// where P::Searcher: ReverseSearcher
772 /// { /* internal ends up calling Searcher::next_match_back() */ }
774 /// impl DoubleEndedIterator for $reverse_iterator
775 /// where P::Searcher: DoubleEndedSearcher
776 /// { /* internal ends up calling Searcher::next_match() */ }
778 /// The internal one is defined outside the macro, and has almost the same
779 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
780 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
782 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
783 /// `Pattern` might not return the same elements, so actually implementing
784 /// `DoubleEndedIterator` for it would be incorrect.
785 /// (See the docs in `str::pattern` for more details)
787 /// However, the internal struct still represents a single ended iterator from
788 /// either end, and depending on pattern is also a valid double ended iterator,
789 /// so the two wrapper structs implement `Iterator`
790 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
791 /// to the complex impls seen above.
792 macro_rules! generate_pattern_iterators {
796 $(#[$forward_iterator_attribute:meta])*
797 struct $forward_iterator:ident;
801 $(#[$reverse_iterator_attribute:meta])*
802 struct $reverse_iterator:ident;
804 // Stability of all generated items
806 $(#[$common_stability_attribute:meta])*
808 // Internal almost-iterator that is being delegated to
810 $internal_iterator:ident yielding ($iterty:ty);
812 // Kind of delgation - either single ended or double ended
815 $(#[$forward_iterator_attribute])*
816 $(#[$common_stability_attribute])*
817 pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
819 $(#[$common_stability_attribute])*
820 impl<'a, P: Pattern<'a>> fmt::Debug for $forward_iterator<'a, P>
821 where P::Searcher: fmt::Debug
823 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
824 f.debug_tuple(stringify!($forward_iterator))
830 $(#[$common_stability_attribute])*
831 impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
835 fn next(&mut self) -> Option<$iterty> {
840 $(#[$common_stability_attribute])*
841 impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
842 where P::Searcher: Clone
844 fn clone(&self) -> Self {
845 $forward_iterator(self.0.clone())
849 $(#[$reverse_iterator_attribute])*
850 $(#[$common_stability_attribute])*
851 pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
853 $(#[$common_stability_attribute])*
854 impl<'a, P: Pattern<'a>> fmt::Debug for $reverse_iterator<'a, P>
855 where P::Searcher: fmt::Debug
857 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
858 f.debug_tuple(stringify!($reverse_iterator))
864 $(#[$common_stability_attribute])*
865 impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
866 where P::Searcher: ReverseSearcher<'a>
871 fn next(&mut self) -> Option<$iterty> {
876 $(#[$common_stability_attribute])*
877 impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
878 where P::Searcher: Clone
880 fn clone(&self) -> Self {
881 $reverse_iterator(self.0.clone())
885 #[unstable(feature = "fused", issue = "35602")]
886 impl<'a, P: Pattern<'a>> FusedIterator for $forward_iterator<'a, P> {}
888 #[unstable(feature = "fused", issue = "35602")]
889 impl<'a, P: Pattern<'a>> FusedIterator for $reverse_iterator<'a, P>
890 where P::Searcher: ReverseSearcher<'a> {}
892 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
894 $reverse_iterator, $iterty);
897 double ended; with $(#[$common_stability_attribute:meta])*,
898 $forward_iterator:ident,
899 $reverse_iterator:ident, $iterty:ty
901 $(#[$common_stability_attribute])*
902 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
903 where P::Searcher: DoubleEndedSearcher<'a>
906 fn next_back(&mut self) -> Option<$iterty> {
911 $(#[$common_stability_attribute])*
912 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
913 where P::Searcher: DoubleEndedSearcher<'a>
916 fn next_back(&mut self) -> Option<$iterty> {
922 single ended; with $(#[$common_stability_attribute:meta])*,
923 $forward_iterator:ident,
924 $reverse_iterator:ident, $iterty:ty
928 derive_pattern_clone!{
930 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
933 struct SplitInternal<'a, P: Pattern<'a>> {
936 matcher: P::Searcher,
937 allow_trailing_empty: bool,
941 impl<'a, P: Pattern<'a>> fmt::Debug for SplitInternal<'a, P> where P::Searcher: fmt::Debug {
942 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
943 f.debug_struct("SplitInternal")
944 .field("start", &self.start)
945 .field("end", &self.end)
946 .field("matcher", &self.matcher)
947 .field("allow_trailing_empty", &self.allow_trailing_empty)
948 .field("finished", &self.finished)
953 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
955 fn get_end(&mut self) -> Option<&'a str> {
956 if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
957 self.finished = true;
959 let string = self.matcher.haystack().slice_unchecked(self.start, self.end);
968 fn next(&mut self) -> Option<&'a str> {
969 if self.finished { return None }
971 let haystack = self.matcher.haystack();
972 match self.matcher.next_match() {
973 Some((a, b)) => unsafe {
974 let elt = haystack.slice_unchecked(self.start, a);
978 None => self.get_end(),
983 fn next_back(&mut self) -> Option<&'a str>
984 where P::Searcher: ReverseSearcher<'a>
986 if self.finished { return None }
988 if !self.allow_trailing_empty {
989 self.allow_trailing_empty = true;
990 match self.next_back() {
991 Some(elt) if !elt.is_empty() => return Some(elt),
992 _ => if self.finished { return None }
996 let haystack = self.matcher.haystack();
997 match self.matcher.next_match_back() {
998 Some((a, b)) => unsafe {
999 let elt = haystack.slice_unchecked(b, self.end);
1004 self.finished = true;
1005 Some(haystack.slice_unchecked(self.start, self.end))
1011 generate_pattern_iterators! {
1013 /// Created with the method [`split`].
1015 /// [`split`]: ../../std/primitive.str.html#method.split
1018 /// Created with the method [`rsplit`].
1020 /// [`rsplit`]: ../../std/primitive.str.html#method.rsplit
1023 #[stable(feature = "rust1", since = "1.0.0")]
1025 SplitInternal yielding (&'a str);
1026 delegate double ended;
1029 generate_pattern_iterators! {
1031 /// Created with the method [`split_terminator`].
1033 /// [`split_terminator`]: ../../std/primitive.str.html#method.split_terminator
1034 struct SplitTerminator;
1036 /// Created with the method [`rsplit_terminator`].
1038 /// [`rsplit_terminator`]: ../../std/primitive.str.html#method.rsplit_terminator
1039 struct RSplitTerminator;
1041 #[stable(feature = "rust1", since = "1.0.0")]
1043 SplitInternal yielding (&'a str);
1044 delegate double ended;
1047 derive_pattern_clone!{
1048 clone SplitNInternal
1049 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
1052 struct SplitNInternal<'a, P: Pattern<'a>> {
1053 iter: SplitInternal<'a, P>,
1054 /// The number of splits remaining
1058 impl<'a, P: Pattern<'a>> fmt::Debug for SplitNInternal<'a, P> where P::Searcher: fmt::Debug {
1059 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1060 f.debug_struct("SplitNInternal")
1061 .field("iter", &self.iter)
1062 .field("count", &self.count)
1067 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
1069 fn next(&mut self) -> Option<&'a str> {
1072 1 => { self.count = 0; self.iter.get_end() }
1073 _ => { self.count -= 1; self.iter.next() }
1078 fn next_back(&mut self) -> Option<&'a str>
1079 where P::Searcher: ReverseSearcher<'a>
1083 1 => { self.count = 0; self.iter.get_end() }
1084 _ => { self.count -= 1; self.iter.next_back() }
1089 generate_pattern_iterators! {
1091 /// Created with the method [`splitn`].
1093 /// [`splitn`]: ../../std/primitive.str.html#method.splitn
1096 /// Created with the method [`rsplitn`].
1098 /// [`rsplitn`]: ../../std/primitive.str.html#method.rsplitn
1101 #[stable(feature = "rust1", since = "1.0.0")]
1103 SplitNInternal yielding (&'a str);
1104 delegate single ended;
1107 derive_pattern_clone!{
1108 clone MatchIndicesInternal
1109 with |s| MatchIndicesInternal(s.0.clone())
1112 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
1114 impl<'a, P: Pattern<'a>> fmt::Debug for MatchIndicesInternal<'a, P> where P::Searcher: fmt::Debug {
1115 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1116 f.debug_tuple("MatchIndicesInternal")
1122 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
1124 fn next(&mut self) -> Option<(usize, &'a str)> {
1125 self.0.next_match().map(|(start, end)| unsafe {
1126 (start, self.0.haystack().slice_unchecked(start, end))
1131 fn next_back(&mut self) -> Option<(usize, &'a str)>
1132 where P::Searcher: ReverseSearcher<'a>
1134 self.0.next_match_back().map(|(start, end)| unsafe {
1135 (start, self.0.haystack().slice_unchecked(start, end))
1140 generate_pattern_iterators! {
1142 /// Created with the method [`match_indices`].
1144 /// [`match_indices`]: ../../std/primitive.str.html#method.match_indices
1145 struct MatchIndices;
1147 /// Created with the method [`rmatch_indices`].
1149 /// [`rmatch_indices`]: ../../std/primitive.str.html#method.rmatch_indices
1150 struct RMatchIndices;
1152 #[stable(feature = "str_match_indices", since = "1.5.0")]
1154 MatchIndicesInternal yielding ((usize, &'a str));
1155 delegate double ended;
1158 derive_pattern_clone!{
1159 clone MatchesInternal
1160 with |s| MatchesInternal(s.0.clone())
1163 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
1165 impl<'a, P: Pattern<'a>> fmt::Debug for MatchesInternal<'a, P> where P::Searcher: fmt::Debug {
1166 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1167 f.debug_tuple("MatchesInternal")
1173 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
1175 fn next(&mut self) -> Option<&'a str> {
1176 self.0.next_match().map(|(a, b)| unsafe {
1177 // Indices are known to be on utf8 boundaries
1178 self.0.haystack().slice_unchecked(a, b)
1183 fn next_back(&mut self) -> Option<&'a str>
1184 where P::Searcher: ReverseSearcher<'a>
1186 self.0.next_match_back().map(|(a, b)| unsafe {
1187 // Indices are known to be on utf8 boundaries
1188 self.0.haystack().slice_unchecked(a, b)
1193 generate_pattern_iterators! {
1195 /// Created with the method [`matches`].
1197 /// [`matches`]: ../../std/primitive.str.html#method.matches
1200 /// Created with the method [`rmatches`].
1202 /// [`rmatches`]: ../../std/primitive.str.html#method.rmatches
1205 #[stable(feature = "str_matches", since = "1.2.0")]
1207 MatchesInternal yielding (&'a str);
1208 delegate double ended;
1211 /// An iterator over the lines of a string, as string slices.
1213 /// This struct is created with the [`lines`] method on [`str`].
1214 /// See its documentation for more.
1216 /// [`lines`]: ../../std/primitive.str.html#method.lines
1217 /// [`str`]: ../../std/primitive.str.html
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 #[derive(Clone, Debug)]
1220 pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>);
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 impl<'a> Iterator for Lines<'a> {
1224 type Item = &'a str;
1227 fn next(&mut self) -> Option<&'a str> {
1232 fn size_hint(&self) -> (usize, Option<usize>) {
1237 #[stable(feature = "rust1", since = "1.0.0")]
1238 impl<'a> DoubleEndedIterator for Lines<'a> {
1240 fn next_back(&mut self) -> Option<&'a str> {
1245 #[unstable(feature = "fused", issue = "35602")]
1246 impl<'a> FusedIterator for Lines<'a> {}
1248 /// Created with the method [`lines_any`].
1250 /// [`lines_any`]: ../../std/primitive.str.html#method.lines_any
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 #[rustc_deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")]
1253 #[derive(Clone, Debug)]
1254 #[allow(deprecated)]
1255 pub struct LinesAny<'a>(Lines<'a>);
1257 /// A nameable, cloneable fn type
1261 impl<'a> Fn<(&'a str,)> for LinesAnyMap {
1263 extern "rust-call" fn call(&self, (line,): (&'a str,)) -> &'a str {
1265 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
1270 impl<'a> FnMut<(&'a str,)> for LinesAnyMap {
1272 extern "rust-call" fn call_mut(&mut self, (line,): (&'a str,)) -> &'a str {
1273 Fn::call(&*self, (line,))
1277 impl<'a> FnOnce<(&'a str,)> for LinesAnyMap {
1278 type Output = &'a str;
1281 extern "rust-call" fn call_once(self, (line,): (&'a str,)) -> &'a str {
1282 Fn::call(&self, (line,))
1286 #[stable(feature = "rust1", since = "1.0.0")]
1287 #[allow(deprecated)]
1288 impl<'a> Iterator for LinesAny<'a> {
1289 type Item = &'a str;
1292 fn next(&mut self) -> Option<&'a str> {
1297 fn size_hint(&self) -> (usize, Option<usize>) {
1302 #[stable(feature = "rust1", since = "1.0.0")]
1303 #[allow(deprecated)]
1304 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1306 fn next_back(&mut self) -> Option<&'a str> {
1311 #[unstable(feature = "fused", issue = "35602")]
1312 #[allow(deprecated)]
1313 impl<'a> FusedIterator for LinesAny<'a> {}
1316 Section: Comparing strings
1319 /// Bytewise slice equality
1320 /// NOTE: This function is (ab)used in rustc::middle::trans::_match
1321 /// to compare &[u8] byte slices that are not necessarily valid UTF-8.
1324 fn eq_slice(a: &str, b: &str) -> bool {
1325 a.as_bytes() == b.as_bytes()
1329 Section: UTF-8 validation
1332 // use truncation to fit u64 into usize
1333 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
1335 /// Returns `true` if any byte in the word `x` is nonascii (>= 128).
1337 fn contains_nonascii(x: usize) -> bool {
1338 (x & NONASCII_MASK) != 0
1341 /// Walks through `iter` checking that it's a valid UTF-8 sequence,
1342 /// returning `true` in that case, or, if it is invalid, `false` with
1343 /// `iter` reset such that it is pointing at the first byte in the
1344 /// invalid sequence.
1346 fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
1350 let usize_bytes = mem::size_of::<usize>();
1351 let ascii_block_size = 2 * usize_bytes;
1352 let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
1355 let old_offset = index;
1357 ($error_len: expr) => {
1358 return Err(Utf8Error {
1359 valid_up_to: old_offset,
1360 error_len: $error_len,
1365 macro_rules! next { () => {{
1367 // we needed data, but there was none: error!
1374 let first = v[index];
1376 let w = UTF8_CHAR_WIDTH[first as usize];
1377 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
1378 // first C2 80 last DF BF
1379 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
1380 // first E0 A0 80 last EF BF BF
1381 // excluding surrogates codepoints \u{d800} to \u{dfff}
1382 // ED A0 80 to ED BF BF
1383 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1384 // first F0 90 80 80 last F4 8F BF BF
1386 // Use the UTF-8 syntax from the RFC
1388 // https://tools.ietf.org/html/rfc3629
1390 // UTF8-2 = %xC2-DF UTF8-tail
1391 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1392 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1393 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1394 // %xF4 %x80-8F 2( UTF8-tail )
1396 2 => if next!() & !CONT_MASK != TAG_CONT_U8 {
1400 match (first, next!()) {
1401 (0xE0 , 0xA0 ... 0xBF) |
1402 (0xE1 ... 0xEC, 0x80 ... 0xBF) |
1403 (0xED , 0x80 ... 0x9F) |
1404 (0xEE ... 0xEF, 0x80 ... 0xBF) => {}
1407 if next!() & !CONT_MASK != TAG_CONT_U8 {
1412 match (first, next!()) {
1413 (0xF0 , 0x90 ... 0xBF) |
1414 (0xF1 ... 0xF3, 0x80 ... 0xBF) |
1415 (0xF4 , 0x80 ... 0x8F) => {}
1418 if next!() & !CONT_MASK != TAG_CONT_U8 {
1421 if next!() & !CONT_MASK != TAG_CONT_U8 {
1429 // Ascii case, try to skip forward quickly.
1430 // When the pointer is aligned, read 2 words of data per iteration
1431 // until we find a word containing a non-ascii byte.
1432 let ptr = v.as_ptr();
1433 let align = (ptr as usize + index) & (usize_bytes - 1);
1435 while index < blocks_end {
1437 let block = ptr.offset(index as isize) as *const usize;
1438 // break if there is a nonascii byte
1439 let zu = contains_nonascii(*block);
1440 let zv = contains_nonascii(*block.offset(1));
1445 index += ascii_block_size;
1447 // step from the point where the wordwise loop stopped
1448 while index < len && v[index] < 128 {
1460 // https://tools.ietf.org/html/rfc3629
1461 static UTF8_CHAR_WIDTH: [u8; 256] = [
1462 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1463 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1464 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1465 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1466 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1467 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1468 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1469 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1470 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1471 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1472 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1473 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1474 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1475 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1476 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1477 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1480 /// Given a first byte, determines how many bytes are in this UTF-8 character.
1481 #[unstable(feature = "str_internals", issue = "0")]
1483 pub fn utf8_char_width(b: u8) -> usize {
1484 return UTF8_CHAR_WIDTH[b as usize] as usize;
1487 /// Mask of the value bits of a continuation byte.
1488 const CONT_MASK: u8 = 0b0011_1111;
1489 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte.
1490 const TAG_CONT_U8: u8 = 0b1000_0000;
1493 Section: Trait implementations
1499 use slice::{self, SliceIndex};
1502 /// Implements ordering of strings.
1504 /// Strings are ordered lexicographically by their byte values. This orders Unicode code
1505 /// points based on their positions in the code charts. This is not necessarily the same as
1506 /// "alphabetical" order, which varies by language and locale. Sorting strings according to
1507 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1509 #[stable(feature = "rust1", since = "1.0.0")]
1512 fn cmp(&self, other: &str) -> Ordering {
1513 self.as_bytes().cmp(other.as_bytes())
1517 #[stable(feature = "rust1", since = "1.0.0")]
1518 impl PartialEq for str {
1520 fn eq(&self, other: &str) -> bool {
1521 eq_slice(self, other)
1524 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1527 #[stable(feature = "rust1", since = "1.0.0")]
1530 /// Implements comparison operations on strings.
1532 /// Strings are compared lexicographically by their byte values. This compares Unicode code
1533 /// points based on their positions in the code charts. This is not necessarily the same as
1534 /// "alphabetical" order, which varies by language and locale. Comparing strings according to
1535 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1537 #[stable(feature = "rust1", since = "1.0.0")]
1538 impl PartialOrd for str {
1540 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1541 Some(self.cmp(other))
1545 /// Implements substring slicing with syntax `&self[begin .. end]`.
1547 /// Returns a slice of the given string from the byte range
1548 /// [`begin`..`end`).
1550 /// This operation is `O(1)`.
1554 /// Panics if `begin` or `end` does not point to the starting
1555 /// byte offset of a character (as defined by `is_char_boundary`).
1556 /// Requires that `begin <= end` and `end <= len` where `len` is the
1557 /// length of the string.
1562 /// let s = "Löwe 老虎 Léopard";
1563 /// assert_eq!(&s[0 .. 1], "L");
1565 /// assert_eq!(&s[1 .. 9], "öwe 老");
1567 /// // these will panic:
1568 /// // byte 2 lies within `ö`:
1571 /// // byte 8 lies within `老`
1574 /// // byte 100 is outside the string
1575 /// // &s[3 .. 100];
1577 #[stable(feature = "rust1", since = "1.0.0")]
1578 impl ops::Index<ops::Range<usize>> for str {
1581 fn index(&self, index: ops::Range<usize>) -> &str {
1586 /// Implements mutable substring slicing with syntax
1587 /// `&mut self[begin .. end]`.
1589 /// Returns a mutable slice of the given string from the byte range
1590 /// [`begin`..`end`).
1592 /// This operation is `O(1)`.
1596 /// Panics if `begin` or `end` does not point to the starting
1597 /// byte offset of a character (as defined by `is_char_boundary`).
1598 /// Requires that `begin <= end` and `end <= len` where `len` is the
1599 /// length of the string.
1600 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1601 impl ops::IndexMut<ops::Range<usize>> for str {
1603 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1604 index.index_mut(self)
1608 /// Implements substring slicing with syntax `&self[.. end]`.
1610 /// Returns a slice of the string from the beginning to byte offset
1613 /// Equivalent to `&self[0 .. end]`.
1614 #[stable(feature = "rust1", since = "1.0.0")]
1615 impl ops::Index<ops::RangeTo<usize>> for str {
1619 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1624 /// Implements mutable substring slicing with syntax `&mut self[.. end]`.
1626 /// Returns a mutable slice of the string from the beginning to byte offset
1629 /// Equivalent to `&mut self[0 .. end]`.
1630 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1631 impl ops::IndexMut<ops::RangeTo<usize>> for str {
1633 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1634 index.index_mut(self)
1638 /// Implements substring slicing with syntax `&self[begin ..]`.
1640 /// Returns a slice of the string from byte offset `begin`
1641 /// to the end of the string.
1643 /// Equivalent to `&self[begin .. len]`.
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 impl ops::Index<ops::RangeFrom<usize>> for str {
1649 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1654 /// Implements mutable substring slicing with syntax `&mut self[begin ..]`.
1656 /// Returns a mutable slice of the string from byte offset `begin`
1657 /// to the end of the string.
1659 /// Equivalent to `&mut self[begin .. len]`.
1660 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1661 impl ops::IndexMut<ops::RangeFrom<usize>> for str {
1663 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1664 index.index_mut(self)
1668 /// Implements substring slicing with syntax `&self[..]`.
1670 /// Returns a slice of the whole string. This operation can
1673 /// Equivalent to `&self[0 .. len]`.
1674 #[stable(feature = "rust1", since = "1.0.0")]
1675 impl ops::Index<ops::RangeFull> for str {
1679 fn index(&self, _index: ops::RangeFull) -> &str {
1684 /// Implements mutable substring slicing with syntax `&mut self[..]`.
1686 /// Returns a mutable slice of the whole string. This operation can
1689 /// Equivalent to `&mut self[0 .. len]`.
1690 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1691 impl ops::IndexMut<ops::RangeFull> for str {
1693 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1698 #[unstable(feature = "inclusive_range",
1699 reason = "recently added, follows RFC",
1701 impl ops::Index<ops::RangeInclusive<usize>> for str {
1705 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1710 #[unstable(feature = "inclusive_range",
1711 reason = "recently added, follows RFC",
1713 impl ops::Index<ops::RangeToInclusive<usize>> for str {
1717 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1722 #[unstable(feature = "inclusive_range",
1723 reason = "recently added, follows RFC",
1725 impl ops::IndexMut<ops::RangeInclusive<usize>> for str {
1727 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1728 index.index_mut(self)
1731 #[unstable(feature = "inclusive_range",
1732 reason = "recently added, follows RFC",
1734 impl ops::IndexMut<ops::RangeToInclusive<usize>> for str {
1736 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1737 index.index_mut(self)
1741 #[unstable(feature = "str_checked_slicing", issue = "39932")]
1742 impl SliceIndex<str> for ops::RangeFull {
1745 fn get(self, slice: &str) -> Option<&Self::Output> {
1749 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1753 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1757 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1761 fn index(self, slice: &str) -> &Self::Output {
1765 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1770 #[unstable(feature = "str_checked_slicing", issue = "39932")]
1771 impl SliceIndex<str> for ops::Range<usize> {
1774 fn get(self, slice: &str) -> Option<&Self::Output> {
1775 if self.start <= self.end &&
1776 slice.is_char_boundary(self.start) &&
1777 slice.is_char_boundary(self.end) {
1778 Some(unsafe { self.get_unchecked(slice) })
1784 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1785 if self.start <= self.end &&
1786 slice.is_char_boundary(self.start) &&
1787 slice.is_char_boundary(self.end) {
1788 Some(unsafe { self.get_unchecked_mut(slice) })
1794 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1795 let ptr = slice.as_ptr().offset(self.start as isize);
1796 let len = self.end - self.start;
1797 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1800 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1801 let ptr = slice.as_ptr().offset(self.start as isize);
1802 let len = self.end - self.start;
1803 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1806 fn index(self, slice: &str) -> &Self::Output {
1807 let (start, end) = (self.start, self.end);
1808 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1811 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1812 // is_char_boundary checks that the index is in [0, .len()]
1813 // canot reuse `get` as above, because of NLL trouble
1814 if self.start <= self.end &&
1815 slice.is_char_boundary(self.start) &&
1816 slice.is_char_boundary(self.end) {
1817 unsafe { self.get_unchecked_mut(slice) }
1819 super::slice_error_fail(slice, self.start, self.end)
1824 #[unstable(feature = "str_checked_slicing", issue = "39932")]
1825 impl SliceIndex<str> for ops::RangeTo<usize> {
1828 fn get(self, slice: &str) -> Option<&Self::Output> {
1829 if slice.is_char_boundary(self.end) {
1830 Some(unsafe { self.get_unchecked(slice) })
1836 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1837 if slice.is_char_boundary(self.end) {
1838 Some(unsafe { self.get_unchecked_mut(slice) })
1844 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1845 let ptr = slice.as_ptr();
1846 super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end))
1849 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1850 let ptr = slice.as_ptr();
1851 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, self.end))
1854 fn index(self, slice: &str) -> &Self::Output {
1856 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end))
1859 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1860 // is_char_boundary checks that the index is in [0, .len()]
1861 if slice.is_char_boundary(self.end) {
1862 unsafe { self.get_unchecked_mut(slice) }
1864 super::slice_error_fail(slice, 0, self.end)
1869 #[unstable(feature = "str_checked_slicing", issue = "39932")]
1870 impl SliceIndex<str> for ops::RangeFrom<usize> {
1873 fn get(self, slice: &str) -> Option<&Self::Output> {
1874 if slice.is_char_boundary(self.start) {
1875 Some(unsafe { self.get_unchecked(slice) })
1881 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1882 if slice.is_char_boundary(self.start) {
1883 Some(unsafe { self.get_unchecked_mut(slice) })
1889 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1890 let ptr = slice.as_ptr().offset(self.start as isize);
1891 let len = slice.len() - self.start;
1892 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1895 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1896 let ptr = slice.as_ptr().offset(self.start as isize);
1897 let len = slice.len() - self.start;
1898 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1901 fn index(self, slice: &str) -> &Self::Output {
1902 let (start, end) = (self.start, slice.len());
1903 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1906 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1907 // is_char_boundary checks that the index is in [0, .len()]
1908 if slice.is_char_boundary(self.start) {
1909 unsafe { self.get_unchecked_mut(slice) }
1911 super::slice_error_fail(slice, self.start, slice.len())
1916 #[unstable(feature = "str_checked_slicing", issue = "39932")]
1917 impl SliceIndex<str> for ops::RangeInclusive<usize> {
1920 fn get(self, slice: &str) -> Option<&Self::Output> {
1921 if let Some(end) = self.end.checked_add(1) {
1922 (self.start..end).get(slice)
1928 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1929 if let Some(end) = self.end.checked_add(1) {
1930 (self.start..end).get_mut(slice)
1936 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1937 (self.start..self.end+1).get_unchecked(slice)
1940 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1941 (self.start..self.end+1).get_unchecked_mut(slice)
1944 fn index(self, slice: &str) -> &Self::Output {
1945 assert!(self.end != usize::max_value(),
1946 "attempted to index str up to maximum usize");
1947 (self.start..self.end+1).index(slice)
1950 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1951 assert!(self.end != usize::max_value(),
1952 "attempted to index str up to maximum usize");
1953 (self.start..self.end+1).index_mut(slice)
1959 #[unstable(feature = "str_checked_slicing", issue = "39932")]
1960 impl SliceIndex<str> for ops::RangeToInclusive<usize> {
1963 fn get(self, slice: &str) -> Option<&Self::Output> {
1964 if self.end < usize::max_value() && slice.is_char_boundary(self.end + 1) {
1965 Some(unsafe { self.get_unchecked(slice) })
1971 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1972 if self.end < usize::max_value() && slice.is_char_boundary(self.end + 1) {
1973 Some(unsafe { self.get_unchecked_mut(slice) })
1979 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1980 let ptr = slice.as_ptr();
1981 super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end + 1))
1984 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1985 let ptr = slice.as_ptr();
1986 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, self.end + 1))
1989 fn index(self, slice: &str) -> &Self::Output {
1990 assert!(self.end != usize::max_value(),
1991 "attempted to index str up to maximum usize");
1992 let end = self.end + 1;
1993 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end))
1996 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1997 assert!(self.end != usize::max_value(),
1998 "attempted to index str up to maximum usize");
1999 if slice.is_char_boundary(self.end) {
2000 unsafe { self.get_unchecked_mut(slice) }
2002 super::slice_error_fail(slice, 0, self.end + 1)
2010 /// Methods for string slices
2011 #[allow(missing_docs)]
2013 #[unstable(feature = "core_str_ext",
2014 reason = "stable interface provided by `impl str` in later crates",
2017 // NB there are no docs here are they're all located on the StrExt trait in
2018 // libcollections, not here.
2020 #[stable(feature = "core", since = "1.6.0")]
2021 fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
2022 #[stable(feature = "core", since = "1.6.0")]
2023 fn chars(&self) -> Chars;
2024 #[stable(feature = "core", since = "1.6.0")]
2025 fn bytes(&self) -> Bytes;
2026 #[stable(feature = "core", since = "1.6.0")]
2027 fn char_indices(&self) -> CharIndices;
2028 #[stable(feature = "core", since = "1.6.0")]
2029 fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P>;
2030 #[stable(feature = "core", since = "1.6.0")]
2031 fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
2032 where P::Searcher: ReverseSearcher<'a>;
2033 #[stable(feature = "core", since = "1.6.0")]
2034 fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P>;
2035 #[stable(feature = "core", since = "1.6.0")]
2036 fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
2037 where P::Searcher: ReverseSearcher<'a>;
2038 #[stable(feature = "core", since = "1.6.0")]
2039 fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P>;
2040 #[stable(feature = "core", since = "1.6.0")]
2041 fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
2042 where P::Searcher: ReverseSearcher<'a>;
2043 #[stable(feature = "core", since = "1.6.0")]
2044 fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P>;
2045 #[stable(feature = "core", since = "1.6.0")]
2046 fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
2047 where P::Searcher: ReverseSearcher<'a>;
2048 #[stable(feature = "core", since = "1.6.0")]
2049 fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P>;
2050 #[stable(feature = "core", since = "1.6.0")]
2051 fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
2052 where P::Searcher: ReverseSearcher<'a>;
2053 #[stable(feature = "core", since = "1.6.0")]
2054 fn lines(&self) -> Lines;
2055 #[stable(feature = "core", since = "1.6.0")]
2056 #[rustc_deprecated(since = "1.6.0", reason = "use lines() instead now")]
2057 #[allow(deprecated)]
2058 fn lines_any(&self) -> LinesAny;
2059 #[unstable(feature = "str_checked_slicing", issue = "39932")]
2060 fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output>;
2061 #[unstable(feature = "str_checked_slicing", issue = "39932")]
2062 fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output>;
2063 #[unstable(feature = "str_checked_slicing", issue = "39932")]
2064 unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output;
2065 #[unstable(feature = "str_checked_slicing", issue = "39932")]
2066 unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output;
2067 #[stable(feature = "core", since = "1.6.0")]
2068 unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str;
2069 #[stable(feature = "core", since = "1.6.0")]
2070 unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str;
2071 #[stable(feature = "core", since = "1.6.0")]
2072 fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
2073 #[stable(feature = "core", since = "1.6.0")]
2074 fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
2075 where P::Searcher: ReverseSearcher<'a>;
2076 #[stable(feature = "core", since = "1.6.0")]
2077 fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
2078 where P::Searcher: DoubleEndedSearcher<'a>;
2079 #[stable(feature = "core", since = "1.6.0")]
2080 fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str;
2081 #[stable(feature = "core", since = "1.6.0")]
2082 fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
2083 where P::Searcher: ReverseSearcher<'a>;
2084 #[stable(feature = "is_char_boundary", since = "1.9.0")]
2085 fn is_char_boundary(&self, index: usize) -> bool;
2086 #[stable(feature = "core", since = "1.6.0")]
2087 fn as_bytes(&self) -> &[u8];
2088 #[unstable(feature = "str_mut_extras", issue = "0")]
2089 unsafe fn as_bytes_mut(&mut self) -> &mut [u8];
2090 #[stable(feature = "core", since = "1.6.0")]
2091 fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
2092 #[stable(feature = "core", since = "1.6.0")]
2093 fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
2094 where P::Searcher: ReverseSearcher<'a>;
2095 fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
2096 #[stable(feature = "core", since = "1.6.0")]
2097 fn split_at(&self, mid: usize) -> (&str, &str);
2098 #[stable(feature = "core", since = "1.6.0")]
2099 fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str);
2100 #[stable(feature = "core", since = "1.6.0")]
2101 fn as_ptr(&self) -> *const u8;
2102 #[stable(feature = "core", since = "1.6.0")]
2103 fn len(&self) -> usize;
2104 #[stable(feature = "core", since = "1.6.0")]
2105 fn is_empty(&self) -> bool;
2106 #[stable(feature = "core", since = "1.6.0")]
2107 fn parse<'a, T: TryFrom<&'a str>>(&'a self) -> Result<T, T::Error>;
2110 // truncate `&str` to length at most equal to `max`
2111 // return `true` if it were truncated, and the new str.
2112 fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
2116 while !s.is_char_boundary(max) {
2125 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
2126 const MAX_DISPLAY_LENGTH: usize = 256;
2127 let (truncated, s_trunc) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
2128 let ellipsis = if truncated { "[...]" } else { "" };
2131 if begin > s.len() || end > s.len() {
2132 let oob_index = if begin > s.len() { begin } else { end };
2133 panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
2137 assert!(begin <= end, "begin <= end ({} <= {}) when slicing `{}`{}",
2138 begin, end, s_trunc, ellipsis);
2140 // 3. character boundary
2141 let index = if !s.is_char_boundary(begin) { begin } else { end };
2142 // find the character
2143 let mut char_start = index;
2144 while !s.is_char_boundary(char_start) {
2147 // `char_start` must be less than len and a char boundary
2148 let ch = s[char_start..].chars().next().unwrap();
2149 let char_range = char_start .. char_start + ch.len_utf8();
2150 panic!("byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
2151 index, ch, char_range, s_trunc, ellipsis);
2154 #[stable(feature = "core", since = "1.6.0")]
2155 impl StrExt for str {
2157 fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2158 pat.is_contained_in(self)
2162 fn chars(&self) -> Chars {
2163 Chars{iter: self.as_bytes().iter()}
2167 fn bytes(&self) -> Bytes {
2168 Bytes(self.as_bytes().iter().cloned())
2172 fn char_indices(&self) -> CharIndices {
2173 CharIndices { front_offset: 0, iter: self.chars() }
2177 fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
2178 Split(SplitInternal {
2181 matcher: pat.into_searcher(self),
2182 allow_trailing_empty: true,
2188 fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
2189 where P::Searcher: ReverseSearcher<'a>
2191 RSplit(self.split(pat).0)
2195 fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
2196 SplitN(SplitNInternal {
2197 iter: self.split(pat).0,
2203 fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
2204 where P::Searcher: ReverseSearcher<'a>
2206 RSplitN(self.splitn(count, pat).0)
2210 fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
2211 SplitTerminator(SplitInternal {
2212 allow_trailing_empty: false,
2218 fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
2219 where P::Searcher: ReverseSearcher<'a>
2221 RSplitTerminator(self.split_terminator(pat).0)
2225 fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
2226 Matches(MatchesInternal(pat.into_searcher(self)))
2230 fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
2231 where P::Searcher: ReverseSearcher<'a>
2233 RMatches(self.matches(pat).0)
2237 fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
2238 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
2242 fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
2243 where P::Searcher: ReverseSearcher<'a>
2245 RMatchIndices(self.match_indices(pat).0)
2248 fn lines(&self) -> Lines {
2249 Lines(self.split_terminator('\n').map(LinesAnyMap))
2253 #[allow(deprecated)]
2254 fn lines_any(&self) -> LinesAny {
2255 LinesAny(self.lines())
2259 fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
2264 fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
2269 unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
2270 i.get_unchecked(self)
2274 unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
2275 i.get_unchecked_mut(self)
2279 unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
2280 (begin..end).get_unchecked(self)
2284 unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
2285 (begin..end).get_unchecked_mut(self)
2289 fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2290 pat.is_prefix_of(self)
2294 fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
2295 where P::Searcher: ReverseSearcher<'a>
2297 pat.is_suffix_of(self)
2301 fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
2302 where P::Searcher: DoubleEndedSearcher<'a>
2306 let mut matcher = pat.into_searcher(self);
2307 if let Some((a, b)) = matcher.next_reject() {
2309 j = b; // Remember earliest known match, correct it below if
2310 // last match is different
2312 if let Some((_, b)) = matcher.next_reject_back() {
2316 // Searcher is known to return valid indices
2317 self.slice_unchecked(i, j)
2322 fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2323 let mut i = self.len();
2324 let mut matcher = pat.into_searcher(self);
2325 if let Some((a, _)) = matcher.next_reject() {
2329 // Searcher is known to return valid indices
2330 self.slice_unchecked(i, self.len())
2335 fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
2336 where P::Searcher: ReverseSearcher<'a>
2339 let mut matcher = pat.into_searcher(self);
2340 if let Some((_, b)) = matcher.next_reject_back() {
2344 // Searcher is known to return valid indices
2345 self.slice_unchecked(0, j)
2350 fn is_char_boundary(&self, index: usize) -> bool {
2351 // 0 and len are always ok.
2352 // Test for 0 explicitly so that it can optimize out the check
2353 // easily and skip reading string data for that case.
2354 if index == 0 || index == self.len() { return true; }
2355 match self.as_bytes().get(index) {
2357 // This is bit magic equivalent to: b < 128 || b >= 192
2358 Some(&b) => (b as i8) >= -0x40,
2363 fn as_bytes(&self) -> &[u8] {
2364 unsafe { mem::transmute(self) }
2368 unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
2369 mem::transmute(self)
2372 fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2373 pat.into_searcher(self).next_match().map(|(i, _)| i)
2376 fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
2377 where P::Searcher: ReverseSearcher<'a>
2379 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
2382 fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2387 fn split_at(&self, mid: usize) -> (&str, &str) {
2388 // is_char_boundary checks that the index is in [0, .len()]
2389 if self.is_char_boundary(mid) {
2391 (self.slice_unchecked(0, mid),
2392 self.slice_unchecked(mid, self.len()))
2395 slice_error_fail(self, 0, mid)
2399 fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
2400 // is_char_boundary checks that the index is in [0, .len()]
2401 if self.is_char_boundary(mid) {
2402 let len = self.len();
2403 let ptr = self.as_ptr() as *mut u8;
2405 (from_raw_parts_mut(ptr, mid),
2406 from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
2409 slice_error_fail(self, 0, mid)
2414 fn as_ptr(&self) -> *const u8 {
2415 self as *const str as *const u8
2419 fn len(&self) -> usize {
2420 self.as_bytes().len()
2424 fn is_empty(&self) -> bool { self.len() == 0 }
2427 fn parse<'a, T>(&'a self) -> Result<T, T::Error> where T: TryFrom<&'a str> {
2432 #[stable(feature = "rust1", since = "1.0.0")]
2433 impl AsRef<[u8]> for str {
2435 fn as_ref(&self) -> &[u8] {
2440 #[stable(feature = "rust1", since = "1.0.0")]
2441 impl<'a> Default for &'a str {
2442 /// Creates an empty str
2443 fn default() -> &'a str { "" }