1 // ignore-tidy-filelength
2 // ignore-tidy-undocumented-unsafe
4 //! String manipulation.
6 //! For more details, see the `std::str` module.
8 #![stable(feature = "rust1", since = "1.0.0")]
10 use self::pattern::Pattern;
11 use self::pattern::{Searcher, SearchStep, ReverseSearcher, DoubleEndedSearcher};
14 use crate::fmt::{self, Write};
15 use crate::iter::{Map, Cloned, FusedIterator, TrustedLen, TrustedRandomAccess, Filter};
16 use crate::iter::{Flatten, FlatMap, Chain};
17 use crate::slice::{self, SliceIndex, Split as SliceSplit};
24 #[unstable(feature = "str_internals", issue = "0")]
25 #[allow(missing_docs)]
28 /// Parse a value from a string
30 /// `FromStr`'s [`from_str`] method is often used implicitly, through
31 /// [`str`]'s [`parse`] method. See [`parse`]'s documentation for examples.
33 /// [`from_str`]: #tymethod.from_str
34 /// [`str`]: ../../std/primitive.str.html
35 /// [`parse`]: ../../std/primitive.str.html#method.parse
37 /// `FromStr` does not have a lifetime parameter, and so you can only parse types
38 /// that do not contain a lifetime parameter themselves. In other words, you can
39 /// parse an `i32` with `FromStr`, but not a `&i32`. You can parse a struct that
40 /// contains an `i32`, but not one that contains an `&i32`.
44 /// Basic implementation of `FromStr` on an example `Point` type:
47 /// use std::str::FromStr;
48 /// use std::num::ParseIntError;
50 /// #[derive(Debug, PartialEq)]
56 /// impl FromStr for Point {
57 /// type Err = ParseIntError;
59 /// fn from_str(s: &str) -> Result<Self, Self::Err> {
60 /// let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
64 /// let x_fromstr = coords[0].parse::<i32>()?;
65 /// let y_fromstr = coords[1].parse::<i32>()?;
67 /// Ok(Point { x: x_fromstr, y: y_fromstr })
71 /// let p = Point::from_str("(1,2)");
72 /// assert_eq!(p.unwrap(), Point{ x: 1, y: 2} )
74 #[stable(feature = "rust1", since = "1.0.0")]
75 pub trait FromStr: Sized {
76 /// The associated error which can be returned from parsing.
77 #[stable(feature = "rust1", since = "1.0.0")]
80 /// Parses a string `s` to return a value of this type.
82 /// If parsing succeeds, return the value inside [`Ok`], otherwise
83 /// when the string is ill-formatted return an error specific to the
84 /// inside [`Err`]. The error type is specific to implementation of the trait.
86 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
87 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
91 /// Basic usage with [`i32`][ithirtytwo], a type that implements `FromStr`:
93 /// [ithirtytwo]: ../../std/primitive.i32.html
96 /// use std::str::FromStr;
99 /// let x = i32::from_str(s).unwrap();
101 /// assert_eq!(5, x);
103 #[stable(feature = "rust1", since = "1.0.0")]
104 fn from_str(s: &str) -> Result<Self, Self::Err>;
107 #[stable(feature = "rust1", since = "1.0.0")]
108 impl FromStr for bool {
109 type Err = ParseBoolError;
111 /// Parse a `bool` from a string.
113 /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
114 /// actually be parseable.
119 /// use std::str::FromStr;
121 /// assert_eq!(FromStr::from_str("true"), Ok(true));
122 /// assert_eq!(FromStr::from_str("false"), Ok(false));
123 /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
126 /// Note, in many cases, the `.parse()` method on `str` is more proper.
129 /// assert_eq!("true".parse(), Ok(true));
130 /// assert_eq!("false".parse(), Ok(false));
131 /// assert!("not even a boolean".parse::<bool>().is_err());
134 fn from_str(s: &str) -> Result<bool, ParseBoolError> {
137 "false" => Ok(false),
138 _ => Err(ParseBoolError { _priv: () }),
143 /// An error returned when parsing a `bool` using [`from_str`] fails
145 /// [`from_str`]: ../../std/primitive.bool.html#method.from_str
146 #[derive(Debug, Clone, PartialEq, Eq)]
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub struct ParseBoolError { _priv: () }
150 #[stable(feature = "rust1", since = "1.0.0")]
151 impl fmt::Display for ParseBoolError {
152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153 "provided string was not `true` or `false`".fmt(f)
158 Section: Creating a string
161 /// Errors which can occur when attempting to interpret a sequence of [`u8`]
164 /// [`u8`]: ../../std/primitive.u8.html
166 /// As such, the `from_utf8` family of functions and methods for both [`String`]s
167 /// and [`&str`]s make use of this error, for example.
169 /// [`String`]: ../../std/string/struct.String.html#method.from_utf8
170 /// [`&str`]: ../../std/str/fn.from_utf8.html
174 /// This error type’s methods can be used to create functionality
175 /// similar to `String::from_utf8_lossy` without allocating heap memory:
178 /// fn from_utf8_lossy<F>(mut input: &[u8], mut push: F) where F: FnMut(&str) {
180 /// match std::str::from_utf8(input) {
186 /// let (valid, after_valid) = input.split_at(error.valid_up_to());
188 /// push(std::str::from_utf8_unchecked(valid))
190 /// push("\u{FFFD}");
192 /// if let Some(invalid_sequence_length) = error.error_len() {
193 /// input = &after_valid[invalid_sequence_length..]
202 #[derive(Copy, Eq, PartialEq, Clone, Debug)]
203 #[stable(feature = "rust1", since = "1.0.0")]
204 pub struct Utf8Error {
206 error_len: Option<u8>,
210 /// Returns the index in the given string up to which valid UTF-8 was
213 /// It is the maximum index such that `from_utf8(&input[..index])`
214 /// would return `Ok(_)`.
223 /// // some invalid bytes, in a vector
224 /// let sparkle_heart = vec![0, 159, 146, 150];
226 /// // std::str::from_utf8 returns a Utf8Error
227 /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
229 /// // the second byte is invalid here
230 /// assert_eq!(1, error.valid_up_to());
232 #[stable(feature = "utf8_error", since = "1.5.0")]
233 pub fn valid_up_to(&self) -> usize { self.valid_up_to }
235 /// Provides more information about the failure:
237 /// * `None`: the end of the input was reached unexpectedly.
238 /// `self.valid_up_to()` is 1 to 3 bytes from the end of the input.
239 /// If a byte stream (such as a file or a network socket) is being decoded incrementally,
240 /// this could be a valid `char` whose UTF-8 byte sequence is spanning multiple chunks.
242 /// * `Some(len)`: an unexpected byte was encountered.
243 /// The length provided is that of the invalid byte sequence
244 /// that starts at the index given by `valid_up_to()`.
245 /// Decoding should resume after that sequence
246 /// (after inserting a [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD]) in case of
249 /// [U+FFFD]: ../../std/char/constant.REPLACEMENT_CHARACTER.html
250 #[stable(feature = "utf8_error_error_len", since = "1.20.0")]
251 pub fn error_len(&self) -> Option<usize> {
252 self.error_len.map(|len| len as usize)
256 /// Converts a slice of bytes to a string slice.
258 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
259 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
260 /// the two. Not all byte slices are valid string slices, however: [`&str`] requires
261 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
262 /// UTF-8, and then does the conversion.
264 /// [`&str`]: ../../std/primitive.str.html
265 /// [`u8`]: ../../std/primitive.u8.html
266 /// [byteslice]: ../../std/primitive.slice.html
268 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
269 /// incur the overhead of the validity check, there is an unsafe version of
270 /// this function, [`from_utf8_unchecked`][fromutf8u], which has the same
271 /// behavior but skips the check.
273 /// [fromutf8u]: fn.from_utf8_unchecked.html
275 /// If you need a `String` instead of a `&str`, consider
276 /// [`String::from_utf8`][string].
278 /// [string]: ../../std/string/struct.String.html#method.from_utf8
280 /// Because you can stack-allocate a `[u8; N]`, and you can take a
281 /// [`&[u8]`][byteslice] of it, this function is one way to have a
282 /// stack-allocated string. There is an example of this in the
283 /// examples section below.
285 /// [byteslice]: ../../std/primitive.slice.html
289 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
290 /// provided slice is not UTF-8.
299 /// // some bytes, in a vector
300 /// let sparkle_heart = vec![240, 159, 146, 150];
302 /// // We know these bytes are valid, so just use `unwrap()`.
303 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
305 /// assert_eq!("💖", sparkle_heart);
313 /// // some invalid bytes, in a vector
314 /// let sparkle_heart = vec![0, 159, 146, 150];
316 /// assert!(str::from_utf8(&sparkle_heart).is_err());
319 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
320 /// errors that can be returned.
322 /// [error]: struct.Utf8Error.html
324 /// A "stack allocated string":
329 /// // some bytes, in a stack-allocated array
330 /// let sparkle_heart = [240, 159, 146, 150];
332 /// // We know these bytes are valid, so just use `unwrap()`.
333 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
335 /// assert_eq!("💖", sparkle_heart);
337 #[stable(feature = "rust1", since = "1.0.0")]
338 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
339 run_utf8_validation(v)?;
340 Ok(unsafe { from_utf8_unchecked(v) })
343 /// Converts a mutable slice of bytes to a mutable string slice.
352 /// // "Hello, Rust!" as a mutable vector
353 /// let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
355 /// // As we know these bytes are valid, we can use `unwrap()`
356 /// let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
358 /// assert_eq!("Hello, Rust!", outstr);
366 /// // Some invalid bytes in a mutable vector
367 /// let mut invalid = vec![128, 223];
369 /// assert!(str::from_utf8_mut(&mut invalid).is_err());
371 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
372 /// errors that can be returned.
374 /// [error]: struct.Utf8Error.html
375 #[stable(feature = "str_mut_extras", since = "1.20.0")]
376 pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
377 run_utf8_validation(v)?;
378 Ok(unsafe { from_utf8_unchecked_mut(v) })
381 /// Converts a slice of bytes to a string slice without checking
382 /// that the string contains valid UTF-8.
384 /// See the safe version, [`from_utf8`][fromutf8], for more information.
386 /// [fromutf8]: fn.from_utf8.html
390 /// This function is unsafe because it does not check that the bytes passed to
391 /// it are valid UTF-8. If this constraint is violated, undefined behavior
392 /// results, as the rest of Rust assumes that [`&str`]s are valid UTF-8.
394 /// [`&str`]: ../../std/primitive.str.html
403 /// // some bytes, in a vector
404 /// let sparkle_heart = vec![240, 159, 146, 150];
406 /// let sparkle_heart = unsafe {
407 /// str::from_utf8_unchecked(&sparkle_heart)
410 /// assert_eq!("💖", sparkle_heart);
413 #[stable(feature = "rust1", since = "1.0.0")]
414 pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
415 &*(v as *const [u8] as *const str)
418 /// Converts a slice of bytes to a string slice without checking
419 /// that the string contains valid UTF-8; mutable version.
421 /// See the immutable version, [`from_utf8_unchecked()`][fromutf8], for more information.
423 /// [fromutf8]: fn.from_utf8_unchecked.html
432 /// let mut heart = vec![240, 159, 146, 150];
433 /// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
435 /// assert_eq!("💖", heart);
438 #[stable(feature = "str_mut_extras", since = "1.20.0")]
439 pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
440 &mut *(v as *mut [u8] as *mut str)
443 #[stable(feature = "rust1", since = "1.0.0")]
444 impl fmt::Display for Utf8Error {
445 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
446 if let Some(error_len) = self.error_len {
447 write!(f, "invalid utf-8 sequence of {} bytes from index {}",
448 error_len, self.valid_up_to)
450 write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to)
459 /// An iterator over the [`char`]s of a string slice.
461 /// [`char`]: ../../std/primitive.char.html
463 /// This struct is created by the [`chars`] method on [`str`].
464 /// See its documentation for more.
466 /// [`chars`]: ../../std/primitive.str.html#method.chars
467 /// [`str`]: ../../std/primitive.str.html
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub struct Chars<'a> {
471 iter: slice::Iter<'a, u8>
474 /// Returns the initial codepoint accumulator for the first byte.
475 /// The first byte is special, only want bottom 5 bits for width 2, 4 bits
476 /// for width 3, and 3 bits for width 4.
478 fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
480 /// Returns the value of `ch` updated with continuation byte `byte`.
482 fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
484 /// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the
487 fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
490 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
497 /// Reads the next code point out of a byte iterator (assuming a
498 /// UTF-8-like encoding).
499 #[unstable(feature = "str_internals", issue = "0")]
501 pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
503 let x = *bytes.next()?;
505 return Some(x as u32)
508 // Multibyte case follows
509 // Decode from a byte combination out of: [[[x y] z] w]
510 // NOTE: Performance is sensitive to the exact formulation here
511 let init = utf8_first_byte(x, 2);
512 let y = unwrap_or_0(bytes.next());
513 let mut ch = utf8_acc_cont_byte(init, y);
516 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
517 let z = unwrap_or_0(bytes.next());
518 let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
519 ch = init << 12 | y_z;
522 // use only the lower 3 bits of `init`
523 let w = unwrap_or_0(bytes.next());
524 ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
531 /// Reads the last code point out of a byte iterator (assuming a
532 /// UTF-8-like encoding).
534 fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
535 where I: DoubleEndedIterator<Item = &'a u8>,
538 let w = match *bytes.next_back()? {
539 next_byte if next_byte < 128 => return Some(next_byte as u32),
540 back_byte => back_byte,
543 // Multibyte case follows
544 // Decode from a byte combination out of: [x [y [z w]]]
546 let z = unwrap_or_0(bytes.next_back());
547 ch = utf8_first_byte(z, 2);
548 if utf8_is_cont_byte(z) {
549 let y = unwrap_or_0(bytes.next_back());
550 ch = utf8_first_byte(y, 3);
551 if utf8_is_cont_byte(y) {
552 let x = unwrap_or_0(bytes.next_back());
553 ch = utf8_first_byte(x, 4);
554 ch = utf8_acc_cont_byte(ch, y);
556 ch = utf8_acc_cont_byte(ch, z);
558 ch = utf8_acc_cont_byte(ch, w);
563 #[stable(feature = "rust1", since = "1.0.0")]
564 impl<'a> Iterator for Chars<'a> {
568 fn next(&mut self) -> Option<char> {
569 next_code_point(&mut self.iter).map(|ch| {
570 // str invariant says `ch` is a valid Unicode Scalar Value
572 char::from_u32_unchecked(ch)
578 fn count(self) -> usize {
579 // length in `char` is equal to the number of non-continuation bytes
580 let bytes_len = self.iter.len();
581 let mut cont_bytes = 0;
582 for &byte in self.iter {
583 cont_bytes += utf8_is_cont_byte(byte) as usize;
585 bytes_len - cont_bytes
589 fn size_hint(&self) -> (usize, Option<usize>) {
590 let len = self.iter.len();
591 // `(len + 3)` can't overflow, because we know that the `slice::Iter`
592 // belongs to a slice in memory which has a maximum length of
593 // `isize::MAX` (that's well below `usize::MAX`).
594 ((len + 3) / 4, Some(len))
598 fn last(mut self) -> Option<char> {
599 // No need to go through the entire string.
604 #[stable(feature = "chars_debug_impl", since = "1.38.0")]
605 impl fmt::Debug for Chars<'_> {
606 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
607 write!(f, "Chars(")?;
608 f.debug_list().entries(self.clone()).finish()?;
614 #[stable(feature = "rust1", since = "1.0.0")]
615 impl<'a> DoubleEndedIterator for Chars<'a> {
617 fn next_back(&mut self) -> Option<char> {
618 next_code_point_reverse(&mut self.iter).map(|ch| {
619 // str invariant says `ch` is a valid Unicode Scalar Value
621 char::from_u32_unchecked(ch)
627 #[stable(feature = "fused", since = "1.26.0")]
628 impl FusedIterator for Chars<'_> {}
631 /// Views the underlying data as a subslice of the original data.
633 /// This has the same lifetime as the original slice, and so the
634 /// iterator can continue to be used while this exists.
639 /// let mut chars = "abc".chars();
641 /// assert_eq!(chars.as_str(), "abc");
643 /// assert_eq!(chars.as_str(), "bc");
646 /// assert_eq!(chars.as_str(), "");
648 #[stable(feature = "iter_to_slice", since = "1.4.0")]
650 pub fn as_str(&self) -> &'a str {
651 unsafe { from_utf8_unchecked(self.iter.as_slice()) }
655 /// An iterator over the [`char`]s of a string slice, and their positions.
657 /// [`char`]: ../../std/primitive.char.html
659 /// This struct is created by the [`char_indices`] method on [`str`].
660 /// See its documentation for more.
662 /// [`char_indices`]: ../../std/primitive.str.html#method.char_indices
663 /// [`str`]: ../../std/primitive.str.html
664 #[derive(Clone, Debug)]
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub struct CharIndices<'a> {
671 #[stable(feature = "rust1", since = "1.0.0")]
672 impl<'a> Iterator for CharIndices<'a> {
673 type Item = (usize, char);
676 fn next(&mut self) -> Option<(usize, char)> {
677 let pre_len = self.iter.iter.len();
678 match self.iter.next() {
681 let index = self.front_offset;
682 let len = self.iter.iter.len();
683 self.front_offset += pre_len - len;
690 fn count(self) -> usize {
695 fn size_hint(&self) -> (usize, Option<usize>) {
696 self.iter.size_hint()
700 fn last(mut self) -> Option<(usize, char)> {
701 // No need to go through the entire string.
706 #[stable(feature = "rust1", since = "1.0.0")]
707 impl<'a> DoubleEndedIterator for CharIndices<'a> {
709 fn next_back(&mut self) -> Option<(usize, char)> {
710 self.iter.next_back().map(|ch| {
711 let index = self.front_offset + self.iter.iter.len();
717 #[stable(feature = "fused", since = "1.26.0")]
718 impl FusedIterator for CharIndices<'_> {}
720 impl<'a> CharIndices<'a> {
721 /// Views the underlying data as a subslice of the original data.
723 /// This has the same lifetime as the original slice, and so the
724 /// iterator can continue to be used while this exists.
725 #[stable(feature = "iter_to_slice", since = "1.4.0")]
727 pub fn as_str(&self) -> &'a str {
732 /// An iterator over the bytes of a string slice.
734 /// This struct is created by the [`bytes`] method on [`str`].
735 /// See its documentation for more.
737 /// [`bytes`]: ../../std/primitive.str.html#method.bytes
738 /// [`str`]: ../../std/primitive.str.html
739 #[stable(feature = "rust1", since = "1.0.0")]
740 #[derive(Clone, Debug)]
741 pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>);
743 #[stable(feature = "rust1", since = "1.0.0")]
744 impl Iterator for Bytes<'_> {
748 fn next(&mut self) -> Option<u8> {
753 fn size_hint(&self) -> (usize, Option<usize>) {
758 fn count(self) -> usize {
763 fn last(self) -> Option<Self::Item> {
768 fn nth(&mut self, n: usize) -> Option<Self::Item> {
773 fn all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
778 fn any<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
783 fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where
784 P: FnMut(&Self::Item) -> bool
786 self.0.find(predicate)
790 fn position<P>(&mut self, predicate: P) -> Option<usize> where
791 P: FnMut(Self::Item) -> bool
793 self.0.position(predicate)
797 fn rposition<P>(&mut self, predicate: P) -> Option<usize> where
798 P: FnMut(Self::Item) -> bool
800 self.0.rposition(predicate)
804 #[stable(feature = "rust1", since = "1.0.0")]
805 impl DoubleEndedIterator for Bytes<'_> {
807 fn next_back(&mut self) -> Option<u8> {
812 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
817 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> where
818 P: FnMut(&Self::Item) -> bool
820 self.0.rfind(predicate)
824 #[stable(feature = "rust1", since = "1.0.0")]
825 impl ExactSizeIterator for Bytes<'_> {
827 fn len(&self) -> usize {
832 fn is_empty(&self) -> bool {
837 #[stable(feature = "fused", since = "1.26.0")]
838 impl FusedIterator for Bytes<'_> {}
840 #[unstable(feature = "trusted_len", issue = "37572")]
841 unsafe impl TrustedLen for Bytes<'_> {}
844 unsafe impl TrustedRandomAccess for Bytes<'_> {
845 unsafe fn get_unchecked(&mut self, i: usize) -> u8 {
846 self.0.get_unchecked(i)
848 fn may_have_side_effect() -> bool { false }
851 /// This macro generates a Clone impl for string pattern API
852 /// wrapper types of the form X<'a, P>
853 macro_rules! derive_pattern_clone {
854 (clone $t:ident with |$s:ident| $e:expr) => {
855 impl<'a, P> Clone for $t<'a, P>
857 P: Pattern<'a, Searcher: Clone>,
859 fn clone(&self) -> Self {
867 /// This macro generates two public iterator structs
868 /// wrapping a private internal one that makes use of the `Pattern` API.
870 /// For all patterns `P: Pattern<'a>` the following items will be
871 /// generated (generics omitted):
873 /// struct $forward_iterator($internal_iterator);
874 /// struct $reverse_iterator($internal_iterator);
876 /// impl Iterator for $forward_iterator
877 /// { /* internal ends up calling Searcher::next_match() */ }
879 /// impl DoubleEndedIterator for $forward_iterator
880 /// where P::Searcher: DoubleEndedSearcher
881 /// { /* internal ends up calling Searcher::next_match_back() */ }
883 /// impl Iterator for $reverse_iterator
884 /// where P::Searcher: ReverseSearcher
885 /// { /* internal ends up calling Searcher::next_match_back() */ }
887 /// impl DoubleEndedIterator for $reverse_iterator
888 /// where P::Searcher: DoubleEndedSearcher
889 /// { /* internal ends up calling Searcher::next_match() */ }
891 /// The internal one is defined outside the macro, and has almost the same
892 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
893 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
895 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
896 /// `Pattern` might not return the same elements, so actually implementing
897 /// `DoubleEndedIterator` for it would be incorrect.
898 /// (See the docs in `str::pattern` for more details)
900 /// However, the internal struct still represents a single ended iterator from
901 /// either end, and depending on pattern is also a valid double ended iterator,
902 /// so the two wrapper structs implement `Iterator`
903 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
904 /// to the complex impls seen above.
905 macro_rules! generate_pattern_iterators {
909 $(#[$forward_iterator_attribute:meta])*
910 struct $forward_iterator:ident;
914 $(#[$reverse_iterator_attribute:meta])*
915 struct $reverse_iterator:ident;
917 // Stability of all generated items
919 $(#[$common_stability_attribute:meta])*
921 // Internal almost-iterator that is being delegated to
923 $internal_iterator:ident yielding ($iterty:ty);
925 // Kind of delegation - either single ended or double ended
928 $(#[$forward_iterator_attribute])*
929 $(#[$common_stability_attribute])*
930 pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
932 $(#[$common_stability_attribute])*
933 impl<'a, P> fmt::Debug for $forward_iterator<'a, P>
935 P: Pattern<'a, Searcher: fmt::Debug>,
937 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
938 f.debug_tuple(stringify!($forward_iterator))
944 $(#[$common_stability_attribute])*
945 impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
949 fn next(&mut self) -> Option<$iterty> {
954 $(#[$common_stability_attribute])*
955 impl<'a, P> Clone for $forward_iterator<'a, P>
957 P: Pattern<'a, Searcher: Clone>,
959 fn clone(&self) -> Self {
960 $forward_iterator(self.0.clone())
964 $(#[$reverse_iterator_attribute])*
965 $(#[$common_stability_attribute])*
966 pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
968 $(#[$common_stability_attribute])*
969 impl<'a, P> fmt::Debug for $reverse_iterator<'a, P>
971 P: Pattern<'a, Searcher: fmt::Debug>,
973 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
974 f.debug_tuple(stringify!($reverse_iterator))
980 $(#[$common_stability_attribute])*
981 impl<'a, P> Iterator for $reverse_iterator<'a, P>
983 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
988 fn next(&mut self) -> Option<$iterty> {
993 $(#[$common_stability_attribute])*
994 impl<'a, P> Clone for $reverse_iterator<'a, P>
996 P: Pattern<'a, Searcher: Clone>,
998 fn clone(&self) -> Self {
999 $reverse_iterator(self.0.clone())
1003 #[stable(feature = "fused", since = "1.26.0")]
1004 impl<'a, P: Pattern<'a>> FusedIterator for $forward_iterator<'a, P> {}
1006 #[stable(feature = "fused", since = "1.26.0")]
1007 impl<'a, P> FusedIterator for $reverse_iterator<'a, P>
1009 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1012 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
1014 $reverse_iterator, $iterty);
1017 double ended; with $(#[$common_stability_attribute:meta])*,
1018 $forward_iterator:ident,
1019 $reverse_iterator:ident, $iterty:ty
1021 $(#[$common_stability_attribute])*
1022 impl<'a, P> DoubleEndedIterator for $forward_iterator<'a, P>
1024 P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>,
1027 fn next_back(&mut self) -> Option<$iterty> {
1032 $(#[$common_stability_attribute])*
1033 impl<'a, P> DoubleEndedIterator for $reverse_iterator<'a, P>
1035 P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>,
1038 fn next_back(&mut self) -> Option<$iterty> {
1044 single ended; with $(#[$common_stability_attribute:meta])*,
1045 $forward_iterator:ident,
1046 $reverse_iterator:ident, $iterty:ty
1050 derive_pattern_clone!{
1052 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
1055 struct SplitInternal<'a, P: Pattern<'a>> {
1058 matcher: P::Searcher,
1059 allow_trailing_empty: bool,
1063 impl<'a, P> fmt::Debug for SplitInternal<'a, P>
1065 P: Pattern<'a, Searcher: fmt::Debug>,
1067 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1068 f.debug_struct("SplitInternal")
1069 .field("start", &self.start)
1070 .field("end", &self.end)
1071 .field("matcher", &self.matcher)
1072 .field("allow_trailing_empty", &self.allow_trailing_empty)
1073 .field("finished", &self.finished)
1078 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
1080 fn get_end(&mut self) -> Option<&'a str> {
1081 if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
1082 self.finished = true;
1084 let string = self.matcher.haystack().get_unchecked(self.start..self.end);
1093 fn next(&mut self) -> Option<&'a str> {
1094 if self.finished { return None }
1096 let haystack = self.matcher.haystack();
1097 match self.matcher.next_match() {
1098 Some((a, b)) => unsafe {
1099 let elt = haystack.get_unchecked(self.start..a);
1103 None => self.get_end(),
1108 fn next_back(&mut self) -> Option<&'a str>
1109 where P::Searcher: ReverseSearcher<'a>
1111 if self.finished { return None }
1113 if !self.allow_trailing_empty {
1114 self.allow_trailing_empty = true;
1115 match self.next_back() {
1116 Some(elt) if !elt.is_empty() => return Some(elt),
1117 _ => if self.finished { return None }
1121 let haystack = self.matcher.haystack();
1122 match self.matcher.next_match_back() {
1123 Some((a, b)) => unsafe {
1124 let elt = haystack.get_unchecked(b..self.end);
1129 self.finished = true;
1130 Some(haystack.get_unchecked(self.start..self.end))
1136 generate_pattern_iterators! {
1138 /// Created with the method [`split`].
1140 /// [`split`]: ../../std/primitive.str.html#method.split
1143 /// Created with the method [`rsplit`].
1145 /// [`rsplit`]: ../../std/primitive.str.html#method.rsplit
1148 #[stable(feature = "rust1", since = "1.0.0")]
1150 SplitInternal yielding (&'a str);
1151 delegate double ended;
1154 generate_pattern_iterators! {
1156 /// Created with the method [`split_terminator`].
1158 /// [`split_terminator`]: ../../std/primitive.str.html#method.split_terminator
1159 struct SplitTerminator;
1161 /// Created with the method [`rsplit_terminator`].
1163 /// [`rsplit_terminator`]: ../../std/primitive.str.html#method.rsplit_terminator
1164 struct RSplitTerminator;
1166 #[stable(feature = "rust1", since = "1.0.0")]
1168 SplitInternal yielding (&'a str);
1169 delegate double ended;
1172 derive_pattern_clone!{
1173 clone SplitNInternal
1174 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
1177 struct SplitNInternal<'a, P: Pattern<'a>> {
1178 iter: SplitInternal<'a, P>,
1179 /// The number of splits remaining
1183 impl<'a, P> fmt::Debug for SplitNInternal<'a, P>
1185 P: Pattern<'a, Searcher: fmt::Debug>,
1187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1188 f.debug_struct("SplitNInternal")
1189 .field("iter", &self.iter)
1190 .field("count", &self.count)
1195 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
1197 fn next(&mut self) -> Option<&'a str> {
1200 1 => { self.count = 0; self.iter.get_end() }
1201 _ => { self.count -= 1; self.iter.next() }
1206 fn next_back(&mut self) -> Option<&'a str>
1207 where P::Searcher: ReverseSearcher<'a>
1211 1 => { self.count = 0; self.iter.get_end() }
1212 _ => { self.count -= 1; self.iter.next_back() }
1217 generate_pattern_iterators! {
1219 /// Created with the method [`splitn`].
1221 /// [`splitn`]: ../../std/primitive.str.html#method.splitn
1224 /// Created with the method [`rsplitn`].
1226 /// [`rsplitn`]: ../../std/primitive.str.html#method.rsplitn
1229 #[stable(feature = "rust1", since = "1.0.0")]
1231 SplitNInternal yielding (&'a str);
1232 delegate single ended;
1235 derive_pattern_clone!{
1236 clone MatchIndicesInternal
1237 with |s| MatchIndicesInternal(s.0.clone())
1240 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
1242 impl<'a, P> fmt::Debug for MatchIndicesInternal<'a, P>
1244 P: Pattern<'a, Searcher: fmt::Debug>,
1246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1247 f.debug_tuple("MatchIndicesInternal")
1253 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
1255 fn next(&mut self) -> Option<(usize, &'a str)> {
1256 self.0.next_match().map(|(start, end)| unsafe {
1257 (start, self.0.haystack().get_unchecked(start..end))
1262 fn next_back(&mut self) -> Option<(usize, &'a str)>
1263 where P::Searcher: ReverseSearcher<'a>
1265 self.0.next_match_back().map(|(start, end)| unsafe {
1266 (start, self.0.haystack().get_unchecked(start..end))
1271 generate_pattern_iterators! {
1273 /// Created with the method [`match_indices`].
1275 /// [`match_indices`]: ../../std/primitive.str.html#method.match_indices
1276 struct MatchIndices;
1278 /// Created with the method [`rmatch_indices`].
1280 /// [`rmatch_indices`]: ../../std/primitive.str.html#method.rmatch_indices
1281 struct RMatchIndices;
1283 #[stable(feature = "str_match_indices", since = "1.5.0")]
1285 MatchIndicesInternal yielding ((usize, &'a str));
1286 delegate double ended;
1289 derive_pattern_clone!{
1290 clone MatchesInternal
1291 with |s| MatchesInternal(s.0.clone())
1294 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
1296 impl<'a, P> fmt::Debug for MatchesInternal<'a, P>
1298 P: Pattern<'a, Searcher: fmt::Debug>,
1300 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1301 f.debug_tuple("MatchesInternal")
1307 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
1309 fn next(&mut self) -> Option<&'a str> {
1310 self.0.next_match().map(|(a, b)| unsafe {
1311 // Indices are known to be on utf8 boundaries
1312 self.0.haystack().get_unchecked(a..b)
1317 fn next_back(&mut self) -> Option<&'a str>
1318 where P::Searcher: ReverseSearcher<'a>
1320 self.0.next_match_back().map(|(a, b)| unsafe {
1321 // Indices are known to be on utf8 boundaries
1322 self.0.haystack().get_unchecked(a..b)
1327 generate_pattern_iterators! {
1329 /// Created with the method [`matches`].
1331 /// [`matches`]: ../../std/primitive.str.html#method.matches
1334 /// Created with the method [`rmatches`].
1336 /// [`rmatches`]: ../../std/primitive.str.html#method.rmatches
1339 #[stable(feature = "str_matches", since = "1.2.0")]
1341 MatchesInternal yielding (&'a str);
1342 delegate double ended;
1345 /// An iterator over the lines of a string, as string slices.
1347 /// This struct is created with the [`lines`] method on [`str`].
1348 /// See its documentation for more.
1350 /// [`lines`]: ../../std/primitive.str.html#method.lines
1351 /// [`str`]: ../../std/primitive.str.html
1352 #[stable(feature = "rust1", since = "1.0.0")]
1353 #[derive(Clone, Debug)]
1354 pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>);
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 impl<'a> Iterator for Lines<'a> {
1358 type Item = &'a str;
1361 fn next(&mut self) -> Option<&'a str> {
1366 fn size_hint(&self) -> (usize, Option<usize>) {
1371 fn last(mut self) -> Option<&'a str> {
1376 #[stable(feature = "rust1", since = "1.0.0")]
1377 impl<'a> DoubleEndedIterator for Lines<'a> {
1379 fn next_back(&mut self) -> Option<&'a str> {
1384 #[stable(feature = "fused", since = "1.26.0")]
1385 impl FusedIterator for Lines<'_> {}
1387 /// Created with the method [`lines_any`].
1389 /// [`lines_any`]: ../../std/primitive.str.html#method.lines_any
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 #[rustc_deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")]
1392 #[derive(Clone, Debug)]
1393 #[allow(deprecated)]
1394 pub struct LinesAny<'a>(Lines<'a>);
1397 /// A nameable, cloneable fn type
1399 struct LinesAnyMap impl<'a> Fn = |line: &'a str| -> &'a str {
1401 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 #[allow(deprecated)]
1408 impl<'a> Iterator for LinesAny<'a> {
1409 type Item = &'a str;
1412 fn next(&mut self) -> Option<&'a str> {
1417 fn size_hint(&self) -> (usize, Option<usize>) {
1422 #[stable(feature = "rust1", since = "1.0.0")]
1423 #[allow(deprecated)]
1424 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1426 fn next_back(&mut self) -> Option<&'a str> {
1431 #[stable(feature = "fused", since = "1.26.0")]
1432 #[allow(deprecated)]
1433 impl FusedIterator for LinesAny<'_> {}
1436 Section: UTF-8 validation
1439 // use truncation to fit u64 into usize
1440 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
1442 /// Returns `true` if any byte in the word `x` is nonascii (>= 128).
1444 fn contains_nonascii(x: usize) -> bool {
1445 (x & NONASCII_MASK) != 0
1448 /// Walks through `v` checking that it's a valid UTF-8 sequence,
1449 /// returning `Ok(())` in that case, or, if it is invalid, `Err(err)`.
1451 fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
1455 let usize_bytes = mem::size_of::<usize>();
1456 let ascii_block_size = 2 * usize_bytes;
1457 let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
1458 let align = v.as_ptr().align_offset(usize_bytes);
1461 let old_offset = index;
1463 ($error_len: expr) => {
1464 return Err(Utf8Error {
1465 valid_up_to: old_offset,
1466 error_len: $error_len,
1471 macro_rules! next { () => {{
1473 // we needed data, but there was none: error!
1480 let first = v[index];
1482 let w = UTF8_CHAR_WIDTH[first as usize];
1483 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
1484 // first C2 80 last DF BF
1485 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
1486 // first E0 A0 80 last EF BF BF
1487 // excluding surrogates codepoints \u{d800} to \u{dfff}
1488 // ED A0 80 to ED BF BF
1489 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1490 // first F0 90 80 80 last F4 8F BF BF
1492 // Use the UTF-8 syntax from the RFC
1494 // https://tools.ietf.org/html/rfc3629
1496 // UTF8-2 = %xC2-DF UTF8-tail
1497 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1498 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1499 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1500 // %xF4 %x80-8F 2( UTF8-tail )
1502 2 => if next!() & !CONT_MASK != TAG_CONT_U8 {
1506 match (first, next!()) {
1507 (0xE0 , 0xA0 ..= 0xBF) |
1508 (0xE1 ..= 0xEC, 0x80 ..= 0xBF) |
1509 (0xED , 0x80 ..= 0x9F) |
1510 (0xEE ..= 0xEF, 0x80 ..= 0xBF) => {}
1513 if next!() & !CONT_MASK != TAG_CONT_U8 {
1518 match (first, next!()) {
1519 (0xF0 , 0x90 ..= 0xBF) |
1520 (0xF1 ..= 0xF3, 0x80 ..= 0xBF) |
1521 (0xF4 , 0x80 ..= 0x8F) => {}
1524 if next!() & !CONT_MASK != TAG_CONT_U8 {
1527 if next!() & !CONT_MASK != TAG_CONT_U8 {
1535 // Ascii case, try to skip forward quickly.
1536 // When the pointer is aligned, read 2 words of data per iteration
1537 // until we find a word containing a non-ascii byte.
1538 if align != usize::max_value() && align.wrapping_sub(index) % usize_bytes == 0 {
1539 let ptr = v.as_ptr();
1540 while index < blocks_end {
1542 let block = ptr.add(index) as *const usize;
1543 // break if there is a nonascii byte
1544 let zu = contains_nonascii(*block);
1545 let zv = contains_nonascii(*block.offset(1));
1550 index += ascii_block_size;
1552 // step from the point where the wordwise loop stopped
1553 while index < len && v[index] < 128 {
1565 // https://tools.ietf.org/html/rfc3629
1566 static UTF8_CHAR_WIDTH: [u8; 256] = [
1567 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1568 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1569 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1570 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1571 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1572 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1573 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1574 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1575 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1576 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1577 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1578 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1579 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1580 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1581 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1582 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1585 /// Given a first byte, determines how many bytes are in this UTF-8 character.
1586 #[unstable(feature = "str_internals", issue = "0")]
1588 pub fn utf8_char_width(b: u8) -> usize {
1589 UTF8_CHAR_WIDTH[b as usize] as usize
1592 /// Mask of the value bits of a continuation byte.
1593 const CONT_MASK: u8 = 0b0011_1111;
1594 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte.
1595 const TAG_CONT_U8: u8 = 0b1000_0000;
1598 Section: Trait implementations
1602 use crate::cmp::Ordering;
1604 use crate::slice::{self, SliceIndex};
1606 /// Implements ordering of strings.
1608 /// Strings are ordered lexicographically by their byte values. This orders Unicode code
1609 /// points based on their positions in the code charts. This is not necessarily the same as
1610 /// "alphabetical" order, which varies by language and locale. Sorting strings according to
1611 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1613 #[stable(feature = "rust1", since = "1.0.0")]
1616 fn cmp(&self, other: &str) -> Ordering {
1617 self.as_bytes().cmp(other.as_bytes())
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 impl PartialEq for str {
1624 fn eq(&self, other: &str) -> bool {
1625 self.as_bytes() == other.as_bytes()
1628 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1631 #[stable(feature = "rust1", since = "1.0.0")]
1634 /// Implements comparison operations on strings.
1636 /// Strings are compared lexicographically by their byte values. This compares Unicode code
1637 /// points based on their positions in the code charts. This is not necessarily the same as
1638 /// "alphabetical" order, which varies by language and locale. Comparing strings according to
1639 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1641 #[stable(feature = "rust1", since = "1.0.0")]
1642 impl PartialOrd for str {
1644 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1645 Some(self.cmp(other))
1649 #[stable(feature = "rust1", since = "1.0.0")]
1650 impl<I> ops::Index<I> for str
1654 type Output = I::Output;
1657 fn index(&self, index: I) -> &I::Output {
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 impl<I> ops::IndexMut<I> for str
1668 fn index_mut(&mut self, index: I) -> &mut I::Output {
1669 index.index_mut(self)
1675 fn str_index_overflow_fail() -> ! {
1676 panic!("attempted to index str up to maximum usize");
1679 /// Implements substring slicing with syntax `&self[..]` or `&mut self[..]`.
1681 /// Returns a slice of the whole string, i.e., returns `&self` or `&mut
1682 /// self`. Equivalent to `&self[0 .. len]` or `&mut self[0 .. len]`. Unlike
1683 /// other indexing operations, this can never panic.
1685 /// This operation is `O(1)`.
1687 /// Prior to 1.20.0, these indexing operations were still supported by
1688 /// direct implementation of `Index` and `IndexMut`.
1690 /// Equivalent to `&self[0 .. len]` or `&mut self[0 .. len]`.
1691 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1692 impl SliceIndex<str> for ops::RangeFull {
1695 fn get(self, slice: &str) -> Option<&Self::Output> {
1699 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1703 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1707 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1711 fn index(self, slice: &str) -> &Self::Output {
1715 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1720 /// Implements substring slicing with syntax `&self[begin .. end]` or `&mut
1721 /// self[begin .. end]`.
1723 /// Returns a slice of the given string from the byte range
1724 /// [`begin`, `end`).
1726 /// This operation is `O(1)`.
1728 /// Prior to 1.20.0, these indexing operations were still supported by
1729 /// direct implementation of `Index` and `IndexMut`.
1733 /// Panics if `begin` or `end` does not point to the starting byte offset of
1734 /// a character (as defined by `is_char_boundary`), if `begin > end`, or if
1740 /// let s = "Löwe 老虎 Léopard";
1741 /// assert_eq!(&s[0 .. 1], "L");
1743 /// assert_eq!(&s[1 .. 9], "öwe 老");
1745 /// // these will panic:
1746 /// // byte 2 lies within `ö`:
1749 /// // byte 8 lies within `老`
1752 /// // byte 100 is outside the string
1753 /// // &s[3 .. 100];
1755 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1756 impl SliceIndex<str> for ops::Range<usize> {
1759 fn get(self, slice: &str) -> Option<&Self::Output> {
1760 if self.start <= self.end &&
1761 slice.is_char_boundary(self.start) &&
1762 slice.is_char_boundary(self.end) {
1763 Some(unsafe { self.get_unchecked(slice) })
1769 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1770 if self.start <= self.end &&
1771 slice.is_char_boundary(self.start) &&
1772 slice.is_char_boundary(self.end) {
1773 Some(unsafe { self.get_unchecked_mut(slice) })
1779 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1780 let ptr = slice.as_ptr().add(self.start);
1781 let len = self.end - self.start;
1782 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1785 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1786 let ptr = slice.as_mut_ptr().add(self.start);
1787 let len = self.end - self.start;
1788 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, len))
1791 fn index(self, slice: &str) -> &Self::Output {
1792 let (start, end) = (self.start, self.end);
1793 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1796 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1797 // is_char_boundary checks that the index is in [0, .len()]
1798 // cannot reuse `get` as above, because of NLL trouble
1799 if self.start <= self.end &&
1800 slice.is_char_boundary(self.start) &&
1801 slice.is_char_boundary(self.end) {
1802 unsafe { self.get_unchecked_mut(slice) }
1804 super::slice_error_fail(slice, self.start, self.end)
1809 /// Implements substring slicing with syntax `&self[.. end]` or `&mut
1812 /// Returns a slice of the given string from the byte range [`0`, `end`).
1813 /// Equivalent to `&self[0 .. end]` or `&mut self[0 .. end]`.
1815 /// This operation is `O(1)`.
1817 /// Prior to 1.20.0, these indexing operations were still supported by
1818 /// direct implementation of `Index` and `IndexMut`.
1822 /// Panics if `end` does not point to the starting byte offset of a
1823 /// character (as defined by `is_char_boundary`), or if `end > len`.
1824 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1825 impl SliceIndex<str> for ops::RangeTo<usize> {
1828 fn get(self, slice: &str) -> Option<&Self::Output> {
1829 if slice.is_char_boundary(self.end) {
1830 Some(unsafe { self.get_unchecked(slice) })
1836 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1837 if slice.is_char_boundary(self.end) {
1838 Some(unsafe { self.get_unchecked_mut(slice) })
1844 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1845 let ptr = slice.as_ptr();
1846 super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end))
1849 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1850 let ptr = slice.as_mut_ptr();
1851 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, self.end))
1854 fn index(self, slice: &str) -> &Self::Output {
1856 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end))
1859 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1860 // is_char_boundary checks that the index is in [0, .len()]
1861 if slice.is_char_boundary(self.end) {
1862 unsafe { self.get_unchecked_mut(slice) }
1864 super::slice_error_fail(slice, 0, self.end)
1869 /// Implements substring slicing with syntax `&self[begin ..]` or `&mut
1870 /// self[begin ..]`.
1872 /// Returns a slice of the given string from the byte range [`begin`,
1873 /// `len`). Equivalent to `&self[begin .. len]` or `&mut self[begin ..
1876 /// This operation is `O(1)`.
1878 /// Prior to 1.20.0, these indexing operations were still supported by
1879 /// direct implementation of `Index` and `IndexMut`.
1883 /// Panics if `begin` does not point to the starting byte offset of
1884 /// a character (as defined by `is_char_boundary`), or if `begin >= len`.
1885 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1886 impl SliceIndex<str> for ops::RangeFrom<usize> {
1889 fn get(self, slice: &str) -> Option<&Self::Output> {
1890 if slice.is_char_boundary(self.start) {
1891 Some(unsafe { self.get_unchecked(slice) })
1897 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1898 if slice.is_char_boundary(self.start) {
1899 Some(unsafe { self.get_unchecked_mut(slice) })
1905 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1906 let ptr = slice.as_ptr().add(self.start);
1907 let len = slice.len() - self.start;
1908 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1911 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1912 let ptr = slice.as_mut_ptr().add(self.start);
1913 let len = slice.len() - self.start;
1914 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, len))
1917 fn index(self, slice: &str) -> &Self::Output {
1918 let (start, end) = (self.start, slice.len());
1919 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1922 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1923 // is_char_boundary checks that the index is in [0, .len()]
1924 if slice.is_char_boundary(self.start) {
1925 unsafe { self.get_unchecked_mut(slice) }
1927 super::slice_error_fail(slice, self.start, slice.len())
1932 /// Implements substring slicing with syntax `&self[begin ..= end]` or `&mut
1933 /// self[begin ..= end]`.
1935 /// Returns a slice of the given string from the byte range
1936 /// [`begin`, `end`]. Equivalent to `&self [begin .. end + 1]` or `&mut
1937 /// self[begin .. end + 1]`, except if `end` has the maximum value for
1940 /// This operation is `O(1)`.
1944 /// Panics if `begin` does not point to the starting byte offset of
1945 /// a character (as defined by `is_char_boundary`), if `end` does not point
1946 /// to the ending byte offset of a character (`end + 1` is either a starting
1947 /// byte offset or equal to `len`), if `begin > end`, or if `end >= len`.
1948 #[stable(feature = "inclusive_range", since = "1.26.0")]
1949 impl SliceIndex<str> for ops::RangeInclusive<usize> {
1952 fn get(self, slice: &str) -> Option<&Self::Output> {
1953 if *self.end() == usize::max_value() { None }
1954 else { (*self.start()..self.end()+1).get(slice) }
1957 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1958 if *self.end() == usize::max_value() { None }
1959 else { (*self.start()..self.end()+1).get_mut(slice) }
1962 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1963 (*self.start()..self.end()+1).get_unchecked(slice)
1966 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1967 (*self.start()..self.end()+1).get_unchecked_mut(slice)
1970 fn index(self, slice: &str) -> &Self::Output {
1971 if *self.end() == usize::max_value() { str_index_overflow_fail(); }
1972 (*self.start()..self.end()+1).index(slice)
1975 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1976 if *self.end() == usize::max_value() { str_index_overflow_fail(); }
1977 (*self.start()..self.end()+1).index_mut(slice)
1981 /// Implements substring slicing with syntax `&self[..= end]` or `&mut
1984 /// Returns a slice of the given string from the byte range [0, `end`].
1985 /// Equivalent to `&self [0 .. end + 1]`, except if `end` has the maximum
1986 /// value for `usize`.
1988 /// This operation is `O(1)`.
1992 /// Panics if `end` does not point to the ending byte offset of a character
1993 /// (`end + 1` is either a starting byte offset as defined by
1994 /// `is_char_boundary`, or equal to `len`), or if `end >= len`.
1995 #[stable(feature = "inclusive_range", since = "1.26.0")]
1996 impl SliceIndex<str> for ops::RangeToInclusive<usize> {
1999 fn get(self, slice: &str) -> Option<&Self::Output> {
2000 if self.end == usize::max_value() { None }
2001 else { (..self.end+1).get(slice) }
2004 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
2005 if self.end == usize::max_value() { None }
2006 else { (..self.end+1).get_mut(slice) }
2009 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
2010 (..self.end+1).get_unchecked(slice)
2013 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
2014 (..self.end+1).get_unchecked_mut(slice)
2017 fn index(self, slice: &str) -> &Self::Output {
2018 if self.end == usize::max_value() { str_index_overflow_fail(); }
2019 (..self.end+1).index(slice)
2022 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
2023 if self.end == usize::max_value() { str_index_overflow_fail(); }
2024 (..self.end+1).index_mut(slice)
2029 // truncate `&str` to length at most equal to `max`
2030 // return `true` if it were truncated, and the new str.
2031 fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
2035 while !s.is_char_boundary(max) {
2044 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
2045 const MAX_DISPLAY_LENGTH: usize = 256;
2046 let (truncated, s_trunc) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
2047 let ellipsis = if truncated { "[...]" } else { "" };
2050 if begin > s.len() || end > s.len() {
2051 let oob_index = if begin > s.len() { begin } else { end };
2052 panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
2056 assert!(begin <= end, "begin <= end ({} <= {}) when slicing `{}`{}",
2057 begin, end, s_trunc, ellipsis);
2059 // 3. character boundary
2060 let index = if !s.is_char_boundary(begin) { begin } else { end };
2061 // find the character
2062 let mut char_start = index;
2063 while !s.is_char_boundary(char_start) {
2066 // `char_start` must be less than len and a char boundary
2067 let ch = s[char_start..].chars().next().unwrap();
2068 let char_range = char_start .. char_start + ch.len_utf8();
2069 panic!("byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
2070 index, ch, char_range, s_trunc, ellipsis);
2076 /// Returns the length of `self`.
2078 /// This length is in bytes, not [`char`]s or graphemes. In other words,
2079 /// it may not be what a human considers the length of the string.
2086 /// let len = "foo".len();
2087 /// assert_eq!(3, len);
2089 /// assert_eq!("ƒoo".len(), 4); // fancy f!
2090 /// assert_eq!("ƒoo".chars().count(), 3);
2092 #[stable(feature = "rust1", since = "1.0.0")]
2093 #[cfg_attr(not(bootstrap), rustc_const_stable(feature = "const_str_len", since = "1.32.0"))]
2095 pub const fn len(&self) -> usize {
2096 self.as_bytes().len()
2099 /// Returns `true` if `self` has a length of zero bytes.
2107 /// assert!(s.is_empty());
2109 /// let s = "not empty";
2110 /// assert!(!s.is_empty());
2113 #[stable(feature = "rust1", since = "1.0.0")]
2116 rustc_const_stable(feature = "const_str_is_empty", since = "1.32.0"),
2118 pub const fn is_empty(&self) -> bool {
2122 /// Checks that `index`-th byte lies at the start and/or end of a
2123 /// UTF-8 code point sequence.
2125 /// The start and end of the string (when `index == self.len()`) are
2126 /// considered to be
2129 /// Returns `false` if `index` is greater than `self.len()`.
2134 /// let s = "Löwe 老虎 Léopard";
2135 /// assert!(s.is_char_boundary(0));
2137 /// assert!(s.is_char_boundary(6));
2138 /// assert!(s.is_char_boundary(s.len()));
2140 /// // second byte of `ö`
2141 /// assert!(!s.is_char_boundary(2));
2143 /// // third byte of `老`
2144 /// assert!(!s.is_char_boundary(8));
2146 #[stable(feature = "is_char_boundary", since = "1.9.0")]
2148 pub fn is_char_boundary(&self, index: usize) -> bool {
2149 // 0 and len are always ok.
2150 // Test for 0 explicitly so that it can optimize out the check
2151 // easily and skip reading string data for that case.
2152 if index == 0 || index == self.len() { return true; }
2153 match self.as_bytes().get(index) {
2155 // This is bit magic equivalent to: b < 128 || b >= 192
2156 Some(&b) => (b as i8) >= -0x40,
2160 /// Converts a string slice to a byte slice. To convert the byte slice back
2161 /// into a string slice, use the [`str::from_utf8`] function.
2163 /// [`str::from_utf8`]: ./str/fn.from_utf8.html
2170 /// let bytes = "bors".as_bytes();
2171 /// assert_eq!(b"bors", bytes);
2173 #[stable(feature = "rust1", since = "1.0.0")]
2174 #[cfg_attr(not(bootstrap), rustc_const_stable(feature = "str_as_bytes", since = "1.32.0"))]
2176 // SAFETY: const sound because we transmute two types with the same layout
2177 #[allow(unused_attributes)]
2178 #[allow_internal_unstable(const_fn_union)]
2179 pub const fn as_bytes(&self) -> &[u8] {
2185 unsafe { Slices { str: self }.slice }
2188 /// Converts a mutable string slice to a mutable byte slice. To convert the
2189 /// mutable byte slice back into a mutable string slice, use the
2190 /// [`str::from_utf8_mut`] function.
2192 /// [`str::from_utf8_mut`]: ./str/fn.from_utf8_mut.html
2199 /// let mut s = String::from("Hello");
2200 /// let bytes = unsafe { s.as_bytes_mut() };
2202 /// assert_eq!(b"Hello", bytes);
2208 /// let mut s = String::from("🗻∈🌏");
2211 /// let bytes = s.as_bytes_mut();
2213 /// bytes[0] = 0xF0;
2214 /// bytes[1] = 0x9F;
2215 /// bytes[2] = 0x8D;
2216 /// bytes[3] = 0x94;
2219 /// assert_eq!("🍔∈🌏", s);
2221 #[stable(feature = "str_mut_extras", since = "1.20.0")]
2223 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
2224 &mut *(self as *mut str as *mut [u8])
2227 /// Converts a string slice to a raw pointer.
2229 /// As string slices are a slice of bytes, the raw pointer points to a
2230 /// [`u8`]. This pointer will be pointing to the first byte of the string
2233 /// The caller must ensure that the returned pointer is never written to.
2234 /// If you need to mutate the contents of the string slice, use [`as_mut_ptr`].
2236 /// [`u8`]: primitive.u8.html
2237 /// [`as_mut_ptr`]: #method.as_mut_ptr
2244 /// let s = "Hello";
2245 /// let ptr = s.as_ptr();
2247 #[stable(feature = "rust1", since = "1.0.0")]
2248 #[cfg_attr(not(bootstrap), rustc_const_stable(feature = "rustc_str_as_ptr", since = "1.32.0"))]
2250 pub const fn as_ptr(&self) -> *const u8 {
2251 self as *const str as *const u8
2254 /// Converts a mutable string slice to a raw pointer.
2256 /// As string slices are a slice of bytes, the raw pointer points to a
2257 /// [`u8`]. This pointer will be pointing to the first byte of the string
2260 /// It is your responsibility to make sure that the string slice only gets
2261 /// modified in a way that it remains valid UTF-8.
2263 /// [`u8`]: primitive.u8.html
2264 #[stable(feature = "str_as_mut_ptr", since = "1.36.0")]
2266 pub fn as_mut_ptr(&mut self) -> *mut u8 {
2267 self as *mut str as *mut u8
2270 /// Returns a subslice of `str`.
2272 /// This is the non-panicking alternative to indexing the `str`. Returns
2273 /// [`None`] whenever equivalent indexing operation would panic.
2275 /// [`None`]: option/enum.Option.html#variant.None
2280 /// let v = String::from("🗻∈🌏");
2282 /// assert_eq!(Some("🗻"), v.get(0..4));
2284 /// // indices not on UTF-8 sequence boundaries
2285 /// assert!(v.get(1..).is_none());
2286 /// assert!(v.get(..8).is_none());
2288 /// // out of bounds
2289 /// assert!(v.get(..42).is_none());
2291 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2293 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
2297 /// Returns a mutable subslice of `str`.
2299 /// This is the non-panicking alternative to indexing the `str`. Returns
2300 /// [`None`] whenever equivalent indexing operation would panic.
2302 /// [`None`]: option/enum.Option.html#variant.None
2307 /// let mut v = String::from("hello");
2308 /// // correct length
2309 /// assert!(v.get_mut(0..5).is_some());
2310 /// // out of bounds
2311 /// assert!(v.get_mut(..42).is_none());
2312 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
2314 /// assert_eq!("hello", v);
2316 /// let s = v.get_mut(0..2);
2317 /// let s = s.map(|s| {
2318 /// s.make_ascii_uppercase();
2321 /// assert_eq!(Some("HE"), s);
2323 /// assert_eq!("HEllo", v);
2325 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2327 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
2331 /// Returns a unchecked subslice of `str`.
2333 /// This is the unchecked alternative to indexing the `str`.
2337 /// Callers of this function are responsible that these preconditions are
2340 /// * The starting index must come before the ending index;
2341 /// * Indexes must be within bounds of the original slice;
2342 /// * Indexes must lie on UTF-8 sequence boundaries.
2344 /// Failing that, the returned string slice may reference invalid memory or
2345 /// violate the invariants communicated by the `str` type.
2352 /// assert_eq!("🗻", v.get_unchecked(0..4));
2353 /// assert_eq!("∈", v.get_unchecked(4..7));
2354 /// assert_eq!("🌏", v.get_unchecked(7..11));
2357 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2359 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
2360 i.get_unchecked(self)
2363 /// Returns a mutable, unchecked subslice of `str`.
2365 /// This is the unchecked alternative to indexing the `str`.
2369 /// Callers of this function are responsible that these preconditions are
2372 /// * The starting index must come before the ending index;
2373 /// * Indexes must be within bounds of the original slice;
2374 /// * Indexes must lie on UTF-8 sequence boundaries.
2376 /// Failing that, the returned string slice may reference invalid memory or
2377 /// violate the invariants communicated by the `str` type.
2382 /// let mut v = String::from("🗻∈🌏");
2384 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
2385 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
2386 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
2389 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2391 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
2392 i.get_unchecked_mut(self)
2395 /// Creates a string slice from another string slice, bypassing safety
2398 /// This is generally not recommended, use with caution! For a safe
2399 /// alternative see [`str`] and [`Index`].
2401 /// [`str`]: primitive.str.html
2402 /// [`Index`]: ops/trait.Index.html
2404 /// This new slice goes from `begin` to `end`, including `begin` but
2405 /// excluding `end`.
2407 /// To get a mutable string slice instead, see the
2408 /// [`slice_mut_unchecked`] method.
2410 /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
2414 /// Callers of this function are responsible that three preconditions are
2417 /// * `begin` must come before `end`.
2418 /// * `begin` and `end` must be byte positions within the string slice.
2419 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2426 /// let s = "Löwe 老虎 Léopard";
2429 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
2432 /// let s = "Hello, world!";
2435 /// assert_eq!("world", s.slice_unchecked(7, 12));
2438 #[stable(feature = "rust1", since = "1.0.0")]
2439 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked(begin..end)` instead")]
2441 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
2442 (begin..end).get_unchecked(self)
2445 /// Creates a string slice from another string slice, bypassing safety
2447 /// This is generally not recommended, use with caution! For a safe
2448 /// alternative see [`str`] and [`IndexMut`].
2450 /// [`str`]: primitive.str.html
2451 /// [`IndexMut`]: ops/trait.IndexMut.html
2453 /// This new slice goes from `begin` to `end`, including `begin` but
2454 /// excluding `end`.
2456 /// To get an immutable string slice instead, see the
2457 /// [`slice_unchecked`] method.
2459 /// [`slice_unchecked`]: #method.slice_unchecked
2463 /// Callers of this function are responsible that three preconditions are
2466 /// * `begin` must come before `end`.
2467 /// * `begin` and `end` must be byte positions within the string slice.
2468 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2469 #[stable(feature = "str_slice_mut", since = "1.5.0")]
2470 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked_mut(begin..end)` instead")]
2472 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
2473 (begin..end).get_unchecked_mut(self)
2476 /// Divide one string slice into two at an index.
2478 /// The argument, `mid`, should be a byte offset from the start of the
2479 /// string. It must also be on the boundary of a UTF-8 code point.
2481 /// The two slices returned go from the start of the string slice to `mid`,
2482 /// and from `mid` to the end of the string slice.
2484 /// To get mutable string slices instead, see the [`split_at_mut`]
2487 /// [`split_at_mut`]: #method.split_at_mut
2491 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2492 /// beyond the last code point of the string slice.
2499 /// let s = "Per Martin-Löf";
2501 /// let (first, last) = s.split_at(3);
2503 /// assert_eq!("Per", first);
2504 /// assert_eq!(" Martin-Löf", last);
2507 #[stable(feature = "str_split_at", since = "1.4.0")]
2508 pub fn split_at(&self, mid: usize) -> (&str, &str) {
2509 // is_char_boundary checks that the index is in [0, .len()]
2510 if self.is_char_boundary(mid) {
2512 (self.get_unchecked(0..mid),
2513 self.get_unchecked(mid..self.len()))
2516 slice_error_fail(self, 0, mid)
2520 /// Divide one mutable string slice into two at an index.
2522 /// The argument, `mid`, should be a byte offset from the start of the
2523 /// string. It must also be on the boundary of a UTF-8 code point.
2525 /// The two slices returned go from the start of the string slice to `mid`,
2526 /// and from `mid` to the end of the string slice.
2528 /// To get immutable string slices instead, see the [`split_at`] method.
2530 /// [`split_at`]: #method.split_at
2534 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2535 /// beyond the last code point of the string slice.
2542 /// let mut s = "Per Martin-Löf".to_string();
2544 /// let (first, last) = s.split_at_mut(3);
2545 /// first.make_ascii_uppercase();
2546 /// assert_eq!("PER", first);
2547 /// assert_eq!(" Martin-Löf", last);
2549 /// assert_eq!("PER Martin-Löf", s);
2552 #[stable(feature = "str_split_at", since = "1.4.0")]
2553 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
2554 // is_char_boundary checks that the index is in [0, .len()]
2555 if self.is_char_boundary(mid) {
2556 let len = self.len();
2557 let ptr = self.as_mut_ptr();
2559 (from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
2560 from_utf8_unchecked_mut(slice::from_raw_parts_mut(
2566 slice_error_fail(self, 0, mid)
2570 /// Returns an iterator over the [`char`]s of a string slice.
2572 /// As a string slice consists of valid UTF-8, we can iterate through a
2573 /// string slice by [`char`]. This method returns such an iterator.
2575 /// It's important to remember that [`char`] represents a Unicode Scalar
2576 /// Value, and may not match your idea of what a 'character' is. Iteration
2577 /// over grapheme clusters may be what you actually want.
2584 /// let word = "goodbye";
2586 /// let count = word.chars().count();
2587 /// assert_eq!(7, count);
2589 /// let mut chars = word.chars();
2591 /// assert_eq!(Some('g'), chars.next());
2592 /// assert_eq!(Some('o'), chars.next());
2593 /// assert_eq!(Some('o'), chars.next());
2594 /// assert_eq!(Some('d'), chars.next());
2595 /// assert_eq!(Some('b'), chars.next());
2596 /// assert_eq!(Some('y'), chars.next());
2597 /// assert_eq!(Some('e'), chars.next());
2599 /// assert_eq!(None, chars.next());
2602 /// Remember, [`char`]s may not match your human intuition about characters:
2607 /// let mut chars = y.chars();
2609 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
2610 /// assert_eq!(Some('\u{0306}'), chars.next());
2612 /// assert_eq!(None, chars.next());
2614 #[stable(feature = "rust1", since = "1.0.0")]
2616 pub fn chars(&self) -> Chars<'_> {
2617 Chars{iter: self.as_bytes().iter()}
2620 /// Returns an iterator over the [`char`]s of a string slice, and their
2623 /// As a string slice consists of valid UTF-8, we can iterate through a
2624 /// string slice by [`char`]. This method returns an iterator of both
2625 /// these [`char`]s, as well as their byte positions.
2627 /// The iterator yields tuples. The position is first, the [`char`] is
2635 /// let word = "goodbye";
2637 /// let count = word.char_indices().count();
2638 /// assert_eq!(7, count);
2640 /// let mut char_indices = word.char_indices();
2642 /// assert_eq!(Some((0, 'g')), char_indices.next());
2643 /// assert_eq!(Some((1, 'o')), char_indices.next());
2644 /// assert_eq!(Some((2, 'o')), char_indices.next());
2645 /// assert_eq!(Some((3, 'd')), char_indices.next());
2646 /// assert_eq!(Some((4, 'b')), char_indices.next());
2647 /// assert_eq!(Some((5, 'y')), char_indices.next());
2648 /// assert_eq!(Some((6, 'e')), char_indices.next());
2650 /// assert_eq!(None, char_indices.next());
2653 /// Remember, [`char`]s may not match your human intuition about characters:
2656 /// let yes = "y̆es";
2658 /// let mut char_indices = yes.char_indices();
2660 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
2661 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
2663 /// // note the 3 here - the last character took up two bytes
2664 /// assert_eq!(Some((3, 'e')), char_indices.next());
2665 /// assert_eq!(Some((4, 's')), char_indices.next());
2667 /// assert_eq!(None, char_indices.next());
2669 #[stable(feature = "rust1", since = "1.0.0")]
2671 pub fn char_indices(&self) -> CharIndices<'_> {
2672 CharIndices { front_offset: 0, iter: self.chars() }
2675 /// An iterator over the bytes of a string slice.
2677 /// As a string slice consists of a sequence of bytes, we can iterate
2678 /// through a string slice by byte. This method returns such an iterator.
2685 /// let mut bytes = "bors".bytes();
2687 /// assert_eq!(Some(b'b'), bytes.next());
2688 /// assert_eq!(Some(b'o'), bytes.next());
2689 /// assert_eq!(Some(b'r'), bytes.next());
2690 /// assert_eq!(Some(b's'), bytes.next());
2692 /// assert_eq!(None, bytes.next());
2694 #[stable(feature = "rust1", since = "1.0.0")]
2696 pub fn bytes(&self) -> Bytes<'_> {
2697 Bytes(self.as_bytes().iter().cloned())
2700 /// Splits a string slice by whitespace.
2702 /// The iterator returned will return string slices that are sub-slices of
2703 /// the original string slice, separated by any amount of whitespace.
2705 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2706 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
2707 /// instead, use [`split_ascii_whitespace`].
2709 /// [`split_ascii_whitespace`]: #method.split_ascii_whitespace
2716 /// let mut iter = "A few words".split_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 whitespace are considered:
2728 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_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_whitespace", since = "1.1.0")]
2739 pub fn split_whitespace(&self) -> SplitWhitespace<'_> {
2740 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
2743 /// Splits a string slice by ASCII whitespace.
2745 /// The iterator returned will return string slices that are sub-slices of
2746 /// the original string slice, separated by any amount of ASCII whitespace.
2748 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
2750 /// [`split_whitespace`]: #method.split_whitespace
2757 /// let mut iter = "A few words".split_ascii_whitespace();
2759 /// assert_eq!(Some("A"), iter.next());
2760 /// assert_eq!(Some("few"), iter.next());
2761 /// assert_eq!(Some("words"), iter.next());
2763 /// assert_eq!(None, iter.next());
2766 /// All kinds of ASCII whitespace are considered:
2769 /// let mut iter = " Mary had\ta little \n\t lamb".split_ascii_whitespace();
2770 /// assert_eq!(Some("Mary"), iter.next());
2771 /// assert_eq!(Some("had"), iter.next());
2772 /// assert_eq!(Some("a"), iter.next());
2773 /// assert_eq!(Some("little"), iter.next());
2774 /// assert_eq!(Some("lamb"), iter.next());
2776 /// assert_eq!(None, iter.next());
2778 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
2780 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> {
2783 .split(IsAsciiWhitespace)
2784 .filter(BytesIsNotEmpty)
2785 .map(UnsafeBytesToStr);
2786 SplitAsciiWhitespace { inner }
2789 /// An iterator over the lines of a string, as string slices.
2791 /// Lines are ended with either a newline (`\n`) or a carriage return with
2792 /// a line feed (`\r\n`).
2794 /// The final line ending is optional.
2801 /// let text = "foo\r\nbar\n\nbaz\n";
2802 /// let mut lines = text.lines();
2804 /// assert_eq!(Some("foo"), lines.next());
2805 /// assert_eq!(Some("bar"), lines.next());
2806 /// assert_eq!(Some(""), lines.next());
2807 /// assert_eq!(Some("baz"), lines.next());
2809 /// assert_eq!(None, lines.next());
2812 /// The final line ending isn't required:
2815 /// let text = "foo\nbar\n\r\nbaz";
2816 /// let mut lines = text.lines();
2818 /// assert_eq!(Some("foo"), lines.next());
2819 /// assert_eq!(Some("bar"), lines.next());
2820 /// assert_eq!(Some(""), lines.next());
2821 /// assert_eq!(Some("baz"), lines.next());
2823 /// assert_eq!(None, lines.next());
2825 #[stable(feature = "rust1", since = "1.0.0")]
2827 pub fn lines(&self) -> Lines<'_> {
2828 Lines(self.split_terminator('\n').map(LinesAnyMap))
2831 /// An iterator over the lines of a string.
2832 #[stable(feature = "rust1", since = "1.0.0")]
2833 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
2835 #[allow(deprecated)]
2836 pub fn lines_any(&self) -> LinesAny<'_> {
2837 LinesAny(self.lines())
2840 /// Returns an iterator of `u16` over the string encoded as UTF-16.
2847 /// let text = "Zażółć gęślą jaźń";
2849 /// let utf8_len = text.len();
2850 /// let utf16_len = text.encode_utf16().count();
2852 /// assert!(utf16_len <= utf8_len);
2854 #[stable(feature = "encode_utf16", since = "1.8.0")]
2855 pub fn encode_utf16(&self) -> EncodeUtf16<'_> {
2856 EncodeUtf16 { chars: self.chars(), extra: 0 }
2859 /// Returns `true` if the given pattern matches a sub-slice of
2860 /// this string slice.
2862 /// Returns `false` if it does not.
2869 /// let bananas = "bananas";
2871 /// assert!(bananas.contains("nana"));
2872 /// assert!(!bananas.contains("apples"));
2874 #[stable(feature = "rust1", since = "1.0.0")]
2876 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2877 pat.is_contained_in(self)
2880 /// Returns `true` if the given pattern matches a prefix of this
2883 /// Returns `false` if it does not.
2890 /// let bananas = "bananas";
2892 /// assert!(bananas.starts_with("bana"));
2893 /// assert!(!bananas.starts_with("nana"));
2895 #[stable(feature = "rust1", since = "1.0.0")]
2896 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2897 pat.is_prefix_of(self)
2900 /// Returns `true` if the given pattern matches a suffix of this
2903 /// Returns `false` if it does not.
2910 /// let bananas = "bananas";
2912 /// assert!(bananas.ends_with("anas"));
2913 /// assert!(!bananas.ends_with("nana"));
2915 #[stable(feature = "rust1", since = "1.0.0")]
2916 pub fn ends_with<'a, P>(&'a self, pat: P) -> bool
2918 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2920 pat.is_suffix_of(self)
2923 /// Returns the byte index of the first character of this string slice that
2924 /// matches the pattern.
2926 /// Returns [`None`] if the pattern doesn't match.
2928 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2929 /// a character matches.
2931 /// [`None`]: option/enum.Option.html#variant.None
2935 /// Simple patterns:
2938 /// let s = "Löwe 老虎 Léopard";
2940 /// assert_eq!(s.find('L'), Some(0));
2941 /// assert_eq!(s.find('é'), Some(14));
2942 /// assert_eq!(s.find("Léopard"), Some(13));
2945 /// More complex patterns using point-free style and closures:
2948 /// let s = "Löwe 老虎 Léopard";
2950 /// assert_eq!(s.find(char::is_whitespace), Some(5));
2951 /// assert_eq!(s.find(char::is_lowercase), Some(1));
2952 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
2953 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
2956 /// Not finding the pattern:
2959 /// let s = "Löwe 老虎 Léopard";
2960 /// let x: &[_] = &['1', '2'];
2962 /// assert_eq!(s.find(x), None);
2964 #[stable(feature = "rust1", since = "1.0.0")]
2966 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2967 pat.into_searcher(self).next_match().map(|(i, _)| i)
2970 /// Returns the byte index of the last character of this string slice that
2971 /// matches the pattern.
2973 /// Returns [`None`] if the pattern doesn't match.
2975 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2976 /// a character matches.
2978 /// [`None`]: option/enum.Option.html#variant.None
2982 /// Simple patterns:
2985 /// let s = "Löwe 老虎 Léopard";
2987 /// assert_eq!(s.rfind('L'), Some(13));
2988 /// assert_eq!(s.rfind('é'), Some(14));
2991 /// More complex patterns with closures:
2994 /// let s = "Löwe 老虎 Léopard";
2996 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
2997 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
3000 /// Not finding the pattern:
3003 /// let s = "Löwe 老虎 Léopard";
3004 /// let x: &[_] = &['1', '2'];
3006 /// assert_eq!(s.rfind(x), None);
3008 #[stable(feature = "rust1", since = "1.0.0")]
3010 pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>
3012 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
3014 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
3017 /// An iterator over substrings of this string slice, separated by
3018 /// characters matched by a pattern.
3020 /// The pattern can be any type that implements the Pattern trait. Notable
3021 /// examples are `&str`, [`char`], and closures that determines the split.
3023 /// # Iterator behavior
3025 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3026 /// allows a reverse search and forward/reverse search yields the same
3027 /// elements. This is true for, e.g., [`char`], but not for `&str`.
3029 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3031 /// If the pattern allows a reverse search but its results might differ
3032 /// from a forward search, the [`rsplit`] method can be used.
3034 /// [`rsplit`]: #method.rsplit
3038 /// Simple patterns:
3041 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
3042 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
3044 /// let v: Vec<&str> = "".split('X').collect();
3045 /// assert_eq!(v, [""]);
3047 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
3048 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
3050 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
3051 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3053 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
3054 /// assert_eq!(v, ["abc", "def", "ghi"]);
3056 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
3057 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3060 /// A more complex pattern, using a closure:
3063 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
3064 /// assert_eq!(v, ["abc", "def", "ghi"]);
3067 /// If a string contains multiple contiguous separators, you will end up
3068 /// with empty strings in the output:
3071 /// let x = "||||a||b|c".to_string();
3072 /// let d: Vec<_> = x.split('|').collect();
3074 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3077 /// Contiguous separators are separated by the empty string.
3080 /// let x = "(///)".to_string();
3081 /// let d: Vec<_> = x.split('/').collect();
3083 /// assert_eq!(d, &["(", "", "", ")"]);
3086 /// Separators at the start or end of a string are neighbored
3087 /// by empty strings.
3090 /// let d: Vec<_> = "010".split("0").collect();
3091 /// assert_eq!(d, &["", "1", ""]);
3094 /// When the empty string is used as a separator, it separates
3095 /// every character in the string, along with the beginning
3096 /// and end of the string.
3099 /// let f: Vec<_> = "rust".split("").collect();
3100 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
3103 /// Contiguous separators can lead to possibly surprising behavior
3104 /// when whitespace is used as the separator. This code is correct:
3107 /// let x = " a b c".to_string();
3108 /// let d: Vec<_> = x.split(' ').collect();
3110 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3113 /// It does _not_ give you:
3116 /// assert_eq!(d, &["a", "b", "c"]);
3119 /// Use [`split_whitespace`] for this behavior.
3121 /// [`split_whitespace`]: #method.split_whitespace
3122 #[stable(feature = "rust1", since = "1.0.0")]
3124 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
3125 Split(SplitInternal {
3128 matcher: pat.into_searcher(self),
3129 allow_trailing_empty: true,
3134 /// An iterator over substrings of the given string slice, separated by
3135 /// characters matched by a pattern and yielded in reverse order.
3137 /// The pattern can be any type that implements the Pattern trait. Notable
3138 /// examples are `&str`, [`char`], and closures that determines the split.
3140 /// # Iterator behavior
3142 /// The returned iterator requires that the pattern supports a reverse
3143 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3144 /// search yields the same elements.
3146 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3148 /// For iterating from the front, the [`split`] method can be used.
3150 /// [`split`]: #method.split
3154 /// Simple patterns:
3157 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
3158 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
3160 /// let v: Vec<&str> = "".rsplit('X').collect();
3161 /// assert_eq!(v, [""]);
3163 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
3164 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
3166 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
3167 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
3170 /// A more complex pattern, using a closure:
3173 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
3174 /// assert_eq!(v, ["ghi", "def", "abc"]);
3176 #[stable(feature = "rust1", since = "1.0.0")]
3178 pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P>
3180 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
3182 RSplit(self.split(pat).0)
3185 /// An iterator over substrings of the given string slice, separated by
3186 /// characters matched by a pattern.
3188 /// The pattern can be any type that implements the Pattern trait. Notable
3189 /// examples are `&str`, [`char`], and closures that determines the split.
3191 /// Equivalent to [`split`], except that the trailing substring
3192 /// is skipped if empty.
3194 /// [`split`]: #method.split
3196 /// This method can be used for string data that is _terminated_,
3197 /// rather than _separated_ by a pattern.
3199 /// # Iterator behavior
3201 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3202 /// allows a reverse search and forward/reverse search yields the same
3203 /// elements. This is true for, e.g., [`char`], but not for `&str`.
3205 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3207 /// If the pattern allows a reverse search but its results might differ
3208 /// from a forward search, the [`rsplit_terminator`] method can be used.
3210 /// [`rsplit_terminator`]: #method.rsplit_terminator
3217 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
3218 /// assert_eq!(v, ["A", "B"]);
3220 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
3221 /// assert_eq!(v, ["A", "", "B", ""]);
3223 #[stable(feature = "rust1", since = "1.0.0")]
3225 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
3226 SplitTerminator(SplitInternal {
3227 allow_trailing_empty: false,
3232 /// An iterator over substrings of `self`, separated by characters
3233 /// matched by a pattern and yielded in reverse order.
3235 /// The pattern can be any type that implements the Pattern trait. Notable
3236 /// examples are `&str`, [`char`], and closures that determines the split.
3237 /// Additional libraries might provide more complex patterns like
3238 /// regular expressions.
3240 /// Equivalent to [`split`], except that the trailing substring is
3241 /// skipped if empty.
3243 /// [`split`]: #method.split
3245 /// This method can be used for string data that is _terminated_,
3246 /// rather than _separated_ by a pattern.
3248 /// # Iterator behavior
3250 /// The returned iterator requires that the pattern supports a
3251 /// reverse search, and it will be double ended if a forward/reverse
3252 /// search yields the same elements.
3254 /// For iterating from the front, the [`split_terminator`] method can be
3257 /// [`split_terminator`]: #method.split_terminator
3262 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
3263 /// assert_eq!(v, ["B", "A"]);
3265 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
3266 /// assert_eq!(v, ["", "B", "", "A"]);
3268 #[stable(feature = "rust1", since = "1.0.0")]
3270 pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P>
3272 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
3274 RSplitTerminator(self.split_terminator(pat).0)
3277 /// An iterator over substrings of the given string slice, separated by a
3278 /// pattern, restricted to returning at most `n` items.
3280 /// If `n` substrings are returned, the last substring (the `n`th substring)
3281 /// will contain the remainder of the string.
3283 /// The pattern can be any type that implements the Pattern trait. Notable
3284 /// examples are `&str`, [`char`], and closures that determines the split.
3286 /// # Iterator behavior
3288 /// The returned iterator will not be double ended, because it is
3289 /// not efficient to support.
3291 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
3294 /// [`rsplitn`]: #method.rsplitn
3298 /// Simple patterns:
3301 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
3302 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
3304 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
3305 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
3307 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
3308 /// assert_eq!(v, ["abcXdef"]);
3310 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
3311 /// assert_eq!(v, [""]);
3314 /// A more complex pattern, using a closure:
3317 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
3318 /// assert_eq!(v, ["abc", "defXghi"]);
3320 #[stable(feature = "rust1", since = "1.0.0")]
3322 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
3323 SplitN(SplitNInternal {
3324 iter: self.split(pat).0,
3329 /// An iterator over substrings of this string slice, separated by a
3330 /// pattern, starting from the end of the string, restricted to returning
3331 /// at most `n` items.
3333 /// If `n` substrings are returned, the last substring (the `n`th substring)
3334 /// will contain the remainder of the string.
3336 /// The pattern can be any type that implements the Pattern trait. Notable
3337 /// examples are `&str`, [`char`], and closures that determines the split.
3339 /// # Iterator behavior
3341 /// The returned iterator will not be double ended, because it is not
3342 /// efficient to support.
3344 /// For splitting from the front, the [`splitn`] method can be used.
3346 /// [`splitn`]: #method.splitn
3350 /// Simple patterns:
3353 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
3354 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
3356 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
3357 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
3359 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
3360 /// assert_eq!(v, ["leopard", "lion::tiger"]);
3363 /// A more complex pattern, using a closure:
3366 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
3367 /// assert_eq!(v, ["ghi", "abc1def"]);
3369 #[stable(feature = "rust1", since = "1.0.0")]
3371 pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
3373 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
3375 RSplitN(self.splitn(n, pat).0)
3378 /// An iterator over the disjoint matches of a pattern within the given string
3381 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3382 /// a character matches.
3384 /// # Iterator behavior
3386 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3387 /// allows a reverse search and forward/reverse search yields the same
3388 /// elements. This is true for, e.g., [`char`], but not for `&str`.
3390 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3392 /// If the pattern allows a reverse search but its results might differ
3393 /// from a forward search, the [`rmatches`] method can be used.
3395 /// [`rmatches`]: #method.rmatches
3402 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
3403 /// assert_eq!(v, ["abc", "abc", "abc"]);
3405 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
3406 /// assert_eq!(v, ["1", "2", "3"]);
3408 #[stable(feature = "str_matches", since = "1.2.0")]
3410 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
3411 Matches(MatchesInternal(pat.into_searcher(self)))
3414 /// An iterator over the disjoint matches of a pattern within this string slice,
3415 /// yielded in reverse order.
3417 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3418 /// a character matches.
3420 /// # Iterator behavior
3422 /// The returned iterator requires that the pattern supports a reverse
3423 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3424 /// search yields the same elements.
3426 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3428 /// For iterating from the front, the [`matches`] method can be used.
3430 /// [`matches`]: #method.matches
3437 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
3438 /// assert_eq!(v, ["abc", "abc", "abc"]);
3440 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
3441 /// assert_eq!(v, ["3", "2", "1"]);
3443 #[stable(feature = "str_matches", since = "1.2.0")]
3445 pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P>
3447 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
3449 RMatches(self.matches(pat).0)
3452 /// An iterator over the disjoint matches of a pattern within this string
3453 /// slice as well as the index that the match starts at.
3455 /// For matches of `pat` within `self` that overlap, only the indices
3456 /// corresponding to the first match are returned.
3458 /// The pattern can be a `&str`, [`char`], or a closure that determines
3459 /// if a character matches.
3461 /// # Iterator behavior
3463 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3464 /// allows a reverse search and forward/reverse search yields the same
3465 /// elements. This is true for, e.g., [`char`], but not for `&str`.
3467 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3469 /// If the pattern allows a reverse search but its results might differ
3470 /// from a forward search, the [`rmatch_indices`] method can be used.
3472 /// [`rmatch_indices`]: #method.rmatch_indices
3479 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
3480 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
3482 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
3483 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
3485 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
3486 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
3488 #[stable(feature = "str_match_indices", since = "1.5.0")]
3490 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
3491 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
3494 /// An iterator over the disjoint matches of a pattern within `self`,
3495 /// yielded in reverse order along with the index of the match.
3497 /// For matches of `pat` within `self` that overlap, only the indices
3498 /// corresponding to the last match are returned.
3500 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
3501 /// character matches.
3503 /// # Iterator behavior
3505 /// The returned iterator requires that the pattern supports a reverse
3506 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3507 /// search yields the same elements.
3509 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3511 /// For iterating from the front, the [`match_indices`] method can be used.
3513 /// [`match_indices`]: #method.match_indices
3520 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
3521 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
3523 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
3524 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
3526 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
3527 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
3529 #[stable(feature = "str_match_indices", since = "1.5.0")]
3531 pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P>
3533 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
3535 RMatchIndices(self.match_indices(pat).0)
3538 /// Returns a string slice with leading and trailing whitespace removed.
3540 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3541 /// Core Property `White_Space`.
3548 /// let s = " Hello\tworld\t";
3550 /// assert_eq!("Hello\tworld", s.trim());
3552 #[must_use = "this returns the trimmed string as a slice, \
3553 without modifying the original"]
3554 #[stable(feature = "rust1", since = "1.0.0")]
3555 pub fn trim(&self) -> &str {
3556 self.trim_matches(|c: char| c.is_whitespace())
3559 /// Returns a string slice with leading whitespace removed.
3561 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3562 /// Core Property `White_Space`.
3564 /// # Text directionality
3566 /// A string is a sequence of bytes. `start` in this context means the first
3567 /// position of that byte string; for a left-to-right language like English or
3568 /// Russian, this will be left side, and for right-to-left languages like
3569 /// Arabic or Hebrew, this will be the right side.
3576 /// let s = " Hello\tworld\t";
3577 /// assert_eq!("Hello\tworld\t", s.trim_start());
3583 /// let s = " English ";
3584 /// assert!(Some('E') == s.trim_start().chars().next());
3586 /// let s = " עברית ";
3587 /// assert!(Some('ע') == s.trim_start().chars().next());
3589 #[must_use = "this returns the trimmed string as a new slice, \
3590 without modifying the original"]
3591 #[stable(feature = "trim_direction", since = "1.30.0")]
3592 pub fn trim_start(&self) -> &str {
3593 self.trim_start_matches(|c: char| c.is_whitespace())
3596 /// Returns a string slice with trailing whitespace removed.
3598 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3599 /// Core Property `White_Space`.
3601 /// # Text directionality
3603 /// A string is a sequence of bytes. `end` in this context means the last
3604 /// position of that byte string; for a left-to-right language like English or
3605 /// Russian, this will be right side, and for right-to-left languages like
3606 /// Arabic or Hebrew, this will be the left side.
3613 /// let s = " Hello\tworld\t";
3614 /// assert_eq!(" Hello\tworld", s.trim_end());
3620 /// let s = " English ";
3621 /// assert!(Some('h') == s.trim_end().chars().rev().next());
3623 /// let s = " עברית ";
3624 /// assert!(Some('ת') == s.trim_end().chars().rev().next());
3626 #[must_use = "this returns the trimmed string as a new slice, \
3627 without modifying the original"]
3628 #[stable(feature = "trim_direction", since = "1.30.0")]
3629 pub fn trim_end(&self) -> &str {
3630 self.trim_end_matches(|c: char| c.is_whitespace())
3633 /// Returns a string slice with leading whitespace removed.
3635 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3636 /// Core Property `White_Space`.
3638 /// # Text directionality
3640 /// A string is a sequence of bytes. 'Left' in this context means the first
3641 /// position of that byte string; for a language like Arabic or Hebrew
3642 /// which are 'right to left' rather than 'left to right', this will be
3643 /// the _right_ side, not the left.
3650 /// let s = " Hello\tworld\t";
3652 /// assert_eq!("Hello\tworld\t", s.trim_left());
3658 /// let s = " English";
3659 /// assert!(Some('E') == s.trim_left().chars().next());
3661 /// let s = " עברית";
3662 /// assert!(Some('ע') == s.trim_left().chars().next());
3664 #[stable(feature = "rust1", since = "1.0.0")]
3667 reason = "superseded by `trim_start`",
3668 suggestion = "trim_start",
3670 pub fn trim_left(&self) -> &str {
3674 /// Returns a string slice with trailing whitespace removed.
3676 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3677 /// Core Property `White_Space`.
3679 /// # Text directionality
3681 /// A string is a sequence of bytes. 'Right' in this context means the last
3682 /// position of that byte string; for a language like Arabic or Hebrew
3683 /// which are 'right to left' rather than 'left to right', this will be
3684 /// the _left_ side, not the right.
3691 /// let s = " Hello\tworld\t";
3693 /// assert_eq!(" Hello\tworld", s.trim_right());
3699 /// let s = "English ";
3700 /// assert!(Some('h') == s.trim_right().chars().rev().next());
3702 /// let s = "עברית ";
3703 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
3705 #[stable(feature = "rust1", since = "1.0.0")]
3708 reason = "superseded by `trim_end`",
3709 suggestion = "trim_end",
3711 pub fn trim_right(&self) -> &str {
3715 /// Returns a string slice with all prefixes and suffixes that match a
3716 /// pattern repeatedly removed.
3718 /// The pattern can be a [`char`] or a closure that determines if a
3719 /// character matches.
3723 /// Simple patterns:
3726 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
3727 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
3729 /// let x: &[_] = &['1', '2'];
3730 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
3733 /// A more complex pattern, using a closure:
3736 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
3738 #[must_use = "this returns the trimmed string as a new slice, \
3739 without modifying the original"]
3740 #[stable(feature = "rust1", since = "1.0.0")]
3741 pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str
3743 P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>,
3747 let mut matcher = pat.into_searcher(self);
3748 if let Some((a, b)) = matcher.next_reject() {
3750 j = b; // Remember earliest known match, correct it below if
3751 // last match is different
3753 if let Some((_, b)) = matcher.next_reject_back() {
3757 // Searcher is known to return valid indices
3758 self.get_unchecked(i..j)
3762 /// Returns a string slice with all prefixes that match a pattern
3763 /// repeatedly removed.
3765 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3766 /// a character matches.
3768 /// # Text directionality
3770 /// A string is a sequence of bytes. `start` in this context means the first
3771 /// position of that byte string; for a left-to-right language like English or
3772 /// Russian, this will be left side, and for right-to-left languages like
3773 /// Arabic or Hebrew, this will be the right side.
3780 /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
3781 /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
3783 /// let x: &[_] = &['1', '2'];
3784 /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
3786 #[must_use = "this returns the trimmed string as a new slice, \
3787 without modifying the original"]
3788 #[stable(feature = "trim_direction", since = "1.30.0")]
3789 pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3790 let mut i = self.len();
3791 let mut matcher = pat.into_searcher(self);
3792 if let Some((a, _)) = matcher.next_reject() {
3796 // Searcher is known to return valid indices
3797 self.get_unchecked(i..self.len())
3801 /// Returns a string slice with the prefix removed.
3803 /// If the string starts with the pattern `prefix`, `Some` is returned with the substring where
3804 /// the prefix is removed. Unlike `trim_start_matches`, this method removes the prefix exactly
3807 /// If the string does not start with `prefix`, `None` is returned.
3812 /// #![feature(str_strip)]
3814 /// assert_eq!("foobar".strip_prefix("foo"), Some("bar"));
3815 /// assert_eq!("foobar".strip_prefix("bar"), None);
3816 /// assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
3818 #[must_use = "this returns the remaining substring as a new slice, \
3819 without modifying the original"]
3820 #[unstable(feature = "str_strip", reason = "newly added", issue = "67302")]
3821 pub fn strip_prefix<'a, P: Pattern<'a>>(&'a self, prefix: P) -> Option<&'a str> {
3822 let mut matcher = prefix.into_searcher(self);
3823 if let SearchStep::Match(start, len) = matcher.next() {
3824 debug_assert_eq!(start, 0, "The first search step from Searcher \
3825 must include the first character");
3827 // Searcher is known to return valid indices.
3828 Some(self.get_unchecked(len..))
3835 /// Returns a string slice with the suffix removed.
3837 /// If the string ends with the pattern `suffix`, `Some` is returned with the substring where
3838 /// the suffix is removed. Unlike `trim_end_matches`, this method removes the suffix exactly
3841 /// If the string does not end with `suffix`, `None` is returned.
3846 /// #![feature(str_strip)]
3847 /// assert_eq!("barfoo".strip_suffix("foo"), Some("bar"));
3848 /// assert_eq!("barfoo".strip_suffix("bar"), None);
3849 /// assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
3851 #[must_use = "this returns the remaining substring as a new slice, \
3852 without modifying the original"]
3853 #[unstable(feature = "str_strip", reason = "newly added", issue = "67302")]
3854 pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>
3857 <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
3859 let mut matcher = suffix.into_searcher(self);
3860 if let SearchStep::Match(start, end) = matcher.next_back() {
3861 debug_assert_eq!(end, self.len(), "The first search step from ReverseSearcher \
3862 must include the last character");
3864 // Searcher is known to return valid indices.
3865 Some(self.get_unchecked(..start))
3872 /// Returns a string slice with all suffixes that match a pattern
3873 /// repeatedly removed.
3875 /// The pattern can be a `&str`, [`char`], or a closure that
3876 /// determines if a character matches.
3878 /// # Text directionality
3880 /// A string is a sequence of bytes. `end` in this context means the last
3881 /// position of that byte string; for a left-to-right language like English or
3882 /// Russian, this will be right side, and for right-to-left languages like
3883 /// Arabic or Hebrew, this will be the left side.
3887 /// Simple patterns:
3890 /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
3891 /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
3893 /// let x: &[_] = &['1', '2'];
3894 /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
3897 /// A more complex pattern, using a closure:
3900 /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
3902 #[must_use = "this returns the trimmed string as a new slice, \
3903 without modifying the original"]
3904 #[stable(feature = "trim_direction", since = "1.30.0")]
3905 pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str
3907 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
3910 let mut matcher = pat.into_searcher(self);
3911 if let Some((_, b)) = matcher.next_reject_back() {
3915 // Searcher is known to return valid indices
3916 self.get_unchecked(0..j)
3920 /// Returns a string slice with all prefixes that match a pattern
3921 /// repeatedly removed.
3923 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3924 /// a character matches.
3926 /// [`char`]: primitive.char.html
3928 /// # Text directionality
3930 /// A string is a sequence of bytes. 'Left' in this context means the first
3931 /// position of that byte string; for a language like Arabic or Hebrew
3932 /// which are 'right to left' rather than 'left to right', this will be
3933 /// the _right_ side, not the left.
3940 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
3941 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
3943 /// let x: &[_] = &['1', '2'];
3944 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
3946 #[stable(feature = "rust1", since = "1.0.0")]
3949 reason = "superseded by `trim_start_matches`",
3950 suggestion = "trim_start_matches",
3952 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3953 self.trim_start_matches(pat)
3956 /// Returns a string slice with all suffixes that match a pattern
3957 /// repeatedly removed.
3959 /// The pattern can be a `&str`, [`char`], or a closure that
3960 /// determines if a character matches.
3962 /// [`char`]: primitive.char.html
3964 /// # Text directionality
3966 /// A string is a sequence of bytes. 'Right' in this context means the last
3967 /// position of that byte string; for a language like Arabic or Hebrew
3968 /// which are 'right to left' rather than 'left to right', this will be
3969 /// the _left_ side, not the right.
3973 /// Simple patterns:
3976 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
3977 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
3979 /// let x: &[_] = &['1', '2'];
3980 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
3983 /// A more complex pattern, using a closure:
3986 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
3988 #[stable(feature = "rust1", since = "1.0.0")]
3991 reason = "superseded by `trim_end_matches`",
3992 suggestion = "trim_end_matches",
3994 pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str
3996 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
3998 self.trim_end_matches(pat)
4001 /// Parses this string slice into another type.
4003 /// Because `parse` is so general, it can cause problems with type
4004 /// inference. As such, `parse` is one of the few times you'll see
4005 /// the syntax affectionately known as the 'turbofish': `::<>`. This
4006 /// helps the inference algorithm understand specifically which type
4007 /// you're trying to parse into.
4009 /// `parse` can parse any type that implements the [`FromStr`] trait.
4011 /// [`FromStr`]: str/trait.FromStr.html
4015 /// Will return [`Err`] if it's not possible to parse this string slice into
4016 /// the desired type.
4018 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
4025 /// let four: u32 = "4".parse().unwrap();
4027 /// assert_eq!(4, four);
4030 /// Using the 'turbofish' instead of annotating `four`:
4033 /// let four = "4".parse::<u32>();
4035 /// assert_eq!(Ok(4), four);
4038 /// Failing to parse:
4041 /// let nope = "j".parse::<u32>();
4043 /// assert!(nope.is_err());
4046 #[stable(feature = "rust1", since = "1.0.0")]
4047 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
4048 FromStr::from_str(self)
4051 /// Checks if all characters in this string are within the ASCII range.
4056 /// let ascii = "hello!\n";
4057 /// let non_ascii = "Grüße, Jürgen ❤";
4059 /// assert!(ascii.is_ascii());
4060 /// assert!(!non_ascii.is_ascii());
4062 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4064 pub fn is_ascii(&self) -> bool {
4065 // We can treat each byte as character here: all multibyte characters
4066 // start with a byte that is not in the ascii range, so we will stop
4068 self.bytes().all(|b| b.is_ascii())
4071 /// Checks that two strings are an ASCII case-insensitive match.
4073 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
4074 /// but without allocating and copying temporaries.
4079 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
4080 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
4081 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
4083 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4085 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
4086 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
4089 /// Converts this string to its ASCII upper case equivalent in-place.
4091 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4092 /// but non-ASCII letters are unchanged.
4094 /// To return a new uppercased value without modifying the existing one, use
4095 /// [`to_ascii_uppercase`].
4097 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4102 /// let mut s = String::from("Grüße, Jürgen ❤");
4104 /// s.make_ascii_uppercase();
4106 /// assert_eq!("GRüßE, JüRGEN ❤", s);
4108 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4109 pub fn make_ascii_uppercase(&mut self) {
4110 let me = unsafe { self.as_bytes_mut() };
4111 me.make_ascii_uppercase()
4114 /// Converts this string to its ASCII lower case equivalent in-place.
4116 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4117 /// but non-ASCII letters are unchanged.
4119 /// To return a new lowercased value without modifying the existing one, use
4120 /// [`to_ascii_lowercase`].
4122 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4127 /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
4129 /// s.make_ascii_lowercase();
4131 /// assert_eq!("grÜße, jÜrgen ❤", s);
4133 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4134 pub fn make_ascii_lowercase(&mut self) {
4135 let me = unsafe { self.as_bytes_mut() };
4136 me.make_ascii_lowercase()
4139 /// Return an iterator that escapes each char in `self` with [`char::escape_debug`].
4141 /// Note: only extended grapheme codepoints that begin the string will be
4144 /// [`char::escape_debug`]: ../std/primitive.char.html#method.escape_debug
4151 /// for c in "❤\n!".escape_debug() {
4152 /// print!("{}", c);
4157 /// Using `println!` directly:
4160 /// println!("{}", "❤\n!".escape_debug());
4164 /// Both are equivalent to:
4167 /// println!("❤\\n!");
4170 /// Using `to_string`:
4173 /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
4175 #[stable(feature = "str_escape", since = "1.34.0")]
4176 pub fn escape_debug(&self) -> EscapeDebug<'_> {
4177 let mut chars = self.chars();
4180 .map(|first| first.escape_debug_ext(true))
4183 .chain(chars.flat_map(CharEscapeDebugContinue))
4187 /// Return an iterator that escapes each char in `self` with [`char::escape_default`].
4189 /// [`char::escape_default`]: ../std/primitive.char.html#method.escape_default
4196 /// for c in "❤\n!".escape_default() {
4197 /// print!("{}", c);
4202 /// Using `println!` directly:
4205 /// println!("{}", "❤\n!".escape_default());
4209 /// Both are equivalent to:
4212 /// println!("\\u{{2764}}\\n!");
4215 /// Using `to_string`:
4218 /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
4220 #[stable(feature = "str_escape", since = "1.34.0")]
4221 pub fn escape_default(&self) -> EscapeDefault<'_> {
4222 EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
4225 /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`].
4227 /// [`char::escape_unicode`]: ../std/primitive.char.html#method.escape_unicode
4234 /// for c in "❤\n!".escape_unicode() {
4235 /// print!("{}", c);
4240 /// Using `println!` directly:
4243 /// println!("{}", "❤\n!".escape_unicode());
4247 /// Both are equivalent to:
4250 /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
4253 /// Using `to_string`:
4256 /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
4258 #[stable(feature = "str_escape", since = "1.34.0")]
4259 pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
4260 EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
4266 struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
4267 c.escape_debug_ext(false)
4271 struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
4275 struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
4280 #[stable(feature = "rust1", since = "1.0.0")]
4281 impl AsRef<[u8]> for str {
4283 fn as_ref(&self) -> &[u8] {
4288 #[stable(feature = "rust1", since = "1.0.0")]
4289 impl Default for &str {
4290 /// Creates an empty str
4291 fn default() -> Self { "" }
4294 #[stable(feature = "default_mut_str", since = "1.28.0")]
4295 impl Default for &mut str {
4296 /// Creates an empty mutable str
4297 fn default() -> Self { unsafe { from_utf8_unchecked_mut(&mut []) } }
4300 /// An iterator over the non-whitespace substrings of a string,
4301 /// separated by any amount of whitespace.
4303 /// This struct is created by the [`split_whitespace`] method on [`str`].
4304 /// See its documentation for more.
4306 /// [`split_whitespace`]: ../../std/primitive.str.html#method.split_whitespace
4307 /// [`str`]: ../../std/primitive.str.html
4308 #[stable(feature = "split_whitespace", since = "1.1.0")]
4309 #[derive(Clone, Debug)]
4310 pub struct SplitWhitespace<'a> {
4311 inner: Filter<Split<'a, IsWhitespace>, IsNotEmpty>,
4314 /// An iterator over the non-ASCII-whitespace substrings of a string,
4315 /// separated by any amount of ASCII whitespace.
4317 /// This struct is created by the [`split_ascii_whitespace`] method on [`str`].
4318 /// See its documentation for more.
4320 /// [`split_ascii_whitespace`]: ../../std/primitive.str.html#method.split_ascii_whitespace
4321 /// [`str`]: ../../std/primitive.str.html
4322 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4323 #[derive(Clone, Debug)]
4324 pub struct SplitAsciiWhitespace<'a> {
4325 inner: Map<Filter<SliceSplit<'a, u8, IsAsciiWhitespace>, BytesIsNotEmpty>, UnsafeBytesToStr>,
4330 struct IsWhitespace impl Fn = |c: char| -> bool {
4335 struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
4336 byte.is_ascii_whitespace()
4340 struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
4345 struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
4350 struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
4351 unsafe { from_utf8_unchecked(bytes) }
4355 #[stable(feature = "split_whitespace", since = "1.1.0")]
4356 impl<'a> Iterator for SplitWhitespace<'a> {
4357 type Item = &'a str;
4360 fn next(&mut self) -> Option<&'a str> {
4365 fn size_hint(&self) -> (usize, Option<usize>) {
4366 self.inner.size_hint()
4370 fn last(mut self) -> Option<&'a str> {
4375 #[stable(feature = "split_whitespace", since = "1.1.0")]
4376 impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
4378 fn next_back(&mut self) -> Option<&'a str> {
4379 self.inner.next_back()
4383 #[stable(feature = "fused", since = "1.26.0")]
4384 impl FusedIterator for SplitWhitespace<'_> {}
4386 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4387 impl<'a> Iterator for SplitAsciiWhitespace<'a> {
4388 type Item = &'a str;
4391 fn next(&mut self) -> Option<&'a str> {
4396 fn size_hint(&self) -> (usize, Option<usize>) {
4397 self.inner.size_hint()
4401 fn last(mut self) -> Option<&'a str> {
4406 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4407 impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> {
4409 fn next_back(&mut self) -> Option<&'a str> {
4410 self.inner.next_back()
4414 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4415 impl FusedIterator for SplitAsciiWhitespace<'_> {}
4417 /// An iterator of [`u16`] over the string encoded as UTF-16.
4419 /// [`u16`]: ../../std/primitive.u16.html
4421 /// This struct is created by the [`encode_utf16`] method on [`str`].
4422 /// See its documentation for more.
4424 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
4425 /// [`str`]: ../../std/primitive.str.html
4427 #[stable(feature = "encode_utf16", since = "1.8.0")]
4428 pub struct EncodeUtf16<'a> {
4433 #[stable(feature = "collection_debug", since = "1.17.0")]
4434 impl fmt::Debug for EncodeUtf16<'_> {
4435 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4436 f.pad("EncodeUtf16 { .. }")
4440 #[stable(feature = "encode_utf16", since = "1.8.0")]
4441 impl<'a> Iterator for EncodeUtf16<'a> {
4445 fn next(&mut self) -> Option<u16> {
4446 if self.extra != 0 {
4447 let tmp = self.extra;
4452 let mut buf = [0; 2];
4453 self.chars.next().map(|ch| {
4454 let n = ch.encode_utf16(&mut buf).len();
4456 self.extra = buf[1];
4463 fn size_hint(&self) -> (usize, Option<usize>) {
4464 let (low, high) = self.chars.size_hint();
4465 // every char gets either one u16 or two u16,
4466 // so this iterator is between 1 or 2 times as
4467 // long as the underlying iterator.
4468 (low, high.and_then(|n| n.checked_mul(2)))
4472 #[stable(feature = "fused", since = "1.26.0")]
4473 impl FusedIterator for EncodeUtf16<'_> {}
4475 /// The return type of [`str::escape_debug`].
4477 /// [`str::escape_debug`]: ../../std/primitive.str.html#method.escape_debug
4478 #[stable(feature = "str_escape", since = "1.34.0")]
4479 #[derive(Clone, Debug)]
4480 pub struct EscapeDebug<'a> {
4482 Flatten<option::IntoIter<char::EscapeDebug>>,
4483 FlatMap<Chars<'a>, char::EscapeDebug, CharEscapeDebugContinue>
4487 /// The return type of [`str::escape_default`].
4489 /// [`str::escape_default`]: ../../std/primitive.str.html#method.escape_default
4490 #[stable(feature = "str_escape", since = "1.34.0")]
4491 #[derive(Clone, Debug)]
4492 pub struct EscapeDefault<'a> {
4493 inner: FlatMap<Chars<'a>, char::EscapeDefault, CharEscapeDefault>,
4496 /// The return type of [`str::escape_unicode`].
4498 /// [`str::escape_unicode`]: ../../std/primitive.str.html#method.escape_unicode
4499 #[stable(feature = "str_escape", since = "1.34.0")]
4500 #[derive(Clone, Debug)]
4501 pub struct EscapeUnicode<'a> {
4502 inner: FlatMap<Chars<'a>, char::EscapeUnicode, CharEscapeUnicode>,
4505 macro_rules! escape_types_impls {
4506 ($( $Name: ident ),+) => {$(
4507 #[stable(feature = "str_escape", since = "1.34.0")]
4508 impl<'a> fmt::Display for $Name<'a> {
4509 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4510 self.clone().try_for_each(|c| f.write_char(c))
4514 #[stable(feature = "str_escape", since = "1.34.0")]
4515 impl<'a> Iterator for $Name<'a> {
4519 fn next(&mut self) -> Option<char> { self.inner.next() }
4522 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
4525 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
4526 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
4528 self.inner.try_fold(init, fold)
4532 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
4533 where Fold: FnMut(Acc, Self::Item) -> Acc,
4535 self.inner.fold(init, fold)
4539 #[stable(feature = "str_escape", since = "1.34.0")]
4540 impl<'a> FusedIterator for $Name<'a> {}
4544 escape_types_impls!(EscapeDebug, EscapeDefault, EscapeUnicode);