1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! String manipulation
13 //! For more details, see std::str
15 #![stable(feature = "rust1", since = "1.0.0")]
17 use self::pattern::Pattern;
18 use self::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
22 use iter::{Map, Cloned, FusedIterator, TrustedLen, Filter};
23 use iter_private::TrustedRandomAccess;
24 use slice::{self, SliceIndex, Split as SliceSplit};
29 #[unstable(feature = "str_internals", issue = "0")]
30 #[allow(missing_docs)]
33 /// A trait to abstract the idea of creating a new instance of a type from a
36 /// `FromStr`'s [`from_str`] method is often used implicitly, through
37 /// [`str`]'s [`parse`] method. See [`parse`]'s documentation for examples.
39 /// [`from_str`]: #tymethod.from_str
40 /// [`str`]: ../../std/primitive.str.html
41 /// [`parse`]: ../../std/primitive.str.html#method.parse
45 /// Basic implementation of `FromStr` on an example `Point` type:
48 /// use std::str::FromStr;
49 /// use std::num::ParseIntError;
51 /// #[derive(Debug, PartialEq)]
57 /// impl FromStr for Point {
58 /// type Err = ParseIntError;
60 /// fn from_str(s: &str) -> Result<Self, Self::Err> {
61 /// let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
65 /// let x_fromstr = coords[0].parse::<i32>()?;
66 /// let y_fromstr = coords[1].parse::<i32>()?;
68 /// Ok(Point { x: x_fromstr, y: y_fromstr })
72 /// let p = Point::from_str("(1,2)");
73 /// assert_eq!(p.unwrap(), Point{ x: 1, y: 2} )
75 #[stable(feature = "rust1", since = "1.0.0")]
76 pub trait FromStr: Sized {
77 /// The associated error which can be returned from parsing.
78 #[stable(feature = "rust1", since = "1.0.0")]
81 /// Parses a string `s` to return a value of this type.
83 /// If parsing succeeds, return the value inside [`Ok`], otherwise
84 /// when the string is ill-formatted return an error specific to the
85 /// inside [`Err`]. The error type is specific to implementation of the trait.
87 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
88 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
92 /// Basic usage with [`i32`][ithirtytwo], a type that implements `FromStr`:
94 /// [ithirtytwo]: ../../std/primitive.i32.html
97 /// use std::str::FromStr;
100 /// let x = i32::from_str(s).unwrap();
102 /// assert_eq!(5, x);
104 #[stable(feature = "rust1", since = "1.0.0")]
105 fn from_str(s: &str) -> Result<Self, Self::Err>;
108 #[stable(feature = "rust1", since = "1.0.0")]
109 impl FromStr for bool {
110 type Err = ParseBoolError;
112 /// Parse a `bool` from a string.
114 /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
115 /// actually be parseable.
120 /// use std::str::FromStr;
122 /// assert_eq!(FromStr::from_str("true"), Ok(true));
123 /// assert_eq!(FromStr::from_str("false"), Ok(false));
124 /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
127 /// Note, in many cases, the `.parse()` method on `str` is more proper.
130 /// assert_eq!("true".parse(), Ok(true));
131 /// assert_eq!("false".parse(), Ok(false));
132 /// assert!("not even a boolean".parse::<bool>().is_err());
135 fn from_str(s: &str) -> Result<bool, ParseBoolError> {
138 "false" => Ok(false),
139 _ => Err(ParseBoolError { _priv: () }),
144 /// An error returned when parsing a `bool` using [`from_str`] fails
146 /// [`from_str`]: ../../std/primitive.bool.html#method.from_str
147 #[derive(Debug, Clone, PartialEq, Eq)]
148 #[stable(feature = "rust1", since = "1.0.0")]
149 pub struct ParseBoolError { _priv: () }
151 #[stable(feature = "rust1", since = "1.0.0")]
152 impl fmt::Display for ParseBoolError {
153 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
154 "provided string was not `true` or `false`".fmt(f)
159 Section: Creating a string
162 /// Errors which can occur when attempting to interpret a sequence of [`u8`]
165 /// [`u8`]: ../../std/primitive.u8.html
167 /// As such, the `from_utf8` family of functions and methods for both [`String`]s
168 /// and [`&str`]s make use of this error, for example.
170 /// [`String`]: ../../std/string/struct.String.html#method.from_utf8
171 /// [`&str`]: ../../std/str/fn.from_utf8.html
175 /// This error type’s methods can be used to create functionality
176 /// similar to `String::from_utf8_lossy` without allocating heap memory:
179 /// fn from_utf8_lossy<F>(mut input: &[u8], mut push: F) where F: FnMut(&str) {
181 /// match ::std::str::from_utf8(input) {
187 /// let (valid, after_valid) = input.split_at(error.valid_up_to());
189 /// push(::std::str::from_utf8_unchecked(valid))
191 /// push("\u{FFFD}");
193 /// if let Some(invalid_sequence_length) = error.error_len() {
194 /// input = &after_valid[invalid_sequence_length..]
203 #[derive(Copy, Eq, PartialEq, Clone, Debug)]
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub struct Utf8Error {
207 error_len: Option<u8>,
211 /// Returns the index in the given string up to which valid UTF-8 was
214 /// It is the maximum index such that `from_utf8(&input[..index])`
215 /// would return `Ok(_)`.
224 /// // some invalid bytes, in a vector
225 /// let sparkle_heart = vec![0, 159, 146, 150];
227 /// // std::str::from_utf8 returns a Utf8Error
228 /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
230 /// // the second byte is invalid here
231 /// assert_eq!(1, error.valid_up_to());
233 #[stable(feature = "utf8_error", since = "1.5.0")]
234 pub fn valid_up_to(&self) -> usize { self.valid_up_to }
236 /// Provide more information about the failure:
238 /// * `None`: the end of the input was reached unexpectedly.
239 /// `self.valid_up_to()` is 1 to 3 bytes from the end of the input.
240 /// If a byte stream (such as a file or a network socket) is being decoded incrementally,
241 /// this could be a valid `char` whose UTF-8 byte sequence is spanning multiple chunks.
243 /// * `Some(len)`: an unexpected byte was encountered.
244 /// The length provided is that of the invalid byte sequence
245 /// that starts at the index given by `valid_up_to()`.
246 /// Decoding should resume after that sequence
247 /// (after inserting a [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD]) in case of
250 /// [U+FFFD]: ../../std/char/constant.REPLACEMENT_CHARACTER.html
251 #[stable(feature = "utf8_error_error_len", since = "1.20.0")]
252 pub fn error_len(&self) -> Option<usize> {
253 self.error_len.map(|len| len as usize)
257 /// Converts a slice of bytes to a string slice.
259 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
260 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
261 /// the two. Not all byte slices are valid string slices, however: [`&str`] requires
262 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
263 /// UTF-8, and then does the conversion.
265 /// [`&str`]: ../../std/primitive.str.html
266 /// [`u8`]: ../../std/primitive.u8.html
267 /// [byteslice]: ../../std/primitive.slice.html
269 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
270 /// incur the overhead of the validity check, there is an unsafe version of
271 /// this function, [`from_utf8_unchecked`][fromutf8u], which has the same
272 /// behavior but skips the check.
274 /// [fromutf8u]: fn.from_utf8_unchecked.html
276 /// If you need a `String` instead of a `&str`, consider
277 /// [`String::from_utf8`][string].
279 /// [string]: ../../std/string/struct.String.html#method.from_utf8
281 /// Because you can stack-allocate a `[u8; N]`, and you can take a
282 /// [`&[u8]`][byteslice] of it, this function is one way to have a
283 /// stack-allocated string. There is an example of this in the
284 /// examples section below.
286 /// [byteslice]: ../../std/primitive.slice.html
290 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
291 /// provided slice is not UTF-8.
300 /// // some bytes, in a vector
301 /// let sparkle_heart = vec![240, 159, 146, 150];
303 /// // We know these bytes are valid, so just use `unwrap()`.
304 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
306 /// assert_eq!("💖", sparkle_heart);
314 /// // some invalid bytes, in a vector
315 /// let sparkle_heart = vec![0, 159, 146, 150];
317 /// assert!(str::from_utf8(&sparkle_heart).is_err());
320 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
321 /// errors that can be returned.
323 /// [error]: struct.Utf8Error.html
325 /// A "stack allocated string":
330 /// // some bytes, in a stack-allocated array
331 /// let sparkle_heart = [240, 159, 146, 150];
333 /// // We know these bytes are valid, so just use `unwrap()`.
334 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
336 /// assert_eq!("💖", sparkle_heart);
338 #[stable(feature = "rust1", since = "1.0.0")]
339 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
340 run_utf8_validation(v)?;
341 Ok(unsafe { from_utf8_unchecked(v) })
344 /// Converts a mutable slice of bytes to a mutable string slice.
353 /// // "Hello, Rust!" as a mutable vector
354 /// let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
356 /// // As we know these bytes are valid, we can use `unwrap()`
357 /// let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
359 /// assert_eq!("Hello, Rust!", outstr);
367 /// // Some invalid bytes in a mutable vector
368 /// let mut invalid = vec![128, 223];
370 /// assert!(str::from_utf8_mut(&mut invalid).is_err());
372 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
373 /// errors that can be returned.
375 /// [error]: struct.Utf8Error.html
376 #[stable(feature = "str_mut_extras", since = "1.20.0")]
377 pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
378 run_utf8_validation(v)?;
379 Ok(unsafe { from_utf8_unchecked_mut(v) })
382 /// Converts a slice of bytes to a string slice without checking
383 /// that the string contains valid UTF-8.
385 /// See the safe version, [`from_utf8`][fromutf8], for more information.
387 /// [fromutf8]: fn.from_utf8.html
391 /// This function is unsafe because it does not check that the bytes passed to
392 /// it are valid UTF-8. If this constraint is violated, undefined behavior
393 /// results, as the rest of Rust assumes that [`&str`]s are valid UTF-8.
395 /// [`&str`]: ../../std/primitive.str.html
404 /// // some bytes, in a vector
405 /// let sparkle_heart = vec![240, 159, 146, 150];
407 /// let sparkle_heart = unsafe {
408 /// str::from_utf8_unchecked(&sparkle_heart)
411 /// assert_eq!("💖", sparkle_heart);
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
416 &*(v as *const [u8] as *const str)
419 /// Converts a slice of bytes to a string slice without checking
420 /// that the string contains valid UTF-8; mutable version.
422 /// See the immutable version, [`from_utf8_unchecked()`][fromutf8], for more information.
424 /// [fromutf8]: fn.from_utf8_unchecked.html
433 /// let mut heart = vec![240, 159, 146, 150];
434 /// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
436 /// assert_eq!("💖", heart);
439 #[stable(feature = "str_mut_extras", since = "1.20.0")]
440 pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
441 &mut *(v as *mut [u8] as *mut str)
444 #[stable(feature = "rust1", since = "1.0.0")]
445 impl fmt::Display for Utf8Error {
446 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
447 if let Some(error_len) = self.error_len {
448 write!(f, "invalid utf-8 sequence of {} bytes from index {}",
449 error_len, self.valid_up_to)
451 write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to)
460 /// An iterator over the [`char`]s of a string slice.
462 /// [`char`]: ../../std/primitive.char.html
464 /// This struct is created by the [`chars`] method on [`str`].
465 /// See its documentation for more.
467 /// [`chars`]: ../../std/primitive.str.html#method.chars
468 /// [`str`]: ../../std/primitive.str.html
469 #[derive(Clone, Debug)]
470 #[stable(feature = "rust1", since = "1.0.0")]
471 pub struct Chars<'a> {
472 iter: slice::Iter<'a, u8>
475 /// Returns the initial codepoint accumulator for the first byte.
476 /// The first byte is special, only want bottom 5 bits for width 2, 4 bits
477 /// for width 3, and 3 bits for width 4.
479 fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
481 /// Returns the value of `ch` updated with continuation byte `byte`.
483 fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
485 /// Checks whether the byte is a UTF-8 continuation byte (i.e. starts with the
488 fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
491 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
498 /// Reads the next code point out of a byte iterator (assuming a
499 /// UTF-8-like encoding).
500 #[unstable(feature = "str_internals", issue = "0")]
502 pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
504 let x = *bytes.next()?;
506 return Some(x as u32)
509 // Multibyte case follows
510 // Decode from a byte combination out of: [[[x y] z] w]
511 // NOTE: Performance is sensitive to the exact formulation here
512 let init = utf8_first_byte(x, 2);
513 let y = unwrap_or_0(bytes.next());
514 let mut ch = utf8_acc_cont_byte(init, y);
517 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
518 let z = unwrap_or_0(bytes.next());
519 let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
520 ch = init << 12 | y_z;
523 // use only the lower 3 bits of `init`
524 let w = unwrap_or_0(bytes.next());
525 ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
532 /// Reads the last code point out of a byte iterator (assuming a
533 /// UTF-8-like encoding).
535 fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
536 where I: DoubleEndedIterator<Item = &'a u8>,
539 let w = match bytes.next_back() {
541 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
542 Some(&back_byte) => back_byte,
545 // Multibyte case follows
546 // Decode from a byte combination out of: [x [y [z w]]]
548 let z = unwrap_or_0(bytes.next_back());
549 ch = utf8_first_byte(z, 2);
550 if utf8_is_cont_byte(z) {
551 let y = unwrap_or_0(bytes.next_back());
552 ch = utf8_first_byte(y, 3);
553 if utf8_is_cont_byte(y) {
554 let x = unwrap_or_0(bytes.next_back());
555 ch = utf8_first_byte(x, 4);
556 ch = utf8_acc_cont_byte(ch, y);
558 ch = utf8_acc_cont_byte(ch, z);
560 ch = utf8_acc_cont_byte(ch, w);
565 #[stable(feature = "rust1", since = "1.0.0")]
566 impl<'a> Iterator for Chars<'a> {
570 fn next(&mut self) -> Option<char> {
571 next_code_point(&mut self.iter).map(|ch| {
572 // str invariant says `ch` is a valid Unicode Scalar Value
574 char::from_u32_unchecked(ch)
580 fn count(self) -> usize {
581 // length in `char` is equal to the number of non-continuation bytes
582 let bytes_len = self.iter.len();
583 let mut cont_bytes = 0;
584 for &byte in self.iter {
585 cont_bytes += utf8_is_cont_byte(byte) as usize;
587 bytes_len - cont_bytes
591 fn size_hint(&self) -> (usize, Option<usize>) {
592 let len = self.iter.len();
593 // `(len + 3)` can't overflow, because we know that the `slice::Iter`
594 // belongs to a slice in memory which has a maximum length of
595 // `isize::MAX` (that's well below `usize::MAX`).
596 ((len + 3) / 4, Some(len))
600 fn last(mut self) -> Option<char> {
601 // No need to go through the entire string.
606 #[stable(feature = "rust1", since = "1.0.0")]
607 impl<'a> DoubleEndedIterator for Chars<'a> {
609 fn next_back(&mut self) -> Option<char> {
610 next_code_point_reverse(&mut self.iter).map(|ch| {
611 // str invariant says `ch` is a valid Unicode Scalar Value
613 char::from_u32_unchecked(ch)
619 #[stable(feature = "fused", since = "1.26.0")]
620 impl FusedIterator for Chars<'_> {}
623 /// View the underlying data as a subslice of the original data.
625 /// This has the same lifetime as the original slice, and so the
626 /// iterator can continue to be used while this exists.
631 /// let mut chars = "abc".chars();
633 /// assert_eq!(chars.as_str(), "abc");
635 /// assert_eq!(chars.as_str(), "bc");
638 /// assert_eq!(chars.as_str(), "");
640 #[stable(feature = "iter_to_slice", since = "1.4.0")]
642 pub fn as_str(&self) -> &'a str {
643 unsafe { from_utf8_unchecked(self.iter.as_slice()) }
647 /// An iterator over the [`char`]s of a string slice, and their positions.
649 /// [`char`]: ../../std/primitive.char.html
651 /// This struct is created by the [`char_indices`] method on [`str`].
652 /// See its documentation for more.
654 /// [`char_indices`]: ../../std/primitive.str.html#method.char_indices
655 /// [`str`]: ../../std/primitive.str.html
656 #[derive(Clone, Debug)]
657 #[stable(feature = "rust1", since = "1.0.0")]
658 pub struct CharIndices<'a> {
663 #[stable(feature = "rust1", since = "1.0.0")]
664 impl<'a> Iterator for CharIndices<'a> {
665 type Item = (usize, char);
668 fn next(&mut self) -> Option<(usize, char)> {
669 let pre_len = self.iter.iter.len();
670 match self.iter.next() {
673 let index = self.front_offset;
674 let len = self.iter.iter.len();
675 self.front_offset += pre_len - len;
682 fn count(self) -> usize {
687 fn size_hint(&self) -> (usize, Option<usize>) {
688 self.iter.size_hint()
692 fn last(mut self) -> Option<(usize, char)> {
693 // No need to go through the entire string.
698 #[stable(feature = "rust1", since = "1.0.0")]
699 impl<'a> DoubleEndedIterator for CharIndices<'a> {
701 fn next_back(&mut self) -> Option<(usize, char)> {
702 self.iter.next_back().map(|ch| {
703 let index = self.front_offset + self.iter.iter.len();
709 #[stable(feature = "fused", since = "1.26.0")]
710 impl FusedIterator for CharIndices<'_> {}
712 impl<'a> CharIndices<'a> {
713 /// View the underlying data as a subslice of the original data.
715 /// This has the same lifetime as the original slice, and so the
716 /// iterator can continue to be used while this exists.
717 #[stable(feature = "iter_to_slice", since = "1.4.0")]
719 pub fn as_str(&self) -> &'a str {
724 /// An iterator over the bytes of a string slice.
726 /// This struct is created by the [`bytes`] method on [`str`].
727 /// See its documentation for more.
729 /// [`bytes`]: ../../std/primitive.str.html#method.bytes
730 /// [`str`]: ../../std/primitive.str.html
731 #[stable(feature = "rust1", since = "1.0.0")]
732 #[derive(Clone, Debug)]
733 pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>);
735 #[stable(feature = "rust1", since = "1.0.0")]
736 impl Iterator for Bytes<'_> {
740 fn next(&mut self) -> Option<u8> {
745 fn size_hint(&self) -> (usize, Option<usize>) {
750 fn count(self) -> usize {
755 fn last(self) -> Option<Self::Item> {
760 fn nth(&mut self, n: usize) -> Option<Self::Item> {
765 fn all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
770 fn any<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
775 fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where
776 P: FnMut(&Self::Item) -> bool
778 self.0.find(predicate)
782 fn position<P>(&mut self, predicate: P) -> Option<usize> where
783 P: FnMut(Self::Item) -> bool
785 self.0.position(predicate)
789 fn rposition<P>(&mut self, predicate: P) -> Option<usize> where
790 P: FnMut(Self::Item) -> bool
792 self.0.rposition(predicate)
796 #[stable(feature = "rust1", since = "1.0.0")]
797 impl DoubleEndedIterator for Bytes<'_> {
799 fn next_back(&mut self) -> Option<u8> {
804 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> where
805 P: FnMut(&Self::Item) -> bool
807 self.0.rfind(predicate)
811 #[stable(feature = "rust1", since = "1.0.0")]
812 impl ExactSizeIterator for Bytes<'_> {
814 fn len(&self) -> usize {
819 fn is_empty(&self) -> bool {
824 #[stable(feature = "fused", since = "1.26.0")]
825 impl FusedIterator for Bytes<'_> {}
827 #[unstable(feature = "trusted_len", issue = "37572")]
828 unsafe impl TrustedLen for Bytes<'_> {}
831 unsafe impl<'a> TrustedRandomAccess for Bytes<'a> {
832 unsafe fn get_unchecked(&mut self, i: usize) -> u8 {
833 self.0.get_unchecked(i)
835 fn may_have_side_effect() -> bool { false }
838 /// This macro generates a Clone impl for string pattern API
839 /// wrapper types of the form X<'a, P>
840 macro_rules! derive_pattern_clone {
841 (clone $t:ident with |$s:ident| $e:expr) => {
842 impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
843 where P::Searcher: Clone
845 fn clone(&self) -> Self {
853 /// This macro generates two public iterator structs
854 /// wrapping a private internal one that makes use of the `Pattern` API.
856 /// For all patterns `P: Pattern<'a>` the following items will be
857 /// generated (generics omitted):
859 /// struct $forward_iterator($internal_iterator);
860 /// struct $reverse_iterator($internal_iterator);
862 /// impl Iterator for $forward_iterator
863 /// { /* internal ends up calling Searcher::next_match() */ }
865 /// impl DoubleEndedIterator for $forward_iterator
866 /// where P::Searcher: DoubleEndedSearcher
867 /// { /* internal ends up calling Searcher::next_match_back() */ }
869 /// impl Iterator for $reverse_iterator
870 /// where P::Searcher: ReverseSearcher
871 /// { /* internal ends up calling Searcher::next_match_back() */ }
873 /// impl DoubleEndedIterator for $reverse_iterator
874 /// where P::Searcher: DoubleEndedSearcher
875 /// { /* internal ends up calling Searcher::next_match() */ }
877 /// The internal one is defined outside the macro, and has almost the same
878 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
879 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
881 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
882 /// `Pattern` might not return the same elements, so actually implementing
883 /// `DoubleEndedIterator` for it would be incorrect.
884 /// (See the docs in `str::pattern` for more details)
886 /// However, the internal struct still represents a single ended iterator from
887 /// either end, and depending on pattern is also a valid double ended iterator,
888 /// so the two wrapper structs implement `Iterator`
889 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
890 /// to the complex impls seen above.
891 macro_rules! generate_pattern_iterators {
895 $(#[$forward_iterator_attribute:meta])*
896 struct $forward_iterator:ident;
900 $(#[$reverse_iterator_attribute:meta])*
901 struct $reverse_iterator:ident;
903 // Stability of all generated items
905 $(#[$common_stability_attribute:meta])*
907 // Internal almost-iterator that is being delegated to
909 $internal_iterator:ident yielding ($iterty:ty);
911 // Kind of delegation - either single ended or double ended
914 $(#[$forward_iterator_attribute])*
915 $(#[$common_stability_attribute])*
916 pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
918 $(#[$common_stability_attribute])*
919 impl<'a, P: Pattern<'a>> fmt::Debug for $forward_iterator<'a, P>
920 where P::Searcher: fmt::Debug
922 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
923 f.debug_tuple(stringify!($forward_iterator))
929 $(#[$common_stability_attribute])*
930 impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
934 fn next(&mut self) -> Option<$iterty> {
939 $(#[$common_stability_attribute])*
940 impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
941 where P::Searcher: Clone
943 fn clone(&self) -> Self {
944 $forward_iterator(self.0.clone())
948 $(#[$reverse_iterator_attribute])*
949 $(#[$common_stability_attribute])*
950 pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
952 $(#[$common_stability_attribute])*
953 impl<'a, P: Pattern<'a>> fmt::Debug for $reverse_iterator<'a, P>
954 where P::Searcher: fmt::Debug
956 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
957 f.debug_tuple(stringify!($reverse_iterator))
963 $(#[$common_stability_attribute])*
964 impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
965 where P::Searcher: ReverseSearcher<'a>
970 fn next(&mut self) -> Option<$iterty> {
975 $(#[$common_stability_attribute])*
976 impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
977 where P::Searcher: Clone
979 fn clone(&self) -> Self {
980 $reverse_iterator(self.0.clone())
984 #[stable(feature = "fused", since = "1.26.0")]
985 impl<'a, P: Pattern<'a>> FusedIterator for $forward_iterator<'a, P> {}
987 #[stable(feature = "fused", since = "1.26.0")]
988 impl<'a, P: Pattern<'a>> FusedIterator for $reverse_iterator<'a, P>
989 where P::Searcher: ReverseSearcher<'a> {}
991 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
993 $reverse_iterator, $iterty);
996 double ended; with $(#[$common_stability_attribute:meta])*,
997 $forward_iterator:ident,
998 $reverse_iterator:ident, $iterty:ty
1000 $(#[$common_stability_attribute])*
1001 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
1002 where P::Searcher: DoubleEndedSearcher<'a>
1005 fn next_back(&mut self) -> Option<$iterty> {
1010 $(#[$common_stability_attribute])*
1011 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
1012 where P::Searcher: DoubleEndedSearcher<'a>
1015 fn next_back(&mut self) -> Option<$iterty> {
1021 single ended; with $(#[$common_stability_attribute:meta])*,
1022 $forward_iterator:ident,
1023 $reverse_iterator:ident, $iterty:ty
1027 derive_pattern_clone!{
1029 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
1032 struct SplitInternal<'a, P: Pattern<'a>> {
1035 matcher: P::Searcher,
1036 allow_trailing_empty: bool,
1040 impl<'a, P: Pattern<'a>> fmt::Debug for SplitInternal<'a, P> where P::Searcher: fmt::Debug {
1041 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1042 f.debug_struct("SplitInternal")
1043 .field("start", &self.start)
1044 .field("end", &self.end)
1045 .field("matcher", &self.matcher)
1046 .field("allow_trailing_empty", &self.allow_trailing_empty)
1047 .field("finished", &self.finished)
1052 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
1054 fn get_end(&mut self) -> Option<&'a str> {
1055 if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
1056 self.finished = true;
1058 let string = self.matcher.haystack().get_unchecked(self.start..self.end);
1067 fn next(&mut self) -> Option<&'a str> {
1068 if self.finished { return None }
1070 let haystack = self.matcher.haystack();
1071 match self.matcher.next_match() {
1072 Some((a, b)) => unsafe {
1073 let elt = haystack.get_unchecked(self.start..a);
1077 None => self.get_end(),
1082 fn next_back(&mut self) -> Option<&'a str>
1083 where P::Searcher: ReverseSearcher<'a>
1085 if self.finished { return None }
1087 if !self.allow_trailing_empty {
1088 self.allow_trailing_empty = true;
1089 match self.next_back() {
1090 Some(elt) if !elt.is_empty() => return Some(elt),
1091 _ => if self.finished { return None }
1095 let haystack = self.matcher.haystack();
1096 match self.matcher.next_match_back() {
1097 Some((a, b)) => unsafe {
1098 let elt = haystack.get_unchecked(b..self.end);
1103 self.finished = true;
1104 Some(haystack.get_unchecked(self.start..self.end))
1110 generate_pattern_iterators! {
1112 /// Created with the method [`split`].
1114 /// [`split`]: ../../std/primitive.str.html#method.split
1117 /// Created with the method [`rsplit`].
1119 /// [`rsplit`]: ../../std/primitive.str.html#method.rsplit
1122 #[stable(feature = "rust1", since = "1.0.0")]
1124 SplitInternal yielding (&'a str);
1125 delegate double ended;
1128 generate_pattern_iterators! {
1130 /// Created with the method [`split_terminator`].
1132 /// [`split_terminator`]: ../../std/primitive.str.html#method.split_terminator
1133 struct SplitTerminator;
1135 /// Created with the method [`rsplit_terminator`].
1137 /// [`rsplit_terminator`]: ../../std/primitive.str.html#method.rsplit_terminator
1138 struct RSplitTerminator;
1140 #[stable(feature = "rust1", since = "1.0.0")]
1142 SplitInternal yielding (&'a str);
1143 delegate double ended;
1146 derive_pattern_clone!{
1147 clone SplitNInternal
1148 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
1151 struct SplitNInternal<'a, P: Pattern<'a>> {
1152 iter: SplitInternal<'a, P>,
1153 /// The number of splits remaining
1157 impl<'a, P: Pattern<'a>> fmt::Debug for SplitNInternal<'a, P> where P::Searcher: fmt::Debug {
1158 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1159 f.debug_struct("SplitNInternal")
1160 .field("iter", &self.iter)
1161 .field("count", &self.count)
1166 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
1168 fn next(&mut self) -> Option<&'a str> {
1171 1 => { self.count = 0; self.iter.get_end() }
1172 _ => { self.count -= 1; self.iter.next() }
1177 fn next_back(&mut self) -> Option<&'a str>
1178 where P::Searcher: ReverseSearcher<'a>
1182 1 => { self.count = 0; self.iter.get_end() }
1183 _ => { self.count -= 1; self.iter.next_back() }
1188 generate_pattern_iterators! {
1190 /// Created with the method [`splitn`].
1192 /// [`splitn`]: ../../std/primitive.str.html#method.splitn
1195 /// Created with the method [`rsplitn`].
1197 /// [`rsplitn`]: ../../std/primitive.str.html#method.rsplitn
1200 #[stable(feature = "rust1", since = "1.0.0")]
1202 SplitNInternal yielding (&'a str);
1203 delegate single ended;
1206 derive_pattern_clone!{
1207 clone MatchIndicesInternal
1208 with |s| MatchIndicesInternal(s.0.clone())
1211 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
1213 impl<'a, P: Pattern<'a>> fmt::Debug for MatchIndicesInternal<'a, P> where P::Searcher: fmt::Debug {
1214 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1215 f.debug_tuple("MatchIndicesInternal")
1221 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
1223 fn next(&mut self) -> Option<(usize, &'a str)> {
1224 self.0.next_match().map(|(start, end)| unsafe {
1225 (start, self.0.haystack().get_unchecked(start..end))
1230 fn next_back(&mut self) -> Option<(usize, &'a str)>
1231 where P::Searcher: ReverseSearcher<'a>
1233 self.0.next_match_back().map(|(start, end)| unsafe {
1234 (start, self.0.haystack().get_unchecked(start..end))
1239 generate_pattern_iterators! {
1241 /// Created with the method [`match_indices`].
1243 /// [`match_indices`]: ../../std/primitive.str.html#method.match_indices
1244 struct MatchIndices;
1246 /// Created with the method [`rmatch_indices`].
1248 /// [`rmatch_indices`]: ../../std/primitive.str.html#method.rmatch_indices
1249 struct RMatchIndices;
1251 #[stable(feature = "str_match_indices", since = "1.5.0")]
1253 MatchIndicesInternal yielding ((usize, &'a str));
1254 delegate double ended;
1257 derive_pattern_clone!{
1258 clone MatchesInternal
1259 with |s| MatchesInternal(s.0.clone())
1262 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
1264 impl<'a, P: Pattern<'a>> fmt::Debug for MatchesInternal<'a, P> where P::Searcher: fmt::Debug {
1265 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1266 f.debug_tuple("MatchesInternal")
1272 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
1274 fn next(&mut self) -> Option<&'a str> {
1275 self.0.next_match().map(|(a, b)| unsafe {
1276 // Indices are known to be on utf8 boundaries
1277 self.0.haystack().get_unchecked(a..b)
1282 fn next_back(&mut self) -> Option<&'a str>
1283 where P::Searcher: ReverseSearcher<'a>
1285 self.0.next_match_back().map(|(a, b)| unsafe {
1286 // Indices are known to be on utf8 boundaries
1287 self.0.haystack().get_unchecked(a..b)
1292 generate_pattern_iterators! {
1294 /// Created with the method [`matches`].
1296 /// [`matches`]: ../../std/primitive.str.html#method.matches
1299 /// Created with the method [`rmatches`].
1301 /// [`rmatches`]: ../../std/primitive.str.html#method.rmatches
1304 #[stable(feature = "str_matches", since = "1.2.0")]
1306 MatchesInternal yielding (&'a str);
1307 delegate double ended;
1310 /// An iterator over the lines of a string, as string slices.
1312 /// This struct is created with the [`lines`] method on [`str`].
1313 /// See its documentation for more.
1315 /// [`lines`]: ../../std/primitive.str.html#method.lines
1316 /// [`str`]: ../../std/primitive.str.html
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 #[derive(Clone, Debug)]
1319 pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>);
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 impl<'a> Iterator for Lines<'a> {
1323 type Item = &'a str;
1326 fn next(&mut self) -> Option<&'a str> {
1331 fn size_hint(&self) -> (usize, Option<usize>) {
1336 #[stable(feature = "rust1", since = "1.0.0")]
1337 impl<'a> DoubleEndedIterator for Lines<'a> {
1339 fn next_back(&mut self) -> Option<&'a str> {
1344 #[stable(feature = "fused", since = "1.26.0")]
1345 impl FusedIterator for Lines<'_> {}
1347 /// Created with the method [`lines_any`].
1349 /// [`lines_any`]: ../../std/primitive.str.html#method.lines_any
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 #[rustc_deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")]
1352 #[derive(Clone, Debug)]
1353 #[allow(deprecated)]
1354 pub struct LinesAny<'a>(Lines<'a>);
1356 /// A nameable, cloneable fn type
1360 impl<'a> Fn<(&'a str,)> for LinesAnyMap {
1362 extern "rust-call" fn call(&self, (line,): (&'a str,)) -> &'a str {
1364 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
1369 impl<'a> FnMut<(&'a str,)> for LinesAnyMap {
1371 extern "rust-call" fn call_mut(&mut self, (line,): (&'a str,)) -> &'a str {
1372 Fn::call(&*self, (line,))
1376 impl<'a> FnOnce<(&'a str,)> for LinesAnyMap {
1377 type Output = &'a str;
1380 extern "rust-call" fn call_once(self, (line,): (&'a str,)) -> &'a str {
1381 Fn::call(&self, (line,))
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 #[allow(deprecated)]
1387 impl<'a> Iterator for LinesAny<'a> {
1388 type Item = &'a str;
1391 fn next(&mut self) -> Option<&'a str> {
1396 fn size_hint(&self) -> (usize, Option<usize>) {
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 #[allow(deprecated)]
1403 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1405 fn next_back(&mut self) -> Option<&'a str> {
1410 #[stable(feature = "fused", since = "1.26.0")]
1411 #[allow(deprecated)]
1412 impl FusedIterator for LinesAny<'_> {}
1415 Section: UTF-8 validation
1418 // use truncation to fit u64 into usize
1419 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
1421 /// Returns `true` if any byte in the word `x` is nonascii (>= 128).
1423 fn contains_nonascii(x: usize) -> bool {
1424 (x & NONASCII_MASK) != 0
1427 /// Walks through `v` checking that it's a valid UTF-8 sequence,
1428 /// returning `Ok(())` in that case, or, if it is invalid, `Err(err)`.
1430 fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
1434 let usize_bytes = mem::size_of::<usize>();
1435 let ascii_block_size = 2 * usize_bytes;
1436 let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
1439 let old_offset = index;
1441 ($error_len: expr) => {
1442 return Err(Utf8Error {
1443 valid_up_to: old_offset,
1444 error_len: $error_len,
1449 macro_rules! next { () => {{
1451 // we needed data, but there was none: error!
1458 let first = v[index];
1460 let w = UTF8_CHAR_WIDTH[first as usize];
1461 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
1462 // first C2 80 last DF BF
1463 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
1464 // first E0 A0 80 last EF BF BF
1465 // excluding surrogates codepoints \u{d800} to \u{dfff}
1466 // ED A0 80 to ED BF BF
1467 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1468 // first F0 90 80 80 last F4 8F BF BF
1470 // Use the UTF-8 syntax from the RFC
1472 // https://tools.ietf.org/html/rfc3629
1474 // UTF8-2 = %xC2-DF UTF8-tail
1475 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1476 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1477 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1478 // %xF4 %x80-8F 2( UTF8-tail )
1480 2 => if next!() & !CONT_MASK != TAG_CONT_U8 {
1484 match (first, next!()) {
1485 (0xE0 , 0xA0 ..= 0xBF) |
1486 (0xE1 ..= 0xEC, 0x80 ..= 0xBF) |
1487 (0xED , 0x80 ..= 0x9F) |
1488 (0xEE ..= 0xEF, 0x80 ..= 0xBF) => {}
1491 if next!() & !CONT_MASK != TAG_CONT_U8 {
1496 match (first, next!()) {
1497 (0xF0 , 0x90 ..= 0xBF) |
1498 (0xF1 ..= 0xF3, 0x80 ..= 0xBF) |
1499 (0xF4 , 0x80 ..= 0x8F) => {}
1502 if next!() & !CONT_MASK != TAG_CONT_U8 {
1505 if next!() & !CONT_MASK != TAG_CONT_U8 {
1513 // Ascii case, try to skip forward quickly.
1514 // When the pointer is aligned, read 2 words of data per iteration
1515 // until we find a word containing a non-ascii byte.
1516 let ptr = v.as_ptr();
1517 let align = unsafe {
1518 // the offset is safe, because `index` is guaranteed inbounds
1519 ptr.add(index).align_offset(usize_bytes)
1522 while index < blocks_end {
1524 let block = ptr.add(index) as *const usize;
1525 // break if there is a nonascii byte
1526 let zu = contains_nonascii(*block);
1527 let zv = contains_nonascii(*block.offset(1));
1532 index += ascii_block_size;
1534 // step from the point where the wordwise loop stopped
1535 while index < len && v[index] < 128 {
1547 // https://tools.ietf.org/html/rfc3629
1548 static UTF8_CHAR_WIDTH: [u8; 256] = [
1549 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1550 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1551 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1552 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1553 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1554 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1555 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1556 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1557 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1558 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1559 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1560 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1561 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1562 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1563 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1564 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1567 /// Given a first byte, determines how many bytes are in this UTF-8 character.
1568 #[unstable(feature = "str_internals", issue = "0")]
1570 pub fn utf8_char_width(b: u8) -> usize {
1571 UTF8_CHAR_WIDTH[b as usize] as usize
1574 /// Mask of the value bits of a continuation byte.
1575 const CONT_MASK: u8 = 0b0011_1111;
1576 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte.
1577 const TAG_CONT_U8: u8 = 0b1000_0000;
1580 Section: Trait implementations
1586 use slice::{self, SliceIndex};
1588 /// Implements ordering of strings.
1590 /// Strings are ordered lexicographically by their byte values. This orders Unicode code
1591 /// points based on their positions in the code charts. This is not necessarily the same as
1592 /// "alphabetical" order, which varies by language and locale. Sorting strings according to
1593 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1595 #[stable(feature = "rust1", since = "1.0.0")]
1598 fn cmp(&self, other: &str) -> Ordering {
1599 self.as_bytes().cmp(other.as_bytes())
1603 #[stable(feature = "rust1", since = "1.0.0")]
1604 impl PartialEq for str {
1606 fn eq(&self, other: &str) -> bool {
1607 self.as_bytes() == other.as_bytes()
1610 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1613 #[stable(feature = "rust1", since = "1.0.0")]
1616 /// Implements comparison operations on strings.
1618 /// Strings are compared lexicographically by their byte values. This compares Unicode code
1619 /// points based on their positions in the code charts. This is not necessarily the same as
1620 /// "alphabetical" order, which varies by language and locale. Comparing strings according to
1621 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1623 #[stable(feature = "rust1", since = "1.0.0")]
1624 impl PartialOrd for str {
1626 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1627 Some(self.cmp(other))
1631 /// Implements substring slicing with syntax `&self[begin .. end]`.
1633 /// Returns a slice of the given string from the byte range
1634 /// [`begin`..`end`).
1636 /// This operation is `O(1)`.
1640 /// Panics if `begin` or `end` does not point to the starting
1641 /// byte offset of a character (as defined by `is_char_boundary`).
1642 /// Requires that `begin <= end` and `end <= len` where `len` is the
1643 /// length of the string.
1648 /// let s = "Löwe 老虎 Léopard";
1649 /// assert_eq!(&s[0 .. 1], "L");
1651 /// assert_eq!(&s[1 .. 9], "öwe 老");
1653 /// // these will panic:
1654 /// // byte 2 lies within `ö`:
1657 /// // byte 8 lies within `老`
1660 /// // byte 100 is outside the string
1661 /// // &s[3 .. 100];
1663 #[stable(feature = "rust1", since = "1.0.0")]
1664 impl ops::Index<ops::Range<usize>> for str {
1667 fn index(&self, index: ops::Range<usize>) -> &str {
1672 /// Implements mutable substring slicing with syntax
1673 /// `&mut self[begin .. end]`.
1675 /// Returns a mutable slice of the given string from the byte range
1676 /// [`begin`..`end`).
1678 /// This operation is `O(1)`.
1682 /// Panics if `begin` or `end` does not point to the starting
1683 /// byte offset of a character (as defined by `is_char_boundary`).
1684 /// Requires that `begin <= end` and `end <= len` where `len` is the
1685 /// length of the string.
1686 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1687 impl ops::IndexMut<ops::Range<usize>> for str {
1689 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1690 index.index_mut(self)
1694 /// Implements substring slicing with syntax `&self[.. end]`.
1696 /// Returns a slice of the string from the beginning to byte offset
1699 /// Equivalent to `&self[0 .. end]`.
1700 #[stable(feature = "rust1", since = "1.0.0")]
1701 impl ops::Index<ops::RangeTo<usize>> for str {
1705 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1710 /// Implements mutable substring slicing with syntax `&mut self[.. end]`.
1712 /// Returns a mutable slice of the string from the beginning to byte offset
1715 /// Equivalent to `&mut self[0 .. end]`.
1716 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1717 impl ops::IndexMut<ops::RangeTo<usize>> for str {
1719 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1720 index.index_mut(self)
1724 /// Implements substring slicing with syntax `&self[begin ..]`.
1726 /// Returns a slice of the string from byte offset `begin`
1727 /// to the end of the string.
1729 /// Equivalent to `&self[begin .. len]`.
1730 #[stable(feature = "rust1", since = "1.0.0")]
1731 impl ops::Index<ops::RangeFrom<usize>> for str {
1735 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1740 /// Implements mutable substring slicing with syntax `&mut self[begin ..]`.
1742 /// Returns a mutable slice of the string from byte offset `begin`
1743 /// to the end of the string.
1745 /// Equivalent to `&mut self[begin .. len]`.
1746 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1747 impl ops::IndexMut<ops::RangeFrom<usize>> for str {
1749 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1750 index.index_mut(self)
1754 /// Implements substring slicing with syntax `&self[..]`.
1756 /// Returns a slice of the whole string. This operation can
1759 /// Equivalent to `&self[0 .. len]`.
1760 #[stable(feature = "rust1", since = "1.0.0")]
1761 impl ops::Index<ops::RangeFull> for str {
1765 fn index(&self, _index: ops::RangeFull) -> &str {
1770 /// Implements mutable substring slicing with syntax `&mut self[..]`.
1772 /// Returns a mutable slice of the whole string. This operation can
1775 /// Equivalent to `&mut self[0 .. len]`.
1776 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1777 impl ops::IndexMut<ops::RangeFull> for str {
1779 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1784 #[stable(feature = "inclusive_range", since = "1.26.0")]
1785 impl ops::Index<ops::RangeInclusive<usize>> for str {
1789 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1794 #[stable(feature = "inclusive_range", since = "1.26.0")]
1795 impl ops::Index<ops::RangeToInclusive<usize>> for str {
1799 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1804 #[stable(feature = "inclusive_range", since = "1.26.0")]
1805 impl ops::IndexMut<ops::RangeInclusive<usize>> for str {
1807 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1808 index.index_mut(self)
1811 #[stable(feature = "inclusive_range", since = "1.26.0")]
1812 impl ops::IndexMut<ops::RangeToInclusive<usize>> for str {
1814 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1815 index.index_mut(self)
1821 fn str_index_overflow_fail() -> ! {
1822 panic!("attempted to index str up to maximum usize");
1825 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1826 impl SliceIndex<str> for ops::RangeFull {
1829 fn get(self, slice: &str) -> Option<&Self::Output> {
1833 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1837 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1841 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1845 fn index(self, slice: &str) -> &Self::Output {
1849 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1854 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1855 impl SliceIndex<str> for ops::Range<usize> {
1858 fn get(self, slice: &str) -> Option<&Self::Output> {
1859 if self.start <= self.end &&
1860 slice.is_char_boundary(self.start) &&
1861 slice.is_char_boundary(self.end) {
1862 Some(unsafe { self.get_unchecked(slice) })
1868 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1869 if self.start <= self.end &&
1870 slice.is_char_boundary(self.start) &&
1871 slice.is_char_boundary(self.end) {
1872 Some(unsafe { self.get_unchecked_mut(slice) })
1878 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1879 let ptr = slice.as_ptr().add(self.start);
1880 let len = self.end - self.start;
1881 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1884 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1885 let ptr = slice.as_ptr().add(self.start);
1886 let len = self.end - self.start;
1887 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1890 fn index(self, slice: &str) -> &Self::Output {
1891 let (start, end) = (self.start, self.end);
1892 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1895 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1896 // is_char_boundary checks that the index is in [0, .len()]
1897 // cannot reuse `get` as above, because of NLL trouble
1898 if self.start <= self.end &&
1899 slice.is_char_boundary(self.start) &&
1900 slice.is_char_boundary(self.end) {
1901 unsafe { self.get_unchecked_mut(slice) }
1903 super::slice_error_fail(slice, self.start, self.end)
1908 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1909 impl SliceIndex<str> for ops::RangeTo<usize> {
1912 fn get(self, slice: &str) -> Option<&Self::Output> {
1913 if slice.is_char_boundary(self.end) {
1914 Some(unsafe { self.get_unchecked(slice) })
1920 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1921 if slice.is_char_boundary(self.end) {
1922 Some(unsafe { self.get_unchecked_mut(slice) })
1928 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1929 let ptr = slice.as_ptr();
1930 super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end))
1933 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1934 let ptr = slice.as_ptr();
1935 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, self.end))
1938 fn index(self, slice: &str) -> &Self::Output {
1940 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end))
1943 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1944 // is_char_boundary checks that the index is in [0, .len()]
1945 if slice.is_char_boundary(self.end) {
1946 unsafe { self.get_unchecked_mut(slice) }
1948 super::slice_error_fail(slice, 0, self.end)
1953 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1954 impl SliceIndex<str> for ops::RangeFrom<usize> {
1957 fn get(self, slice: &str) -> Option<&Self::Output> {
1958 if slice.is_char_boundary(self.start) {
1959 Some(unsafe { self.get_unchecked(slice) })
1965 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1966 if slice.is_char_boundary(self.start) {
1967 Some(unsafe { self.get_unchecked_mut(slice) })
1973 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1974 let ptr = slice.as_ptr().add(self.start);
1975 let len = slice.len() - self.start;
1976 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1979 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1980 let ptr = slice.as_ptr().add(self.start);
1981 let len = slice.len() - self.start;
1982 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1985 fn index(self, slice: &str) -> &Self::Output {
1986 let (start, end) = (self.start, slice.len());
1987 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1990 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1991 // is_char_boundary checks that the index is in [0, .len()]
1992 if slice.is_char_boundary(self.start) {
1993 unsafe { self.get_unchecked_mut(slice) }
1995 super::slice_error_fail(slice, self.start, slice.len())
2000 #[stable(feature = "inclusive_range", since = "1.26.0")]
2001 impl SliceIndex<str> for ops::RangeInclusive<usize> {
2004 fn get(self, slice: &str) -> Option<&Self::Output> {
2005 if *self.end() == usize::max_value() { None }
2006 else { (*self.start()..self.end()+1).get(slice) }
2009 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
2010 if *self.end() == usize::max_value() { None }
2011 else { (*self.start()..self.end()+1).get_mut(slice) }
2014 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
2015 (*self.start()..self.end()+1).get_unchecked(slice)
2018 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
2019 (*self.start()..self.end()+1).get_unchecked_mut(slice)
2022 fn index(self, slice: &str) -> &Self::Output {
2023 if *self.end() == usize::max_value() { str_index_overflow_fail(); }
2024 (*self.start()..self.end()+1).index(slice)
2027 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
2028 if *self.end() == usize::max_value() { str_index_overflow_fail(); }
2029 (*self.start()..self.end()+1).index_mut(slice)
2035 #[stable(feature = "inclusive_range", since = "1.26.0")]
2036 impl SliceIndex<str> for ops::RangeToInclusive<usize> {
2039 fn get(self, slice: &str) -> Option<&Self::Output> {
2040 if self.end == usize::max_value() { None }
2041 else { (..self.end+1).get(slice) }
2044 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
2045 if self.end == usize::max_value() { None }
2046 else { (..self.end+1).get_mut(slice) }
2049 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
2050 (..self.end+1).get_unchecked(slice)
2053 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
2054 (..self.end+1).get_unchecked_mut(slice)
2057 fn index(self, slice: &str) -> &Self::Output {
2058 if self.end == usize::max_value() { str_index_overflow_fail(); }
2059 (..self.end+1).index(slice)
2062 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
2063 if self.end == usize::max_value() { str_index_overflow_fail(); }
2064 (..self.end+1).index_mut(slice)
2069 // truncate `&str` to length at most equal to `max`
2070 // return `true` if it were truncated, and the new str.
2071 fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
2075 while !s.is_char_boundary(max) {
2084 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
2085 const MAX_DISPLAY_LENGTH: usize = 256;
2086 let (truncated, s_trunc) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
2087 let ellipsis = if truncated { "[...]" } else { "" };
2090 if begin > s.len() || end > s.len() {
2091 let oob_index = if begin > s.len() { begin } else { end };
2092 panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
2096 assert!(begin <= end, "begin <= end ({} <= {}) when slicing `{}`{}",
2097 begin, end, s_trunc, ellipsis);
2099 // 3. character boundary
2100 let index = if !s.is_char_boundary(begin) { begin } else { end };
2101 // find the character
2102 let mut char_start = index;
2103 while !s.is_char_boundary(char_start) {
2106 // `char_start` must be less than len and a char boundary
2107 let ch = s[char_start..].chars().next().unwrap();
2108 let char_range = char_start .. char_start + ch.len_utf8();
2109 panic!("byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
2110 index, ch, char_range, s_trunc, ellipsis);
2116 /// Returns the length of `self`.
2118 /// This length is in bytes, not [`char`]s or graphemes. In other words,
2119 /// it may not be what a human considers the length of the string.
2126 /// let len = "foo".len();
2127 /// assert_eq!(3, len);
2129 /// let len = "ƒoo".len(); // fancy f!
2130 /// assert_eq!(4, len);
2132 #[stable(feature = "rust1", since = "1.0.0")]
2134 #[rustc_const_unstable(feature = "const_str_len")]
2135 pub const fn len(&self) -> usize {
2136 self.as_bytes().len()
2139 /// Returns `true` if `self` has a length of zero bytes.
2147 /// assert!(s.is_empty());
2149 /// let s = "not empty";
2150 /// assert!(!s.is_empty());
2153 #[stable(feature = "rust1", since = "1.0.0")]
2154 #[rustc_const_unstable(feature = "const_str_len")]
2155 pub const fn is_empty(&self) -> bool {
2159 /// Checks that `index`-th byte lies at the start and/or end of a
2160 /// UTF-8 code point sequence.
2162 /// The start and end of the string (when `index == self.len()`) are
2163 /// considered to be
2166 /// Returns `false` if `index` is greater than `self.len()`.
2171 /// let s = "Löwe 老虎 Léopard";
2172 /// assert!(s.is_char_boundary(0));
2174 /// assert!(s.is_char_boundary(6));
2175 /// assert!(s.is_char_boundary(s.len()));
2177 /// // second byte of `ö`
2178 /// assert!(!s.is_char_boundary(2));
2180 /// // third byte of `老`
2181 /// assert!(!s.is_char_boundary(8));
2183 #[stable(feature = "is_char_boundary", since = "1.9.0")]
2185 pub fn is_char_boundary(&self, index: usize) -> bool {
2186 // 0 and len are always ok.
2187 // Test for 0 explicitly so that it can optimize out the check
2188 // easily and skip reading string data for that case.
2189 if index == 0 || index == self.len() { return true; }
2190 match self.as_bytes().get(index) {
2192 // This is bit magic equivalent to: b < 128 || b >= 192
2193 Some(&b) => (b as i8) >= -0x40,
2197 /// Converts a string slice to a byte slice. To convert the byte slice back
2198 /// into a string slice, use the [`str::from_utf8`] function.
2200 /// [`str::from_utf8`]: ./str/fn.from_utf8.html
2207 /// let bytes = "bors".as_bytes();
2208 /// assert_eq!(b"bors", bytes);
2210 #[stable(feature = "rust1", since = "1.0.0")]
2212 #[rustc_const_unstable(feature="const_str_as_bytes")]
2213 pub const fn as_bytes(&self) -> &[u8] {
2218 unsafe { Slices { str: self }.slice }
2221 /// Converts a mutable string slice to a mutable byte slice. To convert the
2222 /// mutable byte slice back into a mutable string slice, use the
2223 /// [`str::from_utf8_mut`] function.
2225 /// [`str::from_utf8_mut`]: ./str/fn.from_utf8_mut.html
2232 /// let mut s = String::from("Hello");
2233 /// let bytes = unsafe { s.as_bytes_mut() };
2235 /// assert_eq!(b"Hello", bytes);
2241 /// let mut s = String::from("🗻∈🌏");
2244 /// let bytes = s.as_bytes_mut();
2246 /// bytes[0] = 0xF0;
2247 /// bytes[1] = 0x9F;
2248 /// bytes[2] = 0x8D;
2249 /// bytes[3] = 0x94;
2252 /// assert_eq!("🍔∈🌏", s);
2254 #[stable(feature = "str_mut_extras", since = "1.20.0")]
2256 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
2257 &mut *(self as *mut str as *mut [u8])
2260 /// Converts a string slice to a raw pointer.
2262 /// As string slices are a slice of bytes, the raw pointer points to a
2263 /// [`u8`]. This pointer will be pointing to the first byte of the string
2266 /// [`u8`]: primitive.u8.html
2273 /// let s = "Hello";
2274 /// let ptr = s.as_ptr();
2276 #[stable(feature = "rust1", since = "1.0.0")]
2278 pub const fn as_ptr(&self) -> *const u8 {
2279 self as *const str as *const u8
2282 /// Returns a subslice of `str`.
2284 /// This is the non-panicking alternative to indexing the `str`. Returns
2285 /// [`None`] whenever equivalent indexing operation would panic.
2287 /// [`None`]: option/enum.Option.html#variant.None
2292 /// let v = String::from("🗻∈🌏");
2294 /// assert_eq!(Some("🗻"), v.get(0..4));
2296 /// // indices not on UTF-8 sequence boundaries
2297 /// assert!(v.get(1..).is_none());
2298 /// assert!(v.get(..8).is_none());
2300 /// // out of bounds
2301 /// assert!(v.get(..42).is_none());
2303 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2305 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
2309 /// Returns a mutable subslice of `str`.
2311 /// This is the non-panicking alternative to indexing the `str`. Returns
2312 /// [`None`] whenever equivalent indexing operation would panic.
2314 /// [`None`]: option/enum.Option.html#variant.None
2319 /// let mut v = String::from("hello");
2320 /// // correct length
2321 /// assert!(v.get_mut(0..5).is_some());
2322 /// // out of bounds
2323 /// assert!(v.get_mut(..42).is_none());
2324 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
2326 /// assert_eq!("hello", v);
2328 /// let s = v.get_mut(0..2);
2329 /// let s = s.map(|s| {
2330 /// s.make_ascii_uppercase();
2333 /// assert_eq!(Some("HE"), s);
2335 /// assert_eq!("HEllo", v);
2337 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2339 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
2343 /// Returns a unchecked subslice of `str`.
2345 /// This is the unchecked alternative to indexing the `str`.
2349 /// Callers of this function are responsible that these preconditions are
2352 /// * The starting index must come before the ending index;
2353 /// * Indexes must be within bounds of the original slice;
2354 /// * Indexes must lie on UTF-8 sequence boundaries.
2356 /// Failing that, the returned string slice may reference invalid memory or
2357 /// violate the invariants communicated by the `str` type.
2364 /// assert_eq!("🗻", v.get_unchecked(0..4));
2365 /// assert_eq!("∈", v.get_unchecked(4..7));
2366 /// assert_eq!("🌏", v.get_unchecked(7..11));
2369 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2371 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
2372 i.get_unchecked(self)
2375 /// Returns a mutable, unchecked subslice of `str`.
2377 /// This is the unchecked alternative to indexing the `str`.
2381 /// Callers of this function are responsible that these preconditions are
2384 /// * The starting index must come before the ending index;
2385 /// * Indexes must be within bounds of the original slice;
2386 /// * Indexes must lie on UTF-8 sequence boundaries.
2388 /// Failing that, the returned string slice may reference invalid memory or
2389 /// violate the invariants communicated by the `str` type.
2394 /// let mut v = String::from("🗻∈🌏");
2396 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
2397 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
2398 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
2401 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2403 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
2404 i.get_unchecked_mut(self)
2407 /// Creates a string slice from another string slice, bypassing safety
2410 /// This is generally not recommended, use with caution! For a safe
2411 /// alternative see [`str`] and [`Index`].
2413 /// [`str`]: primitive.str.html
2414 /// [`Index`]: ops/trait.Index.html
2416 /// This new slice goes from `begin` to `end`, including `begin` but
2417 /// excluding `end`.
2419 /// To get a mutable string slice instead, see the
2420 /// [`slice_mut_unchecked`] method.
2422 /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
2426 /// Callers of this function are responsible that three preconditions are
2429 /// * `begin` must come before `end`.
2430 /// * `begin` and `end` must be byte positions within the string slice.
2431 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2438 /// let s = "Löwe 老虎 Léopard";
2441 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
2444 /// let s = "Hello, world!";
2447 /// assert_eq!("world", s.slice_unchecked(7, 12));
2450 #[stable(feature = "rust1", since = "1.0.0")]
2451 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked(begin..end)` instead")]
2453 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
2454 (begin..end).get_unchecked(self)
2457 /// Creates a string slice from another string slice, bypassing safety
2459 /// This is generally not recommended, use with caution! For a safe
2460 /// alternative see [`str`] and [`IndexMut`].
2462 /// [`str`]: primitive.str.html
2463 /// [`IndexMut`]: ops/trait.IndexMut.html
2465 /// This new slice goes from `begin` to `end`, including `begin` but
2466 /// excluding `end`.
2468 /// To get an immutable string slice instead, see the
2469 /// [`slice_unchecked`] method.
2471 /// [`slice_unchecked`]: #method.slice_unchecked
2475 /// Callers of this function are responsible that three preconditions are
2478 /// * `begin` must come before `end`.
2479 /// * `begin` and `end` must be byte positions within the string slice.
2480 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2481 #[stable(feature = "str_slice_mut", since = "1.5.0")]
2482 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked_mut(begin..end)` instead")]
2484 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
2485 (begin..end).get_unchecked_mut(self)
2488 /// Divide one string slice into two at an index.
2490 /// The argument, `mid`, should be a byte offset from the start of the
2491 /// string. It must also be on the boundary of a UTF-8 code point.
2493 /// The two slices returned go from the start of the string slice to `mid`,
2494 /// and from `mid` to the end of the string slice.
2496 /// To get mutable string slices instead, see the [`split_at_mut`]
2499 /// [`split_at_mut`]: #method.split_at_mut
2503 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2504 /// beyond the last code point of the string slice.
2511 /// let s = "Per Martin-Löf";
2513 /// let (first, last) = s.split_at(3);
2515 /// assert_eq!("Per", first);
2516 /// assert_eq!(" Martin-Löf", last);
2519 #[stable(feature = "str_split_at", since = "1.4.0")]
2520 pub fn split_at(&self, mid: usize) -> (&str, &str) {
2521 // is_char_boundary checks that the index is in [0, .len()]
2522 if self.is_char_boundary(mid) {
2524 (self.get_unchecked(0..mid),
2525 self.get_unchecked(mid..self.len()))
2528 slice_error_fail(self, 0, mid)
2532 /// Divide one mutable string slice into two at an index.
2534 /// The argument, `mid`, should be a byte offset from the start of the
2535 /// string. It must also be on the boundary of a UTF-8 code point.
2537 /// The two slices returned go from the start of the string slice to `mid`,
2538 /// and from `mid` to the end of the string slice.
2540 /// To get immutable string slices instead, see the [`split_at`] method.
2542 /// [`split_at`]: #method.split_at
2546 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2547 /// beyond the last code point of the string slice.
2554 /// let mut s = "Per Martin-Löf".to_string();
2556 /// let (first, last) = s.split_at_mut(3);
2557 /// first.make_ascii_uppercase();
2558 /// assert_eq!("PER", first);
2559 /// assert_eq!(" Martin-Löf", last);
2561 /// assert_eq!("PER Martin-Löf", s);
2564 #[stable(feature = "str_split_at", since = "1.4.0")]
2565 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
2566 // is_char_boundary checks that the index is in [0, .len()]
2567 if self.is_char_boundary(mid) {
2568 let len = self.len();
2569 let ptr = self.as_ptr() as *mut u8;
2571 (from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
2572 from_utf8_unchecked_mut(slice::from_raw_parts_mut(
2578 slice_error_fail(self, 0, mid)
2582 /// Returns an iterator over the [`char`]s of a string slice.
2584 /// As a string slice consists of valid UTF-8, we can iterate through a
2585 /// string slice by [`char`]. This method returns such an iterator.
2587 /// It's important to remember that [`char`] represents a Unicode Scalar
2588 /// Value, and may not match your idea of what a 'character' is. Iteration
2589 /// over grapheme clusters may be what you actually want.
2596 /// let word = "goodbye";
2598 /// let count = word.chars().count();
2599 /// assert_eq!(7, count);
2601 /// let mut chars = word.chars();
2603 /// assert_eq!(Some('g'), chars.next());
2604 /// assert_eq!(Some('o'), chars.next());
2605 /// assert_eq!(Some('o'), chars.next());
2606 /// assert_eq!(Some('d'), chars.next());
2607 /// assert_eq!(Some('b'), chars.next());
2608 /// assert_eq!(Some('y'), chars.next());
2609 /// assert_eq!(Some('e'), chars.next());
2611 /// assert_eq!(None, chars.next());
2614 /// Remember, [`char`]s may not match your human intuition about characters:
2619 /// let mut chars = y.chars();
2621 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
2622 /// assert_eq!(Some('\u{0306}'), chars.next());
2624 /// assert_eq!(None, chars.next());
2626 #[stable(feature = "rust1", since = "1.0.0")]
2628 pub fn chars(&self) -> Chars {
2629 Chars{iter: self.as_bytes().iter()}
2632 /// Returns an iterator over the [`char`]s of a string slice, and their
2635 /// As a string slice consists of valid UTF-8, we can iterate through a
2636 /// string slice by [`char`]. This method returns an iterator of both
2637 /// these [`char`]s, as well as their byte positions.
2639 /// The iterator yields tuples. The position is first, the [`char`] is
2647 /// let word = "goodbye";
2649 /// let count = word.char_indices().count();
2650 /// assert_eq!(7, count);
2652 /// let mut char_indices = word.char_indices();
2654 /// assert_eq!(Some((0, 'g')), char_indices.next());
2655 /// assert_eq!(Some((1, 'o')), char_indices.next());
2656 /// assert_eq!(Some((2, 'o')), char_indices.next());
2657 /// assert_eq!(Some((3, 'd')), char_indices.next());
2658 /// assert_eq!(Some((4, 'b')), char_indices.next());
2659 /// assert_eq!(Some((5, 'y')), char_indices.next());
2660 /// assert_eq!(Some((6, 'e')), char_indices.next());
2662 /// assert_eq!(None, char_indices.next());
2665 /// Remember, [`char`]s may not match your human intuition about characters:
2668 /// let yes = "y̆es";
2670 /// let mut char_indices = yes.char_indices();
2672 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
2673 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
2675 /// // note the 3 here - the last character took up two bytes
2676 /// assert_eq!(Some((3, 'e')), char_indices.next());
2677 /// assert_eq!(Some((4, 's')), char_indices.next());
2679 /// assert_eq!(None, char_indices.next());
2681 #[stable(feature = "rust1", since = "1.0.0")]
2683 pub fn char_indices(&self) -> CharIndices {
2684 CharIndices { front_offset: 0, iter: self.chars() }
2687 /// An iterator over the bytes of a string slice.
2689 /// As a string slice consists of a sequence of bytes, we can iterate
2690 /// through a string slice by byte. This method returns such an iterator.
2697 /// let mut bytes = "bors".bytes();
2699 /// assert_eq!(Some(b'b'), bytes.next());
2700 /// assert_eq!(Some(b'o'), bytes.next());
2701 /// assert_eq!(Some(b'r'), bytes.next());
2702 /// assert_eq!(Some(b's'), bytes.next());
2704 /// assert_eq!(None, bytes.next());
2706 #[stable(feature = "rust1", since = "1.0.0")]
2708 pub fn bytes(&self) -> Bytes {
2709 Bytes(self.as_bytes().iter().cloned())
2712 /// Split a string slice by whitespace.
2714 /// The iterator returned will return string slices that are sub-slices of
2715 /// the original string slice, separated by any amount of whitespace.
2717 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2718 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
2719 /// instead, use [`split_ascii_whitespace`].
2721 /// [`split_ascii_whitespace`]: #method.split_ascii_whitespace
2728 /// let mut iter = "A few words".split_whitespace();
2730 /// assert_eq!(Some("A"), iter.next());
2731 /// assert_eq!(Some("few"), iter.next());
2732 /// assert_eq!(Some("words"), iter.next());
2734 /// assert_eq!(None, iter.next());
2737 /// All kinds of whitespace are considered:
2740 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
2741 /// assert_eq!(Some("Mary"), iter.next());
2742 /// assert_eq!(Some("had"), iter.next());
2743 /// assert_eq!(Some("a"), iter.next());
2744 /// assert_eq!(Some("little"), iter.next());
2745 /// assert_eq!(Some("lamb"), iter.next());
2747 /// assert_eq!(None, iter.next());
2749 #[stable(feature = "split_whitespace", since = "1.1.0")]
2751 pub fn split_whitespace(&self) -> SplitWhitespace {
2752 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
2755 /// Split a string slice by ASCII whitespace.
2757 /// The iterator returned will return string slices that are sub-slices of
2758 /// the original string slice, separated by any amount of ASCII whitespace.
2760 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
2762 /// [`split_whitespace`]: #method.split_whitespace
2769 /// #![feature(split_ascii_whitespace)]
2770 /// let mut iter = "A few words".split_ascii_whitespace();
2772 /// assert_eq!(Some("A"), iter.next());
2773 /// assert_eq!(Some("few"), iter.next());
2774 /// assert_eq!(Some("words"), iter.next());
2776 /// assert_eq!(None, iter.next());
2779 /// All kinds of ASCII whitespace are considered:
2782 /// let mut iter = " Mary had\ta little \n\t lamb".split_whitespace();
2783 /// assert_eq!(Some("Mary"), iter.next());
2784 /// assert_eq!(Some("had"), iter.next());
2785 /// assert_eq!(Some("a"), iter.next());
2786 /// assert_eq!(Some("little"), iter.next());
2787 /// assert_eq!(Some("lamb"), iter.next());
2789 /// assert_eq!(None, iter.next());
2791 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
2793 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace {
2796 .split(IsAsciiWhitespace)
2798 .map(UnsafeBytesToStr);
2799 SplitAsciiWhitespace { inner }
2802 /// An iterator over the lines of a string, as string slices.
2804 /// Lines are ended with either a newline (`\n`) or a carriage return with
2805 /// a line feed (`\r\n`).
2807 /// The final line ending is optional.
2814 /// let text = "foo\r\nbar\n\nbaz\n";
2815 /// let mut lines = text.lines();
2817 /// assert_eq!(Some("foo"), lines.next());
2818 /// assert_eq!(Some("bar"), lines.next());
2819 /// assert_eq!(Some(""), lines.next());
2820 /// assert_eq!(Some("baz"), lines.next());
2822 /// assert_eq!(None, lines.next());
2825 /// The final line ending isn't required:
2828 /// let text = "foo\nbar\n\r\nbaz";
2829 /// let mut lines = text.lines();
2831 /// assert_eq!(Some("foo"), lines.next());
2832 /// assert_eq!(Some("bar"), lines.next());
2833 /// assert_eq!(Some(""), lines.next());
2834 /// assert_eq!(Some("baz"), lines.next());
2836 /// assert_eq!(None, lines.next());
2838 #[stable(feature = "rust1", since = "1.0.0")]
2840 pub fn lines(&self) -> Lines {
2841 Lines(self.split_terminator('\n').map(LinesAnyMap))
2844 /// An iterator over the lines of a string.
2845 #[stable(feature = "rust1", since = "1.0.0")]
2846 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
2848 #[allow(deprecated)]
2849 pub fn lines_any(&self) -> LinesAny {
2850 LinesAny(self.lines())
2853 /// Returns an iterator of `u16` over the string encoded as UTF-16.
2860 /// let text = "Zażółć gęślą jaźń";
2862 /// let utf8_len = text.len();
2863 /// let utf16_len = text.encode_utf16().count();
2865 /// assert!(utf16_len <= utf8_len);
2867 #[stable(feature = "encode_utf16", since = "1.8.0")]
2868 pub fn encode_utf16(&self) -> EncodeUtf16 {
2869 EncodeUtf16 { chars: self.chars(), extra: 0 }
2872 /// Returns `true` if the given pattern matches a sub-slice of
2873 /// this string slice.
2875 /// Returns `false` if it does not.
2882 /// let bananas = "bananas";
2884 /// assert!(bananas.contains("nana"));
2885 /// assert!(!bananas.contains("apples"));
2887 #[stable(feature = "rust1", since = "1.0.0")]
2889 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2890 pat.is_contained_in(self)
2893 /// Returns `true` if the given pattern matches a prefix of this
2896 /// Returns `false` if it does not.
2903 /// let bananas = "bananas";
2905 /// assert!(bananas.starts_with("bana"));
2906 /// assert!(!bananas.starts_with("nana"));
2908 #[stable(feature = "rust1", since = "1.0.0")]
2909 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2910 pat.is_prefix_of(self)
2913 /// Returns `true` if the given pattern matches a suffix of this
2916 /// Returns `false` if it does not.
2923 /// let bananas = "bananas";
2925 /// assert!(bananas.ends_with("anas"));
2926 /// assert!(!bananas.ends_with("nana"));
2928 #[stable(feature = "rust1", since = "1.0.0")]
2929 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
2930 where P::Searcher: ReverseSearcher<'a>
2932 pat.is_suffix_of(self)
2935 /// Returns the byte index of the first character of this string slice that
2936 /// matches the pattern.
2938 /// Returns [`None`] if the pattern doesn't match.
2940 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2941 /// a character matches.
2943 /// [`None`]: option/enum.Option.html#variant.None
2947 /// Simple patterns:
2950 /// let s = "Löwe 老虎 Léopard";
2952 /// assert_eq!(s.find('L'), Some(0));
2953 /// assert_eq!(s.find('é'), Some(14));
2954 /// assert_eq!(s.find("Léopard"), Some(13));
2957 /// More complex patterns using point-free style and closures:
2960 /// let s = "Löwe 老虎 Léopard";
2962 /// assert_eq!(s.find(char::is_whitespace), Some(5));
2963 /// assert_eq!(s.find(char::is_lowercase), Some(1));
2964 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
2965 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
2968 /// Not finding the pattern:
2971 /// let s = "Löwe 老虎 Léopard";
2972 /// let x: &[_] = &['1', '2'];
2974 /// assert_eq!(s.find(x), None);
2976 #[stable(feature = "rust1", since = "1.0.0")]
2978 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2979 pat.into_searcher(self).next_match().map(|(i, _)| i)
2982 /// Returns the byte index of the last character of this string slice that
2983 /// matches the pattern.
2985 /// Returns [`None`] if the pattern doesn't match.
2987 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2988 /// a character matches.
2990 /// [`None`]: option/enum.Option.html#variant.None
2994 /// Simple patterns:
2997 /// let s = "Löwe 老虎 Léopard";
2999 /// assert_eq!(s.rfind('L'), Some(13));
3000 /// assert_eq!(s.rfind('é'), Some(14));
3003 /// More complex patterns with closures:
3006 /// let s = "Löwe 老虎 Léopard";
3008 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
3009 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
3012 /// Not finding the pattern:
3015 /// let s = "Löwe 老虎 Léopard";
3016 /// let x: &[_] = &['1', '2'];
3018 /// assert_eq!(s.rfind(x), None);
3020 #[stable(feature = "rust1", since = "1.0.0")]
3022 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
3023 where P::Searcher: ReverseSearcher<'a>
3025 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
3028 /// An iterator over substrings of this string slice, separated by
3029 /// characters matched by a pattern.
3031 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3034 /// # Iterator behavior
3036 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3037 /// allows a reverse search and forward/reverse search yields the same
3038 /// elements. This is true for, eg, [`char`] but not for `&str`.
3040 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3042 /// If the pattern allows a reverse search but its results might differ
3043 /// from a forward search, the [`rsplit`] method can be used.
3045 /// [`rsplit`]: #method.rsplit
3049 /// Simple patterns:
3052 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
3053 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
3055 /// let v: Vec<&str> = "".split('X').collect();
3056 /// assert_eq!(v, [""]);
3058 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
3059 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
3061 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
3062 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3064 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
3065 /// assert_eq!(v, ["abc", "def", "ghi"]);
3067 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
3068 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3071 /// A more complex pattern, using a closure:
3074 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
3075 /// assert_eq!(v, ["abc", "def", "ghi"]);
3078 /// If a string contains multiple contiguous separators, you will end up
3079 /// with empty strings in the output:
3082 /// let x = "||||a||b|c".to_string();
3083 /// let d: Vec<_> = x.split('|').collect();
3085 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3088 /// Contiguous separators are separated by the empty string.
3091 /// let x = "(///)".to_string();
3092 /// let d: Vec<_> = x.split('/').collect();
3094 /// assert_eq!(d, &["(", "", "", ")"]);
3097 /// Separators at the start or end of a string are neighbored
3098 /// by empty strings.
3101 /// let d: Vec<_> = "010".split("0").collect();
3102 /// assert_eq!(d, &["", "1", ""]);
3105 /// When the empty string is used as a separator, it separates
3106 /// every character in the string, along with the beginning
3107 /// and end of the string.
3110 /// let f: Vec<_> = "rust".split("").collect();
3111 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
3114 /// Contiguous separators can lead to possibly surprising behavior
3115 /// when whitespace is used as the separator. This code is correct:
3118 /// let x = " a b c".to_string();
3119 /// let d: Vec<_> = x.split(' ').collect();
3121 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3124 /// It does _not_ give you:
3127 /// assert_eq!(d, &["a", "b", "c"]);
3130 /// Use [`split_whitespace`] for this behavior.
3132 /// [`split_whitespace`]: #method.split_whitespace
3133 #[stable(feature = "rust1", since = "1.0.0")]
3135 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
3136 Split(SplitInternal {
3139 matcher: pat.into_searcher(self),
3140 allow_trailing_empty: true,
3145 /// An iterator over substrings of the given string slice, separated by
3146 /// characters matched by a pattern and yielded in reverse order.
3148 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3151 /// # Iterator behavior
3153 /// The returned iterator requires that the pattern supports a reverse
3154 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3155 /// search yields the same elements.
3157 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3159 /// For iterating from the front, the [`split`] method can be used.
3161 /// [`split`]: #method.split
3165 /// Simple patterns:
3168 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
3169 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
3171 /// let v: Vec<&str> = "".rsplit('X').collect();
3172 /// assert_eq!(v, [""]);
3174 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
3175 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
3177 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
3178 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
3181 /// A more complex pattern, using a closure:
3184 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
3185 /// assert_eq!(v, ["ghi", "def", "abc"]);
3187 #[stable(feature = "rust1", since = "1.0.0")]
3189 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
3190 where P::Searcher: ReverseSearcher<'a>
3192 RSplit(self.split(pat).0)
3195 /// An iterator over substrings of the given string slice, separated by
3196 /// characters matched by a pattern.
3198 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3201 /// Equivalent to [`split`], except that the trailing substring
3202 /// is skipped if empty.
3204 /// [`split`]: #method.split
3206 /// This method can be used for string data that is _terminated_,
3207 /// rather than _separated_ by a pattern.
3209 /// # Iterator behavior
3211 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3212 /// allows a reverse search and forward/reverse search yields the same
3213 /// elements. This is true for, eg, [`char`] but not for `&str`.
3215 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3217 /// If the pattern allows a reverse search but its results might differ
3218 /// from a forward search, the [`rsplit_terminator`] method can be used.
3220 /// [`rsplit_terminator`]: #method.rsplit_terminator
3227 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
3228 /// assert_eq!(v, ["A", "B"]);
3230 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
3231 /// assert_eq!(v, ["A", "", "B", ""]);
3233 #[stable(feature = "rust1", since = "1.0.0")]
3235 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
3236 SplitTerminator(SplitInternal {
3237 allow_trailing_empty: false,
3242 /// An iterator over substrings of `self`, separated by characters
3243 /// matched by a pattern and yielded in reverse order.
3245 /// The pattern can be a simple `&str`, [`char`], or a closure that
3246 /// determines the split.
3247 /// Additional libraries might provide more complex patterns like
3248 /// regular expressions.
3250 /// Equivalent to [`split`], except that the trailing substring is
3251 /// skipped if empty.
3253 /// [`split`]: #method.split
3255 /// This method can be used for string data that is _terminated_,
3256 /// rather than _separated_ by a pattern.
3258 /// # Iterator behavior
3260 /// The returned iterator requires that the pattern supports a
3261 /// reverse search, and it will be double ended if a forward/reverse
3262 /// search yields the same elements.
3264 /// For iterating from the front, the [`split_terminator`] method can be
3267 /// [`split_terminator`]: #method.split_terminator
3272 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
3273 /// assert_eq!(v, ["B", "A"]);
3275 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
3276 /// assert_eq!(v, ["", "B", "", "A"]);
3278 #[stable(feature = "rust1", since = "1.0.0")]
3280 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
3281 where P::Searcher: ReverseSearcher<'a>
3283 RSplitTerminator(self.split_terminator(pat).0)
3286 /// An iterator over substrings of the given string slice, separated by a
3287 /// pattern, restricted to returning at most `n` items.
3289 /// If `n` substrings are returned, the last substring (the `n`th substring)
3290 /// will contain the remainder of the string.
3292 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3295 /// # Iterator behavior
3297 /// The returned iterator will not be double ended, because it is
3298 /// not efficient to support.
3300 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
3303 /// [`rsplitn`]: #method.rsplitn
3307 /// Simple patterns:
3310 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
3311 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
3313 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
3314 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
3316 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
3317 /// assert_eq!(v, ["abcXdef"]);
3319 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
3320 /// assert_eq!(v, [""]);
3323 /// A more complex pattern, using a closure:
3326 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
3327 /// assert_eq!(v, ["abc", "defXghi"]);
3329 #[stable(feature = "rust1", since = "1.0.0")]
3331 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
3332 SplitN(SplitNInternal {
3333 iter: self.split(pat).0,
3338 /// An iterator over substrings of this string slice, separated by a
3339 /// pattern, starting from the end of the string, restricted to returning
3340 /// at most `n` items.
3342 /// If `n` substrings are returned, the last substring (the `n`th substring)
3343 /// will contain the remainder of the string.
3345 /// The pattern can be a `&str`, [`char`], or a closure that
3346 /// determines the split.
3348 /// # Iterator behavior
3350 /// The returned iterator will not be double ended, because it is not
3351 /// efficient to support.
3353 /// For splitting from the front, the [`splitn`] method can be used.
3355 /// [`splitn`]: #method.splitn
3359 /// Simple patterns:
3362 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
3363 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
3365 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
3366 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
3368 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
3369 /// assert_eq!(v, ["leopard", "lion::tiger"]);
3372 /// A more complex pattern, using a closure:
3375 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
3376 /// assert_eq!(v, ["ghi", "abc1def"]);
3378 #[stable(feature = "rust1", since = "1.0.0")]
3380 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
3381 where P::Searcher: ReverseSearcher<'a>
3383 RSplitN(self.splitn(n, pat).0)
3386 /// An iterator over the disjoint matches of a pattern within the given string
3389 /// The pattern can be a `&str`, [`char`], or a closure that
3390 /// determines if a character matches.
3392 /// # Iterator behavior
3394 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3395 /// allows a reverse search and forward/reverse search yields the same
3396 /// elements. This is true for, eg, [`char`] but not for `&str`.
3398 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3400 /// If the pattern allows a reverse search but its results might differ
3401 /// from a forward search, the [`rmatches`] method can be used.
3403 /// [`rmatches`]: #method.rmatches
3410 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
3411 /// assert_eq!(v, ["abc", "abc", "abc"]);
3413 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
3414 /// assert_eq!(v, ["1", "2", "3"]);
3416 #[stable(feature = "str_matches", since = "1.2.0")]
3418 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
3419 Matches(MatchesInternal(pat.into_searcher(self)))
3422 /// An iterator over the disjoint matches of a pattern within this string slice,
3423 /// yielded in reverse order.
3425 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3426 /// a character matches.
3428 /// # Iterator behavior
3430 /// The returned iterator requires that the pattern supports a reverse
3431 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3432 /// search yields the same elements.
3434 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3436 /// For iterating from the front, the [`matches`] method can be used.
3438 /// [`matches`]: #method.matches
3445 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
3446 /// assert_eq!(v, ["abc", "abc", "abc"]);
3448 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
3449 /// assert_eq!(v, ["3", "2", "1"]);
3451 #[stable(feature = "str_matches", since = "1.2.0")]
3453 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
3454 where P::Searcher: ReverseSearcher<'a>
3456 RMatches(self.matches(pat).0)
3459 /// An iterator over the disjoint matches of a pattern within this string
3460 /// slice as well as the index that the match starts at.
3462 /// For matches of `pat` within `self` that overlap, only the indices
3463 /// corresponding to the first match are returned.
3465 /// The pattern can be a `&str`, [`char`], or a closure that determines
3466 /// if a character matches.
3468 /// # Iterator behavior
3470 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3471 /// allows a reverse search and forward/reverse search yields the same
3472 /// elements. This is true for, eg, [`char`] but not for `&str`.
3474 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3476 /// If the pattern allows a reverse search but its results might differ
3477 /// from a forward search, the [`rmatch_indices`] method can be used.
3479 /// [`rmatch_indices`]: #method.rmatch_indices
3486 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
3487 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
3489 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
3490 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
3492 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
3493 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
3495 #[stable(feature = "str_match_indices", since = "1.5.0")]
3497 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
3498 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
3501 /// An iterator over the disjoint matches of a pattern within `self`,
3502 /// yielded in reverse order along with the index of the match.
3504 /// For matches of `pat` within `self` that overlap, only the indices
3505 /// corresponding to the last match are returned.
3507 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
3508 /// character matches.
3510 /// # Iterator behavior
3512 /// The returned iterator requires that the pattern supports a reverse
3513 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3514 /// search yields the same elements.
3516 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3518 /// For iterating from the front, the [`match_indices`] method can be used.
3520 /// [`match_indices`]: #method.match_indices
3527 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
3528 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
3530 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
3531 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
3533 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
3534 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
3536 #[stable(feature = "str_match_indices", since = "1.5.0")]
3538 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
3539 where P::Searcher: ReverseSearcher<'a>
3541 RMatchIndices(self.match_indices(pat).0)
3544 /// Returns a string slice with leading and trailing whitespace removed.
3546 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3547 /// Core Property `White_Space`.
3554 /// let s = " Hello\tworld\t";
3556 /// assert_eq!("Hello\tworld", s.trim());
3558 #[stable(feature = "rust1", since = "1.0.0")]
3559 pub fn trim(&self) -> &str {
3560 self.trim_matches(|c: char| c.is_whitespace())
3563 /// Returns a string slice with leading whitespace removed.
3565 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3566 /// Core Property `White_Space`.
3568 /// # Text directionality
3570 /// A string is a sequence of bytes. `start` in this context means the first
3571 /// position of that byte string; for a left-to-right language like English or
3572 /// Russian, this will be left side; and for right-to-left languages like
3573 /// like Arabic or Hebrew, this will be the right side.
3580 /// let s = " Hello\tworld\t";
3581 /// assert_eq!("Hello\tworld\t", s.trim_start());
3587 /// let s = " English ";
3588 /// assert!(Some('E') == s.trim_start().chars().next());
3590 /// let s = " עברית ";
3591 /// assert!(Some('ע') == s.trim_start().chars().next());
3593 #[stable(feature = "trim_direction", since = "1.30.0")]
3594 pub fn trim_start(&self) -> &str {
3595 self.trim_start_matches(|c: char| c.is_whitespace())
3598 /// Returns a string slice with trailing whitespace removed.
3600 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3601 /// Core Property `White_Space`.
3603 /// # Text directionality
3605 /// A string is a sequence of bytes. `end` in this context means the last
3606 /// position of that byte string; for a left-to-right language like English or
3607 /// Russian, this will be right side; and for right-to-left languages like
3608 /// like Arabic or Hebrew, this will be the left side.
3615 /// let s = " Hello\tworld\t";
3616 /// assert_eq!(" Hello\tworld", s.trim_end());
3622 /// let s = " English ";
3623 /// assert!(Some('h') == s.trim_end().chars().rev().next());
3625 /// let s = " עברית ";
3626 /// assert!(Some('ת') == s.trim_end().chars().rev().next());
3628 #[stable(feature = "trim_direction", since = "1.30.0")]
3629 pub fn trim_end(&self) -> &str {
3630 self.trim_end_matches(|c: char| c.is_whitespace())
3633 /// Returns a string slice with leading whitespace removed.
3635 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3636 /// Core Property `White_Space`.
3638 /// # Text directionality
3640 /// A string is a sequence of bytes. 'Left' in this context means the first
3641 /// position of that byte string; for a language like Arabic or Hebrew
3642 /// which are 'right to left' rather than 'left to right', this will be
3643 /// the _right_ side, not the left.
3650 /// let s = " Hello\tworld\t";
3652 /// assert_eq!("Hello\tworld\t", s.trim_left());
3658 /// let s = " English";
3659 /// assert!(Some('E') == s.trim_left().chars().next());
3661 /// let s = " עברית";
3662 /// assert!(Some('ע') == s.trim_left().chars().next());
3664 #[stable(feature = "rust1", since = "1.0.0")]
3665 #[rustc_deprecated(reason = "superseded by `trim_start`", since = "1.33.0")]
3666 pub fn trim_left(&self) -> &str {
3670 /// Returns a string slice with trailing whitespace removed.
3672 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3673 /// Core Property `White_Space`.
3675 /// # Text directionality
3677 /// A string is a sequence of bytes. 'Right' in this context means the last
3678 /// position of that byte string; for a language like Arabic or Hebrew
3679 /// which are 'right to left' rather than 'left to right', this will be
3680 /// the _left_ side, not the right.
3687 /// let s = " Hello\tworld\t";
3689 /// assert_eq!(" Hello\tworld", s.trim_right());
3695 /// let s = "English ";
3696 /// assert!(Some('h') == s.trim_right().chars().rev().next());
3698 /// let s = "עברית ";
3699 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
3701 #[stable(feature = "rust1", since = "1.0.0")]
3702 #[rustc_deprecated(reason = "superseded by `trim_end`", since = "1.33.0")]
3703 pub fn trim_right(&self) -> &str {
3707 /// Returns a string slice with all prefixes and suffixes that match a
3708 /// pattern repeatedly removed.
3710 /// The pattern can be a [`char`] or a closure that determines if a
3711 /// character matches.
3715 /// Simple patterns:
3718 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
3719 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
3721 /// let x: &[_] = &['1', '2'];
3722 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
3725 /// A more complex pattern, using a closure:
3728 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
3730 #[stable(feature = "rust1", since = "1.0.0")]
3731 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3732 where P::Searcher: DoubleEndedSearcher<'a>
3736 let mut matcher = pat.into_searcher(self);
3737 if let Some((a, b)) = matcher.next_reject() {
3739 j = b; // Remember earliest known match, correct it below if
3740 // last match is different
3742 if let Some((_, b)) = matcher.next_reject_back() {
3746 // Searcher is known to return valid indices
3747 self.get_unchecked(i..j)
3751 /// Returns a string slice with all prefixes that match a pattern
3752 /// repeatedly removed.
3754 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3755 /// a character matches.
3757 /// # Text directionality
3759 /// A string is a sequence of bytes. 'Left' in this context means the first
3760 /// position of that byte string; for a language like Arabic or Hebrew
3761 /// which are 'right to left' rather than 'left to right', this will be
3762 /// the _right_ side, not the left.
3769 /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
3770 /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
3772 /// let x: &[_] = &['1', '2'];
3773 /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
3775 #[stable(feature = "trim_direction", since = "1.30.0")]
3776 pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3777 let mut i = self.len();
3778 let mut matcher = pat.into_searcher(self);
3779 if let Some((a, _)) = matcher.next_reject() {
3783 // Searcher is known to return valid indices
3784 self.get_unchecked(i..self.len())
3788 /// Returns a string slice with all suffixes that match a pattern
3789 /// repeatedly removed.
3791 /// The pattern can be a `&str`, [`char`], or a closure that
3792 /// determines if a character matches.
3794 /// # Text directionality
3796 /// A string is a sequence of bytes. 'Right' in this context means the last
3797 /// position of that byte string; for a language like Arabic or Hebrew
3798 /// which are 'right to left' rather than 'left to right', this will be
3799 /// the _left_ side, not the right.
3803 /// Simple patterns:
3806 /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
3807 /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
3809 /// let x: &[_] = &['1', '2'];
3810 /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
3813 /// A more complex pattern, using a closure:
3816 /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
3818 #[stable(feature = "trim_direction", since = "1.30.0")]
3819 pub fn trim_end_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3820 where P::Searcher: ReverseSearcher<'a>
3823 let mut matcher = pat.into_searcher(self);
3824 if let Some((_, b)) = matcher.next_reject_back() {
3828 // Searcher is known to return valid indices
3829 self.get_unchecked(0..j)
3833 /// Returns a string slice with all prefixes that match a pattern
3834 /// repeatedly removed.
3836 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3837 /// a character matches.
3839 /// [`char`]: primitive.char.html
3841 /// # Text directionality
3843 /// A string is a sequence of bytes. 'Left' in this context means the first
3844 /// position of that byte string; for a language like Arabic or Hebrew
3845 /// which are 'right to left' rather than 'left to right', this will be
3846 /// the _right_ side, not the left.
3853 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
3854 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
3856 /// let x: &[_] = &['1', '2'];
3857 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
3859 #[stable(feature = "rust1", since = "1.0.0")]
3860 #[rustc_deprecated(reason = "superseded by `trim_start_matches`", since = "1.33.0")]
3861 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3862 self.trim_start_matches(pat)
3865 /// Returns a string slice with all suffixes that match a pattern
3866 /// repeatedly removed.
3868 /// The pattern can be a `&str`, [`char`], or a closure that
3869 /// determines if a character matches.
3871 /// [`char`]: primitive.char.html
3873 /// # Text directionality
3875 /// A string is a sequence of bytes. 'Right' in this context means the last
3876 /// position of that byte string; for a language like Arabic or Hebrew
3877 /// which are 'right to left' rather than 'left to right', this will be
3878 /// the _left_ side, not the right.
3882 /// Simple patterns:
3885 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
3886 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
3888 /// let x: &[_] = &['1', '2'];
3889 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
3892 /// A more complex pattern, using a closure:
3895 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
3897 #[stable(feature = "rust1", since = "1.0.0")]
3898 #[rustc_deprecated(reason = "superseded by `trim_end_matches`", since = "1.33.0")]
3899 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3900 where P::Searcher: ReverseSearcher<'a>
3902 self.trim_end_matches(pat)
3905 /// Parses this string slice into another type.
3907 /// Because `parse` is so general, it can cause problems with type
3908 /// inference. As such, `parse` is one of the few times you'll see
3909 /// the syntax affectionately known as the 'turbofish': `::<>`. This
3910 /// helps the inference algorithm understand specifically which type
3911 /// you're trying to parse into.
3913 /// `parse` can parse any type that implements the [`FromStr`] trait.
3915 /// [`FromStr`]: str/trait.FromStr.html
3919 /// Will return [`Err`] if it's not possible to parse this string slice into
3920 /// the desired type.
3922 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
3929 /// let four: u32 = "4".parse().unwrap();
3931 /// assert_eq!(4, four);
3934 /// Using the 'turbofish' instead of annotating `four`:
3937 /// let four = "4".parse::<u32>();
3939 /// assert_eq!(Ok(4), four);
3942 /// Failing to parse:
3945 /// let nope = "j".parse::<u32>();
3947 /// assert!(nope.is_err());
3950 #[stable(feature = "rust1", since = "1.0.0")]
3951 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
3952 FromStr::from_str(self)
3955 /// Checks if all characters in this string are within the ASCII range.
3960 /// let ascii = "hello!\n";
3961 /// let non_ascii = "Grüße, Jürgen ❤";
3963 /// assert!(ascii.is_ascii());
3964 /// assert!(!non_ascii.is_ascii());
3966 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3968 pub fn is_ascii(&self) -> bool {
3969 // We can treat each byte as character here: all multibyte characters
3970 // start with a byte that is not in the ascii range, so we will stop
3972 self.bytes().all(|b| b.is_ascii())
3975 /// Checks that two strings are an ASCII case-insensitive match.
3977 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
3978 /// but without allocating and copying temporaries.
3983 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
3984 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
3985 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
3987 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3989 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
3990 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
3993 /// Converts this string to its ASCII upper case equivalent in-place.
3995 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3996 /// but non-ASCII letters are unchanged.
3998 /// To return a new uppercased value without modifying the existing one, use
3999 /// [`to_ascii_uppercase`].
4001 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4002 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4003 pub fn make_ascii_uppercase(&mut self) {
4004 let me = unsafe { self.as_bytes_mut() };
4005 me.make_ascii_uppercase()
4008 /// Converts this string to its ASCII lower case equivalent in-place.
4010 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4011 /// but non-ASCII letters are unchanged.
4013 /// To return a new lowercased value without modifying the existing one, use
4014 /// [`to_ascii_lowercase`].
4016 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4017 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4018 pub fn make_ascii_lowercase(&mut self) {
4019 let me = unsafe { self.as_bytes_mut() };
4020 me.make_ascii_lowercase()
4024 #[stable(feature = "rust1", since = "1.0.0")]
4025 impl AsRef<[u8]> for str {
4027 fn as_ref(&self) -> &[u8] {
4032 #[stable(feature = "rust1", since = "1.0.0")]
4033 impl Default for &str {
4034 /// Creates an empty str
4035 fn default() -> Self { "" }
4038 #[stable(feature = "default_mut_str", since = "1.28.0")]
4039 impl Default for &mut str {
4040 /// Creates an empty mutable str
4041 fn default() -> Self { unsafe { from_utf8_unchecked_mut(&mut []) } }
4044 /// An iterator over the non-whitespace substrings of a string,
4045 /// separated by any amount of whitespace.
4047 /// This struct is created by the [`split_whitespace`] method on [`str`].
4048 /// See its documentation for more.
4050 /// [`split_whitespace`]: ../../std/primitive.str.html#method.split_whitespace
4051 /// [`str`]: ../../std/primitive.str.html
4052 #[stable(feature = "split_whitespace", since = "1.1.0")]
4053 #[derive(Clone, Debug)]
4054 pub struct SplitWhitespace<'a> {
4055 inner: Filter<Split<'a, IsWhitespace>, IsNotEmpty>,
4058 /// An iterator over the non-ASCII-whitespace substrings of a string,
4059 /// separated by any amount of ASCII whitespace.
4061 /// This struct is created by the [`split_ascii_whitespace`] method on [`str`].
4062 /// See its documentation for more.
4064 /// [`split_ascii_whitespace`]: ../../std/primitive.str.html#method.split_ascii_whitespace
4065 /// [`str`]: ../../std/primitive.str.html
4066 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
4067 #[derive(Clone, Debug)]
4068 pub struct SplitAsciiWhitespace<'a> {
4069 inner: Map<Filter<SliceSplit<'a, u8, IsAsciiWhitespace>, IsNotEmpty>, UnsafeBytesToStr>,
4073 struct IsWhitespace;
4075 impl FnOnce<(char, )> for IsWhitespace {
4079 extern "rust-call" fn call_once(mut self, arg: (char, )) -> bool {
4084 impl FnMut<(char, )> for IsWhitespace {
4086 extern "rust-call" fn call_mut(&mut self, arg: (char, )) -> bool {
4087 arg.0.is_whitespace()
4092 struct IsAsciiWhitespace;
4094 impl<'a> FnOnce<(&'a u8, )> for IsAsciiWhitespace {
4098 extern "rust-call" fn call_once(mut self, arg: (&u8, )) -> bool {
4103 impl<'a> FnMut<(&'a u8, )> for IsAsciiWhitespace {
4105 extern "rust-call" fn call_mut(&mut self, arg: (&u8, )) -> bool {
4106 arg.0.is_ascii_whitespace()
4113 impl<'a, 'b> FnOnce<(&'a &'b str, )> for IsNotEmpty {
4117 extern "rust-call" fn call_once(mut self, arg: (&'a &'b str, )) -> bool {
4122 impl<'a, 'b> FnMut<(&'a &'b str, )> for IsNotEmpty {
4124 extern "rust-call" fn call_mut(&mut self, arg: (&'a &'b str, )) -> bool {
4129 impl<'a, 'b> FnOnce<(&'a &'b [u8], )> for IsNotEmpty {
4133 extern "rust-call" fn call_once(mut self, arg: (&'a &'b [u8], )) -> bool {
4138 impl<'a, 'b> FnMut<(&'a &'b [u8], )> for IsNotEmpty {
4140 extern "rust-call" fn call_mut(&mut self, arg: (&'a &'b [u8], )) -> bool {
4146 struct UnsafeBytesToStr;
4148 impl<'a> FnOnce<(&'a [u8], )> for UnsafeBytesToStr {
4149 type Output = &'a str;
4152 extern "rust-call" fn call_once(mut self, arg: (&'a [u8], )) -> &'a str {
4157 impl<'a> FnMut<(&'a [u8], )> for UnsafeBytesToStr {
4159 extern "rust-call" fn call_mut(&mut self, arg: (&'a [u8], )) -> &'a str {
4160 unsafe { from_utf8_unchecked(arg.0) }
4165 #[stable(feature = "split_whitespace", since = "1.1.0")]
4166 impl<'a> Iterator for SplitWhitespace<'a> {
4167 type Item = &'a str;
4170 fn next(&mut self) -> Option<&'a str> {
4175 fn size_hint(&self) -> (usize, Option<usize>) {
4176 self.inner.size_hint()
4180 #[stable(feature = "split_whitespace", since = "1.1.0")]
4181 impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
4183 fn next_back(&mut self) -> Option<&'a str> {
4184 self.inner.next_back()
4188 #[stable(feature = "fused", since = "1.26.0")]
4189 impl FusedIterator for SplitWhitespace<'_> {}
4191 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
4192 impl<'a> Iterator for SplitAsciiWhitespace<'a> {
4193 type Item = &'a str;
4196 fn next(&mut self) -> Option<&'a str> {
4201 fn size_hint(&self) -> (usize, Option<usize>) {
4202 self.inner.size_hint()
4206 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
4207 impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> {
4209 fn next_back(&mut self) -> Option<&'a str> {
4210 self.inner.next_back()
4214 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
4215 impl FusedIterator for SplitAsciiWhitespace<'_> {}
4217 /// An iterator of [`u16`] over the string encoded as UTF-16.
4219 /// [`u16`]: ../../std/primitive.u16.html
4221 /// This struct is created by the [`encode_utf16`] method on [`str`].
4222 /// See its documentation for more.
4224 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
4225 /// [`str`]: ../../std/primitive.str.html
4227 #[stable(feature = "encode_utf16", since = "1.8.0")]
4228 pub struct EncodeUtf16<'a> {
4233 #[stable(feature = "collection_debug", since = "1.17.0")]
4234 impl fmt::Debug for EncodeUtf16<'_> {
4235 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4236 f.pad("EncodeUtf16 { .. }")
4240 #[stable(feature = "encode_utf16", since = "1.8.0")]
4241 impl<'a> Iterator for EncodeUtf16<'a> {
4245 fn next(&mut self) -> Option<u16> {
4246 if self.extra != 0 {
4247 let tmp = self.extra;
4252 let mut buf = [0; 2];
4253 self.chars.next().map(|ch| {
4254 let n = ch.encode_utf16(&mut buf).len();
4256 self.extra = buf[1];
4263 fn size_hint(&self) -> (usize, Option<usize>) {
4264 let (low, high) = self.chars.size_hint();
4265 // every char gets either one u16 or two u16,
4266 // so this iterator is between 1 or 2 times as
4267 // long as the underlying iterator.
4268 (low, high.and_then(|n| n.checked_mul(2)))
4272 #[stable(feature = "fused", since = "1.26.0")]
4273 impl FusedIterator for EncodeUtf16<'_> {}