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};
22 use iter::{Map, Cloned, FusedIterator, TrustedLen};
23 use iter_private::TrustedRandomAccess;
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.
83 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
84 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
88 /// Basic usage with [`i32`][ithirtytwo], a type that implements `FromStr`:
90 /// [ithirtytwo]: ../../std/primitive.i32.html
93 /// use std::str::FromStr;
96 /// let x = i32::from_str(s).unwrap();
100 #[stable(feature = "rust1", since = "1.0.0")]
101 fn from_str(s: &str) -> Result<Self, Self::Err>;
104 #[stable(feature = "rust1", since = "1.0.0")]
105 impl FromStr for bool {
106 type Err = ParseBoolError;
108 /// Parse a `bool` from a string.
110 /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
111 /// actually be parseable.
116 /// use std::str::FromStr;
118 /// assert_eq!(FromStr::from_str("true"), Ok(true));
119 /// assert_eq!(FromStr::from_str("false"), Ok(false));
120 /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
123 /// Note, in many cases, the `.parse()` method on `str` is more proper.
126 /// assert_eq!("true".parse(), Ok(true));
127 /// assert_eq!("false".parse(), Ok(false));
128 /// assert!("not even a boolean".parse::<bool>().is_err());
131 fn from_str(s: &str) -> Result<bool, ParseBoolError> {
134 "false" => Ok(false),
135 _ => Err(ParseBoolError { _priv: () }),
140 /// An error returned when parsing a `bool` using [`from_str`] fails
142 /// [`from_str`]: ../../std/primitive.bool.html#method.from_str
143 #[derive(Debug, Clone, PartialEq, Eq)]
144 #[stable(feature = "rust1", since = "1.0.0")]
145 pub struct ParseBoolError { _priv: () }
147 #[stable(feature = "rust1", since = "1.0.0")]
148 impl fmt::Display for ParseBoolError {
149 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
150 "provided string was not `true` or `false`".fmt(f)
155 Section: Creating a string
158 /// Errors which can occur when attempting to interpret a sequence of [`u8`]
161 /// [`u8`]: ../../std/primitive.u8.html
163 /// As such, the `from_utf8` family of functions and methods for both [`String`]s
164 /// and [`&str`]s make use of this error, for example.
166 /// [`String`]: ../../std/string/struct.String.html#method.from_utf8
167 /// [`&str`]: ../../std/str/fn.from_utf8.html
168 #[derive(Copy, Eq, PartialEq, Clone, Debug)]
169 #[stable(feature = "rust1", since = "1.0.0")]
170 pub struct Utf8Error {
172 error_len: Option<u8>,
176 /// Returns the index in the given string up to which valid UTF-8 was
179 /// It is the maximum index such that `from_utf8(&input[..index])`
180 /// would return `Ok(_)`.
189 /// // some invalid bytes, in a vector
190 /// let sparkle_heart = vec![0, 159, 146, 150];
192 /// // std::str::from_utf8 returns a Utf8Error
193 /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
195 /// // the second byte is invalid here
196 /// assert_eq!(1, error.valid_up_to());
198 #[stable(feature = "utf8_error", since = "1.5.0")]
199 pub fn valid_up_to(&self) -> usize { self.valid_up_to }
201 /// Provide more information about the failure:
203 /// * `None`: the end of the input was reached unexpectedly.
204 /// `self.valid_up_to()` is 1 to 3 bytes from the end of the input.
205 /// If a byte stream (such as a file or a network socket) is being decoded incrementally,
206 /// this could be a valid `char` whose UTF-8 byte sequence is spanning multiple chunks.
208 /// * `Some(len)`: an unexpected byte was encountered.
209 /// The length provided is that of the invalid byte sequence
210 /// that starts at the index given by `valid_up_to()`.
211 /// Decoding should resume after that sequence
212 /// (after inserting a U+FFFD REPLACEMENT CHARACTER) in case of lossy decoding.
213 #[stable(feature = "utf8_error_error_len", since = "1.20.0")]
214 pub fn error_len(&self) -> Option<usize> {
215 self.error_len.map(|len| len as usize)
219 /// Converts a slice of bytes to a string slice.
221 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
222 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
223 /// the two. Not all byte slices are valid string slices, however: [`&str`] requires
224 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
225 /// UTF-8, and then does the conversion.
227 /// [`&str`]: ../../std/primitive.str.html
228 /// [`u8`]: ../../std/primitive.u8.html
229 /// [byteslice]: ../../std/primitive.slice.html
231 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
232 /// incur the overhead of the validity check, there is an unsafe version of
233 /// this function, [`from_utf8_unchecked`][fromutf8u], which has the same
234 /// behavior but skips the check.
236 /// [fromutf8u]: fn.from_utf8_unchecked.html
238 /// If you need a `String` instead of a `&str`, consider
239 /// [`String::from_utf8`][string].
241 /// [string]: ../../std/string/struct.String.html#method.from_utf8
243 /// Because you can stack-allocate a `[u8; N]`, and you can take a
244 /// [`&[u8]`][byteslice] of it, this function is one way to have a
245 /// stack-allocated string. There is an example of this in the
246 /// examples section below.
248 /// [byteslice]: ../../std/primitive.slice.html
252 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
253 /// provided slice is not UTF-8.
262 /// // some bytes, in a vector
263 /// let sparkle_heart = vec![240, 159, 146, 150];
265 /// // We know these bytes are valid, so just use `unwrap()`.
266 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
268 /// assert_eq!("💖", sparkle_heart);
276 /// // some invalid bytes, in a vector
277 /// let sparkle_heart = vec![0, 159, 146, 150];
279 /// assert!(str::from_utf8(&sparkle_heart).is_err());
282 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
283 /// errors that can be returned.
285 /// [error]: struct.Utf8Error.html
287 /// A "stack allocated string":
292 /// // some bytes, in a stack-allocated array
293 /// let sparkle_heart = [240, 159, 146, 150];
295 /// // We know these bytes are valid, so just use `unwrap()`.
296 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
298 /// assert_eq!("💖", sparkle_heart);
300 #[stable(feature = "rust1", since = "1.0.0")]
301 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
302 run_utf8_validation(v)?;
303 Ok(unsafe { from_utf8_unchecked(v) })
306 /// Converts a mutable slice of bytes to a mutable string slice.
315 /// // "Hello, Rust!" as a mutable vector
316 /// let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
318 /// // As we know these bytes are valid, we can use `unwrap()`
319 /// let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
321 /// assert_eq!("Hello, Rust!", outstr);
329 /// // Some invalid bytes in a mutable vector
330 /// let mut invalid = vec![128, 223];
332 /// assert!(str::from_utf8_mut(&mut invalid).is_err());
334 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
335 /// errors that can be returned.
337 /// [error]: struct.Utf8Error.html
338 #[stable(feature = "str_mut_extras", since = "1.20.0")]
339 pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
340 run_utf8_validation(v)?;
341 Ok(unsafe { from_utf8_unchecked_mut(v) })
344 /// Forms a str from a pointer and a length.
346 /// The `len` argument is the number of bytes in the string.
350 /// This function is unsafe as there is no guarantee that the given pointer is
351 /// valid for `len` bytes, nor whether the lifetime inferred is a suitable
352 /// lifetime for the returned str.
354 /// The data must be valid UTF-8
356 /// `p` must be non-null, even for zero-length strs, because non-zero bits
357 /// are required to distinguish between a zero-length str within `Some()`
358 /// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
359 /// for zero-length strs, though.
363 /// The lifetime for the returned str is inferred from its usage. To
364 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
365 /// source lifetime is safe in the context, such as by providing a helper
366 /// function taking the lifetime of a host value for the str, or by explicit
368 /// Performs the same functionality as `from_raw_parts`, except that a mutable
371 unsafe fn from_raw_parts_mut<'a>(p: *mut u8, len: usize) -> &'a mut str {
372 from_utf8_unchecked_mut(slice::from_raw_parts_mut(p, len))
375 /// Converts a slice of bytes to a string slice without checking
376 /// that the string contains valid UTF-8.
378 /// See the safe version, [`from_utf8`][fromutf8], for more information.
380 /// [fromutf8]: fn.from_utf8.html
384 /// This function is unsafe because it does not check that the bytes passed to
385 /// it are valid UTF-8. If this constraint is violated, undefined behavior
386 /// results, as the rest of Rust assumes that [`&str`]s are valid UTF-8.
388 /// [`&str`]: ../../std/primitive.str.html
397 /// // some bytes, in a vector
398 /// let sparkle_heart = vec![240, 159, 146, 150];
400 /// let sparkle_heart = unsafe {
401 /// str::from_utf8_unchecked(&sparkle_heart)
404 /// assert_eq!("💖", sparkle_heart);
407 #[stable(feature = "rust1", since = "1.0.0")]
408 pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
409 &*(v as *const [u8] as *const str)
412 /// Converts a slice of bytes to a string slice without checking
413 /// that the string contains valid UTF-8; mutable version.
415 /// See the immutable version, [`from_utf8_unchecked()`][fromutf8], for more information.
417 /// [fromutf8]: fn.from_utf8_unchecked.html
426 /// let mut heart = vec![240, 159, 146, 150];
427 /// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
429 /// assert_eq!("💖", heart);
432 #[stable(feature = "str_mut_extras", since = "1.20.0")]
433 pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
434 &mut *(v as *mut [u8] as *mut str)
437 #[stable(feature = "rust1", since = "1.0.0")]
438 impl fmt::Display for Utf8Error {
439 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
440 if let Some(error_len) = self.error_len {
441 write!(f, "invalid utf-8 sequence of {} bytes from index {}",
442 error_len, self.valid_up_to)
444 write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to)
453 /// An iterator over the [`char`]s of a string slice.
455 /// [`char`]: ../../std/primitive.char.html
457 /// This struct is created by the [`chars`] method on [`str`].
458 /// See its documentation for more.
460 /// [`chars`]: ../../std/primitive.str.html#method.chars
461 /// [`str`]: ../../std/primitive.str.html
462 #[derive(Clone, Debug)]
463 #[stable(feature = "rust1", since = "1.0.0")]
464 pub struct Chars<'a> {
465 iter: slice::Iter<'a, u8>
468 /// Returns the initial codepoint accumulator for the first byte.
469 /// The first byte is special, only want bottom 5 bits for width 2, 4 bits
470 /// for width 3, and 3 bits for width 4.
472 fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
474 /// Returns the value of `ch` updated with continuation byte `byte`.
476 fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
478 /// Checks whether the byte is a UTF-8 continuation byte (i.e. starts with the
481 fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
484 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
491 /// Reads the next code point out of a byte iterator (assuming a
492 /// UTF-8-like encoding).
493 #[unstable(feature = "str_internals", issue = "0")]
495 pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
497 let x = *bytes.next()?;
499 return Some(x as u32)
502 // Multibyte case follows
503 // Decode from a byte combination out of: [[[x y] z] w]
504 // NOTE: Performance is sensitive to the exact formulation here
505 let init = utf8_first_byte(x, 2);
506 let y = unwrap_or_0(bytes.next());
507 let mut ch = utf8_acc_cont_byte(init, y);
510 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
511 let z = unwrap_or_0(bytes.next());
512 let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
513 ch = init << 12 | y_z;
516 // use only the lower 3 bits of `init`
517 let w = unwrap_or_0(bytes.next());
518 ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
525 /// Reads the last code point out of a byte iterator (assuming a
526 /// UTF-8-like encoding).
528 fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
529 where I: DoubleEndedIterator<Item = &'a u8>,
532 let w = match bytes.next_back() {
534 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
535 Some(&back_byte) => back_byte,
538 // Multibyte case follows
539 // Decode from a byte combination out of: [x [y [z w]]]
541 let z = unwrap_or_0(bytes.next_back());
542 ch = utf8_first_byte(z, 2);
543 if utf8_is_cont_byte(z) {
544 let y = unwrap_or_0(bytes.next_back());
545 ch = utf8_first_byte(y, 3);
546 if utf8_is_cont_byte(y) {
547 let x = unwrap_or_0(bytes.next_back());
548 ch = utf8_first_byte(x, 4);
549 ch = utf8_acc_cont_byte(ch, y);
551 ch = utf8_acc_cont_byte(ch, z);
553 ch = utf8_acc_cont_byte(ch, w);
558 #[stable(feature = "rust1", since = "1.0.0")]
559 impl<'a> Iterator for Chars<'a> {
563 fn next(&mut self) -> Option<char> {
564 next_code_point(&mut self.iter).map(|ch| {
565 // str invariant says `ch` is a valid Unicode Scalar Value
567 char::from_u32_unchecked(ch)
573 fn count(self) -> usize {
574 // length in `char` is equal to the number of non-continuation bytes
575 let bytes_len = self.iter.len();
576 let mut cont_bytes = 0;
577 for &byte in self.iter {
578 cont_bytes += utf8_is_cont_byte(byte) as usize;
580 bytes_len - cont_bytes
584 fn size_hint(&self) -> (usize, Option<usize>) {
585 let len = self.iter.len();
586 // `(len + 3)` can't overflow, because we know that the `slice::Iter`
587 // belongs to a slice in memory which has a maximum length of
588 // `isize::MAX` (that's well below `usize::MAX`).
589 ((len + 3) / 4, Some(len))
593 fn last(mut self) -> Option<char> {
594 // No need to go through the entire string.
599 #[stable(feature = "rust1", since = "1.0.0")]
600 impl<'a> DoubleEndedIterator for Chars<'a> {
602 fn next_back(&mut self) -> Option<char> {
603 next_code_point_reverse(&mut self.iter).map(|ch| {
604 // str invariant says `ch` is a valid Unicode Scalar Value
606 char::from_u32_unchecked(ch)
612 #[unstable(feature = "fused", issue = "35602")]
613 impl<'a> FusedIterator for Chars<'a> {}
616 /// View the underlying data as a subslice of the original data.
618 /// This has the same lifetime as the original slice, and so the
619 /// iterator can continue to be used while this exists.
624 /// let mut chars = "abc".chars();
626 /// assert_eq!(chars.as_str(), "abc");
628 /// assert_eq!(chars.as_str(), "bc");
631 /// assert_eq!(chars.as_str(), "");
633 #[stable(feature = "iter_to_slice", since = "1.4.0")]
635 pub fn as_str(&self) -> &'a str {
636 unsafe { from_utf8_unchecked(self.iter.as_slice()) }
640 /// An iterator over the [`char`]s of a string slice, and their positions.
642 /// [`char`]: ../../std/primitive.char.html
644 /// This struct is created by the [`char_indices`] method on [`str`].
645 /// See its documentation for more.
647 /// [`char_indices`]: ../../std/primitive.str.html#method.char_indices
648 /// [`str`]: ../../std/primitive.str.html
649 #[derive(Clone, Debug)]
650 #[stable(feature = "rust1", since = "1.0.0")]
651 pub struct CharIndices<'a> {
656 #[stable(feature = "rust1", since = "1.0.0")]
657 impl<'a> Iterator for CharIndices<'a> {
658 type Item = (usize, char);
661 fn next(&mut self) -> Option<(usize, char)> {
662 let pre_len = self.iter.iter.len();
663 match self.iter.next() {
666 let index = self.front_offset;
667 let len = self.iter.iter.len();
668 self.front_offset += pre_len - len;
675 fn count(self) -> usize {
680 fn size_hint(&self) -> (usize, Option<usize>) {
681 self.iter.size_hint()
685 fn last(mut self) -> Option<(usize, char)> {
686 // No need to go through the entire string.
691 #[stable(feature = "rust1", since = "1.0.0")]
692 impl<'a> DoubleEndedIterator for CharIndices<'a> {
694 fn next_back(&mut self) -> Option<(usize, char)> {
695 match self.iter.next_back() {
698 let index = self.front_offset + self.iter.iter.len();
705 #[unstable(feature = "fused", issue = "35602")]
706 impl<'a> FusedIterator for CharIndices<'a> {}
708 impl<'a> CharIndices<'a> {
709 /// View the underlying data as a subslice of the original data.
711 /// This has the same lifetime as the original slice, and so the
712 /// iterator can continue to be used while this exists.
713 #[stable(feature = "iter_to_slice", since = "1.4.0")]
715 pub fn as_str(&self) -> &'a str {
720 /// An iterator over the bytes of a string slice.
722 /// This struct is created by the [`bytes`] method on [`str`].
723 /// See its documentation for more.
725 /// [`bytes`]: ../../std/primitive.str.html#method.bytes
726 /// [`str`]: ../../std/primitive.str.html
727 #[stable(feature = "rust1", since = "1.0.0")]
728 #[derive(Clone, Debug)]
729 pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>);
731 #[stable(feature = "rust1", since = "1.0.0")]
732 impl<'a> Iterator for Bytes<'a> {
736 fn next(&mut self) -> Option<u8> {
741 fn size_hint(&self) -> (usize, Option<usize>) {
746 fn count(self) -> usize {
751 fn last(self) -> Option<Self::Item> {
756 fn nth(&mut self, n: usize) -> Option<Self::Item> {
761 fn all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
766 fn any<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
771 fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where
772 P: FnMut(&Self::Item) -> bool
774 self.0.find(predicate)
778 fn position<P>(&mut self, predicate: P) -> Option<usize> where
779 P: FnMut(Self::Item) -> bool
781 self.0.position(predicate)
785 fn rposition<P>(&mut self, predicate: P) -> Option<usize> where
786 P: FnMut(Self::Item) -> bool
788 self.0.rposition(predicate)
792 #[stable(feature = "rust1", since = "1.0.0")]
793 impl<'a> DoubleEndedIterator for Bytes<'a> {
795 fn next_back(&mut self) -> Option<u8> {
800 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> where
801 P: FnMut(&Self::Item) -> bool
803 self.0.rfind(predicate)
807 #[stable(feature = "rust1", since = "1.0.0")]
808 impl<'a> ExactSizeIterator for Bytes<'a> {
810 fn len(&self) -> usize {
815 fn is_empty(&self) -> bool {
820 #[unstable(feature = "fused", issue = "35602")]
821 impl<'a> FusedIterator for Bytes<'a> {}
823 #[unstable(feature = "trusted_len", issue = "37572")]
824 unsafe impl<'a> TrustedLen for Bytes<'a> {}
827 unsafe impl<'a> TrustedRandomAccess for Bytes<'a> {
828 unsafe fn get_unchecked(&mut self, i: usize) -> u8 {
829 self.0.get_unchecked(i)
831 fn may_have_side_effect() -> bool { false }
834 /// This macro generates a Clone impl for string pattern API
835 /// wrapper types of the form X<'a, P>
836 macro_rules! derive_pattern_clone {
837 (clone $t:ident with |$s:ident| $e:expr) => {
838 impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
839 where P::Searcher: Clone
841 fn clone(&self) -> Self {
849 /// This macro generates two public iterator structs
850 /// wrapping a private internal one that makes use of the `Pattern` API.
852 /// For all patterns `P: Pattern<'a>` the following items will be
853 /// generated (generics omitted):
855 /// struct $forward_iterator($internal_iterator);
856 /// struct $reverse_iterator($internal_iterator);
858 /// impl Iterator for $forward_iterator
859 /// { /* internal ends up calling Searcher::next_match() */ }
861 /// impl DoubleEndedIterator for $forward_iterator
862 /// where P::Searcher: DoubleEndedSearcher
863 /// { /* internal ends up calling Searcher::next_match_back() */ }
865 /// impl Iterator for $reverse_iterator
866 /// where P::Searcher: ReverseSearcher
867 /// { /* internal ends up calling Searcher::next_match_back() */ }
869 /// impl DoubleEndedIterator for $reverse_iterator
870 /// where P::Searcher: DoubleEndedSearcher
871 /// { /* internal ends up calling Searcher::next_match() */ }
873 /// The internal one is defined outside the macro, and has almost the same
874 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
875 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
877 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
878 /// `Pattern` might not return the same elements, so actually implementing
879 /// `DoubleEndedIterator` for it would be incorrect.
880 /// (See the docs in `str::pattern` for more details)
882 /// However, the internal struct still represents a single ended iterator from
883 /// either end, and depending on pattern is also a valid double ended iterator,
884 /// so the two wrapper structs implement `Iterator`
885 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
886 /// to the complex impls seen above.
887 macro_rules! generate_pattern_iterators {
891 $(#[$forward_iterator_attribute:meta])*
892 struct $forward_iterator:ident;
896 $(#[$reverse_iterator_attribute:meta])*
897 struct $reverse_iterator:ident;
899 // Stability of all generated items
901 $(#[$common_stability_attribute:meta])*
903 // Internal almost-iterator that is being delegated to
905 $internal_iterator:ident yielding ($iterty:ty);
907 // Kind of delegation - either single ended or double ended
910 $(#[$forward_iterator_attribute])*
911 $(#[$common_stability_attribute])*
912 pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
914 $(#[$common_stability_attribute])*
915 impl<'a, P: Pattern<'a>> fmt::Debug for $forward_iterator<'a, P>
916 where P::Searcher: fmt::Debug
918 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
919 f.debug_tuple(stringify!($forward_iterator))
925 $(#[$common_stability_attribute])*
926 impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
930 fn next(&mut self) -> Option<$iterty> {
935 $(#[$common_stability_attribute])*
936 impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
937 where P::Searcher: Clone
939 fn clone(&self) -> Self {
940 $forward_iterator(self.0.clone())
944 $(#[$reverse_iterator_attribute])*
945 $(#[$common_stability_attribute])*
946 pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
948 $(#[$common_stability_attribute])*
949 impl<'a, P: Pattern<'a>> fmt::Debug for $reverse_iterator<'a, P>
950 where P::Searcher: fmt::Debug
952 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
953 f.debug_tuple(stringify!($reverse_iterator))
959 $(#[$common_stability_attribute])*
960 impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
961 where P::Searcher: ReverseSearcher<'a>
966 fn next(&mut self) -> Option<$iterty> {
971 $(#[$common_stability_attribute])*
972 impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
973 where P::Searcher: Clone
975 fn clone(&self) -> Self {
976 $reverse_iterator(self.0.clone())
980 #[unstable(feature = "fused", issue = "35602")]
981 impl<'a, P: Pattern<'a>> FusedIterator for $forward_iterator<'a, P> {}
983 #[unstable(feature = "fused", issue = "35602")]
984 impl<'a, P: Pattern<'a>> FusedIterator for $reverse_iterator<'a, P>
985 where P::Searcher: ReverseSearcher<'a> {}
987 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
989 $reverse_iterator, $iterty);
992 double ended; with $(#[$common_stability_attribute:meta])*,
993 $forward_iterator:ident,
994 $reverse_iterator:ident, $iterty:ty
996 $(#[$common_stability_attribute])*
997 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
998 where P::Searcher: DoubleEndedSearcher<'a>
1001 fn next_back(&mut self) -> Option<$iterty> {
1006 $(#[$common_stability_attribute])*
1007 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
1008 where P::Searcher: DoubleEndedSearcher<'a>
1011 fn next_back(&mut self) -> Option<$iterty> {
1017 single ended; with $(#[$common_stability_attribute:meta])*,
1018 $forward_iterator:ident,
1019 $reverse_iterator:ident, $iterty:ty
1023 derive_pattern_clone!{
1025 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
1028 struct SplitInternal<'a, P: Pattern<'a>> {
1031 matcher: P::Searcher,
1032 allow_trailing_empty: bool,
1036 impl<'a, P: Pattern<'a>> fmt::Debug for SplitInternal<'a, P> where P::Searcher: fmt::Debug {
1037 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1038 f.debug_struct("SplitInternal")
1039 .field("start", &self.start)
1040 .field("end", &self.end)
1041 .field("matcher", &self.matcher)
1042 .field("allow_trailing_empty", &self.allow_trailing_empty)
1043 .field("finished", &self.finished)
1048 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
1050 fn get_end(&mut self) -> Option<&'a str> {
1051 if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
1052 self.finished = true;
1054 let string = self.matcher.haystack().slice_unchecked(self.start, self.end);
1063 fn next(&mut self) -> Option<&'a str> {
1064 if self.finished { return None }
1066 let haystack = self.matcher.haystack();
1067 match self.matcher.next_match() {
1068 Some((a, b)) => unsafe {
1069 let elt = haystack.slice_unchecked(self.start, a);
1073 None => self.get_end(),
1078 fn next_back(&mut self) -> Option<&'a str>
1079 where P::Searcher: ReverseSearcher<'a>
1081 if self.finished { return None }
1083 if !self.allow_trailing_empty {
1084 self.allow_trailing_empty = true;
1085 match self.next_back() {
1086 Some(elt) if !elt.is_empty() => return Some(elt),
1087 _ => if self.finished { return None }
1091 let haystack = self.matcher.haystack();
1092 match self.matcher.next_match_back() {
1093 Some((a, b)) => unsafe {
1094 let elt = haystack.slice_unchecked(b, self.end);
1099 self.finished = true;
1100 Some(haystack.slice_unchecked(self.start, self.end))
1106 generate_pattern_iterators! {
1108 /// Created with the method [`split`].
1110 /// [`split`]: ../../std/primitive.str.html#method.split
1113 /// Created with the method [`rsplit`].
1115 /// [`rsplit`]: ../../std/primitive.str.html#method.rsplit
1118 #[stable(feature = "rust1", since = "1.0.0")]
1120 SplitInternal yielding (&'a str);
1121 delegate double ended;
1124 generate_pattern_iterators! {
1126 /// Created with the method [`split_terminator`].
1128 /// [`split_terminator`]: ../../std/primitive.str.html#method.split_terminator
1129 struct SplitTerminator;
1131 /// Created with the method [`rsplit_terminator`].
1133 /// [`rsplit_terminator`]: ../../std/primitive.str.html#method.rsplit_terminator
1134 struct RSplitTerminator;
1136 #[stable(feature = "rust1", since = "1.0.0")]
1138 SplitInternal yielding (&'a str);
1139 delegate double ended;
1142 derive_pattern_clone!{
1143 clone SplitNInternal
1144 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
1147 struct SplitNInternal<'a, P: Pattern<'a>> {
1148 iter: SplitInternal<'a, P>,
1149 /// The number of splits remaining
1153 impl<'a, P: Pattern<'a>> fmt::Debug for SplitNInternal<'a, P> where P::Searcher: fmt::Debug {
1154 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1155 f.debug_struct("SplitNInternal")
1156 .field("iter", &self.iter)
1157 .field("count", &self.count)
1162 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
1164 fn next(&mut self) -> Option<&'a str> {
1167 1 => { self.count = 0; self.iter.get_end() }
1168 _ => { self.count -= 1; self.iter.next() }
1173 fn next_back(&mut self) -> Option<&'a str>
1174 where P::Searcher: ReverseSearcher<'a>
1178 1 => { self.count = 0; self.iter.get_end() }
1179 _ => { self.count -= 1; self.iter.next_back() }
1184 generate_pattern_iterators! {
1186 /// Created with the method [`splitn`].
1188 /// [`splitn`]: ../../std/primitive.str.html#method.splitn
1191 /// Created with the method [`rsplitn`].
1193 /// [`rsplitn`]: ../../std/primitive.str.html#method.rsplitn
1196 #[stable(feature = "rust1", since = "1.0.0")]
1198 SplitNInternal yielding (&'a str);
1199 delegate single ended;
1202 derive_pattern_clone!{
1203 clone MatchIndicesInternal
1204 with |s| MatchIndicesInternal(s.0.clone())
1207 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
1209 impl<'a, P: Pattern<'a>> fmt::Debug for MatchIndicesInternal<'a, P> where P::Searcher: fmt::Debug {
1210 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1211 f.debug_tuple("MatchIndicesInternal")
1217 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
1219 fn next(&mut self) -> Option<(usize, &'a str)> {
1220 self.0.next_match().map(|(start, end)| unsafe {
1221 (start, self.0.haystack().slice_unchecked(start, end))
1226 fn next_back(&mut self) -> Option<(usize, &'a str)>
1227 where P::Searcher: ReverseSearcher<'a>
1229 self.0.next_match_back().map(|(start, end)| unsafe {
1230 (start, self.0.haystack().slice_unchecked(start, end))
1235 generate_pattern_iterators! {
1237 /// Created with the method [`match_indices`].
1239 /// [`match_indices`]: ../../std/primitive.str.html#method.match_indices
1240 struct MatchIndices;
1242 /// Created with the method [`rmatch_indices`].
1244 /// [`rmatch_indices`]: ../../std/primitive.str.html#method.rmatch_indices
1245 struct RMatchIndices;
1247 #[stable(feature = "str_match_indices", since = "1.5.0")]
1249 MatchIndicesInternal yielding ((usize, &'a str));
1250 delegate double ended;
1253 derive_pattern_clone!{
1254 clone MatchesInternal
1255 with |s| MatchesInternal(s.0.clone())
1258 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
1260 impl<'a, P: Pattern<'a>> fmt::Debug for MatchesInternal<'a, P> where P::Searcher: fmt::Debug {
1261 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1262 f.debug_tuple("MatchesInternal")
1268 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
1270 fn next(&mut self) -> Option<&'a str> {
1271 self.0.next_match().map(|(a, b)| unsafe {
1272 // Indices are known to be on utf8 boundaries
1273 self.0.haystack().slice_unchecked(a, b)
1278 fn next_back(&mut self) -> Option<&'a str>
1279 where P::Searcher: ReverseSearcher<'a>
1281 self.0.next_match_back().map(|(a, b)| unsafe {
1282 // Indices are known to be on utf8 boundaries
1283 self.0.haystack().slice_unchecked(a, b)
1288 generate_pattern_iterators! {
1290 /// Created with the method [`matches`].
1292 /// [`matches`]: ../../std/primitive.str.html#method.matches
1295 /// Created with the method [`rmatches`].
1297 /// [`rmatches`]: ../../std/primitive.str.html#method.rmatches
1300 #[stable(feature = "str_matches", since = "1.2.0")]
1302 MatchesInternal yielding (&'a str);
1303 delegate double ended;
1306 /// An iterator over the lines of a string, as string slices.
1308 /// This struct is created with the [`lines`] method on [`str`].
1309 /// See its documentation for more.
1311 /// [`lines`]: ../../std/primitive.str.html#method.lines
1312 /// [`str`]: ../../std/primitive.str.html
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 #[derive(Clone, Debug)]
1315 pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>);
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 impl<'a> Iterator for Lines<'a> {
1319 type Item = &'a str;
1322 fn next(&mut self) -> Option<&'a str> {
1327 fn size_hint(&self) -> (usize, Option<usize>) {
1332 #[stable(feature = "rust1", since = "1.0.0")]
1333 impl<'a> DoubleEndedIterator for Lines<'a> {
1335 fn next_back(&mut self) -> Option<&'a str> {
1340 #[unstable(feature = "fused", issue = "35602")]
1341 impl<'a> FusedIterator for Lines<'a> {}
1343 /// Created with the method [`lines_any`].
1345 /// [`lines_any`]: ../../std/primitive.str.html#method.lines_any
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 #[rustc_deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")]
1348 #[derive(Clone, Debug)]
1349 #[allow(deprecated)]
1350 pub struct LinesAny<'a>(Lines<'a>);
1352 /// A nameable, cloneable fn type
1356 impl<'a> Fn<(&'a str,)> for LinesAnyMap {
1358 extern "rust-call" fn call(&self, (line,): (&'a str,)) -> &'a str {
1360 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
1365 impl<'a> FnMut<(&'a str,)> for LinesAnyMap {
1367 extern "rust-call" fn call_mut(&mut self, (line,): (&'a str,)) -> &'a str {
1368 Fn::call(&*self, (line,))
1372 impl<'a> FnOnce<(&'a str,)> for LinesAnyMap {
1373 type Output = &'a str;
1376 extern "rust-call" fn call_once(self, (line,): (&'a str,)) -> &'a str {
1377 Fn::call(&self, (line,))
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 #[allow(deprecated)]
1383 impl<'a> Iterator for LinesAny<'a> {
1384 type Item = &'a str;
1387 fn next(&mut self) -> Option<&'a str> {
1392 fn size_hint(&self) -> (usize, Option<usize>) {
1397 #[stable(feature = "rust1", since = "1.0.0")]
1398 #[allow(deprecated)]
1399 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1401 fn next_back(&mut self) -> Option<&'a str> {
1406 #[unstable(feature = "fused", issue = "35602")]
1407 #[allow(deprecated)]
1408 impl<'a> FusedIterator for LinesAny<'a> {}
1411 Section: UTF-8 validation
1414 // use truncation to fit u64 into usize
1415 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
1417 /// Returns `true` if any byte in the word `x` is nonascii (>= 128).
1419 fn contains_nonascii(x: usize) -> bool {
1420 (x & NONASCII_MASK) != 0
1423 /// Walks through `iter` checking that it's a valid UTF-8 sequence,
1424 /// returning `true` in that case, or, if it is invalid, `false` with
1425 /// `iter` reset such that it is pointing at the first byte in the
1426 /// invalid sequence.
1428 fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
1432 let usize_bytes = mem::size_of::<usize>();
1433 let ascii_block_size = 2 * usize_bytes;
1434 let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
1437 let old_offset = index;
1439 ($error_len: expr) => {
1440 return Err(Utf8Error {
1441 valid_up_to: old_offset,
1442 error_len: $error_len,
1447 macro_rules! next { () => {{
1449 // we needed data, but there was none: error!
1456 let first = v[index];
1458 let w = UTF8_CHAR_WIDTH[first as usize];
1459 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
1460 // first C2 80 last DF BF
1461 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
1462 // first E0 A0 80 last EF BF BF
1463 // excluding surrogates codepoints \u{d800} to \u{dfff}
1464 // ED A0 80 to ED BF BF
1465 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1466 // first F0 90 80 80 last F4 8F BF BF
1468 // Use the UTF-8 syntax from the RFC
1470 // https://tools.ietf.org/html/rfc3629
1472 // UTF8-2 = %xC2-DF UTF8-tail
1473 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1474 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1475 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1476 // %xF4 %x80-8F 2( UTF8-tail )
1478 2 => if next!() & !CONT_MASK != TAG_CONT_U8 {
1482 match (first, next!()) {
1483 (0xE0 , 0xA0 ... 0xBF) |
1484 (0xE1 ... 0xEC, 0x80 ... 0xBF) |
1485 (0xED , 0x80 ... 0x9F) |
1486 (0xEE ... 0xEF, 0x80 ... 0xBF) => {}
1489 if next!() & !CONT_MASK != TAG_CONT_U8 {
1494 match (first, next!()) {
1495 (0xF0 , 0x90 ... 0xBF) |
1496 (0xF1 ... 0xF3, 0x80 ... 0xBF) |
1497 (0xF4 , 0x80 ... 0x8F) => {}
1500 if next!() & !CONT_MASK != TAG_CONT_U8 {
1503 if next!() & !CONT_MASK != TAG_CONT_U8 {
1511 // Ascii case, try to skip forward quickly.
1512 // When the pointer is aligned, read 2 words of data per iteration
1513 // until we find a word containing a non-ascii byte.
1514 let ptr = v.as_ptr();
1515 let align = unsafe {
1516 // the offset is safe, because `index` is guaranteed inbounds
1517 ptr.offset(index as isize).align_offset(usize_bytes)
1520 while index < blocks_end {
1522 let block = ptr.offset(index as isize) as *const usize;
1523 // break if there is a nonascii byte
1524 let zu = contains_nonascii(*block);
1525 let zv = contains_nonascii(*block.offset(1));
1530 index += ascii_block_size;
1532 // step from the point where the wordwise loop stopped
1533 while index < len && v[index] < 128 {
1545 // https://tools.ietf.org/html/rfc3629
1546 static UTF8_CHAR_WIDTH: [u8; 256] = [
1547 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1548 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1549 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1550 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1551 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1552 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1553 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1554 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1555 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1556 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1557 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1558 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1559 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1560 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1561 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1562 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1565 /// Given a first byte, determines how many bytes are in this UTF-8 character.
1566 #[unstable(feature = "str_internals", issue = "0")]
1568 pub fn utf8_char_width(b: u8) -> usize {
1569 return UTF8_CHAR_WIDTH[b as usize] as usize;
1572 /// Mask of the value bits of a continuation byte.
1573 const CONT_MASK: u8 = 0b0011_1111;
1574 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte.
1575 const TAG_CONT_U8: u8 = 0b1000_0000;
1578 Section: Trait implementations
1584 use slice::{self, SliceIndex};
1586 /// Implements ordering of strings.
1588 /// Strings are ordered lexicographically by their byte values. This orders Unicode code
1589 /// points based on their positions in the code charts. This is not necessarily the same as
1590 /// "alphabetical" order, which varies by language and locale. Sorting strings according to
1591 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1593 #[stable(feature = "rust1", since = "1.0.0")]
1596 fn cmp(&self, other: &str) -> Ordering {
1597 self.as_bytes().cmp(other.as_bytes())
1601 #[stable(feature = "rust1", since = "1.0.0")]
1602 impl PartialEq for str {
1604 fn eq(&self, other: &str) -> bool {
1605 self.as_bytes() == other.as_bytes()
1608 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1611 #[stable(feature = "rust1", since = "1.0.0")]
1614 /// Implements comparison operations on strings.
1616 /// Strings are compared lexicographically by their byte values. This compares Unicode code
1617 /// points based on their positions in the code charts. This is not necessarily the same as
1618 /// "alphabetical" order, which varies by language and locale. Comparing strings according to
1619 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 impl PartialOrd for str {
1624 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1625 Some(self.cmp(other))
1629 /// Implements substring slicing with syntax `&self[begin .. end]`.
1631 /// Returns a 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.
1646 /// let s = "Löwe 老虎 Léopard";
1647 /// assert_eq!(&s[0 .. 1], "L");
1649 /// assert_eq!(&s[1 .. 9], "öwe 老");
1651 /// // these will panic:
1652 /// // byte 2 lies within `ö`:
1655 /// // byte 8 lies within `老`
1658 /// // byte 100 is outside the string
1659 /// // &s[3 .. 100];
1661 #[stable(feature = "rust1", since = "1.0.0")]
1662 impl ops::Index<ops::Range<usize>> for str {
1665 fn index(&self, index: ops::Range<usize>) -> &str {
1670 /// Implements mutable substring slicing with syntax
1671 /// `&mut self[begin .. end]`.
1673 /// Returns a mutable slice of the given string from the byte range
1674 /// [`begin`..`end`).
1676 /// This operation is `O(1)`.
1680 /// Panics if `begin` or `end` does not point to the starting
1681 /// byte offset of a character (as defined by `is_char_boundary`).
1682 /// Requires that `begin <= end` and `end <= len` where `len` is the
1683 /// length of the string.
1684 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1685 impl ops::IndexMut<ops::Range<usize>> for str {
1687 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1688 index.index_mut(self)
1692 /// Implements substring slicing with syntax `&self[.. end]`.
1694 /// Returns a slice of the string from the beginning to byte offset
1697 /// Equivalent to `&self[0 .. end]`.
1698 #[stable(feature = "rust1", since = "1.0.0")]
1699 impl ops::Index<ops::RangeTo<usize>> for str {
1703 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1708 /// Implements mutable substring slicing with syntax `&mut self[.. end]`.
1710 /// Returns a mutable slice of the string from the beginning to byte offset
1713 /// Equivalent to `&mut self[0 .. end]`.
1714 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1715 impl ops::IndexMut<ops::RangeTo<usize>> for str {
1717 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1718 index.index_mut(self)
1722 /// Implements substring slicing with syntax `&self[begin ..]`.
1724 /// Returns a slice of the string from byte offset `begin`
1725 /// to the end of the string.
1727 /// Equivalent to `&self[begin .. len]`.
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 impl ops::Index<ops::RangeFrom<usize>> for str {
1733 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1738 /// Implements mutable substring slicing with syntax `&mut self[begin ..]`.
1740 /// Returns a mutable slice of the string from byte offset `begin`
1741 /// to the end of the string.
1743 /// Equivalent to `&mut self[begin .. len]`.
1744 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1745 impl ops::IndexMut<ops::RangeFrom<usize>> for str {
1747 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1748 index.index_mut(self)
1752 /// Implements substring slicing with syntax `&self[..]`.
1754 /// Returns a slice of the whole string. This operation can
1757 /// Equivalent to `&self[0 .. len]`.
1758 #[stable(feature = "rust1", since = "1.0.0")]
1759 impl ops::Index<ops::RangeFull> for str {
1763 fn index(&self, _index: ops::RangeFull) -> &str {
1768 /// Implements mutable substring slicing with syntax `&mut self[..]`.
1770 /// Returns a mutable slice of the whole string. This operation can
1773 /// Equivalent to `&mut self[0 .. len]`.
1774 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1775 impl ops::IndexMut<ops::RangeFull> for str {
1777 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1782 #[unstable(feature = "inclusive_range",
1783 reason = "recently added, follows RFC",
1785 impl ops::Index<ops::RangeInclusive<usize>> for str {
1789 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1794 #[unstable(feature = "inclusive_range",
1795 reason = "recently added, follows RFC",
1797 impl ops::Index<ops::RangeToInclusive<usize>> for str {
1801 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1806 #[unstable(feature = "inclusive_range",
1807 reason = "recently added, follows RFC",
1809 impl ops::IndexMut<ops::RangeInclusive<usize>> for str {
1811 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1812 index.index_mut(self)
1815 #[unstable(feature = "inclusive_range",
1816 reason = "recently added, follows RFC",
1818 impl ops::IndexMut<ops::RangeToInclusive<usize>> for str {
1820 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1821 index.index_mut(self)
1825 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1826 impl SliceIndex<str> for ops::RangeFull {
1829 fn get(self, slice: &str) -> Option<&Self::Output> {
1833 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1837 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1841 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1845 fn index(self, slice: &str) -> &Self::Output {
1849 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1854 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1855 impl SliceIndex<str> for ops::Range<usize> {
1858 fn get(self, slice: &str) -> Option<&Self::Output> {
1859 if self.start <= self.end &&
1860 slice.is_char_boundary(self.start) &&
1861 slice.is_char_boundary(self.end) {
1862 Some(unsafe { self.get_unchecked(slice) })
1868 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1869 if self.start <= self.end &&
1870 slice.is_char_boundary(self.start) &&
1871 slice.is_char_boundary(self.end) {
1872 Some(unsafe { self.get_unchecked_mut(slice) })
1878 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1879 let ptr = slice.as_ptr().offset(self.start as isize);
1880 let len = self.end - self.start;
1881 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1884 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1885 let ptr = slice.as_ptr().offset(self.start as isize);
1886 let len = self.end - self.start;
1887 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1890 fn index(self, slice: &str) -> &Self::Output {
1891 let (start, end) = (self.start, self.end);
1892 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1895 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1896 // is_char_boundary checks that the index is in [0, .len()]
1897 // canot reuse `get` as above, because of NLL trouble
1898 if self.start <= self.end &&
1899 slice.is_char_boundary(self.start) &&
1900 slice.is_char_boundary(self.end) {
1901 unsafe { self.get_unchecked_mut(slice) }
1903 super::slice_error_fail(slice, self.start, self.end)
1908 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1909 impl SliceIndex<str> for ops::RangeTo<usize> {
1912 fn get(self, slice: &str) -> Option<&Self::Output> {
1913 if slice.is_char_boundary(self.end) {
1914 Some(unsafe { self.get_unchecked(slice) })
1920 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1921 if slice.is_char_boundary(self.end) {
1922 Some(unsafe { self.get_unchecked_mut(slice) })
1928 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1929 let ptr = slice.as_ptr();
1930 super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end))
1933 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1934 let ptr = slice.as_ptr();
1935 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, self.end))
1938 fn index(self, slice: &str) -> &Self::Output {
1940 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end))
1943 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1944 // is_char_boundary checks that the index is in [0, .len()]
1945 if slice.is_char_boundary(self.end) {
1946 unsafe { self.get_unchecked_mut(slice) }
1948 super::slice_error_fail(slice, 0, self.end)
1953 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1954 impl SliceIndex<str> for ops::RangeFrom<usize> {
1957 fn get(self, slice: &str) -> Option<&Self::Output> {
1958 if slice.is_char_boundary(self.start) {
1959 Some(unsafe { self.get_unchecked(slice) })
1965 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1966 if slice.is_char_boundary(self.start) {
1967 Some(unsafe { self.get_unchecked_mut(slice) })
1973 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1974 let ptr = slice.as_ptr().offset(self.start as isize);
1975 let len = slice.len() - self.start;
1976 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1979 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1980 let ptr = slice.as_ptr().offset(self.start as isize);
1981 let len = slice.len() - self.start;
1982 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1985 fn index(self, slice: &str) -> &Self::Output {
1986 let (start, end) = (self.start, slice.len());
1987 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1990 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1991 // is_char_boundary checks that the index is in [0, .len()]
1992 if slice.is_char_boundary(self.start) {
1993 unsafe { self.get_unchecked_mut(slice) }
1995 super::slice_error_fail(slice, self.start, slice.len())
2000 #[unstable(feature = "inclusive_range",
2001 reason = "recently added, follows RFC",
2003 impl SliceIndex<str> for ops::RangeInclusive<usize> {
2006 fn get(self, slice: &str) -> Option<&Self::Output> {
2007 if let Some(end) = self.end.checked_add(1) {
2008 (self.start..end).get(slice)
2014 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
2015 if let Some(end) = self.end.checked_add(1) {
2016 (self.start..end).get_mut(slice)
2022 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
2023 (self.start..self.end+1).get_unchecked(slice)
2026 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
2027 (self.start..self.end+1).get_unchecked_mut(slice)
2030 fn index(self, slice: &str) -> &Self::Output {
2031 assert!(self.end != usize::max_value(),
2032 "attempted to index str up to maximum usize");
2033 (self.start..self.end+1).index(slice)
2036 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
2037 assert!(self.end != usize::max_value(),
2038 "attempted to index str up to maximum usize");
2039 (self.start..self.end+1).index_mut(slice)
2045 #[unstable(feature = "inclusive_range",
2046 reason = "recently added, follows RFC",
2048 impl SliceIndex<str> for ops::RangeToInclusive<usize> {
2051 fn get(self, slice: &str) -> Option<&Self::Output> {
2052 if self.end < usize::max_value() && slice.is_char_boundary(self.end + 1) {
2053 Some(unsafe { self.get_unchecked(slice) })
2059 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
2060 if self.end < usize::max_value() && slice.is_char_boundary(self.end + 1) {
2061 Some(unsafe { self.get_unchecked_mut(slice) })
2067 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
2068 let ptr = slice.as_ptr();
2069 super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end + 1))
2072 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
2073 let ptr = slice.as_ptr();
2074 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, self.end + 1))
2077 fn index(self, slice: &str) -> &Self::Output {
2078 assert!(self.end != usize::max_value(),
2079 "attempted to index str up to maximum usize");
2080 let end = self.end + 1;
2081 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end))
2084 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
2085 assert!(self.end != usize::max_value(),
2086 "attempted to index str up to maximum usize");
2087 if slice.is_char_boundary(self.end) {
2088 unsafe { self.get_unchecked_mut(slice) }
2090 super::slice_error_fail(slice, 0, self.end + 1)
2098 /// Methods for string slices
2099 #[allow(missing_docs)]
2101 #[unstable(feature = "core_str_ext",
2102 reason = "stable interface provided by `impl str` in later crates",
2105 // NB there are no docs here are they're all located on the StrExt trait in
2106 // liballoc, not here.
2108 #[stable(feature = "core", since = "1.6.0")]
2109 fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
2110 #[stable(feature = "core", since = "1.6.0")]
2111 fn chars(&self) -> Chars;
2112 #[stable(feature = "core", since = "1.6.0")]
2113 fn bytes(&self) -> Bytes;
2114 #[stable(feature = "core", since = "1.6.0")]
2115 fn char_indices(&self) -> CharIndices;
2116 #[stable(feature = "core", since = "1.6.0")]
2117 fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P>;
2118 #[stable(feature = "core", since = "1.6.0")]
2119 fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
2120 where P::Searcher: ReverseSearcher<'a>;
2121 #[stable(feature = "core", since = "1.6.0")]
2122 fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P>;
2123 #[stable(feature = "core", since = "1.6.0")]
2124 fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
2125 where P::Searcher: ReverseSearcher<'a>;
2126 #[stable(feature = "core", since = "1.6.0")]
2127 fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P>;
2128 #[stable(feature = "core", since = "1.6.0")]
2129 fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
2130 where P::Searcher: ReverseSearcher<'a>;
2131 #[stable(feature = "core", since = "1.6.0")]
2132 fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P>;
2133 #[stable(feature = "core", since = "1.6.0")]
2134 fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
2135 where P::Searcher: ReverseSearcher<'a>;
2136 #[stable(feature = "core", since = "1.6.0")]
2137 fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P>;
2138 #[stable(feature = "core", since = "1.6.0")]
2139 fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
2140 where P::Searcher: ReverseSearcher<'a>;
2141 #[stable(feature = "core", since = "1.6.0")]
2142 fn lines(&self) -> Lines;
2143 #[stable(feature = "core", since = "1.6.0")]
2144 #[rustc_deprecated(since = "1.6.0", reason = "use lines() instead now")]
2145 #[allow(deprecated)]
2146 fn lines_any(&self) -> LinesAny;
2147 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2148 fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output>;
2149 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2150 fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output>;
2151 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2152 unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output;
2153 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2154 unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output;
2155 #[stable(feature = "core", since = "1.6.0")]
2156 unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str;
2157 #[stable(feature = "core", since = "1.6.0")]
2158 unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str;
2159 #[stable(feature = "core", since = "1.6.0")]
2160 fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
2161 #[stable(feature = "core", since = "1.6.0")]
2162 fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
2163 where P::Searcher: ReverseSearcher<'a>;
2164 #[stable(feature = "core", since = "1.6.0")]
2165 fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
2166 where P::Searcher: DoubleEndedSearcher<'a>;
2167 #[stable(feature = "core", since = "1.6.0")]
2168 fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str;
2169 #[stable(feature = "core", since = "1.6.0")]
2170 fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
2171 where P::Searcher: ReverseSearcher<'a>;
2172 #[stable(feature = "is_char_boundary", since = "1.9.0")]
2173 fn is_char_boundary(&self, index: usize) -> bool;
2174 #[stable(feature = "core", since = "1.6.0")]
2175 fn as_bytes(&self) -> &[u8];
2176 #[stable(feature = "str_mut_extras", since = "1.20.0")]
2177 unsafe fn as_bytes_mut(&mut self) -> &mut [u8];
2178 #[stable(feature = "core", since = "1.6.0")]
2179 fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
2180 #[stable(feature = "core", since = "1.6.0")]
2181 fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
2182 where P::Searcher: ReverseSearcher<'a>;
2183 fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
2184 #[stable(feature = "core", since = "1.6.0")]
2185 fn split_at(&self, mid: usize) -> (&str, &str);
2186 #[stable(feature = "core", since = "1.6.0")]
2187 fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str);
2188 #[stable(feature = "core", since = "1.6.0")]
2189 fn as_ptr(&self) -> *const u8;
2190 #[stable(feature = "core", since = "1.6.0")]
2191 fn len(&self) -> usize;
2192 #[stable(feature = "core", since = "1.6.0")]
2193 fn is_empty(&self) -> bool;
2194 #[stable(feature = "core", since = "1.6.0")]
2195 fn parse<T: FromStr>(&self) -> Result<T, T::Err>;
2198 // truncate `&str` to length at most equal to `max`
2199 // return `true` if it were truncated, and the new str.
2200 fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
2204 while !s.is_char_boundary(max) {
2213 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
2214 const MAX_DISPLAY_LENGTH: usize = 256;
2215 let (truncated, s_trunc) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
2216 let ellipsis = if truncated { "[...]" } else { "" };
2219 if begin > s.len() || end > s.len() {
2220 let oob_index = if begin > s.len() { begin } else { end };
2221 panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
2225 assert!(begin <= end, "begin <= end ({} <= {}) when slicing `{}`{}",
2226 begin, end, s_trunc, ellipsis);
2228 // 3. character boundary
2229 let index = if !s.is_char_boundary(begin) { begin } else { end };
2230 // find the character
2231 let mut char_start = index;
2232 while !s.is_char_boundary(char_start) {
2235 // `char_start` must be less than len and a char boundary
2236 let ch = s[char_start..].chars().next().unwrap();
2237 let char_range = char_start .. char_start + ch.len_utf8();
2238 panic!("byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
2239 index, ch, char_range, s_trunc, ellipsis);
2242 #[stable(feature = "core", since = "1.6.0")]
2243 impl StrExt for str {
2245 fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2246 pat.is_contained_in(self)
2250 fn chars(&self) -> Chars {
2251 Chars{iter: self.as_bytes().iter()}
2255 fn bytes(&self) -> Bytes {
2256 Bytes(self.as_bytes().iter().cloned())
2260 fn char_indices(&self) -> CharIndices {
2261 CharIndices { front_offset: 0, iter: self.chars() }
2265 fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
2266 Split(SplitInternal {
2269 matcher: pat.into_searcher(self),
2270 allow_trailing_empty: true,
2276 fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
2277 where P::Searcher: ReverseSearcher<'a>
2279 RSplit(self.split(pat).0)
2283 fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
2284 SplitN(SplitNInternal {
2285 iter: self.split(pat).0,
2291 fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
2292 where P::Searcher: ReverseSearcher<'a>
2294 RSplitN(self.splitn(count, pat).0)
2298 fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
2299 SplitTerminator(SplitInternal {
2300 allow_trailing_empty: false,
2306 fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
2307 where P::Searcher: ReverseSearcher<'a>
2309 RSplitTerminator(self.split_terminator(pat).0)
2313 fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
2314 Matches(MatchesInternal(pat.into_searcher(self)))
2318 fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
2319 where P::Searcher: ReverseSearcher<'a>
2321 RMatches(self.matches(pat).0)
2325 fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
2326 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
2330 fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
2331 where P::Searcher: ReverseSearcher<'a>
2333 RMatchIndices(self.match_indices(pat).0)
2336 fn lines(&self) -> Lines {
2337 Lines(self.split_terminator('\n').map(LinesAnyMap))
2341 #[allow(deprecated)]
2342 fn lines_any(&self) -> LinesAny {
2343 LinesAny(self.lines())
2347 fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
2352 fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
2357 unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
2358 i.get_unchecked(self)
2362 unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
2363 i.get_unchecked_mut(self)
2367 unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
2368 (begin..end).get_unchecked(self)
2372 unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
2373 (begin..end).get_unchecked_mut(self)
2377 fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2378 pat.is_prefix_of(self)
2382 fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
2383 where P::Searcher: ReverseSearcher<'a>
2385 pat.is_suffix_of(self)
2389 fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
2390 where P::Searcher: DoubleEndedSearcher<'a>
2394 let mut matcher = pat.into_searcher(self);
2395 if let Some((a, b)) = matcher.next_reject() {
2397 j = b; // Remember earliest known match, correct it below if
2398 // last match is different
2400 if let Some((_, b)) = matcher.next_reject_back() {
2404 // Searcher is known to return valid indices
2405 self.slice_unchecked(i, j)
2410 fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2411 let mut i = self.len();
2412 let mut matcher = pat.into_searcher(self);
2413 if let Some((a, _)) = matcher.next_reject() {
2417 // Searcher is known to return valid indices
2418 self.slice_unchecked(i, self.len())
2423 fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
2424 where P::Searcher: ReverseSearcher<'a>
2427 let mut matcher = pat.into_searcher(self);
2428 if let Some((_, b)) = matcher.next_reject_back() {
2432 // Searcher is known to return valid indices
2433 self.slice_unchecked(0, j)
2438 fn is_char_boundary(&self, index: usize) -> bool {
2439 // 0 and len are always ok.
2440 // Test for 0 explicitly so that it can optimize out the check
2441 // easily and skip reading string data for that case.
2442 if index == 0 || index == self.len() { return true; }
2443 match self.as_bytes().get(index) {
2445 // This is bit magic equivalent to: b < 128 || b >= 192
2446 Some(&b) => (b as i8) >= -0x40,
2451 fn as_bytes(&self) -> &[u8] {
2452 unsafe { &*(self as *const str as *const [u8]) }
2456 unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
2457 &mut *(self as *mut str as *mut [u8])
2460 fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2461 pat.into_searcher(self).next_match().map(|(i, _)| i)
2464 fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
2465 where P::Searcher: ReverseSearcher<'a>
2467 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
2470 fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2475 fn split_at(&self, mid: usize) -> (&str, &str) {
2476 // is_char_boundary checks that the index is in [0, .len()]
2477 if self.is_char_boundary(mid) {
2479 (self.slice_unchecked(0, mid),
2480 self.slice_unchecked(mid, self.len()))
2483 slice_error_fail(self, 0, mid)
2487 fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
2488 // is_char_boundary checks that the index is in [0, .len()]
2489 if self.is_char_boundary(mid) {
2490 let len = self.len();
2491 let ptr = self.as_ptr() as *mut u8;
2493 (from_raw_parts_mut(ptr, mid),
2494 from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
2497 slice_error_fail(self, 0, mid)
2502 fn as_ptr(&self) -> *const u8 {
2503 self as *const str as *const u8
2507 fn len(&self) -> usize {
2508 self.as_bytes().len()
2512 fn is_empty(&self) -> bool { self.len() == 0 }
2515 fn parse<T: FromStr>(&self) -> Result<T, T::Err> { FromStr::from_str(self) }
2518 #[stable(feature = "rust1", since = "1.0.0")]
2519 impl AsRef<[u8]> for str {
2521 fn as_ref(&self) -> &[u8] {
2526 #[stable(feature = "rust1", since = "1.0.0")]
2527 impl<'a> Default for &'a str {
2528 /// Creates an empty str
2529 fn default() -> &'a str { "" }