1 //! String manipulation.
3 //! For more details, see the `std::str` module.
5 #![stable(feature = "rust1", since = "1.0.0")]
7 use self::pattern::Pattern;
8 use self::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
11 use fmt::{self, Write};
12 use iter::{Map, Cloned, FusedIterator, TrustedLen, TrustedRandomAccess, Filter};
13 use iter::{Flatten, FlatMap, Chain};
14 use slice::{self, SliceIndex, Split as SliceSplit};
21 #[unstable(feature = "str_internals", issue = "0")]
22 #[allow(missing_docs)]
25 /// Parse a value from a string
27 /// `FromStr`'s [`from_str`] method is often used implicitly, through
28 /// [`str`]'s [`parse`] method. See [`parse`]'s documentation for examples.
30 /// [`from_str`]: #tymethod.from_str
31 /// [`str`]: ../../std/primitive.str.html
32 /// [`parse`]: ../../std/primitive.str.html#method.parse
34 /// `FromStr` does not have a lifetime parameter, and so you can only parse types
35 /// that do not contain a lifetime parameter themselves. In other words, you can
36 /// parse an `i32` with `FromStr`, but not a `&i32`. You can parse a struct that
37 /// contains an `i32`, but not one that contains an `&i32`.
41 /// Basic implementation of `FromStr` on an example `Point` type:
44 /// use std::str::FromStr;
45 /// use std::num::ParseIntError;
47 /// #[derive(Debug, PartialEq)]
53 /// impl FromStr for Point {
54 /// type Err = ParseIntError;
56 /// fn from_str(s: &str) -> Result<Self, Self::Err> {
57 /// let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
61 /// let x_fromstr = coords[0].parse::<i32>()?;
62 /// let y_fromstr = coords[1].parse::<i32>()?;
64 /// Ok(Point { x: x_fromstr, y: y_fromstr })
68 /// let p = Point::from_str("(1,2)");
69 /// assert_eq!(p.unwrap(), Point{ x: 1, y: 2} )
71 #[stable(feature = "rust1", since = "1.0.0")]
72 pub trait FromStr: Sized {
73 /// The associated error which can be returned from parsing.
74 #[stable(feature = "rust1", since = "1.0.0")]
77 /// Parses a string `s` to return a value of this type.
79 /// If parsing succeeds, return the value inside [`Ok`], otherwise
80 /// when the string is ill-formatted return an error specific to the
81 /// inside [`Err`]. The error type is specific to implementation of the trait.
83 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
84 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
88 /// Basic usage with [`i32`][ithirtytwo], a type that implements `FromStr`:
90 /// [ithirtytwo]: ../../std/primitive.i32.html
93 /// use std::str::FromStr;
96 /// let x = i32::from_str(s).unwrap();
100 #[stable(feature = "rust1", since = "1.0.0")]
101 fn from_str(s: &str) -> Result<Self, Self::Err>;
104 #[stable(feature = "rust1", since = "1.0.0")]
105 impl FromStr for bool {
106 type Err = ParseBoolError;
108 /// Parse a `bool` from a string.
110 /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
111 /// actually be parseable.
116 /// use std::str::FromStr;
118 /// assert_eq!(FromStr::from_str("true"), Ok(true));
119 /// assert_eq!(FromStr::from_str("false"), Ok(false));
120 /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
123 /// Note, in many cases, the `.parse()` method on `str` is more proper.
126 /// assert_eq!("true".parse(), Ok(true));
127 /// assert_eq!("false".parse(), Ok(false));
128 /// assert!("not even a boolean".parse::<bool>().is_err());
131 fn from_str(s: &str) -> Result<bool, ParseBoolError> {
134 "false" => Ok(false),
135 _ => Err(ParseBoolError { _priv: () }),
140 /// An error returned when parsing a `bool` using [`from_str`] fails
142 /// [`from_str`]: ../../std/primitive.bool.html#method.from_str
143 #[derive(Debug, Clone, PartialEq, Eq)]
144 #[stable(feature = "rust1", since = "1.0.0")]
145 pub struct ParseBoolError { _priv: () }
147 #[stable(feature = "rust1", since = "1.0.0")]
148 impl fmt::Display for ParseBoolError {
149 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
150 "provided string was not `true` or `false`".fmt(f)
155 Section: Creating a string
158 /// Errors which can occur when attempting to interpret a sequence of [`u8`]
161 /// [`u8`]: ../../std/primitive.u8.html
163 /// As such, the `from_utf8` family of functions and methods for both [`String`]s
164 /// and [`&str`]s make use of this error, for example.
166 /// [`String`]: ../../std/string/struct.String.html#method.from_utf8
167 /// [`&str`]: ../../std/str/fn.from_utf8.html
171 /// This error type’s methods can be used to create functionality
172 /// similar to `String::from_utf8_lossy` without allocating heap memory:
175 /// fn from_utf8_lossy<F>(mut input: &[u8], mut push: F) where F: FnMut(&str) {
177 /// match ::std::str::from_utf8(input) {
183 /// let (valid, after_valid) = input.split_at(error.valid_up_to());
185 /// push(::std::str::from_utf8_unchecked(valid))
187 /// push("\u{FFFD}");
189 /// if let Some(invalid_sequence_length) = error.error_len() {
190 /// input = &after_valid[invalid_sequence_length..]
199 #[derive(Copy, Eq, PartialEq, Clone, Debug)]
200 #[stable(feature = "rust1", since = "1.0.0")]
201 pub struct Utf8Error {
203 error_len: Option<u8>,
207 /// Returns the index in the given string up to which valid UTF-8 was
210 /// It is the maximum index such that `from_utf8(&input[..index])`
211 /// would return `Ok(_)`.
220 /// // some invalid bytes, in a vector
221 /// let sparkle_heart = vec![0, 159, 146, 150];
223 /// // std::str::from_utf8 returns a Utf8Error
224 /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
226 /// // the second byte is invalid here
227 /// assert_eq!(1, error.valid_up_to());
229 #[stable(feature = "utf8_error", since = "1.5.0")]
230 pub fn valid_up_to(&self) -> usize { self.valid_up_to }
232 /// Provides more information about the failure:
234 /// * `None`: the end of the input was reached unexpectedly.
235 /// `self.valid_up_to()` is 1 to 3 bytes from the end of the input.
236 /// If a byte stream (such as a file or a network socket) is being decoded incrementally,
237 /// this could be a valid `char` whose UTF-8 byte sequence is spanning multiple chunks.
239 /// * `Some(len)`: an unexpected byte was encountered.
240 /// The length provided is that of the invalid byte sequence
241 /// that starts at the index given by `valid_up_to()`.
242 /// Decoding should resume after that sequence
243 /// (after inserting a [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD]) in case of
246 /// [U+FFFD]: ../../std/char/constant.REPLACEMENT_CHARACTER.html
247 #[stable(feature = "utf8_error_error_len", since = "1.20.0")]
248 pub fn error_len(&self) -> Option<usize> {
249 self.error_len.map(|len| len as usize)
253 /// Converts a slice of bytes to a string slice.
255 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
256 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
257 /// the two. Not all byte slices are valid string slices, however: [`&str`] requires
258 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
259 /// UTF-8, and then does the conversion.
261 /// [`&str`]: ../../std/primitive.str.html
262 /// [`u8`]: ../../std/primitive.u8.html
263 /// [byteslice]: ../../std/primitive.slice.html
265 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
266 /// incur the overhead of the validity check, there is an unsafe version of
267 /// this function, [`from_utf8_unchecked`][fromutf8u], which has the same
268 /// behavior but skips the check.
270 /// [fromutf8u]: fn.from_utf8_unchecked.html
272 /// If you need a `String` instead of a `&str`, consider
273 /// [`String::from_utf8`][string].
275 /// [string]: ../../std/string/struct.String.html#method.from_utf8
277 /// Because you can stack-allocate a `[u8; N]`, and you can take a
278 /// [`&[u8]`][byteslice] of it, this function is one way to have a
279 /// stack-allocated string. There is an example of this in the
280 /// examples section below.
282 /// [byteslice]: ../../std/primitive.slice.html
286 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
287 /// provided slice is not UTF-8.
296 /// // some bytes, in a vector
297 /// let sparkle_heart = vec![240, 159, 146, 150];
299 /// // We know these bytes are valid, so just use `unwrap()`.
300 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
302 /// assert_eq!("💖", sparkle_heart);
310 /// // some invalid bytes, in a vector
311 /// let sparkle_heart = vec![0, 159, 146, 150];
313 /// assert!(str::from_utf8(&sparkle_heart).is_err());
316 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
317 /// errors that can be returned.
319 /// [error]: struct.Utf8Error.html
321 /// A "stack allocated string":
326 /// // some bytes, in a stack-allocated array
327 /// let sparkle_heart = [240, 159, 146, 150];
329 /// // We know these bytes are valid, so just use `unwrap()`.
330 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
332 /// assert_eq!("💖", sparkle_heart);
334 #[stable(feature = "rust1", since = "1.0.0")]
335 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
336 run_utf8_validation(v)?;
337 Ok(unsafe { from_utf8_unchecked(v) })
340 /// Converts a mutable slice of bytes to a mutable string slice.
349 /// // "Hello, Rust!" as a mutable vector
350 /// let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
352 /// // As we know these bytes are valid, we can use `unwrap()`
353 /// let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
355 /// assert_eq!("Hello, Rust!", outstr);
363 /// // Some invalid bytes in a mutable vector
364 /// let mut invalid = vec![128, 223];
366 /// assert!(str::from_utf8_mut(&mut invalid).is_err());
368 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
369 /// errors that can be returned.
371 /// [error]: struct.Utf8Error.html
372 #[stable(feature = "str_mut_extras", since = "1.20.0")]
373 pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
374 run_utf8_validation(v)?;
375 Ok(unsafe { from_utf8_unchecked_mut(v) })
378 /// Converts a slice of bytes to a string slice without checking
379 /// that the string contains valid UTF-8.
381 /// See the safe version, [`from_utf8`][fromutf8], for more information.
383 /// [fromutf8]: fn.from_utf8.html
387 /// This function is unsafe because it does not check that the bytes passed to
388 /// it are valid UTF-8. If this constraint is violated, undefined behavior
389 /// results, as the rest of Rust assumes that [`&str`]s are valid UTF-8.
391 /// [`&str`]: ../../std/primitive.str.html
400 /// // some bytes, in a vector
401 /// let sparkle_heart = vec![240, 159, 146, 150];
403 /// let sparkle_heart = unsafe {
404 /// str::from_utf8_unchecked(&sparkle_heart)
407 /// assert_eq!("💖", sparkle_heart);
410 #[stable(feature = "rust1", since = "1.0.0")]
411 pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
412 &*(v as *const [u8] as *const str)
415 /// Converts a slice of bytes to a string slice without checking
416 /// that the string contains valid UTF-8; mutable version.
418 /// See the immutable version, [`from_utf8_unchecked()`][fromutf8], for more information.
420 /// [fromutf8]: fn.from_utf8_unchecked.html
429 /// let mut heart = vec![240, 159, 146, 150];
430 /// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
432 /// assert_eq!("💖", heart);
435 #[stable(feature = "str_mut_extras", since = "1.20.0")]
436 pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
437 &mut *(v as *mut [u8] as *mut str)
440 #[stable(feature = "rust1", since = "1.0.0")]
441 impl fmt::Display for Utf8Error {
442 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
443 if let Some(error_len) = self.error_len {
444 write!(f, "invalid utf-8 sequence of {} bytes from index {}",
445 error_len, self.valid_up_to)
447 write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to)
456 /// An iterator over the [`char`]s of a string slice.
458 /// [`char`]: ../../std/primitive.char.html
460 /// This struct is created by the [`chars`] method on [`str`].
461 /// See its documentation for more.
463 /// [`chars`]: ../../std/primitive.str.html#method.chars
464 /// [`str`]: ../../std/primitive.str.html
465 #[derive(Clone, Debug)]
466 #[stable(feature = "rust1", since = "1.0.0")]
467 pub struct Chars<'a> {
468 iter: slice::Iter<'a, u8>
471 /// Returns the initial codepoint accumulator for the first byte.
472 /// The first byte is special, only want bottom 5 bits for width 2, 4 bits
473 /// for width 3, and 3 bits for width 4.
475 fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
477 /// Returns the value of `ch` updated with continuation byte `byte`.
479 fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
481 /// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the
484 fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
487 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
494 /// Reads the next code point out of a byte iterator (assuming a
495 /// UTF-8-like encoding).
496 #[unstable(feature = "str_internals", issue = "0")]
498 pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
500 let x = *bytes.next()?;
502 return Some(x as u32)
505 // Multibyte case follows
506 // Decode from a byte combination out of: [[[x y] z] w]
507 // NOTE: Performance is sensitive to the exact formulation here
508 let init = utf8_first_byte(x, 2);
509 let y = unwrap_or_0(bytes.next());
510 let mut ch = utf8_acc_cont_byte(init, y);
513 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
514 let z = unwrap_or_0(bytes.next());
515 let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
516 ch = init << 12 | y_z;
519 // use only the lower 3 bits of `init`
520 let w = unwrap_or_0(bytes.next());
521 ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
528 /// Reads the last code point out of a byte iterator (assuming a
529 /// UTF-8-like encoding).
531 fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
532 where I: DoubleEndedIterator<Item = &'a u8>,
535 let w = match *bytes.next_back()? {
536 next_byte if next_byte < 128 => return Some(next_byte as u32),
537 back_byte => back_byte,
540 // Multibyte case follows
541 // Decode from a byte combination out of: [x [y [z w]]]
543 let z = unwrap_or_0(bytes.next_back());
544 ch = utf8_first_byte(z, 2);
545 if utf8_is_cont_byte(z) {
546 let y = unwrap_or_0(bytes.next_back());
547 ch = utf8_first_byte(y, 3);
548 if utf8_is_cont_byte(y) {
549 let x = unwrap_or_0(bytes.next_back());
550 ch = utf8_first_byte(x, 4);
551 ch = utf8_acc_cont_byte(ch, y);
553 ch = utf8_acc_cont_byte(ch, z);
555 ch = utf8_acc_cont_byte(ch, w);
560 #[stable(feature = "rust1", since = "1.0.0")]
561 impl<'a> Iterator for Chars<'a> {
565 fn next(&mut self) -> Option<char> {
566 next_code_point(&mut self.iter).map(|ch| {
567 // str invariant says `ch` is a valid Unicode Scalar Value
569 char::from_u32_unchecked(ch)
575 fn count(self) -> usize {
576 // length in `char` is equal to the number of non-continuation bytes
577 let bytes_len = self.iter.len();
578 let mut cont_bytes = 0;
579 for &byte in self.iter {
580 cont_bytes += utf8_is_cont_byte(byte) as usize;
582 bytes_len - cont_bytes
586 fn size_hint(&self) -> (usize, Option<usize>) {
587 let len = self.iter.len();
588 // `(len + 3)` can't overflow, because we know that the `slice::Iter`
589 // belongs to a slice in memory which has a maximum length of
590 // `isize::MAX` (that's well below `usize::MAX`).
591 ((len + 3) / 4, Some(len))
595 fn last(mut self) -> Option<char> {
596 // No need to go through the entire string.
601 #[stable(feature = "rust1", since = "1.0.0")]
602 impl<'a> DoubleEndedIterator for Chars<'a> {
604 fn next_back(&mut self) -> Option<char> {
605 next_code_point_reverse(&mut self.iter).map(|ch| {
606 // str invariant says `ch` is a valid Unicode Scalar Value
608 char::from_u32_unchecked(ch)
614 #[stable(feature = "fused", since = "1.26.0")]
615 impl FusedIterator for Chars<'_> {}
618 /// Views the underlying data as a subslice of the original data.
620 /// This has the same lifetime as the original slice, and so the
621 /// iterator can continue to be used while this exists.
626 /// let mut chars = "abc".chars();
628 /// assert_eq!(chars.as_str(), "abc");
630 /// assert_eq!(chars.as_str(), "bc");
633 /// assert_eq!(chars.as_str(), "");
635 #[stable(feature = "iter_to_slice", since = "1.4.0")]
637 pub fn as_str(&self) -> &'a str {
638 unsafe { from_utf8_unchecked(self.iter.as_slice()) }
642 /// An iterator over the [`char`]s of a string slice, and their positions.
644 /// [`char`]: ../../std/primitive.char.html
646 /// This struct is created by the [`char_indices`] method on [`str`].
647 /// See its documentation for more.
649 /// [`char_indices`]: ../../std/primitive.str.html#method.char_indices
650 /// [`str`]: ../../std/primitive.str.html
651 #[derive(Clone, Debug)]
652 #[stable(feature = "rust1", since = "1.0.0")]
653 pub struct CharIndices<'a> {
658 #[stable(feature = "rust1", since = "1.0.0")]
659 impl<'a> Iterator for CharIndices<'a> {
660 type Item = (usize, char);
663 fn next(&mut self) -> Option<(usize, char)> {
664 let pre_len = self.iter.iter.len();
665 match self.iter.next() {
668 let index = self.front_offset;
669 let len = self.iter.iter.len();
670 self.front_offset += pre_len - len;
677 fn count(self) -> usize {
682 fn size_hint(&self) -> (usize, Option<usize>) {
683 self.iter.size_hint()
687 fn last(mut self) -> Option<(usize, char)> {
688 // No need to go through the entire string.
693 #[stable(feature = "rust1", since = "1.0.0")]
694 impl<'a> DoubleEndedIterator for CharIndices<'a> {
696 fn next_back(&mut self) -> Option<(usize, char)> {
697 self.iter.next_back().map(|ch| {
698 let index = self.front_offset + self.iter.iter.len();
704 #[stable(feature = "fused", since = "1.26.0")]
705 impl FusedIterator for CharIndices<'_> {}
707 impl<'a> CharIndices<'a> {
708 /// Views the underlying data as a subslice of the original data.
710 /// This has the same lifetime as the original slice, and so the
711 /// iterator can continue to be used while this exists.
712 #[stable(feature = "iter_to_slice", since = "1.4.0")]
714 pub fn as_str(&self) -> &'a str {
719 /// An iterator over the bytes of a string slice.
721 /// This struct is created by the [`bytes`] method on [`str`].
722 /// See its documentation for more.
724 /// [`bytes`]: ../../std/primitive.str.html#method.bytes
725 /// [`str`]: ../../std/primitive.str.html
726 #[stable(feature = "rust1", since = "1.0.0")]
727 #[derive(Clone, Debug)]
728 pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>);
730 #[stable(feature = "rust1", since = "1.0.0")]
731 impl Iterator for Bytes<'_> {
735 fn next(&mut self) -> Option<u8> {
740 fn size_hint(&self) -> (usize, Option<usize>) {
745 fn count(self) -> usize {
750 fn last(self) -> Option<Self::Item> {
755 fn nth(&mut self, n: usize) -> Option<Self::Item> {
760 fn all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
765 fn any<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
770 fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where
771 P: FnMut(&Self::Item) -> bool
773 self.0.find(predicate)
777 fn position<P>(&mut self, predicate: P) -> Option<usize> where
778 P: FnMut(Self::Item) -> bool
780 self.0.position(predicate)
784 fn rposition<P>(&mut self, predicate: P) -> Option<usize> where
785 P: FnMut(Self::Item) -> bool
787 self.0.rposition(predicate)
791 #[stable(feature = "rust1", since = "1.0.0")]
792 impl DoubleEndedIterator for Bytes<'_> {
794 fn next_back(&mut self) -> Option<u8> {
799 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> where
800 P: FnMut(&Self::Item) -> bool
802 self.0.rfind(predicate)
806 #[stable(feature = "rust1", since = "1.0.0")]
807 impl ExactSizeIterator for Bytes<'_> {
809 fn len(&self) -> usize {
814 fn is_empty(&self) -> bool {
819 #[stable(feature = "fused", since = "1.26.0")]
820 impl FusedIterator for Bytes<'_> {}
822 #[unstable(feature = "trusted_len", issue = "37572")]
823 unsafe impl TrustedLen for Bytes<'_> {}
826 unsafe impl TrustedRandomAccess for Bytes<'_> {
827 unsafe fn get_unchecked(&mut self, i: usize) -> u8 {
828 self.0.get_unchecked(i)
830 fn may_have_side_effect() -> bool { false }
833 /// This macro generates a Clone impl for string pattern API
834 /// wrapper types of the form X<'a, P>
835 macro_rules! derive_pattern_clone {
836 (clone $t:ident with |$s:ident| $e:expr) => {
837 impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
838 where P::Searcher: Clone
840 fn clone(&self) -> Self {
848 /// This macro generates two public iterator structs
849 /// wrapping a private internal one that makes use of the `Pattern` API.
851 /// For all patterns `P: Pattern<'a>` the following items will be
852 /// generated (generics omitted):
854 /// struct $forward_iterator($internal_iterator);
855 /// struct $reverse_iterator($internal_iterator);
857 /// impl Iterator for $forward_iterator
858 /// { /* internal ends up calling Searcher::next_match() */ }
860 /// impl DoubleEndedIterator for $forward_iterator
861 /// where P::Searcher: DoubleEndedSearcher
862 /// { /* internal ends up calling Searcher::next_match_back() */ }
864 /// impl Iterator for $reverse_iterator
865 /// where P::Searcher: ReverseSearcher
866 /// { /* internal ends up calling Searcher::next_match_back() */ }
868 /// impl DoubleEndedIterator for $reverse_iterator
869 /// where P::Searcher: DoubleEndedSearcher
870 /// { /* internal ends up calling Searcher::next_match() */ }
872 /// The internal one is defined outside the macro, and has almost the same
873 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
874 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
876 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
877 /// `Pattern` might not return the same elements, so actually implementing
878 /// `DoubleEndedIterator` for it would be incorrect.
879 /// (See the docs in `str::pattern` for more details)
881 /// However, the internal struct still represents a single ended iterator from
882 /// either end, and depending on pattern is also a valid double ended iterator,
883 /// so the two wrapper structs implement `Iterator`
884 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
885 /// to the complex impls seen above.
886 macro_rules! generate_pattern_iterators {
890 $(#[$forward_iterator_attribute:meta])*
891 struct $forward_iterator:ident;
895 $(#[$reverse_iterator_attribute:meta])*
896 struct $reverse_iterator:ident;
898 // Stability of all generated items
900 $(#[$common_stability_attribute:meta])*
902 // Internal almost-iterator that is being delegated to
904 $internal_iterator:ident yielding ($iterty:ty);
906 // Kind of delegation - either single ended or double ended
909 $(#[$forward_iterator_attribute])*
910 $(#[$common_stability_attribute])*
911 pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
913 $(#[$common_stability_attribute])*
914 impl<'a, P: Pattern<'a>> fmt::Debug for $forward_iterator<'a, P>
915 where P::Searcher: fmt::Debug
917 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
918 f.debug_tuple(stringify!($forward_iterator))
924 $(#[$common_stability_attribute])*
925 impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
929 fn next(&mut self) -> Option<$iterty> {
934 $(#[$common_stability_attribute])*
935 impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
936 where P::Searcher: Clone
938 fn clone(&self) -> Self {
939 $forward_iterator(self.0.clone())
943 $(#[$reverse_iterator_attribute])*
944 $(#[$common_stability_attribute])*
945 pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
947 $(#[$common_stability_attribute])*
948 impl<'a, P: Pattern<'a>> fmt::Debug for $reverse_iterator<'a, P>
949 where P::Searcher: fmt::Debug
951 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
952 f.debug_tuple(stringify!($reverse_iterator))
958 $(#[$common_stability_attribute])*
959 impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
960 where P::Searcher: ReverseSearcher<'a>
965 fn next(&mut self) -> Option<$iterty> {
970 $(#[$common_stability_attribute])*
971 impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
972 where P::Searcher: Clone
974 fn clone(&self) -> Self {
975 $reverse_iterator(self.0.clone())
979 #[stable(feature = "fused", since = "1.26.0")]
980 impl<'a, P: Pattern<'a>> FusedIterator for $forward_iterator<'a, P> {}
982 #[stable(feature = "fused", since = "1.26.0")]
983 impl<'a, P: Pattern<'a>> FusedIterator for $reverse_iterator<'a, P>
984 where P::Searcher: ReverseSearcher<'a> {}
986 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
988 $reverse_iterator, $iterty);
991 double ended; with $(#[$common_stability_attribute:meta])*,
992 $forward_iterator:ident,
993 $reverse_iterator:ident, $iterty:ty
995 $(#[$common_stability_attribute])*
996 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
997 where P::Searcher: DoubleEndedSearcher<'a>
1000 fn next_back(&mut self) -> Option<$iterty> {
1005 $(#[$common_stability_attribute])*
1006 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
1007 where P::Searcher: DoubleEndedSearcher<'a>
1010 fn next_back(&mut self) -> Option<$iterty> {
1016 single ended; with $(#[$common_stability_attribute:meta])*,
1017 $forward_iterator:ident,
1018 $reverse_iterator:ident, $iterty:ty
1022 derive_pattern_clone!{
1024 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
1027 struct SplitInternal<'a, P: Pattern<'a>> {
1030 matcher: P::Searcher,
1031 allow_trailing_empty: bool,
1035 impl<'a, P: Pattern<'a>> fmt::Debug for SplitInternal<'a, P> where P::Searcher: fmt::Debug {
1036 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1037 f.debug_struct("SplitInternal")
1038 .field("start", &self.start)
1039 .field("end", &self.end)
1040 .field("matcher", &self.matcher)
1041 .field("allow_trailing_empty", &self.allow_trailing_empty)
1042 .field("finished", &self.finished)
1047 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
1049 fn get_end(&mut self) -> Option<&'a str> {
1050 if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
1051 self.finished = true;
1053 let string = self.matcher.haystack().get_unchecked(self.start..self.end);
1062 fn next(&mut self) -> Option<&'a str> {
1063 if self.finished { return None }
1065 let haystack = self.matcher.haystack();
1066 match self.matcher.next_match() {
1067 Some((a, b)) => unsafe {
1068 let elt = haystack.get_unchecked(self.start..a);
1072 None => self.get_end(),
1077 fn next_back(&mut self) -> Option<&'a str>
1078 where P::Searcher: ReverseSearcher<'a>
1080 if self.finished { return None }
1082 if !self.allow_trailing_empty {
1083 self.allow_trailing_empty = true;
1084 match self.next_back() {
1085 Some(elt) if !elt.is_empty() => return Some(elt),
1086 _ => if self.finished { return None }
1090 let haystack = self.matcher.haystack();
1091 match self.matcher.next_match_back() {
1092 Some((a, b)) => unsafe {
1093 let elt = haystack.get_unchecked(b..self.end);
1098 self.finished = true;
1099 Some(haystack.get_unchecked(self.start..self.end))
1105 generate_pattern_iterators! {
1107 /// Created with the method [`split`].
1109 /// [`split`]: ../../std/primitive.str.html#method.split
1112 /// Created with the method [`rsplit`].
1114 /// [`rsplit`]: ../../std/primitive.str.html#method.rsplit
1117 #[stable(feature = "rust1", since = "1.0.0")]
1119 SplitInternal yielding (&'a str);
1120 delegate double ended;
1123 generate_pattern_iterators! {
1125 /// Created with the method [`split_terminator`].
1127 /// [`split_terminator`]: ../../std/primitive.str.html#method.split_terminator
1128 struct SplitTerminator;
1130 /// Created with the method [`rsplit_terminator`].
1132 /// [`rsplit_terminator`]: ../../std/primitive.str.html#method.rsplit_terminator
1133 struct RSplitTerminator;
1135 #[stable(feature = "rust1", since = "1.0.0")]
1137 SplitInternal yielding (&'a str);
1138 delegate double ended;
1141 derive_pattern_clone!{
1142 clone SplitNInternal
1143 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
1146 struct SplitNInternal<'a, P: Pattern<'a>> {
1147 iter: SplitInternal<'a, P>,
1148 /// The number of splits remaining
1152 impl<'a, P: Pattern<'a>> fmt::Debug for SplitNInternal<'a, P> where P::Searcher: fmt::Debug {
1153 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1154 f.debug_struct("SplitNInternal")
1155 .field("iter", &self.iter)
1156 .field("count", &self.count)
1161 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
1163 fn next(&mut self) -> Option<&'a str> {
1166 1 => { self.count = 0; self.iter.get_end() }
1167 _ => { self.count -= 1; self.iter.next() }
1172 fn next_back(&mut self) -> Option<&'a str>
1173 where P::Searcher: ReverseSearcher<'a>
1177 1 => { self.count = 0; self.iter.get_end() }
1178 _ => { self.count -= 1; self.iter.next_back() }
1183 generate_pattern_iterators! {
1185 /// Created with the method [`splitn`].
1187 /// [`splitn`]: ../../std/primitive.str.html#method.splitn
1190 /// Created with the method [`rsplitn`].
1192 /// [`rsplitn`]: ../../std/primitive.str.html#method.rsplitn
1195 #[stable(feature = "rust1", since = "1.0.0")]
1197 SplitNInternal yielding (&'a str);
1198 delegate single ended;
1201 derive_pattern_clone!{
1202 clone MatchIndicesInternal
1203 with |s| MatchIndicesInternal(s.0.clone())
1206 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
1208 impl<'a, P: Pattern<'a>> fmt::Debug for MatchIndicesInternal<'a, P> where P::Searcher: fmt::Debug {
1209 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1210 f.debug_tuple("MatchIndicesInternal")
1216 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
1218 fn next(&mut self) -> Option<(usize, &'a str)> {
1219 self.0.next_match().map(|(start, end)| unsafe {
1220 (start, self.0.haystack().get_unchecked(start..end))
1225 fn next_back(&mut self) -> Option<(usize, &'a str)>
1226 where P::Searcher: ReverseSearcher<'a>
1228 self.0.next_match_back().map(|(start, end)| unsafe {
1229 (start, self.0.haystack().get_unchecked(start..end))
1234 generate_pattern_iterators! {
1236 /// Created with the method [`match_indices`].
1238 /// [`match_indices`]: ../../std/primitive.str.html#method.match_indices
1239 struct MatchIndices;
1241 /// Created with the method [`rmatch_indices`].
1243 /// [`rmatch_indices`]: ../../std/primitive.str.html#method.rmatch_indices
1244 struct RMatchIndices;
1246 #[stable(feature = "str_match_indices", since = "1.5.0")]
1248 MatchIndicesInternal yielding ((usize, &'a str));
1249 delegate double ended;
1252 derive_pattern_clone!{
1253 clone MatchesInternal
1254 with |s| MatchesInternal(s.0.clone())
1257 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
1259 impl<'a, P: Pattern<'a>> fmt::Debug for MatchesInternal<'a, P> where P::Searcher: fmt::Debug {
1260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1261 f.debug_tuple("MatchesInternal")
1267 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
1269 fn next(&mut self) -> Option<&'a str> {
1270 self.0.next_match().map(|(a, b)| unsafe {
1271 // Indices are known to be on utf8 boundaries
1272 self.0.haystack().get_unchecked(a..b)
1277 fn next_back(&mut self) -> Option<&'a str>
1278 where P::Searcher: ReverseSearcher<'a>
1280 self.0.next_match_back().map(|(a, b)| unsafe {
1281 // Indices are known to be on utf8 boundaries
1282 self.0.haystack().get_unchecked(a..b)
1287 generate_pattern_iterators! {
1289 /// Created with the method [`matches`].
1291 /// [`matches`]: ../../std/primitive.str.html#method.matches
1294 /// Created with the method [`rmatches`].
1296 /// [`rmatches`]: ../../std/primitive.str.html#method.rmatches
1299 #[stable(feature = "str_matches", since = "1.2.0")]
1301 MatchesInternal yielding (&'a str);
1302 delegate double ended;
1305 /// An iterator over the lines of a string, as string slices.
1307 /// This struct is created with the [`lines`] method on [`str`].
1308 /// See its documentation for more.
1310 /// [`lines`]: ../../std/primitive.str.html#method.lines
1311 /// [`str`]: ../../std/primitive.str.html
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 #[derive(Clone, Debug)]
1314 pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>);
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 impl<'a> Iterator for Lines<'a> {
1318 type Item = &'a str;
1321 fn next(&mut self) -> Option<&'a str> {
1326 fn size_hint(&self) -> (usize, Option<usize>) {
1331 #[stable(feature = "rust1", since = "1.0.0")]
1332 impl<'a> DoubleEndedIterator for Lines<'a> {
1334 fn next_back(&mut self) -> Option<&'a str> {
1339 #[stable(feature = "fused", since = "1.26.0")]
1340 impl FusedIterator for Lines<'_> {}
1342 /// Created with the method [`lines_any`].
1344 /// [`lines_any`]: ../../std/primitive.str.html#method.lines_any
1345 #[stable(feature = "rust1", since = "1.0.0")]
1346 #[rustc_deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")]
1347 #[derive(Clone, Debug)]
1348 #[allow(deprecated)]
1349 pub struct LinesAny<'a>(Lines<'a>);
1352 /// A nameable, cloneable fn type
1354 struct LinesAnyMap impl<'a> Fn = |line: &'a str| -> &'a str {
1356 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
1361 #[stable(feature = "rust1", since = "1.0.0")]
1362 #[allow(deprecated)]
1363 impl<'a> Iterator for LinesAny<'a> {
1364 type Item = &'a str;
1367 fn next(&mut self) -> Option<&'a str> {
1372 fn size_hint(&self) -> (usize, Option<usize>) {
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 #[allow(deprecated)]
1379 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1381 fn next_back(&mut self) -> Option<&'a str> {
1386 #[stable(feature = "fused", since = "1.26.0")]
1387 #[allow(deprecated)]
1388 impl FusedIterator for LinesAny<'_> {}
1391 Section: UTF-8 validation
1394 // use truncation to fit u64 into usize
1395 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
1397 /// Returns `true` if any byte in the word `x` is nonascii (>= 128).
1399 fn contains_nonascii(x: usize) -> bool {
1400 (x & NONASCII_MASK) != 0
1403 /// Walks through `v` checking that it's a valid UTF-8 sequence,
1404 /// returning `Ok(())` in that case, or, if it is invalid, `Err(err)`.
1406 fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
1410 let usize_bytes = mem::size_of::<usize>();
1411 let ascii_block_size = 2 * usize_bytes;
1412 let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
1415 let old_offset = index;
1417 ($error_len: expr) => {
1418 return Err(Utf8Error {
1419 valid_up_to: old_offset,
1420 error_len: $error_len,
1425 macro_rules! next { () => {{
1427 // we needed data, but there was none: error!
1434 let first = v[index];
1436 let w = UTF8_CHAR_WIDTH[first as usize];
1437 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
1438 // first C2 80 last DF BF
1439 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
1440 // first E0 A0 80 last EF BF BF
1441 // excluding surrogates codepoints \u{d800} to \u{dfff}
1442 // ED A0 80 to ED BF BF
1443 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1444 // first F0 90 80 80 last F4 8F BF BF
1446 // Use the UTF-8 syntax from the RFC
1448 // https://tools.ietf.org/html/rfc3629
1450 // UTF8-2 = %xC2-DF UTF8-tail
1451 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1452 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1453 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1454 // %xF4 %x80-8F 2( UTF8-tail )
1456 2 => if next!() & !CONT_MASK != TAG_CONT_U8 {
1460 match (first, next!()) {
1461 (0xE0 , 0xA0 ..= 0xBF) |
1462 (0xE1 ..= 0xEC, 0x80 ..= 0xBF) |
1463 (0xED , 0x80 ..= 0x9F) |
1464 (0xEE ..= 0xEF, 0x80 ..= 0xBF) => {}
1467 if next!() & !CONT_MASK != TAG_CONT_U8 {
1472 match (first, next!()) {
1473 (0xF0 , 0x90 ..= 0xBF) |
1474 (0xF1 ..= 0xF3, 0x80 ..= 0xBF) |
1475 (0xF4 , 0x80 ..= 0x8F) => {}
1478 if next!() & !CONT_MASK != TAG_CONT_U8 {
1481 if next!() & !CONT_MASK != TAG_CONT_U8 {
1489 // Ascii case, try to skip forward quickly.
1490 // When the pointer is aligned, read 2 words of data per iteration
1491 // until we find a word containing a non-ascii byte.
1492 let ptr = v.as_ptr();
1493 let align = unsafe {
1494 // the offset is safe, because `index` is guaranteed inbounds
1495 ptr.add(index).align_offset(usize_bytes)
1498 while index < blocks_end {
1500 let block = ptr.add(index) as *const usize;
1501 // break if there is a nonascii byte
1502 let zu = contains_nonascii(*block);
1503 let zv = contains_nonascii(*block.offset(1));
1508 index += ascii_block_size;
1510 // step from the point where the wordwise loop stopped
1511 while index < len && v[index] < 128 {
1523 // https://tools.ietf.org/html/rfc3629
1524 static UTF8_CHAR_WIDTH: [u8; 256] = [
1525 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1526 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1527 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1528 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1529 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1530 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1531 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1532 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1533 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1534 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1535 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1536 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1537 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1538 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1539 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1540 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1543 /// Given a first byte, determines how many bytes are in this UTF-8 character.
1544 #[unstable(feature = "str_internals", issue = "0")]
1546 pub fn utf8_char_width(b: u8) -> usize {
1547 UTF8_CHAR_WIDTH[b as usize] as usize
1550 /// Mask of the value bits of a continuation byte.
1551 const CONT_MASK: u8 = 0b0011_1111;
1552 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte.
1553 const TAG_CONT_U8: u8 = 0b1000_0000;
1556 Section: Trait implementations
1562 use slice::{self, SliceIndex};
1564 /// Implements ordering of strings.
1566 /// Strings are ordered lexicographically by their byte values. This orders Unicode code
1567 /// points based on their positions in the code charts. This is not necessarily the same as
1568 /// "alphabetical" order, which varies by language and locale. Sorting strings according to
1569 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1571 #[stable(feature = "rust1", since = "1.0.0")]
1574 fn cmp(&self, other: &str) -> Ordering {
1575 self.as_bytes().cmp(other.as_bytes())
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 impl PartialEq for str {
1582 fn eq(&self, other: &str) -> bool {
1583 self.as_bytes() == other.as_bytes()
1586 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1589 #[stable(feature = "rust1", since = "1.0.0")]
1592 /// Implements comparison operations on strings.
1594 /// Strings are compared lexicographically by their byte values. This compares Unicode code
1595 /// points based on their positions in the code charts. This is not necessarily the same as
1596 /// "alphabetical" order, which varies by language and locale. Comparing strings according to
1597 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 impl PartialOrd for str {
1602 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1603 Some(self.cmp(other))
1607 #[stable(feature = "rust1", since = "1.0.0")]
1608 impl<I> ops::Index<I> for str
1612 type Output = I::Output;
1615 fn index(&self, index: I) -> &I::Output {
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 impl<I> ops::IndexMut<I> for str
1626 fn index_mut(&mut self, index: I) -> &mut I::Output {
1627 index.index_mut(self)
1633 fn str_index_overflow_fail() -> ! {
1634 panic!("attempted to index str up to maximum usize");
1637 /// Implements substring slicing with syntax `&self[..]` or `&mut self[..]`.
1639 /// Returns a slice of the whole string, i.e., returns `&self` or `&mut
1640 /// self`. Equivalent to `&self[0 .. len]` or `&mut self[0 .. len]`. Unlike
1641 /// other indexing operations, this can never panic.
1643 /// This operation is `O(1)`.
1645 /// Prior to 1.20.0, these indexing operations were still supported by
1646 /// direct implementation of `Index` and `IndexMut`.
1648 /// Equivalent to `&self[0 .. len]` or `&mut self[0 .. len]`.
1649 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1650 impl SliceIndex<str> for ops::RangeFull {
1653 fn get(self, slice: &str) -> Option<&Self::Output> {
1657 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1661 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1665 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1669 fn index(self, slice: &str) -> &Self::Output {
1673 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1678 /// Implements substring slicing with syntax `&self[begin .. end]` or `&mut
1679 /// self[begin .. end]`.
1681 /// Returns a slice of the given string from the byte range
1682 /// [`begin`, `end`).
1684 /// This operation is `O(1)`.
1686 /// Prior to 1.20.0, these indexing operations were still supported by
1687 /// direct implementation of `Index` and `IndexMut`.
1691 /// Panics if `begin` or `end` does not point to the starting byte offset of
1692 /// a character (as defined by `is_char_boundary`), if `begin > end`, or if
1698 /// let s = "Löwe 老虎 Léopard";
1699 /// assert_eq!(&s[0 .. 1], "L");
1701 /// assert_eq!(&s[1 .. 9], "öwe 老");
1703 /// // these will panic:
1704 /// // byte 2 lies within `ö`:
1707 /// // byte 8 lies within `老`
1710 /// // byte 100 is outside the string
1711 /// // &s[3 .. 100];
1713 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1714 impl SliceIndex<str> for ops::Range<usize> {
1717 fn get(self, slice: &str) -> Option<&Self::Output> {
1718 if self.start <= self.end &&
1719 slice.is_char_boundary(self.start) &&
1720 slice.is_char_boundary(self.end) {
1721 Some(unsafe { self.get_unchecked(slice) })
1727 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1728 if self.start <= self.end &&
1729 slice.is_char_boundary(self.start) &&
1730 slice.is_char_boundary(self.end) {
1731 Some(unsafe { self.get_unchecked_mut(slice) })
1737 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1738 let ptr = slice.as_ptr().add(self.start);
1739 let len = self.end - self.start;
1740 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1743 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1744 let ptr = slice.as_mut_ptr().add(self.start);
1745 let len = self.end - self.start;
1746 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, len))
1749 fn index(self, slice: &str) -> &Self::Output {
1750 let (start, end) = (self.start, self.end);
1751 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1754 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1755 // is_char_boundary checks that the index is in [0, .len()]
1756 // cannot reuse `get` as above, because of NLL trouble
1757 if self.start <= self.end &&
1758 slice.is_char_boundary(self.start) &&
1759 slice.is_char_boundary(self.end) {
1760 unsafe { self.get_unchecked_mut(slice) }
1762 super::slice_error_fail(slice, self.start, self.end)
1767 /// Implements substring slicing with syntax `&self[.. end]` or `&mut
1770 /// Returns a slice of the given string from the byte range [`0`, `end`).
1771 /// Equivalent to `&self[0 .. end]` or `&mut self[0 .. end]`.
1773 /// This operation is `O(1)`.
1775 /// Prior to 1.20.0, these indexing operations were still supported by
1776 /// direct implementation of `Index` and `IndexMut`.
1780 /// Panics if `end` does not point to the starting byte offset of a
1781 /// character (as defined by `is_char_boundary`), or if `end > len`.
1782 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1783 impl SliceIndex<str> for ops::RangeTo<usize> {
1786 fn get(self, slice: &str) -> Option<&Self::Output> {
1787 if slice.is_char_boundary(self.end) {
1788 Some(unsafe { self.get_unchecked(slice) })
1794 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1795 if slice.is_char_boundary(self.end) {
1796 Some(unsafe { self.get_unchecked_mut(slice) })
1802 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1803 let ptr = slice.as_ptr();
1804 super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end))
1807 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1808 let ptr = slice.as_mut_ptr();
1809 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, self.end))
1812 fn index(self, slice: &str) -> &Self::Output {
1814 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end))
1817 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1818 // is_char_boundary checks that the index is in [0, .len()]
1819 if slice.is_char_boundary(self.end) {
1820 unsafe { self.get_unchecked_mut(slice) }
1822 super::slice_error_fail(slice, 0, self.end)
1827 /// Implements substring slicing with syntax `&self[begin ..]` or `&mut
1828 /// self[begin ..]`.
1830 /// Returns a slice of the given string from the byte range [`begin`,
1831 /// `len`). Equivalent to `&self[begin .. len]` or `&mut self[begin ..
1834 /// This operation is `O(1)`.
1836 /// Prior to 1.20.0, these indexing operations were still supported by
1837 /// direct implementation of `Index` and `IndexMut`.
1841 /// Panics if `begin` does not point to the starting byte offset of
1842 /// a character (as defined by `is_char_boundary`), or if `begin >= len`.
1843 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1844 impl SliceIndex<str> for ops::RangeFrom<usize> {
1847 fn get(self, slice: &str) -> Option<&Self::Output> {
1848 if slice.is_char_boundary(self.start) {
1849 Some(unsafe { self.get_unchecked(slice) })
1855 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1856 if slice.is_char_boundary(self.start) {
1857 Some(unsafe { self.get_unchecked_mut(slice) })
1863 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1864 let ptr = slice.as_ptr().add(self.start);
1865 let len = slice.len() - self.start;
1866 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1869 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1870 let ptr = slice.as_mut_ptr().add(self.start);
1871 let len = slice.len() - self.start;
1872 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, len))
1875 fn index(self, slice: &str) -> &Self::Output {
1876 let (start, end) = (self.start, slice.len());
1877 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1880 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1881 // is_char_boundary checks that the index is in [0, .len()]
1882 if slice.is_char_boundary(self.start) {
1883 unsafe { self.get_unchecked_mut(slice) }
1885 super::slice_error_fail(slice, self.start, slice.len())
1890 /// Implements substring slicing with syntax `&self[begin ..= end]` or `&mut
1891 /// self[begin ..= end]`.
1893 /// Returns a slice of the given string from the byte range
1894 /// [`begin`, `end`]. Equivalent to `&self [begin .. end + 1]` or `&mut
1895 /// self[begin .. end + 1]`, except if `end` has the maximum value for
1898 /// This operation is `O(1)`.
1902 /// Panics if `begin` does not point to the starting byte offset of
1903 /// a character (as defined by `is_char_boundary`), if `end` does not point
1904 /// to the ending byte offset of a character (`end + 1` is either a starting
1905 /// byte offset or equal to `len`), if `begin > end`, or if `end >= len`.
1906 #[stable(feature = "inclusive_range", since = "1.26.0")]
1907 impl SliceIndex<str> for ops::RangeInclusive<usize> {
1910 fn get(self, slice: &str) -> Option<&Self::Output> {
1911 if *self.end() == usize::max_value() { None }
1912 else { (*self.start()..self.end()+1).get(slice) }
1915 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1916 if *self.end() == usize::max_value() { None }
1917 else { (*self.start()..self.end()+1).get_mut(slice) }
1920 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1921 (*self.start()..self.end()+1).get_unchecked(slice)
1924 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1925 (*self.start()..self.end()+1).get_unchecked_mut(slice)
1928 fn index(self, slice: &str) -> &Self::Output {
1929 if *self.end() == usize::max_value() { str_index_overflow_fail(); }
1930 (*self.start()..self.end()+1).index(slice)
1933 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1934 if *self.end() == usize::max_value() { str_index_overflow_fail(); }
1935 (*self.start()..self.end()+1).index_mut(slice)
1939 /// Implements substring slicing with syntax `&self[..= end]` or `&mut
1942 /// Returns a slice of the given string from the byte range [0, `end`].
1943 /// Equivalent to `&self [0 .. end + 1]`, except if `end` has the maximum
1944 /// value for `usize`.
1946 /// This operation is `O(1)`.
1950 /// Panics if `end` does not point to the ending byte offset of a character
1951 /// (`end + 1` is either a starting byte offset as defined by
1952 /// `is_char_boundary`, or equal to `len`), or if `end >= len`.
1953 #[stable(feature = "inclusive_range", since = "1.26.0")]
1954 impl SliceIndex<str> for ops::RangeToInclusive<usize> {
1957 fn get(self, slice: &str) -> Option<&Self::Output> {
1958 if self.end == usize::max_value() { None }
1959 else { (..self.end+1).get(slice) }
1962 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1963 if self.end == usize::max_value() { None }
1964 else { (..self.end+1).get_mut(slice) }
1967 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1968 (..self.end+1).get_unchecked(slice)
1971 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1972 (..self.end+1).get_unchecked_mut(slice)
1975 fn index(self, slice: &str) -> &Self::Output {
1976 if self.end == usize::max_value() { str_index_overflow_fail(); }
1977 (..self.end+1).index(slice)
1980 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1981 if self.end == usize::max_value() { str_index_overflow_fail(); }
1982 (..self.end+1).index_mut(slice)
1987 // truncate `&str` to length at most equal to `max`
1988 // return `true` if it were truncated, and the new str.
1989 fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
1993 while !s.is_char_boundary(max) {
2002 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
2003 const MAX_DISPLAY_LENGTH: usize = 256;
2004 let (truncated, s_trunc) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
2005 let ellipsis = if truncated { "[...]" } else { "" };
2008 if begin > s.len() || end > s.len() {
2009 let oob_index = if begin > s.len() { begin } else { end };
2010 panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
2014 assert!(begin <= end, "begin <= end ({} <= {}) when slicing `{}`{}",
2015 begin, end, s_trunc, ellipsis);
2017 // 3. character boundary
2018 let index = if !s.is_char_boundary(begin) { begin } else { end };
2019 // find the character
2020 let mut char_start = index;
2021 while !s.is_char_boundary(char_start) {
2024 // `char_start` must be less than len and a char boundary
2025 let ch = s[char_start..].chars().next().unwrap();
2026 let char_range = char_start .. char_start + ch.len_utf8();
2027 panic!("byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
2028 index, ch, char_range, s_trunc, ellipsis);
2034 /// Returns the length of `self`.
2036 /// This length is in bytes, not [`char`]s or graphemes. In other words,
2037 /// it may not be what a human considers the length of the string.
2044 /// let len = "foo".len();
2045 /// assert_eq!(3, len);
2047 /// let len = "ƒoo".len(); // fancy f!
2048 /// assert_eq!(4, len);
2050 #[stable(feature = "rust1", since = "1.0.0")]
2052 #[rustc_const_unstable(feature = "const_str_len")]
2053 pub const fn len(&self) -> usize {
2054 self.as_bytes().len()
2057 /// Returns `true` if `self` has a length of zero bytes.
2065 /// assert!(s.is_empty());
2067 /// let s = "not empty";
2068 /// assert!(!s.is_empty());
2071 #[stable(feature = "rust1", since = "1.0.0")]
2072 #[rustc_const_unstable(feature = "const_str_len")]
2073 pub const fn is_empty(&self) -> bool {
2077 /// Checks that `index`-th byte lies at the start and/or end of a
2078 /// UTF-8 code point sequence.
2080 /// The start and end of the string (when `index == self.len()`) are
2081 /// considered to be
2084 /// Returns `false` if `index` is greater than `self.len()`.
2089 /// let s = "Löwe 老虎 Léopard";
2090 /// assert!(s.is_char_boundary(0));
2092 /// assert!(s.is_char_boundary(6));
2093 /// assert!(s.is_char_boundary(s.len()));
2095 /// // second byte of `ö`
2096 /// assert!(!s.is_char_boundary(2));
2098 /// // third byte of `老`
2099 /// assert!(!s.is_char_boundary(8));
2101 #[stable(feature = "is_char_boundary", since = "1.9.0")]
2103 pub fn is_char_boundary(&self, index: usize) -> bool {
2104 // 0 and len are always ok.
2105 // Test for 0 explicitly so that it can optimize out the check
2106 // easily and skip reading string data for that case.
2107 if index == 0 || index == self.len() { return true; }
2108 match self.as_bytes().get(index) {
2110 // This is bit magic equivalent to: b < 128 || b >= 192
2111 Some(&b) => (b as i8) >= -0x40,
2115 /// Converts a string slice to a byte slice. To convert the byte slice back
2116 /// into a string slice, use the [`str::from_utf8`] function.
2118 /// [`str::from_utf8`]: ./str/fn.from_utf8.html
2125 /// let bytes = "bors".as_bytes();
2126 /// assert_eq!(b"bors", bytes);
2128 #[stable(feature = "rust1", since = "1.0.0")]
2130 #[rustc_const_unstable(feature="const_str_as_bytes")]
2131 pub const fn as_bytes(&self) -> &[u8] {
2136 unsafe { Slices { str: self }.slice }
2139 /// Converts a mutable string slice to a mutable byte slice. To convert the
2140 /// mutable byte slice back into a mutable string slice, use the
2141 /// [`str::from_utf8_mut`] function.
2143 /// [`str::from_utf8_mut`]: ./str/fn.from_utf8_mut.html
2150 /// let mut s = String::from("Hello");
2151 /// let bytes = unsafe { s.as_bytes_mut() };
2153 /// assert_eq!(b"Hello", bytes);
2159 /// let mut s = String::from("🗻∈🌏");
2162 /// let bytes = s.as_bytes_mut();
2164 /// bytes[0] = 0xF0;
2165 /// bytes[1] = 0x9F;
2166 /// bytes[2] = 0x8D;
2167 /// bytes[3] = 0x94;
2170 /// assert_eq!("🍔∈🌏", s);
2172 #[stable(feature = "str_mut_extras", since = "1.20.0")]
2174 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
2175 &mut *(self as *mut str as *mut [u8])
2178 /// Converts a string slice to a raw pointer.
2180 /// As string slices are a slice of bytes, the raw pointer points to a
2181 /// [`u8`]. This pointer will be pointing to the first byte of the string
2184 /// [`u8`]: primitive.u8.html
2191 /// let s = "Hello";
2192 /// let ptr = s.as_ptr();
2194 #[stable(feature = "rust1", since = "1.0.0")]
2196 pub const fn as_ptr(&self) -> *const u8 {
2197 self as *const str as *const u8
2200 /// Converts a mutable string slice to a raw pointer.
2202 /// As string slices are a slice of bytes, the raw pointer points to a
2203 /// [`u8`]. This pointer will be pointing to the first byte of the string
2206 /// It is your responsibility to make sure that the string slice only gets
2207 /// modified in a way that it remains valid UTF-8.
2209 /// [`u8`]: primitive.u8.html
2210 #[unstable(feature = "str_as_mut_ptr", issue = "58215")]
2212 pub fn as_mut_ptr(&mut self) -> *mut u8 {
2213 self as *mut str as *mut u8
2216 /// Returns a subslice of `str`.
2218 /// This is the non-panicking alternative to indexing the `str`. Returns
2219 /// [`None`] whenever equivalent indexing operation would panic.
2221 /// [`None`]: option/enum.Option.html#variant.None
2226 /// let v = String::from("🗻∈🌏");
2228 /// assert_eq!(Some("🗻"), v.get(0..4));
2230 /// // indices not on UTF-8 sequence boundaries
2231 /// assert!(v.get(1..).is_none());
2232 /// assert!(v.get(..8).is_none());
2234 /// // out of bounds
2235 /// assert!(v.get(..42).is_none());
2237 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2239 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
2243 /// Returns a mutable subslice of `str`.
2245 /// This is the non-panicking alternative to indexing the `str`. Returns
2246 /// [`None`] whenever equivalent indexing operation would panic.
2248 /// [`None`]: option/enum.Option.html#variant.None
2253 /// let mut v = String::from("hello");
2254 /// // correct length
2255 /// assert!(v.get_mut(0..5).is_some());
2256 /// // out of bounds
2257 /// assert!(v.get_mut(..42).is_none());
2258 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
2260 /// assert_eq!("hello", v);
2262 /// let s = v.get_mut(0..2);
2263 /// let s = s.map(|s| {
2264 /// s.make_ascii_uppercase();
2267 /// assert_eq!(Some("HE"), s);
2269 /// assert_eq!("HEllo", v);
2271 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2273 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
2277 /// Returns a unchecked subslice of `str`.
2279 /// This is the unchecked alternative to indexing the `str`.
2283 /// Callers of this function are responsible that these preconditions are
2286 /// * The starting index must come before the ending index;
2287 /// * Indexes must be within bounds of the original slice;
2288 /// * Indexes must lie on UTF-8 sequence boundaries.
2290 /// Failing that, the returned string slice may reference invalid memory or
2291 /// violate the invariants communicated by the `str` type.
2298 /// assert_eq!("🗻", v.get_unchecked(0..4));
2299 /// assert_eq!("∈", v.get_unchecked(4..7));
2300 /// assert_eq!("🌏", v.get_unchecked(7..11));
2303 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2305 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
2306 i.get_unchecked(self)
2309 /// Returns a mutable, unchecked subslice of `str`.
2311 /// This is the unchecked alternative to indexing the `str`.
2315 /// Callers of this function are responsible that these preconditions are
2318 /// * The starting index must come before the ending index;
2319 /// * Indexes must be within bounds of the original slice;
2320 /// * Indexes must lie on UTF-8 sequence boundaries.
2322 /// Failing that, the returned string slice may reference invalid memory or
2323 /// violate the invariants communicated by the `str` type.
2328 /// let mut v = String::from("🗻∈🌏");
2330 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
2331 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
2332 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
2335 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2337 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
2338 i.get_unchecked_mut(self)
2341 /// Creates a string slice from another string slice, bypassing safety
2344 /// This is generally not recommended, use with caution! For a safe
2345 /// alternative see [`str`] and [`Index`].
2347 /// [`str`]: primitive.str.html
2348 /// [`Index`]: ops/trait.Index.html
2350 /// This new slice goes from `begin` to `end`, including `begin` but
2351 /// excluding `end`.
2353 /// To get a mutable string slice instead, see the
2354 /// [`slice_mut_unchecked`] method.
2356 /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
2360 /// Callers of this function are responsible that three preconditions are
2363 /// * `begin` must come before `end`.
2364 /// * `begin` and `end` must be byte positions within the string slice.
2365 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2372 /// let s = "Löwe 老虎 Léopard";
2375 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
2378 /// let s = "Hello, world!";
2381 /// assert_eq!("world", s.slice_unchecked(7, 12));
2384 #[stable(feature = "rust1", since = "1.0.0")]
2385 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked(begin..end)` instead")]
2387 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
2388 (begin..end).get_unchecked(self)
2391 /// Creates a string slice from another string slice, bypassing safety
2393 /// This is generally not recommended, use with caution! For a safe
2394 /// alternative see [`str`] and [`IndexMut`].
2396 /// [`str`]: primitive.str.html
2397 /// [`IndexMut`]: ops/trait.IndexMut.html
2399 /// This new slice goes from `begin` to `end`, including `begin` but
2400 /// excluding `end`.
2402 /// To get an immutable string slice instead, see the
2403 /// [`slice_unchecked`] method.
2405 /// [`slice_unchecked`]: #method.slice_unchecked
2409 /// Callers of this function are responsible that three preconditions are
2412 /// * `begin` must come before `end`.
2413 /// * `begin` and `end` must be byte positions within the string slice.
2414 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2415 #[stable(feature = "str_slice_mut", since = "1.5.0")]
2416 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked_mut(begin..end)` instead")]
2418 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
2419 (begin..end).get_unchecked_mut(self)
2422 /// Divide one string slice into two at an index.
2424 /// The argument, `mid`, should be a byte offset from the start of the
2425 /// string. It must also be on the boundary of a UTF-8 code point.
2427 /// The two slices returned go from the start of the string slice to `mid`,
2428 /// and from `mid` to the end of the string slice.
2430 /// To get mutable string slices instead, see the [`split_at_mut`]
2433 /// [`split_at_mut`]: #method.split_at_mut
2437 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2438 /// beyond the last code point of the string slice.
2445 /// let s = "Per Martin-Löf";
2447 /// let (first, last) = s.split_at(3);
2449 /// assert_eq!("Per", first);
2450 /// assert_eq!(" Martin-Löf", last);
2453 #[stable(feature = "str_split_at", since = "1.4.0")]
2454 pub fn split_at(&self, mid: usize) -> (&str, &str) {
2455 // is_char_boundary checks that the index is in [0, .len()]
2456 if self.is_char_boundary(mid) {
2458 (self.get_unchecked(0..mid),
2459 self.get_unchecked(mid..self.len()))
2462 slice_error_fail(self, 0, mid)
2466 /// Divide one mutable string slice into two at an index.
2468 /// The argument, `mid`, should be a byte offset from the start of the
2469 /// string. It must also be on the boundary of a UTF-8 code point.
2471 /// The two slices returned go from the start of the string slice to `mid`,
2472 /// and from `mid` to the end of the string slice.
2474 /// To get immutable string slices instead, see the [`split_at`] method.
2476 /// [`split_at`]: #method.split_at
2480 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2481 /// beyond the last code point of the string slice.
2488 /// let mut s = "Per Martin-Löf".to_string();
2490 /// let (first, last) = s.split_at_mut(3);
2491 /// first.make_ascii_uppercase();
2492 /// assert_eq!("PER", first);
2493 /// assert_eq!(" Martin-Löf", last);
2495 /// assert_eq!("PER Martin-Löf", s);
2498 #[stable(feature = "str_split_at", since = "1.4.0")]
2499 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
2500 // is_char_boundary checks that the index is in [0, .len()]
2501 if self.is_char_boundary(mid) {
2502 let len = self.len();
2503 let ptr = self.as_mut_ptr();
2505 (from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
2506 from_utf8_unchecked_mut(slice::from_raw_parts_mut(
2512 slice_error_fail(self, 0, mid)
2516 /// Returns an iterator over the [`char`]s of a string slice.
2518 /// As a string slice consists of valid UTF-8, we can iterate through a
2519 /// string slice by [`char`]. This method returns such an iterator.
2521 /// It's important to remember that [`char`] represents a Unicode Scalar
2522 /// Value, and may not match your idea of what a 'character' is. Iteration
2523 /// over grapheme clusters may be what you actually want.
2530 /// let word = "goodbye";
2532 /// let count = word.chars().count();
2533 /// assert_eq!(7, count);
2535 /// let mut chars = word.chars();
2537 /// assert_eq!(Some('g'), chars.next());
2538 /// assert_eq!(Some('o'), chars.next());
2539 /// assert_eq!(Some('o'), chars.next());
2540 /// assert_eq!(Some('d'), chars.next());
2541 /// assert_eq!(Some('b'), chars.next());
2542 /// assert_eq!(Some('y'), chars.next());
2543 /// assert_eq!(Some('e'), chars.next());
2545 /// assert_eq!(None, chars.next());
2548 /// Remember, [`char`]s may not match your human intuition about characters:
2553 /// let mut chars = y.chars();
2555 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
2556 /// assert_eq!(Some('\u{0306}'), chars.next());
2558 /// assert_eq!(None, chars.next());
2560 #[stable(feature = "rust1", since = "1.0.0")]
2562 pub fn chars(&self) -> Chars {
2563 Chars{iter: self.as_bytes().iter()}
2566 /// Returns an iterator over the [`char`]s of a string slice, and their
2569 /// As a string slice consists of valid UTF-8, we can iterate through a
2570 /// string slice by [`char`]. This method returns an iterator of both
2571 /// these [`char`]s, as well as their byte positions.
2573 /// The iterator yields tuples. The position is first, the [`char`] is
2581 /// let word = "goodbye";
2583 /// let count = word.char_indices().count();
2584 /// assert_eq!(7, count);
2586 /// let mut char_indices = word.char_indices();
2588 /// assert_eq!(Some((0, 'g')), char_indices.next());
2589 /// assert_eq!(Some((1, 'o')), char_indices.next());
2590 /// assert_eq!(Some((2, 'o')), char_indices.next());
2591 /// assert_eq!(Some((3, 'd')), char_indices.next());
2592 /// assert_eq!(Some((4, 'b')), char_indices.next());
2593 /// assert_eq!(Some((5, 'y')), char_indices.next());
2594 /// assert_eq!(Some((6, 'e')), char_indices.next());
2596 /// assert_eq!(None, char_indices.next());
2599 /// Remember, [`char`]s may not match your human intuition about characters:
2602 /// let yes = "y̆es";
2604 /// let mut char_indices = yes.char_indices();
2606 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
2607 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
2609 /// // note the 3 here - the last character took up two bytes
2610 /// assert_eq!(Some((3, 'e')), char_indices.next());
2611 /// assert_eq!(Some((4, 's')), char_indices.next());
2613 /// assert_eq!(None, char_indices.next());
2615 #[stable(feature = "rust1", since = "1.0.0")]
2617 pub fn char_indices(&self) -> CharIndices {
2618 CharIndices { front_offset: 0, iter: self.chars() }
2621 /// An iterator over the bytes of a string slice.
2623 /// As a string slice consists of a sequence of bytes, we can iterate
2624 /// through a string slice by byte. This method returns such an iterator.
2631 /// let mut bytes = "bors".bytes();
2633 /// assert_eq!(Some(b'b'), bytes.next());
2634 /// assert_eq!(Some(b'o'), bytes.next());
2635 /// assert_eq!(Some(b'r'), bytes.next());
2636 /// assert_eq!(Some(b's'), bytes.next());
2638 /// assert_eq!(None, bytes.next());
2640 #[stable(feature = "rust1", since = "1.0.0")]
2642 pub fn bytes(&self) -> Bytes {
2643 Bytes(self.as_bytes().iter().cloned())
2646 /// Splits a string slice by whitespace.
2648 /// The iterator returned will return string slices that are sub-slices of
2649 /// the original string slice, separated by any amount of whitespace.
2651 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2652 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
2653 /// instead, use [`split_ascii_whitespace`].
2655 /// [`split_ascii_whitespace`]: #method.split_ascii_whitespace
2662 /// let mut iter = "A few words".split_whitespace();
2664 /// assert_eq!(Some("A"), iter.next());
2665 /// assert_eq!(Some("few"), iter.next());
2666 /// assert_eq!(Some("words"), iter.next());
2668 /// assert_eq!(None, iter.next());
2671 /// All kinds of whitespace are considered:
2674 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
2675 /// assert_eq!(Some("Mary"), iter.next());
2676 /// assert_eq!(Some("had"), iter.next());
2677 /// assert_eq!(Some("a"), iter.next());
2678 /// assert_eq!(Some("little"), iter.next());
2679 /// assert_eq!(Some("lamb"), iter.next());
2681 /// assert_eq!(None, iter.next());
2683 #[stable(feature = "split_whitespace", since = "1.1.0")]
2685 pub fn split_whitespace(&self) -> SplitWhitespace {
2686 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
2689 /// Splits a string slice by ASCII whitespace.
2691 /// The iterator returned will return string slices that are sub-slices of
2692 /// the original string slice, separated by any amount of ASCII whitespace.
2694 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
2696 /// [`split_whitespace`]: #method.split_whitespace
2703 /// let mut iter = "A few words".split_ascii_whitespace();
2705 /// assert_eq!(Some("A"), iter.next());
2706 /// assert_eq!(Some("few"), iter.next());
2707 /// assert_eq!(Some("words"), iter.next());
2709 /// assert_eq!(None, iter.next());
2712 /// All kinds of ASCII whitespace are considered:
2715 /// let mut iter = " Mary had\ta little \n\t lamb".split_whitespace();
2716 /// assert_eq!(Some("Mary"), iter.next());
2717 /// assert_eq!(Some("had"), iter.next());
2718 /// assert_eq!(Some("a"), iter.next());
2719 /// assert_eq!(Some("little"), iter.next());
2720 /// assert_eq!(Some("lamb"), iter.next());
2722 /// assert_eq!(None, iter.next());
2724 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
2726 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace {
2729 .split(IsAsciiWhitespace)
2730 .filter(BytesIsNotEmpty)
2731 .map(UnsafeBytesToStr);
2732 SplitAsciiWhitespace { inner }
2735 /// An iterator over the lines of a string, as string slices.
2737 /// Lines are ended with either a newline (`\n`) or a carriage return with
2738 /// a line feed (`\r\n`).
2740 /// The final line ending is optional.
2747 /// let text = "foo\r\nbar\n\nbaz\n";
2748 /// let mut lines = text.lines();
2750 /// assert_eq!(Some("foo"), lines.next());
2751 /// assert_eq!(Some("bar"), lines.next());
2752 /// assert_eq!(Some(""), lines.next());
2753 /// assert_eq!(Some("baz"), lines.next());
2755 /// assert_eq!(None, lines.next());
2758 /// The final line ending isn't required:
2761 /// let text = "foo\nbar\n\r\nbaz";
2762 /// let mut lines = text.lines();
2764 /// assert_eq!(Some("foo"), lines.next());
2765 /// assert_eq!(Some("bar"), lines.next());
2766 /// assert_eq!(Some(""), lines.next());
2767 /// assert_eq!(Some("baz"), lines.next());
2769 /// assert_eq!(None, lines.next());
2771 #[stable(feature = "rust1", since = "1.0.0")]
2773 pub fn lines(&self) -> Lines {
2774 Lines(self.split_terminator('\n').map(LinesAnyMap))
2777 /// An iterator over the lines of a string.
2778 #[stable(feature = "rust1", since = "1.0.0")]
2779 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
2781 #[allow(deprecated)]
2782 pub fn lines_any(&self) -> LinesAny {
2783 LinesAny(self.lines())
2786 /// Returns an iterator of `u16` over the string encoded as UTF-16.
2793 /// let text = "Zażółć gęślą jaźń";
2795 /// let utf8_len = text.len();
2796 /// let utf16_len = text.encode_utf16().count();
2798 /// assert!(utf16_len <= utf8_len);
2800 #[stable(feature = "encode_utf16", since = "1.8.0")]
2801 pub fn encode_utf16(&self) -> EncodeUtf16 {
2802 EncodeUtf16 { chars: self.chars(), extra: 0 }
2805 /// Returns `true` if the given pattern matches a sub-slice of
2806 /// this string slice.
2808 /// Returns `false` if it does not.
2815 /// let bananas = "bananas";
2817 /// assert!(bananas.contains("nana"));
2818 /// assert!(!bananas.contains("apples"));
2820 #[stable(feature = "rust1", since = "1.0.0")]
2822 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2823 pat.is_contained_in(self)
2826 /// Returns `true` if the given pattern matches a prefix of this
2829 /// Returns `false` if it does not.
2836 /// let bananas = "bananas";
2838 /// assert!(bananas.starts_with("bana"));
2839 /// assert!(!bananas.starts_with("nana"));
2841 #[stable(feature = "rust1", since = "1.0.0")]
2842 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2843 pat.is_prefix_of(self)
2846 /// Returns `true` if the given pattern matches a suffix of this
2849 /// Returns `false` if it does not.
2856 /// let bananas = "bananas";
2858 /// assert!(bananas.ends_with("anas"));
2859 /// assert!(!bananas.ends_with("nana"));
2861 #[stable(feature = "rust1", since = "1.0.0")]
2862 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
2863 where P::Searcher: ReverseSearcher<'a>
2865 pat.is_suffix_of(self)
2868 /// Returns the byte index of the first character of this string slice that
2869 /// matches the pattern.
2871 /// Returns [`None`] if the pattern doesn't match.
2873 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2874 /// a character matches.
2876 /// [`None`]: option/enum.Option.html#variant.None
2880 /// Simple patterns:
2883 /// let s = "Löwe 老虎 Léopard";
2885 /// assert_eq!(s.find('L'), Some(0));
2886 /// assert_eq!(s.find('é'), Some(14));
2887 /// assert_eq!(s.find("Léopard"), Some(13));
2890 /// More complex patterns using point-free style and closures:
2893 /// let s = "Löwe 老虎 Léopard";
2895 /// assert_eq!(s.find(char::is_whitespace), Some(5));
2896 /// assert_eq!(s.find(char::is_lowercase), Some(1));
2897 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
2898 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
2901 /// Not finding the pattern:
2904 /// let s = "Löwe 老虎 Léopard";
2905 /// let x: &[_] = &['1', '2'];
2907 /// assert_eq!(s.find(x), None);
2909 #[stable(feature = "rust1", since = "1.0.0")]
2911 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2912 pat.into_searcher(self).next_match().map(|(i, _)| i)
2915 /// Returns the byte index of the last character of this string slice that
2916 /// matches the pattern.
2918 /// Returns [`None`] if the pattern doesn't match.
2920 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2921 /// a character matches.
2923 /// [`None`]: option/enum.Option.html#variant.None
2927 /// Simple patterns:
2930 /// let s = "Löwe 老虎 Léopard";
2932 /// assert_eq!(s.rfind('L'), Some(13));
2933 /// assert_eq!(s.rfind('é'), Some(14));
2936 /// More complex patterns with closures:
2939 /// let s = "Löwe 老虎 Léopard";
2941 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
2942 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
2945 /// Not finding the pattern:
2948 /// let s = "Löwe 老虎 Léopard";
2949 /// let x: &[_] = &['1', '2'];
2951 /// assert_eq!(s.rfind(x), None);
2953 #[stable(feature = "rust1", since = "1.0.0")]
2955 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
2956 where P::Searcher: ReverseSearcher<'a>
2958 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
2961 /// An iterator over substrings of this string slice, separated by
2962 /// characters matched by a pattern.
2964 /// The pattern can be any type that implements the Pattern trait. Notable
2965 /// examples are `&str`, [`char`], and closures that determines the split.
2967 /// # Iterator behavior
2969 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
2970 /// allows a reverse search and forward/reverse search yields the same
2971 /// elements. This is true for, eg, [`char`] but not for `&str`.
2973 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
2975 /// If the pattern allows a reverse search but its results might differ
2976 /// from a forward search, the [`rsplit`] method can be used.
2978 /// [`rsplit`]: #method.rsplit
2982 /// Simple patterns:
2985 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
2986 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
2988 /// let v: Vec<&str> = "".split('X').collect();
2989 /// assert_eq!(v, [""]);
2991 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
2992 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
2994 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
2995 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
2997 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
2998 /// assert_eq!(v, ["abc", "def", "ghi"]);
3000 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
3001 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3004 /// A more complex pattern, using a closure:
3007 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
3008 /// assert_eq!(v, ["abc", "def", "ghi"]);
3011 /// If a string contains multiple contiguous separators, you will end up
3012 /// with empty strings in the output:
3015 /// let x = "||||a||b|c".to_string();
3016 /// let d: Vec<_> = x.split('|').collect();
3018 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3021 /// Contiguous separators are separated by the empty string.
3024 /// let x = "(///)".to_string();
3025 /// let d: Vec<_> = x.split('/').collect();
3027 /// assert_eq!(d, &["(", "", "", ")"]);
3030 /// Separators at the start or end of a string are neighbored
3031 /// by empty strings.
3034 /// let d: Vec<_> = "010".split("0").collect();
3035 /// assert_eq!(d, &["", "1", ""]);
3038 /// When the empty string is used as a separator, it separates
3039 /// every character in the string, along with the beginning
3040 /// and end of the string.
3043 /// let f: Vec<_> = "rust".split("").collect();
3044 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
3047 /// Contiguous separators can lead to possibly surprising behavior
3048 /// when whitespace is used as the separator. This code is correct:
3051 /// let x = " a b c".to_string();
3052 /// let d: Vec<_> = x.split(' ').collect();
3054 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3057 /// It does _not_ give you:
3060 /// assert_eq!(d, &["a", "b", "c"]);
3063 /// Use [`split_whitespace`] for this behavior.
3065 /// [`split_whitespace`]: #method.split_whitespace
3066 #[stable(feature = "rust1", since = "1.0.0")]
3068 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
3069 Split(SplitInternal {
3072 matcher: pat.into_searcher(self),
3073 allow_trailing_empty: true,
3078 /// An iterator over substrings of the given string slice, separated by
3079 /// characters matched by a pattern and yielded in reverse order.
3081 /// The pattern can be any type that implements the Pattern trait. Notable
3082 /// examples are `&str`, [`char`], and closures that determines the split.
3084 /// # Iterator behavior
3086 /// The returned iterator requires that the pattern supports a reverse
3087 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3088 /// search yields the same elements.
3090 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3092 /// For iterating from the front, the [`split`] method can be used.
3094 /// [`split`]: #method.split
3098 /// Simple patterns:
3101 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
3102 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
3104 /// let v: Vec<&str> = "".rsplit('X').collect();
3105 /// assert_eq!(v, [""]);
3107 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
3108 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
3110 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
3111 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
3114 /// A more complex pattern, using a closure:
3117 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
3118 /// assert_eq!(v, ["ghi", "def", "abc"]);
3120 #[stable(feature = "rust1", since = "1.0.0")]
3122 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
3123 where P::Searcher: ReverseSearcher<'a>
3125 RSplit(self.split(pat).0)
3128 /// An iterator over substrings of the given string slice, separated by
3129 /// characters matched by a pattern.
3131 /// The pattern can be any type that implements the Pattern trait. Notable
3132 /// examples are `&str`, [`char`], and closures that determines the split.
3134 /// Equivalent to [`split`], except that the trailing substring
3135 /// is skipped if empty.
3137 /// [`split`]: #method.split
3139 /// This method can be used for string data that is _terminated_,
3140 /// rather than _separated_ by a pattern.
3142 /// # Iterator behavior
3144 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3145 /// allows a reverse search and forward/reverse search yields the same
3146 /// elements. This is true for, eg, [`char`] but not for `&str`.
3148 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3150 /// If the pattern allows a reverse search but its results might differ
3151 /// from a forward search, the [`rsplit_terminator`] method can be used.
3153 /// [`rsplit_terminator`]: #method.rsplit_terminator
3160 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
3161 /// assert_eq!(v, ["A", "B"]);
3163 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
3164 /// assert_eq!(v, ["A", "", "B", ""]);
3166 #[stable(feature = "rust1", since = "1.0.0")]
3168 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
3169 SplitTerminator(SplitInternal {
3170 allow_trailing_empty: false,
3175 /// An iterator over substrings of `self`, separated by characters
3176 /// matched by a pattern and yielded in reverse order.
3178 /// The pattern can be any type that implements the Pattern trait. Notable
3179 /// examples are `&str`, [`char`], and closures that determines the split.
3180 /// Additional libraries might provide more complex patterns like
3181 /// regular expressions.
3183 /// Equivalent to [`split`], except that the trailing substring is
3184 /// skipped if empty.
3186 /// [`split`]: #method.split
3188 /// This method can be used for string data that is _terminated_,
3189 /// rather than _separated_ by a pattern.
3191 /// # Iterator behavior
3193 /// The returned iterator requires that the pattern supports a
3194 /// reverse search, and it will be double ended if a forward/reverse
3195 /// search yields the same elements.
3197 /// For iterating from the front, the [`split_terminator`] method can be
3200 /// [`split_terminator`]: #method.split_terminator
3205 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
3206 /// assert_eq!(v, ["B", "A"]);
3208 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
3209 /// assert_eq!(v, ["", "B", "", "A"]);
3211 #[stable(feature = "rust1", since = "1.0.0")]
3213 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
3214 where P::Searcher: ReverseSearcher<'a>
3216 RSplitTerminator(self.split_terminator(pat).0)
3219 /// An iterator over substrings of the given string slice, separated by a
3220 /// pattern, restricted to returning at most `n` items.
3222 /// If `n` substrings are returned, the last substring (the `n`th substring)
3223 /// will contain the remainder of the string.
3225 /// The pattern can be any type that implements the Pattern trait. Notable
3226 /// examples are `&str`, [`char`], and closures that determines the split.
3228 /// # Iterator behavior
3230 /// The returned iterator will not be double ended, because it is
3231 /// not efficient to support.
3233 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
3236 /// [`rsplitn`]: #method.rsplitn
3240 /// Simple patterns:
3243 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
3244 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
3246 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
3247 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
3249 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
3250 /// assert_eq!(v, ["abcXdef"]);
3252 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
3253 /// assert_eq!(v, [""]);
3256 /// A more complex pattern, using a closure:
3259 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
3260 /// assert_eq!(v, ["abc", "defXghi"]);
3262 #[stable(feature = "rust1", since = "1.0.0")]
3264 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
3265 SplitN(SplitNInternal {
3266 iter: self.split(pat).0,
3271 /// An iterator over substrings of this string slice, separated by a
3272 /// pattern, starting from the end of the string, restricted to returning
3273 /// at most `n` items.
3275 /// If `n` substrings are returned, the last substring (the `n`th substring)
3276 /// will contain the remainder of the string.
3278 /// The pattern can be any type that implements the Pattern trait. Notable
3279 /// examples are `&str`, [`char`], and closures that determines the split.
3281 /// # Iterator behavior
3283 /// The returned iterator will not be double ended, because it is not
3284 /// efficient to support.
3286 /// For splitting from the front, the [`splitn`] method can be used.
3288 /// [`splitn`]: #method.splitn
3292 /// Simple patterns:
3295 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
3296 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
3298 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
3299 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
3301 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
3302 /// assert_eq!(v, ["leopard", "lion::tiger"]);
3305 /// A more complex pattern, using a closure:
3308 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
3309 /// assert_eq!(v, ["ghi", "abc1def"]);
3311 #[stable(feature = "rust1", since = "1.0.0")]
3313 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
3314 where P::Searcher: ReverseSearcher<'a>
3316 RSplitN(self.splitn(n, pat).0)
3319 /// An iterator over the disjoint matches of a pattern within the given string
3322 /// The pattern can be any type that implements the Pattern trait. Notable
3323 /// examples are `&str`, [`char`], and closures that determines the split.
3325 /// # Iterator behavior
3327 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3328 /// allows a reverse search and forward/reverse search yields the same
3329 /// elements. This is true for, eg, [`char`] but not for `&str`.
3331 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3333 /// If the pattern allows a reverse search but its results might differ
3334 /// from a forward search, the [`rmatches`] method can be used.
3336 /// [`rmatches`]: #method.rmatches
3343 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
3344 /// assert_eq!(v, ["abc", "abc", "abc"]);
3346 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
3347 /// assert_eq!(v, ["1", "2", "3"]);
3349 #[stable(feature = "str_matches", since = "1.2.0")]
3351 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
3352 Matches(MatchesInternal(pat.into_searcher(self)))
3355 /// An iterator over the disjoint matches of a pattern within this string slice,
3356 /// yielded in reverse order.
3358 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3359 /// a character matches.
3361 /// # Iterator behavior
3363 /// The returned iterator requires that the pattern supports a reverse
3364 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3365 /// search yields the same elements.
3367 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3369 /// For iterating from the front, the [`matches`] method can be used.
3371 /// [`matches`]: #method.matches
3378 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
3379 /// assert_eq!(v, ["abc", "abc", "abc"]);
3381 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
3382 /// assert_eq!(v, ["3", "2", "1"]);
3384 #[stable(feature = "str_matches", since = "1.2.0")]
3386 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
3387 where P::Searcher: ReverseSearcher<'a>
3389 RMatches(self.matches(pat).0)
3392 /// An iterator over the disjoint matches of a pattern within this string
3393 /// slice as well as the index that the match starts at.
3395 /// For matches of `pat` within `self` that overlap, only the indices
3396 /// corresponding to the first match are returned.
3398 /// The pattern can be a `&str`, [`char`], or a closure that determines
3399 /// if a character matches.
3401 /// # Iterator behavior
3403 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3404 /// allows a reverse search and forward/reverse search yields the same
3405 /// elements. This is true for, eg, [`char`] but not for `&str`.
3407 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3409 /// If the pattern allows a reverse search but its results might differ
3410 /// from a forward search, the [`rmatch_indices`] method can be used.
3412 /// [`rmatch_indices`]: #method.rmatch_indices
3419 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
3420 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
3422 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
3423 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
3425 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
3426 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
3428 #[stable(feature = "str_match_indices", since = "1.5.0")]
3430 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
3431 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
3434 /// An iterator over the disjoint matches of a pattern within `self`,
3435 /// yielded in reverse order along with the index of the match.
3437 /// For matches of `pat` within `self` that overlap, only the indices
3438 /// corresponding to the last match are returned.
3440 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
3441 /// character matches.
3443 /// # Iterator behavior
3445 /// The returned iterator requires that the pattern supports a reverse
3446 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3447 /// search yields the same elements.
3449 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3451 /// For iterating from the front, the [`match_indices`] method can be used.
3453 /// [`match_indices`]: #method.match_indices
3460 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
3461 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
3463 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
3464 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
3466 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
3467 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
3469 #[stable(feature = "str_match_indices", since = "1.5.0")]
3471 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
3472 where P::Searcher: ReverseSearcher<'a>
3474 RMatchIndices(self.match_indices(pat).0)
3477 /// Returns a string slice with leading and trailing whitespace removed.
3479 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3480 /// Core Property `White_Space`.
3487 /// let s = " Hello\tworld\t";
3489 /// assert_eq!("Hello\tworld", s.trim());
3491 #[must_use = "this returns the trimmed string as a slice, \
3492 without modifying the original"]
3493 #[stable(feature = "rust1", since = "1.0.0")]
3494 pub fn trim(&self) -> &str {
3495 self.trim_matches(|c: char| c.is_whitespace())
3498 /// Returns a string slice with leading whitespace removed.
3500 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3501 /// Core Property `White_Space`.
3503 /// # Text directionality
3505 /// A string is a sequence of bytes. `start` in this context means the first
3506 /// position of that byte string; for a left-to-right language like English or
3507 /// Russian, this will be left side, and for right-to-left languages like
3508 /// like Arabic or Hebrew, this will be the right side.
3515 /// let s = " Hello\tworld\t";
3516 /// assert_eq!("Hello\tworld\t", s.trim_start());
3522 /// let s = " English ";
3523 /// assert!(Some('E') == s.trim_start().chars().next());
3525 /// let s = " עברית ";
3526 /// assert!(Some('ע') == s.trim_start().chars().next());
3528 #[must_use = "this returns the trimmed string as a new slice, \
3529 without modifying the original"]
3530 #[stable(feature = "trim_direction", since = "1.30.0")]
3531 pub fn trim_start(&self) -> &str {
3532 self.trim_start_matches(|c: char| c.is_whitespace())
3535 /// Returns a string slice with trailing whitespace removed.
3537 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3538 /// Core Property `White_Space`.
3540 /// # Text directionality
3542 /// A string is a sequence of bytes. `end` in this context means the last
3543 /// position of that byte string; for a left-to-right language like English or
3544 /// Russian, this will be right side, and for right-to-left languages like
3545 /// like Arabic or Hebrew, this will be the left side.
3552 /// let s = " Hello\tworld\t";
3553 /// assert_eq!(" Hello\tworld", s.trim_end());
3559 /// let s = " English ";
3560 /// assert!(Some('h') == s.trim_end().chars().rev().next());
3562 /// let s = " עברית ";
3563 /// assert!(Some('ת') == s.trim_end().chars().rev().next());
3565 #[must_use = "this returns the trimmed string as a new slice, \
3566 without modifying the original"]
3567 #[stable(feature = "trim_direction", since = "1.30.0")]
3568 pub fn trim_end(&self) -> &str {
3569 self.trim_end_matches(|c: char| c.is_whitespace())
3572 /// Returns a string slice with leading whitespace removed.
3574 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3575 /// Core Property `White_Space`.
3577 /// # Text directionality
3579 /// A string is a sequence of bytes. 'Left' in this context means the first
3580 /// position of that byte string; for a language like Arabic or Hebrew
3581 /// which are 'right to left' rather than 'left to right', this will be
3582 /// the _right_ side, not the left.
3589 /// let s = " Hello\tworld\t";
3591 /// assert_eq!("Hello\tworld\t", s.trim_left());
3597 /// let s = " English";
3598 /// assert!(Some('E') == s.trim_left().chars().next());
3600 /// let s = " עברית";
3601 /// assert!(Some('ע') == s.trim_left().chars().next());
3603 #[stable(feature = "rust1", since = "1.0.0")]
3604 #[rustc_deprecated(reason = "superseded by `trim_start`", since = "1.33.0")]
3605 pub fn trim_left(&self) -> &str {
3609 /// Returns a string slice with trailing whitespace removed.
3611 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3612 /// Core Property `White_Space`.
3614 /// # Text directionality
3616 /// A string is a sequence of bytes. 'Right' in this context means the last
3617 /// position of that byte string; for a language like Arabic or Hebrew
3618 /// which are 'right to left' rather than 'left to right', this will be
3619 /// the _left_ side, not the right.
3626 /// let s = " Hello\tworld\t";
3628 /// assert_eq!(" Hello\tworld", s.trim_right());
3634 /// let s = "English ";
3635 /// assert!(Some('h') == s.trim_right().chars().rev().next());
3637 /// let s = "עברית ";
3638 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
3640 #[stable(feature = "rust1", since = "1.0.0")]
3641 #[rustc_deprecated(reason = "superseded by `trim_end`", since = "1.33.0")]
3642 pub fn trim_right(&self) -> &str {
3646 /// Returns a string slice with all prefixes and suffixes that match a
3647 /// pattern repeatedly removed.
3649 /// The pattern can be a [`char`] or a closure that determines if a
3650 /// character matches.
3654 /// Simple patterns:
3657 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
3658 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
3660 /// let x: &[_] = &['1', '2'];
3661 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
3664 /// A more complex pattern, using a closure:
3667 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
3669 #[must_use = "this returns the trimmed string as a new slice, \
3670 without modifying the original"]
3671 #[stable(feature = "rust1", since = "1.0.0")]
3672 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3673 where P::Searcher: DoubleEndedSearcher<'a>
3677 let mut matcher = pat.into_searcher(self);
3678 if let Some((a, b)) = matcher.next_reject() {
3680 j = b; // Remember earliest known match, correct it below if
3681 // last match is different
3683 if let Some((_, b)) = matcher.next_reject_back() {
3687 // Searcher is known to return valid indices
3688 self.get_unchecked(i..j)
3692 /// Returns a string slice with all prefixes that match a pattern
3693 /// repeatedly removed.
3695 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3696 /// a character matches.
3698 /// # Text directionality
3700 /// A string is a sequence of bytes. 'Left' in this context means the first
3701 /// position of that byte string; for a language like Arabic or Hebrew
3702 /// which are 'right to left' rather than 'left to right', this will be
3703 /// the _right_ side, not the left.
3710 /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
3711 /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
3713 /// let x: &[_] = &['1', '2'];
3714 /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
3716 #[must_use = "this returns the trimmed string as a new slice, \
3717 without modifying the original"]
3718 #[stable(feature = "trim_direction", since = "1.30.0")]
3719 pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3720 let mut i = self.len();
3721 let mut matcher = pat.into_searcher(self);
3722 if let Some((a, _)) = matcher.next_reject() {
3726 // Searcher is known to return valid indices
3727 self.get_unchecked(i..self.len())
3731 /// Returns a string slice with all suffixes that match a pattern
3732 /// repeatedly removed.
3734 /// The pattern can be a `&str`, [`char`], or a closure that
3735 /// determines if a character matches.
3737 /// # Text directionality
3739 /// A string is a sequence of bytes. 'Right' in this context means the last
3740 /// position of that byte string; for a language like Arabic or Hebrew
3741 /// which are 'right to left' rather than 'left to right', this will be
3742 /// the _left_ side, not the right.
3746 /// Simple patterns:
3749 /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
3750 /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
3752 /// let x: &[_] = &['1', '2'];
3753 /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
3756 /// A more complex pattern, using a closure:
3759 /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
3761 #[must_use = "this returns the trimmed string as a new slice, \
3762 without modifying the original"]
3763 #[stable(feature = "trim_direction", since = "1.30.0")]
3764 pub fn trim_end_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3765 where P::Searcher: ReverseSearcher<'a>
3768 let mut matcher = pat.into_searcher(self);
3769 if let Some((_, b)) = matcher.next_reject_back() {
3773 // Searcher is known to return valid indices
3774 self.get_unchecked(0..j)
3778 /// Returns a string slice with all prefixes that match a pattern
3779 /// repeatedly removed.
3781 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3782 /// a character matches.
3784 /// [`char`]: primitive.char.html
3786 /// # Text directionality
3788 /// A string is a sequence of bytes. `start` in this context means the first
3789 /// position of that byte string; for a left-to-right language like English or
3790 /// Russian, this will be left side, and for right-to-left languages like
3791 /// like Arabic or Hebrew, this will be the right side.
3798 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
3799 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
3801 /// let x: &[_] = &['1', '2'];
3802 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
3804 #[stable(feature = "rust1", since = "1.0.0")]
3805 #[rustc_deprecated(reason = "superseded by `trim_start_matches`", since = "1.33.0")]
3806 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3807 self.trim_start_matches(pat)
3810 /// Returns a string slice with all suffixes that match a pattern
3811 /// repeatedly removed.
3813 /// The pattern can be a `&str`, [`char`], or a closure that
3814 /// determines if a character matches.
3816 /// [`char`]: primitive.char.html
3818 /// # Text directionality
3820 /// A string is a sequence of bytes. `end` in this context means the last
3821 /// position of that byte string; for a left-to-right language like English or
3822 /// Russian, this will be right side, and for right-to-left languages like
3823 /// like Arabic or Hebrew, this will be the left side.
3827 /// Simple patterns:
3830 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
3831 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
3833 /// let x: &[_] = &['1', '2'];
3834 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
3837 /// A more complex pattern, using a closure:
3840 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
3842 #[stable(feature = "rust1", since = "1.0.0")]
3843 #[rustc_deprecated(reason = "superseded by `trim_end_matches`", since = "1.33.0")]
3844 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3845 where P::Searcher: ReverseSearcher<'a>
3847 self.trim_end_matches(pat)
3850 /// Parses this string slice into another type.
3852 /// Because `parse` is so general, it can cause problems with type
3853 /// inference. As such, `parse` is one of the few times you'll see
3854 /// the syntax affectionately known as the 'turbofish': `::<>`. This
3855 /// helps the inference algorithm understand specifically which type
3856 /// you're trying to parse into.
3858 /// `parse` can parse any type that implements the [`FromStr`] trait.
3860 /// [`FromStr`]: str/trait.FromStr.html
3864 /// Will return [`Err`] if it's not possible to parse this string slice into
3865 /// the desired type.
3867 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
3874 /// let four: u32 = "4".parse().unwrap();
3876 /// assert_eq!(4, four);
3879 /// Using the 'turbofish' instead of annotating `four`:
3882 /// let four = "4".parse::<u32>();
3884 /// assert_eq!(Ok(4), four);
3887 /// Failing to parse:
3890 /// let nope = "j".parse::<u32>();
3892 /// assert!(nope.is_err());
3895 #[stable(feature = "rust1", since = "1.0.0")]
3896 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
3897 FromStr::from_str(self)
3900 /// Checks if all characters in this string are within the ASCII range.
3905 /// let ascii = "hello!\n";
3906 /// let non_ascii = "Grüße, Jürgen ❤";
3908 /// assert!(ascii.is_ascii());
3909 /// assert!(!non_ascii.is_ascii());
3911 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3913 pub fn is_ascii(&self) -> bool {
3914 // We can treat each byte as character here: all multibyte characters
3915 // start with a byte that is not in the ascii range, so we will stop
3917 self.bytes().all(|b| b.is_ascii())
3920 /// Checks that two strings are an ASCII case-insensitive match.
3922 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
3923 /// but without allocating and copying temporaries.
3928 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
3929 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
3930 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
3932 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3934 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
3935 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
3938 /// Converts this string to its ASCII upper case equivalent in-place.
3940 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3941 /// but non-ASCII letters are unchanged.
3943 /// To return a new uppercased value without modifying the existing one, use
3944 /// [`to_ascii_uppercase`].
3946 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3947 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3948 pub fn make_ascii_uppercase(&mut self) {
3949 let me = unsafe { self.as_bytes_mut() };
3950 me.make_ascii_uppercase()
3953 /// Converts this string to its ASCII lower case equivalent in-place.
3955 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3956 /// but non-ASCII letters are unchanged.
3958 /// To return a new lowercased value without modifying the existing one, use
3959 /// [`to_ascii_lowercase`].
3961 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3962 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3963 pub fn make_ascii_lowercase(&mut self) {
3964 let me = unsafe { self.as_bytes_mut() };
3965 me.make_ascii_lowercase()
3968 /// Return an iterator that escapes each char in `self` with [`char::escape_debug`].
3970 /// Note: only extended grapheme codepoints that begin the string will be
3973 /// [`char::escape_debug`]: ../std/primitive.char.html#method.escape_debug
3980 /// for c in "❤\n!".escape_debug() {
3981 /// print!("{}", c);
3986 /// Using `println!` directly:
3989 /// println!("{}", "❤\n!".escape_debug());
3993 /// Both are equivalent to:
3996 /// println!("❤\\n!");
3999 /// Using `to_string`:
4002 /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
4004 #[stable(feature = "str_escape", since = "1.34.0")]
4005 pub fn escape_debug(&self) -> EscapeDebug {
4006 let mut chars = self.chars();
4009 .map(|first| first.escape_debug_ext(true))
4012 .chain(chars.flat_map(CharEscapeDebugContinue))
4016 /// Return an iterator that escapes each char in `self` with [`char::escape_default`].
4018 /// [`char::escape_default`]: ../std/primitive.char.html#method.escape_default
4025 /// for c in "❤\n!".escape_default() {
4026 /// print!("{}", c);
4031 /// Using `println!` directly:
4034 /// println!("{}", "❤\n!".escape_default());
4038 /// Both are equivalent to:
4041 /// println!("\\u{{2764}}\n!");
4044 /// Using `to_string`:
4047 /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
4049 #[stable(feature = "str_escape", since = "1.34.0")]
4050 pub fn escape_default(&self) -> EscapeDefault {
4051 EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
4054 /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`].
4056 /// [`char::escape_unicode`]: ../std/primitive.char.html#method.escape_unicode
4063 /// for c in "❤\n!".escape_unicode() {
4064 /// print!("{}", c);
4069 /// Using `println!` directly:
4072 /// println!("{}", "❤\n!".escape_unicode());
4076 /// Both are equivalent to:
4079 /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
4082 /// Using `to_string`:
4085 /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
4087 #[stable(feature = "str_escape", since = "1.34.0")]
4088 pub fn escape_unicode(&self) -> EscapeUnicode {
4089 EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
4095 struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
4096 c.escape_debug_ext(false)
4100 struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
4104 struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
4109 #[stable(feature = "rust1", since = "1.0.0")]
4110 impl AsRef<[u8]> for str {
4112 fn as_ref(&self) -> &[u8] {
4117 #[stable(feature = "rust1", since = "1.0.0")]
4118 impl Default for &str {
4119 /// Creates an empty str
4120 fn default() -> Self { "" }
4123 #[stable(feature = "default_mut_str", since = "1.28.0")]
4124 impl Default for &mut str {
4125 /// Creates an empty mutable str
4126 fn default() -> Self { unsafe { from_utf8_unchecked_mut(&mut []) } }
4129 /// An iterator over the non-whitespace substrings of a string,
4130 /// separated by any amount of whitespace.
4132 /// This struct is created by the [`split_whitespace`] method on [`str`].
4133 /// See its documentation for more.
4135 /// [`split_whitespace`]: ../../std/primitive.str.html#method.split_whitespace
4136 /// [`str`]: ../../std/primitive.str.html
4137 #[stable(feature = "split_whitespace", since = "1.1.0")]
4138 #[derive(Clone, Debug)]
4139 pub struct SplitWhitespace<'a> {
4140 inner: Filter<Split<'a, IsWhitespace>, IsNotEmpty>,
4143 /// An iterator over the non-ASCII-whitespace substrings of a string,
4144 /// separated by any amount of ASCII whitespace.
4146 /// This struct is created by the [`split_ascii_whitespace`] method on [`str`].
4147 /// See its documentation for more.
4149 /// [`split_ascii_whitespace`]: ../../std/primitive.str.html#method.split_ascii_whitespace
4150 /// [`str`]: ../../std/primitive.str.html
4151 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4152 #[derive(Clone, Debug)]
4153 pub struct SplitAsciiWhitespace<'a> {
4154 inner: Map<Filter<SliceSplit<'a, u8, IsAsciiWhitespace>, BytesIsNotEmpty>, UnsafeBytesToStr>,
4159 struct IsWhitespace impl Fn = |c: char| -> bool {
4164 struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
4165 byte.is_ascii_whitespace()
4169 struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
4174 struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
4179 struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
4180 unsafe { from_utf8_unchecked(bytes) }
4184 #[stable(feature = "split_whitespace", since = "1.1.0")]
4185 impl<'a> Iterator for SplitWhitespace<'a> {
4186 type Item = &'a str;
4189 fn next(&mut self) -> Option<&'a str> {
4194 fn size_hint(&self) -> (usize, Option<usize>) {
4195 self.inner.size_hint()
4199 #[stable(feature = "split_whitespace", since = "1.1.0")]
4200 impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
4202 fn next_back(&mut self) -> Option<&'a str> {
4203 self.inner.next_back()
4207 #[stable(feature = "fused", since = "1.26.0")]
4208 impl FusedIterator for SplitWhitespace<'_> {}
4210 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4211 impl<'a> Iterator for SplitAsciiWhitespace<'a> {
4212 type Item = &'a str;
4215 fn next(&mut self) -> Option<&'a str> {
4220 fn size_hint(&self) -> (usize, Option<usize>) {
4221 self.inner.size_hint()
4225 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4226 impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> {
4228 fn next_back(&mut self) -> Option<&'a str> {
4229 self.inner.next_back()
4233 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4234 impl FusedIterator for SplitAsciiWhitespace<'_> {}
4236 /// An iterator of [`u16`] over the string encoded as UTF-16.
4238 /// [`u16`]: ../../std/primitive.u16.html
4240 /// This struct is created by the [`encode_utf16`] method on [`str`].
4241 /// See its documentation for more.
4243 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
4244 /// [`str`]: ../../std/primitive.str.html
4246 #[stable(feature = "encode_utf16", since = "1.8.0")]
4247 pub struct EncodeUtf16<'a> {
4252 #[stable(feature = "collection_debug", since = "1.17.0")]
4253 impl fmt::Debug for EncodeUtf16<'_> {
4254 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4255 f.pad("EncodeUtf16 { .. }")
4259 #[stable(feature = "encode_utf16", since = "1.8.0")]
4260 impl<'a> Iterator for EncodeUtf16<'a> {
4264 fn next(&mut self) -> Option<u16> {
4265 if self.extra != 0 {
4266 let tmp = self.extra;
4271 let mut buf = [0; 2];
4272 self.chars.next().map(|ch| {
4273 let n = ch.encode_utf16(&mut buf).len();
4275 self.extra = buf[1];
4282 fn size_hint(&self) -> (usize, Option<usize>) {
4283 let (low, high) = self.chars.size_hint();
4284 // every char gets either one u16 or two u16,
4285 // so this iterator is between 1 or 2 times as
4286 // long as the underlying iterator.
4287 (low, high.and_then(|n| n.checked_mul(2)))
4291 #[stable(feature = "fused", since = "1.26.0")]
4292 impl FusedIterator for EncodeUtf16<'_> {}
4294 /// The return type of [`str::escape_debug`].
4296 /// [`str::escape_debug`]: ../../std/primitive.str.html#method.escape_debug
4297 #[stable(feature = "str_escape", since = "1.34.0")]
4298 #[derive(Clone, Debug)]
4299 pub struct EscapeDebug<'a> {
4301 Flatten<option::IntoIter<char::EscapeDebug>>,
4302 FlatMap<Chars<'a>, char::EscapeDebug, CharEscapeDebugContinue>
4306 /// The return type of [`str::escape_default`].
4308 /// [`str::escape_default`]: ../../std/primitive.str.html#method.escape_default
4309 #[stable(feature = "str_escape", since = "1.34.0")]
4310 #[derive(Clone, Debug)]
4311 pub struct EscapeDefault<'a> {
4312 inner: FlatMap<Chars<'a>, char::EscapeDefault, CharEscapeDefault>,
4315 /// The return type of [`str::escape_unicode`].
4317 /// [`str::escape_unicode`]: ../../std/primitive.str.html#method.escape_unicode
4318 #[stable(feature = "str_escape", since = "1.34.0")]
4319 #[derive(Clone, Debug)]
4320 pub struct EscapeUnicode<'a> {
4321 inner: FlatMap<Chars<'a>, char::EscapeUnicode, CharEscapeUnicode>,
4324 macro_rules! escape_types_impls {
4325 ($( $Name: ident ),+) => {$(
4326 #[stable(feature = "str_escape", since = "1.34.0")]
4327 impl<'a> fmt::Display for $Name<'a> {
4328 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4329 self.clone().try_for_each(|c| f.write_char(c))
4333 #[stable(feature = "str_escape", since = "1.34.0")]
4334 impl<'a> Iterator for $Name<'a> {
4338 fn next(&mut self) -> Option<char> { self.inner.next() }
4341 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
4344 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
4345 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
4347 self.inner.try_fold(init, fold)
4351 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
4352 where Fold: FnMut(Acc, Self::Item) -> Acc,
4354 self.inner.fold(init, fold)
4358 #[stable(feature = "str_escape", since = "1.34.0")]
4359 impl<'a> FusedIterator for $Name<'a> {}
4363 escape_types_impls!(EscapeDebug, EscapeDefault, EscapeUnicode);