1 // ignore-tidy-filelength
3 //! String manipulation.
5 //! For more details, see the `std::str` module.
7 #![stable(feature = "rust1", since = "1.0.0")]
9 use self::pattern::Pattern;
10 use self::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
13 use crate::fmt::{self, Write};
14 use crate::iter::{Map, Cloned, FusedIterator, TrustedLen, TrustedRandomAccess, Filter};
15 use crate::iter::{Flatten, FlatMap, Chain};
16 use crate::slice::{self, SliceIndex, Split as SliceSplit};
23 #[unstable(feature = "str_internals", issue = "0")]
24 #[allow(missing_docs)]
27 /// Parse a value from a string
29 /// `FromStr`'s [`from_str`] method is often used implicitly, through
30 /// [`str`]'s [`parse`] method. See [`parse`]'s documentation for examples.
32 /// [`from_str`]: #tymethod.from_str
33 /// [`str`]: ../../std/primitive.str.html
34 /// [`parse`]: ../../std/primitive.str.html#method.parse
36 /// `FromStr` does not have a lifetime parameter, and so you can only parse types
37 /// that do not contain a lifetime parameter themselves. In other words, you can
38 /// parse an `i32` with `FromStr`, but not a `&i32`. You can parse a struct that
39 /// contains an `i32`, but not one that contains an `&i32`.
43 /// Basic implementation of `FromStr` on an example `Point` type:
46 /// use std::str::FromStr;
47 /// use std::num::ParseIntError;
49 /// #[derive(Debug, PartialEq)]
55 /// impl FromStr for Point {
56 /// type Err = ParseIntError;
58 /// fn from_str(s: &str) -> Result<Self, Self::Err> {
59 /// let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
63 /// let x_fromstr = coords[0].parse::<i32>()?;
64 /// let y_fromstr = coords[1].parse::<i32>()?;
66 /// Ok(Point { x: x_fromstr, y: y_fromstr })
70 /// let p = Point::from_str("(1,2)");
71 /// assert_eq!(p.unwrap(), Point{ x: 1, y: 2} )
73 #[stable(feature = "rust1", since = "1.0.0")]
74 pub trait FromStr: Sized {
75 /// The associated error which can be returned from parsing.
76 #[stable(feature = "rust1", since = "1.0.0")]
79 /// Parses a string `s` to return a value of this type.
81 /// If parsing succeeds, return the value inside [`Ok`], otherwise
82 /// when the string is ill-formatted return an error specific to the
83 /// inside [`Err`]. The error type is specific to implementation of the trait.
85 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
86 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
90 /// Basic usage with [`i32`][ithirtytwo], a type that implements `FromStr`:
92 /// [ithirtytwo]: ../../std/primitive.i32.html
95 /// use std::str::FromStr;
98 /// let x = i32::from_str(s).unwrap();
100 /// assert_eq!(5, x);
102 #[stable(feature = "rust1", since = "1.0.0")]
103 fn from_str(s: &str) -> Result<Self, Self::Err>;
106 #[stable(feature = "rust1", since = "1.0.0")]
107 impl FromStr for bool {
108 type Err = ParseBoolError;
110 /// Parse a `bool` from a string.
112 /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
113 /// actually be parseable.
118 /// use std::str::FromStr;
120 /// assert_eq!(FromStr::from_str("true"), Ok(true));
121 /// assert_eq!(FromStr::from_str("false"), Ok(false));
122 /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
125 /// Note, in many cases, the `.parse()` method on `str` is more proper.
128 /// assert_eq!("true".parse(), Ok(true));
129 /// assert_eq!("false".parse(), Ok(false));
130 /// assert!("not even a boolean".parse::<bool>().is_err());
133 fn from_str(s: &str) -> Result<bool, ParseBoolError> {
136 "false" => Ok(false),
137 _ => Err(ParseBoolError { _priv: () }),
142 /// An error returned when parsing a `bool` using [`from_str`] fails
144 /// [`from_str`]: ../../std/primitive.bool.html#method.from_str
145 #[derive(Debug, Clone, PartialEq, Eq)]
146 #[stable(feature = "rust1", since = "1.0.0")]
147 pub struct ParseBoolError { _priv: () }
149 #[stable(feature = "rust1", since = "1.0.0")]
150 impl fmt::Display for ParseBoolError {
151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152 "provided string was not `true` or `false`".fmt(f)
157 Section: Creating a string
160 /// Errors which can occur when attempting to interpret a sequence of [`u8`]
163 /// [`u8`]: ../../std/primitive.u8.html
165 /// As such, the `from_utf8` family of functions and methods for both [`String`]s
166 /// and [`&str`]s make use of this error, for example.
168 /// [`String`]: ../../std/string/struct.String.html#method.from_utf8
169 /// [`&str`]: ../../std/str/fn.from_utf8.html
173 /// This error type’s methods can be used to create functionality
174 /// similar to `String::from_utf8_lossy` without allocating heap memory:
177 /// fn from_utf8_lossy<F>(mut input: &[u8], mut push: F) where F: FnMut(&str) {
179 /// match ::std::str::from_utf8(input) {
185 /// let (valid, after_valid) = input.split_at(error.valid_up_to());
187 /// push(::std::str::from_utf8_unchecked(valid))
189 /// push("\u{FFFD}");
191 /// if let Some(invalid_sequence_length) = error.error_len() {
192 /// input = &after_valid[invalid_sequence_length..]
201 #[derive(Copy, Eq, PartialEq, Clone, Debug)]
202 #[stable(feature = "rust1", since = "1.0.0")]
203 pub struct Utf8Error {
205 error_len: Option<u8>,
209 /// Returns the index in the given string up to which valid UTF-8 was
212 /// It is the maximum index such that `from_utf8(&input[..index])`
213 /// would return `Ok(_)`.
222 /// // some invalid bytes, in a vector
223 /// let sparkle_heart = vec![0, 159, 146, 150];
225 /// // std::str::from_utf8 returns a Utf8Error
226 /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
228 /// // the second byte is invalid here
229 /// assert_eq!(1, error.valid_up_to());
231 #[stable(feature = "utf8_error", since = "1.5.0")]
232 pub fn valid_up_to(&self) -> usize { self.valid_up_to }
234 /// Provides more information about the failure:
236 /// * `None`: the end of the input was reached unexpectedly.
237 /// `self.valid_up_to()` is 1 to 3 bytes from the end of the input.
238 /// If a byte stream (such as a file or a network socket) is being decoded incrementally,
239 /// this could be a valid `char` whose UTF-8 byte sequence is spanning multiple chunks.
241 /// * `Some(len)`: an unexpected byte was encountered.
242 /// The length provided is that of the invalid byte sequence
243 /// that starts at the index given by `valid_up_to()`.
244 /// Decoding should resume after that sequence
245 /// (after inserting a [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD]) in case of
248 /// [U+FFFD]: ../../std/char/constant.REPLACEMENT_CHARACTER.html
249 #[stable(feature = "utf8_error_error_len", since = "1.20.0")]
250 pub fn error_len(&self) -> Option<usize> {
251 self.error_len.map(|len| len as usize)
255 /// Converts a slice of bytes to a string slice.
257 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
258 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
259 /// the two. Not all byte slices are valid string slices, however: [`&str`] requires
260 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
261 /// UTF-8, and then does the conversion.
263 /// [`&str`]: ../../std/primitive.str.html
264 /// [`u8`]: ../../std/primitive.u8.html
265 /// [byteslice]: ../../std/primitive.slice.html
267 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
268 /// incur the overhead of the validity check, there is an unsafe version of
269 /// this function, [`from_utf8_unchecked`][fromutf8u], which has the same
270 /// behavior but skips the check.
272 /// [fromutf8u]: fn.from_utf8_unchecked.html
274 /// If you need a `String` instead of a `&str`, consider
275 /// [`String::from_utf8`][string].
277 /// [string]: ../../std/string/struct.String.html#method.from_utf8
279 /// Because you can stack-allocate a `[u8; N]`, and you can take a
280 /// [`&[u8]`][byteslice] of it, this function is one way to have a
281 /// stack-allocated string. There is an example of this in the
282 /// examples section below.
284 /// [byteslice]: ../../std/primitive.slice.html
288 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
289 /// provided slice is not UTF-8.
298 /// // some bytes, in a vector
299 /// let sparkle_heart = vec![240, 159, 146, 150];
301 /// // We know these bytes are valid, so just use `unwrap()`.
302 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
304 /// assert_eq!("💖", sparkle_heart);
312 /// // some invalid bytes, in a vector
313 /// let sparkle_heart = vec![0, 159, 146, 150];
315 /// assert!(str::from_utf8(&sparkle_heart).is_err());
318 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
319 /// errors that can be returned.
321 /// [error]: struct.Utf8Error.html
323 /// A "stack allocated string":
328 /// // some bytes, in a stack-allocated array
329 /// let sparkle_heart = [240, 159, 146, 150];
331 /// // We know these bytes are valid, so just use `unwrap()`.
332 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
334 /// assert_eq!("💖", sparkle_heart);
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
338 run_utf8_validation(v)?;
339 Ok(unsafe { from_utf8_unchecked(v) })
342 /// Converts a mutable slice of bytes to a mutable string slice.
351 /// // "Hello, Rust!" as a mutable vector
352 /// let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
354 /// // As we know these bytes are valid, we can use `unwrap()`
355 /// let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
357 /// assert_eq!("Hello, Rust!", outstr);
365 /// // Some invalid bytes in a mutable vector
366 /// let mut invalid = vec![128, 223];
368 /// assert!(str::from_utf8_mut(&mut invalid).is_err());
370 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
371 /// errors that can be returned.
373 /// [error]: struct.Utf8Error.html
374 #[stable(feature = "str_mut_extras", since = "1.20.0")]
375 pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
376 run_utf8_validation(v)?;
377 Ok(unsafe { from_utf8_unchecked_mut(v) })
380 /// Converts a slice of bytes to a string slice without checking
381 /// that the string contains valid UTF-8.
383 /// See the safe version, [`from_utf8`][fromutf8], for more information.
385 /// [fromutf8]: fn.from_utf8.html
389 /// This function is unsafe because it does not check that the bytes passed to
390 /// it are valid UTF-8. If this constraint is violated, undefined behavior
391 /// results, as the rest of Rust assumes that [`&str`]s are valid UTF-8.
393 /// [`&str`]: ../../std/primitive.str.html
402 /// // some bytes, in a vector
403 /// let sparkle_heart = vec![240, 159, 146, 150];
405 /// let sparkle_heart = unsafe {
406 /// str::from_utf8_unchecked(&sparkle_heart)
409 /// assert_eq!("💖", sparkle_heart);
412 #[stable(feature = "rust1", since = "1.0.0")]
413 pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
414 &*(v as *const [u8] as *const str)
417 /// Converts a slice of bytes to a string slice without checking
418 /// that the string contains valid UTF-8; mutable version.
420 /// See the immutable version, [`from_utf8_unchecked()`][fromutf8], for more information.
422 /// [fromutf8]: fn.from_utf8_unchecked.html
431 /// let mut heart = vec![240, 159, 146, 150];
432 /// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
434 /// assert_eq!("💖", heart);
437 #[stable(feature = "str_mut_extras", since = "1.20.0")]
438 pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
439 &mut *(v as *mut [u8] as *mut str)
442 #[stable(feature = "rust1", since = "1.0.0")]
443 impl fmt::Display for Utf8Error {
444 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445 if let Some(error_len) = self.error_len {
446 write!(f, "invalid utf-8 sequence of {} bytes from index {}",
447 error_len, self.valid_up_to)
449 write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to)
458 /// An iterator over the [`char`]s of a string slice.
460 /// [`char`]: ../../std/primitive.char.html
462 /// This struct is created by the [`chars`] method on [`str`].
463 /// See its documentation for more.
465 /// [`chars`]: ../../std/primitive.str.html#method.chars
466 /// [`str`]: ../../std/primitive.str.html
467 #[derive(Clone, Debug)]
468 #[stable(feature = "rust1", since = "1.0.0")]
469 pub struct Chars<'a> {
470 iter: slice::Iter<'a, u8>
473 /// Returns the initial codepoint accumulator for the first byte.
474 /// The first byte is special, only want bottom 5 bits for width 2, 4 bits
475 /// for width 3, and 3 bits for width 4.
477 fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
479 /// Returns the value of `ch` updated with continuation byte `byte`.
481 fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
483 /// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the
486 fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
489 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
496 /// Reads the next code point out of a byte iterator (assuming a
497 /// UTF-8-like encoding).
498 #[unstable(feature = "str_internals", issue = "0")]
500 pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
502 let x = *bytes.next()?;
504 return Some(x as u32)
507 // Multibyte case follows
508 // Decode from a byte combination out of: [[[x y] z] w]
509 // NOTE: Performance is sensitive to the exact formulation here
510 let init = utf8_first_byte(x, 2);
511 let y = unwrap_or_0(bytes.next());
512 let mut ch = utf8_acc_cont_byte(init, y);
515 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
516 let z = unwrap_or_0(bytes.next());
517 let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
518 ch = init << 12 | y_z;
521 // use only the lower 3 bits of `init`
522 let w = unwrap_or_0(bytes.next());
523 ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
530 /// Reads the last code point out of a byte iterator (assuming a
531 /// UTF-8-like encoding).
533 fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
534 where I: DoubleEndedIterator<Item = &'a u8>,
537 let w = match *bytes.next_back()? {
538 next_byte if next_byte < 128 => return Some(next_byte as u32),
539 back_byte => back_byte,
542 // Multibyte case follows
543 // Decode from a byte combination out of: [x [y [z w]]]
545 let z = unwrap_or_0(bytes.next_back());
546 ch = utf8_first_byte(z, 2);
547 if utf8_is_cont_byte(z) {
548 let y = unwrap_or_0(bytes.next_back());
549 ch = utf8_first_byte(y, 3);
550 if utf8_is_cont_byte(y) {
551 let x = unwrap_or_0(bytes.next_back());
552 ch = utf8_first_byte(x, 4);
553 ch = utf8_acc_cont_byte(ch, y);
555 ch = utf8_acc_cont_byte(ch, z);
557 ch = utf8_acc_cont_byte(ch, w);
562 #[stable(feature = "rust1", since = "1.0.0")]
563 impl<'a> Iterator for Chars<'a> {
567 fn next(&mut self) -> Option<char> {
568 next_code_point(&mut self.iter).map(|ch| {
569 // str invariant says `ch` is a valid Unicode Scalar Value
571 char::from_u32_unchecked(ch)
577 fn count(self) -> usize {
578 // length in `char` is equal to the number of non-continuation bytes
579 let bytes_len = self.iter.len();
580 let mut cont_bytes = 0;
581 for &byte in self.iter {
582 cont_bytes += utf8_is_cont_byte(byte) as usize;
584 bytes_len - cont_bytes
588 fn size_hint(&self) -> (usize, Option<usize>) {
589 let len = self.iter.len();
590 // `(len + 3)` can't overflow, because we know that the `slice::Iter`
591 // belongs to a slice in memory which has a maximum length of
592 // `isize::MAX` (that's well below `usize::MAX`).
593 ((len + 3) / 4, Some(len))
597 fn last(mut self) -> Option<char> {
598 // No need to go through the entire string.
603 #[stable(feature = "rust1", since = "1.0.0")]
604 impl<'a> DoubleEndedIterator for Chars<'a> {
606 fn next_back(&mut self) -> Option<char> {
607 next_code_point_reverse(&mut self.iter).map(|ch| {
608 // str invariant says `ch` is a valid Unicode Scalar Value
610 char::from_u32_unchecked(ch)
616 #[stable(feature = "fused", since = "1.26.0")]
617 impl FusedIterator for Chars<'_> {}
620 /// Views the underlying data as a subslice of the original data.
622 /// This has the same lifetime as the original slice, and so the
623 /// iterator can continue to be used while this exists.
628 /// let mut chars = "abc".chars();
630 /// assert_eq!(chars.as_str(), "abc");
632 /// assert_eq!(chars.as_str(), "bc");
635 /// assert_eq!(chars.as_str(), "");
637 #[stable(feature = "iter_to_slice", since = "1.4.0")]
639 pub fn as_str(&self) -> &'a str {
640 unsafe { from_utf8_unchecked(self.iter.as_slice()) }
644 /// An iterator over the [`char`]s of a string slice, and their positions.
646 /// [`char`]: ../../std/primitive.char.html
648 /// This struct is created by the [`char_indices`] method on [`str`].
649 /// See its documentation for more.
651 /// [`char_indices`]: ../../std/primitive.str.html#method.char_indices
652 /// [`str`]: ../../std/primitive.str.html
653 #[derive(Clone, Debug)]
654 #[stable(feature = "rust1", since = "1.0.0")]
655 pub struct CharIndices<'a> {
660 #[stable(feature = "rust1", since = "1.0.0")]
661 impl<'a> Iterator for CharIndices<'a> {
662 type Item = (usize, char);
665 fn next(&mut self) -> Option<(usize, char)> {
666 let pre_len = self.iter.iter.len();
667 match self.iter.next() {
670 let index = self.front_offset;
671 let len = self.iter.iter.len();
672 self.front_offset += pre_len - len;
679 fn count(self) -> usize {
684 fn size_hint(&self) -> (usize, Option<usize>) {
685 self.iter.size_hint()
689 fn last(mut self) -> Option<(usize, char)> {
690 // No need to go through the entire string.
695 #[stable(feature = "rust1", since = "1.0.0")]
696 impl<'a> DoubleEndedIterator for CharIndices<'a> {
698 fn next_back(&mut self) -> Option<(usize, char)> {
699 self.iter.next_back().map(|ch| {
700 let index = self.front_offset + self.iter.iter.len();
706 #[stable(feature = "fused", since = "1.26.0")]
707 impl FusedIterator for CharIndices<'_> {}
709 impl<'a> CharIndices<'a> {
710 /// Views the underlying data as a subslice of the original data.
712 /// This has the same lifetime as the original slice, and so the
713 /// iterator can continue to be used while this exists.
714 #[stable(feature = "iter_to_slice", since = "1.4.0")]
716 pub fn as_str(&self) -> &'a str {
721 /// An iterator over the bytes of a string slice.
723 /// This struct is created by the [`bytes`] method on [`str`].
724 /// See its documentation for more.
726 /// [`bytes`]: ../../std/primitive.str.html#method.bytes
727 /// [`str`]: ../../std/primitive.str.html
728 #[stable(feature = "rust1", since = "1.0.0")]
729 #[derive(Clone, Debug)]
730 pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>);
732 #[stable(feature = "rust1", since = "1.0.0")]
733 impl Iterator for Bytes<'_> {
737 fn next(&mut self) -> Option<u8> {
742 fn size_hint(&self) -> (usize, Option<usize>) {
747 fn count(self) -> usize {
752 fn last(self) -> Option<Self::Item> {
757 fn nth(&mut self, n: usize) -> Option<Self::Item> {
762 fn all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
767 fn any<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
772 fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where
773 P: FnMut(&Self::Item) -> bool
775 self.0.find(predicate)
779 fn position<P>(&mut self, predicate: P) -> Option<usize> where
780 P: FnMut(Self::Item) -> bool
782 self.0.position(predicate)
786 fn rposition<P>(&mut self, predicate: P) -> Option<usize> where
787 P: FnMut(Self::Item) -> bool
789 self.0.rposition(predicate)
793 #[stable(feature = "rust1", since = "1.0.0")]
794 impl DoubleEndedIterator for Bytes<'_> {
796 fn next_back(&mut self) -> Option<u8> {
801 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
806 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> where
807 P: FnMut(&Self::Item) -> bool
809 self.0.rfind(predicate)
813 #[stable(feature = "rust1", since = "1.0.0")]
814 impl ExactSizeIterator for Bytes<'_> {
816 fn len(&self) -> usize {
821 fn is_empty(&self) -> bool {
826 #[stable(feature = "fused", since = "1.26.0")]
827 impl FusedIterator for Bytes<'_> {}
829 #[unstable(feature = "trusted_len", issue = "37572")]
830 unsafe impl TrustedLen for Bytes<'_> {}
833 unsafe impl TrustedRandomAccess for Bytes<'_> {
834 unsafe fn get_unchecked(&mut self, i: usize) -> u8 {
835 self.0.get_unchecked(i)
837 fn may_have_side_effect() -> bool { false }
840 /// This macro generates a Clone impl for string pattern API
841 /// wrapper types of the form X<'a, P>
842 macro_rules! derive_pattern_clone {
843 (clone $t:ident with |$s:ident| $e:expr) => {
844 impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
845 where P::Searcher: Clone
847 fn clone(&self) -> Self {
855 /// This macro generates two public iterator structs
856 /// wrapping a private internal one that makes use of the `Pattern` API.
858 /// For all patterns `P: Pattern<'a>` the following items will be
859 /// generated (generics omitted):
861 /// struct $forward_iterator($internal_iterator);
862 /// struct $reverse_iterator($internal_iterator);
864 /// impl Iterator for $forward_iterator
865 /// { /* internal ends up calling Searcher::next_match() */ }
867 /// impl DoubleEndedIterator for $forward_iterator
868 /// where P::Searcher: DoubleEndedSearcher
869 /// { /* internal ends up calling Searcher::next_match_back() */ }
871 /// impl Iterator for $reverse_iterator
872 /// where P::Searcher: ReverseSearcher
873 /// { /* internal ends up calling Searcher::next_match_back() */ }
875 /// impl DoubleEndedIterator for $reverse_iterator
876 /// where P::Searcher: DoubleEndedSearcher
877 /// { /* internal ends up calling Searcher::next_match() */ }
879 /// The internal one is defined outside the macro, and has almost the same
880 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
881 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
883 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
884 /// `Pattern` might not return the same elements, so actually implementing
885 /// `DoubleEndedIterator` for it would be incorrect.
886 /// (See the docs in `str::pattern` for more details)
888 /// However, the internal struct still represents a single ended iterator from
889 /// either end, and depending on pattern is also a valid double ended iterator,
890 /// so the two wrapper structs implement `Iterator`
891 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
892 /// to the complex impls seen above.
893 macro_rules! generate_pattern_iterators {
897 $(#[$forward_iterator_attribute:meta])*
898 struct $forward_iterator:ident;
902 $(#[$reverse_iterator_attribute:meta])*
903 struct $reverse_iterator:ident;
905 // Stability of all generated items
907 $(#[$common_stability_attribute:meta])*
909 // Internal almost-iterator that is being delegated to
911 $internal_iterator:ident yielding ($iterty:ty);
913 // Kind of delegation - either single ended or double ended
916 $(#[$forward_iterator_attribute])*
917 $(#[$common_stability_attribute])*
918 pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
920 $(#[$common_stability_attribute])*
921 impl<'a, P: Pattern<'a>> fmt::Debug for $forward_iterator<'a, P>
922 where P::Searcher: fmt::Debug
924 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
925 f.debug_tuple(stringify!($forward_iterator))
931 $(#[$common_stability_attribute])*
932 impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
936 fn next(&mut self) -> Option<$iterty> {
941 $(#[$common_stability_attribute])*
942 impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
943 where P::Searcher: Clone
945 fn clone(&self) -> Self {
946 $forward_iterator(self.0.clone())
950 $(#[$reverse_iterator_attribute])*
951 $(#[$common_stability_attribute])*
952 pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
954 $(#[$common_stability_attribute])*
955 impl<'a, P: Pattern<'a>> fmt::Debug for $reverse_iterator<'a, P>
956 where P::Searcher: fmt::Debug
958 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
959 f.debug_tuple(stringify!($reverse_iterator))
965 $(#[$common_stability_attribute])*
966 impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
967 where P::Searcher: ReverseSearcher<'a>
972 fn next(&mut self) -> Option<$iterty> {
977 $(#[$common_stability_attribute])*
978 impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
979 where P::Searcher: Clone
981 fn clone(&self) -> Self {
982 $reverse_iterator(self.0.clone())
986 #[stable(feature = "fused", since = "1.26.0")]
987 impl<'a, P: Pattern<'a>> FusedIterator for $forward_iterator<'a, P> {}
989 #[stable(feature = "fused", since = "1.26.0")]
990 impl<'a, P: Pattern<'a>> FusedIterator for $reverse_iterator<'a, P>
991 where P::Searcher: ReverseSearcher<'a> {}
993 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
995 $reverse_iterator, $iterty);
998 double ended; with $(#[$common_stability_attribute:meta])*,
999 $forward_iterator:ident,
1000 $reverse_iterator:ident, $iterty:ty
1002 $(#[$common_stability_attribute])*
1003 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
1004 where P::Searcher: DoubleEndedSearcher<'a>
1007 fn next_back(&mut self) -> Option<$iterty> {
1012 $(#[$common_stability_attribute])*
1013 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
1014 where P::Searcher: DoubleEndedSearcher<'a>
1017 fn next_back(&mut self) -> Option<$iterty> {
1023 single ended; with $(#[$common_stability_attribute:meta])*,
1024 $forward_iterator:ident,
1025 $reverse_iterator:ident, $iterty:ty
1029 derive_pattern_clone!{
1031 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
1034 struct SplitInternal<'a, P: Pattern<'a>> {
1037 matcher: P::Searcher,
1038 allow_trailing_empty: bool,
1042 impl<'a, P: Pattern<'a>> fmt::Debug for SplitInternal<'a, P> where P::Searcher: fmt::Debug {
1043 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1044 f.debug_struct("SplitInternal")
1045 .field("start", &self.start)
1046 .field("end", &self.end)
1047 .field("matcher", &self.matcher)
1048 .field("allow_trailing_empty", &self.allow_trailing_empty)
1049 .field("finished", &self.finished)
1054 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
1056 fn get_end(&mut self) -> Option<&'a str> {
1057 if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
1058 self.finished = true;
1060 let string = self.matcher.haystack().get_unchecked(self.start..self.end);
1069 fn next(&mut self) -> Option<&'a str> {
1070 if self.finished { return None }
1072 let haystack = self.matcher.haystack();
1073 match self.matcher.next_match() {
1074 Some((a, b)) => unsafe {
1075 let elt = haystack.get_unchecked(self.start..a);
1079 None => self.get_end(),
1084 fn next_back(&mut self) -> Option<&'a str>
1085 where P::Searcher: ReverseSearcher<'a>
1087 if self.finished { return None }
1089 if !self.allow_trailing_empty {
1090 self.allow_trailing_empty = true;
1091 match self.next_back() {
1092 Some(elt) if !elt.is_empty() => return Some(elt),
1093 _ => if self.finished { return None }
1097 let haystack = self.matcher.haystack();
1098 match self.matcher.next_match_back() {
1099 Some((a, b)) => unsafe {
1100 let elt = haystack.get_unchecked(b..self.end);
1105 self.finished = true;
1106 Some(haystack.get_unchecked(self.start..self.end))
1112 generate_pattern_iterators! {
1114 /// Created with the method [`split`].
1116 /// [`split`]: ../../std/primitive.str.html#method.split
1119 /// Created with the method [`rsplit`].
1121 /// [`rsplit`]: ../../std/primitive.str.html#method.rsplit
1124 #[stable(feature = "rust1", since = "1.0.0")]
1126 SplitInternal yielding (&'a str);
1127 delegate double ended;
1130 generate_pattern_iterators! {
1132 /// Created with the method [`split_terminator`].
1134 /// [`split_terminator`]: ../../std/primitive.str.html#method.split_terminator
1135 struct SplitTerminator;
1137 /// Created with the method [`rsplit_terminator`].
1139 /// [`rsplit_terminator`]: ../../std/primitive.str.html#method.rsplit_terminator
1140 struct RSplitTerminator;
1142 #[stable(feature = "rust1", since = "1.0.0")]
1144 SplitInternal yielding (&'a str);
1145 delegate double ended;
1148 derive_pattern_clone!{
1149 clone SplitNInternal
1150 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
1153 struct SplitNInternal<'a, P: Pattern<'a>> {
1154 iter: SplitInternal<'a, P>,
1155 /// The number of splits remaining
1159 impl<'a, P: Pattern<'a>> fmt::Debug for SplitNInternal<'a, P> where P::Searcher: fmt::Debug {
1160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1161 f.debug_struct("SplitNInternal")
1162 .field("iter", &self.iter)
1163 .field("count", &self.count)
1168 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
1170 fn next(&mut self) -> Option<&'a str> {
1173 1 => { self.count = 0; self.iter.get_end() }
1174 _ => { self.count -= 1; self.iter.next() }
1179 fn next_back(&mut self) -> Option<&'a str>
1180 where P::Searcher: ReverseSearcher<'a>
1184 1 => { self.count = 0; self.iter.get_end() }
1185 _ => { self.count -= 1; self.iter.next_back() }
1190 generate_pattern_iterators! {
1192 /// Created with the method [`splitn`].
1194 /// [`splitn`]: ../../std/primitive.str.html#method.splitn
1197 /// Created with the method [`rsplitn`].
1199 /// [`rsplitn`]: ../../std/primitive.str.html#method.rsplitn
1202 #[stable(feature = "rust1", since = "1.0.0")]
1204 SplitNInternal yielding (&'a str);
1205 delegate single ended;
1208 derive_pattern_clone!{
1209 clone MatchIndicesInternal
1210 with |s| MatchIndicesInternal(s.0.clone())
1213 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
1215 impl<'a, P: Pattern<'a>> fmt::Debug for MatchIndicesInternal<'a, P> where P::Searcher: fmt::Debug {
1216 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1217 f.debug_tuple("MatchIndicesInternal")
1223 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
1225 fn next(&mut self) -> Option<(usize, &'a str)> {
1226 self.0.next_match().map(|(start, end)| unsafe {
1227 (start, self.0.haystack().get_unchecked(start..end))
1232 fn next_back(&mut self) -> Option<(usize, &'a str)>
1233 where P::Searcher: ReverseSearcher<'a>
1235 self.0.next_match_back().map(|(start, end)| unsafe {
1236 (start, self.0.haystack().get_unchecked(start..end))
1241 generate_pattern_iterators! {
1243 /// Created with the method [`match_indices`].
1245 /// [`match_indices`]: ../../std/primitive.str.html#method.match_indices
1246 struct MatchIndices;
1248 /// Created with the method [`rmatch_indices`].
1250 /// [`rmatch_indices`]: ../../std/primitive.str.html#method.rmatch_indices
1251 struct RMatchIndices;
1253 #[stable(feature = "str_match_indices", since = "1.5.0")]
1255 MatchIndicesInternal yielding ((usize, &'a str));
1256 delegate double ended;
1259 derive_pattern_clone!{
1260 clone MatchesInternal
1261 with |s| MatchesInternal(s.0.clone())
1264 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
1266 impl<'a, P: Pattern<'a>> fmt::Debug for MatchesInternal<'a, P> where P::Searcher: fmt::Debug {
1267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1268 f.debug_tuple("MatchesInternal")
1274 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
1276 fn next(&mut self) -> Option<&'a str> {
1277 self.0.next_match().map(|(a, b)| unsafe {
1278 // Indices are known to be on utf8 boundaries
1279 self.0.haystack().get_unchecked(a..b)
1284 fn next_back(&mut self) -> Option<&'a str>
1285 where P::Searcher: ReverseSearcher<'a>
1287 self.0.next_match_back().map(|(a, b)| unsafe {
1288 // Indices are known to be on utf8 boundaries
1289 self.0.haystack().get_unchecked(a..b)
1294 generate_pattern_iterators! {
1296 /// Created with the method [`matches`].
1298 /// [`matches`]: ../../std/primitive.str.html#method.matches
1301 /// Created with the method [`rmatches`].
1303 /// [`rmatches`]: ../../std/primitive.str.html#method.rmatches
1306 #[stable(feature = "str_matches", since = "1.2.0")]
1308 MatchesInternal yielding (&'a str);
1309 delegate double ended;
1312 /// An iterator over the lines of a string, as string slices.
1314 /// This struct is created with the [`lines`] method on [`str`].
1315 /// See its documentation for more.
1317 /// [`lines`]: ../../std/primitive.str.html#method.lines
1318 /// [`str`]: ../../std/primitive.str.html
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 #[derive(Clone, Debug)]
1321 pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>);
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 impl<'a> Iterator for Lines<'a> {
1325 type Item = &'a str;
1328 fn next(&mut self) -> Option<&'a str> {
1333 fn size_hint(&self) -> (usize, Option<usize>) {
1338 fn last(mut self) -> Option<&'a str> {
1343 #[stable(feature = "rust1", since = "1.0.0")]
1344 impl<'a> DoubleEndedIterator for Lines<'a> {
1346 fn next_back(&mut self) -> Option<&'a str> {
1351 #[stable(feature = "fused", since = "1.26.0")]
1352 impl FusedIterator for Lines<'_> {}
1354 /// Created with the method [`lines_any`].
1356 /// [`lines_any`]: ../../std/primitive.str.html#method.lines_any
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 #[rustc_deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")]
1359 #[derive(Clone, Debug)]
1360 #[allow(deprecated)]
1361 pub struct LinesAny<'a>(Lines<'a>);
1364 /// A nameable, cloneable fn type
1366 struct LinesAnyMap impl<'a> Fn = |line: &'a str| -> &'a str {
1368 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 #[allow(deprecated)]
1375 impl<'a> Iterator for LinesAny<'a> {
1376 type Item = &'a str;
1379 fn next(&mut self) -> Option<&'a str> {
1384 fn size_hint(&self) -> (usize, Option<usize>) {
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 #[allow(deprecated)]
1391 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1393 fn next_back(&mut self) -> Option<&'a str> {
1398 #[stable(feature = "fused", since = "1.26.0")]
1399 #[allow(deprecated)]
1400 impl FusedIterator for LinesAny<'_> {}
1403 Section: UTF-8 validation
1406 // use truncation to fit u64 into usize
1407 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
1409 /// Returns `true` if any byte in the word `x` is nonascii (>= 128).
1411 fn contains_nonascii(x: usize) -> bool {
1412 (x & NONASCII_MASK) != 0
1415 /// Walks through `v` checking that it's a valid UTF-8 sequence,
1416 /// returning `Ok(())` in that case, or, if it is invalid, `Err(err)`.
1418 fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
1422 let usize_bytes = mem::size_of::<usize>();
1423 let ascii_block_size = 2 * usize_bytes;
1424 let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
1425 let align = v.as_ptr().align_offset(usize_bytes);
1428 let old_offset = index;
1430 ($error_len: expr) => {
1431 return Err(Utf8Error {
1432 valid_up_to: old_offset,
1433 error_len: $error_len,
1438 macro_rules! next { () => {{
1440 // we needed data, but there was none: error!
1447 let first = v[index];
1449 let w = UTF8_CHAR_WIDTH[first as usize];
1450 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
1451 // first C2 80 last DF BF
1452 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
1453 // first E0 A0 80 last EF BF BF
1454 // excluding surrogates codepoints \u{d800} to \u{dfff}
1455 // ED A0 80 to ED BF BF
1456 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1457 // first F0 90 80 80 last F4 8F BF BF
1459 // Use the UTF-8 syntax from the RFC
1461 // https://tools.ietf.org/html/rfc3629
1463 // UTF8-2 = %xC2-DF UTF8-tail
1464 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1465 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1466 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1467 // %xF4 %x80-8F 2( UTF8-tail )
1469 2 => if next!() & !CONT_MASK != TAG_CONT_U8 {
1473 match (first, next!()) {
1474 (0xE0 , 0xA0 ..= 0xBF) |
1475 (0xE1 ..= 0xEC, 0x80 ..= 0xBF) |
1476 (0xED , 0x80 ..= 0x9F) |
1477 (0xEE ..= 0xEF, 0x80 ..= 0xBF) => {}
1480 if next!() & !CONT_MASK != TAG_CONT_U8 {
1485 match (first, next!()) {
1486 (0xF0 , 0x90 ..= 0xBF) |
1487 (0xF1 ..= 0xF3, 0x80 ..= 0xBF) |
1488 (0xF4 , 0x80 ..= 0x8F) => {}
1491 if next!() & !CONT_MASK != TAG_CONT_U8 {
1494 if next!() & !CONT_MASK != TAG_CONT_U8 {
1502 // Ascii case, try to skip forward quickly.
1503 // When the pointer is aligned, read 2 words of data per iteration
1504 // until we find a word containing a non-ascii byte.
1505 if align != usize::max_value() && align.wrapping_sub(index) % usize_bytes == 0 {
1506 let ptr = v.as_ptr();
1507 while index < blocks_end {
1509 let block = ptr.add(index) as *const usize;
1510 // break if there is a nonascii byte
1511 let zu = contains_nonascii(*block);
1512 let zv = contains_nonascii(*block.offset(1));
1517 index += ascii_block_size;
1519 // step from the point where the wordwise loop stopped
1520 while index < len && v[index] < 128 {
1532 // https://tools.ietf.org/html/rfc3629
1533 static UTF8_CHAR_WIDTH: [u8; 256] = [
1534 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1535 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1536 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1537 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1538 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1539 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1540 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1541 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1542 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1543 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1544 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1545 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1546 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1547 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1548 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1549 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1552 /// Given a first byte, determines how many bytes are in this UTF-8 character.
1553 #[unstable(feature = "str_internals", issue = "0")]
1555 pub fn utf8_char_width(b: u8) -> usize {
1556 UTF8_CHAR_WIDTH[b as usize] as usize
1559 /// Mask of the value bits of a continuation byte.
1560 const CONT_MASK: u8 = 0b0011_1111;
1561 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte.
1562 const TAG_CONT_U8: u8 = 0b1000_0000;
1565 Section: Trait implementations
1569 use crate::cmp::Ordering;
1571 use crate::slice::{self, SliceIndex};
1573 /// Implements ordering of strings.
1575 /// Strings are ordered lexicographically by their byte values. This orders Unicode code
1576 /// points based on their positions in the code charts. This is not necessarily the same as
1577 /// "alphabetical" order, which varies by language and locale. Sorting strings according to
1578 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1580 #[stable(feature = "rust1", since = "1.0.0")]
1583 fn cmp(&self, other: &str) -> Ordering {
1584 self.as_bytes().cmp(other.as_bytes())
1588 #[stable(feature = "rust1", since = "1.0.0")]
1589 impl PartialEq for str {
1591 fn eq(&self, other: &str) -> bool {
1592 self.as_bytes() == other.as_bytes()
1595 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1598 #[stable(feature = "rust1", since = "1.0.0")]
1601 /// Implements comparison operations on strings.
1603 /// Strings are compared lexicographically by their byte values. This compares Unicode code
1604 /// points based on their positions in the code charts. This is not necessarily the same as
1605 /// "alphabetical" order, which varies by language and locale. Comparing strings according to
1606 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1608 #[stable(feature = "rust1", since = "1.0.0")]
1609 impl PartialOrd for str {
1611 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1612 Some(self.cmp(other))
1616 #[stable(feature = "rust1", since = "1.0.0")]
1617 impl<I> ops::Index<I> for str
1621 type Output = I::Output;
1624 fn index(&self, index: I) -> &I::Output {
1629 #[stable(feature = "rust1", since = "1.0.0")]
1630 impl<I> ops::IndexMut<I> for str
1635 fn index_mut(&mut self, index: I) -> &mut I::Output {
1636 index.index_mut(self)
1642 fn str_index_overflow_fail() -> ! {
1643 panic!("attempted to index str up to maximum usize");
1646 /// Implements substring slicing with syntax `&self[..]` or `&mut self[..]`.
1648 /// Returns a slice of the whole string, i.e., returns `&self` or `&mut
1649 /// self`. Equivalent to `&self[0 .. len]` or `&mut self[0 .. len]`. Unlike
1650 /// other indexing operations, this can never panic.
1652 /// This operation is `O(1)`.
1654 /// Prior to 1.20.0, these indexing operations were still supported by
1655 /// direct implementation of `Index` and `IndexMut`.
1657 /// Equivalent to `&self[0 .. len]` or `&mut self[0 .. len]`.
1658 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1659 impl SliceIndex<str> for ops::RangeFull {
1662 fn get(self, slice: &str) -> Option<&Self::Output> {
1666 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1670 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1674 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1678 fn index(self, slice: &str) -> &Self::Output {
1682 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1687 /// Implements substring slicing with syntax `&self[begin .. end]` or `&mut
1688 /// self[begin .. end]`.
1690 /// Returns a slice of the given string from the byte range
1691 /// [`begin`, `end`).
1693 /// This operation is `O(1)`.
1695 /// Prior to 1.20.0, these indexing operations were still supported by
1696 /// direct implementation of `Index` and `IndexMut`.
1700 /// Panics if `begin` or `end` does not point to the starting byte offset of
1701 /// a character (as defined by `is_char_boundary`), if `begin > end`, or if
1707 /// let s = "Löwe 老虎 Léopard";
1708 /// assert_eq!(&s[0 .. 1], "L");
1710 /// assert_eq!(&s[1 .. 9], "öwe 老");
1712 /// // these will panic:
1713 /// // byte 2 lies within `ö`:
1716 /// // byte 8 lies within `老`
1719 /// // byte 100 is outside the string
1720 /// // &s[3 .. 100];
1722 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1723 impl SliceIndex<str> for ops::Range<usize> {
1726 fn get(self, slice: &str) -> Option<&Self::Output> {
1727 if self.start <= self.end &&
1728 slice.is_char_boundary(self.start) &&
1729 slice.is_char_boundary(self.end) {
1730 Some(unsafe { self.get_unchecked(slice) })
1736 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1737 if self.start <= self.end &&
1738 slice.is_char_boundary(self.start) &&
1739 slice.is_char_boundary(self.end) {
1740 Some(unsafe { self.get_unchecked_mut(slice) })
1746 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1747 let ptr = slice.as_ptr().add(self.start);
1748 let len = self.end - self.start;
1749 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1752 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1753 let ptr = slice.as_mut_ptr().add(self.start);
1754 let len = self.end - self.start;
1755 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, len))
1758 fn index(self, slice: &str) -> &Self::Output {
1759 let (start, end) = (self.start, self.end);
1760 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1763 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1764 // is_char_boundary checks that the index is in [0, .len()]
1765 // cannot reuse `get` as above, because of NLL trouble
1766 if self.start <= self.end &&
1767 slice.is_char_boundary(self.start) &&
1768 slice.is_char_boundary(self.end) {
1769 unsafe { self.get_unchecked_mut(slice) }
1771 super::slice_error_fail(slice, self.start, self.end)
1776 /// Implements substring slicing with syntax `&self[.. end]` or `&mut
1779 /// Returns a slice of the given string from the byte range [`0`, `end`).
1780 /// Equivalent to `&self[0 .. end]` or `&mut self[0 .. end]`.
1782 /// This operation is `O(1)`.
1784 /// Prior to 1.20.0, these indexing operations were still supported by
1785 /// direct implementation of `Index` and `IndexMut`.
1789 /// Panics if `end` does not point to the starting byte offset of a
1790 /// character (as defined by `is_char_boundary`), or if `end > len`.
1791 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1792 impl SliceIndex<str> for ops::RangeTo<usize> {
1795 fn get(self, slice: &str) -> Option<&Self::Output> {
1796 if slice.is_char_boundary(self.end) {
1797 Some(unsafe { self.get_unchecked(slice) })
1803 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1804 if slice.is_char_boundary(self.end) {
1805 Some(unsafe { self.get_unchecked_mut(slice) })
1811 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1812 let ptr = slice.as_ptr();
1813 super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end))
1816 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1817 let ptr = slice.as_mut_ptr();
1818 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, self.end))
1821 fn index(self, slice: &str) -> &Self::Output {
1823 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end))
1826 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1827 // is_char_boundary checks that the index is in [0, .len()]
1828 if slice.is_char_boundary(self.end) {
1829 unsafe { self.get_unchecked_mut(slice) }
1831 super::slice_error_fail(slice, 0, self.end)
1836 /// Implements substring slicing with syntax `&self[begin ..]` or `&mut
1837 /// self[begin ..]`.
1839 /// Returns a slice of the given string from the byte range [`begin`,
1840 /// `len`). Equivalent to `&self[begin .. len]` or `&mut self[begin ..
1843 /// This operation is `O(1)`.
1845 /// Prior to 1.20.0, these indexing operations were still supported by
1846 /// direct implementation of `Index` and `IndexMut`.
1850 /// Panics if `begin` does not point to the starting byte offset of
1851 /// a character (as defined by `is_char_boundary`), or if `begin >= len`.
1852 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1853 impl SliceIndex<str> for ops::RangeFrom<usize> {
1856 fn get(self, slice: &str) -> Option<&Self::Output> {
1857 if slice.is_char_boundary(self.start) {
1858 Some(unsafe { self.get_unchecked(slice) })
1864 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1865 if slice.is_char_boundary(self.start) {
1866 Some(unsafe { self.get_unchecked_mut(slice) })
1872 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1873 let ptr = slice.as_ptr().add(self.start);
1874 let len = slice.len() - self.start;
1875 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1878 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1879 let ptr = slice.as_mut_ptr().add(self.start);
1880 let len = slice.len() - self.start;
1881 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, len))
1884 fn index(self, slice: &str) -> &Self::Output {
1885 let (start, end) = (self.start, slice.len());
1886 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1889 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1890 // is_char_boundary checks that the index is in [0, .len()]
1891 if slice.is_char_boundary(self.start) {
1892 unsafe { self.get_unchecked_mut(slice) }
1894 super::slice_error_fail(slice, self.start, slice.len())
1899 /// Implements substring slicing with syntax `&self[begin ..= end]` or `&mut
1900 /// self[begin ..= end]`.
1902 /// Returns a slice of the given string from the byte range
1903 /// [`begin`, `end`]. Equivalent to `&self [begin .. end + 1]` or `&mut
1904 /// self[begin .. end + 1]`, except if `end` has the maximum value for
1907 /// This operation is `O(1)`.
1911 /// Panics if `begin` does not point to the starting byte offset of
1912 /// a character (as defined by `is_char_boundary`), if `end` does not point
1913 /// to the ending byte offset of a character (`end + 1` is either a starting
1914 /// byte offset or equal to `len`), if `begin > end`, or if `end >= len`.
1915 #[stable(feature = "inclusive_range", since = "1.26.0")]
1916 impl SliceIndex<str> for ops::RangeInclusive<usize> {
1919 fn get(self, slice: &str) -> Option<&Self::Output> {
1920 if *self.end() == usize::max_value() { None }
1921 else { (*self.start()..self.end()+1).get(slice) }
1924 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1925 if *self.end() == usize::max_value() { None }
1926 else { (*self.start()..self.end()+1).get_mut(slice) }
1929 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1930 (*self.start()..self.end()+1).get_unchecked(slice)
1933 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1934 (*self.start()..self.end()+1).get_unchecked_mut(slice)
1937 fn index(self, slice: &str) -> &Self::Output {
1938 if *self.end() == usize::max_value() { str_index_overflow_fail(); }
1939 (*self.start()..self.end()+1).index(slice)
1942 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1943 if *self.end() == usize::max_value() { str_index_overflow_fail(); }
1944 (*self.start()..self.end()+1).index_mut(slice)
1948 /// Implements substring slicing with syntax `&self[..= end]` or `&mut
1951 /// Returns a slice of the given string from the byte range [0, `end`].
1952 /// Equivalent to `&self [0 .. end + 1]`, except if `end` has the maximum
1953 /// value for `usize`.
1955 /// This operation is `O(1)`.
1959 /// Panics if `end` does not point to the ending byte offset of a character
1960 /// (`end + 1` is either a starting byte offset as defined by
1961 /// `is_char_boundary`, or equal to `len`), or if `end >= len`.
1962 #[stable(feature = "inclusive_range", since = "1.26.0")]
1963 impl SliceIndex<str> for ops::RangeToInclusive<usize> {
1966 fn get(self, slice: &str) -> Option<&Self::Output> {
1967 if self.end == usize::max_value() { None }
1968 else { (..self.end+1).get(slice) }
1971 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1972 if self.end == usize::max_value() { None }
1973 else { (..self.end+1).get_mut(slice) }
1976 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1977 (..self.end+1).get_unchecked(slice)
1980 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1981 (..self.end+1).get_unchecked_mut(slice)
1984 fn index(self, slice: &str) -> &Self::Output {
1985 if self.end == usize::max_value() { str_index_overflow_fail(); }
1986 (..self.end+1).index(slice)
1989 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1990 if self.end == usize::max_value() { str_index_overflow_fail(); }
1991 (..self.end+1).index_mut(slice)
1996 // truncate `&str` to length at most equal to `max`
1997 // return `true` if it were truncated, and the new str.
1998 fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
2002 while !s.is_char_boundary(max) {
2011 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
2012 const MAX_DISPLAY_LENGTH: usize = 256;
2013 let (truncated, s_trunc) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
2014 let ellipsis = if truncated { "[...]" } else { "" };
2017 if begin > s.len() || end > s.len() {
2018 let oob_index = if begin > s.len() { begin } else { end };
2019 panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
2023 assert!(begin <= end, "begin <= end ({} <= {}) when slicing `{}`{}",
2024 begin, end, s_trunc, ellipsis);
2026 // 3. character boundary
2027 let index = if !s.is_char_boundary(begin) { begin } else { end };
2028 // find the character
2029 let mut char_start = index;
2030 while !s.is_char_boundary(char_start) {
2033 // `char_start` must be less than len and a char boundary
2034 let ch = s[char_start..].chars().next().unwrap();
2035 let char_range = char_start .. char_start + ch.len_utf8();
2036 panic!("byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
2037 index, ch, char_range, s_trunc, ellipsis);
2043 /// Returns the length of `self`.
2045 /// This length is in bytes, not [`char`]s or graphemes. In other words,
2046 /// it may not be what a human considers the length of the string.
2053 /// let len = "foo".len();
2054 /// assert_eq!(3, len);
2056 /// let len = "ƒoo".len(); // fancy f!
2057 /// assert_eq!(4, len);
2059 #[stable(feature = "rust1", since = "1.0.0")]
2061 #[rustc_const_unstable(feature = "const_str_len")]
2062 pub const fn len(&self) -> usize {
2063 self.as_bytes().len()
2066 /// Returns `true` if `self` has a length of zero bytes.
2074 /// assert!(s.is_empty());
2076 /// let s = "not empty";
2077 /// assert!(!s.is_empty());
2080 #[stable(feature = "rust1", since = "1.0.0")]
2081 #[rustc_const_unstable(feature = "const_str_len")]
2082 pub const fn is_empty(&self) -> bool {
2086 /// Checks that `index`-th byte lies at the start and/or end of a
2087 /// UTF-8 code point sequence.
2089 /// The start and end of the string (when `index == self.len()`) are
2090 /// considered to be
2093 /// Returns `false` if `index` is greater than `self.len()`.
2098 /// let s = "Löwe 老虎 Léopard";
2099 /// assert!(s.is_char_boundary(0));
2101 /// assert!(s.is_char_boundary(6));
2102 /// assert!(s.is_char_boundary(s.len()));
2104 /// // second byte of `ö`
2105 /// assert!(!s.is_char_boundary(2));
2107 /// // third byte of `老`
2108 /// assert!(!s.is_char_boundary(8));
2110 #[stable(feature = "is_char_boundary", since = "1.9.0")]
2112 pub fn is_char_boundary(&self, index: usize) -> bool {
2113 // 0 and len are always ok.
2114 // Test for 0 explicitly so that it can optimize out the check
2115 // easily and skip reading string data for that case.
2116 if index == 0 || index == self.len() { return true; }
2117 match self.as_bytes().get(index) {
2119 // This is bit magic equivalent to: b < 128 || b >= 192
2120 Some(&b) => (b as i8) >= -0x40,
2124 /// Converts a string slice to a byte slice. To convert the byte slice back
2125 /// into a string slice, use the [`str::from_utf8`] function.
2127 /// [`str::from_utf8`]: ./str/fn.from_utf8.html
2134 /// let bytes = "bors".as_bytes();
2135 /// assert_eq!(b"bors", bytes);
2137 #[stable(feature = "rust1", since = "1.0.0")]
2139 #[rustc_const_unstable(feature="const_str_as_bytes")]
2140 pub const fn as_bytes(&self) -> &[u8] {
2145 unsafe { Slices { str: self }.slice }
2148 /// Converts a mutable string slice to a mutable byte slice. To convert the
2149 /// mutable byte slice back into a mutable string slice, use the
2150 /// [`str::from_utf8_mut`] function.
2152 /// [`str::from_utf8_mut`]: ./str/fn.from_utf8_mut.html
2159 /// let mut s = String::from("Hello");
2160 /// let bytes = unsafe { s.as_bytes_mut() };
2162 /// assert_eq!(b"Hello", bytes);
2168 /// let mut s = String::from("🗻∈🌏");
2171 /// let bytes = s.as_bytes_mut();
2173 /// bytes[0] = 0xF0;
2174 /// bytes[1] = 0x9F;
2175 /// bytes[2] = 0x8D;
2176 /// bytes[3] = 0x94;
2179 /// assert_eq!("🍔∈🌏", s);
2181 #[stable(feature = "str_mut_extras", since = "1.20.0")]
2183 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
2184 &mut *(self as *mut str as *mut [u8])
2187 /// Converts a string slice to a raw pointer.
2189 /// As string slices are a slice of bytes, the raw pointer points to a
2190 /// [`u8`]. This pointer will be pointing to the first byte of the string
2193 /// The caller must ensure that the returned pointer is never written to.
2194 /// If you need to mutate the contents of the string slice, use [`as_mut_ptr`].
2196 /// [`u8`]: primitive.u8.html
2197 /// [`as_mut_ptr`]: #method.as_mut_ptr
2204 /// let s = "Hello";
2205 /// let ptr = s.as_ptr();
2207 #[stable(feature = "rust1", since = "1.0.0")]
2209 pub const fn as_ptr(&self) -> *const u8 {
2210 self as *const str as *const u8
2213 /// Converts a mutable string slice to a raw pointer.
2215 /// As string slices are a slice of bytes, the raw pointer points to a
2216 /// [`u8`]. This pointer will be pointing to the first byte of the string
2219 /// It is your responsibility to make sure that the string slice only gets
2220 /// modified in a way that it remains valid UTF-8.
2222 /// [`u8`]: primitive.u8.html
2223 #[stable(feature = "str_as_mut_ptr", since = "1.36.0")]
2225 pub fn as_mut_ptr(&mut self) -> *mut u8 {
2226 self as *mut str as *mut u8
2229 /// Returns a subslice of `str`.
2231 /// This is the non-panicking alternative to indexing the `str`. Returns
2232 /// [`None`] whenever equivalent indexing operation would panic.
2234 /// [`None`]: option/enum.Option.html#variant.None
2239 /// let v = String::from("🗻∈🌏");
2241 /// assert_eq!(Some("🗻"), v.get(0..4));
2243 /// // indices not on UTF-8 sequence boundaries
2244 /// assert!(v.get(1..).is_none());
2245 /// assert!(v.get(..8).is_none());
2247 /// // out of bounds
2248 /// assert!(v.get(..42).is_none());
2250 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2252 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
2256 /// Returns a mutable subslice of `str`.
2258 /// This is the non-panicking alternative to indexing the `str`. Returns
2259 /// [`None`] whenever equivalent indexing operation would panic.
2261 /// [`None`]: option/enum.Option.html#variant.None
2266 /// let mut v = String::from("hello");
2267 /// // correct length
2268 /// assert!(v.get_mut(0..5).is_some());
2269 /// // out of bounds
2270 /// assert!(v.get_mut(..42).is_none());
2271 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
2273 /// assert_eq!("hello", v);
2275 /// let s = v.get_mut(0..2);
2276 /// let s = s.map(|s| {
2277 /// s.make_ascii_uppercase();
2280 /// assert_eq!(Some("HE"), s);
2282 /// assert_eq!("HEllo", v);
2284 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2286 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
2290 /// Returns a unchecked subslice of `str`.
2292 /// This is the unchecked alternative to indexing the `str`.
2296 /// Callers of this function are responsible that these preconditions are
2299 /// * The starting index must come before the ending index;
2300 /// * Indexes must be within bounds of the original slice;
2301 /// * Indexes must lie on UTF-8 sequence boundaries.
2303 /// Failing that, the returned string slice may reference invalid memory or
2304 /// violate the invariants communicated by the `str` type.
2311 /// assert_eq!("🗻", v.get_unchecked(0..4));
2312 /// assert_eq!("∈", v.get_unchecked(4..7));
2313 /// assert_eq!("🌏", v.get_unchecked(7..11));
2316 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2318 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
2319 i.get_unchecked(self)
2322 /// Returns a mutable, unchecked subslice of `str`.
2324 /// This is the unchecked alternative to indexing the `str`.
2328 /// Callers of this function are responsible that these preconditions are
2331 /// * The starting index must come before the ending index;
2332 /// * Indexes must be within bounds of the original slice;
2333 /// * Indexes must lie on UTF-8 sequence boundaries.
2335 /// Failing that, the returned string slice may reference invalid memory or
2336 /// violate the invariants communicated by the `str` type.
2341 /// let mut v = String::from("🗻∈🌏");
2343 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
2344 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
2345 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
2348 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2350 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
2351 i.get_unchecked_mut(self)
2354 /// Creates a string slice from another string slice, bypassing safety
2357 /// This is generally not recommended, use with caution! For a safe
2358 /// alternative see [`str`] and [`Index`].
2360 /// [`str`]: primitive.str.html
2361 /// [`Index`]: ops/trait.Index.html
2363 /// This new slice goes from `begin` to `end`, including `begin` but
2364 /// excluding `end`.
2366 /// To get a mutable string slice instead, see the
2367 /// [`slice_mut_unchecked`] method.
2369 /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
2373 /// Callers of this function are responsible that three preconditions are
2376 /// * `begin` must come before `end`.
2377 /// * `begin` and `end` must be byte positions within the string slice.
2378 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2385 /// let s = "Löwe 老虎 Léopard";
2388 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
2391 /// let s = "Hello, world!";
2394 /// assert_eq!("world", s.slice_unchecked(7, 12));
2397 #[stable(feature = "rust1", since = "1.0.0")]
2398 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked(begin..end)` instead")]
2400 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
2401 (begin..end).get_unchecked(self)
2404 /// Creates a string slice from another string slice, bypassing safety
2406 /// This is generally not recommended, use with caution! For a safe
2407 /// alternative see [`str`] and [`IndexMut`].
2409 /// [`str`]: primitive.str.html
2410 /// [`IndexMut`]: ops/trait.IndexMut.html
2412 /// This new slice goes from `begin` to `end`, including `begin` but
2413 /// excluding `end`.
2415 /// To get an immutable string slice instead, see the
2416 /// [`slice_unchecked`] method.
2418 /// [`slice_unchecked`]: #method.slice_unchecked
2422 /// Callers of this function are responsible that three preconditions are
2425 /// * `begin` must come before `end`.
2426 /// * `begin` and `end` must be byte positions within the string slice.
2427 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2428 #[stable(feature = "str_slice_mut", since = "1.5.0")]
2429 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked_mut(begin..end)` instead")]
2431 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
2432 (begin..end).get_unchecked_mut(self)
2435 /// Divide one string slice into two at an index.
2437 /// The argument, `mid`, should be a byte offset from the start of the
2438 /// string. It must also be on the boundary of a UTF-8 code point.
2440 /// The two slices returned go from the start of the string slice to `mid`,
2441 /// and from `mid` to the end of the string slice.
2443 /// To get mutable string slices instead, see the [`split_at_mut`]
2446 /// [`split_at_mut`]: #method.split_at_mut
2450 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2451 /// beyond the last code point of the string slice.
2458 /// let s = "Per Martin-Löf";
2460 /// let (first, last) = s.split_at(3);
2462 /// assert_eq!("Per", first);
2463 /// assert_eq!(" Martin-Löf", last);
2466 #[stable(feature = "str_split_at", since = "1.4.0")]
2467 pub fn split_at(&self, mid: usize) -> (&str, &str) {
2468 // is_char_boundary checks that the index is in [0, .len()]
2469 if self.is_char_boundary(mid) {
2471 (self.get_unchecked(0..mid),
2472 self.get_unchecked(mid..self.len()))
2475 slice_error_fail(self, 0, mid)
2479 /// Divide one mutable string slice into two at an index.
2481 /// The argument, `mid`, should be a byte offset from the start of the
2482 /// string. It must also be on the boundary of a UTF-8 code point.
2484 /// The two slices returned go from the start of the string slice to `mid`,
2485 /// and from `mid` to the end of the string slice.
2487 /// To get immutable string slices instead, see the [`split_at`] method.
2489 /// [`split_at`]: #method.split_at
2493 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2494 /// beyond the last code point of the string slice.
2501 /// let mut s = "Per Martin-Löf".to_string();
2503 /// let (first, last) = s.split_at_mut(3);
2504 /// first.make_ascii_uppercase();
2505 /// assert_eq!("PER", first);
2506 /// assert_eq!(" Martin-Löf", last);
2508 /// assert_eq!("PER Martin-Löf", s);
2511 #[stable(feature = "str_split_at", since = "1.4.0")]
2512 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
2513 // is_char_boundary checks that the index is in [0, .len()]
2514 if self.is_char_boundary(mid) {
2515 let len = self.len();
2516 let ptr = self.as_mut_ptr();
2518 (from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
2519 from_utf8_unchecked_mut(slice::from_raw_parts_mut(
2525 slice_error_fail(self, 0, mid)
2529 /// Returns an iterator over the [`char`]s of a string slice.
2531 /// As a string slice consists of valid UTF-8, we can iterate through a
2532 /// string slice by [`char`]. This method returns such an iterator.
2534 /// It's important to remember that [`char`] represents a Unicode Scalar
2535 /// Value, and may not match your idea of what a 'character' is. Iteration
2536 /// over grapheme clusters may be what you actually want.
2543 /// let word = "goodbye";
2545 /// let count = word.chars().count();
2546 /// assert_eq!(7, count);
2548 /// let mut chars = word.chars();
2550 /// assert_eq!(Some('g'), chars.next());
2551 /// assert_eq!(Some('o'), chars.next());
2552 /// assert_eq!(Some('o'), chars.next());
2553 /// assert_eq!(Some('d'), chars.next());
2554 /// assert_eq!(Some('b'), chars.next());
2555 /// assert_eq!(Some('y'), chars.next());
2556 /// assert_eq!(Some('e'), chars.next());
2558 /// assert_eq!(None, chars.next());
2561 /// Remember, [`char`]s may not match your human intuition about characters:
2566 /// let mut chars = y.chars();
2568 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
2569 /// assert_eq!(Some('\u{0306}'), chars.next());
2571 /// assert_eq!(None, chars.next());
2573 #[stable(feature = "rust1", since = "1.0.0")]
2575 pub fn chars(&self) -> Chars<'_> {
2576 Chars{iter: self.as_bytes().iter()}
2579 /// Returns an iterator over the [`char`]s of a string slice, and their
2582 /// As a string slice consists of valid UTF-8, we can iterate through a
2583 /// string slice by [`char`]. This method returns an iterator of both
2584 /// these [`char`]s, as well as their byte positions.
2586 /// The iterator yields tuples. The position is first, the [`char`] is
2594 /// let word = "goodbye";
2596 /// let count = word.char_indices().count();
2597 /// assert_eq!(7, count);
2599 /// let mut char_indices = word.char_indices();
2601 /// assert_eq!(Some((0, 'g')), char_indices.next());
2602 /// assert_eq!(Some((1, 'o')), char_indices.next());
2603 /// assert_eq!(Some((2, 'o')), char_indices.next());
2604 /// assert_eq!(Some((3, 'd')), char_indices.next());
2605 /// assert_eq!(Some((4, 'b')), char_indices.next());
2606 /// assert_eq!(Some((5, 'y')), char_indices.next());
2607 /// assert_eq!(Some((6, 'e')), char_indices.next());
2609 /// assert_eq!(None, char_indices.next());
2612 /// Remember, [`char`]s may not match your human intuition about characters:
2615 /// let yes = "y̆es";
2617 /// let mut char_indices = yes.char_indices();
2619 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
2620 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
2622 /// // note the 3 here - the last character took up two bytes
2623 /// assert_eq!(Some((3, 'e')), char_indices.next());
2624 /// assert_eq!(Some((4, 's')), char_indices.next());
2626 /// assert_eq!(None, char_indices.next());
2628 #[stable(feature = "rust1", since = "1.0.0")]
2630 pub fn char_indices(&self) -> CharIndices<'_> {
2631 CharIndices { front_offset: 0, iter: self.chars() }
2634 /// An iterator over the bytes of a string slice.
2636 /// As a string slice consists of a sequence of bytes, we can iterate
2637 /// through a string slice by byte. This method returns such an iterator.
2644 /// let mut bytes = "bors".bytes();
2646 /// assert_eq!(Some(b'b'), bytes.next());
2647 /// assert_eq!(Some(b'o'), bytes.next());
2648 /// assert_eq!(Some(b'r'), bytes.next());
2649 /// assert_eq!(Some(b's'), bytes.next());
2651 /// assert_eq!(None, bytes.next());
2653 #[stable(feature = "rust1", since = "1.0.0")]
2655 pub fn bytes(&self) -> Bytes<'_> {
2656 Bytes(self.as_bytes().iter().cloned())
2659 /// Splits a string slice by whitespace.
2661 /// The iterator returned will return string slices that are sub-slices of
2662 /// the original string slice, separated by any amount of whitespace.
2664 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2665 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
2666 /// instead, use [`split_ascii_whitespace`].
2668 /// [`split_ascii_whitespace`]: #method.split_ascii_whitespace
2675 /// let mut iter = "A few words".split_whitespace();
2677 /// assert_eq!(Some("A"), iter.next());
2678 /// assert_eq!(Some("few"), iter.next());
2679 /// assert_eq!(Some("words"), iter.next());
2681 /// assert_eq!(None, iter.next());
2684 /// All kinds of whitespace are considered:
2687 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
2688 /// assert_eq!(Some("Mary"), iter.next());
2689 /// assert_eq!(Some("had"), iter.next());
2690 /// assert_eq!(Some("a"), iter.next());
2691 /// assert_eq!(Some("little"), iter.next());
2692 /// assert_eq!(Some("lamb"), iter.next());
2694 /// assert_eq!(None, iter.next());
2696 #[stable(feature = "split_whitespace", since = "1.1.0")]
2698 pub fn split_whitespace(&self) -> SplitWhitespace<'_> {
2699 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
2702 /// Splits a string slice by ASCII whitespace.
2704 /// The iterator returned will return string slices that are sub-slices of
2705 /// the original string slice, separated by any amount of ASCII whitespace.
2707 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
2709 /// [`split_whitespace`]: #method.split_whitespace
2716 /// let mut iter = "A few words".split_ascii_whitespace();
2718 /// assert_eq!(Some("A"), iter.next());
2719 /// assert_eq!(Some("few"), iter.next());
2720 /// assert_eq!(Some("words"), iter.next());
2722 /// assert_eq!(None, iter.next());
2725 /// All kinds of ASCII whitespace are considered:
2728 /// let mut iter = " Mary had\ta little \n\t lamb".split_ascii_whitespace();
2729 /// assert_eq!(Some("Mary"), iter.next());
2730 /// assert_eq!(Some("had"), iter.next());
2731 /// assert_eq!(Some("a"), iter.next());
2732 /// assert_eq!(Some("little"), iter.next());
2733 /// assert_eq!(Some("lamb"), iter.next());
2735 /// assert_eq!(None, iter.next());
2737 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
2739 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> {
2742 .split(IsAsciiWhitespace)
2743 .filter(BytesIsNotEmpty)
2744 .map(UnsafeBytesToStr);
2745 SplitAsciiWhitespace { inner }
2748 /// An iterator over the lines of a string, as string slices.
2750 /// Lines are ended with either a newline (`\n`) or a carriage return with
2751 /// a line feed (`\r\n`).
2753 /// The final line ending is optional.
2760 /// let text = "foo\r\nbar\n\nbaz\n";
2761 /// let mut lines = text.lines();
2763 /// assert_eq!(Some("foo"), lines.next());
2764 /// assert_eq!(Some("bar"), lines.next());
2765 /// assert_eq!(Some(""), lines.next());
2766 /// assert_eq!(Some("baz"), lines.next());
2768 /// assert_eq!(None, lines.next());
2771 /// The final line ending isn't required:
2774 /// let text = "foo\nbar\n\r\nbaz";
2775 /// let mut lines = text.lines();
2777 /// assert_eq!(Some("foo"), lines.next());
2778 /// assert_eq!(Some("bar"), lines.next());
2779 /// assert_eq!(Some(""), lines.next());
2780 /// assert_eq!(Some("baz"), lines.next());
2782 /// assert_eq!(None, lines.next());
2784 #[stable(feature = "rust1", since = "1.0.0")]
2786 pub fn lines(&self) -> Lines<'_> {
2787 Lines(self.split_terminator('\n').map(LinesAnyMap))
2790 /// An iterator over the lines of a string.
2791 #[stable(feature = "rust1", since = "1.0.0")]
2792 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
2794 #[allow(deprecated)]
2795 pub fn lines_any(&self) -> LinesAny<'_> {
2796 LinesAny(self.lines())
2799 /// Returns an iterator of `u16` over the string encoded as UTF-16.
2806 /// let text = "Zażółć gęślą jaźń";
2808 /// let utf8_len = text.len();
2809 /// let utf16_len = text.encode_utf16().count();
2811 /// assert!(utf16_len <= utf8_len);
2813 #[stable(feature = "encode_utf16", since = "1.8.0")]
2814 pub fn encode_utf16(&self) -> EncodeUtf16<'_> {
2815 EncodeUtf16 { chars: self.chars(), extra: 0 }
2818 /// Returns `true` if the given pattern matches a sub-slice of
2819 /// this string slice.
2821 /// Returns `false` if it does not.
2828 /// let bananas = "bananas";
2830 /// assert!(bananas.contains("nana"));
2831 /// assert!(!bananas.contains("apples"));
2833 #[stable(feature = "rust1", since = "1.0.0")]
2835 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2836 pat.is_contained_in(self)
2839 /// Returns `true` if the given pattern matches a prefix of this
2842 /// Returns `false` if it does not.
2849 /// let bananas = "bananas";
2851 /// assert!(bananas.starts_with("bana"));
2852 /// assert!(!bananas.starts_with("nana"));
2854 #[stable(feature = "rust1", since = "1.0.0")]
2855 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2856 pat.is_prefix_of(self)
2859 /// Returns `true` if the given pattern matches a suffix of this
2862 /// Returns `false` if it does not.
2869 /// let bananas = "bananas";
2871 /// assert!(bananas.ends_with("anas"));
2872 /// assert!(!bananas.ends_with("nana"));
2874 #[stable(feature = "rust1", since = "1.0.0")]
2875 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
2876 where P::Searcher: ReverseSearcher<'a>
2878 pat.is_suffix_of(self)
2881 /// Returns the byte index of the first character of this string slice that
2882 /// matches the pattern.
2884 /// Returns [`None`] if the pattern doesn't match.
2886 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2887 /// a character matches.
2889 /// [`None`]: option/enum.Option.html#variant.None
2893 /// Simple patterns:
2896 /// let s = "Löwe 老虎 Léopard";
2898 /// assert_eq!(s.find('L'), Some(0));
2899 /// assert_eq!(s.find('é'), Some(14));
2900 /// assert_eq!(s.find("Léopard"), Some(13));
2903 /// More complex patterns using point-free style and closures:
2906 /// let s = "Löwe 老虎 Léopard";
2908 /// assert_eq!(s.find(char::is_whitespace), Some(5));
2909 /// assert_eq!(s.find(char::is_lowercase), Some(1));
2910 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
2911 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
2914 /// Not finding the pattern:
2917 /// let s = "Löwe 老虎 Léopard";
2918 /// let x: &[_] = &['1', '2'];
2920 /// assert_eq!(s.find(x), None);
2922 #[stable(feature = "rust1", since = "1.0.0")]
2924 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2925 pat.into_searcher(self).next_match().map(|(i, _)| i)
2928 /// Returns the byte index of the last character of this string slice that
2929 /// matches the pattern.
2931 /// Returns [`None`] if the pattern doesn't match.
2933 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2934 /// a character matches.
2936 /// [`None`]: option/enum.Option.html#variant.None
2940 /// Simple patterns:
2943 /// let s = "Löwe 老虎 Léopard";
2945 /// assert_eq!(s.rfind('L'), Some(13));
2946 /// assert_eq!(s.rfind('é'), Some(14));
2949 /// More complex patterns with closures:
2952 /// let s = "Löwe 老虎 Léopard";
2954 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
2955 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
2958 /// Not finding the pattern:
2961 /// let s = "Löwe 老虎 Léopard";
2962 /// let x: &[_] = &['1', '2'];
2964 /// assert_eq!(s.rfind(x), None);
2966 #[stable(feature = "rust1", since = "1.0.0")]
2968 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
2969 where P::Searcher: ReverseSearcher<'a>
2971 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
2974 /// An iterator over substrings of this string slice, separated by
2975 /// characters matched by a pattern.
2977 /// The pattern can be any type that implements the Pattern trait. Notable
2978 /// examples are `&str`, [`char`], and closures that determines the split.
2980 /// # Iterator behavior
2982 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
2983 /// allows a reverse search and forward/reverse search yields the same
2984 /// elements. This is true for, e.g., [`char`], but not for `&str`.
2986 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
2988 /// If the pattern allows a reverse search but its results might differ
2989 /// from a forward search, the [`rsplit`] method can be used.
2991 /// [`rsplit`]: #method.rsplit
2995 /// Simple patterns:
2998 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
2999 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
3001 /// let v: Vec<&str> = "".split('X').collect();
3002 /// assert_eq!(v, [""]);
3004 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
3005 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
3007 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
3008 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3010 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
3011 /// assert_eq!(v, ["abc", "def", "ghi"]);
3013 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
3014 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3017 /// A more complex pattern, using a closure:
3020 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
3021 /// assert_eq!(v, ["abc", "def", "ghi"]);
3024 /// If a string contains multiple contiguous separators, you will end up
3025 /// with empty strings in the output:
3028 /// let x = "||||a||b|c".to_string();
3029 /// let d: Vec<_> = x.split('|').collect();
3031 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3034 /// Contiguous separators are separated by the empty string.
3037 /// let x = "(///)".to_string();
3038 /// let d: Vec<_> = x.split('/').collect();
3040 /// assert_eq!(d, &["(", "", "", ")"]);
3043 /// Separators at the start or end of a string are neighbored
3044 /// by empty strings.
3047 /// let d: Vec<_> = "010".split("0").collect();
3048 /// assert_eq!(d, &["", "1", ""]);
3051 /// When the empty string is used as a separator, it separates
3052 /// every character in the string, along with the beginning
3053 /// and end of the string.
3056 /// let f: Vec<_> = "rust".split("").collect();
3057 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
3060 /// Contiguous separators can lead to possibly surprising behavior
3061 /// when whitespace is used as the separator. This code is correct:
3064 /// let x = " a b c".to_string();
3065 /// let d: Vec<_> = x.split(' ').collect();
3067 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3070 /// It does _not_ give you:
3073 /// assert_eq!(d, &["a", "b", "c"]);
3076 /// Use [`split_whitespace`] for this behavior.
3078 /// [`split_whitespace`]: #method.split_whitespace
3079 #[stable(feature = "rust1", since = "1.0.0")]
3081 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
3082 Split(SplitInternal {
3085 matcher: pat.into_searcher(self),
3086 allow_trailing_empty: true,
3091 /// An iterator over substrings of the given string slice, separated by
3092 /// characters matched by a pattern and yielded in reverse order.
3094 /// The pattern can be any type that implements the Pattern trait. Notable
3095 /// examples are `&str`, [`char`], and closures that determines the split.
3097 /// # Iterator behavior
3099 /// The returned iterator requires that the pattern supports a reverse
3100 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3101 /// search yields the same elements.
3103 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3105 /// For iterating from the front, the [`split`] method can be used.
3107 /// [`split`]: #method.split
3111 /// Simple patterns:
3114 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
3115 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
3117 /// let v: Vec<&str> = "".rsplit('X').collect();
3118 /// assert_eq!(v, [""]);
3120 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
3121 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
3123 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
3124 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
3127 /// A more complex pattern, using a closure:
3130 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
3131 /// assert_eq!(v, ["ghi", "def", "abc"]);
3133 #[stable(feature = "rust1", since = "1.0.0")]
3135 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
3136 where P::Searcher: ReverseSearcher<'a>
3138 RSplit(self.split(pat).0)
3141 /// An iterator over substrings of the given string slice, separated by
3142 /// characters matched by a pattern.
3144 /// The pattern can be any type that implements the Pattern trait. Notable
3145 /// examples are `&str`, [`char`], and closures that determines the split.
3147 /// Equivalent to [`split`], except that the trailing substring
3148 /// is skipped if empty.
3150 /// [`split`]: #method.split
3152 /// This method can be used for string data that is _terminated_,
3153 /// rather than _separated_ by a pattern.
3155 /// # Iterator behavior
3157 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3158 /// allows a reverse search and forward/reverse search yields the same
3159 /// elements. This is true for, e.g., [`char`], but not for `&str`.
3161 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3163 /// If the pattern allows a reverse search but its results might differ
3164 /// from a forward search, the [`rsplit_terminator`] method can be used.
3166 /// [`rsplit_terminator`]: #method.rsplit_terminator
3173 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
3174 /// assert_eq!(v, ["A", "B"]);
3176 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
3177 /// assert_eq!(v, ["A", "", "B", ""]);
3179 #[stable(feature = "rust1", since = "1.0.0")]
3181 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
3182 SplitTerminator(SplitInternal {
3183 allow_trailing_empty: false,
3188 /// An iterator over substrings of `self`, separated by characters
3189 /// matched by a pattern and yielded in reverse order.
3191 /// The pattern can be any type that implements the Pattern trait. Notable
3192 /// examples are `&str`, [`char`], and closures that determines the split.
3193 /// Additional libraries might provide more complex patterns like
3194 /// regular expressions.
3196 /// Equivalent to [`split`], except that the trailing substring is
3197 /// skipped if empty.
3199 /// [`split`]: #method.split
3201 /// This method can be used for string data that is _terminated_,
3202 /// rather than _separated_ by a pattern.
3204 /// # Iterator behavior
3206 /// The returned iterator requires that the pattern supports a
3207 /// reverse search, and it will be double ended if a forward/reverse
3208 /// search yields the same elements.
3210 /// For iterating from the front, the [`split_terminator`] method can be
3213 /// [`split_terminator`]: #method.split_terminator
3218 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
3219 /// assert_eq!(v, ["B", "A"]);
3221 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
3222 /// assert_eq!(v, ["", "B", "", "A"]);
3224 #[stable(feature = "rust1", since = "1.0.0")]
3226 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
3227 where P::Searcher: ReverseSearcher<'a>
3229 RSplitTerminator(self.split_terminator(pat).0)
3232 /// An iterator over substrings of the given string slice, separated by a
3233 /// pattern, restricted to returning at most `n` items.
3235 /// If `n` substrings are returned, the last substring (the `n`th substring)
3236 /// will contain the remainder of the string.
3238 /// The pattern can be any type that implements the Pattern trait. Notable
3239 /// examples are `&str`, [`char`], and closures that determines the split.
3241 /// # Iterator behavior
3243 /// The returned iterator will not be double ended, because it is
3244 /// not efficient to support.
3246 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
3249 /// [`rsplitn`]: #method.rsplitn
3253 /// Simple patterns:
3256 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
3257 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
3259 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
3260 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
3262 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
3263 /// assert_eq!(v, ["abcXdef"]);
3265 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
3266 /// assert_eq!(v, [""]);
3269 /// A more complex pattern, using a closure:
3272 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
3273 /// assert_eq!(v, ["abc", "defXghi"]);
3275 #[stable(feature = "rust1", since = "1.0.0")]
3277 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
3278 SplitN(SplitNInternal {
3279 iter: self.split(pat).0,
3284 /// An iterator over substrings of this string slice, separated by a
3285 /// pattern, starting from the end of the string, restricted to returning
3286 /// at most `n` items.
3288 /// If `n` substrings are returned, the last substring (the `n`th substring)
3289 /// will contain the remainder of the string.
3291 /// The pattern can be any type that implements the Pattern trait. Notable
3292 /// examples are `&str`, [`char`], and closures that determines the split.
3294 /// # Iterator behavior
3296 /// The returned iterator will not be double ended, because it is not
3297 /// efficient to support.
3299 /// For splitting from the front, the [`splitn`] method can be used.
3301 /// [`splitn`]: #method.splitn
3305 /// Simple patterns:
3308 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
3309 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
3311 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
3312 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
3314 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
3315 /// assert_eq!(v, ["leopard", "lion::tiger"]);
3318 /// A more complex pattern, using a closure:
3321 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
3322 /// assert_eq!(v, ["ghi", "abc1def"]);
3324 #[stable(feature = "rust1", since = "1.0.0")]
3326 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
3327 where P::Searcher: ReverseSearcher<'a>
3329 RSplitN(self.splitn(n, pat).0)
3332 /// An iterator over the disjoint matches of a pattern within the given string
3335 /// The pattern can be any type that implements the Pattern trait. Notable
3336 /// examples are `&str`, [`char`], and closures that determines the split.
3338 /// # Iterator behavior
3340 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3341 /// allows a reverse search and forward/reverse search yields the same
3342 /// elements. This is true for, e.g., [`char`], but not for `&str`.
3344 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3346 /// If the pattern allows a reverse search but its results might differ
3347 /// from a forward search, the [`rmatches`] method can be used.
3349 /// [`rmatches`]: #method.rmatches
3356 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
3357 /// assert_eq!(v, ["abc", "abc", "abc"]);
3359 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
3360 /// assert_eq!(v, ["1", "2", "3"]);
3362 #[stable(feature = "str_matches", since = "1.2.0")]
3364 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
3365 Matches(MatchesInternal(pat.into_searcher(self)))
3368 /// An iterator over the disjoint matches of a pattern within this string slice,
3369 /// yielded in reverse order.
3371 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3372 /// a character matches.
3374 /// # Iterator behavior
3376 /// The returned iterator requires that the pattern supports a reverse
3377 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3378 /// search yields the same elements.
3380 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3382 /// For iterating from the front, the [`matches`] method can be used.
3384 /// [`matches`]: #method.matches
3391 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
3392 /// assert_eq!(v, ["abc", "abc", "abc"]);
3394 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
3395 /// assert_eq!(v, ["3", "2", "1"]);
3397 #[stable(feature = "str_matches", since = "1.2.0")]
3399 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
3400 where P::Searcher: ReverseSearcher<'a>
3402 RMatches(self.matches(pat).0)
3405 /// An iterator over the disjoint matches of a pattern within this string
3406 /// slice as well as the index that the match starts at.
3408 /// For matches of `pat` within `self` that overlap, only the indices
3409 /// corresponding to the first match are returned.
3411 /// The pattern can be a `&str`, [`char`], or a closure that determines
3412 /// if a character matches.
3414 /// # Iterator behavior
3416 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3417 /// allows a reverse search and forward/reverse search yields the same
3418 /// elements. This is true for, e.g., [`char`], but not for `&str`.
3420 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3422 /// If the pattern allows a reverse search but its results might differ
3423 /// from a forward search, the [`rmatch_indices`] method can be used.
3425 /// [`rmatch_indices`]: #method.rmatch_indices
3432 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
3433 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
3435 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
3436 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
3438 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
3439 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
3441 #[stable(feature = "str_match_indices", since = "1.5.0")]
3443 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
3444 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
3447 /// An iterator over the disjoint matches of a pattern within `self`,
3448 /// yielded in reverse order along with the index of the match.
3450 /// For matches of `pat` within `self` that overlap, only the indices
3451 /// corresponding to the last match are returned.
3453 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
3454 /// character matches.
3456 /// # Iterator behavior
3458 /// The returned iterator requires that the pattern supports a reverse
3459 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3460 /// search yields the same elements.
3462 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3464 /// For iterating from the front, the [`match_indices`] method can be used.
3466 /// [`match_indices`]: #method.match_indices
3473 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
3474 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
3476 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
3477 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
3479 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
3480 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
3482 #[stable(feature = "str_match_indices", since = "1.5.0")]
3484 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
3485 where P::Searcher: ReverseSearcher<'a>
3487 RMatchIndices(self.match_indices(pat).0)
3490 /// Returns a string slice with leading and trailing whitespace removed.
3492 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3493 /// Core Property `White_Space`.
3500 /// let s = " Hello\tworld\t";
3502 /// assert_eq!("Hello\tworld", s.trim());
3504 #[must_use = "this returns the trimmed string as a slice, \
3505 without modifying the original"]
3506 #[stable(feature = "rust1", since = "1.0.0")]
3507 pub fn trim(&self) -> &str {
3508 self.trim_matches(|c: char| c.is_whitespace())
3511 /// Returns a string slice with leading whitespace removed.
3513 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3514 /// Core Property `White_Space`.
3516 /// # Text directionality
3518 /// A string is a sequence of bytes. `start` in this context means the first
3519 /// position of that byte string; for a left-to-right language like English or
3520 /// Russian, this will be left side, and for right-to-left languages like
3521 /// like Arabic or Hebrew, this will be the right side.
3528 /// let s = " Hello\tworld\t";
3529 /// assert_eq!("Hello\tworld\t", s.trim_start());
3535 /// let s = " English ";
3536 /// assert!(Some('E') == s.trim_start().chars().next());
3538 /// let s = " עברית ";
3539 /// assert!(Some('ע') == s.trim_start().chars().next());
3541 #[must_use = "this returns the trimmed string as a new slice, \
3542 without modifying the original"]
3543 #[stable(feature = "trim_direction", since = "1.30.0")]
3544 pub fn trim_start(&self) -> &str {
3545 self.trim_start_matches(|c: char| c.is_whitespace())
3548 /// Returns a string slice with trailing whitespace removed.
3550 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3551 /// Core Property `White_Space`.
3553 /// # Text directionality
3555 /// A string is a sequence of bytes. `end` in this context means the last
3556 /// position of that byte string; for a left-to-right language like English or
3557 /// Russian, this will be right side, and for right-to-left languages like
3558 /// like Arabic or Hebrew, this will be the left side.
3565 /// let s = " Hello\tworld\t";
3566 /// assert_eq!(" Hello\tworld", s.trim_end());
3572 /// let s = " English ";
3573 /// assert!(Some('h') == s.trim_end().chars().rev().next());
3575 /// let s = " עברית ";
3576 /// assert!(Some('ת') == s.trim_end().chars().rev().next());
3578 #[must_use = "this returns the trimmed string as a new slice, \
3579 without modifying the original"]
3580 #[stable(feature = "trim_direction", since = "1.30.0")]
3581 pub fn trim_end(&self) -> &str {
3582 self.trim_end_matches(|c: char| c.is_whitespace())
3585 /// Returns a string slice with leading whitespace removed.
3587 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3588 /// Core Property `White_Space`.
3590 /// # Text directionality
3592 /// A string is a sequence of bytes. 'Left' in this context means the first
3593 /// position of that byte string; for a language like Arabic or Hebrew
3594 /// which are 'right to left' rather than 'left to right', this will be
3595 /// the _right_ side, not the left.
3602 /// let s = " Hello\tworld\t";
3604 /// assert_eq!("Hello\tworld\t", s.trim_left());
3610 /// let s = " English";
3611 /// assert!(Some('E') == s.trim_left().chars().next());
3613 /// let s = " עברית";
3614 /// assert!(Some('ע') == s.trim_left().chars().next());
3616 #[stable(feature = "rust1", since = "1.0.0")]
3619 reason = "superseded by `trim_start`",
3620 suggestion = "trim_start",
3622 pub fn trim_left(&self) -> &str {
3626 /// Returns a string slice with trailing whitespace removed.
3628 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3629 /// Core Property `White_Space`.
3631 /// # Text directionality
3633 /// A string is a sequence of bytes. 'Right' in this context means the last
3634 /// position of that byte string; for a language like Arabic or Hebrew
3635 /// which are 'right to left' rather than 'left to right', this will be
3636 /// the _left_ side, not the right.
3643 /// let s = " Hello\tworld\t";
3645 /// assert_eq!(" Hello\tworld", s.trim_right());
3651 /// let s = "English ";
3652 /// assert!(Some('h') == s.trim_right().chars().rev().next());
3654 /// let s = "עברית ";
3655 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
3657 #[stable(feature = "rust1", since = "1.0.0")]
3660 reason = "superseded by `trim_end`",
3661 suggestion = "trim_end",
3663 pub fn trim_right(&self) -> &str {
3667 /// Returns a string slice with all prefixes and suffixes that match a
3668 /// pattern repeatedly removed.
3670 /// The pattern can be a [`char`] or a closure that determines if a
3671 /// character matches.
3675 /// Simple patterns:
3678 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
3679 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
3681 /// let x: &[_] = &['1', '2'];
3682 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
3685 /// A more complex pattern, using a closure:
3688 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
3690 #[must_use = "this returns the trimmed string as a new slice, \
3691 without modifying the original"]
3692 #[stable(feature = "rust1", since = "1.0.0")]
3693 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3694 where P::Searcher: DoubleEndedSearcher<'a>
3698 let mut matcher = pat.into_searcher(self);
3699 if let Some((a, b)) = matcher.next_reject() {
3701 j = b; // Remember earliest known match, correct it below if
3702 // last match is different
3704 if let Some((_, b)) = matcher.next_reject_back() {
3708 // Searcher is known to return valid indices
3709 self.get_unchecked(i..j)
3713 /// Returns a string slice with all prefixes that match a pattern
3714 /// repeatedly removed.
3716 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3717 /// a character matches.
3719 /// # Text directionality
3721 /// A string is a sequence of bytes. `start` in this context means the first
3722 /// position of that byte string; for a left-to-right language like English or
3723 /// Russian, this will be left side, and for right-to-left languages like
3724 /// like Arabic or Hebrew, this will be the right side.
3731 /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
3732 /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
3734 /// let x: &[_] = &['1', '2'];
3735 /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
3737 #[must_use = "this returns the trimmed string as a new slice, \
3738 without modifying the original"]
3739 #[stable(feature = "trim_direction", since = "1.30.0")]
3740 pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3741 let mut i = self.len();
3742 let mut matcher = pat.into_searcher(self);
3743 if let Some((a, _)) = matcher.next_reject() {
3747 // Searcher is known to return valid indices
3748 self.get_unchecked(i..self.len())
3752 /// Returns a string slice with all suffixes that match a pattern
3753 /// repeatedly removed.
3755 /// The pattern can be a `&str`, [`char`], or a closure that
3756 /// determines if a character matches.
3758 /// # Text directionality
3760 /// A string is a sequence of bytes. `end` in this context means the last
3761 /// position of that byte string; for a left-to-right language like English or
3762 /// Russian, this will be right side, and for right-to-left languages like
3763 /// like Arabic or Hebrew, this will be the left side.
3767 /// Simple patterns:
3770 /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
3771 /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
3773 /// let x: &[_] = &['1', '2'];
3774 /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
3777 /// A more complex pattern, using a closure:
3780 /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
3782 #[must_use = "this returns the trimmed string as a new slice, \
3783 without modifying the original"]
3784 #[stable(feature = "trim_direction", since = "1.30.0")]
3785 pub fn trim_end_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3786 where P::Searcher: ReverseSearcher<'a>
3789 let mut matcher = pat.into_searcher(self);
3790 if let Some((_, b)) = matcher.next_reject_back() {
3794 // Searcher is known to return valid indices
3795 self.get_unchecked(0..j)
3799 /// Returns a string slice with all prefixes that match a pattern
3800 /// repeatedly removed.
3802 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3803 /// a character matches.
3805 /// [`char`]: primitive.char.html
3807 /// # Text directionality
3809 /// A string is a sequence of bytes. 'Left' in this context means the first
3810 /// position of that byte string; for a language like Arabic or Hebrew
3811 /// which are 'right to left' rather than 'left to right', this will be
3812 /// the _right_ side, not the left.
3819 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
3820 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
3822 /// let x: &[_] = &['1', '2'];
3823 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
3825 #[stable(feature = "rust1", since = "1.0.0")]
3828 reason = "superseded by `trim_start_matches`",
3829 suggestion = "trim_start_matches",
3831 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3832 self.trim_start_matches(pat)
3835 /// Returns a string slice with all suffixes that match a pattern
3836 /// repeatedly removed.
3838 /// The pattern can be a `&str`, [`char`], or a closure that
3839 /// determines if a character matches.
3841 /// [`char`]: primitive.char.html
3843 /// # Text directionality
3845 /// A string is a sequence of bytes. 'Right' in this context means the last
3846 /// position of that byte string; for a language like Arabic or Hebrew
3847 /// which are 'right to left' rather than 'left to right', this will be
3848 /// the _left_ side, not the right.
3852 /// Simple patterns:
3855 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
3856 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
3858 /// let x: &[_] = &['1', '2'];
3859 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
3862 /// A more complex pattern, using a closure:
3865 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
3867 #[stable(feature = "rust1", since = "1.0.0")]
3870 reason = "superseded by `trim_end_matches`",
3871 suggestion = "trim_end_matches",
3873 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3874 where P::Searcher: ReverseSearcher<'a>
3876 self.trim_end_matches(pat)
3879 /// Parses this string slice into another type.
3881 /// Because `parse` is so general, it can cause problems with type
3882 /// inference. As such, `parse` is one of the few times you'll see
3883 /// the syntax affectionately known as the 'turbofish': `::<>`. This
3884 /// helps the inference algorithm understand specifically which type
3885 /// you're trying to parse into.
3887 /// `parse` can parse any type that implements the [`FromStr`] trait.
3889 /// [`FromStr`]: str/trait.FromStr.html
3893 /// Will return [`Err`] if it's not possible to parse this string slice into
3894 /// the desired type.
3896 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
3903 /// let four: u32 = "4".parse().unwrap();
3905 /// assert_eq!(4, four);
3908 /// Using the 'turbofish' instead of annotating `four`:
3911 /// let four = "4".parse::<u32>();
3913 /// assert_eq!(Ok(4), four);
3916 /// Failing to parse:
3919 /// let nope = "j".parse::<u32>();
3921 /// assert!(nope.is_err());
3924 #[stable(feature = "rust1", since = "1.0.0")]
3925 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
3926 FromStr::from_str(self)
3929 /// Checks if all characters in this string are within the ASCII range.
3934 /// let ascii = "hello!\n";
3935 /// let non_ascii = "Grüße, Jürgen ❤";
3937 /// assert!(ascii.is_ascii());
3938 /// assert!(!non_ascii.is_ascii());
3940 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3942 pub fn is_ascii(&self) -> bool {
3943 // We can treat each byte as character here: all multibyte characters
3944 // start with a byte that is not in the ascii range, so we will stop
3946 self.bytes().all(|b| b.is_ascii())
3949 /// Checks that two strings are an ASCII case-insensitive match.
3951 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
3952 /// but without allocating and copying temporaries.
3957 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
3958 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
3959 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
3961 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3963 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
3964 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
3967 /// Converts this string to its ASCII upper case equivalent in-place.
3969 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3970 /// but non-ASCII letters are unchanged.
3972 /// To return a new uppercased value without modifying the existing one, use
3973 /// [`to_ascii_uppercase`].
3975 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3980 /// let mut s = String::from("Grüße, Jürgen ❤");
3982 /// s.make_ascii_uppercase();
3984 /// assert_eq!("GRüßE, JüRGEN ❤", s);
3986 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3987 pub fn make_ascii_uppercase(&mut self) {
3988 let me = unsafe { self.as_bytes_mut() };
3989 me.make_ascii_uppercase()
3992 /// Converts this string to its ASCII lower case equivalent in-place.
3994 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3995 /// but non-ASCII letters are unchanged.
3997 /// To return a new lowercased value without modifying the existing one, use
3998 /// [`to_ascii_lowercase`].
4000 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4005 /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
4007 /// s.make_ascii_lowercase();
4009 /// assert_eq!("grÜße, jÜrgen ❤", s);
4011 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4012 pub fn make_ascii_lowercase(&mut self) {
4013 let me = unsafe { self.as_bytes_mut() };
4014 me.make_ascii_lowercase()
4017 /// Return an iterator that escapes each char in `self` with [`char::escape_debug`].
4019 /// Note: only extended grapheme codepoints that begin the string will be
4022 /// [`char::escape_debug`]: ../std/primitive.char.html#method.escape_debug
4029 /// for c in "❤\n!".escape_debug() {
4030 /// print!("{}", c);
4035 /// Using `println!` directly:
4038 /// println!("{}", "❤\n!".escape_debug());
4042 /// Both are equivalent to:
4045 /// println!("❤\\n!");
4048 /// Using `to_string`:
4051 /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
4053 #[stable(feature = "str_escape", since = "1.34.0")]
4054 pub fn escape_debug(&self) -> EscapeDebug<'_> {
4055 let mut chars = self.chars();
4058 .map(|first| first.escape_debug_ext(true))
4061 .chain(chars.flat_map(CharEscapeDebugContinue))
4065 /// Return an iterator that escapes each char in `self` with [`char::escape_default`].
4067 /// [`char::escape_default`]: ../std/primitive.char.html#method.escape_default
4074 /// for c in "❤\n!".escape_default() {
4075 /// print!("{}", c);
4080 /// Using `println!` directly:
4083 /// println!("{}", "❤\n!".escape_default());
4087 /// Both are equivalent to:
4090 /// println!("\\u{{2764}}\\n!");
4093 /// Using `to_string`:
4096 /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
4098 #[stable(feature = "str_escape", since = "1.34.0")]
4099 pub fn escape_default(&self) -> EscapeDefault<'_> {
4100 EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
4103 /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`].
4105 /// [`char::escape_unicode`]: ../std/primitive.char.html#method.escape_unicode
4112 /// for c in "❤\n!".escape_unicode() {
4113 /// print!("{}", c);
4118 /// Using `println!` directly:
4121 /// println!("{}", "❤\n!".escape_unicode());
4125 /// Both are equivalent to:
4128 /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
4131 /// Using `to_string`:
4134 /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
4136 #[stable(feature = "str_escape", since = "1.34.0")]
4137 pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
4138 EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
4144 struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
4145 c.escape_debug_ext(false)
4149 struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
4153 struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
4158 #[stable(feature = "rust1", since = "1.0.0")]
4159 impl AsRef<[u8]> for str {
4161 fn as_ref(&self) -> &[u8] {
4166 #[stable(feature = "rust1", since = "1.0.0")]
4167 impl Default for &str {
4168 /// Creates an empty str
4169 fn default() -> Self { "" }
4172 #[stable(feature = "default_mut_str", since = "1.28.0")]
4173 impl Default for &mut str {
4174 /// Creates an empty mutable str
4175 fn default() -> Self { unsafe { from_utf8_unchecked_mut(&mut []) } }
4178 /// An iterator over the non-whitespace substrings of a string,
4179 /// separated by any amount of whitespace.
4181 /// This struct is created by the [`split_whitespace`] method on [`str`].
4182 /// See its documentation for more.
4184 /// [`split_whitespace`]: ../../std/primitive.str.html#method.split_whitespace
4185 /// [`str`]: ../../std/primitive.str.html
4186 #[stable(feature = "split_whitespace", since = "1.1.0")]
4187 #[derive(Clone, Debug)]
4188 pub struct SplitWhitespace<'a> {
4189 inner: Filter<Split<'a, IsWhitespace>, IsNotEmpty>,
4192 /// An iterator over the non-ASCII-whitespace substrings of a string,
4193 /// separated by any amount of ASCII whitespace.
4195 /// This struct is created by the [`split_ascii_whitespace`] method on [`str`].
4196 /// See its documentation for more.
4198 /// [`split_ascii_whitespace`]: ../../std/primitive.str.html#method.split_ascii_whitespace
4199 /// [`str`]: ../../std/primitive.str.html
4200 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4201 #[derive(Clone, Debug)]
4202 pub struct SplitAsciiWhitespace<'a> {
4203 inner: Map<Filter<SliceSplit<'a, u8, IsAsciiWhitespace>, BytesIsNotEmpty>, UnsafeBytesToStr>,
4208 struct IsWhitespace impl Fn = |c: char| -> bool {
4213 struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
4214 byte.is_ascii_whitespace()
4218 struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
4223 struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
4228 struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
4229 unsafe { from_utf8_unchecked(bytes) }
4233 #[stable(feature = "split_whitespace", since = "1.1.0")]
4234 impl<'a> Iterator for SplitWhitespace<'a> {
4235 type Item = &'a str;
4238 fn next(&mut self) -> Option<&'a str> {
4243 fn size_hint(&self) -> (usize, Option<usize>) {
4244 self.inner.size_hint()
4248 fn last(mut self) -> Option<&'a str> {
4253 #[stable(feature = "split_whitespace", since = "1.1.0")]
4254 impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
4256 fn next_back(&mut self) -> Option<&'a str> {
4257 self.inner.next_back()
4261 #[stable(feature = "fused", since = "1.26.0")]
4262 impl FusedIterator for SplitWhitespace<'_> {}
4264 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4265 impl<'a> Iterator for SplitAsciiWhitespace<'a> {
4266 type Item = &'a str;
4269 fn next(&mut self) -> Option<&'a str> {
4274 fn size_hint(&self) -> (usize, Option<usize>) {
4275 self.inner.size_hint()
4279 fn last(mut self) -> Option<&'a str> {
4284 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4285 impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> {
4287 fn next_back(&mut self) -> Option<&'a str> {
4288 self.inner.next_back()
4292 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4293 impl FusedIterator for SplitAsciiWhitespace<'_> {}
4295 /// An iterator of [`u16`] over the string encoded as UTF-16.
4297 /// [`u16`]: ../../std/primitive.u16.html
4299 /// This struct is created by the [`encode_utf16`] method on [`str`].
4300 /// See its documentation for more.
4302 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
4303 /// [`str`]: ../../std/primitive.str.html
4305 #[stable(feature = "encode_utf16", since = "1.8.0")]
4306 pub struct EncodeUtf16<'a> {
4311 #[stable(feature = "collection_debug", since = "1.17.0")]
4312 impl fmt::Debug for EncodeUtf16<'_> {
4313 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4314 f.pad("EncodeUtf16 { .. }")
4318 #[stable(feature = "encode_utf16", since = "1.8.0")]
4319 impl<'a> Iterator for EncodeUtf16<'a> {
4323 fn next(&mut self) -> Option<u16> {
4324 if self.extra != 0 {
4325 let tmp = self.extra;
4330 let mut buf = [0; 2];
4331 self.chars.next().map(|ch| {
4332 let n = ch.encode_utf16(&mut buf).len();
4334 self.extra = buf[1];
4341 fn size_hint(&self) -> (usize, Option<usize>) {
4342 let (low, high) = self.chars.size_hint();
4343 // every char gets either one u16 or two u16,
4344 // so this iterator is between 1 or 2 times as
4345 // long as the underlying iterator.
4346 (low, high.and_then(|n| n.checked_mul(2)))
4350 #[stable(feature = "fused", since = "1.26.0")]
4351 impl FusedIterator for EncodeUtf16<'_> {}
4353 /// The return type of [`str::escape_debug`].
4355 /// [`str::escape_debug`]: ../../std/primitive.str.html#method.escape_debug
4356 #[stable(feature = "str_escape", since = "1.34.0")]
4357 #[derive(Clone, Debug)]
4358 pub struct EscapeDebug<'a> {
4360 Flatten<option::IntoIter<char::EscapeDebug>>,
4361 FlatMap<Chars<'a>, char::EscapeDebug, CharEscapeDebugContinue>
4365 /// The return type of [`str::escape_default`].
4367 /// [`str::escape_default`]: ../../std/primitive.str.html#method.escape_default
4368 #[stable(feature = "str_escape", since = "1.34.0")]
4369 #[derive(Clone, Debug)]
4370 pub struct EscapeDefault<'a> {
4371 inner: FlatMap<Chars<'a>, char::EscapeDefault, CharEscapeDefault>,
4374 /// The return type of [`str::escape_unicode`].
4376 /// [`str::escape_unicode`]: ../../std/primitive.str.html#method.escape_unicode
4377 #[stable(feature = "str_escape", since = "1.34.0")]
4378 #[derive(Clone, Debug)]
4379 pub struct EscapeUnicode<'a> {
4380 inner: FlatMap<Chars<'a>, char::EscapeUnicode, CharEscapeUnicode>,
4383 macro_rules! escape_types_impls {
4384 ($( $Name: ident ),+) => {$(
4385 #[stable(feature = "str_escape", since = "1.34.0")]
4386 impl<'a> fmt::Display for $Name<'a> {
4387 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4388 self.clone().try_for_each(|c| f.write_char(c))
4392 #[stable(feature = "str_escape", since = "1.34.0")]
4393 impl<'a> Iterator for $Name<'a> {
4397 fn next(&mut self) -> Option<char> { self.inner.next() }
4400 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
4403 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
4404 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
4406 self.inner.try_fold(init, fold)
4410 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
4411 where Fold: FnMut(Acc, Self::Item) -> Acc,
4413 self.inner.fold(init, fold)
4417 #[stable(feature = "str_escape", since = "1.34.0")]
4418 impl<'a> FusedIterator for $Name<'a> {}
4422 escape_types_impls!(EscapeDebug, EscapeDefault, EscapeUnicode);