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) in case of lossy decoding.
248 #[stable(feature = "utf8_error_error_len", since = "1.20.0")]
249 pub fn error_len(&self) -> Option<usize> {
250 self.error_len.map(|len| len as usize)
254 /// Converts a slice of bytes to a string slice.
256 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
257 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
258 /// the two. Not all byte slices are valid string slices, however: [`&str`] requires
259 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
260 /// UTF-8, and then does the conversion.
262 /// [`&str`]: ../../std/primitive.str.html
263 /// [`u8`]: ../../std/primitive.u8.html
264 /// [byteslice]: ../../std/primitive.slice.html
266 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
267 /// incur the overhead of the validity check, there is an unsafe version of
268 /// this function, [`from_utf8_unchecked`][fromutf8u], which has the same
269 /// behavior but skips the check.
271 /// [fromutf8u]: fn.from_utf8_unchecked.html
273 /// If you need a `String` instead of a `&str`, consider
274 /// [`String::from_utf8`][string].
276 /// [string]: ../../std/string/struct.String.html#method.from_utf8
278 /// Because you can stack-allocate a `[u8; N]`, and you can take a
279 /// [`&[u8]`][byteslice] of it, this function is one way to have a
280 /// stack-allocated string. There is an example of this in the
281 /// examples section below.
283 /// [byteslice]: ../../std/primitive.slice.html
287 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
288 /// provided slice is not UTF-8.
297 /// // some bytes, in a vector
298 /// let sparkle_heart = vec![240, 159, 146, 150];
300 /// // We know these bytes are valid, so just use `unwrap()`.
301 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
303 /// assert_eq!("💖", sparkle_heart);
311 /// // some invalid bytes, in a vector
312 /// let sparkle_heart = vec![0, 159, 146, 150];
314 /// assert!(str::from_utf8(&sparkle_heart).is_err());
317 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
318 /// errors that can be returned.
320 /// [error]: struct.Utf8Error.html
322 /// A "stack allocated string":
327 /// // some bytes, in a stack-allocated array
328 /// let sparkle_heart = [240, 159, 146, 150];
330 /// // We know these bytes are valid, so just use `unwrap()`.
331 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
333 /// assert_eq!("💖", sparkle_heart);
335 #[stable(feature = "rust1", since = "1.0.0")]
336 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
337 run_utf8_validation(v)?;
338 Ok(unsafe { from_utf8_unchecked(v) })
341 /// Converts a mutable slice of bytes to a mutable string slice.
350 /// // "Hello, Rust!" as a mutable vector
351 /// let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
353 /// // As we know these bytes are valid, we can use `unwrap()`
354 /// let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
356 /// assert_eq!("Hello, Rust!", outstr);
364 /// // Some invalid bytes in a mutable vector
365 /// let mut invalid = vec![128, 223];
367 /// assert!(str::from_utf8_mut(&mut invalid).is_err());
369 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
370 /// errors that can be returned.
372 /// [error]: struct.Utf8Error.html
373 #[stable(feature = "str_mut_extras", since = "1.20.0")]
374 pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
375 run_utf8_validation(v)?;
376 Ok(unsafe { from_utf8_unchecked_mut(v) })
379 /// Converts a slice of bytes to a string slice without checking
380 /// that the string contains valid UTF-8.
382 /// See the safe version, [`from_utf8`][fromutf8], for more information.
384 /// [fromutf8]: fn.from_utf8.html
388 /// This function is unsafe because it does not check that the bytes passed to
389 /// it are valid UTF-8. If this constraint is violated, undefined behavior
390 /// results, as the rest of Rust assumes that [`&str`]s are valid UTF-8.
392 /// [`&str`]: ../../std/primitive.str.html
401 /// // some bytes, in a vector
402 /// let sparkle_heart = vec![240, 159, 146, 150];
404 /// let sparkle_heart = unsafe {
405 /// str::from_utf8_unchecked(&sparkle_heart)
408 /// assert_eq!("💖", sparkle_heart);
411 #[stable(feature = "rust1", since = "1.0.0")]
412 pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
413 &*(v as *const [u8] as *const str)
416 /// Converts a slice of bytes to a string slice without checking
417 /// that the string contains valid UTF-8; mutable version.
419 /// See the immutable version, [`from_utf8_unchecked()`][fromutf8], for more information.
421 /// [fromutf8]: fn.from_utf8_unchecked.html
430 /// let mut heart = vec![240, 159, 146, 150];
431 /// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
433 /// assert_eq!("💖", heart);
436 #[stable(feature = "str_mut_extras", since = "1.20.0")]
437 pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
438 &mut *(v as *mut [u8] as *mut str)
441 #[stable(feature = "rust1", since = "1.0.0")]
442 impl fmt::Display for Utf8Error {
443 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
444 if let Some(error_len) = self.error_len {
445 write!(f, "invalid utf-8 sequence of {} bytes from index {}",
446 error_len, self.valid_up_to)
448 write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to)
457 /// An iterator over the [`char`]s of a string slice.
459 /// [`char`]: ../../std/primitive.char.html
461 /// This struct is created by the [`chars`] method on [`str`].
462 /// See its documentation for more.
464 /// [`chars`]: ../../std/primitive.str.html#method.chars
465 /// [`str`]: ../../std/primitive.str.html
466 #[derive(Clone, Debug)]
467 #[stable(feature = "rust1", since = "1.0.0")]
468 pub struct Chars<'a> {
469 iter: slice::Iter<'a, u8>
472 /// Returns the initial codepoint accumulator for the first byte.
473 /// The first byte is special, only want bottom 5 bits for width 2, 4 bits
474 /// for width 3, and 3 bits for width 4.
476 fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
478 /// Returns the value of `ch` updated with continuation byte `byte`.
480 fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
482 /// Checks whether the byte is a UTF-8 continuation byte (i.e. starts with the
485 fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
488 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
495 /// Reads the next code point out of a byte iterator (assuming a
496 /// UTF-8-like encoding).
497 #[unstable(feature = "str_internals", issue = "0")]
499 pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
501 let x = *bytes.next()?;
503 return Some(x as u32)
506 // Multibyte case follows
507 // Decode from a byte combination out of: [[[x y] z] w]
508 // NOTE: Performance is sensitive to the exact formulation here
509 let init = utf8_first_byte(x, 2);
510 let y = unwrap_or_0(bytes.next());
511 let mut ch = utf8_acc_cont_byte(init, y);
514 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
515 let z = unwrap_or_0(bytes.next());
516 let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
517 ch = init << 12 | y_z;
520 // use only the lower 3 bits of `init`
521 let w = unwrap_or_0(bytes.next());
522 ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
529 /// Reads the last code point out of a byte iterator (assuming a
530 /// UTF-8-like encoding).
532 fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
533 where I: DoubleEndedIterator<Item = &'a u8>,
536 let w = match bytes.next_back() {
538 Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
539 Some(&back_byte) => back_byte,
542 // Multibyte case follows
543 // Decode from a byte combination out of: [x [y [z w]]]
545 let z = unwrap_or_0(bytes.next_back());
546 ch = utf8_first_byte(z, 2);
547 if utf8_is_cont_byte(z) {
548 let y = unwrap_or_0(bytes.next_back());
549 ch = utf8_first_byte(y, 3);
550 if utf8_is_cont_byte(y) {
551 let x = unwrap_or_0(bytes.next_back());
552 ch = utf8_first_byte(x, 4);
553 ch = utf8_acc_cont_byte(ch, y);
555 ch = utf8_acc_cont_byte(ch, z);
557 ch = utf8_acc_cont_byte(ch, w);
562 #[stable(feature = "rust1", since = "1.0.0")]
563 impl<'a> Iterator for Chars<'a> {
567 fn next(&mut self) -> Option<char> {
568 next_code_point(&mut self.iter).map(|ch| {
569 // str invariant says `ch` is a valid Unicode Scalar Value
571 char::from_u32_unchecked(ch)
577 fn count(self) -> usize {
578 // length in `char` is equal to the number of non-continuation bytes
579 let bytes_len = self.iter.len();
580 let mut cont_bytes = 0;
581 for &byte in self.iter {
582 cont_bytes += utf8_is_cont_byte(byte) as usize;
584 bytes_len - cont_bytes
588 fn size_hint(&self) -> (usize, Option<usize>) {
589 let len = self.iter.len();
590 // `(len + 3)` can't overflow, because we know that the `slice::Iter`
591 // belongs to a slice in memory which has a maximum length of
592 // `isize::MAX` (that's well below `usize::MAX`).
593 ((len + 3) / 4, Some(len))
597 fn last(mut self) -> Option<char> {
598 // No need to go through the entire string.
603 #[stable(feature = "rust1", since = "1.0.0")]
604 impl<'a> DoubleEndedIterator for Chars<'a> {
606 fn next_back(&mut self) -> Option<char> {
607 next_code_point_reverse(&mut self.iter).map(|ch| {
608 // str invariant says `ch` is a valid Unicode Scalar Value
610 char::from_u32_unchecked(ch)
616 #[stable(feature = "fused", since = "1.26.0")]
617 impl<'a> FusedIterator for Chars<'a> {}
620 /// View the underlying data as a subslice of the original data.
622 /// This has the same lifetime as the original slice, and so the
623 /// iterator can continue to be used while this exists.
628 /// let mut chars = "abc".chars();
630 /// assert_eq!(chars.as_str(), "abc");
632 /// assert_eq!(chars.as_str(), "bc");
635 /// assert_eq!(chars.as_str(), "");
637 #[stable(feature = "iter_to_slice", since = "1.4.0")]
639 pub fn as_str(&self) -> &'a str {
640 unsafe { from_utf8_unchecked(self.iter.as_slice()) }
644 /// An iterator over the [`char`]s of a string slice, and their positions.
646 /// [`char`]: ../../std/primitive.char.html
648 /// This struct is created by the [`char_indices`] method on [`str`].
649 /// See its documentation for more.
651 /// [`char_indices`]: ../../std/primitive.str.html#method.char_indices
652 /// [`str`]: ../../std/primitive.str.html
653 #[derive(Clone, Debug)]
654 #[stable(feature = "rust1", since = "1.0.0")]
655 pub struct CharIndices<'a> {
660 #[stable(feature = "rust1", since = "1.0.0")]
661 impl<'a> Iterator for CharIndices<'a> {
662 type Item = (usize, char);
665 fn next(&mut self) -> Option<(usize, char)> {
666 let pre_len = self.iter.iter.len();
667 match self.iter.next() {
670 let index = self.front_offset;
671 let len = self.iter.iter.len();
672 self.front_offset += pre_len - len;
679 fn count(self) -> usize {
684 fn size_hint(&self) -> (usize, Option<usize>) {
685 self.iter.size_hint()
689 fn last(mut self) -> Option<(usize, char)> {
690 // No need to go through the entire string.
695 #[stable(feature = "rust1", since = "1.0.0")]
696 impl<'a> DoubleEndedIterator for CharIndices<'a> {
698 fn next_back(&mut self) -> Option<(usize, char)> {
699 match self.iter.next_back() {
702 let index = self.front_offset + self.iter.iter.len();
709 #[stable(feature = "fused", since = "1.26.0")]
710 impl<'a> FusedIterator for CharIndices<'a> {}
712 impl<'a> CharIndices<'a> {
713 /// View the underlying data as a subslice of the original data.
715 /// This has the same lifetime as the original slice, and so the
716 /// iterator can continue to be used while this exists.
717 #[stable(feature = "iter_to_slice", since = "1.4.0")]
719 pub fn as_str(&self) -> &'a str {
724 /// An iterator over the bytes of a string slice.
726 /// This struct is created by the [`bytes`] method on [`str`].
727 /// See its documentation for more.
729 /// [`bytes`]: ../../std/primitive.str.html#method.bytes
730 /// [`str`]: ../../std/primitive.str.html
731 #[stable(feature = "rust1", since = "1.0.0")]
732 #[derive(Clone, Debug)]
733 pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>);
735 #[stable(feature = "rust1", since = "1.0.0")]
736 impl<'a> Iterator for Bytes<'a> {
740 fn next(&mut self) -> Option<u8> {
745 fn size_hint(&self) -> (usize, Option<usize>) {
750 fn count(self) -> usize {
755 fn last(self) -> Option<Self::Item> {
760 fn nth(&mut self, n: usize) -> Option<Self::Item> {
765 fn all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
770 fn any<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
775 fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where
776 P: FnMut(&Self::Item) -> bool
778 self.0.find(predicate)
782 fn position<P>(&mut self, predicate: P) -> Option<usize> where
783 P: FnMut(Self::Item) -> bool
785 self.0.position(predicate)
789 fn rposition<P>(&mut self, predicate: P) -> Option<usize> where
790 P: FnMut(Self::Item) -> bool
792 self.0.rposition(predicate)
796 #[stable(feature = "rust1", since = "1.0.0")]
797 impl<'a> DoubleEndedIterator for Bytes<'a> {
799 fn next_back(&mut self) -> Option<u8> {
804 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> where
805 P: FnMut(&Self::Item) -> bool
807 self.0.rfind(predicate)
811 #[stable(feature = "rust1", since = "1.0.0")]
812 impl<'a> ExactSizeIterator for Bytes<'a> {
814 fn len(&self) -> usize {
819 fn is_empty(&self) -> bool {
824 #[stable(feature = "fused", since = "1.26.0")]
825 impl<'a> FusedIterator for Bytes<'a> {}
827 #[unstable(feature = "trusted_len", issue = "37572")]
828 unsafe impl<'a> TrustedLen for Bytes<'a> {}
831 unsafe impl<'a> TrustedRandomAccess for Bytes<'a> {
832 unsafe fn get_unchecked(&mut self, i: usize) -> u8 {
833 self.0.get_unchecked(i)
835 fn may_have_side_effect() -> bool { false }
838 /// This macro generates a Clone impl for string pattern API
839 /// wrapper types of the form X<'a, P>
840 macro_rules! derive_pattern_clone {
841 (clone $t:ident with |$s:ident| $e:expr) => {
842 impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
843 where P::Searcher: Clone
845 fn clone(&self) -> Self {
853 /// This macro generates two public iterator structs
854 /// wrapping a private internal one that makes use of the `Pattern` API.
856 /// For all patterns `P: Pattern<'a>` the following items will be
857 /// generated (generics omitted):
859 /// struct $forward_iterator($internal_iterator);
860 /// struct $reverse_iterator($internal_iterator);
862 /// impl Iterator for $forward_iterator
863 /// { /* internal ends up calling Searcher::next_match() */ }
865 /// impl DoubleEndedIterator for $forward_iterator
866 /// where P::Searcher: DoubleEndedSearcher
867 /// { /* internal ends up calling Searcher::next_match_back() */ }
869 /// impl Iterator for $reverse_iterator
870 /// where P::Searcher: ReverseSearcher
871 /// { /* internal ends up calling Searcher::next_match_back() */ }
873 /// impl DoubleEndedIterator for $reverse_iterator
874 /// where P::Searcher: DoubleEndedSearcher
875 /// { /* internal ends up calling Searcher::next_match() */ }
877 /// The internal one is defined outside the macro, and has almost the same
878 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
879 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
881 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
882 /// `Pattern` might not return the same elements, so actually implementing
883 /// `DoubleEndedIterator` for it would be incorrect.
884 /// (See the docs in `str::pattern` for more details)
886 /// However, the internal struct still represents a single ended iterator from
887 /// either end, and depending on pattern is also a valid double ended iterator,
888 /// so the two wrapper structs implement `Iterator`
889 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
890 /// to the complex impls seen above.
891 macro_rules! generate_pattern_iterators {
895 $(#[$forward_iterator_attribute:meta])*
896 struct $forward_iterator:ident;
900 $(#[$reverse_iterator_attribute:meta])*
901 struct $reverse_iterator:ident;
903 // Stability of all generated items
905 $(#[$common_stability_attribute:meta])*
907 // Internal almost-iterator that is being delegated to
909 $internal_iterator:ident yielding ($iterty:ty);
911 // Kind of delegation - either single ended or double ended
914 $(#[$forward_iterator_attribute])*
915 $(#[$common_stability_attribute])*
916 pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
918 $(#[$common_stability_attribute])*
919 impl<'a, P: Pattern<'a>> fmt::Debug for $forward_iterator<'a, P>
920 where P::Searcher: fmt::Debug
922 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
923 f.debug_tuple(stringify!($forward_iterator))
929 $(#[$common_stability_attribute])*
930 impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
934 fn next(&mut self) -> Option<$iterty> {
939 $(#[$common_stability_attribute])*
940 impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
941 where P::Searcher: Clone
943 fn clone(&self) -> Self {
944 $forward_iterator(self.0.clone())
948 $(#[$reverse_iterator_attribute])*
949 $(#[$common_stability_attribute])*
950 pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
952 $(#[$common_stability_attribute])*
953 impl<'a, P: Pattern<'a>> fmt::Debug for $reverse_iterator<'a, P>
954 where P::Searcher: fmt::Debug
956 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
957 f.debug_tuple(stringify!($reverse_iterator))
963 $(#[$common_stability_attribute])*
964 impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
965 where P::Searcher: ReverseSearcher<'a>
970 fn next(&mut self) -> Option<$iterty> {
975 $(#[$common_stability_attribute])*
976 impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
977 where P::Searcher: Clone
979 fn clone(&self) -> Self {
980 $reverse_iterator(self.0.clone())
984 #[stable(feature = "fused", since = "1.26.0")]
985 impl<'a, P: Pattern<'a>> FusedIterator for $forward_iterator<'a, P> {}
987 #[stable(feature = "fused", since = "1.26.0")]
988 impl<'a, P: Pattern<'a>> FusedIterator for $reverse_iterator<'a, P>
989 where P::Searcher: ReverseSearcher<'a> {}
991 generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
993 $reverse_iterator, $iterty);
996 double ended; with $(#[$common_stability_attribute:meta])*,
997 $forward_iterator:ident,
998 $reverse_iterator:ident, $iterty:ty
1000 $(#[$common_stability_attribute])*
1001 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
1002 where P::Searcher: DoubleEndedSearcher<'a>
1005 fn next_back(&mut self) -> Option<$iterty> {
1010 $(#[$common_stability_attribute])*
1011 impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
1012 where P::Searcher: DoubleEndedSearcher<'a>
1015 fn next_back(&mut self) -> Option<$iterty> {
1021 single ended; with $(#[$common_stability_attribute:meta])*,
1022 $forward_iterator:ident,
1023 $reverse_iterator:ident, $iterty:ty
1027 derive_pattern_clone!{
1029 with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
1032 struct SplitInternal<'a, P: Pattern<'a>> {
1035 matcher: P::Searcher,
1036 allow_trailing_empty: bool,
1040 impl<'a, P: Pattern<'a>> fmt::Debug for SplitInternal<'a, P> where P::Searcher: fmt::Debug {
1041 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1042 f.debug_struct("SplitInternal")
1043 .field("start", &self.start)
1044 .field("end", &self.end)
1045 .field("matcher", &self.matcher)
1046 .field("allow_trailing_empty", &self.allow_trailing_empty)
1047 .field("finished", &self.finished)
1052 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
1054 fn get_end(&mut self) -> Option<&'a str> {
1055 if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
1056 self.finished = true;
1058 let string = self.matcher.haystack().slice_unchecked(self.start, self.end);
1067 fn next(&mut self) -> Option<&'a str> {
1068 if self.finished { return None }
1070 let haystack = self.matcher.haystack();
1071 match self.matcher.next_match() {
1072 Some((a, b)) => unsafe {
1073 let elt = haystack.slice_unchecked(self.start, a);
1077 None => self.get_end(),
1082 fn next_back(&mut self) -> Option<&'a str>
1083 where P::Searcher: ReverseSearcher<'a>
1085 if self.finished { return None }
1087 if !self.allow_trailing_empty {
1088 self.allow_trailing_empty = true;
1089 match self.next_back() {
1090 Some(elt) if !elt.is_empty() => return Some(elt),
1091 _ => if self.finished { return None }
1095 let haystack = self.matcher.haystack();
1096 match self.matcher.next_match_back() {
1097 Some((a, b)) => unsafe {
1098 let elt = haystack.slice_unchecked(b, self.end);
1103 self.finished = true;
1104 Some(haystack.slice_unchecked(self.start, self.end))
1110 generate_pattern_iterators! {
1112 /// Created with the method [`split`].
1114 /// [`split`]: ../../std/primitive.str.html#method.split
1117 /// Created with the method [`rsplit`].
1119 /// [`rsplit`]: ../../std/primitive.str.html#method.rsplit
1122 #[stable(feature = "rust1", since = "1.0.0")]
1124 SplitInternal yielding (&'a str);
1125 delegate double ended;
1128 generate_pattern_iterators! {
1130 /// Created with the method [`split_terminator`].
1132 /// [`split_terminator`]: ../../std/primitive.str.html#method.split_terminator
1133 struct SplitTerminator;
1135 /// Created with the method [`rsplit_terminator`].
1137 /// [`rsplit_terminator`]: ../../std/primitive.str.html#method.rsplit_terminator
1138 struct RSplitTerminator;
1140 #[stable(feature = "rust1", since = "1.0.0")]
1142 SplitInternal yielding (&'a str);
1143 delegate double ended;
1146 derive_pattern_clone!{
1147 clone SplitNInternal
1148 with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
1151 struct SplitNInternal<'a, P: Pattern<'a>> {
1152 iter: SplitInternal<'a, P>,
1153 /// The number of splits remaining
1157 impl<'a, P: Pattern<'a>> fmt::Debug for SplitNInternal<'a, P> where P::Searcher: fmt::Debug {
1158 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1159 f.debug_struct("SplitNInternal")
1160 .field("iter", &self.iter)
1161 .field("count", &self.count)
1166 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
1168 fn next(&mut self) -> Option<&'a str> {
1171 1 => { self.count = 0; self.iter.get_end() }
1172 _ => { self.count -= 1; self.iter.next() }
1177 fn next_back(&mut self) -> Option<&'a str>
1178 where P::Searcher: ReverseSearcher<'a>
1182 1 => { self.count = 0; self.iter.get_end() }
1183 _ => { self.count -= 1; self.iter.next_back() }
1188 generate_pattern_iterators! {
1190 /// Created with the method [`splitn`].
1192 /// [`splitn`]: ../../std/primitive.str.html#method.splitn
1195 /// Created with the method [`rsplitn`].
1197 /// [`rsplitn`]: ../../std/primitive.str.html#method.rsplitn
1200 #[stable(feature = "rust1", since = "1.0.0")]
1202 SplitNInternal yielding (&'a str);
1203 delegate single ended;
1206 derive_pattern_clone!{
1207 clone MatchIndicesInternal
1208 with |s| MatchIndicesInternal(s.0.clone())
1211 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
1213 impl<'a, P: Pattern<'a>> fmt::Debug for MatchIndicesInternal<'a, P> where P::Searcher: fmt::Debug {
1214 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1215 f.debug_tuple("MatchIndicesInternal")
1221 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
1223 fn next(&mut self) -> Option<(usize, &'a str)> {
1224 self.0.next_match().map(|(start, end)| unsafe {
1225 (start, self.0.haystack().slice_unchecked(start, end))
1230 fn next_back(&mut self) -> Option<(usize, &'a str)>
1231 where P::Searcher: ReverseSearcher<'a>
1233 self.0.next_match_back().map(|(start, end)| unsafe {
1234 (start, self.0.haystack().slice_unchecked(start, end))
1239 generate_pattern_iterators! {
1241 /// Created with the method [`match_indices`].
1243 /// [`match_indices`]: ../../std/primitive.str.html#method.match_indices
1244 struct MatchIndices;
1246 /// Created with the method [`rmatch_indices`].
1248 /// [`rmatch_indices`]: ../../std/primitive.str.html#method.rmatch_indices
1249 struct RMatchIndices;
1251 #[stable(feature = "str_match_indices", since = "1.5.0")]
1253 MatchIndicesInternal yielding ((usize, &'a str));
1254 delegate double ended;
1257 derive_pattern_clone!{
1258 clone MatchesInternal
1259 with |s| MatchesInternal(s.0.clone())
1262 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
1264 impl<'a, P: Pattern<'a>> fmt::Debug for MatchesInternal<'a, P> where P::Searcher: fmt::Debug {
1265 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1266 f.debug_tuple("MatchesInternal")
1272 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
1274 fn next(&mut self) -> Option<&'a str> {
1275 self.0.next_match().map(|(a, b)| unsafe {
1276 // Indices are known to be on utf8 boundaries
1277 self.0.haystack().slice_unchecked(a, b)
1282 fn next_back(&mut self) -> Option<&'a str>
1283 where P::Searcher: ReverseSearcher<'a>
1285 self.0.next_match_back().map(|(a, b)| unsafe {
1286 // Indices are known to be on utf8 boundaries
1287 self.0.haystack().slice_unchecked(a, b)
1292 generate_pattern_iterators! {
1294 /// Created with the method [`matches`].
1296 /// [`matches`]: ../../std/primitive.str.html#method.matches
1299 /// Created with the method [`rmatches`].
1301 /// [`rmatches`]: ../../std/primitive.str.html#method.rmatches
1304 #[stable(feature = "str_matches", since = "1.2.0")]
1306 MatchesInternal yielding (&'a str);
1307 delegate double ended;
1310 /// An iterator over the lines of a string, as string slices.
1312 /// This struct is created with the [`lines`] method on [`str`].
1313 /// See its documentation for more.
1315 /// [`lines`]: ../../std/primitive.str.html#method.lines
1316 /// [`str`]: ../../std/primitive.str.html
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 #[derive(Clone, Debug)]
1319 pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>);
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 impl<'a> Iterator for Lines<'a> {
1323 type Item = &'a str;
1326 fn next(&mut self) -> Option<&'a str> {
1331 fn size_hint(&self) -> (usize, Option<usize>) {
1336 #[stable(feature = "rust1", since = "1.0.0")]
1337 impl<'a> DoubleEndedIterator for Lines<'a> {
1339 fn next_back(&mut self) -> Option<&'a str> {
1344 #[stable(feature = "fused", since = "1.26.0")]
1345 impl<'a> FusedIterator for Lines<'a> {}
1347 /// Created with the method [`lines_any`].
1349 /// [`lines_any`]: ../../std/primitive.str.html#method.lines_any
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 #[rustc_deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")]
1352 #[derive(Clone, Debug)]
1353 #[allow(deprecated)]
1354 pub struct LinesAny<'a>(Lines<'a>);
1356 /// A nameable, cloneable fn type
1360 impl<'a> Fn<(&'a str,)> for LinesAnyMap {
1362 extern "rust-call" fn call(&self, (line,): (&'a str,)) -> &'a str {
1364 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
1369 impl<'a> FnMut<(&'a str,)> for LinesAnyMap {
1371 extern "rust-call" fn call_mut(&mut self, (line,): (&'a str,)) -> &'a str {
1372 Fn::call(&*self, (line,))
1376 impl<'a> FnOnce<(&'a str,)> for LinesAnyMap {
1377 type Output = &'a str;
1380 extern "rust-call" fn call_once(self, (line,): (&'a str,)) -> &'a str {
1381 Fn::call(&self, (line,))
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 #[allow(deprecated)]
1387 impl<'a> Iterator for LinesAny<'a> {
1388 type Item = &'a str;
1391 fn next(&mut self) -> Option<&'a str> {
1396 fn size_hint(&self) -> (usize, Option<usize>) {
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 #[allow(deprecated)]
1403 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1405 fn next_back(&mut self) -> Option<&'a str> {
1410 #[stable(feature = "fused", since = "1.26.0")]
1411 #[allow(deprecated)]
1412 impl<'a> FusedIterator for LinesAny<'a> {}
1415 Section: UTF-8 validation
1418 // use truncation to fit u64 into usize
1419 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
1421 /// Returns `true` if any byte in the word `x` is nonascii (>= 128).
1423 fn contains_nonascii(x: usize) -> bool {
1424 (x & NONASCII_MASK) != 0
1427 /// Walks through `iter` checking that it's a valid UTF-8 sequence,
1428 /// returning `true` in that case, or, if it is invalid, `false` with
1429 /// `iter` reset such that it is pointing at the first byte in the
1430 /// invalid sequence.
1432 fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
1436 let usize_bytes = mem::size_of::<usize>();
1437 let ascii_block_size = 2 * usize_bytes;
1438 let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
1441 let old_offset = index;
1443 ($error_len: expr) => {
1444 return Err(Utf8Error {
1445 valid_up_to: old_offset,
1446 error_len: $error_len,
1451 macro_rules! next { () => {{
1453 // we needed data, but there was none: error!
1460 let first = v[index];
1462 let w = UTF8_CHAR_WIDTH[first as usize];
1463 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
1464 // first C2 80 last DF BF
1465 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
1466 // first E0 A0 80 last EF BF BF
1467 // excluding surrogates codepoints \u{d800} to \u{dfff}
1468 // ED A0 80 to ED BF BF
1469 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1470 // first F0 90 80 80 last F4 8F BF BF
1472 // Use the UTF-8 syntax from the RFC
1474 // https://tools.ietf.org/html/rfc3629
1476 // UTF8-2 = %xC2-DF UTF8-tail
1477 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1478 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1479 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1480 // %xF4 %x80-8F 2( UTF8-tail )
1482 2 => if next!() & !CONT_MASK != TAG_CONT_U8 {
1486 match (first, next!()) {
1487 (0xE0 , 0xA0 ..= 0xBF) |
1488 (0xE1 ..= 0xEC, 0x80 ..= 0xBF) |
1489 (0xED , 0x80 ..= 0x9F) |
1490 (0xEE ..= 0xEF, 0x80 ..= 0xBF) => {}
1493 if next!() & !CONT_MASK != TAG_CONT_U8 {
1498 match (first, next!()) {
1499 (0xF0 , 0x90 ..= 0xBF) |
1500 (0xF1 ..= 0xF3, 0x80 ..= 0xBF) |
1501 (0xF4 , 0x80 ..= 0x8F) => {}
1504 if next!() & !CONT_MASK != TAG_CONT_U8 {
1507 if next!() & !CONT_MASK != TAG_CONT_U8 {
1515 // Ascii case, try to skip forward quickly.
1516 // When the pointer is aligned, read 2 words of data per iteration
1517 // until we find a word containing a non-ascii byte.
1518 let ptr = v.as_ptr();
1519 let align = unsafe {
1520 // the offset is safe, because `index` is guaranteed inbounds
1521 ptr.offset(index as isize).align_offset(usize_bytes)
1524 while index < blocks_end {
1526 let block = ptr.offset(index as isize) as *const usize;
1527 // break if there is a nonascii byte
1528 let zu = contains_nonascii(*block);
1529 let zv = contains_nonascii(*block.offset(1));
1534 index += ascii_block_size;
1536 // step from the point where the wordwise loop stopped
1537 while index < len && v[index] < 128 {
1549 // https://tools.ietf.org/html/rfc3629
1550 static UTF8_CHAR_WIDTH: [u8; 256] = [
1551 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1552 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1553 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1554 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1555 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1556 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1557 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1558 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1559 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1560 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1561 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1562 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1563 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1564 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1565 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1566 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1569 /// Given a first byte, determines how many bytes are in this UTF-8 character.
1570 #[unstable(feature = "str_internals", issue = "0")]
1572 pub fn utf8_char_width(b: u8) -> usize {
1573 return UTF8_CHAR_WIDTH[b as usize] as usize;
1576 /// Mask of the value bits of a continuation byte.
1577 const CONT_MASK: u8 = 0b0011_1111;
1578 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte.
1579 const TAG_CONT_U8: u8 = 0b1000_0000;
1582 Section: Trait implementations
1588 use slice::{self, SliceIndex};
1590 /// Implements ordering of strings.
1592 /// Strings are ordered lexicographically by their byte values. This orders Unicode code
1593 /// points based on their positions in the code charts. This is not necessarily the same as
1594 /// "alphabetical" order, which varies by language and locale. Sorting strings according to
1595 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1597 #[stable(feature = "rust1", since = "1.0.0")]
1600 fn cmp(&self, other: &str) -> Ordering {
1601 self.as_bytes().cmp(other.as_bytes())
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 impl PartialEq for str {
1608 fn eq(&self, other: &str) -> bool {
1609 self.as_bytes() == other.as_bytes()
1612 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1615 #[stable(feature = "rust1", since = "1.0.0")]
1618 /// Implements comparison operations on strings.
1620 /// Strings are compared lexicographically by their byte values. This compares Unicode code
1621 /// points based on their positions in the code charts. This is not necessarily the same as
1622 /// "alphabetical" order, which varies by language and locale. Comparing strings according to
1623 /// culturally-accepted standards requires locale-specific data that is outside the scope of
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 impl PartialOrd for str {
1628 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1629 Some(self.cmp(other))
1633 /// Implements substring slicing with syntax `&self[begin .. end]`.
1635 /// Returns a slice of the given string from the byte range
1636 /// [`begin`..`end`).
1638 /// This operation is `O(1)`.
1642 /// Panics if `begin` or `end` does not point to the starting
1643 /// byte offset of a character (as defined by `is_char_boundary`).
1644 /// Requires that `begin <= end` and `end <= len` where `len` is the
1645 /// length of the string.
1650 /// let s = "Löwe 老虎 Léopard";
1651 /// assert_eq!(&s[0 .. 1], "L");
1653 /// assert_eq!(&s[1 .. 9], "öwe 老");
1655 /// // these will panic:
1656 /// // byte 2 lies within `ö`:
1659 /// // byte 8 lies within `老`
1662 /// // byte 100 is outside the string
1663 /// // &s[3 .. 100];
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 impl ops::Index<ops::Range<usize>> for str {
1669 fn index(&self, index: ops::Range<usize>) -> &str {
1674 /// Implements mutable substring slicing with syntax
1675 /// `&mut self[begin .. end]`.
1677 /// Returns a mutable slice of the given string from the byte range
1678 /// [`begin`..`end`).
1680 /// This operation is `O(1)`.
1684 /// Panics if `begin` or `end` does not point to the starting
1685 /// byte offset of a character (as defined by `is_char_boundary`).
1686 /// Requires that `begin <= end` and `end <= len` where `len` is the
1687 /// length of the string.
1688 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1689 impl ops::IndexMut<ops::Range<usize>> for str {
1691 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1692 index.index_mut(self)
1696 /// Implements substring slicing with syntax `&self[.. end]`.
1698 /// Returns a slice of the string from the beginning to byte offset
1701 /// Equivalent to `&self[0 .. end]`.
1702 #[stable(feature = "rust1", since = "1.0.0")]
1703 impl ops::Index<ops::RangeTo<usize>> for str {
1707 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1712 /// Implements mutable substring slicing with syntax `&mut self[.. end]`.
1714 /// Returns a mutable slice of the string from the beginning to byte offset
1717 /// Equivalent to `&mut self[0 .. end]`.
1718 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1719 impl ops::IndexMut<ops::RangeTo<usize>> for str {
1721 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1722 index.index_mut(self)
1726 /// Implements substring slicing with syntax `&self[begin ..]`.
1728 /// Returns a slice of the string from byte offset `begin`
1729 /// to the end of the string.
1731 /// Equivalent to `&self[begin .. len]`.
1732 #[stable(feature = "rust1", since = "1.0.0")]
1733 impl ops::Index<ops::RangeFrom<usize>> for str {
1737 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1742 /// Implements mutable substring slicing with syntax `&mut self[begin ..]`.
1744 /// Returns a mutable slice of the string from byte offset `begin`
1745 /// to the end of the string.
1747 /// Equivalent to `&mut self[begin .. len]`.
1748 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1749 impl ops::IndexMut<ops::RangeFrom<usize>> for str {
1751 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1752 index.index_mut(self)
1756 /// Implements substring slicing with syntax `&self[..]`.
1758 /// Returns a slice of the whole string. This operation can
1761 /// Equivalent to `&self[0 .. len]`.
1762 #[stable(feature = "rust1", since = "1.0.0")]
1763 impl ops::Index<ops::RangeFull> for str {
1767 fn index(&self, _index: ops::RangeFull) -> &str {
1772 /// Implements mutable substring slicing with syntax `&mut self[..]`.
1774 /// Returns a mutable slice of the whole string. This operation can
1777 /// Equivalent to `&mut self[0 .. len]`.
1778 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1779 impl ops::IndexMut<ops::RangeFull> for str {
1781 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1786 #[stable(feature = "inclusive_range", since = "1.26.0")]
1787 impl ops::Index<ops::RangeInclusive<usize>> for str {
1791 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1796 #[stable(feature = "inclusive_range", since = "1.26.0")]
1797 impl ops::Index<ops::RangeToInclusive<usize>> for str {
1801 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1806 #[stable(feature = "inclusive_range", since = "1.26.0")]
1807 impl ops::IndexMut<ops::RangeInclusive<usize>> for str {
1809 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1810 index.index_mut(self)
1813 #[stable(feature = "inclusive_range", since = "1.26.0")]
1814 impl ops::IndexMut<ops::RangeToInclusive<usize>> for str {
1816 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1817 index.index_mut(self)
1823 fn str_index_overflow_fail() -> ! {
1824 panic!("attempted to index str up to maximum usize");
1827 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1828 impl SliceIndex<str> for ops::RangeFull {
1831 fn get(self, slice: &str) -> Option<&Self::Output> {
1835 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1839 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1843 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1847 fn index(self, slice: &str) -> &Self::Output {
1851 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1856 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1857 impl SliceIndex<str> for ops::Range<usize> {
1860 fn get(self, slice: &str) -> Option<&Self::Output> {
1861 if self.start <= self.end &&
1862 slice.is_char_boundary(self.start) &&
1863 slice.is_char_boundary(self.end) {
1864 Some(unsafe { self.get_unchecked(slice) })
1870 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1871 if self.start <= self.end &&
1872 slice.is_char_boundary(self.start) &&
1873 slice.is_char_boundary(self.end) {
1874 Some(unsafe { self.get_unchecked_mut(slice) })
1880 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1881 let ptr = slice.as_ptr().offset(self.start as isize);
1882 let len = self.end - self.start;
1883 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1886 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1887 let ptr = slice.as_ptr().offset(self.start as isize);
1888 let len = self.end - self.start;
1889 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1892 fn index(self, slice: &str) -> &Self::Output {
1893 let (start, end) = (self.start, self.end);
1894 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1897 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1898 // is_char_boundary checks that the index is in [0, .len()]
1899 // canot reuse `get` as above, because of NLL trouble
1900 if self.start <= self.end &&
1901 slice.is_char_boundary(self.start) &&
1902 slice.is_char_boundary(self.end) {
1903 unsafe { self.get_unchecked_mut(slice) }
1905 super::slice_error_fail(slice, self.start, self.end)
1910 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1911 impl SliceIndex<str> for ops::RangeTo<usize> {
1914 fn get(self, slice: &str) -> Option<&Self::Output> {
1915 if slice.is_char_boundary(self.end) {
1916 Some(unsafe { self.get_unchecked(slice) })
1922 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1923 if slice.is_char_boundary(self.end) {
1924 Some(unsafe { self.get_unchecked_mut(slice) })
1930 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1931 let ptr = slice.as_ptr();
1932 super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end))
1935 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1936 let ptr = slice.as_ptr();
1937 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, self.end))
1940 fn index(self, slice: &str) -> &Self::Output {
1942 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end))
1945 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1946 // is_char_boundary checks that the index is in [0, .len()]
1947 if slice.is_char_boundary(self.end) {
1948 unsafe { self.get_unchecked_mut(slice) }
1950 super::slice_error_fail(slice, 0, self.end)
1955 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1956 impl SliceIndex<str> for ops::RangeFrom<usize> {
1959 fn get(self, slice: &str) -> Option<&Self::Output> {
1960 if slice.is_char_boundary(self.start) {
1961 Some(unsafe { self.get_unchecked(slice) })
1967 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1968 if slice.is_char_boundary(self.start) {
1969 Some(unsafe { self.get_unchecked_mut(slice) })
1975 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1976 let ptr = slice.as_ptr().offset(self.start as isize);
1977 let len = slice.len() - self.start;
1978 super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1981 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1982 let ptr = slice.as_ptr().offset(self.start as isize);
1983 let len = slice.len() - self.start;
1984 super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
1987 fn index(self, slice: &str) -> &Self::Output {
1988 let (start, end) = (self.start, slice.len());
1989 self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1992 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1993 // is_char_boundary checks that the index is in [0, .len()]
1994 if slice.is_char_boundary(self.start) {
1995 unsafe { self.get_unchecked_mut(slice) }
1997 super::slice_error_fail(slice, self.start, slice.len())
2002 #[stable(feature = "inclusive_range", since = "1.26.0")]
2003 impl SliceIndex<str> for ops::RangeInclusive<usize> {
2006 fn get(self, slice: &str) -> Option<&Self::Output> {
2007 if self.end == usize::max_value() { None }
2008 else { (self.start..self.end+1).get(slice) }
2011 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
2012 if self.end == usize::max_value() { None }
2013 else { (self.start..self.end+1).get_mut(slice) }
2016 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
2017 (self.start..self.end+1).get_unchecked(slice)
2020 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
2021 (self.start..self.end+1).get_unchecked_mut(slice)
2024 fn index(self, slice: &str) -> &Self::Output {
2025 if self.end == usize::max_value() { str_index_overflow_fail(); }
2026 (self.start..self.end+1).index(slice)
2029 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
2030 if self.end == usize::max_value() { str_index_overflow_fail(); }
2031 (self.start..self.end+1).index_mut(slice)
2037 #[stable(feature = "inclusive_range", since = "1.26.0")]
2038 impl SliceIndex<str> for ops::RangeToInclusive<usize> {
2041 fn get(self, slice: &str) -> Option<&Self::Output> {
2042 if self.end == usize::max_value() { None }
2043 else { (..self.end+1).get(slice) }
2046 fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
2047 if self.end == usize::max_value() { None }
2048 else { (..self.end+1).get_mut(slice) }
2051 unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
2052 (..self.end+1).get_unchecked(slice)
2055 unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
2056 (..self.end+1).get_unchecked_mut(slice)
2059 fn index(self, slice: &str) -> &Self::Output {
2060 if self.end == usize::max_value() { str_index_overflow_fail(); }
2061 (..self.end+1).index(slice)
2064 fn index_mut(self, slice: &mut str) -> &mut Self::Output {
2065 if self.end == usize::max_value() { str_index_overflow_fail(); }
2066 (..self.end+1).index_mut(slice)
2071 // truncate `&str` to length at most equal to `max`
2072 // return `true` if it were truncated, and the new str.
2073 fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
2077 while !s.is_char_boundary(max) {
2086 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
2087 const MAX_DISPLAY_LENGTH: usize = 256;
2088 let (truncated, s_trunc) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
2089 let ellipsis = if truncated { "[...]" } else { "" };
2092 if begin > s.len() || end > s.len() {
2093 let oob_index = if begin > s.len() { begin } else { end };
2094 panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
2098 assert!(begin <= end, "begin <= end ({} <= {}) when slicing `{}`{}",
2099 begin, end, s_trunc, ellipsis);
2101 // 3. character boundary
2102 let index = if !s.is_char_boundary(begin) { begin } else { end };
2103 // find the character
2104 let mut char_start = index;
2105 while !s.is_char_boundary(char_start) {
2108 // `char_start` must be less than len and a char boundary
2109 let ch = s[char_start..].chars().next().unwrap();
2110 let char_range = char_start .. char_start + ch.len_utf8();
2111 panic!("byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
2112 index, ch, char_range, s_trunc, ellipsis);
2118 /// Returns the length of `self`.
2120 /// This length is in bytes, not [`char`]s or graphemes. In other words,
2121 /// it may not be what a human considers the length of the string.
2123 /// [`char`]: primitive.char.html
2130 /// let len = "foo".len();
2131 /// assert_eq!(3, len);
2133 /// let len = "ƒoo".len(); // fancy f!
2134 /// assert_eq!(4, len);
2136 #[stable(feature = "rust1", since = "1.0.0")]
2138 #[rustc_const_unstable(feature = "const_str_len")]
2139 pub const fn len(&self) -> usize {
2140 self.as_bytes().len()
2143 /// Returns `true` if `self` has a length of zero bytes.
2151 /// assert!(s.is_empty());
2153 /// let s = "not empty";
2154 /// assert!(!s.is_empty());
2157 #[stable(feature = "rust1", since = "1.0.0")]
2158 #[rustc_const_unstable(feature = "const_str_len")]
2159 pub const fn is_empty(&self) -> bool {
2163 /// Checks that `index`-th byte lies at the start and/or end of a
2164 /// UTF-8 code point sequence.
2166 /// The start and end of the string (when `index == self.len()`) are
2167 /// considered to be
2170 /// Returns `false` if `index` is greater than `self.len()`.
2175 /// let s = "Löwe 老虎 Léopard";
2176 /// assert!(s.is_char_boundary(0));
2178 /// assert!(s.is_char_boundary(6));
2179 /// assert!(s.is_char_boundary(s.len()));
2181 /// // second byte of `ö`
2182 /// assert!(!s.is_char_boundary(2));
2184 /// // third byte of `老`
2185 /// assert!(!s.is_char_boundary(8));
2187 #[stable(feature = "is_char_boundary", since = "1.9.0")]
2189 pub fn is_char_boundary(&self, index: usize) -> bool {
2190 // 0 and len are always ok.
2191 // Test for 0 explicitly so that it can optimize out the check
2192 // easily and skip reading string data for that case.
2193 if index == 0 || index == self.len() { return true; }
2194 match self.as_bytes().get(index) {
2196 // This is bit magic equivalent to: b < 128 || b >= 192
2197 Some(&b) => (b as i8) >= -0x40,
2201 /// Converts a string slice to a byte slice. To convert the byte slice back
2202 /// into a string slice, use the [`str::from_utf8`] function.
2204 /// [`str::from_utf8`]: ./str/fn.from_utf8.html
2211 /// let bytes = "bors".as_bytes();
2212 /// assert_eq!(b"bors", bytes);
2214 #[stable(feature = "rust1", since = "1.0.0")]
2216 #[rustc_const_unstable(feature="const_str_as_bytes")]
2217 pub const fn as_bytes(&self) -> &[u8] {
2222 unsafe { Slices { str: self }.slice }
2225 /// Converts a mutable string slice to a mutable byte slice. To convert the
2226 /// mutable byte slice back into a mutable string slice, use the
2227 /// [`str::from_utf8_mut`] function.
2229 /// [`str::from_utf8_mut`]: ./str/fn.from_utf8_mut.html
2236 /// let mut s = String::from("Hello");
2237 /// let bytes = unsafe { s.as_bytes_mut() };
2239 /// assert_eq!(b"Hello", bytes);
2245 /// let mut s = String::from("🗻∈🌏");
2248 /// let bytes = s.as_bytes_mut();
2250 /// bytes[0] = 0xF0;
2251 /// bytes[1] = 0x9F;
2252 /// bytes[2] = 0x8D;
2253 /// bytes[3] = 0x94;
2256 /// assert_eq!("🍔∈🌏", s);
2258 #[stable(feature = "str_mut_extras", since = "1.20.0")]
2260 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
2261 &mut *(self as *mut str as *mut [u8])
2264 /// Converts a string slice to a raw pointer.
2266 /// As string slices are a slice of bytes, the raw pointer points to a
2267 /// [`u8`]. This pointer will be pointing to the first byte of the string
2270 /// [`u8`]: primitive.u8.html
2277 /// let s = "Hello";
2278 /// let ptr = s.as_ptr();
2280 #[stable(feature = "rust1", since = "1.0.0")]
2282 #[rustc_const_unstable(feature = "const_str_as_ptr")]
2283 pub const fn as_ptr(&self) -> *const u8 {
2284 self as *const str as *const u8
2287 /// Returns a subslice of `str`.
2289 /// This is the non-panicking alternative to indexing the `str`. Returns
2290 /// [`None`] whenever equivalent indexing operation would panic.
2292 /// [`None`]: option/enum.Option.html#variant.None
2297 /// let v = String::from("🗻∈🌏");
2299 /// assert_eq!(Some("🗻"), v.get(0..4));
2301 /// // indices not on UTF-8 sequence boundaries
2302 /// assert!(v.get(1..).is_none());
2303 /// assert!(v.get(..8).is_none());
2305 /// // out of bounds
2306 /// assert!(v.get(..42).is_none());
2308 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2310 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
2314 /// Returns a mutable subslice of `str`.
2316 /// This is the non-panicking alternative to indexing the `str`. Returns
2317 /// [`None`] whenever equivalent indexing operation would panic.
2319 /// [`None`]: option/enum.Option.html#variant.None
2324 /// let mut v = String::from("hello");
2325 /// // correct length
2326 /// assert!(v.get_mut(0..5).is_some());
2327 /// // out of bounds
2328 /// assert!(v.get_mut(..42).is_none());
2329 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
2331 /// assert_eq!("hello", v);
2333 /// let s = v.get_mut(0..2);
2334 /// let s = s.map(|s| {
2335 /// s.make_ascii_uppercase();
2338 /// assert_eq!(Some("HE"), s);
2340 /// assert_eq!("HEllo", v);
2342 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2344 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
2348 /// Returns a unchecked subslice of `str`.
2350 /// This is the unchecked alternative to indexing the `str`.
2354 /// Callers of this function are responsible that these preconditions are
2357 /// * The starting index must come before the ending index;
2358 /// * Indexes must be within bounds of the original slice;
2359 /// * Indexes must lie on UTF-8 sequence boundaries.
2361 /// Failing that, the returned string slice may reference invalid memory or
2362 /// violate the invariants communicated by the `str` type.
2369 /// assert_eq!("🗻", v.get_unchecked(0..4));
2370 /// assert_eq!("∈", v.get_unchecked(4..7));
2371 /// assert_eq!("🌏", v.get_unchecked(7..11));
2374 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2376 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
2377 i.get_unchecked(self)
2380 /// Returns a mutable, unchecked subslice of `str`.
2382 /// This is the unchecked alternative to indexing the `str`.
2386 /// Callers of this function are responsible that these preconditions are
2389 /// * The starting index must come before the ending index;
2390 /// * Indexes must be within bounds of the original slice;
2391 /// * Indexes must lie on UTF-8 sequence boundaries.
2393 /// Failing that, the returned string slice may reference invalid memory or
2394 /// violate the invariants communicated by the `str` type.
2399 /// let mut v = String::from("🗻∈🌏");
2401 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
2402 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
2403 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
2406 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2408 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
2409 i.get_unchecked_mut(self)
2412 /// Creates a string slice from another string slice, bypassing safety
2415 /// This is generally not recommended, use with caution! For a safe
2416 /// alternative see [`str`] and [`Index`].
2418 /// [`str`]: primitive.str.html
2419 /// [`Index`]: ops/trait.Index.html
2421 /// This new slice goes from `begin` to `end`, including `begin` but
2422 /// excluding `end`.
2424 /// To get a mutable string slice instead, see the
2425 /// [`slice_mut_unchecked`] method.
2427 /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
2431 /// Callers of this function are responsible that three preconditions are
2434 /// * `begin` must come before `end`.
2435 /// * `begin` and `end` must be byte positions within the string slice.
2436 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2443 /// let s = "Löwe 老虎 Léopard";
2446 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
2449 /// let s = "Hello, world!";
2452 /// assert_eq!("world", s.slice_unchecked(7, 12));
2455 #[stable(feature = "rust1", since = "1.0.0")]
2457 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
2458 (begin..end).get_unchecked(self)
2461 /// Creates a string slice from another string slice, bypassing safety
2463 /// This is generally not recommended, use with caution! For a safe
2464 /// alternative see [`str`] and [`IndexMut`].
2466 /// [`str`]: primitive.str.html
2467 /// [`IndexMut`]: ops/trait.IndexMut.html
2469 /// This new slice goes from `begin` to `end`, including `begin` but
2470 /// excluding `end`.
2472 /// To get an immutable string slice instead, see the
2473 /// [`slice_unchecked`] method.
2475 /// [`slice_unchecked`]: #method.slice_unchecked
2479 /// Callers of this function are responsible that three preconditions are
2482 /// * `begin` must come before `end`.
2483 /// * `begin` and `end` must be byte positions within the string slice.
2484 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2485 #[stable(feature = "str_slice_mut", since = "1.5.0")]
2487 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
2488 (begin..end).get_unchecked_mut(self)
2491 /// Divide one string slice into two at an index.
2493 /// The argument, `mid`, should be a byte offset from the start of the
2494 /// string. It must also be on the boundary of a UTF-8 code point.
2496 /// The two slices returned go from the start of the string slice to `mid`,
2497 /// and from `mid` to the end of the string slice.
2499 /// To get mutable string slices instead, see the [`split_at_mut`]
2502 /// [`split_at_mut`]: #method.split_at_mut
2506 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2507 /// beyond the last code point of the string slice.
2514 /// let s = "Per Martin-Löf";
2516 /// let (first, last) = s.split_at(3);
2518 /// assert_eq!("Per", first);
2519 /// assert_eq!(" Martin-Löf", last);
2522 #[stable(feature = "str_split_at", since = "1.4.0")]
2523 pub fn split_at(&self, mid: usize) -> (&str, &str) {
2524 // is_char_boundary checks that the index is in [0, .len()]
2525 if self.is_char_boundary(mid) {
2527 (self.slice_unchecked(0, mid),
2528 self.slice_unchecked(mid, self.len()))
2531 slice_error_fail(self, 0, mid)
2535 /// Divide one mutable string slice into two at an index.
2537 /// The argument, `mid`, should be a byte offset from the start of the
2538 /// string. It must also be on the boundary of a UTF-8 code point.
2540 /// The two slices returned go from the start of the string slice to `mid`,
2541 /// and from `mid` to the end of the string slice.
2543 /// To get immutable string slices instead, see the [`split_at`] method.
2545 /// [`split_at`]: #method.split_at
2549 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2550 /// beyond the last code point of the string slice.
2557 /// let mut s = "Per Martin-Löf".to_string();
2559 /// let (first, last) = s.split_at_mut(3);
2560 /// first.make_ascii_uppercase();
2561 /// assert_eq!("PER", first);
2562 /// assert_eq!(" Martin-Löf", last);
2564 /// assert_eq!("PER Martin-Löf", s);
2567 #[stable(feature = "str_split_at", since = "1.4.0")]
2568 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
2569 // is_char_boundary checks that the index is in [0, .len()]
2570 if self.is_char_boundary(mid) {
2571 let len = self.len();
2572 let ptr = self.as_ptr() as *mut u8;
2574 (from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
2575 from_utf8_unchecked_mut(slice::from_raw_parts_mut(
2576 ptr.offset(mid as isize),
2581 slice_error_fail(self, 0, mid)
2585 /// Returns an iterator over the [`char`]s of a string slice.
2587 /// As a string slice consists of valid UTF-8, we can iterate through a
2588 /// string slice by [`char`]. This method returns such an iterator.
2590 /// It's important to remember that [`char`] represents a Unicode Scalar
2591 /// Value, and may not match your idea of what a 'character' is. Iteration
2592 /// over grapheme clusters may be what you actually want.
2594 /// [`char`]: primitive.char.html
2601 /// let word = "goodbye";
2603 /// let count = word.chars().count();
2604 /// assert_eq!(7, count);
2606 /// let mut chars = word.chars();
2608 /// assert_eq!(Some('g'), chars.next());
2609 /// assert_eq!(Some('o'), chars.next());
2610 /// assert_eq!(Some('o'), chars.next());
2611 /// assert_eq!(Some('d'), chars.next());
2612 /// assert_eq!(Some('b'), chars.next());
2613 /// assert_eq!(Some('y'), chars.next());
2614 /// assert_eq!(Some('e'), chars.next());
2616 /// assert_eq!(None, chars.next());
2619 /// Remember, [`char`]s may not match your human intuition about characters:
2624 /// let mut chars = y.chars();
2626 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
2627 /// assert_eq!(Some('\u{0306}'), chars.next());
2629 /// assert_eq!(None, chars.next());
2631 #[stable(feature = "rust1", since = "1.0.0")]
2633 pub fn chars(&self) -> Chars {
2634 Chars{iter: self.as_bytes().iter()}
2637 /// Returns an iterator over the [`char`]s of a string slice, and their
2640 /// As a string slice consists of valid UTF-8, we can iterate through a
2641 /// string slice by [`char`]. This method returns an iterator of both
2642 /// these [`char`]s, as well as their byte positions.
2644 /// The iterator yields tuples. The position is first, the [`char`] is
2647 /// [`char`]: primitive.char.html
2654 /// let word = "goodbye";
2656 /// let count = word.char_indices().count();
2657 /// assert_eq!(7, count);
2659 /// let mut char_indices = word.char_indices();
2661 /// assert_eq!(Some((0, 'g')), char_indices.next());
2662 /// assert_eq!(Some((1, 'o')), char_indices.next());
2663 /// assert_eq!(Some((2, 'o')), char_indices.next());
2664 /// assert_eq!(Some((3, 'd')), char_indices.next());
2665 /// assert_eq!(Some((4, 'b')), char_indices.next());
2666 /// assert_eq!(Some((5, 'y')), char_indices.next());
2667 /// assert_eq!(Some((6, 'e')), char_indices.next());
2669 /// assert_eq!(None, char_indices.next());
2672 /// Remember, [`char`]s may not match your human intuition about characters:
2675 /// let yes = "y̆es";
2677 /// let mut char_indices = yes.char_indices();
2679 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
2680 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
2682 /// // note the 3 here - the last character took up two bytes
2683 /// assert_eq!(Some((3, 'e')), char_indices.next());
2684 /// assert_eq!(Some((4, 's')), char_indices.next());
2686 /// assert_eq!(None, char_indices.next());
2688 #[stable(feature = "rust1", since = "1.0.0")]
2690 pub fn char_indices(&self) -> CharIndices {
2691 CharIndices { front_offset: 0, iter: self.chars() }
2694 /// An iterator over the bytes of a string slice.
2696 /// As a string slice consists of a sequence of bytes, we can iterate
2697 /// through a string slice by byte. This method returns such an iterator.
2704 /// let mut bytes = "bors".bytes();
2706 /// assert_eq!(Some(b'b'), bytes.next());
2707 /// assert_eq!(Some(b'o'), bytes.next());
2708 /// assert_eq!(Some(b'r'), bytes.next());
2709 /// assert_eq!(Some(b's'), bytes.next());
2711 /// assert_eq!(None, bytes.next());
2713 #[stable(feature = "rust1", since = "1.0.0")]
2715 pub fn bytes(&self) -> Bytes {
2716 Bytes(self.as_bytes().iter().cloned())
2719 /// Split a string slice by whitespace.
2721 /// The iterator returned will return string slices that are sub-slices of
2722 /// the original string slice, separated by any amount of whitespace.
2724 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2725 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
2726 /// instead, use [`split_ascii_whitespace`].
2728 /// [`split_ascii_whitespace`]: #method.split_ascii_whitespace
2735 /// let mut iter = "A few words".split_whitespace();
2737 /// assert_eq!(Some("A"), iter.next());
2738 /// assert_eq!(Some("few"), iter.next());
2739 /// assert_eq!(Some("words"), iter.next());
2741 /// assert_eq!(None, iter.next());
2744 /// All kinds of whitespace are considered:
2747 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
2748 /// assert_eq!(Some("Mary"), iter.next());
2749 /// assert_eq!(Some("had"), iter.next());
2750 /// assert_eq!(Some("a"), iter.next());
2751 /// assert_eq!(Some("little"), iter.next());
2752 /// assert_eq!(Some("lamb"), iter.next());
2754 /// assert_eq!(None, iter.next());
2756 #[stable(feature = "split_whitespace", since = "1.1.0")]
2758 pub fn split_whitespace(&self) -> SplitWhitespace {
2759 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
2762 /// Split a string slice by ASCII whitespace.
2764 /// The iterator returned will return string slices that are sub-slices of
2765 /// the original string slice, separated by any amount of ASCII whitespace.
2767 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
2769 /// [`split_whitespace`]: #method.split_whitespace
2776 /// #![feature(split_ascii_whitespace)]
2777 /// let mut iter = "A few words".split_ascii_whitespace();
2779 /// assert_eq!(Some("A"), iter.next());
2780 /// assert_eq!(Some("few"), iter.next());
2781 /// assert_eq!(Some("words"), iter.next());
2783 /// assert_eq!(None, iter.next());
2786 /// All kinds of ASCII whitespace are considered:
2789 /// let mut iter = " Mary had\ta little \n\t lamb".split_whitespace();
2790 /// assert_eq!(Some("Mary"), iter.next());
2791 /// assert_eq!(Some("had"), iter.next());
2792 /// assert_eq!(Some("a"), iter.next());
2793 /// assert_eq!(Some("little"), iter.next());
2794 /// assert_eq!(Some("lamb"), iter.next());
2796 /// assert_eq!(None, iter.next());
2798 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
2800 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace {
2803 .split(IsAsciiWhitespace)
2805 .map(UnsafeBytesToStr);
2806 SplitAsciiWhitespace { inner }
2809 /// An iterator over the lines of a string, as string slices.
2811 /// Lines are ended with either a newline (`\n`) or a carriage return with
2812 /// a line feed (`\r\n`).
2814 /// The final line ending is optional.
2821 /// let text = "foo\r\nbar\n\nbaz\n";
2822 /// let mut lines = text.lines();
2824 /// assert_eq!(Some("foo"), lines.next());
2825 /// assert_eq!(Some("bar"), lines.next());
2826 /// assert_eq!(Some(""), lines.next());
2827 /// assert_eq!(Some("baz"), lines.next());
2829 /// assert_eq!(None, lines.next());
2832 /// The final line ending isn't required:
2835 /// let text = "foo\nbar\n\r\nbaz";
2836 /// let mut lines = text.lines();
2838 /// assert_eq!(Some("foo"), lines.next());
2839 /// assert_eq!(Some("bar"), lines.next());
2840 /// assert_eq!(Some(""), lines.next());
2841 /// assert_eq!(Some("baz"), lines.next());
2843 /// assert_eq!(None, lines.next());
2845 #[stable(feature = "rust1", since = "1.0.0")]
2847 pub fn lines(&self) -> Lines {
2848 Lines(self.split_terminator('\n').map(LinesAnyMap))
2851 /// An iterator over the lines of a string.
2852 #[stable(feature = "rust1", since = "1.0.0")]
2853 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
2855 #[allow(deprecated)]
2856 pub fn lines_any(&self) -> LinesAny {
2857 LinesAny(self.lines())
2860 /// Returns an iterator of `u16` over the string encoded as UTF-16.
2867 /// let text = "Zażółć gęślą jaźń";
2869 /// let utf8_len = text.len();
2870 /// let utf16_len = text.encode_utf16().count();
2872 /// assert!(utf16_len <= utf8_len);
2874 #[stable(feature = "encode_utf16", since = "1.8.0")]
2875 pub fn encode_utf16(&self) -> EncodeUtf16 {
2876 EncodeUtf16 { chars: self.chars(), extra: 0 }
2879 /// Returns `true` if the given pattern matches a sub-slice of
2880 /// this string slice.
2882 /// Returns `false` if it does not.
2889 /// let bananas = "bananas";
2891 /// assert!(bananas.contains("nana"));
2892 /// assert!(!bananas.contains("apples"));
2894 #[stable(feature = "rust1", since = "1.0.0")]
2896 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2897 pat.is_contained_in(self)
2900 /// Returns `true` if the given pattern matches a prefix of this
2903 /// Returns `false` if it does not.
2910 /// let bananas = "bananas";
2912 /// assert!(bananas.starts_with("bana"));
2913 /// assert!(!bananas.starts_with("nana"));
2915 #[stable(feature = "rust1", since = "1.0.0")]
2916 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2917 pat.is_prefix_of(self)
2920 /// Returns `true` if the given pattern matches a suffix of this
2923 /// Returns `false` if it does not.
2930 /// let bananas = "bananas";
2932 /// assert!(bananas.ends_with("anas"));
2933 /// assert!(!bananas.ends_with("nana"));
2935 #[stable(feature = "rust1", since = "1.0.0")]
2936 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
2937 where P::Searcher: ReverseSearcher<'a>
2939 pat.is_suffix_of(self)
2942 /// Returns the byte index of the first character of this string slice that
2943 /// matches the pattern.
2945 /// Returns [`None`] if the pattern doesn't match.
2947 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2948 /// a character matches.
2950 /// [`char`]: primitive.char.html
2951 /// [`None`]: option/enum.Option.html#variant.None
2955 /// Simple patterns:
2958 /// let s = "Löwe 老虎 Léopard";
2960 /// assert_eq!(s.find('L'), Some(0));
2961 /// assert_eq!(s.find('é'), Some(14));
2962 /// assert_eq!(s.find("Léopard"), Some(13));
2965 /// More complex patterns using point-free style and closures:
2968 /// let s = "Löwe 老虎 Léopard";
2970 /// assert_eq!(s.find(char::is_whitespace), Some(5));
2971 /// assert_eq!(s.find(char::is_lowercase), Some(1));
2972 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
2973 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
2976 /// Not finding the pattern:
2979 /// let s = "Löwe 老虎 Léopard";
2980 /// let x: &[_] = &['1', '2'];
2982 /// assert_eq!(s.find(x), None);
2984 #[stable(feature = "rust1", since = "1.0.0")]
2986 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2987 pat.into_searcher(self).next_match().map(|(i, _)| i)
2990 /// Returns the byte index of the last character of this string slice that
2991 /// matches the pattern.
2993 /// Returns [`None`] if the pattern doesn't match.
2995 /// The pattern can be a `&str`, [`char`], or a closure that determines if
2996 /// a character matches.
2998 /// [`char`]: primitive.char.html
2999 /// [`None`]: option/enum.Option.html#variant.None
3003 /// Simple patterns:
3006 /// let s = "Löwe 老虎 Léopard";
3008 /// assert_eq!(s.rfind('L'), Some(13));
3009 /// assert_eq!(s.rfind('é'), Some(14));
3012 /// More complex patterns with closures:
3015 /// let s = "Löwe 老虎 Léopard";
3017 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
3018 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
3021 /// Not finding the pattern:
3024 /// let s = "Löwe 老虎 Léopard";
3025 /// let x: &[_] = &['1', '2'];
3027 /// assert_eq!(s.rfind(x), None);
3029 #[stable(feature = "rust1", since = "1.0.0")]
3031 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
3032 where P::Searcher: ReverseSearcher<'a>
3034 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
3037 /// An iterator over substrings of this string slice, separated by
3038 /// characters matched by a pattern.
3040 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3043 /// # Iterator behavior
3045 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3046 /// allows a reverse search and forward/reverse search yields the same
3047 /// elements. This is true for, eg, [`char`] but not for `&str`.
3049 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3051 /// If the pattern allows a reverse search but its results might differ
3052 /// from a forward search, the [`rsplit`] method can be used.
3054 /// [`char`]: primitive.char.html
3055 /// [`rsplit`]: #method.rsplit
3059 /// Simple patterns:
3062 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
3063 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
3065 /// let v: Vec<&str> = "".split('X').collect();
3066 /// assert_eq!(v, [""]);
3068 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
3069 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
3071 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
3072 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3074 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
3075 /// assert_eq!(v, ["abc", "def", "ghi"]);
3077 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
3078 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3081 /// A more complex pattern, using a closure:
3084 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
3085 /// assert_eq!(v, ["abc", "def", "ghi"]);
3088 /// If a string contains multiple contiguous separators, you will end up
3089 /// with empty strings in the output:
3092 /// let x = "||||a||b|c".to_string();
3093 /// let d: Vec<_> = x.split('|').collect();
3095 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3098 /// Contiguous separators are separated by the empty string.
3101 /// let x = "(///)".to_string();
3102 /// let d: Vec<_> = x.split('/').collect();
3104 /// assert_eq!(d, &["(", "", "", ")"]);
3107 /// Separators at the start or end of a string are neighbored
3108 /// by empty strings.
3111 /// let d: Vec<_> = "010".split("0").collect();
3112 /// assert_eq!(d, &["", "1", ""]);
3115 /// When the empty string is used as a separator, it separates
3116 /// every character in the string, along with the beginning
3117 /// and end of the string.
3120 /// let f: Vec<_> = "rust".split("").collect();
3121 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
3124 /// Contiguous separators can lead to possibly surprising behavior
3125 /// when whitespace is used as the separator. This code is correct:
3128 /// let x = " a b c".to_string();
3129 /// let d: Vec<_> = x.split(' ').collect();
3131 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3134 /// It does _not_ give you:
3137 /// assert_eq!(d, &["a", "b", "c"]);
3140 /// Use [`split_whitespace`] for this behavior.
3142 /// [`split_whitespace`]: #method.split_whitespace
3143 #[stable(feature = "rust1", since = "1.0.0")]
3145 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
3146 Split(SplitInternal {
3149 matcher: pat.into_searcher(self),
3150 allow_trailing_empty: true,
3155 /// An iterator over substrings of the given string slice, separated by
3156 /// characters matched by a pattern and yielded in reverse order.
3158 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3161 /// [`char`]: primitive.char.html
3163 /// # Iterator behavior
3165 /// The returned iterator requires that the pattern supports a reverse
3166 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3167 /// search yields the same elements.
3169 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3171 /// For iterating from the front, the [`split`] method can be used.
3173 /// [`split`]: #method.split
3177 /// Simple patterns:
3180 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
3181 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
3183 /// let v: Vec<&str> = "".rsplit('X').collect();
3184 /// assert_eq!(v, [""]);
3186 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
3187 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
3189 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
3190 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
3193 /// A more complex pattern, using a closure:
3196 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
3197 /// assert_eq!(v, ["ghi", "def", "abc"]);
3199 #[stable(feature = "rust1", since = "1.0.0")]
3201 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
3202 where P::Searcher: ReverseSearcher<'a>
3204 RSplit(self.split(pat).0)
3207 /// An iterator over substrings of the given string slice, separated by
3208 /// characters matched by a pattern.
3210 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3213 /// Equivalent to [`split`], except that the trailing substring
3214 /// is skipped if empty.
3216 /// [`split`]: #method.split
3218 /// This method can be used for string data that is _terminated_,
3219 /// rather than _separated_ by a pattern.
3221 /// # Iterator behavior
3223 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3224 /// allows a reverse search and forward/reverse search yields the same
3225 /// elements. This is true for, eg, [`char`] but not for `&str`.
3227 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3228 /// [`char`]: primitive.char.html
3230 /// If the pattern allows a reverse search but its results might differ
3231 /// from a forward search, the [`rsplit_terminator`] method can be used.
3233 /// [`rsplit_terminator`]: #method.rsplit_terminator
3240 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
3241 /// assert_eq!(v, ["A", "B"]);
3243 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
3244 /// assert_eq!(v, ["A", "", "B", ""]);
3246 #[stable(feature = "rust1", since = "1.0.0")]
3248 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
3249 SplitTerminator(SplitInternal {
3250 allow_trailing_empty: false,
3255 /// An iterator over substrings of `self`, separated by characters
3256 /// matched by a pattern and yielded in reverse order.
3258 /// The pattern can be a simple `&str`, [`char`], or a closure that
3259 /// determines the split.
3260 /// Additional libraries might provide more complex patterns like
3261 /// regular expressions.
3263 /// [`char`]: primitive.char.html
3265 /// Equivalent to [`split`], except that the trailing substring is
3266 /// skipped if empty.
3268 /// [`split`]: #method.split
3270 /// This method can be used for string data that is _terminated_,
3271 /// rather than _separated_ by a pattern.
3273 /// # Iterator behavior
3275 /// The returned iterator requires that the pattern supports a
3276 /// reverse search, and it will be double ended if a forward/reverse
3277 /// search yields the same elements.
3279 /// For iterating from the front, the [`split_terminator`] method can be
3282 /// [`split_terminator`]: #method.split_terminator
3287 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
3288 /// assert_eq!(v, ["B", "A"]);
3290 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
3291 /// assert_eq!(v, ["", "B", "", "A"]);
3293 #[stable(feature = "rust1", since = "1.0.0")]
3295 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
3296 where P::Searcher: ReverseSearcher<'a>
3298 RSplitTerminator(self.split_terminator(pat).0)
3301 /// An iterator over substrings of the given string slice, separated by a
3302 /// pattern, restricted to returning at most `n` items.
3304 /// If `n` substrings are returned, the last substring (the `n`th substring)
3305 /// will contain the remainder of the string.
3307 /// The pattern can be a `&str`, [`char`], or a closure that determines the
3310 /// [`char`]: primitive.char.html
3312 /// # Iterator behavior
3314 /// The returned iterator will not be double ended, because it is
3315 /// not efficient to support.
3317 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
3320 /// [`rsplitn`]: #method.rsplitn
3324 /// Simple patterns:
3327 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
3328 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
3330 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
3331 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
3333 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
3334 /// assert_eq!(v, ["abcXdef"]);
3336 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
3337 /// assert_eq!(v, [""]);
3340 /// A more complex pattern, using a closure:
3343 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
3344 /// assert_eq!(v, ["abc", "defXghi"]);
3346 #[stable(feature = "rust1", since = "1.0.0")]
3348 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
3349 SplitN(SplitNInternal {
3350 iter: self.split(pat).0,
3355 /// An iterator over substrings of this string slice, separated by a
3356 /// pattern, starting from the end of the string, restricted to returning
3357 /// at most `n` items.
3359 /// If `n` substrings are returned, the last substring (the `n`th substring)
3360 /// will contain the remainder of the string.
3362 /// The pattern can be a `&str`, [`char`], or a closure that
3363 /// determines the split.
3365 /// [`char`]: primitive.char.html
3367 /// # Iterator behavior
3369 /// The returned iterator will not be double ended, because it is not
3370 /// efficient to support.
3372 /// For splitting from the front, the [`splitn`] method can be used.
3374 /// [`splitn`]: #method.splitn
3378 /// Simple patterns:
3381 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
3382 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
3384 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
3385 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
3387 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
3388 /// assert_eq!(v, ["leopard", "lion::tiger"]);
3391 /// A more complex pattern, using a closure:
3394 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
3395 /// assert_eq!(v, ["ghi", "abc1def"]);
3397 #[stable(feature = "rust1", since = "1.0.0")]
3399 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
3400 where P::Searcher: ReverseSearcher<'a>
3402 RSplitN(self.splitn(n, pat).0)
3405 /// An iterator over the disjoint matches of a pattern within the given string
3408 /// The pattern can be a `&str`, [`char`], or a closure that
3409 /// determines if a character matches.
3411 /// [`char`]: primitive.char.html
3413 /// # Iterator behavior
3415 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3416 /// allows a reverse search and forward/reverse search yields the same
3417 /// elements. This is true for, eg, [`char`] but not for `&str`.
3419 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3420 /// [`char`]: primitive.char.html
3422 /// If the pattern allows a reverse search but its results might differ
3423 /// from a forward search, the [`rmatches`] method can be used.
3425 /// [`rmatches`]: #method.rmatches
3432 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
3433 /// assert_eq!(v, ["abc", "abc", "abc"]);
3435 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
3436 /// assert_eq!(v, ["1", "2", "3"]);
3438 #[stable(feature = "str_matches", since = "1.2.0")]
3440 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
3441 Matches(MatchesInternal(pat.into_searcher(self)))
3444 /// An iterator over the disjoint matches of a pattern within this string slice,
3445 /// yielded in reverse order.
3447 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3448 /// a character matches.
3450 /// [`char`]: primitive.char.html
3452 /// # Iterator behavior
3454 /// The returned iterator requires that the pattern supports a reverse
3455 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3456 /// search yields the same elements.
3458 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3460 /// For iterating from the front, the [`matches`] method can be used.
3462 /// [`matches`]: #method.matches
3469 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
3470 /// assert_eq!(v, ["abc", "abc", "abc"]);
3472 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
3473 /// assert_eq!(v, ["3", "2", "1"]);
3475 #[stable(feature = "str_matches", since = "1.2.0")]
3477 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
3478 where P::Searcher: ReverseSearcher<'a>
3480 RMatches(self.matches(pat).0)
3483 /// An iterator over the disjoint matches of a pattern within this string
3484 /// slice as well as the index that the match starts at.
3486 /// For matches of `pat` within `self` that overlap, only the indices
3487 /// corresponding to the first match are returned.
3489 /// The pattern can be a `&str`, [`char`], or a closure that determines
3490 /// if a character matches.
3492 /// [`char`]: primitive.char.html
3494 /// # Iterator behavior
3496 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3497 /// allows a reverse search and forward/reverse search yields the same
3498 /// elements. This is true for, eg, [`char`] but not for `&str`.
3500 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3502 /// If the pattern allows a reverse search but its results might differ
3503 /// from a forward search, the [`rmatch_indices`] method can be used.
3505 /// [`rmatch_indices`]: #method.rmatch_indices
3512 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
3513 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
3515 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
3516 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
3518 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
3519 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
3521 #[stable(feature = "str_match_indices", since = "1.5.0")]
3523 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
3524 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
3527 /// An iterator over the disjoint matches of a pattern within `self`,
3528 /// yielded in reverse order along with the index of the match.
3530 /// For matches of `pat` within `self` that overlap, only the indices
3531 /// corresponding to the last match are returned.
3533 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
3534 /// character matches.
3536 /// [`char`]: primitive.char.html
3538 /// # Iterator behavior
3540 /// The returned iterator requires that the pattern supports a reverse
3541 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3542 /// search yields the same elements.
3544 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3546 /// For iterating from the front, the [`match_indices`] method can be used.
3548 /// [`match_indices`]: #method.match_indices
3555 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
3556 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
3558 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
3559 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
3561 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
3562 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
3564 #[stable(feature = "str_match_indices", since = "1.5.0")]
3566 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
3567 where P::Searcher: ReverseSearcher<'a>
3569 RMatchIndices(self.match_indices(pat).0)
3572 /// Returns a string slice with leading and trailing whitespace removed.
3574 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3575 /// Core Property `White_Space`.
3582 /// let s = " Hello\tworld\t";
3584 /// assert_eq!("Hello\tworld", s.trim());
3586 #[stable(feature = "rust1", since = "1.0.0")]
3587 pub fn trim(&self) -> &str {
3588 self.trim_matches(|c: char| c.is_whitespace())
3591 /// Returns a string slice with leading whitespace removed.
3593 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3594 /// Core Property `White_Space`.
3596 /// # Text directionality
3598 /// A string is a sequence of bytes. 'Left' in this context means the first
3599 /// position of that byte string; for a language like Arabic or Hebrew
3600 /// which are 'right to left' rather than 'left to right', this will be
3601 /// the _right_ side, not the left.
3608 /// let s = " Hello\tworld\t";
3610 /// assert_eq!("Hello\tworld\t", s.trim_left());
3616 /// let s = " English";
3617 /// assert!(Some('E') == s.trim_left().chars().next());
3619 /// let s = " עברית";
3620 /// assert!(Some('ע') == s.trim_left().chars().next());
3622 #[stable(feature = "rust1", since = "1.0.0")]
3623 pub fn trim_left(&self) -> &str {
3624 self.trim_left_matches(|c: char| c.is_whitespace())
3627 /// Returns a string slice with trailing whitespace removed.
3629 /// 'Whitespace' is defined according to the terms of the Unicode Derived
3630 /// Core Property `White_Space`.
3632 /// # Text directionality
3634 /// A string is a sequence of bytes. 'Right' in this context means the last
3635 /// position of that byte string; for a language like Arabic or Hebrew
3636 /// which are 'right to left' rather than 'left to right', this will be
3637 /// the _left_ side, not the right.
3644 /// let s = " Hello\tworld\t";
3646 /// assert_eq!(" Hello\tworld", s.trim_right());
3652 /// let s = "English ";
3653 /// assert!(Some('h') == s.trim_right().chars().rev().next());
3655 /// let s = "עברית ";
3656 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
3658 #[stable(feature = "rust1", since = "1.0.0")]
3659 pub fn trim_right(&self) -> &str {
3660 self.trim_right_matches(|c: char| c.is_whitespace())
3663 /// Returns a string slice with all prefixes and suffixes that match a
3664 /// pattern repeatedly removed.
3666 /// The pattern can be a [`char`] or a closure that determines if a
3667 /// character matches.
3669 /// [`char`]: primitive.char.html
3673 /// Simple patterns:
3676 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
3677 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
3679 /// let x: &[_] = &['1', '2'];
3680 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
3683 /// A more complex pattern, using a closure:
3686 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
3688 #[stable(feature = "rust1", since = "1.0.0")]
3689 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3690 where P::Searcher: DoubleEndedSearcher<'a>
3694 let mut matcher = pat.into_searcher(self);
3695 if let Some((a, b)) = matcher.next_reject() {
3697 j = b; // Remember earliest known match, correct it below if
3698 // last match is different
3700 if let Some((_, b)) = matcher.next_reject_back() {
3704 // Searcher is known to return valid indices
3705 self.slice_unchecked(i, j)
3709 /// Returns a string slice with all prefixes that match a pattern
3710 /// repeatedly removed.
3712 /// The pattern can be a `&str`, [`char`], or a closure that determines if
3713 /// a character matches.
3715 /// [`char`]: primitive.char.html
3717 /// # Text directionality
3719 /// A string is a sequence of bytes. 'Left' in this context means the first
3720 /// position of that byte string; for a language like Arabic or Hebrew
3721 /// which are 'right to left' rather than 'left to right', this will be
3722 /// the _right_ side, not the left.
3729 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
3730 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
3732 /// let x: &[_] = &['1', '2'];
3733 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
3735 #[stable(feature = "rust1", since = "1.0.0")]
3736 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3737 let mut i = self.len();
3738 let mut matcher = pat.into_searcher(self);
3739 if let Some((a, _)) = matcher.next_reject() {
3743 // Searcher is known to return valid indices
3744 self.slice_unchecked(i, self.len())
3748 /// Returns a string slice with all suffixes that match a pattern
3749 /// repeatedly removed.
3751 /// The pattern can be a `&str`, [`char`], or a closure that
3752 /// determines if a character matches.
3754 /// [`char`]: primitive.char.html
3756 /// # Text directionality
3758 /// A string is a sequence of bytes. 'Right' in this context means the last
3759 /// position of that byte string; for a language like Arabic or Hebrew
3760 /// which are 'right to left' rather than 'left to right', this will be
3761 /// the _left_ side, not the right.
3765 /// Simple patterns:
3768 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
3769 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
3771 /// let x: &[_] = &['1', '2'];
3772 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
3775 /// A more complex pattern, using a closure:
3778 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
3780 #[stable(feature = "rust1", since = "1.0.0")]
3781 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3782 where P::Searcher: ReverseSearcher<'a>
3785 let mut matcher = pat.into_searcher(self);
3786 if let Some((_, b)) = matcher.next_reject_back() {
3790 // Searcher is known to return valid indices
3791 self.slice_unchecked(0, j)
3795 /// Parses this string slice into another type.
3797 /// Because `parse` is so general, it can cause problems with type
3798 /// inference. As such, `parse` is one of the few times you'll see
3799 /// the syntax affectionately known as the 'turbofish': `::<>`. This
3800 /// helps the inference algorithm understand specifically which type
3801 /// you're trying to parse into.
3803 /// `parse` can parse any type that implements the [`FromStr`] trait.
3805 /// [`FromStr`]: str/trait.FromStr.html
3809 /// Will return [`Err`] if it's not possible to parse this string slice into
3810 /// the desired type.
3812 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
3819 /// let four: u32 = "4".parse().unwrap();
3821 /// assert_eq!(4, four);
3824 /// Using the 'turbofish' instead of annotating `four`:
3827 /// let four = "4".parse::<u32>();
3829 /// assert_eq!(Ok(4), four);
3832 /// Failing to parse:
3835 /// let nope = "j".parse::<u32>();
3837 /// assert!(nope.is_err());
3840 #[stable(feature = "rust1", since = "1.0.0")]
3841 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
3842 FromStr::from_str(self)
3845 /// Checks if all characters in this string are within the ASCII range.
3850 /// let ascii = "hello!\n";
3851 /// let non_ascii = "Grüße, Jürgen ❤";
3853 /// assert!(ascii.is_ascii());
3854 /// assert!(!non_ascii.is_ascii());
3856 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3858 pub fn is_ascii(&self) -> bool {
3859 // We can treat each byte as character here: all multibyte characters
3860 // start with a byte that is not in the ascii range, so we will stop
3862 self.bytes().all(|b| b.is_ascii())
3865 /// Checks that two strings are an ASCII case-insensitive match.
3867 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
3868 /// but without allocating and copying temporaries.
3873 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
3874 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
3875 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
3877 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3879 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
3880 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
3883 /// Converts this string to its ASCII upper case equivalent in-place.
3885 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3886 /// but non-ASCII letters are unchanged.
3888 /// To return a new uppercased value without modifying the existing one, use
3889 /// [`to_ascii_uppercase`].
3891 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3892 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3893 pub fn make_ascii_uppercase(&mut self) {
3894 let me = unsafe { self.as_bytes_mut() };
3895 me.make_ascii_uppercase()
3898 /// Converts this string to its ASCII lower case equivalent in-place.
3900 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3901 /// but non-ASCII letters are unchanged.
3903 /// To return a new lowercased value without modifying the existing one, use
3904 /// [`to_ascii_lowercase`].
3906 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3907 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3908 pub fn make_ascii_lowercase(&mut self) {
3909 let me = unsafe { self.as_bytes_mut() };
3910 me.make_ascii_lowercase()
3914 #[stable(feature = "rust1", since = "1.0.0")]
3915 impl AsRef<[u8]> for str {
3917 fn as_ref(&self) -> &[u8] {
3922 #[stable(feature = "rust1", since = "1.0.0")]
3923 impl<'a> Default for &'a str {
3924 /// Creates an empty str
3925 fn default() -> &'a str { "" }
3928 #[stable(feature = "default_mut_str", since = "1.28.0")]
3929 impl<'a> Default for &'a mut str {
3930 /// Creates an empty mutable str
3931 fn default() -> &'a mut str { unsafe { from_utf8_unchecked_mut(&mut []) } }
3934 /// An iterator over the non-whitespace substrings of a string,
3935 /// separated by any amount of whitespace.
3937 /// This struct is created by the [`split_whitespace`] method on [`str`].
3938 /// See its documentation for more.
3940 /// [`split_whitespace`]: ../../std/primitive.str.html#method.split_whitespace
3941 /// [`str`]: ../../std/primitive.str.html
3942 #[stable(feature = "split_whitespace", since = "1.1.0")]
3943 #[derive(Clone, Debug)]
3944 pub struct SplitWhitespace<'a> {
3945 inner: Filter<Split<'a, IsWhitespace>, IsNotEmpty>,
3948 /// An iterator over the non-ASCII-whitespace substrings of a string,
3949 /// separated by any amount of ASCII whitespace.
3951 /// This struct is created by the [`split_ascii_whitespace`] method on [`str`].
3952 /// See its documentation for more.
3954 /// [`split_ascii_whitespace`]: ../../std/primitive.str.html#method.split_ascii_whitespace
3955 /// [`str`]: ../../std/primitive.str.html
3956 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
3957 #[derive(Clone, Debug)]
3958 pub struct SplitAsciiWhitespace<'a> {
3959 inner: Map<Filter<SliceSplit<'a, u8, IsAsciiWhitespace>, IsNotEmpty>, UnsafeBytesToStr>,
3963 struct IsWhitespace;
3965 impl FnOnce<(char, )> for IsWhitespace {
3969 extern "rust-call" fn call_once(mut self, arg: (char, )) -> bool {
3974 impl FnMut<(char, )> for IsWhitespace {
3976 extern "rust-call" fn call_mut(&mut self, arg: (char, )) -> bool {
3977 arg.0.is_whitespace()
3982 struct IsAsciiWhitespace;
3984 impl<'a> FnOnce<(&'a u8, )> for IsAsciiWhitespace {
3988 extern "rust-call" fn call_once(mut self, arg: (&u8, )) -> bool {
3993 impl<'a> FnMut<(&'a u8, )> for IsAsciiWhitespace {
3995 extern "rust-call" fn call_mut(&mut self, arg: (&u8, )) -> bool {
3996 arg.0.is_ascii_whitespace()
4003 impl<'a, 'b> FnOnce<(&'a &'b str, )> for IsNotEmpty {
4007 extern "rust-call" fn call_once(mut self, arg: (&'a &'b str, )) -> bool {
4012 impl<'a, 'b> FnMut<(&'a &'b str, )> for IsNotEmpty {
4014 extern "rust-call" fn call_mut(&mut self, arg: (&'a &'b str, )) -> bool {
4019 impl<'a, 'b> FnOnce<(&'a &'b [u8], )> for IsNotEmpty {
4023 extern "rust-call" fn call_once(mut self, arg: (&'a &'b [u8], )) -> bool {
4028 impl<'a, 'b> FnMut<(&'a &'b [u8], )> for IsNotEmpty {
4030 extern "rust-call" fn call_mut(&mut self, arg: (&'a &'b [u8], )) -> bool {
4036 struct UnsafeBytesToStr;
4038 impl<'a> FnOnce<(&'a [u8], )> for UnsafeBytesToStr {
4039 type Output = &'a str;
4042 extern "rust-call" fn call_once(mut self, arg: (&'a [u8], )) -> &'a str {
4047 impl<'a> FnMut<(&'a [u8], )> for UnsafeBytesToStr {
4049 extern "rust-call" fn call_mut(&mut self, arg: (&'a [u8], )) -> &'a str {
4050 unsafe { from_utf8_unchecked(arg.0) }
4055 #[stable(feature = "split_whitespace", since = "1.1.0")]
4056 impl<'a> Iterator for SplitWhitespace<'a> {
4057 type Item = &'a str;
4060 fn next(&mut self) -> Option<&'a str> {
4065 fn size_hint(&self) -> (usize, Option<usize>) {
4066 self.inner.size_hint()
4070 #[stable(feature = "split_whitespace", since = "1.1.0")]
4071 impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
4073 fn next_back(&mut self) -> Option<&'a str> {
4074 self.inner.next_back()
4078 #[stable(feature = "fused", since = "1.26.0")]
4079 impl<'a> FusedIterator for SplitWhitespace<'a> {}
4081 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
4082 impl<'a> Iterator for SplitAsciiWhitespace<'a> {
4083 type Item = &'a str;
4086 fn next(&mut self) -> Option<&'a str> {
4091 fn size_hint(&self) -> (usize, Option<usize>) {
4092 self.inner.size_hint()
4096 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
4097 impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> {
4099 fn next_back(&mut self) -> Option<&'a str> {
4100 self.inner.next_back()
4104 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
4105 impl<'a> FusedIterator for SplitAsciiWhitespace<'a> {}
4107 /// An iterator of [`u16`] over the string encoded as UTF-16.
4109 /// [`u16`]: ../../std/primitive.u16.html
4111 /// This struct is created by the [`encode_utf16`] method on [`str`].
4112 /// See its documentation for more.
4114 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
4115 /// [`str`]: ../../std/primitive.str.html
4117 #[stable(feature = "encode_utf16", since = "1.8.0")]
4118 pub struct EncodeUtf16<'a> {
4123 #[stable(feature = "collection_debug", since = "1.17.0")]
4124 impl<'a> fmt::Debug for EncodeUtf16<'a> {
4125 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4126 f.pad("EncodeUtf16 { .. }")
4130 #[stable(feature = "encode_utf16", since = "1.8.0")]
4131 impl<'a> Iterator for EncodeUtf16<'a> {
4135 fn next(&mut self) -> Option<u16> {
4136 if self.extra != 0 {
4137 let tmp = self.extra;
4142 let mut buf = [0; 2];
4143 self.chars.next().map(|ch| {
4144 let n = ch.encode_utf16(&mut buf).len();
4146 self.extra = buf[1];
4153 fn size_hint(&self) -> (usize, Option<usize>) {
4154 let (low, high) = self.chars.size_hint();
4155 // every char gets either one u16 or two u16,
4156 // so this iterator is between 1 or 2 times as
4157 // long as the underlying iterator.
4158 (low, high.and_then(|n| n.checked_mul(2)))
4162 #[stable(feature = "fused", since = "1.26.0")]
4163 impl<'a> FusedIterator for EncodeUtf16<'a> {}