1 //! String manipulation
3 //! For more details, see std::str
5 #![stable(feature = "rust1", since = "1.0.0")]
7 use self::pattern::Pattern;
8 use self::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
12 use iter::{Map, Cloned, FusedIterator, TrustedLen, TrustedRandomAccess, Filter};
13 use slice::{self, SliceIndex, Split as SliceSplit};
18 #[unstable(feature = "str_internals", issue = "0")]
19 #[allow(missing_docs)]
22 /// Parse a value from a string
24 /// `FromStr`'s [`from_str`] method is often used implicitly, through
25 /// [`str`]'s [`parse`] method. See [`parse`]'s documentation for examples.
27 /// [`from_str`]: #tymethod.from_str
28 /// [`str`]: ../../std/primitive.str.html
29 /// [`parse`]: ../../std/primitive.str.html#method.parse
31 /// `FromStr` does not have a lifetime parameter, and so you can only parse types
32 /// that do not contain a lifetime parameter themselves. In other words, you can
33 /// parse an `i32` with `FromStr`, but not a `&i32`. You can parse a struct that
34 /// contains an `i32`, but not one that contains an `&i32`.
38 /// Basic implementation of `FromStr` on an example `Point` type:
41 /// use std::str::FromStr;
42 /// use std::num::ParseIntError;
44 /// #[derive(Debug, PartialEq)]
50 /// impl FromStr for Point {
51 /// type Err = ParseIntError;
53 /// fn from_str(s: &str) -> Result<Self, Self::Err> {
54 /// let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
58 /// let x_fromstr = coords[0].parse::<i32>()?;
59 /// let y_fromstr = coords[1].parse::<i32>()?;
61 /// Ok(Point { x: x_fromstr, y: y_fromstr })
65 /// let p = Point::from_str("(1,2)");
66 /// assert_eq!(p.unwrap(), Point{ x: 1, y: 2} )
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub trait FromStr: Sized {
70 /// The associated error which can be returned from parsing.
71 #[stable(feature = "rust1", since = "1.0.0")]
74 /// Parses a string `s` to return a value of this type.
76 /// If parsing succeeds, return the value inside [`Ok`], otherwise
77 /// when the string is ill-formatted return an error specific to the
78 /// inside [`Err`]. The error type is specific to implementation of the trait.
80 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
81 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
85 /// Basic usage with [`i32`][ithirtytwo], a type that implements `FromStr`:
87 /// [ithirtytwo]: ../../std/primitive.i32.html
90 /// use std::str::FromStr;
93 /// let x = i32::from_str(s).unwrap();
97 #[stable(feature = "rust1", since = "1.0.0")]
98 fn from_str(s: &str) -> Result<Self, Self::Err>;
101 #[stable(feature = "rust1", since = "1.0.0")]
102 impl FromStr for bool {
103 type Err = ParseBoolError;
105 /// Parse a `bool` from a string.
107 /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
108 /// actually be parseable.
113 /// use std::str::FromStr;
115 /// assert_eq!(FromStr::from_str("true"), Ok(true));
116 /// assert_eq!(FromStr::from_str("false"), Ok(false));
117 /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
120 /// Note, in many cases, the `.parse()` method on `str` is more proper.
123 /// assert_eq!("true".parse(), Ok(true));
124 /// assert_eq!("false".parse(), Ok(false));
125 /// assert!("not even a boolean".parse::<bool>().is_err());
128 fn from_str(s: &str) -> Result<bool, ParseBoolError> {
131 "false" => Ok(false),
132 _ => Err(ParseBoolError { _priv: () }),
137 /// An error returned when parsing a `bool` using [`from_str`] fails
139 /// [`from_str`]: ../../std/primitive.bool.html#method.from_str
140 #[derive(Debug, Clone, PartialEq, Eq)]
141 #[stable(feature = "rust1", since = "1.0.0")]
142 pub struct ParseBoolError { _priv: () }
144 #[stable(feature = "rust1", since = "1.0.0")]
145 impl fmt::Display for ParseBoolError {
146 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
147 "provided string was not `true` or `false`".fmt(f)
152 Section: Creating a string
155 /// Errors which can occur when attempting to interpret a sequence of [`u8`]
158 /// [`u8`]: ../../std/primitive.u8.html
160 /// As such, the `from_utf8` family of functions and methods for both [`String`]s
161 /// and [`&str`]s make use of this error, for example.
163 /// [`String`]: ../../std/string/struct.String.html#method.from_utf8
164 /// [`&str`]: ../../std/str/fn.from_utf8.html
168 /// This error type’s methods can be used to create functionality
169 /// similar to `String::from_utf8_lossy` without allocating heap memory:
172 /// fn from_utf8_lossy<F>(mut input: &[u8], mut push: F) where F: FnMut(&str) {
174 /// match ::std::str::from_utf8(input) {
180 /// let (valid, after_valid) = input.split_at(error.valid_up_to());
182 /// push(::std::str::from_utf8_unchecked(valid))
184 /// push("\u{FFFD}");
186 /// if let Some(invalid_sequence_length) = error.error_len() {
187 /// input = &after_valid[invalid_sequence_length..]
196 #[derive(Copy, Eq, PartialEq, Clone, Debug)]
197 #[stable(feature = "rust1", since = "1.0.0")]
198 pub struct Utf8Error {
200 error_len: Option<u8>,
204 /// Returns the index in the given string up to which valid UTF-8 was
207 /// It is the maximum index such that `from_utf8(&input[..index])`
208 /// would return `Ok(_)`.
217 /// // some invalid bytes, in a vector
218 /// let sparkle_heart = vec![0, 159, 146, 150];
220 /// // std::str::from_utf8 returns a Utf8Error
221 /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
223 /// // the second byte is invalid here
224 /// assert_eq!(1, error.valid_up_to());
226 #[stable(feature = "utf8_error", since = "1.5.0")]
227 pub fn valid_up_to(&self) -> usize { self.valid_up_to }
229 /// Provide more information about the failure:
231 /// * `None`: the end of the input was reached unexpectedly.
232 /// `self.valid_up_to()` is 1 to 3 bytes from the end of the input.
233 /// If a byte stream (such as a file or a network socket) is being decoded incrementally,
234 /// this could be a valid `char` whose UTF-8 byte sequence is spanning multiple chunks.
236 /// * `Some(len)`: an unexpected byte was encountered.
237 /// The length provided is that of the invalid byte sequence
238 /// that starts at the index given by `valid_up_to()`.
239 /// Decoding should resume after that sequence
240 /// (after inserting a [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD]) in case of
243 /// [U+FFFD]: ../../std/char/constant.REPLACEMENT_CHARACTER.html
244 #[stable(feature = "utf8_error_error_len", since = "1.20.0")]
245 pub fn error_len(&self) -> Option<usize> {
246 self.error_len.map(|len| len as usize)
250 /// Converts a slice of bytes to a string slice.
252 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
253 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
254 /// the two. Not all byte slices are valid string slices, however: [`&str`] requires
255 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
256 /// UTF-8, and then does the conversion.
258 /// [`&str`]: ../../std/primitive.str.html
259 /// [`u8`]: ../../std/primitive.u8.html
260 /// [byteslice]: ../../std/primitive.slice.html
262 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
263 /// incur the overhead of the validity check, there is an unsafe version of
264 /// this function, [`from_utf8_unchecked`][fromutf8u], which has the same
265 /// behavior but skips the check.
267 /// [fromutf8u]: fn.from_utf8_unchecked.html
269 /// If you need a `String` instead of a `&str`, consider
270 /// [`String::from_utf8`][string].
272 /// [string]: ../../std/string/struct.String.html#method.from_utf8
274 /// Because you can stack-allocate a `[u8; N]`, and you can take a
275 /// [`&[u8]`][byteslice] of it, this function is one way to have a
276 /// stack-allocated string. There is an example of this in the
277 /// examples section below.
279 /// [byteslice]: ../../std/primitive.slice.html
283 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
284 /// provided slice is not UTF-8.
293 /// // some bytes, in a vector
294 /// let sparkle_heart = vec![240, 159, 146, 150];
296 /// // We know these bytes are valid, so just use `unwrap()`.
297 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
299 /// assert_eq!("💖", sparkle_heart);
307 /// // some invalid bytes, in a vector
308 /// let sparkle_heart = vec![0, 159, 146, 150];
310 /// assert!(str::from_utf8(&sparkle_heart).is_err());
313 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
314 /// errors that can be returned.
316 /// [error]: struct.Utf8Error.html
318 /// A "stack allocated string":
323 /// // some bytes, in a stack-allocated array
324 /// let sparkle_heart = [240, 159, 146, 150];
326 /// // We know these bytes are valid, so just use `unwrap()`.
327 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
329 /// assert_eq!("💖", sparkle_heart);
331 #[stable(feature = "rust1", since = "1.0.0")]
332 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
333 run_utf8_validation(v)?;
334 Ok(unsafe { from_utf8_unchecked(v) })
337 /// Converts a mutable slice of bytes to a mutable string slice.
346 /// // "Hello, Rust!" as a mutable vector
347 /// let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
349 /// // As we know these bytes are valid, we can use `unwrap()`
350 /// let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
352 /// assert_eq!("Hello, Rust!", outstr);
360 /// // Some invalid bytes in a mutable vector
361 /// let mut invalid = vec![128, 223];
363 /// assert!(str::from_utf8_mut(&mut invalid).is_err());
365 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
366 /// errors that can be returned.
368 /// [error]: struct.Utf8Error.html
369 #[stable(feature = "str_mut_extras", since = "1.20.0")]
370 pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
371 run_utf8_validation(v)?;
372 Ok(unsafe { from_utf8_unchecked_mut(v) })
375 /// Converts a slice of bytes to a string slice without checking
376 /// that the string contains valid UTF-8.
378 /// See the safe version, [`from_utf8`][fromutf8], for more information.
380 /// [fromutf8]: fn.from_utf8.html
384 /// This function is unsafe because it does not check that the bytes passed to
385 /// it are valid UTF-8. If this constraint is violated, undefined behavior
386 /// results, as the rest of Rust assumes that [`&str`]s are valid UTF-8.
388 /// [`&str`]: ../../std/primitive.str.html
397 /// // some bytes, in a vector
398 /// let sparkle_heart = vec![240, 159, 146, 150];
400 /// let sparkle_heart = unsafe {
401 /// str::from_utf8_unchecked(&sparkle_heart)
404 /// assert_eq!("💖", sparkle_heart);
407 #[stable(feature = "rust1", since = "1.0.0")]
408 pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
409 &*(v as *const [u8] as *const str)
412 /// Converts a slice of bytes to a string slice without checking
413 /// that the string contains valid UTF-8; mutable version.
415 /// See the immutable version, [`from_utf8_unchecked()`][fromutf8], for more information.
417 /// [fromutf8]: fn.from_utf8_unchecked.html
426 /// let mut heart = vec![240, 159, 146, 150];
427 /// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
429 /// assert_eq!("💖", heart);
432 #[stable(feature = "str_mut_extras", since = "1.20.0")]
433 pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
434 &mut *(v as *mut [u8] as *mut str)
437 #[stable(feature = "rust1", since = "1.0.0")]
438 impl fmt::Display for Utf8Error {
439 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
440 if let Some(error_len) = self.error_len {
441 write!(f, "invalid utf-8 sequence of {} bytes from index {}",
442 error_len, self.valid_up_to)
444 write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to)
453 /// An iterator over the [`char`]s of a string slice.
455 /// [`char`]: ../../std/primitive.char.html
457 /// This struct is created by the [`chars`] method on [`str`].
458 /// See its documentation for more.
460 /// [`chars`]: ../../std/primitive.str.html#method.chars
461 /// [`str`]: ../../std/primitive.str.html
462 #[derive(Clone, Debug)]
463 #[stable(feature = "rust1", since = "1.0.0")]
464 pub struct Chars<'a> {
465 iter: slice::Iter<'a, u8>
468 /// Returns the initial codepoint accumulator for the first byte.
469 /// The first byte is special, only want bottom 5 bits for width 2, 4 bits
470 /// for width 3, and 3 bits for width 4.
472 fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
474 /// Returns the value of `ch` updated with continuation byte `byte`.
476 fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
478 /// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the
481 fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
484 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
491 /// Reads the next code point out of a byte iterator (assuming a
492 /// UTF-8-like encoding).
493 #[unstable(feature = "str_internals", issue = "0")]
495 pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
497 let x = *bytes.next()?;
499 return Some(x as u32)
502 // Multibyte case follows
503 // Decode from a byte combination out of: [[[x y] z] w]
504 // NOTE: Performance is sensitive to the exact formulation here
505 let init = utf8_first_byte(x, 2);
506 let y = unwrap_or_0(bytes.next());
507 let mut ch = utf8_acc_cont_byte(init, y);
510 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
511 let z = unwrap_or_0(bytes.next());
512 let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
513 ch = init << 12 | y_z;
516 // use only the lower 3 bits of `init`
517 let w = unwrap_or_0(bytes.next());
518 ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
525 /// Reads the last code point out of a byte iterator (assuming a
526 /// UTF-8-like encoding).
528 fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
529 where I: DoubleEndedIterator<Item = &'a u8>,
532 let w = match *bytes.next_back()? {
533 next_byte if next_byte < 128 => return Some(next_byte as u32),
534 back_byte => back_byte,
537 // Multibyte case follows
538 // Decode from a byte combination out of: [x [y [z w]]]
540 let z = unwrap_or_0(bytes.next_back());
541 ch = utf8_first_byte(z, 2);
542 if utf8_is_cont_byte(z) {
543 let y = unwrap_or_0(bytes.next_back());
544 ch = utf8_first_byte(y, 3);
545 if utf8_is_cont_byte(y) {
546 let x = unwrap_or_0(bytes.next_back());
547 ch = utf8_first_byte(x, 4);
548 ch = utf8_acc_cont_byte(ch, y);
550 ch = utf8_acc_cont_byte(ch, z);
552 ch = utf8_acc_cont_byte(ch, w);
557 #[stable(feature = "rust1", since = "1.0.0")]
558 impl<'a> Iterator for Chars<'a> {
562 fn next(&mut self) -> Option<char> {
563 next_code_point(&mut self.iter).map(|ch| {
564 // str invariant says `ch` is a valid Unicode Scalar Value
566 char::from_u32_unchecked(ch)
572 fn count(self) -> usize {
573 // length in `char` is equal to the number of non-continuation bytes
574 let bytes_len = self.iter.len();
575 let mut cont_bytes = 0;
576 for &byte in self.iter {
577 cont_bytes += utf8_is_cont_byte(byte) as usize;
579 bytes_len - cont_bytes
583 fn size_hint(&self) -> (usize, Option<usize>) {
584 let len = self.iter.len();
585 // `(len + 3)` can't overflow, because we know that the `slice::Iter`
586 // belongs to a slice in memory which has a maximum length of
587 // `isize::MAX` (that's well below `usize::MAX`).
588 ((len + 3) / 4, Some(len))
592 fn last(mut self) -> Option<char> {
593 // No need to go through the entire string.
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl<'a> DoubleEndedIterator for Chars<'a> {
601 fn next_back(&mut self) -> Option<char> {
602 next_code_point_reverse(&mut self.iter).map(|ch| {
603 // str invariant says `ch` is a valid Unicode Scalar Value
605 char::from_u32_unchecked(ch)
611 #[stable(feature = "fused", since = "1.26.0")]
612 impl FusedIterator for Chars<'_> {}
615 /// View the underlying data as a subslice of the original data.
617 /// This has the same lifetime as the original slice, and so the
618 /// iterator can continue to be used while this exists.
623 /// let mut chars = "abc".chars();
625 /// assert_eq!(chars.as_str(), "abc");
627 /// assert_eq!(chars.as_str(), "bc");
630 /// assert_eq!(chars.as_str(), "");
632 #[stable(feature = "iter_to_slice", since = "1.4.0")]
634 pub fn as_str(&self) -> &'a str {
635 unsafe { from_utf8_unchecked(self.iter.as_slice()) }
639 /// An iterator over the [`char`]s of a string slice, and their positions.
641 /// [`char`]: ../../std/primitive.char.html
643 /// This struct is created by the [`char_indices`] method on [`str`].
644 /// See its documentation for more.
646 /// [`char_indices`]: ../../std/primitive.str.html#method.char_indices
647 /// [`str`]: ../../std/primitive.str.html
648 #[derive(Clone, Debug)]
649 #[stable(feature = "rust1", since = "1.0.0")]
650 pub struct CharIndices<'a> {
655 #[stable(feature = "rust1", since = "1.0.0")]
656 impl<'a> Iterator for CharIndices<'a> {
657 type Item = (usize, char);
660 fn next(&mut self) -> Option<(usize, char)> {
661 let pre_len = self.iter.iter.len();
662 match self.iter.next() {
665 let index = self.front_offset;
666 let len = self.iter.iter.len();
667 self.front_offset += pre_len - len;
674 fn count(self) -> usize {
679 fn size_hint(&self) -> (usize, Option<usize>) {
680 self.iter.size_hint()
684 fn last(mut self) -> Option<(usize, char)> {
685 // No need to go through the entire string.
690 #[stable(feature = "rust1", since = "1.0.0")]
691 impl<'a> DoubleEndedIterator for CharIndices<'a> {
693 fn next_back(&mut self) -> Option<(usize, char)> {
694 self.iter.next_back().map(|ch| {
695 let index = self.front_offset + self.iter.iter.len();
701 #[stable(feature = "fused", since = "1.26.0")]
702 impl FusedIterator for CharIndices<'_> {}
704 impl<'a> CharIndices<'a> {
705 /// View the underlying data as a subslice of the original data.
707 /// This has the same lifetime as the original slice, and so the
708 /// iterator can continue to be used while this exists.
709 #[stable(feature = "iter_to_slice", since = "1.4.0")]
711 pub fn as_str(&self) -> &'a str {
716 /// An iterator over the bytes of a string slice.
718 /// This struct is created by the [`bytes`] method on [`str`].
719 /// See its documentation for more.
721 /// [`bytes`]: ../../std/primitive.str.html#method.bytes
722 /// [`str`]: ../../std/primitive.str.html
723 #[stable(feature = "rust1", since = "1.0.0")]
724 #[derive(Clone, Debug)]
725 pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>);
727 #[stable(feature = "rust1", since = "1.0.0")]
728 impl Iterator for Bytes<'_> {
732 fn next(&mut self) -> Option<u8> {
737 fn size_hint(&self) -> (usize, Option<usize>) {
742 fn count(self) -> usize {
747 fn last(self) -> Option<Self::Item> {
752 fn nth(&mut self, n: usize) -> Option<Self::Item> {
757 fn all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
762 fn any<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
767 fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where
768 P: FnMut(&Self::Item) -> bool
770 self.0.find(predicate)
774 fn position<P>(&mut self, predicate: P) -> Option<usize> where
775 P: FnMut(Self::Item) -> bool
777 self.0.position(predicate)
781 fn rposition<P>(&mut self, predicate: P) -> Option<usize> where
782 P: FnMut(Self::Item) -> bool
784 self.0.rposition(predicate)
788 #[stable(feature = "rust1", since = "1.0.0")]
789 impl DoubleEndedIterator for Bytes<'_> {
791 fn next_back(&mut self) -> Option<u8> {
796 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> where
797 P: FnMut(&Self::Item) -> bool
799 self.0.rfind(predicate)
803 #[stable(feature = "rust1", since = "1.0.0")]
804 impl ExactSizeIterator for Bytes<'_> {
806 fn len(&self) -> usize {
811 fn is_empty(&self) -> bool {
816 #[stable(feature = "fused", since = "1.26.0")]
817 impl FusedIterator for Bytes<'_> {}
819 #[unstable(feature = "trusted_len", issue = "37572")]
820 unsafe impl TrustedLen for Bytes<'_> {}
823 unsafe impl<'a> TrustedRandomAccess for Bytes<'a> {
824 unsafe fn get_unchecked(&mut self, i: usize) -> u8 {
825 self.0.get_unchecked(i)
827 fn may_have_side_effect() -> bool { false }
830 /// This macro generates a Clone impl for string pattern API
831 /// wrapper types of the form X<'a, P>
832 macro_rules! derive_pattern_clone {
833 (clone $t:ident with |$s:ident| $e:expr) => {
834 impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
835 where P::Searcher: Clone
837 fn clone(&self) -> Self {
845 /// This macro generates two public iterator structs
846 /// wrapping a private internal one that makes use of the `Pattern` API.
848 /// For all patterns `P: Pattern<'a>` the following items will be
849 /// generated (generics omitted):
851 /// struct $forward_iterator($internal_iterator);
852 /// struct $reverse_iterator($internal_iterator);
854 /// impl Iterator for $forward_iterator
855 /// { /* internal ends up calling Searcher::next_match() */ }
857 /// impl DoubleEndedIterator for $forward_iterator
858 /// where P::Searcher: DoubleEndedSearcher
859 /// { /* internal ends up calling Searcher::next_match_back() */ }
861 /// impl Iterator for $reverse_iterator
862 /// where P::Searcher: ReverseSearcher
863 /// { /* internal ends up calling Searcher::next_match_back() */ }
865 /// impl DoubleEndedIterator for $reverse_iterator
866 /// where P::Searcher: DoubleEndedSearcher
867 /// { /* internal ends up calling Searcher::next_match() */ }
869 /// The internal one is defined outside the macro, and has almost the same
870 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
871 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
873 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
874 /// `Pattern` might not return the same elements, so actually implementing
875 /// `DoubleEndedIterator` for it would be incorrect.
876 /// (See the docs in `str::pattern` for more details)
878 /// However, the internal struct still represents a single ended iterator from
879 /// either end, and depending on pattern is also a valid double ended iterator,
880 /// so the two wrapper structs implement `Iterator`
881 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
882 /// to the complex impls seen above.
883 macro_rules! generate_pattern_iterators {
887 $(#[$forward_iterator_attribute:meta])*
888 struct $forward_iterator:ident;
892 $(#[$reverse_iterator_attribute:meta])*
893 struct $reverse_iterator:ident;
895 // Stability of all generated items
897 $(#[$common_stability_attribute:meta])*
899 // Internal almost-iterator that is being delegated to
901 $internal_iterator:ident yielding ($iterty:ty);
903 // Kind of delegation - either single ended or double ended
906 $(#[$forward_iterator_attribute])*
907 $(#[$common_stability_attribute])*
908 pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
910 $(#[$common_stability_attribute])*
911 impl<'a, P: Pattern<'a>> fmt::Debug for $forward_iterator<'a, P>
912 where P::Searcher: fmt::Debug
914 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
915 f.debug_tuple(stringify!($forward_iterator))
921 $(#[$common_stability_attribute])*
922 impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
926 fn next(&mut self) -> Option<$iterty> {
931 $(#[$common_stability_attribute])*
932 impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
933 where P::Searcher: Clone
935 fn clone(&self) -> Self {
936 $forward_iterator(self.0.clone())
940 $(#[$reverse_iterator_attribute])*
941 $(#[$common_stability_attribute])*
942 pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
944 $(#[$common_stability_attribute])*
945 impl<'a, P: Pattern<'a>> fmt::Debug for $reverse_iterator<'a, P>
946 where P::Searcher: fmt::Debug
948 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
949 f.debug_tuple(stringify!($reverse_iterator))
955 $(#[$common_stability_attribute])*
956 impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
957 where P::Searcher: ReverseSearcher<'a>
962 fn next(&mut self) -> Option<$iterty> {
967 $(#[$common_stability_attribute])*
968 impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
969 where P::Searcher: Clone
971 fn clone(&self) -> Self {
972 $reverse_iterator(self.0.clone())
976 #[stable(feature = "fused", since = "1.26.0")]
977 impl<'a, P: Pattern<'a>> FusedIterator for $forward_iterator<'a, P> {}
979 #[stable(feature = "fused", since = "1.26.0")]
980 impl<'a, P: Pattern<'a>> FusedIterator for $reverse_iterator<'a, P>
981 where P::Searcher: ReverseSearcher<'a> {}
983 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
985 $reverse_iterator, $iterty);
988 double ended; with $(#[$common_stability_attribute:meta])*,
989 $forward_iterator:ident,
990 $reverse_iterator:ident, $iterty:ty
992 $(#[$common_stability_attribute])*
993 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
994 where P::Searcher: DoubleEndedSearcher<'a>
997 fn next_back(&mut self) -> Option<$iterty> {
1002 $(#[$common_stability_attribute])*
1003 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
1004 where P::Searcher: DoubleEndedSearcher<'a>
1007 fn next_back(&mut self) -> Option<$iterty> {
1013 single ended; with $(#[$common_stability_attribute:meta])*,
1014 $forward_iterator:ident,
1015 $reverse_iterator:ident, $iterty:ty
1019 derive_pattern_clone!{
1021 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
1024 struct SplitInternal<'a, P: Pattern<'a>> {
1027 matcher: P::Searcher,
1028 allow_trailing_empty: bool,
1032 impl<'a, P: Pattern<'a>> fmt::Debug for SplitInternal<'a, P> where P::Searcher: fmt::Debug {
1033 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1034 f.debug_struct("SplitInternal")
1035 .field("start", &self.start)
1036 .field("end", &self.end)
1037 .field("matcher", &self.matcher)
1038 .field("allow_trailing_empty", &self.allow_trailing_empty)
1039 .field("finished", &self.finished)
1044 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
1046 fn get_end(&mut self) -> Option<&'a str> {
1047 if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
1048 self.finished = true;
1050 let string = self.matcher.haystack().get_unchecked(self.start..self.end);
1059 fn next(&mut self) -> Option<&'a str> {
1060 if self.finished { return None }
1062 let haystack = self.matcher.haystack();
1063 match self.matcher.next_match() {
1064 Some((a, b)) => unsafe {
1065 let elt = haystack.get_unchecked(self.start..a);
1069 None => self.get_end(),
1074 fn next_back(&mut self) -> Option<&'a str>
1075 where P::Searcher: ReverseSearcher<'a>
1077 if self.finished { return None }
1079 if !self.allow_trailing_empty {
1080 self.allow_trailing_empty = true;
1081 match self.next_back() {
1082 Some(elt) if !elt.is_empty() => return Some(elt),
1083 _ => if self.finished { return None }
1087 let haystack = self.matcher.haystack();
1088 match self.matcher.next_match_back() {
1089 Some((a, b)) => unsafe {
1090 let elt = haystack.get_unchecked(b..self.end);
1095 self.finished = true;
1096 Some(haystack.get_unchecked(self.start..self.end))
1102 generate_pattern_iterators! {
1104 /// Created with the method [`split`].
1106 /// [`split`]: ../../std/primitive.str.html#method.split
1109 /// Created with the method [`rsplit`].
1111 /// [`rsplit`]: ../../std/primitive.str.html#method.rsplit
1114 #[stable(feature = "rust1", since = "1.0.0")]
1116 SplitInternal yielding (&'a str);
1117 delegate double ended;
1120 generate_pattern_iterators! {
1122 /// Created with the method [`split_terminator`].
1124 /// [`split_terminator`]: ../../std/primitive.str.html#method.split_terminator
1125 struct SplitTerminator;
1127 /// Created with the method [`rsplit_terminator`].
1129 /// [`rsplit_terminator`]: ../../std/primitive.str.html#method.rsplit_terminator
1130 struct RSplitTerminator;
1132 #[stable(feature = "rust1", since = "1.0.0")]
1134 SplitInternal yielding (&'a str);
1135 delegate double ended;
1138 derive_pattern_clone!{
1139 clone SplitNInternal
1140 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
1143 struct SplitNInternal<'a, P: Pattern<'a>> {
1144 iter: SplitInternal<'a, P>,
1145 /// The number of splits remaining
1149 impl<'a, P: Pattern<'a>> fmt::Debug for SplitNInternal<'a, P> where P::Searcher: fmt::Debug {
1150 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1151 f.debug_struct("SplitNInternal")
1152 .field("iter", &self.iter)
1153 .field("count", &self.count)
1158 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
1160 fn next(&mut self) -> Option<&'a str> {
1163 1 => { self.count = 0; self.iter.get_end() }
1164 _ => { self.count -= 1; self.iter.next() }
1169 fn next_back(&mut self) -> Option<&'a str>
1170 where P::Searcher: ReverseSearcher<'a>
1174 1 => { self.count = 0; self.iter.get_end() }
1175 _ => { self.count -= 1; self.iter.next_back() }
1180 generate_pattern_iterators! {
1182 /// Created with the method [`splitn`].
1184 /// [`splitn`]: ../../std/primitive.str.html#method.splitn
1187 /// Created with the method [`rsplitn`].
1189 /// [`rsplitn`]: ../../std/primitive.str.html#method.rsplitn
1192 #[stable(feature = "rust1", since = "1.0.0")]
1194 SplitNInternal yielding (&'a str);
1195 delegate single ended;
1198 derive_pattern_clone!{
1199 clone MatchIndicesInternal
1200 with |s| MatchIndicesInternal(s.0.clone())
1203 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
1205 impl<'a, P: Pattern<'a>> fmt::Debug for MatchIndicesInternal<'a, P> where P::Searcher: fmt::Debug {
1206 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1207 f.debug_tuple("MatchIndicesInternal")
1213 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
1215 fn next(&mut self) -> Option<(usize, &'a str)> {
1216 self.0.next_match().map(|(start, end)| unsafe {
1217 (start, self.0.haystack().get_unchecked(start..end))
1222 fn next_back(&mut self) -> Option<(usize, &'a str)>
1223 where P::Searcher: ReverseSearcher<'a>
1225 self.0.next_match_back().map(|(start, end)| unsafe {
1226 (start, self.0.haystack().get_unchecked(start..end))
1231 generate_pattern_iterators! {
1233 /// Created with the method [`match_indices`].
1235 /// [`match_indices`]: ../../std/primitive.str.html#method.match_indices
1236 struct MatchIndices;
1238 /// Created with the method [`rmatch_indices`].
1240 /// [`rmatch_indices`]: ../../std/primitive.str.html#method.rmatch_indices
1241 struct RMatchIndices;
1243 #[stable(feature = "str_match_indices", since = "1.5.0")]
1245 MatchIndicesInternal yielding ((usize, &'a str));
1246 delegate double ended;
1249 derive_pattern_clone!{
1250 clone MatchesInternal
1251 with |s| MatchesInternal(s.0.clone())
1254 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
1256 impl<'a, P: Pattern<'a>> fmt::Debug for MatchesInternal<'a, P> where P::Searcher: fmt::Debug {
1257 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1258 f.debug_tuple("MatchesInternal")
1264 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
1266 fn next(&mut self) -> Option<&'a str> {
1267 self.0.next_match().map(|(a, b)| unsafe {
1268 // Indices are known to be on utf8 boundaries
1269 self.0.haystack().get_unchecked(a..b)
1274 fn next_back(&mut self) -> Option<&'a str>
1275 where P::Searcher: ReverseSearcher<'a>
1277 self.0.next_match_back().map(|(a, b)| unsafe {
1278 // Indices are known to be on utf8 boundaries
1279 self.0.haystack().get_unchecked(a..b)
1284 generate_pattern_iterators! {
1286 /// Created with the method [`matches`].
1288 /// [`matches`]: ../../std/primitive.str.html#method.matches
1291 /// Created with the method [`rmatches`].
1293 /// [`rmatches`]: ../../std/primitive.str.html#method.rmatches
1296 #[stable(feature = "str_matches", since = "1.2.0")]
1298 MatchesInternal yielding (&'a str);
1299 delegate double ended;
1302 /// An iterator over the lines of a string, as string slices.
1304 /// This struct is created with the [`lines`] method on [`str`].
1305 /// See its documentation for more.
1307 /// [`lines`]: ../../std/primitive.str.html#method.lines
1308 /// [`str`]: ../../std/primitive.str.html
1309 #[stable(feature = "rust1", since = "1.0.0")]
1310 #[derive(Clone, Debug)]
1311 pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>);
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 impl<'a> Iterator for Lines<'a> {
1315 type Item = &'a str;
1318 fn next(&mut self) -> Option<&'a str> {
1323 fn size_hint(&self) -> (usize, Option<usize>) {
1328 #[stable(feature = "rust1", since = "1.0.0")]
1329 impl<'a> DoubleEndedIterator for Lines<'a> {
1331 fn next_back(&mut self) -> Option<&'a str> {
1336 #[stable(feature = "fused", since = "1.26.0")]
1337 impl FusedIterator for Lines<'_> {}
1339 /// Created with the method [`lines_any`].
1341 /// [`lines_any`]: ../../std/primitive.str.html#method.lines_any
1342 #[stable(feature = "rust1", since = "1.0.0")]
1343 #[rustc_deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")]
1344 #[derive(Clone, Debug)]
1345 #[allow(deprecated)]
1346 pub struct LinesAny<'a>(Lines<'a>);
1348 /// A nameable, cloneable fn type
1352 impl<'a> Fn<(&'a str,)> for LinesAnyMap {
1354 extern "rust-call" fn call(&self, (line,): (&'a str,)) -> &'a str {
1356 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
1361 impl<'a> FnMut<(&'a str,)> for LinesAnyMap {
1363 extern "rust-call" fn call_mut(&mut self, (line,): (&'a str,)) -> &'a str {
1364 Fn::call(&*self, (line,))
1368 impl<'a> FnOnce<(&'a str,)> for LinesAnyMap {
1369 type Output = &'a str;
1372 extern "rust-call" fn call_once(self, (line,): (&'a str,)) -> &'a str {
1373 Fn::call(&self, (line,))
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 #[allow(deprecated)]
1379 impl<'a> Iterator for LinesAny<'a> {
1380 type Item = &'a str;
1383 fn next(&mut self) -> Option<&'a str> {
1388 fn size_hint(&self) -> (usize, Option<usize>) {
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 #[allow(deprecated)]
1395 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1397 fn next_back(&mut self) -> Option<&'a str> {
1402 #[stable(feature = "fused", since = "1.26.0")]
1403 #[allow(deprecated)]
1404 impl FusedIterator for LinesAny<'_> {}
1407 Section: UTF-8 validation
1410 // use truncation to fit u64 into usize
1411 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
1413 /// Returns `true` if any byte in the word `x` is nonascii (>= 128).
1415 fn contains_nonascii(x: usize) -> bool {
1416 (x & NONASCII_MASK) != 0
1419 /// Walks through `v` checking that it's a valid UTF-8 sequence,
1420 /// returning `Ok(())` in that case, or, if it is invalid, `Err(err)`.
1422 fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
1426 let usize_bytes = mem::size_of::<usize>();
1427 let ascii_block_size = 2 * usize_bytes;
1428 let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
1431 let old_offset = index;
1433 ($error_len: expr) => {
1434 return Err(Utf8Error {
1435 valid_up_to: old_offset,
1436 error_len: $error_len,
1441 macro_rules! next { () => {{
1443 // we needed data, but there was none: error!
1450 let first = v[index];
1452 let w = UTF8_CHAR_WIDTH[first as usize];
1453 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
1454 // first C2 80 last DF BF
1455 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
1456 // first E0 A0 80 last EF BF BF
1457 // excluding surrogates codepoints \u{d800} to \u{dfff}
1458 // ED A0 80 to ED BF BF
1459 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1460 // first F0 90 80 80 last F4 8F BF BF
1462 // Use the UTF-8 syntax from the RFC
1464 // https://tools.ietf.org/html/rfc3629
1466 // UTF8-2 = %xC2-DF UTF8-tail
1467 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1468 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1469 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1470 // %xF4 %x80-8F 2( UTF8-tail )
1472 2 => if next!() & !CONT_MASK != TAG_CONT_U8 {
1476 match (first, next!()) {
1477 (0xE0 , 0xA0 ..= 0xBF) |
1478 (0xE1 ..= 0xEC, 0x80 ..= 0xBF) |
1479 (0xED , 0x80 ..= 0x9F) |
1480 (0xEE ..= 0xEF, 0x80 ..= 0xBF) => {}
1483 if next!() & !CONT_MASK != TAG_CONT_U8 {
1488 match (first, next!()) {
1489 (0xF0 , 0x90 ..= 0xBF) |
1490 (0xF1 ..= 0xF3, 0x80 ..= 0xBF) |
1491 (0xF4 , 0x80 ..= 0x8F) => {}
1494 if next!() & !CONT_MASK != TAG_CONT_U8 {
1497 if next!() & !CONT_MASK != TAG_CONT_U8 {
1505 // Ascii case, try to skip forward quickly.
1506 // When the pointer is aligned, read 2 words of data per iteration
1507 // until we find a word containing a non-ascii byte.
1508 let ptr = v.as_ptr();
1509 let align = unsafe {
1510 // the offset is safe, because `index` is guaranteed inbounds
1511 ptr.add(index).align_offset(usize_bytes)
1514 while index < blocks_end {
1516 let block = ptr.add(index) as *const usize;
1517 // break if there is a nonascii byte
1518 let zu = contains_nonascii(*block);
1519 let zv = contains_nonascii(*block.offset(1));
1524 index += ascii_block_size;
1526 // step from the point where the wordwise loop stopped
1527 while index < len && v[index] < 128 {
1539 // https://tools.ietf.org/html/rfc3629
1540 static UTF8_CHAR_WIDTH: [u8; 256] = [
1541 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1542 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1543 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1544 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1545 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1546 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1547 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1548 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1549 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1550 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1551 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1552 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1553 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1554 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1555 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1556 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1559 /// Given a first byte, determines how many bytes are in this UTF-8 character.
1560 #[unstable(feature = "str_internals", issue = "0")]
1562 pub fn utf8_char_width(b: u8) -> usize {
1563 UTF8_CHAR_WIDTH[b as usize] as usize
1566 /// Mask of the value bits of a continuation byte.
1567 const CONT_MASK: u8 = 0b0011_1111;
1568 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte.
1569 const TAG_CONT_U8: u8 = 0b1000_0000;
1572 Section: Trait implementations
1578 use slice::{self, SliceIndex};
1580 /// Implements ordering of strings.
1582 /// Strings are ordered lexicographically by their byte values. This orders Unicode code
1583 /// points based on their positions in the code charts. This is not necessarily the same as
1584 /// "alphabetical" order, which varies by language and locale. Sorting strings according to
1585 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1587 #[stable(feature = "rust1", since = "1.0.0")]
1590 fn cmp(&self, other: &str) -> Ordering {
1591 self.as_bytes().cmp(other.as_bytes())
1595 #[stable(feature = "rust1", since = "1.0.0")]
1596 impl PartialEq for str {
1598 fn eq(&self, other: &str) -> bool {
1599 self.as_bytes() == other.as_bytes()
1602 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1605 #[stable(feature = "rust1", since = "1.0.0")]
1608 /// Implements comparison operations on strings.
1610 /// Strings are compared lexicographically by their byte values. This compares Unicode code
1611 /// points based on their positions in the code charts. This is not necessarily the same as
1612 /// "alphabetical" order, which varies by language and locale. Comparing strings according to
1613 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1615 #[stable(feature = "rust1", since = "1.0.0")]
1616 impl PartialOrd for str {
1618 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1619 Some(self.cmp(other))
1623 #[stable(feature = "rust1", since = "1.0.0")]
1624 impl<I> ops::Index<I> for str
1628 type Output = I::Output;
1631 fn index(&self, index: I) -> &I::Output {
1636 #[stable(feature = "rust1", since = "1.0.0")]
1637 impl<I> ops::IndexMut<I> for str
1642 fn index_mut(&mut self, index: I) -> &mut I::Output {
1643 index.index_mut(self)
1649 fn str_index_overflow_fail() -> ! {
1650 panic!("attempted to index str up to maximum usize");
1653 /// Implements substring slicing with syntax `&self[..]` or `&mut self[..]`.
1655 /// Returns a slice of the whole string, i.e., returns `&self` or `&mut
1656 /// self`. Equivalent to `&self[0 .. len]` or `&mut self[0 .. len]`. Unlike
1657 /// other indexing operations, this can never panic.
1659 /// This operation is `O(1)`.
1661 /// Prior to 1.20.0, these indexing operations were still supported by
1662 /// direct implementation of `Index` and `IndexMut`.
1664 /// Equivalent to `&self[0 .. len]` or `&mut self[0 .. len]`.
1665 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1666 impl SliceIndex<str> for ops::RangeFull {
1669 fn get(self, slice: &str) -> Option<&Self::Output> {
1673 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1677 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1681 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1685 fn index(self, slice: &str) -> &Self::Output {
1689 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1694 /// Implements substring slicing with syntax `&self[begin .. end]` or `&mut
1695 /// self[begin .. end]`.
1697 /// Returns a slice of the given string from the byte range
1698 /// [`begin`, `end`).
1700 /// This operation is `O(1)`.
1702 /// Prior to 1.20.0, these indexing operations were still supported by
1703 /// direct implementation of `Index` and `IndexMut`.
1707 /// Panics if `begin` or `end` does not point to the starting byte offset of
1708 /// a character (as defined by `is_char_boundary`), if `begin > end`, or if
1714 /// let s = "Löwe 老虎 Léopard";
1715 /// assert_eq!(&s[0 .. 1], "L");
1717 /// assert_eq!(&s[1 .. 9], "öwe 老");
1719 /// // these will panic:
1720 /// // byte 2 lies within `ö`:
1723 /// // byte 8 lies within `老`
1726 /// // byte 100 is outside the string
1727 /// // &s[3 .. 100];
1729 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1730 impl SliceIndex<str> for ops::Range<usize> {
1733 fn get(self, slice: &str) -> Option<&Self::Output> {
1734 if self.start <= self.end &&
1735 slice.is_char_boundary(self.start) &&
1736 slice.is_char_boundary(self.end) {
1737 Some(unsafe { self.get_unchecked(slice) })
1743 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1744 if self.start <= self.end &&
1745 slice.is_char_boundary(self.start) &&
1746 slice.is_char_boundary(self.end) {
1747 Some(unsafe { self.get_unchecked_mut(slice) })
1753 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1754 let ptr = slice.as_ptr().add(self.start);
1755 let len = self.end - self.start;
1756 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1759 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1760 let ptr = slice.as_ptr().add(self.start);
1761 let len = self.end - self.start;
1762 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1765 fn index(self, slice: &str) -> &Self::Output {
1766 let (start, end) = (self.start, self.end);
1767 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1770 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1771 // is_char_boundary checks that the index is in [0, .len()]
1772 // cannot reuse `get` as above, because of NLL trouble
1773 if self.start <= self.end &&
1774 slice.is_char_boundary(self.start) &&
1775 slice.is_char_boundary(self.end) {
1776 unsafe { self.get_unchecked_mut(slice) }
1778 super::slice_error_fail(slice, self.start, self.end)
1783 /// Implements substring slicing with syntax `&self[.. end]` or `&mut
1786 /// Returns a slice of the given string from the byte range [`0`, `end`).
1787 /// Equivalent to `&self[0 .. end]` or `&mut self[0 .. end]`.
1789 /// This operation is `O(1)`.
1791 /// Prior to 1.20.0, these indexing operations were still supported by
1792 /// direct implementation of `Index` and `IndexMut`.
1796 /// Panics if `end` does not point to the starting byte offset of a
1797 /// character (as defined by `is_char_boundary`), or if `end > len`.
1798 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1799 impl SliceIndex<str> for ops::RangeTo<usize> {
1802 fn get(self, slice: &str) -> Option<&Self::Output> {
1803 if slice.is_char_boundary(self.end) {
1804 Some(unsafe { self.get_unchecked(slice) })
1810 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1811 if slice.is_char_boundary(self.end) {
1812 Some(unsafe { self.get_unchecked_mut(slice) })
1818 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1819 let ptr = slice.as_ptr();
1820 super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end))
1823 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1824 let ptr = slice.as_ptr();
1825 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, self.end))
1828 fn index(self, slice: &str) -> &Self::Output {
1830 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end))
1833 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1834 // is_char_boundary checks that the index is in [0, .len()]
1835 if slice.is_char_boundary(self.end) {
1836 unsafe { self.get_unchecked_mut(slice) }
1838 super::slice_error_fail(slice, 0, self.end)
1843 /// Implements substring slicing with syntax `&self[begin ..]` or `&mut
1844 /// self[begin ..]`.
1846 /// Returns a slice of the given string from the byte range [`begin`,
1847 /// `len`). Equivalent to `&self[begin .. len]` or `&mut self[begin ..
1850 /// This operation is `O(1)`.
1852 /// Prior to 1.20.0, these indexing operations were still supported by
1853 /// direct implementation of `Index` and `IndexMut`.
1857 /// Panics if `begin` does not point to the starting byte offset of
1858 /// a character (as defined by `is_char_boundary`), or if `begin >= len`.
1859 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1860 impl SliceIndex<str> for ops::RangeFrom<usize> {
1863 fn get(self, slice: &str) -> Option<&Self::Output> {
1864 if slice.is_char_boundary(self.start) {
1865 Some(unsafe { self.get_unchecked(slice) })
1871 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1872 if slice.is_char_boundary(self.start) {
1873 Some(unsafe { self.get_unchecked_mut(slice) })
1879 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1880 let ptr = slice.as_ptr().add(self.start);
1881 let len = slice.len() - self.start;
1882 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1885 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1886 let ptr = slice.as_ptr().add(self.start);
1887 let len = slice.len() - self.start;
1888 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1891 fn index(self, slice: &str) -> &Self::Output {
1892 let (start, end) = (self.start, slice.len());
1893 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1896 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1897 // is_char_boundary checks that the index is in [0, .len()]
1898 if slice.is_char_boundary(self.start) {
1899 unsafe { self.get_unchecked_mut(slice) }
1901 super::slice_error_fail(slice, self.start, slice.len())
1906 /// Implements substring slicing with syntax `&self[begin ..= end]` or `&mut
1907 /// self[begin ..= end]`.
1909 /// Returns a slice of the given string from the byte range
1910 /// [`begin`, `end`]. Equivalent to `&self [begin .. end + 1]` or `&mut
1911 /// self[begin .. end + 1]`, except if `end` has the maximum value for
1914 /// This operation is `O(1)`.
1918 /// Panics if `begin` does not point to the starting byte offset of
1919 /// a character (as defined by `is_char_boundary`), if `end` does not point
1920 /// to the ending byte offset of a character (`end + 1` is either a starting
1921 /// byte offset or equal to `len`), if `begin > end`, or if `end >= len`.
1922 #[stable(feature = "inclusive_range", since = "1.26.0")]
1923 impl SliceIndex<str> for ops::RangeInclusive<usize> {
1926 fn get(self, slice: &str) -> Option<&Self::Output> {
1927 if *self.end() == usize::max_value() { None }
1928 else { (*self.start()..self.end()+1).get(slice) }
1931 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1932 if *self.end() == usize::max_value() { None }
1933 else { (*self.start()..self.end()+1).get_mut(slice) }
1936 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1937 (*self.start()..self.end()+1).get_unchecked(slice)
1940 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1941 (*self.start()..self.end()+1).get_unchecked_mut(slice)
1944 fn index(self, slice: &str) -> &Self::Output {
1945 if *self.end() == usize::max_value() { str_index_overflow_fail(); }
1946 (*self.start()..self.end()+1).index(slice)
1949 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1950 if *self.end() == usize::max_value() { str_index_overflow_fail(); }
1951 (*self.start()..self.end()+1).index_mut(slice)
1955 /// Implements substring slicing with syntax `&self[..= end]` or `&mut
1958 /// Returns a slice of the given string from the byte range [0, `end`].
1959 /// Equivalent to `&self [0 .. end + 1]`, except if `end` has the maximum
1960 /// value for `usize`.
1962 /// This operation is `O(1)`.
1966 /// Panics if `end` does not point to the ending byte offset of a character
1967 /// (`end + 1` is either a starting byte offset as defined by
1968 /// `is_char_boundary`, or equal to `len`), or if `end >= len`.
1969 #[stable(feature = "inclusive_range", since = "1.26.0")]
1970 impl SliceIndex<str> for ops::RangeToInclusive<usize> {
1973 fn get(self, slice: &str) -> Option<&Self::Output> {
1974 if self.end == usize::max_value() { None }
1975 else { (..self.end+1).get(slice) }
1978 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1979 if self.end == usize::max_value() { None }
1980 else { (..self.end+1).get_mut(slice) }
1983 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1984 (..self.end+1).get_unchecked(slice)
1987 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1988 (..self.end+1).get_unchecked_mut(slice)
1991 fn index(self, slice: &str) -> &Self::Output {
1992 if self.end == usize::max_value() { str_index_overflow_fail(); }
1993 (..self.end+1).index(slice)
1996 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1997 if self.end == usize::max_value() { str_index_overflow_fail(); }
1998 (..self.end+1).index_mut(slice)
2003 // truncate `&str` to length at most equal to `max`
2004 // return `true` if it were truncated, and the new str.
2005 fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
2009 while !s.is_char_boundary(max) {
2018 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
2019 const MAX_DISPLAY_LENGTH: usize = 256;
2020 let (truncated, s_trunc) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
2021 let ellipsis = if truncated { "[...]" } else { "" };
2024 if begin > s.len() || end > s.len() {
2025 let oob_index = if begin > s.len() { begin } else { end };
2026 panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
2030 assert!(begin <= end, "begin <= end ({} <= {}) when slicing `{}`{}",
2031 begin, end, s_trunc, ellipsis);
2033 // 3. character boundary
2034 let index = if !s.is_char_boundary(begin) { begin } else { end };
2035 // find the character
2036 let mut char_start = index;
2037 while !s.is_char_boundary(char_start) {
2040 // `char_start` must be less than len and a char boundary
2041 let ch = s[char_start..].chars().next().unwrap();
2042 let char_range = char_start .. char_start + ch.len_utf8();
2043 panic!("byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
2044 index, ch, char_range, s_trunc, ellipsis);
2050 /// Returns the length of `self`.
2052 /// This length is in bytes, not [`char`]s or graphemes. In other words,
2053 /// it may not be what a human considers the length of the string.
2060 /// let len = "foo".len();
2061 /// assert_eq!(3, len);
2063 /// let len = "ƒoo".len(); // fancy f!
2064 /// assert_eq!(4, len);
2066 #[stable(feature = "rust1", since = "1.0.0")]
2068 #[rustc_const_unstable(feature = "const_str_len")]
2069 pub const fn len(&self) -> usize {
2070 self.as_bytes().len()
2073 /// Returns `true` if `self` has a length of zero bytes.
2081 /// assert!(s.is_empty());
2083 /// let s = "not empty";
2084 /// assert!(!s.is_empty());
2087 #[stable(feature = "rust1", since = "1.0.0")]
2088 #[rustc_const_unstable(feature = "const_str_len")]
2089 pub const fn is_empty(&self) -> bool {
2093 /// Checks that `index`-th byte lies at the start and/or end of a
2094 /// UTF-8 code point sequence.
2096 /// The start and end of the string (when `index == self.len()`) are
2097 /// considered to be
2100 /// Returns `false` if `index` is greater than `self.len()`.
2105 /// let s = "Löwe 老虎 Léopard";
2106 /// assert!(s.is_char_boundary(0));
2108 /// assert!(s.is_char_boundary(6));
2109 /// assert!(s.is_char_boundary(s.len()));
2111 /// // second byte of `ö`
2112 /// assert!(!s.is_char_boundary(2));
2114 /// // third byte of `老`
2115 /// assert!(!s.is_char_boundary(8));
2117 #[stable(feature = "is_char_boundary", since = "1.9.0")]
2119 pub fn is_char_boundary(&self, index: usize) -> bool {
2120 // 0 and len are always ok.
2121 // Test for 0 explicitly so that it can optimize out the check
2122 // easily and skip reading string data for that case.
2123 if index == 0 || index == self.len() { return true; }
2124 match self.as_bytes().get(index) {
2126 // This is bit magic equivalent to: b < 128 || b >= 192
2127 Some(&b) => (b as i8) >= -0x40,
2131 /// Converts a string slice to a byte slice. To convert the byte slice back
2132 /// into a string slice, use the [`str::from_utf8`] function.
2134 /// [`str::from_utf8`]: ./str/fn.from_utf8.html
2141 /// let bytes = "bors".as_bytes();
2142 /// assert_eq!(b"bors", bytes);
2144 #[stable(feature = "rust1", since = "1.0.0")]
2146 #[rustc_const_unstable(feature="const_str_as_bytes")]
2147 pub const fn as_bytes(&self) -> &[u8] {
2152 unsafe { Slices { str: self }.slice }
2155 /// Converts a mutable string slice to a mutable byte slice. To convert the
2156 /// mutable byte slice back into a mutable string slice, use the
2157 /// [`str::from_utf8_mut`] function.
2159 /// [`str::from_utf8_mut`]: ./str/fn.from_utf8_mut.html
2166 /// let mut s = String::from("Hello");
2167 /// let bytes = unsafe { s.as_bytes_mut() };
2169 /// assert_eq!(b"Hello", bytes);
2175 /// let mut s = String::from("🗻∈🌏");
2178 /// let bytes = s.as_bytes_mut();
2180 /// bytes[0] = 0xF0;
2181 /// bytes[1] = 0x9F;
2182 /// bytes[2] = 0x8D;
2183 /// bytes[3] = 0x94;
2186 /// assert_eq!("🍔∈🌏", s);
2188 #[stable(feature = "str_mut_extras", since = "1.20.0")]
2190 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
2191 &mut *(self as *mut str as *mut [u8])
2194 /// Converts a string slice to a raw pointer.
2196 /// As string slices are a slice of bytes, the raw pointer points to a
2197 /// [`u8`]. This pointer will be pointing to the first byte of the string
2200 /// [`u8`]: primitive.u8.html
2207 /// let s = "Hello";
2208 /// let ptr = s.as_ptr();
2210 #[stable(feature = "rust1", since = "1.0.0")]
2212 pub const fn as_ptr(&self) -> *const u8 {
2213 self as *const str as *const u8
2216 /// Returns a subslice of `str`.
2218 /// This is the non-panicking alternative to indexing the `str`. Returns
2219 /// [`None`] whenever equivalent indexing operation would panic.
2221 /// [`None`]: option/enum.Option.html#variant.None
2226 /// let v = String::from("🗻∈🌏");
2228 /// assert_eq!(Some("🗻"), v.get(0..4));
2230 /// // indices not on UTF-8 sequence boundaries
2231 /// assert!(v.get(1..).is_none());
2232 /// assert!(v.get(..8).is_none());
2234 /// // out of bounds
2235 /// assert!(v.get(..42).is_none());
2237 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2239 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
2243 /// Returns a mutable subslice of `str`.
2245 /// This is the non-panicking alternative to indexing the `str`. Returns
2246 /// [`None`] whenever equivalent indexing operation would panic.
2248 /// [`None`]: option/enum.Option.html#variant.None
2253 /// let mut v = String::from("hello");
2254 /// // correct length
2255 /// assert!(v.get_mut(0..5).is_some());
2256 /// // out of bounds
2257 /// assert!(v.get_mut(..42).is_none());
2258 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
2260 /// assert_eq!("hello", v);
2262 /// let s = v.get_mut(0..2);
2263 /// let s = s.map(|s| {
2264 /// s.make_ascii_uppercase();
2267 /// assert_eq!(Some("HE"), s);
2269 /// assert_eq!("HEllo", v);
2271 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2273 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
2277 /// Returns a unchecked subslice of `str`.
2279 /// This is the unchecked alternative to indexing the `str`.
2283 /// Callers of this function are responsible that these preconditions are
2286 /// * The starting index must come before the ending index;
2287 /// * Indexes must be within bounds of the original slice;
2288 /// * Indexes must lie on UTF-8 sequence boundaries.
2290 /// Failing that, the returned string slice may reference invalid memory or
2291 /// violate the invariants communicated by the `str` type.
2298 /// assert_eq!("🗻", v.get_unchecked(0..4));
2299 /// assert_eq!("∈", v.get_unchecked(4..7));
2300 /// assert_eq!("🌏", v.get_unchecked(7..11));
2303 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2305 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
2306 i.get_unchecked(self)
2309 /// Returns a mutable, unchecked subslice of `str`.
2311 /// This is the unchecked alternative to indexing the `str`.
2315 /// Callers of this function are responsible that these preconditions are
2318 /// * The starting index must come before the ending index;
2319 /// * Indexes must be within bounds of the original slice;
2320 /// * Indexes must lie on UTF-8 sequence boundaries.
2322 /// Failing that, the returned string slice may reference invalid memory or
2323 /// violate the invariants communicated by the `str` type.
2328 /// let mut v = String::from("🗻∈🌏");
2330 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
2331 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
2332 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
2335 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2337 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
2338 i.get_unchecked_mut(self)
2341 /// Creates a string slice from another string slice, bypassing safety
2344 /// This is generally not recommended, use with caution! For a safe
2345 /// alternative see [`str`] and [`Index`].
2347 /// [`str`]: primitive.str.html
2348 /// [`Index`]: ops/trait.Index.html
2350 /// This new slice goes from `begin` to `end`, including `begin` but
2351 /// excluding `end`.
2353 /// To get a mutable string slice instead, see the
2354 /// [`slice_mut_unchecked`] method.
2356 /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
2360 /// Callers of this function are responsible that three preconditions are
2363 /// * `begin` must come before `end`.
2364 /// * `begin` and `end` must be byte positions within the string slice.
2365 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2372 /// let s = "Löwe 老虎 Léopard";
2375 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
2378 /// let s = "Hello, world!";
2381 /// assert_eq!("world", s.slice_unchecked(7, 12));
2384 #[stable(feature = "rust1", since = "1.0.0")]
2385 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked(begin..end)` instead")]
2387 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
2388 (begin..end).get_unchecked(self)
2391 /// Creates a string slice from another string slice, bypassing safety
2393 /// This is generally not recommended, use with caution! For a safe
2394 /// alternative see [`str`] and [`IndexMut`].
2396 /// [`str`]: primitive.str.html
2397 /// [`IndexMut`]: ops/trait.IndexMut.html
2399 /// This new slice goes from `begin` to `end`, including `begin` but
2400 /// excluding `end`.
2402 /// To get an immutable string slice instead, see the
2403 /// [`slice_unchecked`] method.
2405 /// [`slice_unchecked`]: #method.slice_unchecked
2409 /// Callers of this function are responsible that three preconditions are
2412 /// * `begin` must come before `end`.
2413 /// * `begin` and `end` must be byte positions within the string slice.
2414 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2415 #[stable(feature = "str_slice_mut", since = "1.5.0")]
2416 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked_mut(begin..end)` instead")]
2418 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
2419 (begin..end).get_unchecked_mut(self)
2422 /// Divide one string slice into two at an index.
2424 /// The argument, `mid`, should be a byte offset from the start of the
2425 /// string. It must also be on the boundary of a UTF-8 code point.
2427 /// The two slices returned go from the start of the string slice to `mid`,
2428 /// and from `mid` to the end of the string slice.
2430 /// To get mutable string slices instead, see the [`split_at_mut`]
2433 /// [`split_at_mut`]: #method.split_at_mut
2437 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2438 /// beyond the last code point of the string slice.
2445 /// let s = "Per Martin-Löf";
2447 /// let (first, last) = s.split_at(3);
2449 /// assert_eq!("Per", first);
2450 /// assert_eq!(" Martin-Löf", last);
2453 #[stable(feature = "str_split_at", since = "1.4.0")]
2454 pub fn split_at(&self, mid: usize) -> (&str, &str) {
2455 // is_char_boundary checks that the index is in [0, .len()]
2456 if self.is_char_boundary(mid) {
2458 (self.get_unchecked(0..mid),
2459 self.get_unchecked(mid..self.len()))
2462 slice_error_fail(self, 0, mid)
2466 /// Divide one mutable string slice into two at an index.
2468 /// The argument, `mid`, should be a byte offset from the start of the
2469 /// string. It must also be on the boundary of a UTF-8 code point.
2471 /// The two slices returned go from the start of the string slice to `mid`,
2472 /// and from `mid` to the end of the string slice.
2474 /// To get immutable string slices instead, see the [`split_at`] method.
2476 /// [`split_at`]: #method.split_at
2480 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2481 /// beyond the last code point of the string slice.
2488 /// let mut s = "Per Martin-Löf".to_string();
2490 /// let (first, last) = s.split_at_mut(3);
2491 /// first.make_ascii_uppercase();
2492 /// assert_eq!("PER", first);
2493 /// assert_eq!(" Martin-Löf", last);
2495 /// assert_eq!("PER Martin-Löf", s);
2498 #[stable(feature = "str_split_at", since = "1.4.0")]
2499 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
2500 // is_char_boundary checks that the index is in [0, .len()]
2501 if self.is_char_boundary(mid) {
2502 let len = self.len();
2503 let ptr = self.as_ptr() as *mut u8;
2505 (from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
2506 from_utf8_unchecked_mut(slice::from_raw_parts_mut(
2512 slice_error_fail(self, 0, mid)
2516 /// Returns an iterator over the [`char`]s of a string slice.
2518 /// As a string slice consists of valid UTF-8, we can iterate through a
2519 /// string slice by [`char`]. This method returns such an iterator.
2521 /// It's important to remember that [`char`] represents a Unicode Scalar
2522 /// Value, and may not match your idea of what a 'character' is. Iteration
2523 /// over grapheme clusters may be what you actually want.
2530 /// let word = "goodbye";
2532 /// let count = word.chars().count();
2533 /// assert_eq!(7, count);
2535 /// let mut chars = word.chars();
2537 /// assert_eq!(Some('g'), chars.next());
2538 /// assert_eq!(Some('o'), chars.next());
2539 /// assert_eq!(Some('o'), chars.next());
2540 /// assert_eq!(Some('d'), chars.next());
2541 /// assert_eq!(Some('b'), chars.next());
2542 /// assert_eq!(Some('y'), chars.next());
2543 /// assert_eq!(Some('e'), chars.next());
2545 /// assert_eq!(None, chars.next());
2548 /// Remember, [`char`]s may not match your human intuition about characters:
2553 /// let mut chars = y.chars();
2555 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
2556 /// assert_eq!(Some('\u{0306}'), chars.next());
2558 /// assert_eq!(None, chars.next());
2560 #[stable(feature = "rust1", since = "1.0.0")]
2562 pub fn chars(&self) -> Chars {
2563 Chars{iter: self.as_bytes().iter()}
2566 /// Returns an iterator over the [`char`]s of a string slice, and their
2569 /// As a string slice consists of valid UTF-8, we can iterate through a
2570 /// string slice by [`char`]. This method returns an iterator of both
2571 /// these [`char`]s, as well as their byte positions.
2573 /// The iterator yields tuples. The position is first, the [`char`] is
2581 /// let word = "goodbye";
2583 /// let count = word.char_indices().count();
2584 /// assert_eq!(7, count);
2586 /// let mut char_indices = word.char_indices();
2588 /// assert_eq!(Some((0, 'g')), char_indices.next());
2589 /// assert_eq!(Some((1, 'o')), char_indices.next());
2590 /// assert_eq!(Some((2, 'o')), char_indices.next());
2591 /// assert_eq!(Some((3, 'd')), char_indices.next());
2592 /// assert_eq!(Some((4, 'b')), char_indices.next());
2593 /// assert_eq!(Some((5, 'y')), char_indices.next());
2594 /// assert_eq!(Some((6, 'e')), char_indices.next());
2596 /// assert_eq!(None, char_indices.next());
2599 /// Remember, [`char`]s may not match your human intuition about characters:
2602 /// let yes = "y̆es";
2604 /// let mut char_indices = yes.char_indices();
2606 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
2607 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
2609 /// // note the 3 here - the last character took up two bytes
2610 /// assert_eq!(Some((3, 'e')), char_indices.next());
2611 /// assert_eq!(Some((4, 's')), char_indices.next());
2613 /// assert_eq!(None, char_indices.next());
2615 #[stable(feature = "rust1", since = "1.0.0")]
2617 pub fn char_indices(&self) -> CharIndices {
2618 CharIndices { front_offset: 0, iter: self.chars() }
2621 /// An iterator over the bytes of a string slice.
2623 /// As a string slice consists of a sequence of bytes, we can iterate
2624 /// through a string slice by byte. This method returns such an iterator.
2631 /// let mut bytes = "bors".bytes();
2633 /// assert_eq!(Some(b'b'), bytes.next());
2634 /// assert_eq!(Some(b'o'), bytes.next());
2635 /// assert_eq!(Some(b'r'), bytes.next());
2636 /// assert_eq!(Some(b's'), bytes.next());
2638 /// assert_eq!(None, bytes.next());
2640 #[stable(feature = "rust1", since = "1.0.0")]
2642 pub fn bytes(&self) -> Bytes {
2643 Bytes(self.as_bytes().iter().cloned())
2646 /// Split a string slice by whitespace.
2648 /// The iterator returned will return string slices that are sub-slices of
2649 /// the original string slice, separated by any amount of whitespace.
2651 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2652 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
2653 /// instead, use [`split_ascii_whitespace`].
2655 /// [`split_ascii_whitespace`]: #method.split_ascii_whitespace
2662 /// let mut iter = "A few words".split_whitespace();
2664 /// assert_eq!(Some("A"), iter.next());
2665 /// assert_eq!(Some("few"), iter.next());
2666 /// assert_eq!(Some("words"), iter.next());
2668 /// assert_eq!(None, iter.next());
2671 /// All kinds of whitespace are considered:
2674 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
2675 /// assert_eq!(Some("Mary"), iter.next());
2676 /// assert_eq!(Some("had"), iter.next());
2677 /// assert_eq!(Some("a"), iter.next());
2678 /// assert_eq!(Some("little"), iter.next());
2679 /// assert_eq!(Some("lamb"), iter.next());
2681 /// assert_eq!(None, iter.next());
2683 #[stable(feature = "split_whitespace", since = "1.1.0")]
2685 pub fn split_whitespace(&self) -> SplitWhitespace {
2686 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
2689 /// Split a string slice by ASCII whitespace.
2691 /// The iterator returned will return string slices that are sub-slices of
2692 /// the original string slice, separated by any amount of ASCII whitespace.
2694 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
2696 /// [`split_whitespace`]: #method.split_whitespace
2703 /// let mut iter = "A few words".split_ascii_whitespace();
2705 /// assert_eq!(Some("A"), iter.next());
2706 /// assert_eq!(Some("few"), iter.next());
2707 /// assert_eq!(Some("words"), iter.next());
2709 /// assert_eq!(None, iter.next());
2712 /// All kinds of ASCII whitespace are considered:
2715 /// let mut iter = " Mary had\ta little \n\t lamb".split_whitespace();
2716 /// assert_eq!(Some("Mary"), iter.next());
2717 /// assert_eq!(Some("had"), iter.next());
2718 /// assert_eq!(Some("a"), iter.next());
2719 /// assert_eq!(Some("little"), iter.next());
2720 /// assert_eq!(Some("lamb"), iter.next());
2722 /// assert_eq!(None, iter.next());
2724 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
2726 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace {
2729 .split(IsAsciiWhitespace)
2731 .map(UnsafeBytesToStr);
2732 SplitAsciiWhitespace { inner }
2735 /// An iterator over the lines of a string, as string slices.
2737 /// Lines are ended with either a newline (`\n`) or a carriage return with
2738 /// a line feed (`\r\n`).
2740 /// The final line ending is optional.
2747 /// let text = "foo\r\nbar\n\nbaz\n";
2748 /// let mut lines = text.lines();
2750 /// assert_eq!(Some("foo"), lines.next());
2751 /// assert_eq!(Some("bar"), lines.next());
2752 /// assert_eq!(Some(""), lines.next());
2753 /// assert_eq!(Some("baz"), lines.next());
2755 /// assert_eq!(None, lines.next());
2758 /// The final line ending isn't required:
2761 /// let text = "foo\nbar\n\r\nbaz";
2762 /// let mut lines = text.lines();
2764 /// assert_eq!(Some("foo"), lines.next());
2765 /// assert_eq!(Some("bar"), lines.next());
2766 /// assert_eq!(Some(""), lines.next());
2767 /// assert_eq!(Some("baz"), lines.next());
2769 /// assert_eq!(None, lines.next());
2771 #[stable(feature = "rust1", since = "1.0.0")]
2773 pub fn lines(&self) -> Lines {
2774 Lines(self.split_terminator('\n').map(LinesAnyMap))
2777 /// An iterator over the lines of a string.
2778 #[stable(feature = "rust1", since = "1.0.0")]
2779 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
2781 #[allow(deprecated)]
2782 pub fn lines_any(&self) -> LinesAny {
2783 LinesAny(self.lines())
2786 /// Returns an iterator of `u16` over the string encoded as UTF-16.
2793 /// let text = "Zażółć gęślą jaźń";
2795 /// let utf8_len = text.len();
2796 /// let utf16_len = text.encode_utf16().count();
2798 /// assert!(utf16_len <= utf8_len);
2800 #[stable(feature = "encode_utf16", since = "1.8.0")]
2801 pub fn encode_utf16(&self) -> EncodeUtf16 {
2802 EncodeUtf16 { chars: self.chars(), extra: 0 }
2805 /// Returns `true` if the given pattern matches a sub-slice of
2806 /// this string slice.
2808 /// Returns `false` if it does not.
2815 /// let bananas = "bananas";
2817 /// assert!(bananas.contains("nana"));
2818 /// assert!(!bananas.contains("apples"));
2820 #[stable(feature = "rust1", since = "1.0.0")]
2822 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2823 pat.is_contained_in(self)
2826 /// Returns `true` if the given pattern matches a prefix of this
2829 /// Returns `false` if it does not.
2836 /// let bananas = "bananas";
2838 /// assert!(bananas.starts_with("bana"));
2839 /// assert!(!bananas.starts_with("nana"));
2841 #[stable(feature = "rust1", since = "1.0.0")]
2842 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2843 pat.is_prefix_of(self)
2846 /// Returns `true` if the given pattern matches a suffix of this
2849 /// Returns `false` if it does not.
2856 /// let bananas = "bananas";
2858 /// assert!(bananas.ends_with("anas"));
2859 /// assert!(!bananas.ends_with("nana"));
2861 #[stable(feature = "rust1", since = "1.0.0")]
2862 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
2863 where P::Searcher: ReverseSearcher<'a>
2865 pat.is_suffix_of(self)
2868 /// Returns the byte index of the first character of this string slice that
2869 /// matches the pattern.
2871 /// Returns [`None`] if the pattern doesn't match.
2873 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2874 /// a character matches.
2876 /// [`None`]: option/enum.Option.html#variant.None
2880 /// Simple patterns:
2883 /// let s = "Löwe 老虎 Léopard";
2885 /// assert_eq!(s.find('L'), Some(0));
2886 /// assert_eq!(s.find('é'), Some(14));
2887 /// assert_eq!(s.find("Léopard"), Some(13));
2890 /// More complex patterns using point-free style and closures:
2893 /// let s = "Löwe 老虎 Léopard";
2895 /// assert_eq!(s.find(char::is_whitespace), Some(5));
2896 /// assert_eq!(s.find(char::is_lowercase), Some(1));
2897 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
2898 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
2901 /// Not finding the pattern:
2904 /// let s = "Löwe 老虎 Léopard";
2905 /// let x: &[_] = &['1', '2'];
2907 /// assert_eq!(s.find(x), None);
2909 #[stable(feature = "rust1", since = "1.0.0")]
2911 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2912 pat.into_searcher(self).next_match().map(|(i, _)| i)
2915 /// Returns the byte index of the last character of this string slice that
2916 /// matches the pattern.
2918 /// Returns [`None`] if the pattern doesn't match.
2920 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2921 /// a character matches.
2923 /// [`None`]: option/enum.Option.html#variant.None
2927 /// Simple patterns:
2930 /// let s = "Löwe 老虎 Léopard";
2932 /// assert_eq!(s.rfind('L'), Some(13));
2933 /// assert_eq!(s.rfind('é'), Some(14));
2936 /// More complex patterns with closures:
2939 /// let s = "Löwe 老虎 Léopard";
2941 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
2942 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
2945 /// Not finding the pattern:
2948 /// let s = "Löwe 老虎 Léopard";
2949 /// let x: &[_] = &['1', '2'];
2951 /// assert_eq!(s.rfind(x), None);
2953 #[stable(feature = "rust1", since = "1.0.0")]
2955 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
2956 where P::Searcher: ReverseSearcher<'a>
2958 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
2961 /// An iterator over substrings of this string slice, separated by
2962 /// characters matched by a pattern.
2964 /// The pattern can be a `&str`, [`char`], or a closure that determines the
2967 /// # Iterator behavior
2969 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
2970 /// allows a reverse search and forward/reverse search yields the same
2971 /// elements. This is true for, eg, [`char`] but not for `&str`.
2973 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
2975 /// If the pattern allows a reverse search but its results might differ
2976 /// from a forward search, the [`rsplit`] method can be used.
2978 /// [`rsplit`]: #method.rsplit
2982 /// Simple patterns:
2985 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
2986 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
2988 /// let v: Vec<&str> = "".split('X').collect();
2989 /// assert_eq!(v, [""]);
2991 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
2992 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
2994 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
2995 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
2997 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
2998 /// assert_eq!(v, ["abc", "def", "ghi"]);
3000 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
3001 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3004 /// A more complex pattern, using a closure:
3007 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
3008 /// assert_eq!(v, ["abc", "def", "ghi"]);
3011 /// If a string contains multiple contiguous separators, you will end up
3012 /// with empty strings in the output:
3015 /// let x = "||||a||b|c".to_string();
3016 /// let d: Vec<_> = x.split('|').collect();
3018 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3021 /// Contiguous separators are separated by the empty string.
3024 /// let x = "(///)".to_string();
3025 /// let d: Vec<_> = x.split('/').collect();
3027 /// assert_eq!(d, &["(", "", "", ")"]);
3030 /// Separators at the start or end of a string are neighbored
3031 /// by empty strings.
3034 /// let d: Vec<_> = "010".split("0").collect();
3035 /// assert_eq!(d, &["", "1", ""]);
3038 /// When the empty string is used as a separator, it separates
3039 /// every character in the string, along with the beginning
3040 /// and end of the string.
3043 /// let f: Vec<_> = "rust".split("").collect();
3044 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
3047 /// Contiguous separators can lead to possibly surprising behavior
3048 /// when whitespace is used as the separator. This code is correct:
3051 /// let x = " a b c".to_string();
3052 /// let d: Vec<_> = x.split(' ').collect();
3054 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3057 /// It does _not_ give you:
3060 /// assert_eq!(d, &["a", "b", "c"]);
3063 /// Use [`split_whitespace`] for this behavior.
3065 /// [`split_whitespace`]: #method.split_whitespace
3066 #[stable(feature = "rust1", since = "1.0.0")]
3068 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
3069 Split(SplitInternal {
3072 matcher: pat.into_searcher(self),
3073 allow_trailing_empty: true,
3078 /// An iterator over substrings of the given string slice, separated by
3079 /// characters matched by a pattern and yielded in reverse order.
3081 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3084 /// # Iterator behavior
3086 /// The returned iterator requires that the pattern supports a reverse
3087 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3088 /// search yields the same elements.
3090 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3092 /// For iterating from the front, the [`split`] method can be used.
3094 /// [`split`]: #method.split
3098 /// Simple patterns:
3101 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
3102 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
3104 /// let v: Vec<&str> = "".rsplit('X').collect();
3105 /// assert_eq!(v, [""]);
3107 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
3108 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
3110 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
3111 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
3114 /// A more complex pattern, using a closure:
3117 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
3118 /// assert_eq!(v, ["ghi", "def", "abc"]);
3120 #[stable(feature = "rust1", since = "1.0.0")]
3122 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
3123 where P::Searcher: ReverseSearcher<'a>
3125 RSplit(self.split(pat).0)
3128 /// An iterator over substrings of the given string slice, separated by
3129 /// characters matched by a pattern.
3131 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3134 /// Equivalent to [`split`], except that the trailing substring
3135 /// is skipped if empty.
3137 /// [`split`]: #method.split
3139 /// This method can be used for string data that is _terminated_,
3140 /// rather than _separated_ by a pattern.
3142 /// # Iterator behavior
3144 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3145 /// allows a reverse search and forward/reverse search yields the same
3146 /// elements. This is true for, eg, [`char`] but not for `&str`.
3148 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3150 /// If the pattern allows a reverse search but its results might differ
3151 /// from a forward search, the [`rsplit_terminator`] method can be used.
3153 /// [`rsplit_terminator`]: #method.rsplit_terminator
3160 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
3161 /// assert_eq!(v, ["A", "B"]);
3163 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
3164 /// assert_eq!(v, ["A", "", "B", ""]);
3166 #[stable(feature = "rust1", since = "1.0.0")]
3168 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
3169 SplitTerminator(SplitInternal {
3170 allow_trailing_empty: false,
3175 /// An iterator over substrings of `self`, separated by characters
3176 /// matched by a pattern and yielded in reverse order.
3178 /// The pattern can be a simple `&str`, [`char`], or a closure that
3179 /// determines the split.
3180 /// Additional libraries might provide more complex patterns like
3181 /// regular expressions.
3183 /// Equivalent to [`split`], except that the trailing substring is
3184 /// skipped if empty.
3186 /// [`split`]: #method.split
3188 /// This method can be used for string data that is _terminated_,
3189 /// rather than _separated_ by a pattern.
3191 /// # Iterator behavior
3193 /// The returned iterator requires that the pattern supports a
3194 /// reverse search, and it will be double ended if a forward/reverse
3195 /// search yields the same elements.
3197 /// For iterating from the front, the [`split_terminator`] method can be
3200 /// [`split_terminator`]: #method.split_terminator
3205 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
3206 /// assert_eq!(v, ["B", "A"]);
3208 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
3209 /// assert_eq!(v, ["", "B", "", "A"]);
3211 #[stable(feature = "rust1", since = "1.0.0")]
3213 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
3214 where P::Searcher: ReverseSearcher<'a>
3216 RSplitTerminator(self.split_terminator(pat).0)
3219 /// An iterator over substrings of the given string slice, separated by a
3220 /// pattern, restricted to returning at most `n` items.
3222 /// If `n` substrings are returned, the last substring (the `n`th substring)
3223 /// will contain the remainder of the string.
3225 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3228 /// # Iterator behavior
3230 /// The returned iterator will not be double ended, because it is
3231 /// not efficient to support.
3233 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
3236 /// [`rsplitn`]: #method.rsplitn
3240 /// Simple patterns:
3243 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
3244 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
3246 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
3247 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
3249 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
3250 /// assert_eq!(v, ["abcXdef"]);
3252 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
3253 /// assert_eq!(v, [""]);
3256 /// A more complex pattern, using a closure:
3259 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
3260 /// assert_eq!(v, ["abc", "defXghi"]);
3262 #[stable(feature = "rust1", since = "1.0.0")]
3264 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
3265 SplitN(SplitNInternal {
3266 iter: self.split(pat).0,
3271 /// An iterator over substrings of this string slice, separated by a
3272 /// pattern, starting from the end of the string, restricted to returning
3273 /// at most `n` items.
3275 /// If `n` substrings are returned, the last substring (the `n`th substring)
3276 /// will contain the remainder of the string.
3278 /// The pattern can be a `&str`, [`char`], or a closure that
3279 /// determines the split.
3281 /// # Iterator behavior
3283 /// The returned iterator will not be double ended, because it is not
3284 /// efficient to support.
3286 /// For splitting from the front, the [`splitn`] method can be used.
3288 /// [`splitn`]: #method.splitn
3292 /// Simple patterns:
3295 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
3296 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
3298 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
3299 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
3301 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
3302 /// assert_eq!(v, ["leopard", "lion::tiger"]);
3305 /// A more complex pattern, using a closure:
3308 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
3309 /// assert_eq!(v, ["ghi", "abc1def"]);
3311 #[stable(feature = "rust1", since = "1.0.0")]
3313 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
3314 where P::Searcher: ReverseSearcher<'a>
3316 RSplitN(self.splitn(n, pat).0)
3319 /// An iterator over the disjoint matches of a pattern within the given string
3322 /// The pattern can be a `&str`, [`char`], or a closure that
3323 /// determines if a character matches.
3325 /// # Iterator behavior
3327 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3328 /// allows a reverse search and forward/reverse search yields the same
3329 /// elements. This is true for, eg, [`char`] but not for `&str`.
3331 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3333 /// If the pattern allows a reverse search but its results might differ
3334 /// from a forward search, the [`rmatches`] method can be used.
3336 /// [`rmatches`]: #method.rmatches
3343 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
3344 /// assert_eq!(v, ["abc", "abc", "abc"]);
3346 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
3347 /// assert_eq!(v, ["1", "2", "3"]);
3349 #[stable(feature = "str_matches", since = "1.2.0")]
3351 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
3352 Matches(MatchesInternal(pat.into_searcher(self)))
3355 /// An iterator over the disjoint matches of a pattern within this string slice,
3356 /// yielded in reverse order.
3358 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3359 /// a character matches.
3361 /// # Iterator behavior
3363 /// The returned iterator requires that the pattern supports a reverse
3364 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3365 /// search yields the same elements.
3367 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3369 /// For iterating from the front, the [`matches`] method can be used.
3371 /// [`matches`]: #method.matches
3378 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
3379 /// assert_eq!(v, ["abc", "abc", "abc"]);
3381 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
3382 /// assert_eq!(v, ["3", "2", "1"]);
3384 #[stable(feature = "str_matches", since = "1.2.0")]
3386 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
3387 where P::Searcher: ReverseSearcher<'a>
3389 RMatches(self.matches(pat).0)
3392 /// An iterator over the disjoint matches of a pattern within this string
3393 /// slice as well as the index that the match starts at.
3395 /// For matches of `pat` within `self` that overlap, only the indices
3396 /// corresponding to the first match are returned.
3398 /// The pattern can be a `&str`, [`char`], or a closure that determines
3399 /// if a character matches.
3401 /// # Iterator behavior
3403 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3404 /// allows a reverse search and forward/reverse search yields the same
3405 /// elements. This is true for, eg, [`char`] but not for `&str`.
3407 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3409 /// If the pattern allows a reverse search but its results might differ
3410 /// from a forward search, the [`rmatch_indices`] method can be used.
3412 /// [`rmatch_indices`]: #method.rmatch_indices
3419 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
3420 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
3422 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
3423 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
3425 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
3426 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
3428 #[stable(feature = "str_match_indices", since = "1.5.0")]
3430 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
3431 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
3434 /// An iterator over the disjoint matches of a pattern within `self`,
3435 /// yielded in reverse order along with the index of the match.
3437 /// For matches of `pat` within `self` that overlap, only the indices
3438 /// corresponding to the last match are returned.
3440 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
3441 /// character matches.
3443 /// # Iterator behavior
3445 /// The returned iterator requires that the pattern supports a reverse
3446 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3447 /// search yields the same elements.
3449 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3451 /// For iterating from the front, the [`match_indices`] method can be used.
3453 /// [`match_indices`]: #method.match_indices
3460 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
3461 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
3463 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
3464 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
3466 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
3467 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
3469 #[stable(feature = "str_match_indices", since = "1.5.0")]
3471 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
3472 where P::Searcher: ReverseSearcher<'a>
3474 RMatchIndices(self.match_indices(pat).0)
3477 /// Returns a string slice with leading and trailing whitespace removed.
3479 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3480 /// Core Property `White_Space`.
3487 /// let s = " Hello\tworld\t";
3489 /// assert_eq!("Hello\tworld", s.trim());
3491 #[must_use = "this returns the trimmed string as a slice, \
3492 without modifying the original"]
3493 #[stable(feature = "rust1", since = "1.0.0")]
3494 pub fn trim(&self) -> &str {
3495 self.trim_matches(|c: char| c.is_whitespace())
3498 /// Returns a string slice with leading whitespace removed.
3500 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3501 /// Core Property `White_Space`.
3503 /// # Text directionality
3505 /// A string is a sequence of bytes. `start` in this context means the first
3506 /// position of that byte string; for a left-to-right language like English or
3507 /// Russian, this will be left side; and for right-to-left languages like
3508 /// like Arabic or Hebrew, this will be the right side.
3515 /// let s = " Hello\tworld\t";
3516 /// assert_eq!("Hello\tworld\t", s.trim_start());
3522 /// let s = " English ";
3523 /// assert!(Some('E') == s.trim_start().chars().next());
3525 /// let s = " עברית ";
3526 /// assert!(Some('ע') == s.trim_start().chars().next());
3528 #[must_use = "this returns the trimmed string as a new slice, \
3529 without modifying the original"]
3530 #[stable(feature = "trim_direction", since = "1.30.0")]
3531 pub fn trim_start(&self) -> &str {
3532 self.trim_start_matches(|c: char| c.is_whitespace())
3535 /// Returns a string slice with trailing whitespace removed.
3537 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3538 /// Core Property `White_Space`.
3540 /// # Text directionality
3542 /// A string is a sequence of bytes. `end` in this context means the last
3543 /// position of that byte string; for a left-to-right language like English or
3544 /// Russian, this will be right side; and for right-to-left languages like
3545 /// like Arabic or Hebrew, this will be the left side.
3552 /// let s = " Hello\tworld\t";
3553 /// assert_eq!(" Hello\tworld", s.trim_end());
3559 /// let s = " English ";
3560 /// assert!(Some('h') == s.trim_end().chars().rev().next());
3562 /// let s = " עברית ";
3563 /// assert!(Some('ת') == s.trim_end().chars().rev().next());
3565 #[must_use = "this returns the trimmed string as a new slice, \
3566 without modifying the original"]
3567 #[stable(feature = "trim_direction", since = "1.30.0")]
3568 pub fn trim_end(&self) -> &str {
3569 self.trim_end_matches(|c: char| c.is_whitespace())
3572 /// Returns a string slice with leading whitespace removed.
3574 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3575 /// Core Property `White_Space`.
3577 /// # Text directionality
3579 /// A string is a sequence of bytes. 'Left' in this context means the first
3580 /// position of that byte string; for a language like Arabic or Hebrew
3581 /// which are 'right to left' rather than 'left to right', this will be
3582 /// the _right_ side, not the left.
3589 /// let s = " Hello\tworld\t";
3591 /// assert_eq!("Hello\tworld\t", s.trim_left());
3597 /// let s = " English";
3598 /// assert!(Some('E') == s.trim_left().chars().next());
3600 /// let s = " עברית";
3601 /// assert!(Some('ע') == s.trim_left().chars().next());
3603 #[stable(feature = "rust1", since = "1.0.0")]
3604 #[rustc_deprecated(reason = "superseded by `trim_start`", since = "1.33.0")]
3605 pub fn trim_left(&self) -> &str {
3609 /// Returns a string slice with trailing whitespace removed.
3611 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3612 /// Core Property `White_Space`.
3614 /// # Text directionality
3616 /// A string is a sequence of bytes. 'Right' in this context means the last
3617 /// position of that byte string; for a language like Arabic or Hebrew
3618 /// which are 'right to left' rather than 'left to right', this will be
3619 /// the _left_ side, not the right.
3626 /// let s = " Hello\tworld\t";
3628 /// assert_eq!(" Hello\tworld", s.trim_right());
3634 /// let s = "English ";
3635 /// assert!(Some('h') == s.trim_right().chars().rev().next());
3637 /// let s = "עברית ";
3638 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
3640 #[stable(feature = "rust1", since = "1.0.0")]
3641 #[rustc_deprecated(reason = "superseded by `trim_end`", since = "1.33.0")]
3642 pub fn trim_right(&self) -> &str {
3646 /// Returns a string slice with all prefixes and suffixes that match a
3647 /// pattern repeatedly removed.
3649 /// The pattern can be a [`char`] or a closure that determines if a
3650 /// character matches.
3654 /// Simple patterns:
3657 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
3658 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
3660 /// let x: &[_] = &['1', '2'];
3661 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
3664 /// A more complex pattern, using a closure:
3667 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
3669 #[must_use = "this returns the trimmed string as a new slice, \
3670 without modifying the original"]
3671 #[stable(feature = "rust1", since = "1.0.0")]
3672 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3673 where P::Searcher: DoubleEndedSearcher<'a>
3677 let mut matcher = pat.into_searcher(self);
3678 if let Some((a, b)) = matcher.next_reject() {
3680 j = b; // Remember earliest known match, correct it below if
3681 // last match is different
3683 if let Some((_, b)) = matcher.next_reject_back() {
3687 // Searcher is known to return valid indices
3688 self.get_unchecked(i..j)
3692 /// Returns a string slice with all prefixes that match a pattern
3693 /// repeatedly removed.
3695 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3696 /// a character matches.
3698 /// # Text directionality
3700 /// A string is a sequence of bytes. 'Left' in this context means the first
3701 /// position of that byte string; for a language like Arabic or Hebrew
3702 /// which are 'right to left' rather than 'left to right', this will be
3703 /// the _right_ side, not the left.
3710 /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
3711 /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
3713 /// let x: &[_] = &['1', '2'];
3714 /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
3716 #[must_use = "this returns the trimmed string as a new slice, \
3717 without modifying the original"]
3718 #[stable(feature = "trim_direction", since = "1.30.0")]
3719 pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3720 let mut i = self.len();
3721 let mut matcher = pat.into_searcher(self);
3722 if let Some((a, _)) = matcher.next_reject() {
3726 // Searcher is known to return valid indices
3727 self.get_unchecked(i..self.len())
3731 /// Returns a string slice with all suffixes that match a pattern
3732 /// repeatedly removed.
3734 /// The pattern can be a `&str`, [`char`], or a closure that
3735 /// determines if a character matches.
3737 /// # Text directionality
3739 /// A string is a sequence of bytes. 'Right' in this context means the last
3740 /// position of that byte string; for a language like Arabic or Hebrew
3741 /// which are 'right to left' rather than 'left to right', this will be
3742 /// the _left_ side, not the right.
3746 /// Simple patterns:
3749 /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
3750 /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
3752 /// let x: &[_] = &['1', '2'];
3753 /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
3756 /// A more complex pattern, using a closure:
3759 /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
3761 #[must_use = "this returns the trimmed string as a new slice, \
3762 without modifying the original"]
3763 #[stable(feature = "trim_direction", since = "1.30.0")]
3764 pub fn trim_end_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3765 where P::Searcher: ReverseSearcher<'a>
3768 let mut matcher = pat.into_searcher(self);
3769 if let Some((_, b)) = matcher.next_reject_back() {
3773 // Searcher is known to return valid indices
3774 self.get_unchecked(0..j)
3778 /// Returns a string slice with all prefixes that match a pattern
3779 /// repeatedly removed.
3781 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3782 /// a character matches.
3784 /// [`char`]: primitive.char.html
3786 /// # Text directionality
3788 /// A string is a sequence of bytes. `start` in this context means the first
3789 /// position of that byte string; for a left-to-right language like English or
3790 /// Russian, this will be left side; and for right-to-left languages like
3791 /// like Arabic or Hebrew, this will be the right side.
3798 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
3799 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
3801 /// let x: &[_] = &['1', '2'];
3802 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
3804 #[stable(feature = "rust1", since = "1.0.0")]
3805 #[rustc_deprecated(reason = "superseded by `trim_start_matches`", since = "1.33.0")]
3806 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3807 self.trim_start_matches(pat)
3810 /// Returns a string slice with all suffixes that match a pattern
3811 /// repeatedly removed.
3813 /// The pattern can be a `&str`, [`char`], or a closure that
3814 /// determines if a character matches.
3816 /// [`char`]: primitive.char.html
3818 /// # Text directionality
3820 /// A string is a sequence of bytes. `end` in this context means the last
3821 /// position of that byte string; for a left-to-right language like English or
3822 /// Russian, this will be right side; and for right-to-left languages like
3823 /// like Arabic or Hebrew, this will be the left side.
3827 /// Simple patterns:
3830 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
3831 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
3833 /// let x: &[_] = &['1', '2'];
3834 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
3837 /// A more complex pattern, using a closure:
3840 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
3842 #[stable(feature = "rust1", since = "1.0.0")]
3843 #[rustc_deprecated(reason = "superseded by `trim_end_matches`", since = "1.33.0")]
3844 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3845 where P::Searcher: ReverseSearcher<'a>
3847 self.trim_end_matches(pat)
3850 /// Parses this string slice into another type.
3852 /// Because `parse` is so general, it can cause problems with type
3853 /// inference. As such, `parse` is one of the few times you'll see
3854 /// the syntax affectionately known as the 'turbofish': `::<>`. This
3855 /// helps the inference algorithm understand specifically which type
3856 /// you're trying to parse into.
3858 /// `parse` can parse any type that implements the [`FromStr`] trait.
3860 /// [`FromStr`]: str/trait.FromStr.html
3864 /// Will return [`Err`] if it's not possible to parse this string slice into
3865 /// the desired type.
3867 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
3874 /// let four: u32 = "4".parse().unwrap();
3876 /// assert_eq!(4, four);
3879 /// Using the 'turbofish' instead of annotating `four`:
3882 /// let four = "4".parse::<u32>();
3884 /// assert_eq!(Ok(4), four);
3887 /// Failing to parse:
3890 /// let nope = "j".parse::<u32>();
3892 /// assert!(nope.is_err());
3895 #[stable(feature = "rust1", since = "1.0.0")]
3896 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
3897 FromStr::from_str(self)
3900 /// Checks if all characters in this string are within the ASCII range.
3905 /// let ascii = "hello!\n";
3906 /// let non_ascii = "Grüße, Jürgen ❤";
3908 /// assert!(ascii.is_ascii());
3909 /// assert!(!non_ascii.is_ascii());
3911 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3913 pub fn is_ascii(&self) -> bool {
3914 // We can treat each byte as character here: all multibyte characters
3915 // start with a byte that is not in the ascii range, so we will stop
3917 self.bytes().all(|b| b.is_ascii())
3920 /// Checks that two strings are an ASCII case-insensitive match.
3922 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
3923 /// but without allocating and copying temporaries.
3928 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
3929 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
3930 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
3932 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3934 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
3935 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
3938 /// Converts this string to its ASCII upper case equivalent in-place.
3940 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3941 /// but non-ASCII letters are unchanged.
3943 /// To return a new uppercased value without modifying the existing one, use
3944 /// [`to_ascii_uppercase`].
3946 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3947 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3948 pub fn make_ascii_uppercase(&mut self) {
3949 let me = unsafe { self.as_bytes_mut() };
3950 me.make_ascii_uppercase()
3953 /// Converts this string to its ASCII lower case equivalent in-place.
3955 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3956 /// but non-ASCII letters are unchanged.
3958 /// To return a new lowercased value without modifying the existing one, use
3959 /// [`to_ascii_lowercase`].
3961 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3962 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3963 pub fn make_ascii_lowercase(&mut self) {
3964 let me = unsafe { self.as_bytes_mut() };
3965 me.make_ascii_lowercase()
3969 #[stable(feature = "rust1", since = "1.0.0")]
3970 impl AsRef<[u8]> for str {
3972 fn as_ref(&self) -> &[u8] {
3977 #[stable(feature = "rust1", since = "1.0.0")]
3978 impl Default for &str {
3979 /// Creates an empty str
3980 fn default() -> Self { "" }
3983 #[stable(feature = "default_mut_str", since = "1.28.0")]
3984 impl Default for &mut str {
3985 /// Creates an empty mutable str
3986 fn default() -> Self { unsafe { from_utf8_unchecked_mut(&mut []) } }
3989 /// An iterator over the non-whitespace substrings of a string,
3990 /// separated by any amount of whitespace.
3992 /// This struct is created by the [`split_whitespace`] method on [`str`].
3993 /// See its documentation for more.
3995 /// [`split_whitespace`]: ../../std/primitive.str.html#method.split_whitespace
3996 /// [`str`]: ../../std/primitive.str.html
3997 #[stable(feature = "split_whitespace", since = "1.1.0")]
3998 #[derive(Clone, Debug)]
3999 pub struct SplitWhitespace<'a> {
4000 inner: Filter<Split<'a, IsWhitespace>, IsNotEmpty>,
4003 /// An iterator over the non-ASCII-whitespace substrings of a string,
4004 /// separated by any amount of ASCII whitespace.
4006 /// This struct is created by the [`split_ascii_whitespace`] method on [`str`].
4007 /// See its documentation for more.
4009 /// [`split_ascii_whitespace`]: ../../std/primitive.str.html#method.split_ascii_whitespace
4010 /// [`str`]: ../../std/primitive.str.html
4011 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4012 #[derive(Clone, Debug)]
4013 pub struct SplitAsciiWhitespace<'a> {
4014 inner: Map<Filter<SliceSplit<'a, u8, IsAsciiWhitespace>, IsNotEmpty>, UnsafeBytesToStr>,
4018 struct IsWhitespace;
4020 impl FnOnce<(char, )> for IsWhitespace {
4024 extern "rust-call" fn call_once(mut self, arg: (char, )) -> bool {
4029 impl FnMut<(char, )> for IsWhitespace {
4031 extern "rust-call" fn call_mut(&mut self, arg: (char, )) -> bool {
4032 arg.0.is_whitespace()
4037 struct IsAsciiWhitespace;
4039 impl<'a> FnOnce<(&'a u8, )> for IsAsciiWhitespace {
4043 extern "rust-call" fn call_once(mut self, arg: (&u8, )) -> bool {
4048 impl<'a> FnMut<(&'a u8, )> for IsAsciiWhitespace {
4050 extern "rust-call" fn call_mut(&mut self, arg: (&u8, )) -> bool {
4051 arg.0.is_ascii_whitespace()
4058 impl<'a, 'b> FnOnce<(&'a &'b str, )> for IsNotEmpty {
4062 extern "rust-call" fn call_once(mut self, arg: (&'a &'b str, )) -> bool {
4067 impl<'a, 'b> FnMut<(&'a &'b str, )> for IsNotEmpty {
4069 extern "rust-call" fn call_mut(&mut self, arg: (&'a &'b str, )) -> bool {
4074 impl<'a, 'b> FnOnce<(&'a &'b [u8], )> for IsNotEmpty {
4078 extern "rust-call" fn call_once(mut self, arg: (&'a &'b [u8], )) -> bool {
4083 impl<'a, 'b> FnMut<(&'a &'b [u8], )> for IsNotEmpty {
4085 extern "rust-call" fn call_mut(&mut self, arg: (&'a &'b [u8], )) -> bool {
4091 struct UnsafeBytesToStr;
4093 impl<'a> FnOnce<(&'a [u8], )> for UnsafeBytesToStr {
4094 type Output = &'a str;
4097 extern "rust-call" fn call_once(mut self, arg: (&'a [u8], )) -> &'a str {
4102 impl<'a> FnMut<(&'a [u8], )> for UnsafeBytesToStr {
4104 extern "rust-call" fn call_mut(&mut self, arg: (&'a [u8], )) -> &'a str {
4105 unsafe { from_utf8_unchecked(arg.0) }
4110 #[stable(feature = "split_whitespace", since = "1.1.0")]
4111 impl<'a> Iterator for SplitWhitespace<'a> {
4112 type Item = &'a str;
4115 fn next(&mut self) -> Option<&'a str> {
4120 fn size_hint(&self) -> (usize, Option<usize>) {
4121 self.inner.size_hint()
4125 #[stable(feature = "split_whitespace", since = "1.1.0")]
4126 impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
4128 fn next_back(&mut self) -> Option<&'a str> {
4129 self.inner.next_back()
4133 #[stable(feature = "fused", since = "1.26.0")]
4134 impl FusedIterator for SplitWhitespace<'_> {}
4136 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4137 impl<'a> Iterator for SplitAsciiWhitespace<'a> {
4138 type Item = &'a str;
4141 fn next(&mut self) -> Option<&'a str> {
4146 fn size_hint(&self) -> (usize, Option<usize>) {
4147 self.inner.size_hint()
4151 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4152 impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> {
4154 fn next_back(&mut self) -> Option<&'a str> {
4155 self.inner.next_back()
4159 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4160 impl FusedIterator for SplitAsciiWhitespace<'_> {}
4162 /// An iterator of [`u16`] over the string encoded as UTF-16.
4164 /// [`u16`]: ../../std/primitive.u16.html
4166 /// This struct is created by the [`encode_utf16`] method on [`str`].
4167 /// See its documentation for more.
4169 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
4170 /// [`str`]: ../../std/primitive.str.html
4172 #[stable(feature = "encode_utf16", since = "1.8.0")]
4173 pub struct EncodeUtf16<'a> {
4178 #[stable(feature = "collection_debug", since = "1.17.0")]
4179 impl fmt::Debug for EncodeUtf16<'_> {
4180 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4181 f.pad("EncodeUtf16 { .. }")
4185 #[stable(feature = "encode_utf16", since = "1.8.0")]
4186 impl<'a> Iterator for EncodeUtf16<'a> {
4190 fn next(&mut self) -> Option<u16> {
4191 if self.extra != 0 {
4192 let tmp = self.extra;
4197 let mut buf = [0; 2];
4198 self.chars.next().map(|ch| {
4199 let n = ch.encode_utf16(&mut buf).len();
4201 self.extra = buf[1];
4208 fn size_hint(&self) -> (usize, Option<usize>) {
4209 let (low, high) = self.chars.size_hint();
4210 // every char gets either one u16 or two u16,
4211 // so this iterator is between 1 or 2 times as
4212 // long as the underlying iterator.
4213 (low, high.and_then(|n| n.checked_mul(2)))
4217 #[stable(feature = "fused", since = "1.26.0")]
4218 impl FusedIterator for EncodeUtf16<'_> {}