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, Filter};
23 use iter_private::TrustedRandomAccess;
24 use slice::{self, SliceIndex};
29 #[unstable(feature = "str_internals", issue = "0")]
30 #[allow(missing_docs)]
33 /// A trait to abstract the idea of creating a new instance of a type from a
36 /// `FromStr`'s [`from_str`] method is often used implicitly, through
37 /// [`str`]'s [`parse`] method. See [`parse`]'s documentation for examples.
39 /// [`from_str`]: #tymethod.from_str
40 /// [`str`]: ../../std/primitive.str.html
41 /// [`parse`]: ../../std/primitive.str.html#method.parse
45 /// Basic implementation of `FromStr` on an example `Point` type:
48 /// use std::str::FromStr;
49 /// use std::num::ParseIntError;
51 /// #[derive(Debug, PartialEq)]
57 /// impl FromStr for Point {
58 /// type Err = ParseIntError;
60 /// fn from_str(s: &str) -> Result<Self, Self::Err> {
61 /// let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
65 /// let x_fromstr = coords[0].parse::<i32>()?;
66 /// let y_fromstr = coords[1].parse::<i32>()?;
68 /// Ok(Point { x: x_fromstr, y: y_fromstr })
72 /// let p = Point::from_str("(1,2)");
73 /// assert_eq!(p.unwrap(), Point{ x: 1, y: 2} )
75 #[stable(feature = "rust1", since = "1.0.0")]
76 pub trait FromStr: Sized {
77 /// The associated error which can be returned from parsing.
78 #[stable(feature = "rust1", since = "1.0.0")]
81 /// Parses a string `s` to return a value of this type.
83 /// If parsing succeeds, return the value inside [`Ok`], otherwise
84 /// when the string is ill-formatted return an error specific to the
85 /// inside [`Err`]. The error type is specific to implementation of the trait.
87 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
88 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
92 /// Basic usage with [`i32`][ithirtytwo], a type that implements `FromStr`:
94 /// [ithirtytwo]: ../../std/primitive.i32.html
97 /// use std::str::FromStr;
100 /// let x = i32::from_str(s).unwrap();
102 /// assert_eq!(5, x);
104 #[stable(feature = "rust1", since = "1.0.0")]
105 fn from_str(s: &str) -> Result<Self, Self::Err>;
108 #[stable(feature = "rust1", since = "1.0.0")]
109 impl FromStr for bool {
110 type Err = ParseBoolError;
112 /// Parse a `bool` from a string.
114 /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
115 /// actually be parseable.
120 /// use std::str::FromStr;
122 /// assert_eq!(FromStr::from_str("true"), Ok(true));
123 /// assert_eq!(FromStr::from_str("false"), Ok(false));
124 /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
127 /// Note, in many cases, the `.parse()` method on `str` is more proper.
130 /// assert_eq!("true".parse(), Ok(true));
131 /// assert_eq!("false".parse(), Ok(false));
132 /// assert!("not even a boolean".parse::<bool>().is_err());
135 fn from_str(s: &str) -> Result<bool, ParseBoolError> {
138 "false" => Ok(false),
139 _ => Err(ParseBoolError { _priv: () }),
144 /// An error returned when parsing a `bool` using [`from_str`] fails
146 /// [`from_str`]: ../../std/primitive.bool.html#method.from_str
147 #[derive(Debug, Clone, PartialEq, Eq)]
148 #[stable(feature = "rust1", since = "1.0.0")]
149 pub struct ParseBoolError { _priv: () }
151 #[stable(feature = "rust1", since = "1.0.0")]
152 impl fmt::Display for ParseBoolError {
153 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
154 "provided string was not `true` or `false`".fmt(f)
159 Section: Creating a string
162 /// Errors which can occur when attempting to interpret a sequence of [`u8`]
165 /// [`u8`]: ../../std/primitive.u8.html
167 /// As such, the `from_utf8` family of functions and methods for both [`String`]s
168 /// and [`&str`]s make use of this error, for example.
170 /// [`String`]: ../../std/string/struct.String.html#method.from_utf8
171 /// [`&str`]: ../../std/str/fn.from_utf8.html
175 /// This error type’s methods can be used to create functionality
176 /// similar to `String::from_utf8_lossy` without allocating heap memory:
179 /// fn from_utf8_lossy<F>(mut input: &[u8], mut push: F) where F: FnMut(&str) {
181 /// match ::std::str::from_utf8(input) {
187 /// let (valid, after_valid) = input.split_at(error.valid_up_to());
189 /// push(::std::str::from_utf8_unchecked(valid))
191 /// push("\u{FFFD}");
193 /// if let Some(invalid_sequence_length) = error.error_len() {
194 /// input = &after_valid[invalid_sequence_length..]
203 #[derive(Copy, Eq, PartialEq, Clone, Debug)]
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub struct Utf8Error {
207 error_len: Option<u8>,
211 /// Returns the index in the given string up to which valid UTF-8 was
214 /// It is the maximum index such that `from_utf8(&input[..index])`
215 /// would return `Ok(_)`.
224 /// // some invalid bytes, in a vector
225 /// let sparkle_heart = vec![0, 159, 146, 150];
227 /// // std::str::from_utf8 returns a Utf8Error
228 /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
230 /// // the second byte is invalid here
231 /// assert_eq!(1, error.valid_up_to());
233 #[stable(feature = "utf8_error", since = "1.5.0")]
234 pub fn valid_up_to(&self) -> usize { self.valid_up_to }
236 /// Provide more information about the failure:
238 /// * `None`: the end of the input was reached unexpectedly.
239 /// `self.valid_up_to()` is 1 to 3 bytes from the end of the input.
240 /// If a byte stream (such as a file or a network socket) is being decoded incrementally,
241 /// this could be a valid `char` whose UTF-8 byte sequence is spanning multiple chunks.
243 /// * `Some(len)`: an unexpected byte was encountered.
244 /// The length provided is that of the invalid byte sequence
245 /// that starts at the index given by `valid_up_to()`.
246 /// Decoding should resume after that sequence
247 /// (after inserting a U+FFFD REPLACEMENT CHARACTER) in case of lossy decoding.
248 #[stable(feature = "utf8_error_error_len", since = "1.20.0")]
249 pub fn error_len(&self) -> Option<usize> {
250 self.error_len.map(|len| len as usize)
254 /// Converts a slice of bytes to a string slice.
256 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
257 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
258 /// the two. Not all byte slices are valid string slices, however: [`&str`] requires
259 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
260 /// UTF-8, and then does the conversion.
262 /// [`&str`]: ../../std/primitive.str.html
263 /// [`u8`]: ../../std/primitive.u8.html
264 /// [byteslice]: ../../std/primitive.slice.html
266 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
267 /// incur the overhead of the validity check, there is an unsafe version of
268 /// this function, [`from_utf8_unchecked`][fromutf8u], which has the same
269 /// behavior but skips the check.
271 /// [fromutf8u]: fn.from_utf8_unchecked.html
273 /// If you need a `String` instead of a `&str`, consider
274 /// [`String::from_utf8`][string].
276 /// [string]: ../../std/string/struct.String.html#method.from_utf8
278 /// Because you can stack-allocate a `[u8; N]`, and you can take a
279 /// [`&[u8]`][byteslice] of it, this function is one way to have a
280 /// stack-allocated string. There is an example of this in the
281 /// examples section below.
283 /// [byteslice]: ../../std/primitive.slice.html
287 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
288 /// provided slice is not UTF-8.
297 /// // some bytes, in a vector
298 /// let sparkle_heart = vec![240, 159, 146, 150];
300 /// // We know these bytes are valid, so just use `unwrap()`.
301 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
303 /// assert_eq!("💖", sparkle_heart);
311 /// // some invalid bytes, in a vector
312 /// let sparkle_heart = vec![0, 159, 146, 150];
314 /// assert!(str::from_utf8(&sparkle_heart).is_err());
317 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
318 /// errors that can be returned.
320 /// [error]: struct.Utf8Error.html
322 /// A "stack allocated string":
327 /// // some bytes, in a stack-allocated array
328 /// let sparkle_heart = [240, 159, 146, 150];
330 /// // We know these bytes are valid, so just use `unwrap()`.
331 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
333 /// assert_eq!("💖", sparkle_heart);
335 #[stable(feature = "rust1", since = "1.0.0")]
336 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
337 run_utf8_validation(v)?;
338 Ok(unsafe { from_utf8_unchecked(v) })
341 /// Converts a mutable slice of bytes to a mutable string slice.
350 /// // "Hello, Rust!" as a mutable vector
351 /// let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
353 /// // As we know these bytes are valid, we can use `unwrap()`
354 /// let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
356 /// assert_eq!("Hello, Rust!", outstr);
364 /// // Some invalid bytes in a mutable vector
365 /// let mut invalid = vec![128, 223];
367 /// assert!(str::from_utf8_mut(&mut invalid).is_err());
369 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
370 /// errors that can be returned.
372 /// [error]: struct.Utf8Error.html
373 #[stable(feature = "str_mut_extras", since = "1.20.0")]
374 pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
375 run_utf8_validation(v)?;
376 Ok(unsafe { from_utf8_unchecked_mut(v) })
379 /// Converts a slice of bytes to a string slice without checking
380 /// that the string contains valid UTF-8.
382 /// See the safe version, [`from_utf8`][fromutf8], for more information.
384 /// [fromutf8]: fn.from_utf8.html
388 /// This function is unsafe because it does not check that the bytes passed to
389 /// it are valid UTF-8. If this constraint is violated, undefined behavior
390 /// results, as the rest of Rust assumes that [`&str`]s are valid UTF-8.
392 /// [`&str`]: ../../std/primitive.str.html
401 /// // some bytes, in a vector
402 /// let sparkle_heart = vec![240, 159, 146, 150];
404 /// let sparkle_heart = unsafe {
405 /// str::from_utf8_unchecked(&sparkle_heart)
408 /// assert_eq!("💖", sparkle_heart);
411 #[stable(feature = "rust1", since = "1.0.0")]
412 pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
413 &*(v as *const [u8] as *const str)
416 /// Converts a slice of bytes to a string slice without checking
417 /// that the string contains valid UTF-8; mutable version.
419 /// See the immutable version, [`from_utf8_unchecked()`][fromutf8], for more information.
421 /// [fromutf8]: fn.from_utf8_unchecked.html
430 /// let mut heart = vec![240, 159, 146, 150];
431 /// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
433 /// assert_eq!("💖", heart);
436 #[stable(feature = "str_mut_extras", since = "1.20.0")]
437 pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
438 &mut *(v as *mut [u8] as *mut str)
441 #[stable(feature = "rust1", since = "1.0.0")]
442 impl fmt::Display for Utf8Error {
443 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
444 if let Some(error_len) = self.error_len {
445 write!(f, "invalid utf-8 sequence of {} bytes from index {}",
446 error_len, self.valid_up_to)
448 write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to)
457 /// An iterator over the [`char`]s of a string slice.
459 /// [`char`]: ../../std/primitive.char.html
461 /// This struct is created by the [`chars`] method on [`str`].
462 /// See its documentation for more.
464 /// [`chars`]: ../../std/primitive.str.html#method.chars
465 /// [`str`]: ../../std/primitive.str.html
466 #[derive(Clone, Debug)]
467 #[stable(feature = "rust1", since = "1.0.0")]
468 pub struct Chars<'a> {
469 iter: slice::Iter<'a, u8>
472 /// Returns the initial codepoint accumulator for the first byte.
473 /// The first byte is special, only want bottom 5 bits for width 2, 4 bits
474 /// for width 3, and 3 bits for width 4.
476 fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
478 /// Returns the value of `ch` updated with continuation byte `byte`.
480 fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
482 /// Checks whether the byte is a UTF-8 continuation byte (i.e. starts with the
485 fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
488 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
495 /// Reads the next code point out of a byte iterator (assuming a
496 /// UTF-8-like encoding).
497 #[unstable(feature = "str_internals", issue = "0")]
499 pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
501 let x = *bytes.next()?;
503 return Some(x as u32)
506 // Multibyte case follows
507 // Decode from a byte combination out of: [[[x y] z] w]
508 // NOTE: Performance is sensitive to the exact formulation here
509 let init = utf8_first_byte(x, 2);
510 let y = unwrap_or_0(bytes.next());
511 let mut ch = utf8_acc_cont_byte(init, y);
514 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
515 let z = unwrap_or_0(bytes.next());
516 let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
517 ch = init << 12 | y_z;
520 // use only the lower 3 bits of `init`
521 let w = unwrap_or_0(bytes.next());
522 ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
529 /// Reads the last code point out of a byte iterator (assuming a
530 /// UTF-8-like encoding).
532 fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
533 where I: DoubleEndedIterator<Item = &'a u8>,
536 let w = match bytes.next_back() {
538 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
539 Some(&back_byte) => back_byte,
542 // Multibyte case follows
543 // Decode from a byte combination out of: [x [y [z w]]]
545 let z = unwrap_or_0(bytes.next_back());
546 ch = utf8_first_byte(z, 2);
547 if utf8_is_cont_byte(z) {
548 let y = unwrap_or_0(bytes.next_back());
549 ch = utf8_first_byte(y, 3);
550 if utf8_is_cont_byte(y) {
551 let x = unwrap_or_0(bytes.next_back());
552 ch = utf8_first_byte(x, 4);
553 ch = utf8_acc_cont_byte(ch, y);
555 ch = utf8_acc_cont_byte(ch, z);
557 ch = utf8_acc_cont_byte(ch, w);
562 #[stable(feature = "rust1", since = "1.0.0")]
563 impl<'a> Iterator for Chars<'a> {
567 fn next(&mut self) -> Option<char> {
568 next_code_point(&mut self.iter).map(|ch| {
569 // str invariant says `ch` is a valid Unicode Scalar Value
571 char::from_u32_unchecked(ch)
577 fn count(self) -> usize {
578 // length in `char` is equal to the number of non-continuation bytes
579 let bytes_len = self.iter.len();
580 let mut cont_bytes = 0;
581 for &byte in self.iter {
582 cont_bytes += utf8_is_cont_byte(byte) as usize;
584 bytes_len - cont_bytes
588 fn size_hint(&self) -> (usize, Option<usize>) {
589 let len = self.iter.len();
590 // `(len + 3)` can't overflow, because we know that the `slice::Iter`
591 // belongs to a slice in memory which has a maximum length of
592 // `isize::MAX` (that's well below `usize::MAX`).
593 ((len + 3) / 4, Some(len))
597 fn last(mut self) -> Option<char> {
598 // No need to go through the entire string.
603 #[stable(feature = "rust1", since = "1.0.0")]
604 impl<'a> DoubleEndedIterator for Chars<'a> {
606 fn next_back(&mut self) -> Option<char> {
607 next_code_point_reverse(&mut self.iter).map(|ch| {
608 // str invariant says `ch` is a valid Unicode Scalar Value
610 char::from_u32_unchecked(ch)
616 #[stable(feature = "fused", since = "1.26.0")]
617 impl<'a> FusedIterator for Chars<'a> {}
620 /// View the underlying data as a subslice of the original data.
622 /// This has the same lifetime as the original slice, and so the
623 /// iterator can continue to be used while this exists.
628 /// let mut chars = "abc".chars();
630 /// assert_eq!(chars.as_str(), "abc");
632 /// assert_eq!(chars.as_str(), "bc");
635 /// assert_eq!(chars.as_str(), "");
637 #[stable(feature = "iter_to_slice", since = "1.4.0")]
639 pub fn as_str(&self) -> &'a str {
640 unsafe { from_utf8_unchecked(self.iter.as_slice()) }
644 /// An iterator over the [`char`]s of a string slice, and their positions.
646 /// [`char`]: ../../std/primitive.char.html
648 /// This struct is created by the [`char_indices`] method on [`str`].
649 /// See its documentation for more.
651 /// [`char_indices`]: ../../std/primitive.str.html#method.char_indices
652 /// [`str`]: ../../std/primitive.str.html
653 #[derive(Clone, Debug)]
654 #[stable(feature = "rust1", since = "1.0.0")]
655 pub struct CharIndices<'a> {
660 #[stable(feature = "rust1", since = "1.0.0")]
661 impl<'a> Iterator for CharIndices<'a> {
662 type Item = (usize, char);
665 fn next(&mut self) -> Option<(usize, char)> {
666 let pre_len = self.iter.iter.len();
667 match self.iter.next() {
670 let index = self.front_offset;
671 let len = self.iter.iter.len();
672 self.front_offset += pre_len - len;
679 fn count(self) -> usize {
684 fn size_hint(&self) -> (usize, Option<usize>) {
685 self.iter.size_hint()
689 fn last(mut self) -> Option<(usize, char)> {
690 // No need to go through the entire string.
695 #[stable(feature = "rust1", since = "1.0.0")]
696 impl<'a> DoubleEndedIterator for CharIndices<'a> {
698 fn next_back(&mut self) -> Option<(usize, char)> {
699 match self.iter.next_back() {
702 let index = self.front_offset + self.iter.iter.len();
709 #[stable(feature = "fused", since = "1.26.0")]
710 impl<'a> FusedIterator for CharIndices<'a> {}
712 impl<'a> CharIndices<'a> {
713 /// View the underlying data as a subslice of the original data.
715 /// This has the same lifetime as the original slice, and so the
716 /// iterator can continue to be used while this exists.
717 #[stable(feature = "iter_to_slice", since = "1.4.0")]
719 pub fn as_str(&self) -> &'a str {
724 /// An iterator over the bytes of a string slice.
726 /// This struct is created by the [`bytes`] method on [`str`].
727 /// See its documentation for more.
729 /// [`bytes`]: ../../std/primitive.str.html#method.bytes
730 /// [`str`]: ../../std/primitive.str.html
731 #[stable(feature = "rust1", since = "1.0.0")]
732 #[derive(Clone, Debug)]
733 pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>);
735 #[stable(feature = "rust1", since = "1.0.0")]
736 impl<'a> Iterator for Bytes<'a> {
740 fn next(&mut self) -> Option<u8> {
745 fn size_hint(&self) -> (usize, Option<usize>) {
750 fn count(self) -> usize {
755 fn last(self) -> Option<Self::Item> {
760 fn nth(&mut self, n: usize) -> Option<Self::Item> {
765 fn all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
770 fn any<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
775 fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where
776 P: FnMut(&Self::Item) -> bool
778 self.0.find(predicate)
782 fn position<P>(&mut self, predicate: P) -> Option<usize> where
783 P: FnMut(Self::Item) -> bool
785 self.0.position(predicate)
789 fn rposition<P>(&mut self, predicate: P) -> Option<usize> where
790 P: FnMut(Self::Item) -> bool
792 self.0.rposition(predicate)
796 #[stable(feature = "rust1", since = "1.0.0")]
797 impl<'a> DoubleEndedIterator for Bytes<'a> {
799 fn next_back(&mut self) -> Option<u8> {
804 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> where
805 P: FnMut(&Self::Item) -> bool
807 self.0.rfind(predicate)
811 #[stable(feature = "rust1", since = "1.0.0")]
812 impl<'a> ExactSizeIterator for Bytes<'a> {
814 fn len(&self) -> usize {
819 fn is_empty(&self) -> bool {
824 #[stable(feature = "fused", since = "1.26.0")]
825 impl<'a> FusedIterator for Bytes<'a> {}
827 #[unstable(feature = "trusted_len", issue = "37572")]
828 unsafe impl<'a> TrustedLen for Bytes<'a> {}
831 unsafe impl<'a> TrustedRandomAccess for Bytes<'a> {
832 unsafe fn get_unchecked(&mut self, i: usize) -> u8 {
833 self.0.get_unchecked(i)
835 fn may_have_side_effect() -> bool { false }
838 /// This macro generates a Clone impl for string pattern API
839 /// wrapper types of the form X<'a, P>
840 macro_rules! derive_pattern_clone {
841 (clone $t:ident with |$s:ident| $e:expr) => {
842 impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
843 where P::Searcher: Clone
845 fn clone(&self) -> Self {
853 /// This macro generates two public iterator structs
854 /// wrapping a private internal one that makes use of the `Pattern` API.
856 /// For all patterns `P: Pattern<'a>` the following items will be
857 /// generated (generics omitted):
859 /// struct $forward_iterator($internal_iterator);
860 /// struct $reverse_iterator($internal_iterator);
862 /// impl Iterator for $forward_iterator
863 /// { /* internal ends up calling Searcher::next_match() */ }
865 /// impl DoubleEndedIterator for $forward_iterator
866 /// where P::Searcher: DoubleEndedSearcher
867 /// { /* internal ends up calling Searcher::next_match_back() */ }
869 /// impl Iterator for $reverse_iterator
870 /// where P::Searcher: ReverseSearcher
871 /// { /* internal ends up calling Searcher::next_match_back() */ }
873 /// impl DoubleEndedIterator for $reverse_iterator
874 /// where P::Searcher: DoubleEndedSearcher
875 /// { /* internal ends up calling Searcher::next_match() */ }
877 /// The internal one is defined outside the macro, and has almost the same
878 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
879 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
881 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
882 /// `Pattern` might not return the same elements, so actually implementing
883 /// `DoubleEndedIterator` for it would be incorrect.
884 /// (See the docs in `str::pattern` for more details)
886 /// However, the internal struct still represents a single ended iterator from
887 /// either end, and depending on pattern is also a valid double ended iterator,
888 /// so the two wrapper structs implement `Iterator`
889 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
890 /// to the complex impls seen above.
891 macro_rules! generate_pattern_iterators {
895 $(#[$forward_iterator_attribute:meta])*
896 struct $forward_iterator:ident;
900 $(#[$reverse_iterator_attribute:meta])*
901 struct $reverse_iterator:ident;
903 // Stability of all generated items
905 $(#[$common_stability_attribute:meta])*
907 // Internal almost-iterator that is being delegated to
909 $internal_iterator:ident yielding ($iterty:ty);
911 // Kind of delegation - either single ended or double ended
914 $(#[$forward_iterator_attribute])*
915 $(#[$common_stability_attribute])*
916 pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
918 $(#[$common_stability_attribute])*
919 impl<'a, P: Pattern<'a>> fmt::Debug for $forward_iterator<'a, P>
920 where P::Searcher: fmt::Debug
922 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
923 f.debug_tuple(stringify!($forward_iterator))
929 $(#[$common_stability_attribute])*
930 impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
934 fn next(&mut self) -> Option<$iterty> {
939 $(#[$common_stability_attribute])*
940 impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
941 where P::Searcher: Clone
943 fn clone(&self) -> Self {
944 $forward_iterator(self.0.clone())
948 $(#[$reverse_iterator_attribute])*
949 $(#[$common_stability_attribute])*
950 pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
952 $(#[$common_stability_attribute])*
953 impl<'a, P: Pattern<'a>> fmt::Debug for $reverse_iterator<'a, P>
954 where P::Searcher: fmt::Debug
956 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
957 f.debug_tuple(stringify!($reverse_iterator))
963 $(#[$common_stability_attribute])*
964 impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
965 where P::Searcher: ReverseSearcher<'a>
970 fn next(&mut self) -> Option<$iterty> {
975 $(#[$common_stability_attribute])*
976 impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
977 where P::Searcher: Clone
979 fn clone(&self) -> Self {
980 $reverse_iterator(self.0.clone())
984 #[stable(feature = "fused", since = "1.26.0")]
985 impl<'a, P: Pattern<'a>> FusedIterator for $forward_iterator<'a, P> {}
987 #[stable(feature = "fused", since = "1.26.0")]
988 impl<'a, P: Pattern<'a>> FusedIterator for $reverse_iterator<'a, P>
989 where P::Searcher: ReverseSearcher<'a> {}
991 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
993 $reverse_iterator, $iterty);
996 double ended; with $(#[$common_stability_attribute:meta])*,
997 $forward_iterator:ident,
998 $reverse_iterator:ident, $iterty:ty
1000 $(#[$common_stability_attribute])*
1001 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
1002 where P::Searcher: DoubleEndedSearcher<'a>
1005 fn next_back(&mut self) -> Option<$iterty> {
1010 $(#[$common_stability_attribute])*
1011 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
1012 where P::Searcher: DoubleEndedSearcher<'a>
1015 fn next_back(&mut self) -> Option<$iterty> {
1021 single ended; with $(#[$common_stability_attribute:meta])*,
1022 $forward_iterator:ident,
1023 $reverse_iterator:ident, $iterty:ty
1027 derive_pattern_clone!{
1029 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
1032 struct SplitInternal<'a, P: Pattern<'a>> {
1035 matcher: P::Searcher,
1036 allow_trailing_empty: bool,
1040 impl<'a, P: Pattern<'a>> fmt::Debug for SplitInternal<'a, P> where P::Searcher: fmt::Debug {
1041 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1042 f.debug_struct("SplitInternal")
1043 .field("start", &self.start)
1044 .field("end", &self.end)
1045 .field("matcher", &self.matcher)
1046 .field("allow_trailing_empty", &self.allow_trailing_empty)
1047 .field("finished", &self.finished)
1052 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
1054 fn get_end(&mut self) -> Option<&'a str> {
1055 if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
1056 self.finished = true;
1058 let string = self.matcher.haystack().slice_unchecked(self.start, self.end);
1067 fn next(&mut self) -> Option<&'a str> {
1068 if self.finished { return None }
1070 let haystack = self.matcher.haystack();
1071 match self.matcher.next_match() {
1072 Some((a, b)) => unsafe {
1073 let elt = haystack.slice_unchecked(self.start, a);
1077 None => self.get_end(),
1082 fn next_back(&mut self) -> Option<&'a str>
1083 where P::Searcher: ReverseSearcher<'a>
1085 if self.finished { return None }
1087 if !self.allow_trailing_empty {
1088 self.allow_trailing_empty = true;
1089 match self.next_back() {
1090 Some(elt) if !elt.is_empty() => return Some(elt),
1091 _ => if self.finished { return None }
1095 let haystack = self.matcher.haystack();
1096 match self.matcher.next_match_back() {
1097 Some((a, b)) => unsafe {
1098 let elt = haystack.slice_unchecked(b, self.end);
1103 self.finished = true;
1104 Some(haystack.slice_unchecked(self.start, self.end))
1110 generate_pattern_iterators! {
1112 /// Created with the method [`split`].
1114 /// [`split`]: ../../std/primitive.str.html#method.split
1117 /// Created with the method [`rsplit`].
1119 /// [`rsplit`]: ../../std/primitive.str.html#method.rsplit
1122 #[stable(feature = "rust1", since = "1.0.0")]
1124 SplitInternal yielding (&'a str);
1125 delegate double ended;
1128 generate_pattern_iterators! {
1130 /// Created with the method [`split_terminator`].
1132 /// [`split_terminator`]: ../../std/primitive.str.html#method.split_terminator
1133 struct SplitTerminator;
1135 /// Created with the method [`rsplit_terminator`].
1137 /// [`rsplit_terminator`]: ../../std/primitive.str.html#method.rsplit_terminator
1138 struct RSplitTerminator;
1140 #[stable(feature = "rust1", since = "1.0.0")]
1142 SplitInternal yielding (&'a str);
1143 delegate double ended;
1146 derive_pattern_clone!{
1147 clone SplitNInternal
1148 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
1151 struct SplitNInternal<'a, P: Pattern<'a>> {
1152 iter: SplitInternal<'a, P>,
1153 /// The number of splits remaining
1157 impl<'a, P: Pattern<'a>> fmt::Debug for SplitNInternal<'a, P> where P::Searcher: fmt::Debug {
1158 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1159 f.debug_struct("SplitNInternal")
1160 .field("iter", &self.iter)
1161 .field("count", &self.count)
1166 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
1168 fn next(&mut self) -> Option<&'a str> {
1171 1 => { self.count = 0; self.iter.get_end() }
1172 _ => { self.count -= 1; self.iter.next() }
1177 fn next_back(&mut self) -> Option<&'a str>
1178 where P::Searcher: ReverseSearcher<'a>
1182 1 => { self.count = 0; self.iter.get_end() }
1183 _ => { self.count -= 1; self.iter.next_back() }
1188 generate_pattern_iterators! {
1190 /// Created with the method [`splitn`].
1192 /// [`splitn`]: ../../std/primitive.str.html#method.splitn
1195 /// Created with the method [`rsplitn`].
1197 /// [`rsplitn`]: ../../std/primitive.str.html#method.rsplitn
1200 #[stable(feature = "rust1", since = "1.0.0")]
1202 SplitNInternal yielding (&'a str);
1203 delegate single ended;
1206 derive_pattern_clone!{
1207 clone MatchIndicesInternal
1208 with |s| MatchIndicesInternal(s.0.clone())
1211 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
1213 impl<'a, P: Pattern<'a>> fmt::Debug for MatchIndicesInternal<'a, P> where P::Searcher: fmt::Debug {
1214 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1215 f.debug_tuple("MatchIndicesInternal")
1221 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
1223 fn next(&mut self) -> Option<(usize, &'a str)> {
1224 self.0.next_match().map(|(start, end)| unsafe {
1225 (start, self.0.haystack().slice_unchecked(start, end))
1230 fn next_back(&mut self) -> Option<(usize, &'a str)>
1231 where P::Searcher: ReverseSearcher<'a>
1233 self.0.next_match_back().map(|(start, end)| unsafe {
1234 (start, self.0.haystack().slice_unchecked(start, end))
1239 generate_pattern_iterators! {
1241 /// Created with the method [`match_indices`].
1243 /// [`match_indices`]: ../../std/primitive.str.html#method.match_indices
1244 struct MatchIndices;
1246 /// Created with the method [`rmatch_indices`].
1248 /// [`rmatch_indices`]: ../../std/primitive.str.html#method.rmatch_indices
1249 struct RMatchIndices;
1251 #[stable(feature = "str_match_indices", since = "1.5.0")]
1253 MatchIndicesInternal yielding ((usize, &'a str));
1254 delegate double ended;
1257 derive_pattern_clone!{
1258 clone MatchesInternal
1259 with |s| MatchesInternal(s.0.clone())
1262 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
1264 impl<'a, P: Pattern<'a>> fmt::Debug for MatchesInternal<'a, P> where P::Searcher: fmt::Debug {
1265 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1266 f.debug_tuple("MatchesInternal")
1272 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
1274 fn next(&mut self) -> Option<&'a str> {
1275 self.0.next_match().map(|(a, b)| unsafe {
1276 // Indices are known to be on utf8 boundaries
1277 self.0.haystack().slice_unchecked(a, b)
1282 fn next_back(&mut self) -> Option<&'a str>
1283 where P::Searcher: ReverseSearcher<'a>
1285 self.0.next_match_back().map(|(a, b)| unsafe {
1286 // Indices are known to be on utf8 boundaries
1287 self.0.haystack().slice_unchecked(a, b)
1292 generate_pattern_iterators! {
1294 /// Created with the method [`matches`].
1296 /// [`matches`]: ../../std/primitive.str.html#method.matches
1299 /// Created with the method [`rmatches`].
1301 /// [`rmatches`]: ../../std/primitive.str.html#method.rmatches
1304 #[stable(feature = "str_matches", since = "1.2.0")]
1306 MatchesInternal yielding (&'a str);
1307 delegate double ended;
1310 /// An iterator over the lines of a string, as string slices.
1312 /// This struct is created with the [`lines`] method on [`str`].
1313 /// See its documentation for more.
1315 /// [`lines`]: ../../std/primitive.str.html#method.lines
1316 /// [`str`]: ../../std/primitive.str.html
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 #[derive(Clone, Debug)]
1319 pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>);
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 impl<'a> Iterator for Lines<'a> {
1323 type Item = &'a str;
1326 fn next(&mut self) -> Option<&'a str> {
1331 fn size_hint(&self) -> (usize, Option<usize>) {
1336 #[stable(feature = "rust1", since = "1.0.0")]
1337 impl<'a> DoubleEndedIterator for Lines<'a> {
1339 fn next_back(&mut self) -> Option<&'a str> {
1344 #[stable(feature = "fused", since = "1.26.0")]
1345 impl<'a> FusedIterator for Lines<'a> {}
1347 /// Created with the method [`lines_any`].
1349 /// [`lines_any`]: ../../std/primitive.str.html#method.lines_any
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 #[rustc_deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")]
1352 #[derive(Clone, Debug)]
1353 #[allow(deprecated)]
1354 pub struct LinesAny<'a>(Lines<'a>);
1356 /// A nameable, cloneable fn type
1360 impl<'a> Fn<(&'a str,)> for LinesAnyMap {
1362 extern "rust-call" fn call(&self, (line,): (&'a str,)) -> &'a str {
1364 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
1369 impl<'a> FnMut<(&'a str,)> for LinesAnyMap {
1371 extern "rust-call" fn call_mut(&mut self, (line,): (&'a str,)) -> &'a str {
1372 Fn::call(&*self, (line,))
1376 impl<'a> FnOnce<(&'a str,)> for LinesAnyMap {
1377 type Output = &'a str;
1380 extern "rust-call" fn call_once(self, (line,): (&'a str,)) -> &'a str {
1381 Fn::call(&self, (line,))
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 #[allow(deprecated)]
1387 impl<'a> Iterator for LinesAny<'a> {
1388 type Item = &'a str;
1391 fn next(&mut self) -> Option<&'a str> {
1396 fn size_hint(&self) -> (usize, Option<usize>) {
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 #[allow(deprecated)]
1403 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1405 fn next_back(&mut self) -> Option<&'a str> {
1410 #[stable(feature = "fused", since = "1.26.0")]
1411 #[allow(deprecated)]
1412 impl<'a> FusedIterator for LinesAny<'a> {}
1415 Section: UTF-8 validation
1418 // use truncation to fit u64 into usize
1419 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
1421 /// Returns `true` if any byte in the word `x` is nonascii (>= 128).
1423 fn contains_nonascii(x: usize) -> bool {
1424 (x & NONASCII_MASK) != 0
1427 /// Walks through `iter` checking that it's a valid UTF-8 sequence,
1428 /// returning `true` in that case, or, if it is invalid, `false` with
1429 /// `iter` reset such that it is pointing at the first byte in the
1430 /// invalid sequence.
1432 fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
1436 let usize_bytes = mem::size_of::<usize>();
1437 let ascii_block_size = 2 * usize_bytes;
1438 let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
1441 let old_offset = index;
1443 ($error_len: expr) => {
1444 return Err(Utf8Error {
1445 valid_up_to: old_offset,
1446 error_len: $error_len,
1451 macro_rules! next { () => {{
1453 // we needed data, but there was none: error!
1460 let first = v[index];
1462 let w = UTF8_CHAR_WIDTH[first as usize];
1463 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
1464 // first C2 80 last DF BF
1465 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
1466 // first E0 A0 80 last EF BF BF
1467 // excluding surrogates codepoints \u{d800} to \u{dfff}
1468 // ED A0 80 to ED BF BF
1469 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1470 // first F0 90 80 80 last F4 8F BF BF
1472 // Use the UTF-8 syntax from the RFC
1474 // https://tools.ietf.org/html/rfc3629
1476 // UTF8-2 = %xC2-DF UTF8-tail
1477 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1478 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1479 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1480 // %xF4 %x80-8F 2( UTF8-tail )
1482 2 => if next!() & !CONT_MASK != TAG_CONT_U8 {
1486 match (first, next!()) {
1487 (0xE0 , 0xA0 ... 0xBF) |
1488 (0xE1 ... 0xEC, 0x80 ... 0xBF) |
1489 (0xED , 0x80 ... 0x9F) |
1490 (0xEE ... 0xEF, 0x80 ... 0xBF) => {}
1493 if next!() & !CONT_MASK != TAG_CONT_U8 {
1498 match (first, next!()) {
1499 (0xF0 , 0x90 ... 0xBF) |
1500 (0xF1 ... 0xF3, 0x80 ... 0xBF) |
1501 (0xF4 , 0x80 ... 0x8F) => {}
1504 if next!() & !CONT_MASK != TAG_CONT_U8 {
1507 if next!() & !CONT_MASK != TAG_CONT_U8 {
1515 // Ascii case, try to skip forward quickly.
1516 // When the pointer is aligned, read 2 words of data per iteration
1517 // until we find a word containing a non-ascii byte.
1518 let ptr = v.as_ptr();
1519 let align = unsafe {
1520 // the offset is safe, because `index` is guaranteed inbounds
1521 ptr.offset(index as isize).align_offset(usize_bytes)
1524 while index < blocks_end {
1526 let block = ptr.offset(index as isize) as *const usize;
1527 // break if there is a nonascii byte
1528 let zu = contains_nonascii(*block);
1529 let zv = contains_nonascii(*block.offset(1));
1534 index += ascii_block_size;
1536 // step from the point where the wordwise loop stopped
1537 while index < len && v[index] < 128 {
1549 // https://tools.ietf.org/html/rfc3629
1550 static UTF8_CHAR_WIDTH: [u8; 256] = [
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, // 0x1F
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, // 0x3F
1555 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1556 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1557 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1558 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1559 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1560 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1561 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1562 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1563 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1564 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1565 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1566 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1569 /// Given a first byte, determines how many bytes are in this UTF-8 character.
1570 #[unstable(feature = "str_internals", issue = "0")]
1572 pub fn utf8_char_width(b: u8) -> usize {
1573 return UTF8_CHAR_WIDTH[b as usize] as usize;
1576 /// Mask of the value bits of a continuation byte.
1577 const CONT_MASK: u8 = 0b0011_1111;
1578 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte.
1579 const TAG_CONT_U8: u8 = 0b1000_0000;
1582 Section: Trait implementations
1588 use slice::{self, SliceIndex};
1590 /// Implements ordering of strings.
1592 /// Strings are ordered lexicographically by their byte values. This orders Unicode code
1593 /// points based on their positions in the code charts. This is not necessarily the same as
1594 /// "alphabetical" order, which varies by language and locale. Sorting strings according to
1595 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1597 #[stable(feature = "rust1", since = "1.0.0")]
1600 fn cmp(&self, other: &str) -> Ordering {
1601 self.as_bytes().cmp(other.as_bytes())
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 impl PartialEq for str {
1608 fn eq(&self, other: &str) -> bool {
1609 self.as_bytes() == other.as_bytes()
1612 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1615 #[stable(feature = "rust1", since = "1.0.0")]
1618 /// Implements comparison operations on strings.
1620 /// Strings are compared lexicographically by their byte values. This compares Unicode code
1621 /// points based on their positions in the code charts. This is not necessarily the same as
1622 /// "alphabetical" order, which varies by language and locale. Comparing strings according to
1623 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 impl PartialOrd for str {
1628 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1629 Some(self.cmp(other))
1633 /// Implements substring slicing with syntax `&self[begin .. end]`.
1635 /// Returns a slice of the given string from the byte range
1636 /// [`begin`..`end`).
1638 /// This operation is `O(1)`.
1642 /// Panics if `begin` or `end` does not point to the starting
1643 /// byte offset of a character (as defined by `is_char_boundary`).
1644 /// Requires that `begin <= end` and `end <= len` where `len` is the
1645 /// length of the string.
1650 /// let s = "Löwe 老虎 Léopard";
1651 /// assert_eq!(&s[0 .. 1], "L");
1653 /// assert_eq!(&s[1 .. 9], "öwe 老");
1655 /// // these will panic:
1656 /// // byte 2 lies within `ö`:
1659 /// // byte 8 lies within `老`
1662 /// // byte 100 is outside the string
1663 /// // &s[3 .. 100];
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 impl ops::Index<ops::Range<usize>> for str {
1669 fn index(&self, index: ops::Range<usize>) -> &str {
1674 /// Implements mutable substring slicing with syntax
1675 /// `&mut self[begin .. end]`.
1677 /// Returns a mutable slice of the given string from the byte range
1678 /// [`begin`..`end`).
1680 /// This operation is `O(1)`.
1684 /// Panics if `begin` or `end` does not point to the starting
1685 /// byte offset of a character (as defined by `is_char_boundary`).
1686 /// Requires that `begin <= end` and `end <= len` where `len` is the
1687 /// length of the string.
1688 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1689 impl ops::IndexMut<ops::Range<usize>> for str {
1691 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1692 index.index_mut(self)
1696 /// Implements substring slicing with syntax `&self[.. end]`.
1698 /// Returns a slice of the string from the beginning to byte offset
1701 /// Equivalent to `&self[0 .. end]`.
1702 #[stable(feature = "rust1", since = "1.0.0")]
1703 impl ops::Index<ops::RangeTo<usize>> for str {
1707 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1712 /// Implements mutable substring slicing with syntax `&mut self[.. end]`.
1714 /// Returns a mutable slice of the string from the beginning to byte offset
1717 /// Equivalent to `&mut self[0 .. end]`.
1718 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1719 impl ops::IndexMut<ops::RangeTo<usize>> for str {
1721 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1722 index.index_mut(self)
1726 /// Implements substring slicing with syntax `&self[begin ..]`.
1728 /// Returns a slice of the string from byte offset `begin`
1729 /// to the end of the string.
1731 /// Equivalent to `&self[begin .. len]`.
1732 #[stable(feature = "rust1", since = "1.0.0")]
1733 impl ops::Index<ops::RangeFrom<usize>> for str {
1737 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1742 /// Implements mutable substring slicing with syntax `&mut self[begin ..]`.
1744 /// Returns a mutable slice of the string from byte offset `begin`
1745 /// to the end of the string.
1747 /// Equivalent to `&mut self[begin .. len]`.
1748 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1749 impl ops::IndexMut<ops::RangeFrom<usize>> for str {
1751 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1752 index.index_mut(self)
1756 /// Implements substring slicing with syntax `&self[..]`.
1758 /// Returns a slice of the whole string. This operation can
1761 /// Equivalent to `&self[0 .. len]`.
1762 #[stable(feature = "rust1", since = "1.0.0")]
1763 impl ops::Index<ops::RangeFull> for str {
1767 fn index(&self, _index: ops::RangeFull) -> &str {
1772 /// Implements mutable substring slicing with syntax `&mut self[..]`.
1774 /// Returns a mutable slice of the whole string. This operation can
1777 /// Equivalent to `&mut self[0 .. len]`.
1778 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1779 impl ops::IndexMut<ops::RangeFull> for str {
1781 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1786 #[stable(feature = "inclusive_range", since = "1.26.0")]
1787 impl ops::Index<ops::RangeInclusive<usize>> for str {
1791 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1796 #[stable(feature = "inclusive_range", since = "1.26.0")]
1797 impl ops::Index<ops::RangeToInclusive<usize>> for str {
1801 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1806 #[stable(feature = "inclusive_range", since = "1.26.0")]
1807 impl ops::IndexMut<ops::RangeInclusive<usize>> for str {
1809 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1810 index.index_mut(self)
1813 #[stable(feature = "inclusive_range", since = "1.26.0")]
1814 impl ops::IndexMut<ops::RangeToInclusive<usize>> for str {
1816 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1817 index.index_mut(self)
1823 fn str_index_overflow_fail() -> ! {
1824 panic!("attempted to index str up to maximum usize");
1827 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1828 impl SliceIndex<str> for ops::RangeFull {
1831 fn get(self, slice: &str) -> Option<&Self::Output> {
1835 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1839 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1843 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1847 fn index(self, slice: &str) -> &Self::Output {
1851 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1856 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1857 impl SliceIndex<str> for ops::Range<usize> {
1860 fn get(self, slice: &str) -> Option<&Self::Output> {
1861 if self.start <= self.end &&
1862 slice.is_char_boundary(self.start) &&
1863 slice.is_char_boundary(self.end) {
1864 Some(unsafe { self.get_unchecked(slice) })
1870 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1871 if self.start <= self.end &&
1872 slice.is_char_boundary(self.start) &&
1873 slice.is_char_boundary(self.end) {
1874 Some(unsafe { self.get_unchecked_mut(slice) })
1880 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1881 let ptr = slice.as_ptr().offset(self.start as isize);
1882 let len = self.end - self.start;
1883 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1886 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1887 let ptr = slice.as_ptr().offset(self.start as isize);
1888 let len = self.end - self.start;
1889 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1892 fn index(self, slice: &str) -> &Self::Output {
1893 let (start, end) = (self.start, self.end);
1894 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1897 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1898 // is_char_boundary checks that the index is in [0, .len()]
1899 // canot reuse `get` as above, because of NLL trouble
1900 if self.start <= self.end &&
1901 slice.is_char_boundary(self.start) &&
1902 slice.is_char_boundary(self.end) {
1903 unsafe { self.get_unchecked_mut(slice) }
1905 super::slice_error_fail(slice, self.start, self.end)
1910 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1911 impl SliceIndex<str> for ops::RangeTo<usize> {
1914 fn get(self, slice: &str) -> Option<&Self::Output> {
1915 if slice.is_char_boundary(self.end) {
1916 Some(unsafe { self.get_unchecked(slice) })
1922 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1923 if slice.is_char_boundary(self.end) {
1924 Some(unsafe { self.get_unchecked_mut(slice) })
1930 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1931 let ptr = slice.as_ptr();
1932 super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end))
1935 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1936 let ptr = slice.as_ptr();
1937 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, self.end))
1940 fn index(self, slice: &str) -> &Self::Output {
1942 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end))
1945 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1946 // is_char_boundary checks that the index is in [0, .len()]
1947 if slice.is_char_boundary(self.end) {
1948 unsafe { self.get_unchecked_mut(slice) }
1950 super::slice_error_fail(slice, 0, self.end)
1955 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1956 impl SliceIndex<str> for ops::RangeFrom<usize> {
1959 fn get(self, slice: &str) -> Option<&Self::Output> {
1960 if slice.is_char_boundary(self.start) {
1961 Some(unsafe { self.get_unchecked(slice) })
1967 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1968 if slice.is_char_boundary(self.start) {
1969 Some(unsafe { self.get_unchecked_mut(slice) })
1975 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1976 let ptr = slice.as_ptr().offset(self.start as isize);
1977 let len = slice.len() - self.start;
1978 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1981 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1982 let ptr = slice.as_ptr().offset(self.start as isize);
1983 let len = slice.len() - self.start;
1984 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1987 fn index(self, slice: &str) -> &Self::Output {
1988 let (start, end) = (self.start, slice.len());
1989 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1992 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1993 // is_char_boundary checks that the index is in [0, .len()]
1994 if slice.is_char_boundary(self.start) {
1995 unsafe { self.get_unchecked_mut(slice) }
1997 super::slice_error_fail(slice, self.start, slice.len())
2002 #[stable(feature = "inclusive_range", since = "1.26.0")]
2003 impl SliceIndex<str> for ops::RangeInclusive<usize> {
2006 fn get(self, slice: &str) -> Option<&Self::Output> {
2007 if self.end == usize::max_value() { None }
2008 else { (self.start..self.end+1).get(slice) }
2011 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
2012 if self.end == usize::max_value() { None }
2013 else { (self.start..self.end+1).get_mut(slice) }
2016 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
2017 (self.start..self.end+1).get_unchecked(slice)
2020 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
2021 (self.start..self.end+1).get_unchecked_mut(slice)
2024 fn index(self, slice: &str) -> &Self::Output {
2025 if self.end == usize::max_value() { str_index_overflow_fail(); }
2026 (self.start..self.end+1).index(slice)
2029 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
2030 if self.end == usize::max_value() { str_index_overflow_fail(); }
2031 (self.start..self.end+1).index_mut(slice)
2037 #[stable(feature = "inclusive_range", since = "1.26.0")]
2038 impl SliceIndex<str> for ops::RangeToInclusive<usize> {
2041 fn get(self, slice: &str) -> Option<&Self::Output> {
2042 if self.end == usize::max_value() { None }
2043 else { (..self.end+1).get(slice) }
2046 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
2047 if self.end == usize::max_value() { None }
2048 else { (..self.end+1).get_mut(slice) }
2051 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
2052 (..self.end+1).get_unchecked(slice)
2055 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
2056 (..self.end+1).get_unchecked_mut(slice)
2059 fn index(self, slice: &str) -> &Self::Output {
2060 if self.end == usize::max_value() { str_index_overflow_fail(); }
2061 (..self.end+1).index(slice)
2064 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
2065 if self.end == usize::max_value() { str_index_overflow_fail(); }
2066 (..self.end+1).index_mut(slice)
2071 // truncate `&str` to length at most equal to `max`
2072 // return `true` if it were truncated, and the new str.
2073 fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
2077 while !s.is_char_boundary(max) {
2086 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
2087 const MAX_DISPLAY_LENGTH: usize = 256;
2088 let (truncated, s_trunc) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
2089 let ellipsis = if truncated { "[...]" } else { "" };
2092 if begin > s.len() || end > s.len() {
2093 let oob_index = if begin > s.len() { begin } else { end };
2094 panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
2098 assert!(begin <= end, "begin <= end ({} <= {}) when slicing `{}`{}",
2099 begin, end, s_trunc, ellipsis);
2101 // 3. character boundary
2102 let index = if !s.is_char_boundary(begin) { begin } else { end };
2103 // find the character
2104 let mut char_start = index;
2105 while !s.is_char_boundary(char_start) {
2108 // `char_start` must be less than len and a char boundary
2109 let ch = s[char_start..].chars().next().unwrap();
2110 let char_range = char_start .. char_start + ch.len_utf8();
2111 panic!("byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
2112 index, ch, char_range, s_trunc, ellipsis);
2118 /// Returns the length of `self`.
2120 /// This length is in bytes, not [`char`]s or graphemes. In other words,
2121 /// it may not be what a human considers the length of the string.
2123 /// [`char`]: primitive.char.html
2130 /// let len = "foo".len();
2131 /// assert_eq!(3, len);
2133 /// let len = "ƒoo".len(); // fancy f!
2134 /// assert_eq!(4, len);
2136 #[stable(feature = "rust1", since = "1.0.0")]
2138 #[rustc_const_unstable(feature = "const_str_len")]
2139 pub const fn len(&self) -> usize {
2140 self.as_bytes().len()
2143 /// Returns `true` if `self` has a length of zero bytes.
2151 /// assert!(s.is_empty());
2153 /// let s = "not empty";
2154 /// assert!(!s.is_empty());
2157 #[stable(feature = "rust1", since = "1.0.0")]
2158 #[rustc_const_unstable(feature = "const_str_len")]
2159 pub const fn is_empty(&self) -> bool {
2163 /// Checks that `index`-th byte lies at the start and/or end of a
2164 /// UTF-8 code point sequence.
2166 /// The start and end of the string (when `index == self.len()`) are
2167 /// considered to be
2170 /// Returns `false` if `index` is greater than `self.len()`.
2175 /// let s = "Löwe 老虎 Léopard";
2176 /// assert!(s.is_char_boundary(0));
2178 /// assert!(s.is_char_boundary(6));
2179 /// assert!(s.is_char_boundary(s.len()));
2181 /// // second byte of `ö`
2182 /// assert!(!s.is_char_boundary(2));
2184 /// // third byte of `老`
2185 /// assert!(!s.is_char_boundary(8));
2187 #[stable(feature = "is_char_boundary", since = "1.9.0")]
2189 pub fn is_char_boundary(&self, index: usize) -> bool {
2190 // 0 and len are always ok.
2191 // Test for 0 explicitly so that it can optimize out the check
2192 // easily and skip reading string data for that case.
2193 if index == 0 || index == self.len() { return true; }
2194 match self.as_bytes().get(index) {
2196 // This is bit magic equivalent to: b < 128 || b >= 192
2197 Some(&b) => (b as i8) >= -0x40,
2201 /// Converts a string slice to a byte slice. To convert the byte slice back
2202 /// into a string slice, use the [`str::from_utf8`] function.
2204 /// [`str::from_utf8`]: ./str/fn.from_utf8.html
2211 /// let bytes = "bors".as_bytes();
2212 /// assert_eq!(b"bors", bytes);
2214 #[stable(feature = "rust1", since = "1.0.0")]
2216 #[rustc_const_unstable(feature="const_str_as_bytes")]
2217 pub const fn as_bytes(&self) -> &[u8] {
2222 unsafe { Slices { str: self }.slice }
2225 /// Converts a mutable string slice to a mutable byte slice. To convert the
2226 /// mutable byte slice back into a mutable string slice, use the
2227 /// [`str::from_utf8_mut`] function.
2229 /// [`str::from_utf8_mut`]: ./str/fn.from_utf8_mut.html
2236 /// let mut s = String::from("Hello");
2237 /// let bytes = unsafe { s.as_bytes_mut() };
2239 /// assert_eq!(b"Hello", bytes);
2245 /// let mut s = String::from("🗻∈🌏");
2248 /// let bytes = s.as_bytes_mut();
2250 /// bytes[0] = 0xF0;
2251 /// bytes[1] = 0x9F;
2252 /// bytes[2] = 0x8D;
2253 /// bytes[3] = 0x94;
2256 /// assert_eq!("🍔∈🌏", s);
2258 #[stable(feature = "str_mut_extras", since = "1.20.0")]
2260 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
2261 &mut *(self as *mut str as *mut [u8])
2264 /// Converts a string slice to a raw pointer.
2266 /// As string slices are a slice of bytes, the raw pointer points to a
2267 /// [`u8`]. This pointer will be pointing to the first byte of the string
2270 /// [`u8`]: primitive.u8.html
2277 /// let s = "Hello";
2278 /// let ptr = s.as_ptr();
2280 #[stable(feature = "rust1", since = "1.0.0")]
2282 #[rustc_const_unstable(feature = "const_str_as_ptr")]
2283 pub const fn as_ptr(&self) -> *const u8 {
2284 self as *const str as *const u8
2287 /// Returns a subslice of `str`.
2289 /// This is the non-panicking alternative to indexing the `str`. Returns
2290 /// [`None`] whenever equivalent indexing operation would panic.
2292 /// [`None`]: option/enum.Option.html#variant.None
2297 /// let v = String::from("🗻∈🌏");
2299 /// assert_eq!(Some("🗻"), v.get(0..4));
2301 /// // indices not on UTF-8 sequence boundaries
2302 /// assert!(v.get(1..).is_none());
2303 /// assert!(v.get(..8).is_none());
2305 /// // out of bounds
2306 /// assert!(v.get(..42).is_none());
2308 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2310 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
2314 /// Returns a mutable subslice of `str`.
2316 /// This is the non-panicking alternative to indexing the `str`. Returns
2317 /// [`None`] whenever equivalent indexing operation would panic.
2319 /// [`None`]: option/enum.Option.html#variant.None
2324 /// let mut v = String::from("hello");
2325 /// // correct length
2326 /// assert!(v.get_mut(0..5).is_some());
2327 /// // out of bounds
2328 /// assert!(v.get_mut(..42).is_none());
2329 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
2331 /// assert_eq!("hello", v);
2333 /// let s = v.get_mut(0..2);
2334 /// let s = s.map(|s| {
2335 /// s.make_ascii_uppercase();
2338 /// assert_eq!(Some("HE"), s);
2340 /// assert_eq!("HEllo", v);
2342 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2344 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
2348 /// Returns a unchecked subslice of `str`.
2350 /// This is the unchecked alternative to indexing the `str`.
2354 /// Callers of this function are responsible that these preconditions are
2357 /// * The starting index must come before the ending index;
2358 /// * Indexes must be within bounds of the original slice;
2359 /// * Indexes must lie on UTF-8 sequence boundaries.
2361 /// Failing that, the returned string slice may reference invalid memory or
2362 /// violate the invariants communicated by the `str` type.
2369 /// assert_eq!("🗻", v.get_unchecked(0..4));
2370 /// assert_eq!("∈", v.get_unchecked(4..7));
2371 /// assert_eq!("🌏", v.get_unchecked(7..11));
2374 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2376 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
2377 i.get_unchecked(self)
2380 /// Returns a mutable, unchecked subslice of `str`.
2382 /// This is the unchecked alternative to indexing the `str`.
2386 /// Callers of this function are responsible that these preconditions are
2389 /// * The starting index must come before the ending index;
2390 /// * Indexes must be within bounds of the original slice;
2391 /// * Indexes must lie on UTF-8 sequence boundaries.
2393 /// Failing that, the returned string slice may reference invalid memory or
2394 /// violate the invariants communicated by the `str` type.
2399 /// let mut v = String::from("🗻∈🌏");
2401 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
2402 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
2403 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
2406 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2408 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
2409 i.get_unchecked_mut(self)
2412 /// Creates a string slice from another string slice, bypassing safety
2415 /// This is generally not recommended, use with caution! For a safe
2416 /// alternative see [`str`] and [`Index`].
2418 /// [`str`]: primitive.str.html
2419 /// [`Index`]: ops/trait.Index.html
2421 /// This new slice goes from `begin` to `end`, including `begin` but
2422 /// excluding `end`.
2424 /// To get a mutable string slice instead, see the
2425 /// [`slice_mut_unchecked`] method.
2427 /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
2431 /// Callers of this function are responsible that three preconditions are
2434 /// * `begin` must come before `end`.
2435 /// * `begin` and `end` must be byte positions within the string slice.
2436 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2443 /// let s = "Löwe 老虎 Léopard";
2446 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
2449 /// let s = "Hello, world!";
2452 /// assert_eq!("world", s.slice_unchecked(7, 12));
2455 #[stable(feature = "rust1", since = "1.0.0")]
2457 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
2458 (begin..end).get_unchecked(self)
2461 /// Creates a string slice from another string slice, bypassing safety
2463 /// This is generally not recommended, use with caution! For a safe
2464 /// alternative see [`str`] and [`IndexMut`].
2466 /// [`str`]: primitive.str.html
2467 /// [`IndexMut`]: ops/trait.IndexMut.html
2469 /// This new slice goes from `begin` to `end`, including `begin` but
2470 /// excluding `end`.
2472 /// To get an immutable string slice instead, see the
2473 /// [`slice_unchecked`] method.
2475 /// [`slice_unchecked`]: #method.slice_unchecked
2479 /// Callers of this function are responsible that three preconditions are
2482 /// * `begin` must come before `end`.
2483 /// * `begin` and `end` must be byte positions within the string slice.
2484 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2485 #[stable(feature = "str_slice_mut", since = "1.5.0")]
2487 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
2488 (begin..end).get_unchecked_mut(self)
2491 /// Divide one string slice into two at an index.
2493 /// The argument, `mid`, should be a byte offset from the start of the
2494 /// string. It must also be on the boundary of a UTF-8 code point.
2496 /// The two slices returned go from the start of the string slice to `mid`,
2497 /// and from `mid` to the end of the string slice.
2499 /// To get mutable string slices instead, see the [`split_at_mut`]
2502 /// [`split_at_mut`]: #method.split_at_mut
2506 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2507 /// beyond the last code point of the string slice.
2514 /// let s = "Per Martin-Löf";
2516 /// let (first, last) = s.split_at(3);
2518 /// assert_eq!("Per", first);
2519 /// assert_eq!(" Martin-Löf", last);
2522 #[stable(feature = "str_split_at", since = "1.4.0")]
2523 pub fn split_at(&self, mid: usize) -> (&str, &str) {
2524 // is_char_boundary checks that the index is in [0, .len()]
2525 if self.is_char_boundary(mid) {
2527 (self.slice_unchecked(0, mid),
2528 self.slice_unchecked(mid, self.len()))
2531 slice_error_fail(self, 0, mid)
2535 /// Divide one mutable string slice into two at an index.
2537 /// The argument, `mid`, should be a byte offset from the start of the
2538 /// string. It must also be on the boundary of a UTF-8 code point.
2540 /// The two slices returned go from the start of the string slice to `mid`,
2541 /// and from `mid` to the end of the string slice.
2543 /// To get immutable string slices instead, see the [`split_at`] method.
2545 /// [`split_at`]: #method.split_at
2549 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2550 /// beyond the last code point of the string slice.
2557 /// let mut s = "Per Martin-Löf".to_string();
2559 /// let (first, last) = s.split_at_mut(3);
2560 /// first.make_ascii_uppercase();
2561 /// assert_eq!("PER", first);
2562 /// assert_eq!(" Martin-Löf", last);
2564 /// assert_eq!("PER Martin-Löf", s);
2567 #[stable(feature = "str_split_at", since = "1.4.0")]
2568 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
2569 // is_char_boundary checks that the index is in [0, .len()]
2570 if self.is_char_boundary(mid) {
2571 let len = self.len();
2572 let ptr = self.as_ptr() as *mut u8;
2574 (from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
2575 from_utf8_unchecked_mut(slice::from_raw_parts_mut(
2576 ptr.offset(mid as isize),
2581 slice_error_fail(self, 0, mid)
2585 /// Returns an iterator over the [`char`]s of a string slice.
2587 /// As a string slice consists of valid UTF-8, we can iterate through a
2588 /// string slice by [`char`]. This method returns such an iterator.
2590 /// It's important to remember that [`char`] represents a Unicode Scalar
2591 /// Value, and may not match your idea of what a 'character' is. Iteration
2592 /// over grapheme clusters may be what you actually want.
2594 /// [`char`]: primitive.char.html
2601 /// let word = "goodbye";
2603 /// let count = word.chars().count();
2604 /// assert_eq!(7, count);
2606 /// let mut chars = word.chars();
2608 /// assert_eq!(Some('g'), chars.next());
2609 /// assert_eq!(Some('o'), chars.next());
2610 /// assert_eq!(Some('o'), chars.next());
2611 /// assert_eq!(Some('d'), chars.next());
2612 /// assert_eq!(Some('b'), chars.next());
2613 /// assert_eq!(Some('y'), chars.next());
2614 /// assert_eq!(Some('e'), chars.next());
2616 /// assert_eq!(None, chars.next());
2619 /// Remember, [`char`]s may not match your human intuition about characters:
2624 /// let mut chars = y.chars();
2626 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
2627 /// assert_eq!(Some('\u{0306}'), chars.next());
2629 /// assert_eq!(None, chars.next());
2631 #[stable(feature = "rust1", since = "1.0.0")]
2633 pub fn chars(&self) -> Chars {
2634 Chars{iter: self.as_bytes().iter()}
2637 /// Returns an iterator over the [`char`]s of a string slice, and their
2640 /// As a string slice consists of valid UTF-8, we can iterate through a
2641 /// string slice by [`char`]. This method returns an iterator of both
2642 /// these [`char`]s, as well as their byte positions.
2644 /// The iterator yields tuples. The position is first, the [`char`] is
2647 /// [`char`]: primitive.char.html
2654 /// let word = "goodbye";
2656 /// let count = word.char_indices().count();
2657 /// assert_eq!(7, count);
2659 /// let mut char_indices = word.char_indices();
2661 /// assert_eq!(Some((0, 'g')), char_indices.next());
2662 /// assert_eq!(Some((1, 'o')), char_indices.next());
2663 /// assert_eq!(Some((2, 'o')), char_indices.next());
2664 /// assert_eq!(Some((3, 'd')), char_indices.next());
2665 /// assert_eq!(Some((4, 'b')), char_indices.next());
2666 /// assert_eq!(Some((5, 'y')), char_indices.next());
2667 /// assert_eq!(Some((6, 'e')), char_indices.next());
2669 /// assert_eq!(None, char_indices.next());
2672 /// Remember, [`char`]s may not match your human intuition about characters:
2675 /// let yes = "y̆es";
2677 /// let mut char_indices = yes.char_indices();
2679 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
2680 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
2682 /// // note the 3 here - the last character took up two bytes
2683 /// assert_eq!(Some((3, 'e')), char_indices.next());
2684 /// assert_eq!(Some((4, 's')), char_indices.next());
2686 /// assert_eq!(None, char_indices.next());
2688 #[stable(feature = "rust1", since = "1.0.0")]
2690 pub fn char_indices(&self) -> CharIndices {
2691 CharIndices { front_offset: 0, iter: self.chars() }
2694 /// An iterator over the bytes of a string slice.
2696 /// As a string slice consists of a sequence of bytes, we can iterate
2697 /// through a string slice by byte. This method returns such an iterator.
2704 /// let mut bytes = "bors".bytes();
2706 /// assert_eq!(Some(b'b'), bytes.next());
2707 /// assert_eq!(Some(b'o'), bytes.next());
2708 /// assert_eq!(Some(b'r'), bytes.next());
2709 /// assert_eq!(Some(b's'), bytes.next());
2711 /// assert_eq!(None, bytes.next());
2713 #[stable(feature = "rust1", since = "1.0.0")]
2715 pub fn bytes(&self) -> Bytes {
2716 Bytes(self.as_bytes().iter().cloned())
2719 /// Split a string slice by whitespace.
2721 /// The iterator returned will return string slices that are sub-slices of
2722 /// the original string slice, separated by any amount of whitespace.
2724 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2725 /// Core Property `White_Space`.
2732 /// let mut iter = "A few words".split_whitespace();
2734 /// assert_eq!(Some("A"), iter.next());
2735 /// assert_eq!(Some("few"), iter.next());
2736 /// assert_eq!(Some("words"), iter.next());
2738 /// assert_eq!(None, iter.next());
2741 /// All kinds of whitespace are considered:
2744 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
2745 /// assert_eq!(Some("Mary"), iter.next());
2746 /// assert_eq!(Some("had"), iter.next());
2747 /// assert_eq!(Some("a"), iter.next());
2748 /// assert_eq!(Some("little"), iter.next());
2749 /// assert_eq!(Some("lamb"), iter.next());
2751 /// assert_eq!(None, iter.next());
2753 #[stable(feature = "split_whitespace", since = "1.1.0")]
2755 pub fn split_whitespace(&self) -> SplitWhitespace {
2756 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
2759 /// An iterator over the lines of a string, as string slices.
2761 /// Lines are ended with either a newline (`\n`) or a carriage return with
2762 /// a line feed (`\r\n`).
2764 /// The final line ending is optional.
2771 /// let text = "foo\r\nbar\n\nbaz\n";
2772 /// let mut lines = text.lines();
2774 /// assert_eq!(Some("foo"), lines.next());
2775 /// assert_eq!(Some("bar"), lines.next());
2776 /// assert_eq!(Some(""), lines.next());
2777 /// assert_eq!(Some("baz"), lines.next());
2779 /// assert_eq!(None, lines.next());
2782 /// The final line ending isn't required:
2785 /// let text = "foo\nbar\n\r\nbaz";
2786 /// let mut lines = text.lines();
2788 /// assert_eq!(Some("foo"), lines.next());
2789 /// assert_eq!(Some("bar"), lines.next());
2790 /// assert_eq!(Some(""), lines.next());
2791 /// assert_eq!(Some("baz"), lines.next());
2793 /// assert_eq!(None, lines.next());
2795 #[stable(feature = "rust1", since = "1.0.0")]
2797 pub fn lines(&self) -> Lines {
2798 Lines(self.split_terminator('\n').map(LinesAnyMap))
2801 /// An iterator over the lines of a string.
2802 #[stable(feature = "rust1", since = "1.0.0")]
2803 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
2805 #[allow(deprecated)]
2806 pub fn lines_any(&self) -> LinesAny {
2807 LinesAny(self.lines())
2810 /// Returns an iterator of `u16` over the string encoded as UTF-16.
2817 /// let text = "Zażółć gęślą jaźń";
2819 /// let utf8_len = text.len();
2820 /// let utf16_len = text.encode_utf16().count();
2822 /// assert!(utf16_len <= utf8_len);
2824 #[stable(feature = "encode_utf16", since = "1.8.0")]
2825 pub fn encode_utf16(&self) -> EncodeUtf16 {
2826 EncodeUtf16 { chars: self.chars(), extra: 0 }
2829 /// Returns `true` if the given pattern matches a sub-slice of
2830 /// this string slice.
2832 /// Returns `false` if it does not.
2839 /// let bananas = "bananas";
2841 /// assert!(bananas.contains("nana"));
2842 /// assert!(!bananas.contains("apples"));
2844 #[stable(feature = "rust1", since = "1.0.0")]
2846 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2847 pat.is_contained_in(self)
2850 /// Returns `true` if the given pattern matches a prefix of this
2853 /// Returns `false` if it does not.
2860 /// let bananas = "bananas";
2862 /// assert!(bananas.starts_with("bana"));
2863 /// assert!(!bananas.starts_with("nana"));
2865 #[stable(feature = "rust1", since = "1.0.0")]
2866 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2867 pat.is_prefix_of(self)
2870 /// Returns `true` if the given pattern matches a suffix of this
2873 /// Returns `false` if it does not.
2880 /// let bananas = "bananas";
2882 /// assert!(bananas.ends_with("anas"));
2883 /// assert!(!bananas.ends_with("nana"));
2885 #[stable(feature = "rust1", since = "1.0.0")]
2886 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
2887 where P::Searcher: ReverseSearcher<'a>
2889 pat.is_suffix_of(self)
2892 /// Returns the byte index of the first character of this string slice that
2893 /// matches the pattern.
2895 /// Returns [`None`] if the pattern doesn't match.
2897 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2898 /// a character matches.
2900 /// [`char`]: primitive.char.html
2901 /// [`None`]: option/enum.Option.html#variant.None
2905 /// Simple patterns:
2908 /// let s = "Löwe 老虎 Léopard";
2910 /// assert_eq!(s.find('L'), Some(0));
2911 /// assert_eq!(s.find('é'), Some(14));
2912 /// assert_eq!(s.find("Léopard"), Some(13));
2915 /// More complex patterns using point-free style and closures:
2918 /// let s = "Löwe 老虎 Léopard";
2920 /// assert_eq!(s.find(char::is_whitespace), Some(5));
2921 /// assert_eq!(s.find(char::is_lowercase), Some(1));
2922 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
2923 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
2926 /// Not finding the pattern:
2929 /// let s = "Löwe 老虎 Léopard";
2930 /// let x: &[_] = &['1', '2'];
2932 /// assert_eq!(s.find(x), None);
2934 #[stable(feature = "rust1", since = "1.0.0")]
2936 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2937 pat.into_searcher(self).next_match().map(|(i, _)| i)
2940 /// Returns the byte index of the last character of this string slice that
2941 /// matches the pattern.
2943 /// Returns [`None`] if the pattern doesn't match.
2945 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2946 /// a character matches.
2948 /// [`char`]: primitive.char.html
2949 /// [`None`]: option/enum.Option.html#variant.None
2953 /// Simple patterns:
2956 /// let s = "Löwe 老虎 Léopard";
2958 /// assert_eq!(s.rfind('L'), Some(13));
2959 /// assert_eq!(s.rfind('é'), Some(14));
2962 /// More complex patterns with closures:
2965 /// let s = "Löwe 老虎 Léopard";
2967 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
2968 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
2971 /// Not finding the pattern:
2974 /// let s = "Löwe 老虎 Léopard";
2975 /// let x: &[_] = &['1', '2'];
2977 /// assert_eq!(s.rfind(x), None);
2979 #[stable(feature = "rust1", since = "1.0.0")]
2981 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
2982 where P::Searcher: ReverseSearcher<'a>
2984 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
2987 /// An iterator over substrings of this string slice, separated by
2988 /// characters matched by a pattern.
2990 /// The pattern can be a `&str`, [`char`], or a closure that determines the
2993 /// # Iterator behavior
2995 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
2996 /// allows a reverse search and forward/reverse search yields the same
2997 /// elements. This is true for, eg, [`char`] but not for `&str`.
2999 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3001 /// If the pattern allows a reverse search but its results might differ
3002 /// from a forward search, the [`rsplit`] method can be used.
3004 /// [`char`]: primitive.char.html
3005 /// [`rsplit`]: #method.rsplit
3009 /// Simple patterns:
3012 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
3013 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
3015 /// let v: Vec<&str> = "".split('X').collect();
3016 /// assert_eq!(v, [""]);
3018 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
3019 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
3021 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
3022 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3024 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
3025 /// assert_eq!(v, ["abc", "def", "ghi"]);
3027 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
3028 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3031 /// A more complex pattern, using a closure:
3034 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
3035 /// assert_eq!(v, ["abc", "def", "ghi"]);
3038 /// If a string contains multiple contiguous separators, you will end up
3039 /// with empty strings in the output:
3042 /// let x = "||||a||b|c".to_string();
3043 /// let d: Vec<_> = x.split('|').collect();
3045 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3048 /// Contiguous separators are separated by the empty string.
3051 /// let x = "(///)".to_string();
3052 /// let d: Vec<_> = x.split('/').collect();
3054 /// assert_eq!(d, &["(", "", "", ")"]);
3057 /// Separators at the start or end of a string are neighbored
3058 /// by empty strings.
3061 /// let d: Vec<_> = "010".split("0").collect();
3062 /// assert_eq!(d, &["", "1", ""]);
3065 /// When the empty string is used as a separator, it separates
3066 /// every character in the string, along with the beginning
3067 /// and end of the string.
3070 /// let f: Vec<_> = "rust".split("").collect();
3071 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
3074 /// Contiguous separators can lead to possibly surprising behavior
3075 /// when whitespace is used as the separator. This code is correct:
3078 /// let x = " a b c".to_string();
3079 /// let d: Vec<_> = x.split(' ').collect();
3081 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3084 /// It does _not_ give you:
3087 /// assert_eq!(d, &["a", "b", "c"]);
3090 /// Use [`split_whitespace`] for this behavior.
3092 /// [`split_whitespace`]: #method.split_whitespace
3093 #[stable(feature = "rust1", since = "1.0.0")]
3095 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
3096 Split(SplitInternal {
3099 matcher: pat.into_searcher(self),
3100 allow_trailing_empty: true,
3105 /// An iterator over substrings of the given string slice, separated by
3106 /// characters matched by a pattern and yielded in reverse order.
3108 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3111 /// [`char`]: primitive.char.html
3113 /// # Iterator behavior
3115 /// The returned iterator requires that the pattern supports a reverse
3116 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3117 /// search yields the same elements.
3119 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3121 /// For iterating from the front, the [`split`] method can be used.
3123 /// [`split`]: #method.split
3127 /// Simple patterns:
3130 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
3131 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
3133 /// let v: Vec<&str> = "".rsplit('X').collect();
3134 /// assert_eq!(v, [""]);
3136 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
3137 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
3139 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
3140 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
3143 /// A more complex pattern, using a closure:
3146 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
3147 /// assert_eq!(v, ["ghi", "def", "abc"]);
3149 #[stable(feature = "rust1", since = "1.0.0")]
3151 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
3152 where P::Searcher: ReverseSearcher<'a>
3154 RSplit(self.split(pat).0)
3157 /// An iterator over substrings of the given string slice, separated by
3158 /// characters matched by a pattern.
3160 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3163 /// Equivalent to [`split`], except that the trailing substring
3164 /// is skipped if empty.
3166 /// [`split`]: #method.split
3168 /// This method can be used for string data that is _terminated_,
3169 /// rather than _separated_ by a pattern.
3171 /// # Iterator behavior
3173 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3174 /// allows a reverse search and forward/reverse search yields the same
3175 /// elements. This is true for, eg, [`char`] but not for `&str`.
3177 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3178 /// [`char`]: primitive.char.html
3180 /// If the pattern allows a reverse search but its results might differ
3181 /// from a forward search, the [`rsplit_terminator`] method can be used.
3183 /// [`rsplit_terminator`]: #method.rsplit_terminator
3190 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
3191 /// assert_eq!(v, ["A", "B"]);
3193 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
3194 /// assert_eq!(v, ["A", "", "B", ""]);
3196 #[stable(feature = "rust1", since = "1.0.0")]
3198 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
3199 SplitTerminator(SplitInternal {
3200 allow_trailing_empty: false,
3205 /// An iterator over substrings of `self`, separated by characters
3206 /// matched by a pattern and yielded in reverse order.
3208 /// The pattern can be a simple `&str`, [`char`], or a closure that
3209 /// determines the split.
3210 /// Additional libraries might provide more complex patterns like
3211 /// regular expressions.
3213 /// [`char`]: primitive.char.html
3215 /// Equivalent to [`split`], except that the trailing substring is
3216 /// skipped if empty.
3218 /// [`split`]: #method.split
3220 /// This method can be used for string data that is _terminated_,
3221 /// rather than _separated_ by a pattern.
3223 /// # Iterator behavior
3225 /// The returned iterator requires that the pattern supports a
3226 /// reverse search, and it will be double ended if a forward/reverse
3227 /// search yields the same elements.
3229 /// For iterating from the front, the [`split_terminator`] method can be
3232 /// [`split_terminator`]: #method.split_terminator
3237 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
3238 /// assert_eq!(v, ["B", "A"]);
3240 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
3241 /// assert_eq!(v, ["", "B", "", "A"]);
3243 #[stable(feature = "rust1", since = "1.0.0")]
3245 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
3246 where P::Searcher: ReverseSearcher<'a>
3248 RSplitTerminator(self.split_terminator(pat).0)
3251 /// An iterator over substrings of the given string slice, separated by a
3252 /// pattern, restricted to returning at most `n` items.
3254 /// If `n` substrings are returned, the last substring (the `n`th substring)
3255 /// will contain the remainder of the string.
3257 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3260 /// [`char`]: primitive.char.html
3262 /// # Iterator behavior
3264 /// The returned iterator will not be double ended, because it is
3265 /// not efficient to support.
3267 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
3270 /// [`rsplitn`]: #method.rsplitn
3274 /// Simple patterns:
3277 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
3278 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
3280 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
3281 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
3283 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
3284 /// assert_eq!(v, ["abcXdef"]);
3286 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
3287 /// assert_eq!(v, [""]);
3290 /// A more complex pattern, using a closure:
3293 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
3294 /// assert_eq!(v, ["abc", "defXghi"]);
3296 #[stable(feature = "rust1", since = "1.0.0")]
3298 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
3299 SplitN(SplitNInternal {
3300 iter: self.split(pat).0,
3305 /// An iterator over substrings of this string slice, separated by a
3306 /// pattern, starting from the end of the string, restricted to returning
3307 /// at most `n` items.
3309 /// If `n` substrings are returned, the last substring (the `n`th substring)
3310 /// will contain the remainder of the string.
3312 /// The pattern can be a `&str`, [`char`], or a closure that
3313 /// determines the split.
3315 /// [`char`]: primitive.char.html
3317 /// # Iterator behavior
3319 /// The returned iterator will not be double ended, because it is not
3320 /// efficient to support.
3322 /// For splitting from the front, the [`splitn`] method can be used.
3324 /// [`splitn`]: #method.splitn
3328 /// Simple patterns:
3331 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
3332 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
3334 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
3335 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
3337 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
3338 /// assert_eq!(v, ["leopard", "lion::tiger"]);
3341 /// A more complex pattern, using a closure:
3344 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
3345 /// assert_eq!(v, ["ghi", "abc1def"]);
3347 #[stable(feature = "rust1", since = "1.0.0")]
3349 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
3350 where P::Searcher: ReverseSearcher<'a>
3352 RSplitN(self.splitn(n, pat).0)
3355 /// An iterator over the disjoint matches of a pattern within the given string
3358 /// The pattern can be a `&str`, [`char`], or a closure that
3359 /// determines if a character matches.
3361 /// [`char`]: primitive.char.html
3363 /// # Iterator behavior
3365 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3366 /// allows a reverse search and forward/reverse search yields the same
3367 /// elements. This is true for, eg, [`char`] but not for `&str`.
3369 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3370 /// [`char`]: primitive.char.html
3372 /// If the pattern allows a reverse search but its results might differ
3373 /// from a forward search, the [`rmatches`] method can be used.
3375 /// [`rmatches`]: #method.rmatches
3382 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
3383 /// assert_eq!(v, ["abc", "abc", "abc"]);
3385 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
3386 /// assert_eq!(v, ["1", "2", "3"]);
3388 #[stable(feature = "str_matches", since = "1.2.0")]
3390 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
3391 Matches(MatchesInternal(pat.into_searcher(self)))
3394 /// An iterator over the disjoint matches of a pattern within this string slice,
3395 /// yielded in reverse order.
3397 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3398 /// a character matches.
3400 /// [`char`]: primitive.char.html
3402 /// # Iterator behavior
3404 /// The returned iterator requires that the pattern supports a reverse
3405 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3406 /// search yields the same elements.
3408 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3410 /// For iterating from the front, the [`matches`] method can be used.
3412 /// [`matches`]: #method.matches
3419 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
3420 /// assert_eq!(v, ["abc", "abc", "abc"]);
3422 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
3423 /// assert_eq!(v, ["3", "2", "1"]);
3425 #[stable(feature = "str_matches", since = "1.2.0")]
3427 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
3428 where P::Searcher: ReverseSearcher<'a>
3430 RMatches(self.matches(pat).0)
3433 /// An iterator over the disjoint matches of a pattern within this string
3434 /// slice as well as the index that the match starts at.
3436 /// For matches of `pat` within `self` that overlap, only the indices
3437 /// corresponding to the first match are returned.
3439 /// The pattern can be a `&str`, [`char`], or a closure that determines
3440 /// if a character matches.
3442 /// [`char`]: primitive.char.html
3444 /// # Iterator behavior
3446 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3447 /// allows a reverse search and forward/reverse search yields the same
3448 /// elements. This is true for, eg, [`char`] but not for `&str`.
3450 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3452 /// If the pattern allows a reverse search but its results might differ
3453 /// from a forward search, the [`rmatch_indices`] method can be used.
3455 /// [`rmatch_indices`]: #method.rmatch_indices
3462 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
3463 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
3465 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
3466 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
3468 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
3469 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
3471 #[stable(feature = "str_match_indices", since = "1.5.0")]
3473 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
3474 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
3477 /// An iterator over the disjoint matches of a pattern within `self`,
3478 /// yielded in reverse order along with the index of the match.
3480 /// For matches of `pat` within `self` that overlap, only the indices
3481 /// corresponding to the last match are returned.
3483 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
3484 /// character matches.
3486 /// [`char`]: primitive.char.html
3488 /// # Iterator behavior
3490 /// The returned iterator requires that the pattern supports a reverse
3491 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3492 /// search yields the same elements.
3494 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3496 /// For iterating from the front, the [`match_indices`] method can be used.
3498 /// [`match_indices`]: #method.match_indices
3505 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
3506 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
3508 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
3509 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
3511 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
3512 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
3514 #[stable(feature = "str_match_indices", since = "1.5.0")]
3516 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
3517 where P::Searcher: ReverseSearcher<'a>
3519 RMatchIndices(self.match_indices(pat).0)
3522 /// Returns a string slice with leading and trailing whitespace removed.
3524 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3525 /// Core Property `White_Space`.
3532 /// let s = " Hello\tworld\t";
3534 /// assert_eq!("Hello\tworld", s.trim());
3536 #[stable(feature = "rust1", since = "1.0.0")]
3537 pub fn trim(&self) -> &str {
3538 self.trim_matches(|c: char| c.is_whitespace())
3541 /// Returns a string slice with leading whitespace removed.
3543 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3544 /// Core Property `White_Space`.
3546 /// # Text directionality
3548 /// A string is a sequence of bytes. 'Left' in this context means the first
3549 /// position of that byte string; for a language like Arabic or Hebrew
3550 /// which are 'right to left' rather than 'left to right', this will be
3551 /// the _right_ side, not the left.
3558 /// let s = " Hello\tworld\t";
3560 /// assert_eq!("Hello\tworld\t", s.trim_left());
3566 /// let s = " English";
3567 /// assert!(Some('E') == s.trim_left().chars().next());
3569 /// let s = " עברית";
3570 /// assert!(Some('ע') == s.trim_left().chars().next());
3572 #[stable(feature = "rust1", since = "1.0.0")]
3573 pub fn trim_left(&self) -> &str {
3574 self.trim_left_matches(|c: char| c.is_whitespace())
3577 /// Returns a string slice with trailing whitespace removed.
3579 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3580 /// Core Property `White_Space`.
3582 /// # Text directionality
3584 /// A string is a sequence of bytes. 'Right' in this context means the last
3585 /// position of that byte string; for a language like Arabic or Hebrew
3586 /// which are 'right to left' rather than 'left to right', this will be
3587 /// the _left_ side, not the right.
3594 /// let s = " Hello\tworld\t";
3596 /// assert_eq!(" Hello\tworld", s.trim_right());
3602 /// let s = "English ";
3603 /// assert!(Some('h') == s.trim_right().chars().rev().next());
3605 /// let s = "עברית ";
3606 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
3608 #[stable(feature = "rust1", since = "1.0.0")]
3609 pub fn trim_right(&self) -> &str {
3610 self.trim_right_matches(|c: char| c.is_whitespace())
3613 /// Returns a string slice with all prefixes and suffixes that match a
3614 /// pattern repeatedly removed.
3616 /// The pattern can be a [`char`] or a closure that determines if a
3617 /// character matches.
3619 /// [`char`]: primitive.char.html
3623 /// Simple patterns:
3626 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
3627 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
3629 /// let x: &[_] = &['1', '2'];
3630 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
3633 /// A more complex pattern, using a closure:
3636 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
3638 #[stable(feature = "rust1", since = "1.0.0")]
3639 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3640 where P::Searcher: DoubleEndedSearcher<'a>
3644 let mut matcher = pat.into_searcher(self);
3645 if let Some((a, b)) = matcher.next_reject() {
3647 j = b; // Remember earliest known match, correct it below if
3648 // last match is different
3650 if let Some((_, b)) = matcher.next_reject_back() {
3654 // Searcher is known to return valid indices
3655 self.slice_unchecked(i, j)
3659 /// Returns a string slice with all prefixes that match a pattern
3660 /// repeatedly removed.
3662 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3663 /// a character matches.
3665 /// [`char`]: primitive.char.html
3667 /// # Text directionality
3669 /// A string is a sequence of bytes. 'Left' in this context means the first
3670 /// position of that byte string; for a language like Arabic or Hebrew
3671 /// which are 'right to left' rather than 'left to right', this will be
3672 /// the _right_ side, not the left.
3679 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
3680 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
3682 /// let x: &[_] = &['1', '2'];
3683 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
3685 #[stable(feature = "rust1", since = "1.0.0")]
3686 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3687 let mut i = self.len();
3688 let mut matcher = pat.into_searcher(self);
3689 if let Some((a, _)) = matcher.next_reject() {
3693 // Searcher is known to return valid indices
3694 self.slice_unchecked(i, self.len())
3698 /// Returns a string slice with all suffixes that match a pattern
3699 /// repeatedly removed.
3701 /// The pattern can be a `&str`, [`char`], or a closure that
3702 /// determines if a character matches.
3704 /// [`char`]: primitive.char.html
3706 /// # Text directionality
3708 /// A string is a sequence of bytes. 'Right' in this context means the last
3709 /// position of that byte string; for a language like Arabic or Hebrew
3710 /// which are 'right to left' rather than 'left to right', this will be
3711 /// the _left_ side, not the right.
3715 /// Simple patterns:
3718 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
3719 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
3721 /// let x: &[_] = &['1', '2'];
3722 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
3725 /// A more complex pattern, using a closure:
3728 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
3730 #[stable(feature = "rust1", since = "1.0.0")]
3731 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3732 where P::Searcher: ReverseSearcher<'a>
3735 let mut matcher = pat.into_searcher(self);
3736 if let Some((_, b)) = matcher.next_reject_back() {
3740 // Searcher is known to return valid indices
3741 self.slice_unchecked(0, j)
3745 /// Parses this string slice into another type.
3747 /// Because `parse` is so general, it can cause problems with type
3748 /// inference. As such, `parse` is one of the few times you'll see
3749 /// the syntax affectionately known as the 'turbofish': `::<>`. This
3750 /// helps the inference algorithm understand specifically which type
3751 /// you're trying to parse into.
3753 /// `parse` can parse any type that implements the [`FromStr`] trait.
3755 /// [`FromStr`]: str/trait.FromStr.html
3759 /// Will return [`Err`] if it's not possible to parse this string slice into
3760 /// the desired type.
3762 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
3769 /// let four: u32 = "4".parse().unwrap();
3771 /// assert_eq!(4, four);
3774 /// Using the 'turbofish' instead of annotating `four`:
3777 /// let four = "4".parse::<u32>();
3779 /// assert_eq!(Ok(4), four);
3782 /// Failing to parse:
3785 /// let nope = "j".parse::<u32>();
3787 /// assert!(nope.is_err());
3790 #[stable(feature = "rust1", since = "1.0.0")]
3791 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
3792 FromStr::from_str(self)
3795 /// Checks if all characters in this string are within the ASCII range.
3800 /// let ascii = "hello!\n";
3801 /// let non_ascii = "Grüße, Jürgen ❤";
3803 /// assert!(ascii.is_ascii());
3804 /// assert!(!non_ascii.is_ascii());
3806 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3808 pub fn is_ascii(&self) -> bool {
3809 // We can treat each byte as character here: all multibyte characters
3810 // start with a byte that is not in the ascii range, so we will stop
3812 self.bytes().all(|b| b.is_ascii())
3815 /// Checks that two strings are an ASCII case-insensitive match.
3817 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
3818 /// but without allocating and copying temporaries.
3823 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
3824 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
3825 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
3827 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3829 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
3830 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
3833 /// Converts this string to its ASCII upper case equivalent in-place.
3835 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3836 /// but non-ASCII letters are unchanged.
3838 /// To return a new uppercased value without modifying the existing one, use
3839 /// [`to_ascii_uppercase`].
3841 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3842 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3843 pub fn make_ascii_uppercase(&mut self) {
3844 let me = unsafe { self.as_bytes_mut() };
3845 me.make_ascii_uppercase()
3848 /// Converts this string to its ASCII lower case equivalent in-place.
3850 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3851 /// but non-ASCII letters are unchanged.
3853 /// To return a new lowercased value without modifying the existing one, use
3854 /// [`to_ascii_lowercase`].
3856 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3857 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3858 pub fn make_ascii_lowercase(&mut self) {
3859 let me = unsafe { self.as_bytes_mut() };
3860 me.make_ascii_lowercase()
3864 #[stable(feature = "rust1", since = "1.0.0")]
3865 impl AsRef<[u8]> for str {
3867 fn as_ref(&self) -> &[u8] {
3872 #[stable(feature = "rust1", since = "1.0.0")]
3873 impl<'a> Default for &'a str {
3874 /// Creates an empty str
3875 fn default() -> &'a str { "" }
3878 #[stable(feature = "default_mut_str", since = "1.28.0")]
3879 impl<'a> Default for &'a mut str {
3880 /// Creates an empty mutable str
3881 fn default() -> &'a mut str { unsafe { from_utf8_unchecked_mut(&mut []) } }
3884 /// An iterator over the non-whitespace substrings of a string,
3885 /// separated by any amount of whitespace.
3887 /// This struct is created by the [`split_whitespace`] method on [`str`].
3888 /// See its documentation for more.
3890 /// [`split_whitespace`]: ../../std/primitive.str.html#method.split_whitespace
3891 /// [`str`]: ../../std/primitive.str.html
3892 #[stable(feature = "split_whitespace", since = "1.1.0")]
3893 #[derive(Clone, Debug)]
3894 pub struct SplitWhitespace<'a> {
3895 inner: Filter<Split<'a, IsWhitespace>, IsNotEmpty>,
3899 struct IsWhitespace;
3901 impl FnOnce<(char, )> for IsWhitespace {
3905 extern "rust-call" fn call_once(mut self, arg: (char, )) -> bool {
3910 impl FnMut<(char, )> for IsWhitespace {
3912 extern "rust-call" fn call_mut(&mut self, arg: (char, )) -> bool {
3913 arg.0.is_whitespace()
3920 impl<'a, 'b> FnOnce<(&'a &'b str, )> for IsNotEmpty {
3924 extern "rust-call" fn call_once(mut self, arg: (&&str, )) -> bool {
3929 impl<'a, 'b> FnMut<(&'a &'b str, )> for IsNotEmpty {
3931 extern "rust-call" fn call_mut(&mut self, arg: (&&str, )) -> bool {
3937 #[stable(feature = "split_whitespace", since = "1.1.0")]
3938 impl<'a> Iterator for SplitWhitespace<'a> {
3939 type Item = &'a str;
3941 fn next(&mut self) -> Option<&'a str> {
3946 #[stable(feature = "split_whitespace", since = "1.1.0")]
3947 impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
3948 fn next_back(&mut self) -> Option<&'a str> {
3949 self.inner.next_back()
3953 #[stable(feature = "fused", since = "1.26.0")]
3954 impl<'a> FusedIterator for SplitWhitespace<'a> {}
3956 /// An iterator of [`u16`] over the string encoded as UTF-16.
3958 /// [`u16`]: ../../std/primitive.u16.html
3960 /// This struct is created by the [`encode_utf16`] method on [`str`].
3961 /// See its documentation for more.
3963 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
3964 /// [`str`]: ../../std/primitive.str.html
3966 #[stable(feature = "encode_utf16", since = "1.8.0")]
3967 pub struct EncodeUtf16<'a> {
3972 #[stable(feature = "collection_debug", since = "1.17.0")]
3973 impl<'a> fmt::Debug for EncodeUtf16<'a> {
3974 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3975 f.pad("EncodeUtf16 { .. }")
3979 #[stable(feature = "encode_utf16", since = "1.8.0")]
3980 impl<'a> Iterator for EncodeUtf16<'a> {
3984 fn next(&mut self) -> Option<u16> {
3985 if self.extra != 0 {
3986 let tmp = self.extra;
3991 let mut buf = [0; 2];
3992 self.chars.next().map(|ch| {
3993 let n = ch.encode_utf16(&mut buf).len();
3995 self.extra = buf[1];
4002 fn size_hint(&self) -> (usize, Option<usize>) {
4003 let (low, high) = self.chars.size_hint();
4004 // every char gets either one u16 or two u16,
4005 // so this iterator is between 1 or 2 times as
4006 // long as the underlying iterator.
4007 (low, high.and_then(|n| n.checked_mul(2)))
4011 #[stable(feature = "fused", since = "1.26.0")]
4012 impl<'a> FusedIterator for EncodeUtf16<'a> {}