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()? {
540 next_byte if next_byte < 128 => return Some(next_byte as u32),
541 back_byte => back_byte,
544 // Multibyte case follows
545 // Decode from a byte combination out of: [x [y [z w]]]
547 let z = unwrap_or_0(bytes.next_back());
548 ch = utf8_first_byte(z, 2);
549 if utf8_is_cont_byte(z) {
550 let y = unwrap_or_0(bytes.next_back());
551 ch = utf8_first_byte(y, 3);
552 if utf8_is_cont_byte(y) {
553 let x = unwrap_or_0(bytes.next_back());
554 ch = utf8_first_byte(x, 4);
555 ch = utf8_acc_cont_byte(ch, y);
557 ch = utf8_acc_cont_byte(ch, z);
559 ch = utf8_acc_cont_byte(ch, w);
564 #[stable(feature = "rust1", since = "1.0.0")]
565 impl<'a> Iterator for Chars<'a> {
569 fn next(&mut self) -> Option<char> {
570 next_code_point(&mut self.iter).map(|ch| {
571 // str invariant says `ch` is a valid Unicode Scalar Value
573 char::from_u32_unchecked(ch)
579 fn count(self) -> usize {
580 // length in `char` is equal to the number of non-continuation bytes
581 let bytes_len = self.iter.len();
582 let mut cont_bytes = 0;
583 for &byte in self.iter {
584 cont_bytes += utf8_is_cont_byte(byte) as usize;
586 bytes_len - cont_bytes
590 fn size_hint(&self) -> (usize, Option<usize>) {
591 let len = self.iter.len();
592 // `(len + 3)` can't overflow, because we know that the `slice::Iter`
593 // belongs to a slice in memory which has a maximum length of
594 // `isize::MAX` (that's well below `usize::MAX`).
595 ((len + 3) / 4, Some(len))
599 fn last(mut self) -> Option<char> {
600 // No need to go through the entire string.
605 #[stable(feature = "rust1", since = "1.0.0")]
606 impl<'a> DoubleEndedIterator for Chars<'a> {
608 fn next_back(&mut self) -> Option<char> {
609 next_code_point_reverse(&mut self.iter).map(|ch| {
610 // str invariant says `ch` is a valid Unicode Scalar Value
612 char::from_u32_unchecked(ch)
618 #[stable(feature = "fused", since = "1.26.0")]
619 impl FusedIterator for Chars<'_> {}
622 /// View the underlying data as a subslice of the original data.
624 /// This has the same lifetime as the original slice, and so the
625 /// iterator can continue to be used while this exists.
630 /// let mut chars = "abc".chars();
632 /// assert_eq!(chars.as_str(), "abc");
634 /// assert_eq!(chars.as_str(), "bc");
637 /// assert_eq!(chars.as_str(), "");
639 #[stable(feature = "iter_to_slice", since = "1.4.0")]
641 pub fn as_str(&self) -> &'a str {
642 unsafe { from_utf8_unchecked(self.iter.as_slice()) }
646 /// An iterator over the [`char`]s of a string slice, and their positions.
648 /// [`char`]: ../../std/primitive.char.html
650 /// This struct is created by the [`char_indices`] method on [`str`].
651 /// See its documentation for more.
653 /// [`char_indices`]: ../../std/primitive.str.html#method.char_indices
654 /// [`str`]: ../../std/primitive.str.html
655 #[derive(Clone, Debug)]
656 #[stable(feature = "rust1", since = "1.0.0")]
657 pub struct CharIndices<'a> {
662 #[stable(feature = "rust1", since = "1.0.0")]
663 impl<'a> Iterator for CharIndices<'a> {
664 type Item = (usize, char);
667 fn next(&mut self) -> Option<(usize, char)> {
668 let pre_len = self.iter.iter.len();
669 match self.iter.next() {
672 let index = self.front_offset;
673 let len = self.iter.iter.len();
674 self.front_offset += pre_len - len;
681 fn count(self) -> usize {
686 fn size_hint(&self) -> (usize, Option<usize>) {
687 self.iter.size_hint()
691 fn last(mut self) -> Option<(usize, char)> {
692 // No need to go through the entire string.
697 #[stable(feature = "rust1", since = "1.0.0")]
698 impl<'a> DoubleEndedIterator for CharIndices<'a> {
700 fn next_back(&mut self) -> Option<(usize, char)> {
701 self.iter.next_back().map(|ch| {
702 let index = self.front_offset + self.iter.iter.len();
708 #[stable(feature = "fused", since = "1.26.0")]
709 impl FusedIterator for CharIndices<'_> {}
711 impl<'a> CharIndices<'a> {
712 /// View the underlying data as a subslice of the original data.
714 /// This has the same lifetime as the original slice, and so the
715 /// iterator can continue to be used while this exists.
716 #[stable(feature = "iter_to_slice", since = "1.4.0")]
718 pub fn as_str(&self) -> &'a str {
723 /// An iterator over the bytes of a string slice.
725 /// This struct is created by the [`bytes`] method on [`str`].
726 /// See its documentation for more.
728 /// [`bytes`]: ../../std/primitive.str.html#method.bytes
729 /// [`str`]: ../../std/primitive.str.html
730 #[stable(feature = "rust1", since = "1.0.0")]
731 #[derive(Clone, Debug)]
732 pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>);
734 #[stable(feature = "rust1", since = "1.0.0")]
735 impl Iterator for Bytes<'_> {
739 fn next(&mut self) -> Option<u8> {
744 fn size_hint(&self) -> (usize, Option<usize>) {
749 fn count(self) -> usize {
754 fn last(self) -> Option<Self::Item> {
759 fn nth(&mut self, n: usize) -> Option<Self::Item> {
764 fn all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
769 fn any<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
774 fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where
775 P: FnMut(&Self::Item) -> bool
777 self.0.find(predicate)
781 fn position<P>(&mut self, predicate: P) -> Option<usize> where
782 P: FnMut(Self::Item) -> bool
784 self.0.position(predicate)
788 fn rposition<P>(&mut self, predicate: P) -> Option<usize> where
789 P: FnMut(Self::Item) -> bool
791 self.0.rposition(predicate)
795 #[stable(feature = "rust1", since = "1.0.0")]
796 impl DoubleEndedIterator for Bytes<'_> {
798 fn next_back(&mut self) -> Option<u8> {
803 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> where
804 P: FnMut(&Self::Item) -> bool
806 self.0.rfind(predicate)
810 #[stable(feature = "rust1", since = "1.0.0")]
811 impl ExactSizeIterator for Bytes<'_> {
813 fn len(&self) -> usize {
818 fn is_empty(&self) -> bool {
823 #[stable(feature = "fused", since = "1.26.0")]
824 impl FusedIterator for Bytes<'_> {}
826 #[unstable(feature = "trusted_len", issue = "37572")]
827 unsafe impl TrustedLen for Bytes<'_> {}
830 unsafe impl<'a> TrustedRandomAccess for Bytes<'a> {
831 unsafe fn get_unchecked(&mut self, i: usize) -> u8 {
832 self.0.get_unchecked(i)
834 fn may_have_side_effect() -> bool { false }
837 /// This macro generates a Clone impl for string pattern API
838 /// wrapper types of the form X<'a, P>
839 macro_rules! derive_pattern_clone {
840 (clone $t:ident with |$s:ident| $e:expr) => {
841 impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
842 where P::Searcher: Clone
844 fn clone(&self) -> Self {
852 /// This macro generates two public iterator structs
853 /// wrapping a private internal one that makes use of the `Pattern` API.
855 /// For all patterns `P: Pattern<'a>` the following items will be
856 /// generated (generics omitted):
858 /// struct $forward_iterator($internal_iterator);
859 /// struct $reverse_iterator($internal_iterator);
861 /// impl Iterator for $forward_iterator
862 /// { /* internal ends up calling Searcher::next_match() */ }
864 /// impl DoubleEndedIterator for $forward_iterator
865 /// where P::Searcher: DoubleEndedSearcher
866 /// { /* internal ends up calling Searcher::next_match_back() */ }
868 /// impl Iterator for $reverse_iterator
869 /// where P::Searcher: ReverseSearcher
870 /// { /* internal ends up calling Searcher::next_match_back() */ }
872 /// impl DoubleEndedIterator for $reverse_iterator
873 /// where P::Searcher: DoubleEndedSearcher
874 /// { /* internal ends up calling Searcher::next_match() */ }
876 /// The internal one is defined outside the macro, and has almost the same
877 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
878 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
880 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
881 /// `Pattern` might not return the same elements, so actually implementing
882 /// `DoubleEndedIterator` for it would be incorrect.
883 /// (See the docs in `str::pattern` for more details)
885 /// However, the internal struct still represents a single ended iterator from
886 /// either end, and depending on pattern is also a valid double ended iterator,
887 /// so the two wrapper structs implement `Iterator`
888 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
889 /// to the complex impls seen above.
890 macro_rules! generate_pattern_iterators {
894 $(#[$forward_iterator_attribute:meta])*
895 struct $forward_iterator:ident;
899 $(#[$reverse_iterator_attribute:meta])*
900 struct $reverse_iterator:ident;
902 // Stability of all generated items
904 $(#[$common_stability_attribute:meta])*
906 // Internal almost-iterator that is being delegated to
908 $internal_iterator:ident yielding ($iterty:ty);
910 // Kind of delegation - either single ended or double ended
913 $(#[$forward_iterator_attribute])*
914 $(#[$common_stability_attribute])*
915 pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
917 $(#[$common_stability_attribute])*
918 impl<'a, P: Pattern<'a>> fmt::Debug for $forward_iterator<'a, P>
919 where P::Searcher: fmt::Debug
921 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
922 f.debug_tuple(stringify!($forward_iterator))
928 $(#[$common_stability_attribute])*
929 impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
933 fn next(&mut self) -> Option<$iterty> {
938 $(#[$common_stability_attribute])*
939 impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
940 where P::Searcher: Clone
942 fn clone(&self) -> Self {
943 $forward_iterator(self.0.clone())
947 $(#[$reverse_iterator_attribute])*
948 $(#[$common_stability_attribute])*
949 pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
951 $(#[$common_stability_attribute])*
952 impl<'a, P: Pattern<'a>> fmt::Debug for $reverse_iterator<'a, P>
953 where P::Searcher: fmt::Debug
955 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
956 f.debug_tuple(stringify!($reverse_iterator))
962 $(#[$common_stability_attribute])*
963 impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
964 where P::Searcher: ReverseSearcher<'a>
969 fn next(&mut self) -> Option<$iterty> {
974 $(#[$common_stability_attribute])*
975 impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
976 where P::Searcher: Clone
978 fn clone(&self) -> Self {
979 $reverse_iterator(self.0.clone())
983 #[stable(feature = "fused", since = "1.26.0")]
984 impl<'a, P: Pattern<'a>> FusedIterator for $forward_iterator<'a, P> {}
986 #[stable(feature = "fused", since = "1.26.0")]
987 impl<'a, P: Pattern<'a>> FusedIterator for $reverse_iterator<'a, P>
988 where P::Searcher: ReverseSearcher<'a> {}
990 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
992 $reverse_iterator, $iterty);
995 double ended; with $(#[$common_stability_attribute:meta])*,
996 $forward_iterator:ident,
997 $reverse_iterator:ident, $iterty:ty
999 $(#[$common_stability_attribute])*
1000 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
1001 where P::Searcher: DoubleEndedSearcher<'a>
1004 fn next_back(&mut self) -> Option<$iterty> {
1009 $(#[$common_stability_attribute])*
1010 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
1011 where P::Searcher: DoubleEndedSearcher<'a>
1014 fn next_back(&mut self) -> Option<$iterty> {
1020 single ended; with $(#[$common_stability_attribute:meta])*,
1021 $forward_iterator:ident,
1022 $reverse_iterator:ident, $iterty:ty
1026 derive_pattern_clone!{
1028 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
1031 struct SplitInternal<'a, P: Pattern<'a>> {
1034 matcher: P::Searcher,
1035 allow_trailing_empty: bool,
1039 impl<'a, P: Pattern<'a>> fmt::Debug for SplitInternal<'a, P> where P::Searcher: fmt::Debug {
1040 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1041 f.debug_struct("SplitInternal")
1042 .field("start", &self.start)
1043 .field("end", &self.end)
1044 .field("matcher", &self.matcher)
1045 .field("allow_trailing_empty", &self.allow_trailing_empty)
1046 .field("finished", &self.finished)
1051 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
1053 fn get_end(&mut self) -> Option<&'a str> {
1054 if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
1055 self.finished = true;
1057 let string = self.matcher.haystack().get_unchecked(self.start..self.end);
1066 fn next(&mut self) -> Option<&'a str> {
1067 if self.finished { return None }
1069 let haystack = self.matcher.haystack();
1070 match self.matcher.next_match() {
1071 Some((a, b)) => unsafe {
1072 let elt = haystack.get_unchecked(self.start..a);
1076 None => self.get_end(),
1081 fn next_back(&mut self) -> Option<&'a str>
1082 where P::Searcher: ReverseSearcher<'a>
1084 if self.finished { return None }
1086 if !self.allow_trailing_empty {
1087 self.allow_trailing_empty = true;
1088 match self.next_back() {
1089 Some(elt) if !elt.is_empty() => return Some(elt),
1090 _ => if self.finished { return None }
1094 let haystack = self.matcher.haystack();
1095 match self.matcher.next_match_back() {
1096 Some((a, b)) => unsafe {
1097 let elt = haystack.get_unchecked(b..self.end);
1102 self.finished = true;
1103 Some(haystack.get_unchecked(self.start..self.end))
1109 generate_pattern_iterators! {
1111 /// Created with the method [`split`].
1113 /// [`split`]: ../../std/primitive.str.html#method.split
1116 /// Created with the method [`rsplit`].
1118 /// [`rsplit`]: ../../std/primitive.str.html#method.rsplit
1121 #[stable(feature = "rust1", since = "1.0.0")]
1123 SplitInternal yielding (&'a str);
1124 delegate double ended;
1127 generate_pattern_iterators! {
1129 /// Created with the method [`split_terminator`].
1131 /// [`split_terminator`]: ../../std/primitive.str.html#method.split_terminator
1132 struct SplitTerminator;
1134 /// Created with the method [`rsplit_terminator`].
1136 /// [`rsplit_terminator`]: ../../std/primitive.str.html#method.rsplit_terminator
1137 struct RSplitTerminator;
1139 #[stable(feature = "rust1", since = "1.0.0")]
1141 SplitInternal yielding (&'a str);
1142 delegate double ended;
1145 derive_pattern_clone!{
1146 clone SplitNInternal
1147 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
1150 struct SplitNInternal<'a, P: Pattern<'a>> {
1151 iter: SplitInternal<'a, P>,
1152 /// The number of splits remaining
1156 impl<'a, P: Pattern<'a>> fmt::Debug for SplitNInternal<'a, P> where P::Searcher: fmt::Debug {
1157 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1158 f.debug_struct("SplitNInternal")
1159 .field("iter", &self.iter)
1160 .field("count", &self.count)
1165 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
1167 fn next(&mut self) -> Option<&'a str> {
1170 1 => { self.count = 0; self.iter.get_end() }
1171 _ => { self.count -= 1; self.iter.next() }
1176 fn next_back(&mut self) -> Option<&'a str>
1177 where P::Searcher: ReverseSearcher<'a>
1181 1 => { self.count = 0; self.iter.get_end() }
1182 _ => { self.count -= 1; self.iter.next_back() }
1187 generate_pattern_iterators! {
1189 /// Created with the method [`splitn`].
1191 /// [`splitn`]: ../../std/primitive.str.html#method.splitn
1194 /// Created with the method [`rsplitn`].
1196 /// [`rsplitn`]: ../../std/primitive.str.html#method.rsplitn
1199 #[stable(feature = "rust1", since = "1.0.0")]
1201 SplitNInternal yielding (&'a str);
1202 delegate single ended;
1205 derive_pattern_clone!{
1206 clone MatchIndicesInternal
1207 with |s| MatchIndicesInternal(s.0.clone())
1210 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
1212 impl<'a, P: Pattern<'a>> fmt::Debug for MatchIndicesInternal<'a, P> where P::Searcher: fmt::Debug {
1213 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1214 f.debug_tuple("MatchIndicesInternal")
1220 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
1222 fn next(&mut self) -> Option<(usize, &'a str)> {
1223 self.0.next_match().map(|(start, end)| unsafe {
1224 (start, self.0.haystack().get_unchecked(start..end))
1229 fn next_back(&mut self) -> Option<(usize, &'a str)>
1230 where P::Searcher: ReverseSearcher<'a>
1232 self.0.next_match_back().map(|(start, end)| unsafe {
1233 (start, self.0.haystack().get_unchecked(start..end))
1238 generate_pattern_iterators! {
1240 /// Created with the method [`match_indices`].
1242 /// [`match_indices`]: ../../std/primitive.str.html#method.match_indices
1243 struct MatchIndices;
1245 /// Created with the method [`rmatch_indices`].
1247 /// [`rmatch_indices`]: ../../std/primitive.str.html#method.rmatch_indices
1248 struct RMatchIndices;
1250 #[stable(feature = "str_match_indices", since = "1.5.0")]
1252 MatchIndicesInternal yielding ((usize, &'a str));
1253 delegate double ended;
1256 derive_pattern_clone!{
1257 clone MatchesInternal
1258 with |s| MatchesInternal(s.0.clone())
1261 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
1263 impl<'a, P: Pattern<'a>> fmt::Debug for MatchesInternal<'a, P> where P::Searcher: fmt::Debug {
1264 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1265 f.debug_tuple("MatchesInternal")
1271 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
1273 fn next(&mut self) -> Option<&'a str> {
1274 self.0.next_match().map(|(a, b)| unsafe {
1275 // Indices are known to be on utf8 boundaries
1276 self.0.haystack().get_unchecked(a..b)
1281 fn next_back(&mut self) -> Option<&'a str>
1282 where P::Searcher: ReverseSearcher<'a>
1284 self.0.next_match_back().map(|(a, b)| unsafe {
1285 // Indices are known to be on utf8 boundaries
1286 self.0.haystack().get_unchecked(a..b)
1291 generate_pattern_iterators! {
1293 /// Created with the method [`matches`].
1295 /// [`matches`]: ../../std/primitive.str.html#method.matches
1298 /// Created with the method [`rmatches`].
1300 /// [`rmatches`]: ../../std/primitive.str.html#method.rmatches
1303 #[stable(feature = "str_matches", since = "1.2.0")]
1305 MatchesInternal yielding (&'a str);
1306 delegate double ended;
1309 /// An iterator over the lines of a string, as string slices.
1311 /// This struct is created with the [`lines`] method on [`str`].
1312 /// See its documentation for more.
1314 /// [`lines`]: ../../std/primitive.str.html#method.lines
1315 /// [`str`]: ../../std/primitive.str.html
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 #[derive(Clone, Debug)]
1318 pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>);
1320 #[stable(feature = "rust1", since = "1.0.0")]
1321 impl<'a> Iterator for Lines<'a> {
1322 type Item = &'a str;
1325 fn next(&mut self) -> Option<&'a str> {
1330 fn size_hint(&self) -> (usize, Option<usize>) {
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 impl<'a> DoubleEndedIterator for Lines<'a> {
1338 fn next_back(&mut self) -> Option<&'a str> {
1343 #[stable(feature = "fused", since = "1.26.0")]
1344 impl FusedIterator for Lines<'_> {}
1346 /// Created with the method [`lines_any`].
1348 /// [`lines_any`]: ../../std/primitive.str.html#method.lines_any
1349 #[stable(feature = "rust1", since = "1.0.0")]
1350 #[rustc_deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")]
1351 #[derive(Clone, Debug)]
1352 #[allow(deprecated)]
1353 pub struct LinesAny<'a>(Lines<'a>);
1355 /// A nameable, cloneable fn type
1359 impl<'a> Fn<(&'a str,)> for LinesAnyMap {
1361 extern "rust-call" fn call(&self, (line,): (&'a str,)) -> &'a str {
1363 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
1368 impl<'a> FnMut<(&'a str,)> for LinesAnyMap {
1370 extern "rust-call" fn call_mut(&mut self, (line,): (&'a str,)) -> &'a str {
1371 Fn::call(&*self, (line,))
1375 impl<'a> FnOnce<(&'a str,)> for LinesAnyMap {
1376 type Output = &'a str;
1379 extern "rust-call" fn call_once(self, (line,): (&'a str,)) -> &'a str {
1380 Fn::call(&self, (line,))
1384 #[stable(feature = "rust1", since = "1.0.0")]
1385 #[allow(deprecated)]
1386 impl<'a> Iterator for LinesAny<'a> {
1387 type Item = &'a str;
1390 fn next(&mut self) -> Option<&'a str> {
1395 fn size_hint(&self) -> (usize, Option<usize>) {
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 #[allow(deprecated)]
1402 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1404 fn next_back(&mut self) -> Option<&'a str> {
1409 #[stable(feature = "fused", since = "1.26.0")]
1410 #[allow(deprecated)]
1411 impl FusedIterator for LinesAny<'_> {}
1414 Section: UTF-8 validation
1417 // use truncation to fit u64 into usize
1418 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
1420 /// Returns `true` if any byte in the word `x` is nonascii (>= 128).
1422 fn contains_nonascii(x: usize) -> bool {
1423 (x & NONASCII_MASK) != 0
1426 /// Walks through `iter` checking that it's a valid UTF-8 sequence,
1427 /// returning `true` in that case, or, if it is invalid, `false` with
1428 /// `iter` reset such that it is pointing at the first byte in the
1429 /// invalid sequence.
1431 fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
1435 let usize_bytes = mem::size_of::<usize>();
1436 let ascii_block_size = 2 * usize_bytes;
1437 let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
1440 let old_offset = index;
1442 ($error_len: expr) => {
1443 return Err(Utf8Error {
1444 valid_up_to: old_offset,
1445 error_len: $error_len,
1450 macro_rules! next { () => {{
1452 // we needed data, but there was none: error!
1459 let first = v[index];
1461 let w = UTF8_CHAR_WIDTH[first as usize];
1462 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
1463 // first C2 80 last DF BF
1464 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
1465 // first E0 A0 80 last EF BF BF
1466 // excluding surrogates codepoints \u{d800} to \u{dfff}
1467 // ED A0 80 to ED BF BF
1468 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1469 // first F0 90 80 80 last F4 8F BF BF
1471 // Use the UTF-8 syntax from the RFC
1473 // https://tools.ietf.org/html/rfc3629
1475 // UTF8-2 = %xC2-DF UTF8-tail
1476 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1477 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1478 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1479 // %xF4 %x80-8F 2( UTF8-tail )
1481 2 => if next!() & !CONT_MASK != TAG_CONT_U8 {
1485 match (first, next!()) {
1486 (0xE0 , 0xA0 ..= 0xBF) |
1487 (0xE1 ..= 0xEC, 0x80 ..= 0xBF) |
1488 (0xED , 0x80 ..= 0x9F) |
1489 (0xEE ..= 0xEF, 0x80 ..= 0xBF) => {}
1492 if next!() & !CONT_MASK != TAG_CONT_U8 {
1497 match (first, next!()) {
1498 (0xF0 , 0x90 ..= 0xBF) |
1499 (0xF1 ..= 0xF3, 0x80 ..= 0xBF) |
1500 (0xF4 , 0x80 ..= 0x8F) => {}
1503 if next!() & !CONT_MASK != TAG_CONT_U8 {
1506 if next!() & !CONT_MASK != TAG_CONT_U8 {
1514 // Ascii case, try to skip forward quickly.
1515 // When the pointer is aligned, read 2 words of data per iteration
1516 // until we find a word containing a non-ascii byte.
1517 let ptr = v.as_ptr();
1518 let align = unsafe {
1519 // the offset is safe, because `index` is guaranteed inbounds
1520 ptr.add(index).align_offset(usize_bytes)
1523 while index < blocks_end {
1525 let block = ptr.add(index) as *const usize;
1526 // break if there is a nonascii byte
1527 let zu = contains_nonascii(*block);
1528 let zv = contains_nonascii(*block.offset(1));
1533 index += ascii_block_size;
1535 // step from the point where the wordwise loop stopped
1536 while index < len && v[index] < 128 {
1548 // https://tools.ietf.org/html/rfc3629
1549 static UTF8_CHAR_WIDTH: [u8; 256] = [
1550 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1551 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1552 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1553 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1554 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1555 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1556 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1557 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1558 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1559 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1560 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1561 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1562 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1563 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1564 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1565 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1568 /// Given a first byte, determines how many bytes are in this UTF-8 character.
1569 #[unstable(feature = "str_internals", issue = "0")]
1571 pub fn utf8_char_width(b: u8) -> usize {
1572 UTF8_CHAR_WIDTH[b as usize] as usize
1575 /// Mask of the value bits of a continuation byte.
1576 const CONT_MASK: u8 = 0b0011_1111;
1577 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte.
1578 const TAG_CONT_U8: u8 = 0b1000_0000;
1581 Section: Trait implementations
1587 use slice::{self, SliceIndex};
1589 /// Implements ordering of strings.
1591 /// Strings are ordered lexicographically by their byte values. This orders Unicode code
1592 /// points based on their positions in the code charts. This is not necessarily the same as
1593 /// "alphabetical" order, which varies by language and locale. Sorting strings according to
1594 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1596 #[stable(feature = "rust1", since = "1.0.0")]
1599 fn cmp(&self, other: &str) -> Ordering {
1600 self.as_bytes().cmp(other.as_bytes())
1604 #[stable(feature = "rust1", since = "1.0.0")]
1605 impl PartialEq for str {
1607 fn eq(&self, other: &str) -> bool {
1608 self.as_bytes() == other.as_bytes()
1611 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1614 #[stable(feature = "rust1", since = "1.0.0")]
1617 /// Implements comparison operations on strings.
1619 /// Strings are compared lexicographically by their byte values. This compares Unicode code
1620 /// points based on their positions in the code charts. This is not necessarily the same as
1621 /// "alphabetical" order, which varies by language and locale. Comparing strings according to
1622 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 impl PartialOrd for str {
1627 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1628 Some(self.cmp(other))
1632 /// Implements substring slicing with syntax `&self[begin .. end]`.
1634 /// Returns a slice of the given string from the byte range
1635 /// [`begin`..`end`).
1637 /// This operation is `O(1)`.
1641 /// Panics if `begin` or `end` does not point to the starting
1642 /// byte offset of a character (as defined by `is_char_boundary`).
1643 /// Requires that `begin <= end` and `end <= len` where `len` is the
1644 /// length of the string.
1649 /// let s = "Löwe 老虎 Léopard";
1650 /// assert_eq!(&s[0 .. 1], "L");
1652 /// assert_eq!(&s[1 .. 9], "öwe 老");
1654 /// // these will panic:
1655 /// // byte 2 lies within `ö`:
1658 /// // byte 8 lies within `老`
1661 /// // byte 100 is outside the string
1662 /// // &s[3 .. 100];
1664 #[stable(feature = "rust1", since = "1.0.0")]
1665 impl ops::Index<ops::Range<usize>> for str {
1668 fn index(&self, index: ops::Range<usize>) -> &str {
1673 /// Implements mutable substring slicing with syntax
1674 /// `&mut self[begin .. end]`.
1676 /// Returns a mutable slice of the given string from the byte range
1677 /// [`begin`..`end`).
1679 /// This operation is `O(1)`.
1683 /// Panics if `begin` or `end` does not point to the starting
1684 /// byte offset of a character (as defined by `is_char_boundary`).
1685 /// Requires that `begin <= end` and `end <= len` where `len` is the
1686 /// length of the string.
1687 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1688 impl ops::IndexMut<ops::Range<usize>> for str {
1690 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1691 index.index_mut(self)
1695 /// Implements substring slicing with syntax `&self[.. end]`.
1697 /// Returns a slice of the string from the beginning to byte offset
1700 /// Equivalent to `&self[0 .. end]`.
1701 #[stable(feature = "rust1", since = "1.0.0")]
1702 impl ops::Index<ops::RangeTo<usize>> for str {
1706 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1711 /// Implements mutable substring slicing with syntax `&mut self[.. end]`.
1713 /// Returns a mutable slice of the string from the beginning to byte offset
1716 /// Equivalent to `&mut self[0 .. end]`.
1717 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1718 impl ops::IndexMut<ops::RangeTo<usize>> for str {
1720 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1721 index.index_mut(self)
1725 /// Implements substring slicing with syntax `&self[begin ..]`.
1727 /// Returns a slice of the string from byte offset `begin`
1728 /// to the end of the string.
1730 /// Equivalent to `&self[begin .. len]`.
1731 #[stable(feature = "rust1", since = "1.0.0")]
1732 impl ops::Index<ops::RangeFrom<usize>> for str {
1736 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1741 /// Implements mutable substring slicing with syntax `&mut self[begin ..]`.
1743 /// Returns a mutable slice of the string from byte offset `begin`
1744 /// to the end of the string.
1746 /// Equivalent to `&mut self[begin .. len]`.
1747 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1748 impl ops::IndexMut<ops::RangeFrom<usize>> for str {
1750 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1751 index.index_mut(self)
1755 /// Implements substring slicing with syntax `&self[..]`.
1757 /// Returns a slice of the whole string. This operation can
1760 /// Equivalent to `&self[0 .. len]`.
1761 #[stable(feature = "rust1", since = "1.0.0")]
1762 impl ops::Index<ops::RangeFull> for str {
1766 fn index(&self, _index: ops::RangeFull) -> &str {
1771 /// Implements mutable substring slicing with syntax `&mut self[..]`.
1773 /// Returns a mutable slice of the whole string. This operation can
1776 /// Equivalent to `&mut self[0 .. len]`.
1777 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1778 impl ops::IndexMut<ops::RangeFull> for str {
1780 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1785 #[stable(feature = "inclusive_range", since = "1.26.0")]
1786 impl ops::Index<ops::RangeInclusive<usize>> for str {
1790 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1795 #[stable(feature = "inclusive_range", since = "1.26.0")]
1796 impl ops::Index<ops::RangeToInclusive<usize>> for str {
1800 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1805 #[stable(feature = "inclusive_range", since = "1.26.0")]
1806 impl ops::IndexMut<ops::RangeInclusive<usize>> for str {
1808 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1809 index.index_mut(self)
1812 #[stable(feature = "inclusive_range", since = "1.26.0")]
1813 impl ops::IndexMut<ops::RangeToInclusive<usize>> for str {
1815 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1816 index.index_mut(self)
1822 fn str_index_overflow_fail() -> ! {
1823 panic!("attempted to index str up to maximum usize");
1826 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1827 impl SliceIndex<str> for ops::RangeFull {
1830 fn get(self, slice: &str) -> Option<&Self::Output> {
1834 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1838 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1842 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1846 fn index(self, slice: &str) -> &Self::Output {
1850 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1855 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1856 impl SliceIndex<str> for ops::Range<usize> {
1859 fn get(self, slice: &str) -> Option<&Self::Output> {
1860 if self.start <= self.end &&
1861 slice.is_char_boundary(self.start) &&
1862 slice.is_char_boundary(self.end) {
1863 Some(unsafe { self.get_unchecked(slice) })
1869 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1870 if self.start <= self.end &&
1871 slice.is_char_boundary(self.start) &&
1872 slice.is_char_boundary(self.end) {
1873 Some(unsafe { self.get_unchecked_mut(slice) })
1879 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1880 let ptr = slice.as_ptr().add(self.start);
1881 let len = self.end - self.start;
1882 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1885 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1886 let ptr = slice.as_ptr().add(self.start);
1887 let len = self.end - self.start;
1888 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1891 fn index(self, slice: &str) -> &Self::Output {
1892 let (start, end) = (self.start, self.end);
1893 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1896 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1897 // is_char_boundary checks that the index is in [0, .len()]
1898 // canot reuse `get` as above, because of NLL trouble
1899 if self.start <= self.end &&
1900 slice.is_char_boundary(self.start) &&
1901 slice.is_char_boundary(self.end) {
1902 unsafe { self.get_unchecked_mut(slice) }
1904 super::slice_error_fail(slice, self.start, self.end)
1909 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1910 impl SliceIndex<str> for ops::RangeTo<usize> {
1913 fn get(self, slice: &str) -> Option<&Self::Output> {
1914 if slice.is_char_boundary(self.end) {
1915 Some(unsafe { self.get_unchecked(slice) })
1921 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1922 if slice.is_char_boundary(self.end) {
1923 Some(unsafe { self.get_unchecked_mut(slice) })
1929 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1930 let ptr = slice.as_ptr();
1931 super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end))
1934 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1935 let ptr = slice.as_ptr();
1936 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, self.end))
1939 fn index(self, slice: &str) -> &Self::Output {
1941 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end))
1944 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1945 // is_char_boundary checks that the index is in [0, .len()]
1946 if slice.is_char_boundary(self.end) {
1947 unsafe { self.get_unchecked_mut(slice) }
1949 super::slice_error_fail(slice, 0, self.end)
1954 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1955 impl SliceIndex<str> for ops::RangeFrom<usize> {
1958 fn get(self, slice: &str) -> Option<&Self::Output> {
1959 if slice.is_char_boundary(self.start) {
1960 Some(unsafe { self.get_unchecked(slice) })
1966 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1967 if slice.is_char_boundary(self.start) {
1968 Some(unsafe { self.get_unchecked_mut(slice) })
1974 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1975 let ptr = slice.as_ptr().add(self.start);
1976 let len = slice.len() - self.start;
1977 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1980 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1981 let ptr = slice.as_ptr().add(self.start);
1982 let len = slice.len() - self.start;
1983 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1986 fn index(self, slice: &str) -> &Self::Output {
1987 let (start, end) = (self.start, slice.len());
1988 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1991 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1992 // is_char_boundary checks that the index is in [0, .len()]
1993 if slice.is_char_boundary(self.start) {
1994 unsafe { self.get_unchecked_mut(slice) }
1996 super::slice_error_fail(slice, self.start, slice.len())
2001 #[stable(feature = "inclusive_range", since = "1.26.0")]
2002 impl SliceIndex<str> for ops::RangeInclusive<usize> {
2005 fn get(self, slice: &str) -> Option<&Self::Output> {
2006 if *self.end() == usize::max_value() { None }
2007 else { (*self.start()..self.end()+1).get(slice) }
2010 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
2011 if *self.end() == usize::max_value() { None }
2012 else { (*self.start()..self.end()+1).get_mut(slice) }
2015 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
2016 (*self.start()..self.end()+1).get_unchecked(slice)
2019 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
2020 (*self.start()..self.end()+1).get_unchecked_mut(slice)
2023 fn index(self, slice: &str) -> &Self::Output {
2024 if *self.end() == usize::max_value() { str_index_overflow_fail(); }
2025 (*self.start()..self.end()+1).index(slice)
2028 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
2029 if *self.end() == usize::max_value() { str_index_overflow_fail(); }
2030 (*self.start()..self.end()+1).index_mut(slice)
2036 #[stable(feature = "inclusive_range", since = "1.26.0")]
2037 impl SliceIndex<str> for ops::RangeToInclusive<usize> {
2040 fn get(self, slice: &str) -> Option<&Self::Output> {
2041 if self.end == usize::max_value() { None }
2042 else { (..self.end+1).get(slice) }
2045 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
2046 if self.end == usize::max_value() { None }
2047 else { (..self.end+1).get_mut(slice) }
2050 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
2051 (..self.end+1).get_unchecked(slice)
2054 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
2055 (..self.end+1).get_unchecked_mut(slice)
2058 fn index(self, slice: &str) -> &Self::Output {
2059 if self.end == usize::max_value() { str_index_overflow_fail(); }
2060 (..self.end+1).index(slice)
2063 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
2064 if self.end == usize::max_value() { str_index_overflow_fail(); }
2065 (..self.end+1).index_mut(slice)
2070 // truncate `&str` to length at most equal to `max`
2071 // return `true` if it were truncated, and the new str.
2072 fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
2076 while !s.is_char_boundary(max) {
2085 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
2086 const MAX_DISPLAY_LENGTH: usize = 256;
2087 let (truncated, s_trunc) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
2088 let ellipsis = if truncated { "[...]" } else { "" };
2091 if begin > s.len() || end > s.len() {
2092 let oob_index = if begin > s.len() { begin } else { end };
2093 panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
2097 assert!(begin <= end, "begin <= end ({} <= {}) when slicing `{}`{}",
2098 begin, end, s_trunc, ellipsis);
2100 // 3. character boundary
2101 let index = if !s.is_char_boundary(begin) { begin } else { end };
2102 // find the character
2103 let mut char_start = index;
2104 while !s.is_char_boundary(char_start) {
2107 // `char_start` must be less than len and a char boundary
2108 let ch = s[char_start..].chars().next().unwrap();
2109 let char_range = char_start .. char_start + ch.len_utf8();
2110 panic!("byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
2111 index, ch, char_range, s_trunc, ellipsis);
2117 /// Returns the length of `self`.
2119 /// This length is in bytes, not [`char`]s or graphemes. In other words,
2120 /// it may not be what a human considers the length of the string.
2127 /// let len = "foo".len();
2128 /// assert_eq!(3, len);
2130 /// let len = "ƒoo".len(); // fancy f!
2131 /// assert_eq!(4, len);
2133 #[stable(feature = "rust1", since = "1.0.0")]
2135 #[rustc_const_unstable(feature = "const_str_len")]
2136 pub const fn len(&self) -> usize {
2137 self.as_bytes().len()
2140 /// Returns `true` if `self` has a length of zero bytes.
2148 /// assert!(s.is_empty());
2150 /// let s = "not empty";
2151 /// assert!(!s.is_empty());
2154 #[stable(feature = "rust1", since = "1.0.0")]
2155 #[rustc_const_unstable(feature = "const_str_len")]
2156 pub const fn is_empty(&self) -> bool {
2160 /// Checks that `index`-th byte lies at the start and/or end of a
2161 /// UTF-8 code point sequence.
2163 /// The start and end of the string (when `index == self.len()`) are
2164 /// considered to be
2167 /// Returns `false` if `index` is greater than `self.len()`.
2172 /// let s = "Löwe 老虎 Léopard";
2173 /// assert!(s.is_char_boundary(0));
2175 /// assert!(s.is_char_boundary(6));
2176 /// assert!(s.is_char_boundary(s.len()));
2178 /// // second byte of `ö`
2179 /// assert!(!s.is_char_boundary(2));
2181 /// // third byte of `老`
2182 /// assert!(!s.is_char_boundary(8));
2184 #[stable(feature = "is_char_boundary", since = "1.9.0")]
2186 pub fn is_char_boundary(&self, index: usize) -> bool {
2187 // 0 and len are always ok.
2188 // Test for 0 explicitly so that it can optimize out the check
2189 // easily and skip reading string data for that case.
2190 if index == 0 || index == self.len() { return true; }
2191 match self.as_bytes().get(index) {
2193 // This is bit magic equivalent to: b < 128 || b >= 192
2194 Some(&b) => (b as i8) >= -0x40,
2198 /// Converts a string slice to a byte slice. To convert the byte slice back
2199 /// into a string slice, use the [`str::from_utf8`] function.
2201 /// [`str::from_utf8`]: ./str/fn.from_utf8.html
2208 /// let bytes = "bors".as_bytes();
2209 /// assert_eq!(b"bors", bytes);
2211 #[stable(feature = "rust1", since = "1.0.0")]
2213 #[rustc_const_unstable(feature="const_str_as_bytes")]
2214 pub const fn as_bytes(&self) -> &[u8] {
2219 unsafe { Slices { str: self }.slice }
2222 /// Converts a mutable string slice to a mutable byte slice. To convert the
2223 /// mutable byte slice back into a mutable string slice, use the
2224 /// [`str::from_utf8_mut`] function.
2226 /// [`str::from_utf8_mut`]: ./str/fn.from_utf8_mut.html
2233 /// let mut s = String::from("Hello");
2234 /// let bytes = unsafe { s.as_bytes_mut() };
2236 /// assert_eq!(b"Hello", bytes);
2242 /// let mut s = String::from("🗻∈🌏");
2245 /// let bytes = s.as_bytes_mut();
2247 /// bytes[0] = 0xF0;
2248 /// bytes[1] = 0x9F;
2249 /// bytes[2] = 0x8D;
2250 /// bytes[3] = 0x94;
2253 /// assert_eq!("🍔∈🌏", s);
2255 #[stable(feature = "str_mut_extras", since = "1.20.0")]
2257 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
2258 &mut *(self as *mut str as *mut [u8])
2261 /// Converts a string slice to a raw pointer.
2263 /// As string slices are a slice of bytes, the raw pointer points to a
2264 /// [`u8`]. This pointer will be pointing to the first byte of the string
2267 /// [`u8`]: primitive.u8.html
2274 /// let s = "Hello";
2275 /// let ptr = s.as_ptr();
2277 #[stable(feature = "rust1", since = "1.0.0")]
2279 #[rustc_const_unstable(feature = "const_str_as_ptr")]
2280 pub const fn as_ptr(&self) -> *const u8 {
2281 self as *const str as *const u8
2284 /// Returns a subslice of `str`.
2286 /// This is the non-panicking alternative to indexing the `str`. Returns
2287 /// [`None`] whenever equivalent indexing operation would panic.
2289 /// [`None`]: option/enum.Option.html#variant.None
2294 /// let v = String::from("🗻∈🌏");
2296 /// assert_eq!(Some("🗻"), v.get(0..4));
2298 /// // indices not on UTF-8 sequence boundaries
2299 /// assert!(v.get(1..).is_none());
2300 /// assert!(v.get(..8).is_none());
2302 /// // out of bounds
2303 /// assert!(v.get(..42).is_none());
2305 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2307 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
2311 /// Returns a mutable subslice of `str`.
2313 /// This is the non-panicking alternative to indexing the `str`. Returns
2314 /// [`None`] whenever equivalent indexing operation would panic.
2316 /// [`None`]: option/enum.Option.html#variant.None
2321 /// let mut v = String::from("hello");
2322 /// // correct length
2323 /// assert!(v.get_mut(0..5).is_some());
2324 /// // out of bounds
2325 /// assert!(v.get_mut(..42).is_none());
2326 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
2328 /// assert_eq!("hello", v);
2330 /// let s = v.get_mut(0..2);
2331 /// let s = s.map(|s| {
2332 /// s.make_ascii_uppercase();
2335 /// assert_eq!(Some("HE"), s);
2337 /// assert_eq!("HEllo", v);
2339 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2341 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
2345 /// Returns a unchecked subslice of `str`.
2347 /// This is the unchecked alternative to indexing the `str`.
2351 /// Callers of this function are responsible that these preconditions are
2354 /// * The starting index must come before the ending index;
2355 /// * Indexes must be within bounds of the original slice;
2356 /// * Indexes must lie on UTF-8 sequence boundaries.
2358 /// Failing that, the returned string slice may reference invalid memory or
2359 /// violate the invariants communicated by the `str` type.
2366 /// assert_eq!("🗻", v.get_unchecked(0..4));
2367 /// assert_eq!("∈", v.get_unchecked(4..7));
2368 /// assert_eq!("🌏", v.get_unchecked(7..11));
2371 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2373 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
2374 i.get_unchecked(self)
2377 /// Returns a mutable, unchecked subslice of `str`.
2379 /// This is the unchecked alternative to indexing the `str`.
2383 /// Callers of this function are responsible that these preconditions are
2386 /// * The starting index must come before the ending index;
2387 /// * Indexes must be within bounds of the original slice;
2388 /// * Indexes must lie on UTF-8 sequence boundaries.
2390 /// Failing that, the returned string slice may reference invalid memory or
2391 /// violate the invariants communicated by the `str` type.
2396 /// let mut v = String::from("🗻∈🌏");
2398 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
2399 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
2400 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
2403 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2405 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
2406 i.get_unchecked_mut(self)
2409 /// Creates a string slice from another string slice, bypassing safety
2412 /// This is generally not recommended, use with caution! For a safe
2413 /// alternative see [`str`] and [`Index`].
2415 /// [`str`]: primitive.str.html
2416 /// [`Index`]: ops/trait.Index.html
2418 /// This new slice goes from `begin` to `end`, including `begin` but
2419 /// excluding `end`.
2421 /// To get a mutable string slice instead, see the
2422 /// [`slice_mut_unchecked`] method.
2424 /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
2428 /// Callers of this function are responsible that three preconditions are
2431 /// * `begin` must come before `end`.
2432 /// * `begin` and `end` must be byte positions within the string slice.
2433 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2440 /// let s = "Löwe 老虎 Léopard";
2443 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
2446 /// let s = "Hello, world!";
2449 /// assert_eq!("world", s.slice_unchecked(7, 12));
2452 #[stable(feature = "rust1", since = "1.0.0")]
2453 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked(begin..end)` instead")]
2455 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
2456 (begin..end).get_unchecked(self)
2459 /// Creates a string slice from another string slice, bypassing safety
2461 /// This is generally not recommended, use with caution! For a safe
2462 /// alternative see [`str`] and [`IndexMut`].
2464 /// [`str`]: primitive.str.html
2465 /// [`IndexMut`]: ops/trait.IndexMut.html
2467 /// This new slice goes from `begin` to `end`, including `begin` but
2468 /// excluding `end`.
2470 /// To get an immutable string slice instead, see the
2471 /// [`slice_unchecked`] method.
2473 /// [`slice_unchecked`]: #method.slice_unchecked
2477 /// Callers of this function are responsible that three preconditions are
2480 /// * `begin` must come before `end`.
2481 /// * `begin` and `end` must be byte positions within the string slice.
2482 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2483 #[stable(feature = "str_slice_mut", since = "1.5.0")]
2484 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked_mut(begin..end)` instead")]
2486 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
2487 (begin..end).get_unchecked_mut(self)
2490 /// Divide one string slice into two at an index.
2492 /// The argument, `mid`, should be a byte offset from the start of the
2493 /// string. It must also be on the boundary of a UTF-8 code point.
2495 /// The two slices returned go from the start of the string slice to `mid`,
2496 /// and from `mid` to the end of the string slice.
2498 /// To get mutable string slices instead, see the [`split_at_mut`]
2501 /// [`split_at_mut`]: #method.split_at_mut
2505 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2506 /// beyond the last code point of the string slice.
2513 /// let s = "Per Martin-Löf";
2515 /// let (first, last) = s.split_at(3);
2517 /// assert_eq!("Per", first);
2518 /// assert_eq!(" Martin-Löf", last);
2521 #[stable(feature = "str_split_at", since = "1.4.0")]
2522 pub fn split_at(&self, mid: usize) -> (&str, &str) {
2523 // is_char_boundary checks that the index is in [0, .len()]
2524 if self.is_char_boundary(mid) {
2526 (self.get_unchecked(0..mid),
2527 self.get_unchecked(mid..self.len()))
2530 slice_error_fail(self, 0, mid)
2534 /// Divide one mutable string slice into two at an index.
2536 /// The argument, `mid`, should be a byte offset from the start of the
2537 /// string. It must also be on the boundary of a UTF-8 code point.
2539 /// The two slices returned go from the start of the string slice to `mid`,
2540 /// and from `mid` to the end of the string slice.
2542 /// To get immutable string slices instead, see the [`split_at`] method.
2544 /// [`split_at`]: #method.split_at
2548 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2549 /// beyond the last code point of the string slice.
2556 /// let mut s = "Per Martin-Löf".to_string();
2558 /// let (first, last) = s.split_at_mut(3);
2559 /// first.make_ascii_uppercase();
2560 /// assert_eq!("PER", first);
2561 /// assert_eq!(" Martin-Löf", last);
2563 /// assert_eq!("PER Martin-Löf", s);
2566 #[stable(feature = "str_split_at", since = "1.4.0")]
2567 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
2568 // is_char_boundary checks that the index is in [0, .len()]
2569 if self.is_char_boundary(mid) {
2570 let len = self.len();
2571 let ptr = self.as_ptr() as *mut u8;
2573 (from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
2574 from_utf8_unchecked_mut(slice::from_raw_parts_mut(
2580 slice_error_fail(self, 0, mid)
2584 /// Returns an iterator over the [`char`]s of a string slice.
2586 /// As a string slice consists of valid UTF-8, we can iterate through a
2587 /// string slice by [`char`]. This method returns such an iterator.
2589 /// It's important to remember that [`char`] represents a Unicode Scalar
2590 /// Value, and may not match your idea of what a 'character' is. Iteration
2591 /// over grapheme clusters may be what you actually want.
2598 /// let word = "goodbye";
2600 /// let count = word.chars().count();
2601 /// assert_eq!(7, count);
2603 /// let mut chars = word.chars();
2605 /// assert_eq!(Some('g'), chars.next());
2606 /// assert_eq!(Some('o'), chars.next());
2607 /// assert_eq!(Some('o'), chars.next());
2608 /// assert_eq!(Some('d'), chars.next());
2609 /// assert_eq!(Some('b'), chars.next());
2610 /// assert_eq!(Some('y'), chars.next());
2611 /// assert_eq!(Some('e'), chars.next());
2613 /// assert_eq!(None, chars.next());
2616 /// Remember, [`char`]s may not match your human intuition about characters:
2621 /// let mut chars = y.chars();
2623 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
2624 /// assert_eq!(Some('\u{0306}'), chars.next());
2626 /// assert_eq!(None, chars.next());
2628 #[stable(feature = "rust1", since = "1.0.0")]
2630 pub fn chars(&self) -> Chars {
2631 Chars{iter: self.as_bytes().iter()}
2634 /// Returns an iterator over the [`char`]s of a string slice, and their
2637 /// As a string slice consists of valid UTF-8, we can iterate through a
2638 /// string slice by [`char`]. This method returns an iterator of both
2639 /// these [`char`]s, as well as their byte positions.
2641 /// The iterator yields tuples. The position is first, the [`char`] is
2649 /// let word = "goodbye";
2651 /// let count = word.char_indices().count();
2652 /// assert_eq!(7, count);
2654 /// let mut char_indices = word.char_indices();
2656 /// assert_eq!(Some((0, 'g')), char_indices.next());
2657 /// assert_eq!(Some((1, 'o')), char_indices.next());
2658 /// assert_eq!(Some((2, 'o')), char_indices.next());
2659 /// assert_eq!(Some((3, 'd')), char_indices.next());
2660 /// assert_eq!(Some((4, 'b')), char_indices.next());
2661 /// assert_eq!(Some((5, 'y')), char_indices.next());
2662 /// assert_eq!(Some((6, 'e')), char_indices.next());
2664 /// assert_eq!(None, char_indices.next());
2667 /// Remember, [`char`]s may not match your human intuition about characters:
2670 /// let yes = "y̆es";
2672 /// let mut char_indices = yes.char_indices();
2674 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
2675 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
2677 /// // note the 3 here - the last character took up two bytes
2678 /// assert_eq!(Some((3, 'e')), char_indices.next());
2679 /// assert_eq!(Some((4, 's')), char_indices.next());
2681 /// assert_eq!(None, char_indices.next());
2683 #[stable(feature = "rust1", since = "1.0.0")]
2685 pub fn char_indices(&self) -> CharIndices {
2686 CharIndices { front_offset: 0, iter: self.chars() }
2689 /// An iterator over the bytes of a string slice.
2691 /// As a string slice consists of a sequence of bytes, we can iterate
2692 /// through a string slice by byte. This method returns such an iterator.
2699 /// let mut bytes = "bors".bytes();
2701 /// assert_eq!(Some(b'b'), bytes.next());
2702 /// assert_eq!(Some(b'o'), bytes.next());
2703 /// assert_eq!(Some(b'r'), bytes.next());
2704 /// assert_eq!(Some(b's'), bytes.next());
2706 /// assert_eq!(None, bytes.next());
2708 #[stable(feature = "rust1", since = "1.0.0")]
2710 pub fn bytes(&self) -> Bytes {
2711 Bytes(self.as_bytes().iter().cloned())
2714 /// Split a string slice by whitespace.
2716 /// The iterator returned will return string slices that are sub-slices of
2717 /// the original string slice, separated by any amount of whitespace.
2719 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2720 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
2721 /// instead, use [`split_ascii_whitespace`].
2723 /// [`split_ascii_whitespace`]: #method.split_ascii_whitespace
2730 /// let mut iter = "A few words".split_whitespace();
2732 /// assert_eq!(Some("A"), iter.next());
2733 /// assert_eq!(Some("few"), iter.next());
2734 /// assert_eq!(Some("words"), iter.next());
2736 /// assert_eq!(None, iter.next());
2739 /// All kinds of whitespace are considered:
2742 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
2743 /// assert_eq!(Some("Mary"), iter.next());
2744 /// assert_eq!(Some("had"), iter.next());
2745 /// assert_eq!(Some("a"), iter.next());
2746 /// assert_eq!(Some("little"), iter.next());
2747 /// assert_eq!(Some("lamb"), iter.next());
2749 /// assert_eq!(None, iter.next());
2751 #[stable(feature = "split_whitespace", since = "1.1.0")]
2753 pub fn split_whitespace(&self) -> SplitWhitespace {
2754 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
2757 /// Split a string slice by ASCII whitespace.
2759 /// The iterator returned will return string slices that are sub-slices of
2760 /// the original string slice, separated by any amount of ASCII whitespace.
2762 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
2764 /// [`split_whitespace`]: #method.split_whitespace
2771 /// #![feature(split_ascii_whitespace)]
2772 /// let mut iter = "A few words".split_ascii_whitespace();
2774 /// assert_eq!(Some("A"), iter.next());
2775 /// assert_eq!(Some("few"), iter.next());
2776 /// assert_eq!(Some("words"), iter.next());
2778 /// assert_eq!(None, iter.next());
2781 /// All kinds of ASCII whitespace are considered:
2784 /// let mut iter = " Mary had\ta little \n\t lamb".split_whitespace();
2785 /// assert_eq!(Some("Mary"), iter.next());
2786 /// assert_eq!(Some("had"), iter.next());
2787 /// assert_eq!(Some("a"), iter.next());
2788 /// assert_eq!(Some("little"), iter.next());
2789 /// assert_eq!(Some("lamb"), iter.next());
2791 /// assert_eq!(None, iter.next());
2793 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
2795 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace {
2798 .split(IsAsciiWhitespace)
2800 .map(UnsafeBytesToStr);
2801 SplitAsciiWhitespace { inner }
2804 /// An iterator over the lines of a string, as string slices.
2806 /// Lines are ended with either a newline (`\n`) or a carriage return with
2807 /// a line feed (`\r\n`).
2809 /// The final line ending is optional.
2816 /// let text = "foo\r\nbar\n\nbaz\n";
2817 /// let mut lines = text.lines();
2819 /// assert_eq!(Some("foo"), lines.next());
2820 /// assert_eq!(Some("bar"), lines.next());
2821 /// assert_eq!(Some(""), lines.next());
2822 /// assert_eq!(Some("baz"), lines.next());
2824 /// assert_eq!(None, lines.next());
2827 /// The final line ending isn't required:
2830 /// let text = "foo\nbar\n\r\nbaz";
2831 /// let mut lines = text.lines();
2833 /// assert_eq!(Some("foo"), lines.next());
2834 /// assert_eq!(Some("bar"), lines.next());
2835 /// assert_eq!(Some(""), lines.next());
2836 /// assert_eq!(Some("baz"), lines.next());
2838 /// assert_eq!(None, lines.next());
2840 #[stable(feature = "rust1", since = "1.0.0")]
2842 pub fn lines(&self) -> Lines {
2843 Lines(self.split_terminator('\n').map(LinesAnyMap))
2846 /// An iterator over the lines of a string.
2847 #[stable(feature = "rust1", since = "1.0.0")]
2848 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
2850 #[allow(deprecated)]
2851 pub fn lines_any(&self) -> LinesAny {
2852 LinesAny(self.lines())
2855 /// Returns an iterator of `u16` over the string encoded as UTF-16.
2862 /// let text = "Zażółć gęślą jaźń";
2864 /// let utf8_len = text.len();
2865 /// let utf16_len = text.encode_utf16().count();
2867 /// assert!(utf16_len <= utf8_len);
2869 #[stable(feature = "encode_utf16", since = "1.8.0")]
2870 pub fn encode_utf16(&self) -> EncodeUtf16 {
2871 EncodeUtf16 { chars: self.chars(), extra: 0 }
2874 /// Returns `true` if the given pattern matches a sub-slice of
2875 /// this string slice.
2877 /// Returns `false` if it does not.
2884 /// let bananas = "bananas";
2886 /// assert!(bananas.contains("nana"));
2887 /// assert!(!bananas.contains("apples"));
2889 #[stable(feature = "rust1", since = "1.0.0")]
2891 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2892 pat.is_contained_in(self)
2895 /// Returns `true` if the given pattern matches a prefix of this
2898 /// Returns `false` if it does not.
2905 /// let bananas = "bananas";
2907 /// assert!(bananas.starts_with("bana"));
2908 /// assert!(!bananas.starts_with("nana"));
2910 #[stable(feature = "rust1", since = "1.0.0")]
2911 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2912 pat.is_prefix_of(self)
2915 /// Returns `true` if the given pattern matches a suffix of this
2918 /// Returns `false` if it does not.
2925 /// let bananas = "bananas";
2927 /// assert!(bananas.ends_with("anas"));
2928 /// assert!(!bananas.ends_with("nana"));
2930 #[stable(feature = "rust1", since = "1.0.0")]
2931 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
2932 where P::Searcher: ReverseSearcher<'a>
2934 pat.is_suffix_of(self)
2937 /// Returns the byte index of the first character of this string slice that
2938 /// matches the pattern.
2940 /// Returns [`None`] if the pattern doesn't match.
2942 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2943 /// a character matches.
2945 /// [`None`]: option/enum.Option.html#variant.None
2949 /// Simple patterns:
2952 /// let s = "Löwe 老虎 Léopard";
2954 /// assert_eq!(s.find('L'), Some(0));
2955 /// assert_eq!(s.find('é'), Some(14));
2956 /// assert_eq!(s.find("Léopard"), Some(13));
2959 /// More complex patterns using point-free style and closures:
2962 /// let s = "Löwe 老虎 Léopard";
2964 /// assert_eq!(s.find(char::is_whitespace), Some(5));
2965 /// assert_eq!(s.find(char::is_lowercase), Some(1));
2966 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
2967 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
2970 /// Not finding the pattern:
2973 /// let s = "Löwe 老虎 Léopard";
2974 /// let x: &[_] = &['1', '2'];
2976 /// assert_eq!(s.find(x), None);
2978 #[stable(feature = "rust1", since = "1.0.0")]
2980 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2981 pat.into_searcher(self).next_match().map(|(i, _)| i)
2984 /// Returns the byte index of the last character of this string slice that
2985 /// matches the pattern.
2987 /// Returns [`None`] if the pattern doesn't match.
2989 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2990 /// a character matches.
2992 /// [`None`]: option/enum.Option.html#variant.None
2996 /// Simple patterns:
2999 /// let s = "Löwe 老虎 Léopard";
3001 /// assert_eq!(s.rfind('L'), Some(13));
3002 /// assert_eq!(s.rfind('é'), Some(14));
3005 /// More complex patterns with closures:
3008 /// let s = "Löwe 老虎 Léopard";
3010 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
3011 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
3014 /// Not finding the pattern:
3017 /// let s = "Löwe 老虎 Léopard";
3018 /// let x: &[_] = &['1', '2'];
3020 /// assert_eq!(s.rfind(x), None);
3022 #[stable(feature = "rust1", since = "1.0.0")]
3024 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
3025 where P::Searcher: ReverseSearcher<'a>
3027 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
3030 /// An iterator over substrings of this string slice, separated by
3031 /// characters matched by a pattern.
3033 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3036 /// # Iterator behavior
3038 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3039 /// allows a reverse search and forward/reverse search yields the same
3040 /// elements. This is true for, eg, [`char`] but not for `&str`.
3042 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3044 /// If the pattern allows a reverse search but its results might differ
3045 /// from a forward search, the [`rsplit`] method can be used.
3047 /// [`rsplit`]: #method.rsplit
3051 /// Simple patterns:
3054 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
3055 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
3057 /// let v: Vec<&str> = "".split('X').collect();
3058 /// assert_eq!(v, [""]);
3060 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
3061 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
3063 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
3064 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3066 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
3067 /// assert_eq!(v, ["abc", "def", "ghi"]);
3069 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
3070 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3073 /// A more complex pattern, using a closure:
3076 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
3077 /// assert_eq!(v, ["abc", "def", "ghi"]);
3080 /// If a string contains multiple contiguous separators, you will end up
3081 /// with empty strings in the output:
3084 /// let x = "||||a||b|c".to_string();
3085 /// let d: Vec<_> = x.split('|').collect();
3087 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3090 /// Contiguous separators are separated by the empty string.
3093 /// let x = "(///)".to_string();
3094 /// let d: Vec<_> = x.split('/').collect();
3096 /// assert_eq!(d, &["(", "", "", ")"]);
3099 /// Separators at the start or end of a string are neighbored
3100 /// by empty strings.
3103 /// let d: Vec<_> = "010".split("0").collect();
3104 /// assert_eq!(d, &["", "1", ""]);
3107 /// When the empty string is used as a separator, it separates
3108 /// every character in the string, along with the beginning
3109 /// and end of the string.
3112 /// let f: Vec<_> = "rust".split("").collect();
3113 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
3116 /// Contiguous separators can lead to possibly surprising behavior
3117 /// when whitespace is used as the separator. This code is correct:
3120 /// let x = " a b c".to_string();
3121 /// let d: Vec<_> = x.split(' ').collect();
3123 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3126 /// It does _not_ give you:
3129 /// assert_eq!(d, &["a", "b", "c"]);
3132 /// Use [`split_whitespace`] for this behavior.
3134 /// [`split_whitespace`]: #method.split_whitespace
3135 #[stable(feature = "rust1", since = "1.0.0")]
3137 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
3138 Split(SplitInternal {
3141 matcher: pat.into_searcher(self),
3142 allow_trailing_empty: true,
3147 /// An iterator over substrings of the given string slice, separated by
3148 /// characters matched by a pattern and yielded in reverse order.
3150 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3153 /// # Iterator behavior
3155 /// The returned iterator requires that the pattern supports a reverse
3156 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3157 /// search yields the same elements.
3159 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3161 /// For iterating from the front, the [`split`] method can be used.
3163 /// [`split`]: #method.split
3167 /// Simple patterns:
3170 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
3171 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
3173 /// let v: Vec<&str> = "".rsplit('X').collect();
3174 /// assert_eq!(v, [""]);
3176 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
3177 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
3179 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
3180 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
3183 /// A more complex pattern, using a closure:
3186 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
3187 /// assert_eq!(v, ["ghi", "def", "abc"]);
3189 #[stable(feature = "rust1", since = "1.0.0")]
3191 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
3192 where P::Searcher: ReverseSearcher<'a>
3194 RSplit(self.split(pat).0)
3197 /// An iterator over substrings of the given string slice, separated by
3198 /// characters matched by a pattern.
3200 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3203 /// Equivalent to [`split`], except that the trailing substring
3204 /// is skipped if empty.
3206 /// [`split`]: #method.split
3208 /// This method can be used for string data that is _terminated_,
3209 /// rather than _separated_ by a pattern.
3211 /// # Iterator behavior
3213 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3214 /// allows a reverse search and forward/reverse search yields the same
3215 /// elements. This is true for, eg, [`char`] but not for `&str`.
3217 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3219 /// If the pattern allows a reverse search but its results might differ
3220 /// from a forward search, the [`rsplit_terminator`] method can be used.
3222 /// [`rsplit_terminator`]: #method.rsplit_terminator
3229 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
3230 /// assert_eq!(v, ["A", "B"]);
3232 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
3233 /// assert_eq!(v, ["A", "", "B", ""]);
3235 #[stable(feature = "rust1", since = "1.0.0")]
3237 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
3238 SplitTerminator(SplitInternal {
3239 allow_trailing_empty: false,
3244 /// An iterator over substrings of `self`, separated by characters
3245 /// matched by a pattern and yielded in reverse order.
3247 /// The pattern can be a simple `&str`, [`char`], or a closure that
3248 /// determines the split.
3249 /// Additional libraries might provide more complex patterns like
3250 /// regular expressions.
3252 /// Equivalent to [`split`], except that the trailing substring is
3253 /// skipped if empty.
3255 /// [`split`]: #method.split
3257 /// This method can be used for string data that is _terminated_,
3258 /// rather than _separated_ by a pattern.
3260 /// # Iterator behavior
3262 /// The returned iterator requires that the pattern supports a
3263 /// reverse search, and it will be double ended if a forward/reverse
3264 /// search yields the same elements.
3266 /// For iterating from the front, the [`split_terminator`] method can be
3269 /// [`split_terminator`]: #method.split_terminator
3274 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
3275 /// assert_eq!(v, ["B", "A"]);
3277 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
3278 /// assert_eq!(v, ["", "B", "", "A"]);
3280 #[stable(feature = "rust1", since = "1.0.0")]
3282 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
3283 where P::Searcher: ReverseSearcher<'a>
3285 RSplitTerminator(self.split_terminator(pat).0)
3288 /// An iterator over substrings of the given string slice, separated by a
3289 /// pattern, restricted to returning at most `n` items.
3291 /// If `n` substrings are returned, the last substring (the `n`th substring)
3292 /// will contain the remainder of the string.
3294 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3297 /// # Iterator behavior
3299 /// The returned iterator will not be double ended, because it is
3300 /// not efficient to support.
3302 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
3305 /// [`rsplitn`]: #method.rsplitn
3309 /// Simple patterns:
3312 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
3313 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
3315 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
3316 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
3318 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
3319 /// assert_eq!(v, ["abcXdef"]);
3321 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
3322 /// assert_eq!(v, [""]);
3325 /// A more complex pattern, using a closure:
3328 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
3329 /// assert_eq!(v, ["abc", "defXghi"]);
3331 #[stable(feature = "rust1", since = "1.0.0")]
3333 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
3334 SplitN(SplitNInternal {
3335 iter: self.split(pat).0,
3340 /// An iterator over substrings of this string slice, separated by a
3341 /// pattern, starting from the end of the string, restricted to returning
3342 /// at most `n` items.
3344 /// If `n` substrings are returned, the last substring (the `n`th substring)
3345 /// will contain the remainder of the string.
3347 /// The pattern can be a `&str`, [`char`], or a closure that
3348 /// determines the split.
3350 /// # Iterator behavior
3352 /// The returned iterator will not be double ended, because it is not
3353 /// efficient to support.
3355 /// For splitting from the front, the [`splitn`] method can be used.
3357 /// [`splitn`]: #method.splitn
3361 /// Simple patterns:
3364 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
3365 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
3367 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
3368 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
3370 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
3371 /// assert_eq!(v, ["leopard", "lion::tiger"]);
3374 /// A more complex pattern, using a closure:
3377 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
3378 /// assert_eq!(v, ["ghi", "abc1def"]);
3380 #[stable(feature = "rust1", since = "1.0.0")]
3382 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
3383 where P::Searcher: ReverseSearcher<'a>
3385 RSplitN(self.splitn(n, pat).0)
3388 /// An iterator over the disjoint matches of a pattern within the given string
3391 /// The pattern can be a `&str`, [`char`], or a closure that
3392 /// determines if a character matches.
3394 /// # Iterator behavior
3396 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3397 /// allows a reverse search and forward/reverse search yields the same
3398 /// elements. This is true for, eg, [`char`] but not for `&str`.
3400 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3402 /// If the pattern allows a reverse search but its results might differ
3403 /// from a forward search, the [`rmatches`] method can be used.
3405 /// [`rmatches`]: #method.rmatches
3412 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
3413 /// assert_eq!(v, ["abc", "abc", "abc"]);
3415 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
3416 /// assert_eq!(v, ["1", "2", "3"]);
3418 #[stable(feature = "str_matches", since = "1.2.0")]
3420 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
3421 Matches(MatchesInternal(pat.into_searcher(self)))
3424 /// An iterator over the disjoint matches of a pattern within this string slice,
3425 /// yielded in reverse order.
3427 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3428 /// a character matches.
3430 /// # Iterator behavior
3432 /// The returned iterator requires that the pattern supports a reverse
3433 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3434 /// search yields the same elements.
3436 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3438 /// For iterating from the front, the [`matches`] method can be used.
3440 /// [`matches`]: #method.matches
3447 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
3448 /// assert_eq!(v, ["abc", "abc", "abc"]);
3450 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
3451 /// assert_eq!(v, ["3", "2", "1"]);
3453 #[stable(feature = "str_matches", since = "1.2.0")]
3455 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
3456 where P::Searcher: ReverseSearcher<'a>
3458 RMatches(self.matches(pat).0)
3461 /// An iterator over the disjoint matches of a pattern within this string
3462 /// slice as well as the index that the match starts at.
3464 /// For matches of `pat` within `self` that overlap, only the indices
3465 /// corresponding to the first match are returned.
3467 /// The pattern can be a `&str`, [`char`], or a closure that determines
3468 /// if a character matches.
3470 /// # Iterator behavior
3472 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3473 /// allows a reverse search and forward/reverse search yields the same
3474 /// elements. This is true for, eg, [`char`] but not for `&str`.
3476 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3478 /// If the pattern allows a reverse search but its results might differ
3479 /// from a forward search, the [`rmatch_indices`] method can be used.
3481 /// [`rmatch_indices`]: #method.rmatch_indices
3488 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
3489 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
3491 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
3492 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
3494 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
3495 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
3497 #[stable(feature = "str_match_indices", since = "1.5.0")]
3499 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
3500 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
3503 /// An iterator over the disjoint matches of a pattern within `self`,
3504 /// yielded in reverse order along with the index of the match.
3506 /// For matches of `pat` within `self` that overlap, only the indices
3507 /// corresponding to the last match are returned.
3509 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
3510 /// character matches.
3512 /// # Iterator behavior
3514 /// The returned iterator requires that the pattern supports a reverse
3515 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3516 /// search yields the same elements.
3518 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3520 /// For iterating from the front, the [`match_indices`] method can be used.
3522 /// [`match_indices`]: #method.match_indices
3529 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
3530 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
3532 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
3533 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
3535 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
3536 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
3538 #[stable(feature = "str_match_indices", since = "1.5.0")]
3540 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
3541 where P::Searcher: ReverseSearcher<'a>
3543 RMatchIndices(self.match_indices(pat).0)
3546 /// Returns a string slice with leading and trailing whitespace removed.
3548 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3549 /// Core Property `White_Space`.
3556 /// let s = " Hello\tworld\t";
3558 /// assert_eq!("Hello\tworld", s.trim());
3560 #[stable(feature = "rust1", since = "1.0.0")]
3561 pub fn trim(&self) -> &str {
3562 self.trim_matches(|c: char| c.is_whitespace())
3565 /// Returns a string slice with leading whitespace removed.
3567 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3568 /// Core Property `White_Space`.
3570 /// # Text directionality
3572 /// A string is a sequence of bytes. `start` in this context means the first
3573 /// position of that byte string; for a left-to-right language like English or
3574 /// Russian, this will be left side; and for right-to-left languages like
3575 /// like Arabic or Hebrew, this will be the right side.
3582 /// let s = " Hello\tworld\t";
3583 /// assert_eq!("Hello\tworld\t", s.trim_start());
3589 /// let s = " English ";
3590 /// assert!(Some('E') == s.trim_start().chars().next());
3592 /// let s = " עברית ";
3593 /// assert!(Some('ע') == s.trim_start().chars().next());
3595 #[stable(feature = "trim_direction", since = "1.30.0")]
3596 pub fn trim_start(&self) -> &str {
3597 self.trim_start_matches(|c: char| c.is_whitespace())
3600 /// Returns a string slice with trailing whitespace removed.
3602 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3603 /// Core Property `White_Space`.
3605 /// # Text directionality
3607 /// A string is a sequence of bytes. `end` in this context means the last
3608 /// position of that byte string; for a left-to-right language like English or
3609 /// Russian, this will be right side; and for right-to-left languages like
3610 /// like Arabic or Hebrew, this will be the left side.
3617 /// let s = " Hello\tworld\t";
3618 /// assert_eq!(" Hello\tworld", s.trim_end());
3624 /// let s = " English ";
3625 /// assert!(Some('h') == s.trim_end().chars().rev().next());
3627 /// let s = " עברית ";
3628 /// assert!(Some('ת') == s.trim_end().chars().rev().next());
3630 #[stable(feature = "trim_direction", since = "1.30.0")]
3631 pub fn trim_end(&self) -> &str {
3632 self.trim_end_matches(|c: char| c.is_whitespace())
3635 /// Returns a string slice with leading whitespace removed.
3637 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3638 /// Core Property `White_Space`.
3640 /// # Text directionality
3642 /// A string is a sequence of bytes. 'Left' in this context means the first
3643 /// position of that byte string; for a language like Arabic or Hebrew
3644 /// which are 'right to left' rather than 'left to right', this will be
3645 /// the _right_ side, not the left.
3652 /// let s = " Hello\tworld\t";
3654 /// assert_eq!("Hello\tworld\t", s.trim_left());
3660 /// let s = " English";
3661 /// assert!(Some('E') == s.trim_left().chars().next());
3663 /// let s = " עברית";
3664 /// assert!(Some('ע') == s.trim_left().chars().next());
3666 #[stable(feature = "rust1", since = "1.0.0")]
3667 #[rustc_deprecated(reason = "superseded by `trim_start`", since = "1.33.0")]
3668 pub fn trim_left(&self) -> &str {
3672 /// Returns a string slice with trailing whitespace removed.
3674 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3675 /// Core Property `White_Space`.
3677 /// # Text directionality
3679 /// A string is a sequence of bytes. 'Right' in this context means the last
3680 /// position of that byte string; for a language like Arabic or Hebrew
3681 /// which are 'right to left' rather than 'left to right', this will be
3682 /// the _left_ side, not the right.
3689 /// let s = " Hello\tworld\t";
3691 /// assert_eq!(" Hello\tworld", s.trim_right());
3697 /// let s = "English ";
3698 /// assert!(Some('h') == s.trim_right().chars().rev().next());
3700 /// let s = "עברית ";
3701 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
3703 #[stable(feature = "rust1", since = "1.0.0")]
3704 #[rustc_deprecated(reason = "superseded by `trim_end`", since = "1.33.0")]
3705 pub fn trim_right(&self) -> &str {
3709 /// Returns a string slice with all prefixes and suffixes that match a
3710 /// pattern repeatedly removed.
3712 /// The pattern can be a [`char`] or a closure that determines if a
3713 /// character matches.
3717 /// Simple patterns:
3720 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
3721 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
3723 /// let x: &[_] = &['1', '2'];
3724 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
3727 /// A more complex pattern, using a closure:
3730 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
3732 #[stable(feature = "rust1", since = "1.0.0")]
3733 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3734 where P::Searcher: DoubleEndedSearcher<'a>
3738 let mut matcher = pat.into_searcher(self);
3739 if let Some((a, b)) = matcher.next_reject() {
3741 j = b; // Remember earliest known match, correct it below if
3742 // last match is different
3744 if let Some((_, b)) = matcher.next_reject_back() {
3748 // Searcher is known to return valid indices
3749 self.get_unchecked(i..j)
3753 /// Returns a string slice with all prefixes that match a pattern
3754 /// repeatedly removed.
3756 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3757 /// a character matches.
3759 /// # Text directionality
3761 /// A string is a sequence of bytes. 'Left' in this context means the first
3762 /// position of that byte string; for a language like Arabic or Hebrew
3763 /// which are 'right to left' rather than 'left to right', this will be
3764 /// the _right_ side, not the left.
3771 /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
3772 /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
3774 /// let x: &[_] = &['1', '2'];
3775 /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
3777 #[stable(feature = "trim_direction", since = "1.30.0")]
3778 pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3779 let mut i = self.len();
3780 let mut matcher = pat.into_searcher(self);
3781 if let Some((a, _)) = matcher.next_reject() {
3785 // Searcher is known to return valid indices
3786 self.get_unchecked(i..self.len())
3790 /// Returns a string slice with all suffixes that match a pattern
3791 /// repeatedly removed.
3793 /// The pattern can be a `&str`, [`char`], or a closure that
3794 /// determines if a character matches.
3796 /// # Text directionality
3798 /// A string is a sequence of bytes. 'Right' in this context means the last
3799 /// position of that byte string; for a language like Arabic or Hebrew
3800 /// which are 'right to left' rather than 'left to right', this will be
3801 /// the _left_ side, not the right.
3805 /// Simple patterns:
3808 /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
3809 /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
3811 /// let x: &[_] = &['1', '2'];
3812 /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
3815 /// A more complex pattern, using a closure:
3818 /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
3820 #[stable(feature = "trim_direction", since = "1.30.0")]
3821 pub fn trim_end_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3822 where P::Searcher: ReverseSearcher<'a>
3825 let mut matcher = pat.into_searcher(self);
3826 if let Some((_, b)) = matcher.next_reject_back() {
3830 // Searcher is known to return valid indices
3831 self.get_unchecked(0..j)
3835 /// Returns a string slice with all prefixes that match a pattern
3836 /// repeatedly removed.
3838 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3839 /// a character matches.
3841 /// [`char`]: primitive.char.html
3843 /// # Text directionality
3845 /// A string is a sequence of bytes. 'Left' in this context means the first
3846 /// position of that byte string; for a language like Arabic or Hebrew
3847 /// which are 'right to left' rather than 'left to right', this will be
3848 /// the _right_ side, not the left.
3855 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
3856 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
3858 /// let x: &[_] = &['1', '2'];
3859 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
3861 #[stable(feature = "rust1", since = "1.0.0")]
3862 #[rustc_deprecated(reason = "superseded by `trim_start_matches`", since = "1.33.0")]
3863 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3864 self.trim_start_matches(pat)
3867 /// Returns a string slice with all suffixes that match a pattern
3868 /// repeatedly removed.
3870 /// The pattern can be a `&str`, [`char`], or a closure that
3871 /// determines if a character matches.
3873 /// [`char`]: primitive.char.html
3875 /// # Text directionality
3877 /// A string is a sequence of bytes. 'Right' in this context means the last
3878 /// position of that byte string; for a language like Arabic or Hebrew
3879 /// which are 'right to left' rather than 'left to right', this will be
3880 /// the _left_ side, not the right.
3884 /// Simple patterns:
3887 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
3888 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
3890 /// let x: &[_] = &['1', '2'];
3891 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
3894 /// A more complex pattern, using a closure:
3897 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
3899 #[stable(feature = "rust1", since = "1.0.0")]
3900 #[rustc_deprecated(reason = "superseded by `trim_end_matches`", since = "1.33.0")]
3901 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3902 where P::Searcher: ReverseSearcher<'a>
3904 self.trim_end_matches(pat)
3907 /// Parses this string slice into another type.
3909 /// Because `parse` is so general, it can cause problems with type
3910 /// inference. As such, `parse` is one of the few times you'll see
3911 /// the syntax affectionately known as the 'turbofish': `::<>`. This
3912 /// helps the inference algorithm understand specifically which type
3913 /// you're trying to parse into.
3915 /// `parse` can parse any type that implements the [`FromStr`] trait.
3917 /// [`FromStr`]: str/trait.FromStr.html
3921 /// Will return [`Err`] if it's not possible to parse this string slice into
3922 /// the desired type.
3924 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
3931 /// let four: u32 = "4".parse().unwrap();
3933 /// assert_eq!(4, four);
3936 /// Using the 'turbofish' instead of annotating `four`:
3939 /// let four = "4".parse::<u32>();
3941 /// assert_eq!(Ok(4), four);
3944 /// Failing to parse:
3947 /// let nope = "j".parse::<u32>();
3949 /// assert!(nope.is_err());
3952 #[stable(feature = "rust1", since = "1.0.0")]
3953 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
3954 FromStr::from_str(self)
3957 /// Checks if all characters in this string are within the ASCII range.
3962 /// let ascii = "hello!\n";
3963 /// let non_ascii = "Grüße, Jürgen ❤";
3965 /// assert!(ascii.is_ascii());
3966 /// assert!(!non_ascii.is_ascii());
3968 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3970 pub fn is_ascii(&self) -> bool {
3971 // We can treat each byte as character here: all multibyte characters
3972 // start with a byte that is not in the ascii range, so we will stop
3974 self.bytes().all(|b| b.is_ascii())
3977 /// Checks that two strings are an ASCII case-insensitive match.
3979 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
3980 /// but without allocating and copying temporaries.
3985 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
3986 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
3987 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
3989 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3991 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
3992 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
3995 /// Converts this string to its ASCII upper case equivalent in-place.
3997 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3998 /// but non-ASCII letters are unchanged.
4000 /// To return a new uppercased value without modifying the existing one, use
4001 /// [`to_ascii_uppercase`].
4003 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4004 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4005 pub fn make_ascii_uppercase(&mut self) {
4006 let me = unsafe { self.as_bytes_mut() };
4007 me.make_ascii_uppercase()
4010 /// Converts this string to its ASCII lower case equivalent in-place.
4012 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4013 /// but non-ASCII letters are unchanged.
4015 /// To return a new lowercased value without modifying the existing one, use
4016 /// [`to_ascii_lowercase`].
4018 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4019 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4020 pub fn make_ascii_lowercase(&mut self) {
4021 let me = unsafe { self.as_bytes_mut() };
4022 me.make_ascii_lowercase()
4026 #[stable(feature = "rust1", since = "1.0.0")]
4027 impl AsRef<[u8]> for str {
4029 fn as_ref(&self) -> &[u8] {
4034 #[stable(feature = "rust1", since = "1.0.0")]
4035 impl Default for &str {
4036 /// Creates an empty str
4037 fn default() -> Self { "" }
4040 #[stable(feature = "default_mut_str", since = "1.28.0")]
4041 impl Default for &mut str {
4042 /// Creates an empty mutable str
4043 fn default() -> Self { unsafe { from_utf8_unchecked_mut(&mut []) } }
4046 /// An iterator over the non-whitespace substrings of a string,
4047 /// separated by any amount of whitespace.
4049 /// This struct is created by the [`split_whitespace`] method on [`str`].
4050 /// See its documentation for more.
4052 /// [`split_whitespace`]: ../../std/primitive.str.html#method.split_whitespace
4053 /// [`str`]: ../../std/primitive.str.html
4054 #[stable(feature = "split_whitespace", since = "1.1.0")]
4055 #[derive(Clone, Debug)]
4056 pub struct SplitWhitespace<'a> {
4057 inner: Filter<Split<'a, IsWhitespace>, IsNotEmpty>,
4060 /// An iterator over the non-ASCII-whitespace substrings of a string,
4061 /// separated by any amount of ASCII whitespace.
4063 /// This struct is created by the [`split_ascii_whitespace`] method on [`str`].
4064 /// See its documentation for more.
4066 /// [`split_ascii_whitespace`]: ../../std/primitive.str.html#method.split_ascii_whitespace
4067 /// [`str`]: ../../std/primitive.str.html
4068 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
4069 #[derive(Clone, Debug)]
4070 pub struct SplitAsciiWhitespace<'a> {
4071 inner: Map<Filter<SliceSplit<'a, u8, IsAsciiWhitespace>, IsNotEmpty>, UnsafeBytesToStr>,
4075 struct IsWhitespace;
4077 impl FnOnce<(char, )> for IsWhitespace {
4081 extern "rust-call" fn call_once(mut self, arg: (char, )) -> bool {
4086 impl FnMut<(char, )> for IsWhitespace {
4088 extern "rust-call" fn call_mut(&mut self, arg: (char, )) -> bool {
4089 arg.0.is_whitespace()
4094 struct IsAsciiWhitespace;
4096 impl<'a> FnOnce<(&'a u8, )> for IsAsciiWhitespace {
4100 extern "rust-call" fn call_once(mut self, arg: (&u8, )) -> bool {
4105 impl<'a> FnMut<(&'a u8, )> for IsAsciiWhitespace {
4107 extern "rust-call" fn call_mut(&mut self, arg: (&u8, )) -> bool {
4108 arg.0.is_ascii_whitespace()
4115 impl<'a, 'b> FnOnce<(&'a &'b str, )> for IsNotEmpty {
4119 extern "rust-call" fn call_once(mut self, arg: (&'a &'b str, )) -> bool {
4124 impl<'a, 'b> FnMut<(&'a &'b str, )> for IsNotEmpty {
4126 extern "rust-call" fn call_mut(&mut self, arg: (&'a &'b str, )) -> bool {
4131 impl<'a, 'b> FnOnce<(&'a &'b [u8], )> for IsNotEmpty {
4135 extern "rust-call" fn call_once(mut self, arg: (&'a &'b [u8], )) -> bool {
4140 impl<'a, 'b> FnMut<(&'a &'b [u8], )> for IsNotEmpty {
4142 extern "rust-call" fn call_mut(&mut self, arg: (&'a &'b [u8], )) -> bool {
4148 struct UnsafeBytesToStr;
4150 impl<'a> FnOnce<(&'a [u8], )> for UnsafeBytesToStr {
4151 type Output = &'a str;
4154 extern "rust-call" fn call_once(mut self, arg: (&'a [u8], )) -> &'a str {
4159 impl<'a> FnMut<(&'a [u8], )> for UnsafeBytesToStr {
4161 extern "rust-call" fn call_mut(&mut self, arg: (&'a [u8], )) -> &'a str {
4162 unsafe { from_utf8_unchecked(arg.0) }
4167 #[stable(feature = "split_whitespace", since = "1.1.0")]
4168 impl<'a> Iterator for SplitWhitespace<'a> {
4169 type Item = &'a str;
4172 fn next(&mut self) -> Option<&'a str> {
4177 fn size_hint(&self) -> (usize, Option<usize>) {
4178 self.inner.size_hint()
4182 #[stable(feature = "split_whitespace", since = "1.1.0")]
4183 impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
4185 fn next_back(&mut self) -> Option<&'a str> {
4186 self.inner.next_back()
4190 #[stable(feature = "fused", since = "1.26.0")]
4191 impl FusedIterator for SplitWhitespace<'_> {}
4193 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
4194 impl<'a> Iterator for SplitAsciiWhitespace<'a> {
4195 type Item = &'a str;
4198 fn next(&mut self) -> Option<&'a str> {
4203 fn size_hint(&self) -> (usize, Option<usize>) {
4204 self.inner.size_hint()
4208 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
4209 impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> {
4211 fn next_back(&mut self) -> Option<&'a str> {
4212 self.inner.next_back()
4216 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
4217 impl FusedIterator for SplitAsciiWhitespace<'_> {}
4219 /// An iterator of [`u16`] over the string encoded as UTF-16.
4221 /// [`u16`]: ../../std/primitive.u16.html
4223 /// This struct is created by the [`encode_utf16`] method on [`str`].
4224 /// See its documentation for more.
4226 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
4227 /// [`str`]: ../../std/primitive.str.html
4229 #[stable(feature = "encode_utf16", since = "1.8.0")]
4230 pub struct EncodeUtf16<'a> {
4235 #[stable(feature = "collection_debug", since = "1.17.0")]
4236 impl fmt::Debug for EncodeUtf16<'_> {
4237 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4238 f.pad("EncodeUtf16 { .. }")
4242 #[stable(feature = "encode_utf16", since = "1.8.0")]
4243 impl<'a> Iterator for EncodeUtf16<'a> {
4247 fn next(&mut self) -> Option<u16> {
4248 if self.extra != 0 {
4249 let tmp = self.extra;
4254 let mut buf = [0; 2];
4255 self.chars.next().map(|ch| {
4256 let n = ch.encode_utf16(&mut buf).len();
4258 self.extra = buf[1];
4265 fn size_hint(&self) -> (usize, Option<usize>) {
4266 let (low, high) = self.chars.size_hint();
4267 // every char gets either one u16 or two u16,
4268 // so this iterator is between 1 or 2 times as
4269 // long as the underlying iterator.
4270 (low, high.and_then(|n| n.checked_mul(2)))
4274 #[stable(feature = "fused", since = "1.26.0")]
4275 impl FusedIterator for EncodeUtf16<'_> {}