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};
26 use intrinsics::align_offset;
30 /// A trait to abstract the idea of creating a new instance of a type from a
33 /// `FromStr`'s [`from_str`] method is often used implicitly, through
34 /// [`str`]'s [`parse`] method. See [`parse`]'s documentation for examples.
36 /// [`from_str`]: #tymethod.from_str
37 /// [`str`]: ../../std/primitive.str.html
38 /// [`parse`]: ../../std/primitive.str.html#method.parse
42 /// Basic implementation of `FromStr` on an example `Point` type:
45 /// use std::str::FromStr;
46 /// use std::num::ParseIntError;
48 /// #[derive(Debug, PartialEq)]
54 /// impl FromStr for Point {
55 /// type Err = ParseIntError;
57 /// fn from_str(s: &str) -> Result<Self, Self::Err> {
58 /// let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
62 /// let x_fromstr = coords[0].parse::<i32>()?;
63 /// let y_fromstr = coords[1].parse::<i32>()?;
65 /// Ok(Point { x: x_fromstr, y: y_fromstr })
69 /// let p = Point::from_str("(1,2)");
70 /// assert_eq!(p.unwrap(), Point{ x: 1, y: 2} )
72 #[stable(feature = "rust1", since = "1.0.0")]
73 pub trait FromStr: Sized {
74 /// The associated error which can be returned from parsing.
75 #[stable(feature = "rust1", since = "1.0.0")]
78 /// Parses a string `s` to return a value of this type.
80 /// If parsing succeeds, return the value inside `Ok`, otherwise
81 /// when the string is ill-formatted return an error specific to the
82 /// inside `Err`. The error type is specific to implementation of the trait.
86 /// Basic usage with [`i32`][ithirtytwo], a type that implements `FromStr`:
88 /// [ithirtytwo]: ../../std/primitive.i32.html
91 /// use std::str::FromStr;
94 /// let x = i32::from_str(s).unwrap();
98 #[stable(feature = "rust1", since = "1.0.0")]
99 fn from_str(s: &str) -> Result<Self, Self::Err>;
102 #[stable(feature = "rust1", since = "1.0.0")]
103 impl FromStr for bool {
104 type Err = ParseBoolError;
106 /// Parse a `bool` from a string.
108 /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
109 /// actually be parseable.
114 /// use std::str::FromStr;
116 /// assert_eq!(FromStr::from_str("true"), Ok(true));
117 /// assert_eq!(FromStr::from_str("false"), Ok(false));
118 /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
121 /// Note, in many cases, the `.parse()` method on `str` is more proper.
124 /// assert_eq!("true".parse(), Ok(true));
125 /// assert_eq!("false".parse(), Ok(false));
126 /// assert!("not even a boolean".parse::<bool>().is_err());
129 fn from_str(s: &str) -> Result<bool, ParseBoolError> {
132 "false" => Ok(false),
133 _ => Err(ParseBoolError { _priv: () }),
138 /// An error returned when parsing a `bool` using [`from_str`] fails
140 /// [`from_str`]: ../../std/primitive.bool.html#method.from_str
141 #[derive(Debug, Clone, PartialEq, Eq)]
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub struct ParseBoolError { _priv: () }
145 #[stable(feature = "rust1", since = "1.0.0")]
146 impl fmt::Display for ParseBoolError {
147 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
148 "provided string was not `true` or `false`".fmt(f)
153 Section: Creating a string
156 /// Errors which can occur when attempting to interpret a sequence of [`u8`]
159 /// [`u8`]: ../../std/primitive.u8.html
161 /// As such, the `from_utf8` family of functions and methods for both [`String`]s
162 /// and [`&str`]s make use of this error, for example.
164 /// [`String`]: ../../std/string/struct.String.html#method.from_utf8
165 /// [`&str`]: ../../std/str/fn.from_utf8.html
166 #[derive(Copy, Eq, PartialEq, Clone, Debug)]
167 #[stable(feature = "rust1", since = "1.0.0")]
168 pub struct Utf8Error {
170 error_len: Option<u8>,
174 /// Returns the index in the given string up to which valid UTF-8 was
177 /// It is the maximum index such that `from_utf8(&input[..index])`
178 /// would return `Ok(_)`.
187 /// // some invalid bytes, in a vector
188 /// let sparkle_heart = vec![0, 159, 146, 150];
190 /// // std::str::from_utf8 returns a Utf8Error
191 /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
193 /// // the second byte is invalid here
194 /// assert_eq!(1, error.valid_up_to());
196 #[stable(feature = "utf8_error", since = "1.5.0")]
197 pub fn valid_up_to(&self) -> usize { self.valid_up_to }
199 /// Provide more information about the failure:
201 /// * `None`: the end of the input was reached unexpectedly.
202 /// `self.valid_up_to()` is 1 to 3 bytes from the end of the input.
203 /// If a byte stream (such as a file or a network socket) is being decoded incrementally,
204 /// this could be a valid `char` whose UTF-8 byte sequence is spanning multiple chunks.
206 /// * `Some(len)`: an unexpected byte was encountered.
207 /// The length provided is that of the invalid byte sequence
208 /// that starts at the index given by `valid_up_to()`.
209 /// Decoding should resume after that sequence
210 /// (after inserting a U+FFFD REPLACEMENT CHARACTER) in case of lossy decoding.
211 #[stable(feature = "utf8_error_error_len", since = "1.20.0")]
212 pub fn error_len(&self) -> Option<usize> {
213 self.error_len.map(|len| len as usize)
217 /// Converts a slice of bytes to a string slice.
219 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
220 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
221 /// the two. Not all byte slices are valid string slices, however: [`&str`] requires
222 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
223 /// UTF-8, and then does the conversion.
225 /// [`&str`]: ../../std/primitive.str.html
226 /// [`u8`]: ../../std/primitive.u8.html
227 /// [byteslice]: ../../std/primitive.slice.html
229 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
230 /// incur the overhead of the validity check, there is an unsafe version of
231 /// this function, [`from_utf8_unchecked`][fromutf8u], which has the same
232 /// behavior but skips the check.
234 /// [fromutf8u]: fn.from_utf8_unchecked.html
236 /// If you need a `String` instead of a `&str`, consider
237 /// [`String::from_utf8`][string].
239 /// [string]: ../../std/string/struct.String.html#method.from_utf8
241 /// Because you can stack-allocate a `[u8; N]`, and you can take a
242 /// [`&[u8]`][byteslice] of it, this function is one way to have a
243 /// stack-allocated string. There is an example of this in the
244 /// examples section below.
246 /// [byteslice]: ../../std/primitive.slice.html
250 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
251 /// provided slice is not UTF-8.
260 /// // some bytes, in a vector
261 /// let sparkle_heart = vec![240, 159, 146, 150];
263 /// // We know these bytes are valid, so just use `unwrap()`.
264 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
266 /// assert_eq!("💖", sparkle_heart);
274 /// // some invalid bytes, in a vector
275 /// let sparkle_heart = vec![0, 159, 146, 150];
277 /// assert!(str::from_utf8(&sparkle_heart).is_err());
280 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
281 /// errors that can be returned.
283 /// [error]: struct.Utf8Error.html
285 /// A "stack allocated string":
290 /// // some bytes, in a stack-allocated array
291 /// let sparkle_heart = [240, 159, 146, 150];
293 /// // We know these bytes are valid, so just use `unwrap()`.
294 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
296 /// assert_eq!("💖", sparkle_heart);
298 #[stable(feature = "rust1", since = "1.0.0")]
299 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
300 run_utf8_validation(v)?;
301 Ok(unsafe { from_utf8_unchecked(v) })
304 /// Converts a mutable slice of bytes to a mutable string slice.
305 #[stable(feature = "str_mut_extras", since = "1.20.0")]
306 pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
307 run_utf8_validation(v)?;
308 Ok(unsafe { from_utf8_unchecked_mut(v) })
311 /// Forms a str from a pointer and a length.
313 /// The `len` argument is the number of bytes in the string.
317 /// This function is unsafe as there is no guarantee that the given pointer is
318 /// valid for `len` bytes, nor whether the lifetime inferred is a suitable
319 /// lifetime for the returned str.
321 /// The data must be valid UTF-8
323 /// `p` must be non-null, even for zero-length strs, because non-zero bits
324 /// are required to distinguish between a zero-length str within `Some()`
325 /// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
326 /// for zero-length strs, though.
330 /// The lifetime for the returned str is inferred from its usage. To
331 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
332 /// source lifetime is safe in the context, such as by providing a helper
333 /// function taking the lifetime of a host value for the str, or by explicit
335 /// Performs the same functionality as `from_raw_parts`, except that a mutable
338 unsafe fn from_raw_parts_mut<'a>(p: *mut u8, len: usize) -> &'a mut str {
339 from_utf8_unchecked_mut(slice::from_raw_parts_mut(p, len))
342 /// Converts a slice of bytes to a string slice without checking
343 /// that the string contains valid UTF-8.
345 /// See the safe version, [`from_utf8`][fromutf8], for more information.
347 /// [fromutf8]: fn.from_utf8.html
351 /// This function is unsafe because it does not check that the bytes passed to
352 /// it are valid UTF-8. If this constraint is violated, undefined behavior
353 /// results, as the rest of Rust assumes that [`&str`]s are valid UTF-8.
355 /// [`&str`]: ../../std/primitive.str.html
364 /// // some bytes, in a vector
365 /// let sparkle_heart = vec![240, 159, 146, 150];
367 /// let sparkle_heart = unsafe {
368 /// str::from_utf8_unchecked(&sparkle_heart)
371 /// assert_eq!("💖", sparkle_heart);
374 #[stable(feature = "rust1", since = "1.0.0")]
375 pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
379 /// Converts a slice of bytes to a string slice without checking
380 /// that the string contains valid UTF-8; mutable version.
382 /// See the immutable version, [`from_utf8_unchecked()`][fromutf8], for more information.
384 /// [fromutf8]: fn.from_utf8_unchecked.html
386 #[stable(feature = "str_mut_extras", since = "1.20.0")]
387 pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
391 #[stable(feature = "rust1", since = "1.0.0")]
392 impl fmt::Display for Utf8Error {
393 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
394 if let Some(error_len) = self.error_len {
395 write!(f, "invalid utf-8 sequence of {} bytes from index {}",
396 error_len, self.valid_up_to)
398 write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to)
407 /// An iterator over the [`char`]s of a string slice.
409 /// [`char`]: ../../std/primitive.char.html
411 /// This struct is created by the [`chars`] method on [`str`].
412 /// See its documentation for more.
414 /// [`chars`]: ../../std/primitive.str.html#method.chars
415 /// [`str`]: ../../std/primitive.str.html
416 #[derive(Clone, Debug)]
417 #[stable(feature = "rust1", since = "1.0.0")]
418 pub struct Chars<'a> {
419 iter: slice::Iter<'a, u8>
422 /// Returns the initial codepoint accumulator for the first byte.
423 /// The first byte is special, only want bottom 5 bits for width 2, 4 bits
424 /// for width 3, and 3 bits for width 4.
426 fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
428 /// Returns the value of `ch` updated with continuation byte `byte`.
430 fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
432 /// Checks whether the byte is a UTF-8 continuation byte (i.e. starts with the
435 fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
438 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
445 /// Reads the next code point out of a byte iterator (assuming a
446 /// UTF-8-like encoding).
447 #[unstable(feature = "str_internals", issue = "0")]
449 pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
451 let x = match bytes.next() {
453 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
454 Some(&next_byte) => next_byte,
457 // Multibyte case follows
458 // Decode from a byte combination out of: [[[x y] z] w]
459 // NOTE: Performance is sensitive to the exact formulation here
460 let init = utf8_first_byte(x, 2);
461 let y = unwrap_or_0(bytes.next());
462 let mut ch = utf8_acc_cont_byte(init, y);
465 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
466 let z = unwrap_or_0(bytes.next());
467 let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
468 ch = init << 12 | y_z;
471 // use only the lower 3 bits of `init`
472 let w = unwrap_or_0(bytes.next());
473 ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
480 /// Reads the last code point out of a byte iterator (assuming a
481 /// UTF-8-like encoding).
483 fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
484 where I: DoubleEndedIterator<Item = &'a u8>,
487 let w = match bytes.next_back() {
489 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
490 Some(&back_byte) => back_byte,
493 // Multibyte case follows
494 // Decode from a byte combination out of: [x [y [z w]]]
496 let z = unwrap_or_0(bytes.next_back());
497 ch = utf8_first_byte(z, 2);
498 if utf8_is_cont_byte(z) {
499 let y = unwrap_or_0(bytes.next_back());
500 ch = utf8_first_byte(y, 3);
501 if utf8_is_cont_byte(y) {
502 let x = unwrap_or_0(bytes.next_back());
503 ch = utf8_first_byte(x, 4);
504 ch = utf8_acc_cont_byte(ch, y);
506 ch = utf8_acc_cont_byte(ch, z);
508 ch = utf8_acc_cont_byte(ch, w);
513 #[stable(feature = "rust1", since = "1.0.0")]
514 impl<'a> Iterator for Chars<'a> {
518 fn next(&mut self) -> Option<char> {
519 next_code_point(&mut self.iter).map(|ch| {
520 // str invariant says `ch` is a valid Unicode Scalar Value
522 char::from_u32_unchecked(ch)
528 fn count(self) -> usize {
529 // length in `char` is equal to the number of non-continuation bytes
530 let bytes_len = self.iter.len();
531 let mut cont_bytes = 0;
532 for &byte in self.iter {
533 cont_bytes += utf8_is_cont_byte(byte) as usize;
535 bytes_len - cont_bytes
539 fn size_hint(&self) -> (usize, Option<usize>) {
540 let len = self.iter.len();
541 // `(len + 3)` can't overflow, because we know that the `slice::Iter`
542 // belongs to a slice in memory which has a maximum length of
543 // `isize::MAX` (that's well below `usize::MAX`).
544 ((len + 3) / 4, Some(len))
548 fn last(mut self) -> Option<char> {
549 // No need to go through the entire string.
554 #[stable(feature = "rust1", since = "1.0.0")]
555 impl<'a> DoubleEndedIterator for Chars<'a> {
557 fn next_back(&mut self) -> Option<char> {
558 next_code_point_reverse(&mut self.iter).map(|ch| {
559 // str invariant says `ch` is a valid Unicode Scalar Value
561 char::from_u32_unchecked(ch)
567 #[unstable(feature = "fused", issue = "35602")]
568 impl<'a> FusedIterator for Chars<'a> {}
571 /// View the underlying data as a subslice of the original data.
573 /// This has the same lifetime as the original slice, and so the
574 /// iterator can continue to be used while this exists.
579 /// let mut chars = "abc".chars();
581 /// assert_eq!(chars.as_str(), "abc");
583 /// assert_eq!(chars.as_str(), "bc");
586 /// assert_eq!(chars.as_str(), "");
588 #[stable(feature = "iter_to_slice", since = "1.4.0")]
590 pub fn as_str(&self) -> &'a str {
591 unsafe { from_utf8_unchecked(self.iter.as_slice()) }
595 /// An iterator over the [`char`]s of a string slice, and their positions.
597 /// [`char`]: ../../std/primitive.char.html
599 /// This struct is created by the [`char_indices`] method on [`str`].
600 /// See its documentation for more.
602 /// [`char_indices`]: ../../std/primitive.str.html#method.char_indices
603 /// [`str`]: ../../std/primitive.str.html
604 #[derive(Clone, Debug)]
605 #[stable(feature = "rust1", since = "1.0.0")]
606 pub struct CharIndices<'a> {
611 #[stable(feature = "rust1", since = "1.0.0")]
612 impl<'a> Iterator for CharIndices<'a> {
613 type Item = (usize, char);
616 fn next(&mut self) -> Option<(usize, char)> {
617 let pre_len = self.iter.iter.len();
618 match self.iter.next() {
621 let index = self.front_offset;
622 let len = self.iter.iter.len();
623 self.front_offset += pre_len - len;
630 fn count(self) -> usize {
635 fn size_hint(&self) -> (usize, Option<usize>) {
636 self.iter.size_hint()
640 fn last(mut self) -> Option<(usize, char)> {
641 // No need to go through the entire string.
646 #[stable(feature = "rust1", since = "1.0.0")]
647 impl<'a> DoubleEndedIterator for CharIndices<'a> {
649 fn next_back(&mut self) -> Option<(usize, char)> {
650 match self.iter.next_back() {
653 let index = self.front_offset + self.iter.iter.len();
660 #[unstable(feature = "fused", issue = "35602")]
661 impl<'a> FusedIterator for CharIndices<'a> {}
663 impl<'a> CharIndices<'a> {
664 /// View the underlying data as a subslice of the original data.
666 /// This has the same lifetime as the original slice, and so the
667 /// iterator can continue to be used while this exists.
668 #[stable(feature = "iter_to_slice", since = "1.4.0")]
670 pub fn as_str(&self) -> &'a str {
675 /// An iterator over the bytes of a string slice.
677 /// This struct is created by the [`bytes`] method on [`str`].
678 /// See its documentation for more.
680 /// [`bytes`]: ../../std/primitive.str.html#method.bytes
681 /// [`str`]: ../../std/primitive.str.html
682 #[stable(feature = "rust1", since = "1.0.0")]
683 #[derive(Clone, Debug)]
684 pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>);
686 #[stable(feature = "rust1", since = "1.0.0")]
687 impl<'a> Iterator for Bytes<'a> {
691 fn next(&mut self) -> Option<u8> {
696 fn size_hint(&self) -> (usize, Option<usize>) {
701 fn count(self) -> usize {
706 fn last(self) -> Option<Self::Item> {
711 fn nth(&mut self, n: usize) -> Option<Self::Item> {
716 fn all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
721 fn any<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
726 fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where
727 P: FnMut(&Self::Item) -> bool
729 self.0.find(predicate)
733 fn position<P>(&mut self, predicate: P) -> Option<usize> where
734 P: FnMut(Self::Item) -> bool
736 self.0.position(predicate)
740 fn rposition<P>(&mut self, predicate: P) -> Option<usize> where
741 P: FnMut(Self::Item) -> bool
743 self.0.rposition(predicate)
747 #[stable(feature = "rust1", since = "1.0.0")]
748 impl<'a> DoubleEndedIterator for Bytes<'a> {
750 fn next_back(&mut self) -> Option<u8> {
755 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> where
756 P: FnMut(&Self::Item) -> bool
758 self.0.rfind(predicate)
762 #[stable(feature = "rust1", since = "1.0.0")]
763 impl<'a> ExactSizeIterator for Bytes<'a> {
765 fn len(&self) -> usize {
770 fn is_empty(&self) -> bool {
775 #[unstable(feature = "fused", issue = "35602")]
776 impl<'a> FusedIterator for Bytes<'a> {}
778 /// This macro generates a Clone impl for string pattern API
779 /// wrapper types of the form X<'a, P>
780 macro_rules! derive_pattern_clone {
781 (clone $t:ident with |$s:ident| $e:expr) => {
782 impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
783 where P::Searcher: Clone
785 fn clone(&self) -> Self {
793 /// This macro generates two public iterator structs
794 /// wrapping a private internal one that makes use of the `Pattern` API.
796 /// For all patterns `P: Pattern<'a>` the following items will be
797 /// generated (generics omitted):
799 /// struct $forward_iterator($internal_iterator);
800 /// struct $reverse_iterator($internal_iterator);
802 /// impl Iterator for $forward_iterator
803 /// { /* internal ends up calling Searcher::next_match() */ }
805 /// impl DoubleEndedIterator for $forward_iterator
806 /// where P::Searcher: DoubleEndedSearcher
807 /// { /* internal ends up calling Searcher::next_match_back() */ }
809 /// impl Iterator for $reverse_iterator
810 /// where P::Searcher: ReverseSearcher
811 /// { /* internal ends up calling Searcher::next_match_back() */ }
813 /// impl DoubleEndedIterator for $reverse_iterator
814 /// where P::Searcher: DoubleEndedSearcher
815 /// { /* internal ends up calling Searcher::next_match() */ }
817 /// The internal one is defined outside the macro, and has almost the same
818 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
819 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
821 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
822 /// `Pattern` might not return the same elements, so actually implementing
823 /// `DoubleEndedIterator` for it would be incorrect.
824 /// (See the docs in `str::pattern` for more details)
826 /// However, the internal struct still represents a single ended iterator from
827 /// either end, and depending on pattern is also a valid double ended iterator,
828 /// so the two wrapper structs implement `Iterator`
829 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
830 /// to the complex impls seen above.
831 macro_rules! generate_pattern_iterators {
835 $(#[$forward_iterator_attribute:meta])*
836 struct $forward_iterator:ident;
840 $(#[$reverse_iterator_attribute:meta])*
841 struct $reverse_iterator:ident;
843 // Stability of all generated items
845 $(#[$common_stability_attribute:meta])*
847 // Internal almost-iterator that is being delegated to
849 $internal_iterator:ident yielding ($iterty:ty);
851 // Kind of delegation - either single ended or double ended
854 $(#[$forward_iterator_attribute])*
855 $(#[$common_stability_attribute])*
856 pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
858 $(#[$common_stability_attribute])*
859 impl<'a, P: Pattern<'a>> fmt::Debug for $forward_iterator<'a, P>
860 where P::Searcher: fmt::Debug
862 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
863 f.debug_tuple(stringify!($forward_iterator))
869 $(#[$common_stability_attribute])*
870 impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
874 fn next(&mut self) -> Option<$iterty> {
879 $(#[$common_stability_attribute])*
880 impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
881 where P::Searcher: Clone
883 fn clone(&self) -> Self {
884 $forward_iterator(self.0.clone())
888 $(#[$reverse_iterator_attribute])*
889 $(#[$common_stability_attribute])*
890 pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
892 $(#[$common_stability_attribute])*
893 impl<'a, P: Pattern<'a>> fmt::Debug for $reverse_iterator<'a, P>
894 where P::Searcher: fmt::Debug
896 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
897 f.debug_tuple(stringify!($reverse_iterator))
903 $(#[$common_stability_attribute])*
904 impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
905 where P::Searcher: ReverseSearcher<'a>
910 fn next(&mut self) -> Option<$iterty> {
915 $(#[$common_stability_attribute])*
916 impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
917 where P::Searcher: Clone
919 fn clone(&self) -> Self {
920 $reverse_iterator(self.0.clone())
924 #[unstable(feature = "fused", issue = "35602")]
925 impl<'a, P: Pattern<'a>> FusedIterator for $forward_iterator<'a, P> {}
927 #[unstable(feature = "fused", issue = "35602")]
928 impl<'a, P: Pattern<'a>> FusedIterator for $reverse_iterator<'a, P>
929 where P::Searcher: ReverseSearcher<'a> {}
931 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
933 $reverse_iterator, $iterty);
936 double ended; with $(#[$common_stability_attribute:meta])*,
937 $forward_iterator:ident,
938 $reverse_iterator:ident, $iterty:ty
940 $(#[$common_stability_attribute])*
941 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
942 where P::Searcher: DoubleEndedSearcher<'a>
945 fn next_back(&mut self) -> Option<$iterty> {
950 $(#[$common_stability_attribute])*
951 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
952 where P::Searcher: DoubleEndedSearcher<'a>
955 fn next_back(&mut self) -> Option<$iterty> {
961 single ended; with $(#[$common_stability_attribute:meta])*,
962 $forward_iterator:ident,
963 $reverse_iterator:ident, $iterty:ty
967 derive_pattern_clone!{
969 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
972 struct SplitInternal<'a, P: Pattern<'a>> {
975 matcher: P::Searcher,
976 allow_trailing_empty: bool,
980 impl<'a, P: Pattern<'a>> fmt::Debug for SplitInternal<'a, P> where P::Searcher: fmt::Debug {
981 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
982 f.debug_struct("SplitInternal")
983 .field("start", &self.start)
984 .field("end", &self.end)
985 .field("matcher", &self.matcher)
986 .field("allow_trailing_empty", &self.allow_trailing_empty)
987 .field("finished", &self.finished)
992 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
994 fn get_end(&mut self) -> Option<&'a str> {
995 if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
996 self.finished = true;
998 let string = self.matcher.haystack().slice_unchecked(self.start, self.end);
1007 fn next(&mut self) -> Option<&'a str> {
1008 if self.finished { return None }
1010 let haystack = self.matcher.haystack();
1011 match self.matcher.next_match() {
1012 Some((a, b)) => unsafe {
1013 let elt = haystack.slice_unchecked(self.start, a);
1017 None => self.get_end(),
1022 fn next_back(&mut self) -> Option<&'a str>
1023 where P::Searcher: ReverseSearcher<'a>
1025 if self.finished { return None }
1027 if !self.allow_trailing_empty {
1028 self.allow_trailing_empty = true;
1029 match self.next_back() {
1030 Some(elt) if !elt.is_empty() => return Some(elt),
1031 _ => if self.finished { return None }
1035 let haystack = self.matcher.haystack();
1036 match self.matcher.next_match_back() {
1037 Some((a, b)) => unsafe {
1038 let elt = haystack.slice_unchecked(b, self.end);
1043 self.finished = true;
1044 Some(haystack.slice_unchecked(self.start, self.end))
1050 generate_pattern_iterators! {
1052 /// Created with the method [`split`].
1054 /// [`split`]: ../../std/primitive.str.html#method.split
1057 /// Created with the method [`rsplit`].
1059 /// [`rsplit`]: ../../std/primitive.str.html#method.rsplit
1062 #[stable(feature = "rust1", since = "1.0.0")]
1064 SplitInternal yielding (&'a str);
1065 delegate double ended;
1068 generate_pattern_iterators! {
1070 /// Created with the method [`split_terminator`].
1072 /// [`split_terminator`]: ../../std/primitive.str.html#method.split_terminator
1073 struct SplitTerminator;
1075 /// Created with the method [`rsplit_terminator`].
1077 /// [`rsplit_terminator`]: ../../std/primitive.str.html#method.rsplit_terminator
1078 struct RSplitTerminator;
1080 #[stable(feature = "rust1", since = "1.0.0")]
1082 SplitInternal yielding (&'a str);
1083 delegate double ended;
1086 derive_pattern_clone!{
1087 clone SplitNInternal
1088 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
1091 struct SplitNInternal<'a, P: Pattern<'a>> {
1092 iter: SplitInternal<'a, P>,
1093 /// The number of splits remaining
1097 impl<'a, P: Pattern<'a>> fmt::Debug for SplitNInternal<'a, P> where P::Searcher: fmt::Debug {
1098 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1099 f.debug_struct("SplitNInternal")
1100 .field("iter", &self.iter)
1101 .field("count", &self.count)
1106 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
1108 fn next(&mut self) -> Option<&'a str> {
1111 1 => { self.count = 0; self.iter.get_end() }
1112 _ => { self.count -= 1; self.iter.next() }
1117 fn next_back(&mut self) -> Option<&'a str>
1118 where P::Searcher: ReverseSearcher<'a>
1122 1 => { self.count = 0; self.iter.get_end() }
1123 _ => { self.count -= 1; self.iter.next_back() }
1128 generate_pattern_iterators! {
1130 /// Created with the method [`splitn`].
1132 /// [`splitn`]: ../../std/primitive.str.html#method.splitn
1135 /// Created with the method [`rsplitn`].
1137 /// [`rsplitn`]: ../../std/primitive.str.html#method.rsplitn
1140 #[stable(feature = "rust1", since = "1.0.0")]
1142 SplitNInternal yielding (&'a str);
1143 delegate single ended;
1146 derive_pattern_clone!{
1147 clone MatchIndicesInternal
1148 with |s| MatchIndicesInternal(s.0.clone())
1151 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
1153 impl<'a, P: Pattern<'a>> fmt::Debug for MatchIndicesInternal<'a, P> where P::Searcher: fmt::Debug {
1154 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1155 f.debug_tuple("MatchIndicesInternal")
1161 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
1163 fn next(&mut self) -> Option<(usize, &'a str)> {
1164 self.0.next_match().map(|(start, end)| unsafe {
1165 (start, self.0.haystack().slice_unchecked(start, end))
1170 fn next_back(&mut self) -> Option<(usize, &'a str)>
1171 where P::Searcher: ReverseSearcher<'a>
1173 self.0.next_match_back().map(|(start, end)| unsafe {
1174 (start, self.0.haystack().slice_unchecked(start, end))
1179 generate_pattern_iterators! {
1181 /// Created with the method [`match_indices`].
1183 /// [`match_indices`]: ../../std/primitive.str.html#method.match_indices
1184 struct MatchIndices;
1186 /// Created with the method [`rmatch_indices`].
1188 /// [`rmatch_indices`]: ../../std/primitive.str.html#method.rmatch_indices
1189 struct RMatchIndices;
1191 #[stable(feature = "str_match_indices", since = "1.5.0")]
1193 MatchIndicesInternal yielding ((usize, &'a str));
1194 delegate double ended;
1197 derive_pattern_clone!{
1198 clone MatchesInternal
1199 with |s| MatchesInternal(s.0.clone())
1202 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
1204 impl<'a, P: Pattern<'a>> fmt::Debug for MatchesInternal<'a, P> where P::Searcher: fmt::Debug {
1205 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1206 f.debug_tuple("MatchesInternal")
1212 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
1214 fn next(&mut self) -> Option<&'a str> {
1215 self.0.next_match().map(|(a, b)| unsafe {
1216 // Indices are known to be on utf8 boundaries
1217 self.0.haystack().slice_unchecked(a, b)
1222 fn next_back(&mut self) -> Option<&'a str>
1223 where P::Searcher: ReverseSearcher<'a>
1225 self.0.next_match_back().map(|(a, b)| unsafe {
1226 // Indices are known to be on utf8 boundaries
1227 self.0.haystack().slice_unchecked(a, b)
1232 generate_pattern_iterators! {
1234 /// Created with the method [`matches`].
1236 /// [`matches`]: ../../std/primitive.str.html#method.matches
1239 /// Created with the method [`rmatches`].
1241 /// [`rmatches`]: ../../std/primitive.str.html#method.rmatches
1244 #[stable(feature = "str_matches", since = "1.2.0")]
1246 MatchesInternal yielding (&'a str);
1247 delegate double ended;
1250 /// An iterator over the lines of a string, as string slices.
1252 /// This struct is created with the [`lines`] method on [`str`].
1253 /// See its documentation for more.
1255 /// [`lines`]: ../../std/primitive.str.html#method.lines
1256 /// [`str`]: ../../std/primitive.str.html
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 #[derive(Clone, Debug)]
1259 pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>);
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 impl<'a> Iterator for Lines<'a> {
1263 type Item = &'a str;
1266 fn next(&mut self) -> Option<&'a str> {
1271 fn size_hint(&self) -> (usize, Option<usize>) {
1276 #[stable(feature = "rust1", since = "1.0.0")]
1277 impl<'a> DoubleEndedIterator for Lines<'a> {
1279 fn next_back(&mut self) -> Option<&'a str> {
1284 #[unstable(feature = "fused", issue = "35602")]
1285 impl<'a> FusedIterator for Lines<'a> {}
1287 /// Created with the method [`lines_any`].
1289 /// [`lines_any`]: ../../std/primitive.str.html#method.lines_any
1290 #[stable(feature = "rust1", since = "1.0.0")]
1291 #[rustc_deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")]
1292 #[derive(Clone, Debug)]
1293 #[allow(deprecated)]
1294 pub struct LinesAny<'a>(Lines<'a>);
1296 /// A nameable, cloneable fn type
1300 impl<'a> Fn<(&'a str,)> for LinesAnyMap {
1302 extern "rust-call" fn call(&self, (line,): (&'a str,)) -> &'a str {
1304 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
1309 impl<'a> FnMut<(&'a str,)> for LinesAnyMap {
1311 extern "rust-call" fn call_mut(&mut self, (line,): (&'a str,)) -> &'a str {
1312 Fn::call(&*self, (line,))
1316 impl<'a> FnOnce<(&'a str,)> for LinesAnyMap {
1317 type Output = &'a str;
1320 extern "rust-call" fn call_once(self, (line,): (&'a str,)) -> &'a str {
1321 Fn::call(&self, (line,))
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 #[allow(deprecated)]
1327 impl<'a> Iterator for LinesAny<'a> {
1328 type Item = &'a str;
1331 fn next(&mut self) -> Option<&'a str> {
1336 fn size_hint(&self) -> (usize, Option<usize>) {
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 #[allow(deprecated)]
1343 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1345 fn next_back(&mut self) -> Option<&'a str> {
1350 #[unstable(feature = "fused", issue = "35602")]
1351 #[allow(deprecated)]
1352 impl<'a> FusedIterator for LinesAny<'a> {}
1355 Section: Comparing strings
1358 /// Bytewise slice equality
1359 /// NOTE: This function is (ab)used in rustc::middle::trans::_match
1360 /// to compare &[u8] byte slices that are not necessarily valid UTF-8.
1363 fn eq_slice(a: &str, b: &str) -> bool {
1364 a.as_bytes() == b.as_bytes()
1368 Section: UTF-8 validation
1371 // use truncation to fit u64 into usize
1372 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
1374 /// Returns `true` if any byte in the word `x` is nonascii (>= 128).
1376 fn contains_nonascii(x: usize) -> bool {
1377 (x & NONASCII_MASK) != 0
1380 /// Walks through `iter` checking that it's a valid UTF-8 sequence,
1381 /// returning `true` in that case, or, if it is invalid, `false` with
1382 /// `iter` reset such that it is pointing at the first byte in the
1383 /// invalid sequence.
1385 fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
1389 let usize_bytes = mem::size_of::<usize>();
1390 let ascii_block_size = 2 * usize_bytes;
1391 let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
1394 let old_offset = index;
1396 ($error_len: expr) => {
1397 return Err(Utf8Error {
1398 valid_up_to: old_offset,
1399 error_len: $error_len,
1404 macro_rules! next { () => {{
1406 // we needed data, but there was none: error!
1413 let first = v[index];
1415 let w = UTF8_CHAR_WIDTH[first as usize];
1416 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
1417 // first C2 80 last DF BF
1418 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
1419 // first E0 A0 80 last EF BF BF
1420 // excluding surrogates codepoints \u{d800} to \u{dfff}
1421 // ED A0 80 to ED BF BF
1422 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1423 // first F0 90 80 80 last F4 8F BF BF
1425 // Use the UTF-8 syntax from the RFC
1427 // https://tools.ietf.org/html/rfc3629
1429 // UTF8-2 = %xC2-DF UTF8-tail
1430 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1431 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1432 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1433 // %xF4 %x80-8F 2( UTF8-tail )
1435 2 => if next!() & !CONT_MASK != TAG_CONT_U8 {
1439 match (first, next!()) {
1440 (0xE0 , 0xA0 ... 0xBF) |
1441 (0xE1 ... 0xEC, 0x80 ... 0xBF) |
1442 (0xED , 0x80 ... 0x9F) |
1443 (0xEE ... 0xEF, 0x80 ... 0xBF) => {}
1446 if next!() & !CONT_MASK != TAG_CONT_U8 {
1451 match (first, next!()) {
1452 (0xF0 , 0x90 ... 0xBF) |
1453 (0xF1 ... 0xF3, 0x80 ... 0xBF) |
1454 (0xF4 , 0x80 ... 0x8F) => {}
1457 if next!() & !CONT_MASK != TAG_CONT_U8 {
1460 if next!() & !CONT_MASK != TAG_CONT_U8 {
1468 // Ascii case, try to skip forward quickly.
1469 // When the pointer is aligned, read 2 words of data per iteration
1470 // until we find a word containing a non-ascii byte.
1471 let ptr = v.as_ptr();
1472 let align = unsafe {
1473 // the offset is safe, because `index` is guaranteed inbounds
1474 align_offset(ptr.offset(index as isize) as *const (), usize_bytes)
1477 while index < blocks_end {
1479 let block = ptr.offset(index as isize) as *const usize;
1480 // break if there is a nonascii byte
1481 let zu = contains_nonascii(*block);
1482 let zv = contains_nonascii(*block.offset(1));
1487 index += ascii_block_size;
1489 // step from the point where the wordwise loop stopped
1490 while index < len && v[index] < 128 {
1502 // https://tools.ietf.org/html/rfc3629
1503 static UTF8_CHAR_WIDTH: [u8; 256] = [
1504 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1505 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1506 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1507 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1508 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1509 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1510 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1511 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1512 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1513 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1514 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1515 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1516 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1517 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1518 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1519 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1522 /// Given a first byte, determines how many bytes are in this UTF-8 character.
1523 #[unstable(feature = "str_internals", issue = "0")]
1525 pub fn utf8_char_width(b: u8) -> usize {
1526 return UTF8_CHAR_WIDTH[b as usize] as usize;
1529 /// Mask of the value bits of a continuation byte.
1530 const CONT_MASK: u8 = 0b0011_1111;
1531 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte.
1532 const TAG_CONT_U8: u8 = 0b1000_0000;
1535 Section: Trait implementations
1541 use slice::{self, SliceIndex};
1544 /// Implements ordering of strings.
1546 /// Strings are ordered lexicographically by their byte values. This orders Unicode code
1547 /// points based on their positions in the code charts. This is not necessarily the same as
1548 /// "alphabetical" order, which varies by language and locale. Sorting strings according to
1549 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1551 #[stable(feature = "rust1", since = "1.0.0")]
1554 fn cmp(&self, other: &str) -> Ordering {
1555 self.as_bytes().cmp(other.as_bytes())
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 impl PartialEq for str {
1562 fn eq(&self, other: &str) -> bool {
1563 eq_slice(self, other)
1566 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1569 #[stable(feature = "rust1", since = "1.0.0")]
1572 /// Implements comparison operations on strings.
1574 /// Strings are compared lexicographically by their byte values. This compares Unicode code
1575 /// points based on their positions in the code charts. This is not necessarily the same as
1576 /// "alphabetical" order, which varies by language and locale. Comparing strings according to
1577 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 impl PartialOrd for str {
1582 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1583 Some(self.cmp(other))
1587 /// Implements substring slicing with syntax `&self[begin .. end]`.
1589 /// Returns a 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.
1604 /// let s = "Löwe 老虎 Léopard";
1605 /// assert_eq!(&s[0 .. 1], "L");
1607 /// assert_eq!(&s[1 .. 9], "öwe 老");
1609 /// // these will panic:
1610 /// // byte 2 lies within `ö`:
1613 /// // byte 8 lies within `老`
1616 /// // byte 100 is outside the string
1617 /// // &s[3 .. 100];
1619 #[stable(feature = "rust1", since = "1.0.0")]
1620 impl ops::Index<ops::Range<usize>> for str {
1623 fn index(&self, index: ops::Range<usize>) -> &str {
1628 /// Implements mutable substring slicing with syntax
1629 /// `&mut self[begin .. end]`.
1631 /// Returns a mutable slice of the given string from the byte range
1632 /// [`begin`..`end`).
1634 /// This operation is `O(1)`.
1638 /// Panics if `begin` or `end` does not point to the starting
1639 /// byte offset of a character (as defined by `is_char_boundary`).
1640 /// Requires that `begin <= end` and `end <= len` where `len` is the
1641 /// length of the string.
1642 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1643 impl ops::IndexMut<ops::Range<usize>> for str {
1645 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1646 index.index_mut(self)
1650 /// Implements substring slicing with syntax `&self[.. end]`.
1652 /// Returns a slice of the string from the beginning to byte offset
1655 /// Equivalent to `&self[0 .. end]`.
1656 #[stable(feature = "rust1", since = "1.0.0")]
1657 impl ops::Index<ops::RangeTo<usize>> for str {
1661 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1666 /// Implements mutable substring slicing with syntax `&mut self[.. end]`.
1668 /// Returns a mutable slice of the string from the beginning to byte offset
1671 /// Equivalent to `&mut self[0 .. end]`.
1672 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1673 impl ops::IndexMut<ops::RangeTo<usize>> for str {
1675 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1676 index.index_mut(self)
1680 /// Implements substring slicing with syntax `&self[begin ..]`.
1682 /// Returns a slice of the string from byte offset `begin`
1683 /// to the end of the string.
1685 /// Equivalent to `&self[begin .. len]`.
1686 #[stable(feature = "rust1", since = "1.0.0")]
1687 impl ops::Index<ops::RangeFrom<usize>> for str {
1691 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1696 /// Implements mutable substring slicing with syntax `&mut self[begin ..]`.
1698 /// Returns a mutable slice of the string from byte offset `begin`
1699 /// to the end of the string.
1701 /// Equivalent to `&mut self[begin .. len]`.
1702 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1703 impl ops::IndexMut<ops::RangeFrom<usize>> for str {
1705 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1706 index.index_mut(self)
1710 /// Implements substring slicing with syntax `&self[..]`.
1712 /// Returns a slice of the whole string. This operation can
1715 /// Equivalent to `&self[0 .. len]`.
1716 #[stable(feature = "rust1", since = "1.0.0")]
1717 impl ops::Index<ops::RangeFull> for str {
1721 fn index(&self, _index: ops::RangeFull) -> &str {
1726 /// Implements mutable substring slicing with syntax `&mut self[..]`.
1728 /// Returns a mutable slice of the whole string. This operation can
1731 /// Equivalent to `&mut self[0 .. len]`.
1732 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1733 impl ops::IndexMut<ops::RangeFull> for str {
1735 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1740 #[unstable(feature = "inclusive_range",
1741 reason = "recently added, follows RFC",
1743 impl ops::Index<ops::RangeInclusive<usize>> for str {
1747 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1752 #[unstable(feature = "inclusive_range",
1753 reason = "recently added, follows RFC",
1755 impl ops::Index<ops::RangeToInclusive<usize>> for str {
1759 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1764 #[unstable(feature = "inclusive_range",
1765 reason = "recently added, follows RFC",
1767 impl ops::IndexMut<ops::RangeInclusive<usize>> for str {
1769 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1770 index.index_mut(self)
1773 #[unstable(feature = "inclusive_range",
1774 reason = "recently added, follows RFC",
1776 impl ops::IndexMut<ops::RangeToInclusive<usize>> for str {
1778 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1779 index.index_mut(self)
1783 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1784 impl SliceIndex<str> for ops::RangeFull {
1787 fn get(self, slice: &str) -> Option<&Self::Output> {
1791 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1795 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1799 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1803 fn index(self, slice: &str) -> &Self::Output {
1807 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1812 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1813 impl SliceIndex<str> for ops::Range<usize> {
1816 fn get(self, slice: &str) -> Option<&Self::Output> {
1817 if self.start <= self.end &&
1818 slice.is_char_boundary(self.start) &&
1819 slice.is_char_boundary(self.end) {
1820 Some(unsafe { self.get_unchecked(slice) })
1826 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1827 if self.start <= self.end &&
1828 slice.is_char_boundary(self.start) &&
1829 slice.is_char_boundary(self.end) {
1830 Some(unsafe { self.get_unchecked_mut(slice) })
1836 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1837 let ptr = slice.as_ptr().offset(self.start as isize);
1838 let len = self.end - self.start;
1839 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1842 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1843 let ptr = slice.as_ptr().offset(self.start as isize);
1844 let len = self.end - self.start;
1845 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1848 fn index(self, slice: &str) -> &Self::Output {
1849 let (start, end) = (self.start, self.end);
1850 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1853 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1854 // is_char_boundary checks that the index is in [0, .len()]
1855 // canot reuse `get` as above, because of NLL trouble
1856 if self.start <= self.end &&
1857 slice.is_char_boundary(self.start) &&
1858 slice.is_char_boundary(self.end) {
1859 unsafe { self.get_unchecked_mut(slice) }
1861 super::slice_error_fail(slice, self.start, self.end)
1866 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1867 impl SliceIndex<str> for ops::RangeTo<usize> {
1870 fn get(self, slice: &str) -> Option<&Self::Output> {
1871 if slice.is_char_boundary(self.end) {
1872 Some(unsafe { self.get_unchecked(slice) })
1878 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1879 if slice.is_char_boundary(self.end) {
1880 Some(unsafe { self.get_unchecked_mut(slice) })
1886 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1887 let ptr = slice.as_ptr();
1888 super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end))
1891 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1892 let ptr = slice.as_ptr();
1893 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, self.end))
1896 fn index(self, slice: &str) -> &Self::Output {
1898 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end))
1901 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1902 // is_char_boundary checks that the index is in [0, .len()]
1903 if slice.is_char_boundary(self.end) {
1904 unsafe { self.get_unchecked_mut(slice) }
1906 super::slice_error_fail(slice, 0, self.end)
1911 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1912 impl SliceIndex<str> for ops::RangeFrom<usize> {
1915 fn get(self, slice: &str) -> Option<&Self::Output> {
1916 if slice.is_char_boundary(self.start) {
1917 Some(unsafe { self.get_unchecked(slice) })
1923 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1924 if slice.is_char_boundary(self.start) {
1925 Some(unsafe { self.get_unchecked_mut(slice) })
1931 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1932 let ptr = slice.as_ptr().offset(self.start as isize);
1933 let len = slice.len() - self.start;
1934 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1937 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1938 let ptr = slice.as_ptr().offset(self.start as isize);
1939 let len = slice.len() - self.start;
1940 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1943 fn index(self, slice: &str) -> &Self::Output {
1944 let (start, end) = (self.start, slice.len());
1945 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1948 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1949 // is_char_boundary checks that the index is in [0, .len()]
1950 if slice.is_char_boundary(self.start) {
1951 unsafe { self.get_unchecked_mut(slice) }
1953 super::slice_error_fail(slice, self.start, slice.len())
1958 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1959 impl SliceIndex<str> for ops::RangeInclusive<usize> {
1962 fn get(self, slice: &str) -> Option<&Self::Output> {
1963 if let Some(end) = self.end.checked_add(1) {
1964 (self.start..end).get(slice)
1970 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1971 if let Some(end) = self.end.checked_add(1) {
1972 (self.start..end).get_mut(slice)
1978 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1979 (self.start..self.end+1).get_unchecked(slice)
1982 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1983 (self.start..self.end+1).get_unchecked_mut(slice)
1986 fn index(self, slice: &str) -> &Self::Output {
1987 assert!(self.end != usize::max_value(),
1988 "attempted to index str up to maximum usize");
1989 (self.start..self.end+1).index(slice)
1992 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1993 assert!(self.end != usize::max_value(),
1994 "attempted to index str up to maximum usize");
1995 (self.start..self.end+1).index_mut(slice)
2001 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2002 impl SliceIndex<str> for ops::RangeToInclusive<usize> {
2005 fn get(self, slice: &str) -> Option<&Self::Output> {
2006 if self.end < usize::max_value() && slice.is_char_boundary(self.end + 1) {
2007 Some(unsafe { self.get_unchecked(slice) })
2013 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
2014 if self.end < usize::max_value() && slice.is_char_boundary(self.end + 1) {
2015 Some(unsafe { self.get_unchecked_mut(slice) })
2021 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
2022 let ptr = slice.as_ptr();
2023 super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end + 1))
2026 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
2027 let ptr = slice.as_ptr();
2028 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, self.end + 1))
2031 fn index(self, slice: &str) -> &Self::Output {
2032 assert!(self.end != usize::max_value(),
2033 "attempted to index str up to maximum usize");
2034 let end = self.end + 1;
2035 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end))
2038 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
2039 assert!(self.end != usize::max_value(),
2040 "attempted to index str up to maximum usize");
2041 if slice.is_char_boundary(self.end) {
2042 unsafe { self.get_unchecked_mut(slice) }
2044 super::slice_error_fail(slice, 0, self.end + 1)
2052 /// Methods for string slices
2053 #[allow(missing_docs)]
2055 #[unstable(feature = "core_str_ext",
2056 reason = "stable interface provided by `impl str` in later crates",
2059 // NB there are no docs here are they're all located on the StrExt trait in
2060 // liballoc, not here.
2062 #[stable(feature = "core", since = "1.6.0")]
2063 fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
2064 #[stable(feature = "core", since = "1.6.0")]
2065 fn chars(&self) -> Chars;
2066 #[stable(feature = "core", since = "1.6.0")]
2067 fn bytes(&self) -> Bytes;
2068 #[stable(feature = "core", since = "1.6.0")]
2069 fn char_indices(&self) -> CharIndices;
2070 #[stable(feature = "core", since = "1.6.0")]
2071 fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P>;
2072 #[stable(feature = "core", since = "1.6.0")]
2073 fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
2074 where P::Searcher: ReverseSearcher<'a>;
2075 #[stable(feature = "core", since = "1.6.0")]
2076 fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P>;
2077 #[stable(feature = "core", since = "1.6.0")]
2078 fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
2079 where P::Searcher: ReverseSearcher<'a>;
2080 #[stable(feature = "core", since = "1.6.0")]
2081 fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P>;
2082 #[stable(feature = "core", since = "1.6.0")]
2083 fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
2084 where P::Searcher: ReverseSearcher<'a>;
2085 #[stable(feature = "core", since = "1.6.0")]
2086 fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P>;
2087 #[stable(feature = "core", since = "1.6.0")]
2088 fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
2089 where P::Searcher: ReverseSearcher<'a>;
2090 #[stable(feature = "core", since = "1.6.0")]
2091 fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P>;
2092 #[stable(feature = "core", since = "1.6.0")]
2093 fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
2094 where P::Searcher: ReverseSearcher<'a>;
2095 #[stable(feature = "core", since = "1.6.0")]
2096 fn lines(&self) -> Lines;
2097 #[stable(feature = "core", since = "1.6.0")]
2098 #[rustc_deprecated(since = "1.6.0", reason = "use lines() instead now")]
2099 #[allow(deprecated)]
2100 fn lines_any(&self) -> LinesAny;
2101 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2102 fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output>;
2103 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2104 fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output>;
2105 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2106 unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output;
2107 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2108 unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output;
2109 #[stable(feature = "core", since = "1.6.0")]
2110 unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str;
2111 #[stable(feature = "core", since = "1.6.0")]
2112 unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str;
2113 #[stable(feature = "core", since = "1.6.0")]
2114 fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
2115 #[stable(feature = "core", since = "1.6.0")]
2116 fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
2117 where P::Searcher: ReverseSearcher<'a>;
2118 #[stable(feature = "core", since = "1.6.0")]
2119 fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
2120 where P::Searcher: DoubleEndedSearcher<'a>;
2121 #[stable(feature = "core", since = "1.6.0")]
2122 fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str;
2123 #[stable(feature = "core", since = "1.6.0")]
2124 fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
2125 where P::Searcher: ReverseSearcher<'a>;
2126 #[stable(feature = "is_char_boundary", since = "1.9.0")]
2127 fn is_char_boundary(&self, index: usize) -> bool;
2128 #[stable(feature = "core", since = "1.6.0")]
2129 fn as_bytes(&self) -> &[u8];
2130 #[stable(feature = "str_mut_extras", since = "1.20.0")]
2131 unsafe fn as_bytes_mut(&mut self) -> &mut [u8];
2132 #[stable(feature = "core", since = "1.6.0")]
2133 fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
2134 #[stable(feature = "core", since = "1.6.0")]
2135 fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
2136 where P::Searcher: ReverseSearcher<'a>;
2137 fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
2138 #[stable(feature = "core", since = "1.6.0")]
2139 fn split_at(&self, mid: usize) -> (&str, &str);
2140 #[stable(feature = "core", since = "1.6.0")]
2141 fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str);
2142 #[stable(feature = "core", since = "1.6.0")]
2143 fn as_ptr(&self) -> *const u8;
2144 #[stable(feature = "core", since = "1.6.0")]
2145 fn len(&self) -> usize;
2146 #[stable(feature = "core", since = "1.6.0")]
2147 fn is_empty(&self) -> bool;
2148 #[stable(feature = "core", since = "1.6.0")]
2149 fn parse<'a, T: TryFrom<&'a str>>(&'a self) -> Result<T, T::Error>;
2152 // truncate `&str` to length at most equal to `max`
2153 // return `true` if it were truncated, and the new str.
2154 fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
2158 while !s.is_char_boundary(max) {
2167 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
2168 const MAX_DISPLAY_LENGTH: usize = 256;
2169 let (truncated, s_trunc) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
2170 let ellipsis = if truncated { "[...]" } else { "" };
2173 if begin > s.len() || end > s.len() {
2174 let oob_index = if begin > s.len() { begin } else { end };
2175 panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
2179 assert!(begin <= end, "begin <= end ({} <= {}) when slicing `{}`{}",
2180 begin, end, s_trunc, ellipsis);
2182 // 3. character boundary
2183 let index = if !s.is_char_boundary(begin) { begin } else { end };
2184 // find the character
2185 let mut char_start = index;
2186 while !s.is_char_boundary(char_start) {
2189 // `char_start` must be less than len and a char boundary
2190 let ch = s[char_start..].chars().next().unwrap();
2191 let char_range = char_start .. char_start + ch.len_utf8();
2192 panic!("byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
2193 index, ch, char_range, s_trunc, ellipsis);
2196 #[stable(feature = "core", since = "1.6.0")]
2197 impl StrExt for str {
2199 fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2200 pat.is_contained_in(self)
2204 fn chars(&self) -> Chars {
2205 Chars{iter: self.as_bytes().iter()}
2209 fn bytes(&self) -> Bytes {
2210 Bytes(self.as_bytes().iter().cloned())
2214 fn char_indices(&self) -> CharIndices {
2215 CharIndices { front_offset: 0, iter: self.chars() }
2219 fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
2220 Split(SplitInternal {
2223 matcher: pat.into_searcher(self),
2224 allow_trailing_empty: true,
2230 fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
2231 where P::Searcher: ReverseSearcher<'a>
2233 RSplit(self.split(pat).0)
2237 fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
2238 SplitN(SplitNInternal {
2239 iter: self.split(pat).0,
2245 fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
2246 where P::Searcher: ReverseSearcher<'a>
2248 RSplitN(self.splitn(count, pat).0)
2252 fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
2253 SplitTerminator(SplitInternal {
2254 allow_trailing_empty: false,
2260 fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
2261 where P::Searcher: ReverseSearcher<'a>
2263 RSplitTerminator(self.split_terminator(pat).0)
2267 fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
2268 Matches(MatchesInternal(pat.into_searcher(self)))
2272 fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
2273 where P::Searcher: ReverseSearcher<'a>
2275 RMatches(self.matches(pat).0)
2279 fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
2280 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
2284 fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
2285 where P::Searcher: ReverseSearcher<'a>
2287 RMatchIndices(self.match_indices(pat).0)
2290 fn lines(&self) -> Lines {
2291 Lines(self.split_terminator('\n').map(LinesAnyMap))
2295 #[allow(deprecated)]
2296 fn lines_any(&self) -> LinesAny {
2297 LinesAny(self.lines())
2301 fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
2306 fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
2311 unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
2312 i.get_unchecked(self)
2316 unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
2317 i.get_unchecked_mut(self)
2321 unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
2322 (begin..end).get_unchecked(self)
2326 unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
2327 (begin..end).get_unchecked_mut(self)
2331 fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2332 pat.is_prefix_of(self)
2336 fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
2337 where P::Searcher: ReverseSearcher<'a>
2339 pat.is_suffix_of(self)
2343 fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
2344 where P::Searcher: DoubleEndedSearcher<'a>
2348 let mut matcher = pat.into_searcher(self);
2349 if let Some((a, b)) = matcher.next_reject() {
2351 j = b; // Remember earliest known match, correct it below if
2352 // last match is different
2354 if let Some((_, b)) = matcher.next_reject_back() {
2358 // Searcher is known to return valid indices
2359 self.slice_unchecked(i, j)
2364 fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2365 let mut i = self.len();
2366 let mut matcher = pat.into_searcher(self);
2367 if let Some((a, _)) = matcher.next_reject() {
2371 // Searcher is known to return valid indices
2372 self.slice_unchecked(i, self.len())
2377 fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
2378 where P::Searcher: ReverseSearcher<'a>
2381 let mut matcher = pat.into_searcher(self);
2382 if let Some((_, b)) = matcher.next_reject_back() {
2386 // Searcher is known to return valid indices
2387 self.slice_unchecked(0, j)
2392 fn is_char_boundary(&self, index: usize) -> bool {
2393 // 0 and len are always ok.
2394 // Test for 0 explicitly so that it can optimize out the check
2395 // easily and skip reading string data for that case.
2396 if index == 0 || index == self.len() { return true; }
2397 match self.as_bytes().get(index) {
2399 // This is bit magic equivalent to: b < 128 || b >= 192
2400 Some(&b) => (b as i8) >= -0x40,
2405 fn as_bytes(&self) -> &[u8] {
2406 unsafe { mem::transmute(self) }
2410 unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
2411 mem::transmute(self)
2414 fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2415 pat.into_searcher(self).next_match().map(|(i, _)| i)
2418 fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
2419 where P::Searcher: ReverseSearcher<'a>
2421 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
2424 fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2429 fn split_at(&self, mid: usize) -> (&str, &str) {
2430 // is_char_boundary checks that the index is in [0, .len()]
2431 if self.is_char_boundary(mid) {
2433 (self.slice_unchecked(0, mid),
2434 self.slice_unchecked(mid, self.len()))
2437 slice_error_fail(self, 0, mid)
2441 fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
2442 // is_char_boundary checks that the index is in [0, .len()]
2443 if self.is_char_boundary(mid) {
2444 let len = self.len();
2445 let ptr = self.as_ptr() as *mut u8;
2447 (from_raw_parts_mut(ptr, mid),
2448 from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
2451 slice_error_fail(self, 0, mid)
2456 fn as_ptr(&self) -> *const u8 {
2457 self as *const str as *const u8
2461 fn len(&self) -> usize {
2462 self.as_bytes().len()
2466 fn is_empty(&self) -> bool { self.len() == 0 }
2469 fn parse<'a, T>(&'a self) -> Result<T, T::Error> where T: TryFrom<&'a str> {
2474 #[stable(feature = "rust1", since = "1.0.0")]
2475 impl AsRef<[u8]> for str {
2477 fn as_ref(&self) -> &[u8] {
2482 #[stable(feature = "rust1", since = "1.0.0")]
2483 impl<'a> Default for &'a str {
2484 /// Creates an empty str
2485 fn default() -> &'a str { "" }