]> git.lizzy.rs Git - rust.git/blob - src/libcore/str/mod.rs
Auto merge of #63089 - kennytm:use-try-run-for-linkchecker, r=Mark-Simulacrum
[rust.git] / src / libcore / str / mod.rs
1 // ignore-tidy-filelength
2
3 //! String manipulation.
4 //!
5 //! For more details, see the `std::str` module.
6
7 #![stable(feature = "rust1", since = "1.0.0")]
8
9 use self::pattern::Pattern;
10 use self::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
11
12 use crate::char;
13 use crate::fmt::{self, Write};
14 use crate::iter::{Map, Cloned, FusedIterator, TrustedLen, TrustedRandomAccess, Filter};
15 use crate::iter::{Flatten, FlatMap, Chain};
16 use crate::slice::{self, SliceIndex, Split as SliceSplit};
17 use crate::mem;
18 use crate::ops::Try;
19 use crate::option;
20
21 pub mod pattern;
22
23 #[unstable(feature = "str_internals", issue = "0")]
24 #[allow(missing_docs)]
25 pub mod lossy;
26
27 /// Parse a value from a string
28 ///
29 /// `FromStr`'s [`from_str`] method is often used implicitly, through
30 /// [`str`]'s [`parse`] method. See [`parse`]'s documentation for examples.
31 ///
32 /// [`from_str`]: #tymethod.from_str
33 /// [`str`]: ../../std/primitive.str.html
34 /// [`parse`]: ../../std/primitive.str.html#method.parse
35 ///
36 /// `FromStr` does not have a lifetime parameter, and so you can only parse types
37 /// that do not contain a lifetime parameter themselves. In other words, you can
38 /// parse an `i32` with `FromStr`, but not a `&i32`. You can parse a struct that
39 /// contains an `i32`, but not one that contains an `&i32`.
40 ///
41 /// # Examples
42 ///
43 /// Basic implementation of `FromStr` on an example `Point` type:
44 ///
45 /// ```
46 /// use std::str::FromStr;
47 /// use std::num::ParseIntError;
48 ///
49 /// #[derive(Debug, PartialEq)]
50 /// struct Point {
51 ///     x: i32,
52 ///     y: i32
53 /// }
54 ///
55 /// impl FromStr for Point {
56 ///     type Err = ParseIntError;
57 ///
58 ///     fn from_str(s: &str) -> Result<Self, Self::Err> {
59 ///         let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
60 ///                                  .split(',')
61 ///                                  .collect();
62 ///
63 ///         let x_fromstr = coords[0].parse::<i32>()?;
64 ///         let y_fromstr = coords[1].parse::<i32>()?;
65 ///
66 ///         Ok(Point { x: x_fromstr, y: y_fromstr })
67 ///     }
68 /// }
69 ///
70 /// let p = Point::from_str("(1,2)");
71 /// assert_eq!(p.unwrap(), Point{ x: 1, y: 2} )
72 /// ```
73 #[stable(feature = "rust1", since = "1.0.0")]
74 pub trait FromStr: Sized {
75     /// The associated error which can be returned from parsing.
76     #[stable(feature = "rust1", since = "1.0.0")]
77     type Err;
78
79     /// Parses a string `s` to return a value of this type.
80     ///
81     /// If parsing succeeds, return the value inside [`Ok`], otherwise
82     /// when the string is ill-formatted return an error specific to the
83     /// inside [`Err`]. The error type is specific to implementation of the trait.
84     ///
85     /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
86     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
87     ///
88     /// # Examples
89     ///
90     /// Basic usage with [`i32`][ithirtytwo], a type that implements `FromStr`:
91     ///
92     /// [ithirtytwo]: ../../std/primitive.i32.html
93     ///
94     /// ```
95     /// use std::str::FromStr;
96     ///
97     /// let s = "5";
98     /// let x = i32::from_str(s).unwrap();
99     ///
100     /// assert_eq!(5, x);
101     /// ```
102     #[stable(feature = "rust1", since = "1.0.0")]
103     fn from_str(s: &str) -> Result<Self, Self::Err>;
104 }
105
106 #[stable(feature = "rust1", since = "1.0.0")]
107 impl FromStr for bool {
108     type Err = ParseBoolError;
109
110     /// Parse a `bool` from a string.
111     ///
112     /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
113     /// actually be parseable.
114     ///
115     /// # Examples
116     ///
117     /// ```
118     /// use std::str::FromStr;
119     ///
120     /// assert_eq!(FromStr::from_str("true"), Ok(true));
121     /// assert_eq!(FromStr::from_str("false"), Ok(false));
122     /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
123     /// ```
124     ///
125     /// Note, in many cases, the `.parse()` method on `str` is more proper.
126     ///
127     /// ```
128     /// assert_eq!("true".parse(), Ok(true));
129     /// assert_eq!("false".parse(), Ok(false));
130     /// assert!("not even a boolean".parse::<bool>().is_err());
131     /// ```
132     #[inline]
133     fn from_str(s: &str) -> Result<bool, ParseBoolError> {
134         match s {
135             "true"  => Ok(true),
136             "false" => Ok(false),
137             _       => Err(ParseBoolError { _priv: () }),
138         }
139     }
140 }
141
142 /// An error returned when parsing a `bool` using [`from_str`] fails
143 ///
144 /// [`from_str`]: ../../std/primitive.bool.html#method.from_str
145 #[derive(Debug, Clone, PartialEq, Eq)]
146 #[stable(feature = "rust1", since = "1.0.0")]
147 pub struct ParseBoolError { _priv: () }
148
149 #[stable(feature = "rust1", since = "1.0.0")]
150 impl fmt::Display for ParseBoolError {
151     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152         "provided string was not `true` or `false`".fmt(f)
153     }
154 }
155
156 /*
157 Section: Creating a string
158 */
159
160 /// Errors which can occur when attempting to interpret a sequence of [`u8`]
161 /// as a string.
162 ///
163 /// [`u8`]: ../../std/primitive.u8.html
164 ///
165 /// As such, the `from_utf8` family of functions and methods for both [`String`]s
166 /// and [`&str`]s make use of this error, for example.
167 ///
168 /// [`String`]: ../../std/string/struct.String.html#method.from_utf8
169 /// [`&str`]: ../../std/str/fn.from_utf8.html
170 ///
171 /// # Examples
172 ///
173 /// This error type’s methods can be used to create functionality
174 /// similar to `String::from_utf8_lossy` without allocating heap memory:
175 ///
176 /// ```
177 /// fn from_utf8_lossy<F>(mut input: &[u8], mut push: F) where F: FnMut(&str) {
178 ///     loop {
179 ///         match ::std::str::from_utf8(input) {
180 ///             Ok(valid) => {
181 ///                 push(valid);
182 ///                 break
183 ///             }
184 ///             Err(error) => {
185 ///                 let (valid, after_valid) = input.split_at(error.valid_up_to());
186 ///                 unsafe {
187 ///                     push(::std::str::from_utf8_unchecked(valid))
188 ///                 }
189 ///                 push("\u{FFFD}");
190 ///
191 ///                 if let Some(invalid_sequence_length) = error.error_len() {
192 ///                     input = &after_valid[invalid_sequence_length..]
193 ///                 } else {
194 ///                     break
195 ///                 }
196 ///             }
197 ///         }
198 ///     }
199 /// }
200 /// ```
201 #[derive(Copy, Eq, PartialEq, Clone, Debug)]
202 #[stable(feature = "rust1", since = "1.0.0")]
203 pub struct Utf8Error {
204     valid_up_to: usize,
205     error_len: Option<u8>,
206 }
207
208 impl Utf8Error {
209     /// Returns the index in the given string up to which valid UTF-8 was
210     /// verified.
211     ///
212     /// It is the maximum index such that `from_utf8(&input[..index])`
213     /// would return `Ok(_)`.
214     ///
215     /// # Examples
216     ///
217     /// Basic usage:
218     ///
219     /// ```
220     /// use std::str;
221     ///
222     /// // some invalid bytes, in a vector
223     /// let sparkle_heart = vec![0, 159, 146, 150];
224     ///
225     /// // std::str::from_utf8 returns a Utf8Error
226     /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
227     ///
228     /// // the second byte is invalid here
229     /// assert_eq!(1, error.valid_up_to());
230     /// ```
231     #[stable(feature = "utf8_error", since = "1.5.0")]
232     pub fn valid_up_to(&self) -> usize { self.valid_up_to }
233
234     /// Provides more information about the failure:
235     ///
236     /// * `None`: the end of the input was reached unexpectedly.
237     ///   `self.valid_up_to()` is 1 to 3 bytes from the end of the input.
238     ///   If a byte stream (such as a file or a network socket) is being decoded incrementally,
239     ///   this could be a valid `char` whose UTF-8 byte sequence is spanning multiple chunks.
240     ///
241     /// * `Some(len)`: an unexpected byte was encountered.
242     ///   The length provided is that of the invalid byte sequence
243     ///   that starts at the index given by `valid_up_to()`.
244     ///   Decoding should resume after that sequence
245     ///   (after inserting a [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD]) in case of
246     ///   lossy decoding.
247     ///
248     /// [U+FFFD]: ../../std/char/constant.REPLACEMENT_CHARACTER.html
249     #[stable(feature = "utf8_error_error_len", since = "1.20.0")]
250     pub fn error_len(&self) -> Option<usize> {
251         self.error_len.map(|len| len as usize)
252     }
253 }
254
255 /// Converts a slice of bytes to a string slice.
256 ///
257 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
258 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
259 /// the two. Not all byte slices are valid string slices, however: [`&str`] requires
260 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
261 /// UTF-8, and then does the conversion.
262 ///
263 /// [`&str`]: ../../std/primitive.str.html
264 /// [`u8`]: ../../std/primitive.u8.html
265 /// [byteslice]: ../../std/primitive.slice.html
266 ///
267 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
268 /// incur the overhead of the validity check, there is an unsafe version of
269 /// this function, [`from_utf8_unchecked`][fromutf8u], which has the same
270 /// behavior but skips the check.
271 ///
272 /// [fromutf8u]: fn.from_utf8_unchecked.html
273 ///
274 /// If you need a `String` instead of a `&str`, consider
275 /// [`String::from_utf8`][string].
276 ///
277 /// [string]: ../../std/string/struct.String.html#method.from_utf8
278 ///
279 /// Because you can stack-allocate a `[u8; N]`, and you can take a
280 /// [`&[u8]`][byteslice] of it, this function is one way to have a
281 /// stack-allocated string. There is an example of this in the
282 /// examples section below.
283 ///
284 /// [byteslice]: ../../std/primitive.slice.html
285 ///
286 /// # Errors
287 ///
288 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
289 /// provided slice is not UTF-8.
290 ///
291 /// # Examples
292 ///
293 /// Basic usage:
294 ///
295 /// ```
296 /// use std::str;
297 ///
298 /// // some bytes, in a vector
299 /// let sparkle_heart = vec![240, 159, 146, 150];
300 ///
301 /// // We know these bytes are valid, so just use `unwrap()`.
302 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
303 ///
304 /// assert_eq!("💖", sparkle_heart);
305 /// ```
306 ///
307 /// Incorrect bytes:
308 ///
309 /// ```
310 /// use std::str;
311 ///
312 /// // some invalid bytes, in a vector
313 /// let sparkle_heart = vec![0, 159, 146, 150];
314 ///
315 /// assert!(str::from_utf8(&sparkle_heart).is_err());
316 /// ```
317 ///
318 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
319 /// errors that can be returned.
320 ///
321 /// [error]: struct.Utf8Error.html
322 ///
323 /// A "stack allocated string":
324 ///
325 /// ```
326 /// use std::str;
327 ///
328 /// // some bytes, in a stack-allocated array
329 /// let sparkle_heart = [240, 159, 146, 150];
330 ///
331 /// // We know these bytes are valid, so just use `unwrap()`.
332 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
333 ///
334 /// assert_eq!("💖", sparkle_heart);
335 /// ```
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
338     run_utf8_validation(v)?;
339     Ok(unsafe { from_utf8_unchecked(v) })
340 }
341
342 /// Converts a mutable slice of bytes to a mutable string slice.
343 ///
344 /// # Examples
345 ///
346 /// Basic usage:
347 ///
348 /// ```
349 /// use std::str;
350 ///
351 /// // "Hello, Rust!" as a mutable vector
352 /// let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
353 ///
354 /// // As we know these bytes are valid, we can use `unwrap()`
355 /// let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
356 ///
357 /// assert_eq!("Hello, Rust!", outstr);
358 /// ```
359 ///
360 /// Incorrect bytes:
361 ///
362 /// ```
363 /// use std::str;
364 ///
365 /// // Some invalid bytes in a mutable vector
366 /// let mut invalid = vec![128, 223];
367 ///
368 /// assert!(str::from_utf8_mut(&mut invalid).is_err());
369 /// ```
370 /// See the docs for [`Utf8Error`][error] for more details on the kinds of
371 /// errors that can be returned.
372 ///
373 /// [error]: struct.Utf8Error.html
374 #[stable(feature = "str_mut_extras", since = "1.20.0")]
375 pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
376     run_utf8_validation(v)?;
377     Ok(unsafe { from_utf8_unchecked_mut(v) })
378 }
379
380 /// Converts a slice of bytes to a string slice without checking
381 /// that the string contains valid UTF-8.
382 ///
383 /// See the safe version, [`from_utf8`][fromutf8], for more information.
384 ///
385 /// [fromutf8]: fn.from_utf8.html
386 ///
387 /// # Safety
388 ///
389 /// This function is unsafe because it does not check that the bytes passed to
390 /// it are valid UTF-8. If this constraint is violated, undefined behavior
391 /// results, as the rest of Rust assumes that [`&str`]s are valid UTF-8.
392 ///
393 /// [`&str`]: ../../std/primitive.str.html
394 ///
395 /// # Examples
396 ///
397 /// Basic usage:
398 ///
399 /// ```
400 /// use std::str;
401 ///
402 /// // some bytes, in a vector
403 /// let sparkle_heart = vec![240, 159, 146, 150];
404 ///
405 /// let sparkle_heart = unsafe {
406 ///     str::from_utf8_unchecked(&sparkle_heart)
407 /// };
408 ///
409 /// assert_eq!("💖", sparkle_heart);
410 /// ```
411 #[inline]
412 #[stable(feature = "rust1", since = "1.0.0")]
413 pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
414     &*(v as *const [u8] as *const str)
415 }
416
417 /// Converts a slice of bytes to a string slice without checking
418 /// that the string contains valid UTF-8; mutable version.
419 ///
420 /// See the immutable version, [`from_utf8_unchecked()`][fromutf8], for more information.
421 ///
422 /// [fromutf8]: fn.from_utf8_unchecked.html
423 ///
424 /// # Examples
425 ///
426 /// Basic usage:
427 ///
428 /// ```
429 /// use std::str;
430 ///
431 /// let mut heart = vec![240, 159, 146, 150];
432 /// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
433 ///
434 /// assert_eq!("💖", heart);
435 /// ```
436 #[inline]
437 #[stable(feature = "str_mut_extras", since = "1.20.0")]
438 pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
439     &mut *(v as *mut [u8] as *mut str)
440 }
441
442 #[stable(feature = "rust1", since = "1.0.0")]
443 impl fmt::Display for Utf8Error {
444     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445         if let Some(error_len) = self.error_len {
446             write!(f, "invalid utf-8 sequence of {} bytes from index {}",
447                    error_len, self.valid_up_to)
448         } else {
449             write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to)
450         }
451     }
452 }
453
454 /*
455 Section: Iterators
456 */
457
458 /// An iterator over the [`char`]s of a string slice.
459 ///
460 /// [`char`]: ../../std/primitive.char.html
461 ///
462 /// This struct is created by the [`chars`] method on [`str`].
463 /// See its documentation for more.
464 ///
465 /// [`chars`]: ../../std/primitive.str.html#method.chars
466 /// [`str`]: ../../std/primitive.str.html
467 #[derive(Clone, Debug)]
468 #[stable(feature = "rust1", since = "1.0.0")]
469 pub struct Chars<'a> {
470     iter: slice::Iter<'a, u8>
471 }
472
473 /// Returns the initial codepoint accumulator for the first byte.
474 /// The first byte is special, only want bottom 5 bits for width 2, 4 bits
475 /// for width 3, and 3 bits for width 4.
476 #[inline]
477 fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
478
479 /// Returns the value of `ch` updated with continuation byte `byte`.
480 #[inline]
481 fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
482
483 /// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the
484 /// bits `10`).
485 #[inline]
486 fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
487
488 #[inline]
489 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
490     match opt {
491         Some(&byte) => byte,
492         None => 0,
493     }
494 }
495
496 /// Reads the next code point out of a byte iterator (assuming a
497 /// UTF-8-like encoding).
498 #[unstable(feature = "str_internals", issue = "0")]
499 #[inline]
500 pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
501     // Decode UTF-8
502     let x = *bytes.next()?;
503     if x < 128 {
504         return Some(x as u32)
505     }
506
507     // Multibyte case follows
508     // Decode from a byte combination out of: [[[x y] z] w]
509     // NOTE: Performance is sensitive to the exact formulation here
510     let init = utf8_first_byte(x, 2);
511     let y = unwrap_or_0(bytes.next());
512     let mut ch = utf8_acc_cont_byte(init, y);
513     if x >= 0xE0 {
514         // [[x y z] w] case
515         // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
516         let z = unwrap_or_0(bytes.next());
517         let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
518         ch = init << 12 | y_z;
519         if x >= 0xF0 {
520             // [x y z w] case
521             // use only the lower 3 bits of `init`
522             let w = unwrap_or_0(bytes.next());
523             ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
524         }
525     }
526
527     Some(ch)
528 }
529
530 /// Reads the last code point out of a byte iterator (assuming a
531 /// UTF-8-like encoding).
532 #[inline]
533 fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
534     where I: DoubleEndedIterator<Item = &'a u8>,
535 {
536     // Decode UTF-8
537     let w = match *bytes.next_back()? {
538         next_byte if next_byte < 128 => return Some(next_byte as u32),
539         back_byte => back_byte,
540     };
541
542     // Multibyte case follows
543     // Decode from a byte combination out of: [x [y [z w]]]
544     let mut ch;
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);
554         }
555         ch = utf8_acc_cont_byte(ch, z);
556     }
557     ch = utf8_acc_cont_byte(ch, w);
558
559     Some(ch)
560 }
561
562 #[stable(feature = "rust1", since = "1.0.0")]
563 impl<'a> Iterator for Chars<'a> {
564     type Item = char;
565
566     #[inline]
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
570             unsafe {
571                 char::from_u32_unchecked(ch)
572             }
573         })
574     }
575
576     #[inline]
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;
583         }
584         bytes_len - cont_bytes
585     }
586
587     #[inline]
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))
594     }
595
596     #[inline]
597     fn last(mut self) -> Option<char> {
598         // No need to go through the entire string.
599         self.next_back()
600     }
601 }
602
603 #[stable(feature = "rust1", since = "1.0.0")]
604 impl<'a> DoubleEndedIterator for Chars<'a> {
605     #[inline]
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
609             unsafe {
610                 char::from_u32_unchecked(ch)
611             }
612         })
613     }
614 }
615
616 #[stable(feature = "fused", since = "1.26.0")]
617 impl FusedIterator for Chars<'_> {}
618
619 impl<'a> Chars<'a> {
620     /// Views the underlying data as a subslice of the original data.
621     ///
622     /// This has the same lifetime as the original slice, and so the
623     /// iterator can continue to be used while this exists.
624     ///
625     /// # Examples
626     ///
627     /// ```
628     /// let mut chars = "abc".chars();
629     ///
630     /// assert_eq!(chars.as_str(), "abc");
631     /// chars.next();
632     /// assert_eq!(chars.as_str(), "bc");
633     /// chars.next();
634     /// chars.next();
635     /// assert_eq!(chars.as_str(), "");
636     /// ```
637     #[stable(feature = "iter_to_slice", since = "1.4.0")]
638     #[inline]
639     pub fn as_str(&self) -> &'a str {
640         unsafe { from_utf8_unchecked(self.iter.as_slice()) }
641     }
642 }
643
644 /// An iterator over the [`char`]s of a string slice, and their positions.
645 ///
646 /// [`char`]: ../../std/primitive.char.html
647 ///
648 /// This struct is created by the [`char_indices`] method on [`str`].
649 /// See its documentation for more.
650 ///
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> {
656     front_offset: usize,
657     iter: Chars<'a>,
658 }
659
660 #[stable(feature = "rust1", since = "1.0.0")]
661 impl<'a> Iterator for CharIndices<'a> {
662     type Item = (usize, char);
663
664     #[inline]
665     fn next(&mut self) -> Option<(usize, char)> {
666         let pre_len = self.iter.iter.len();
667         match self.iter.next() {
668             None => None,
669             Some(ch) => {
670                 let index = self.front_offset;
671                 let len = self.iter.iter.len();
672                 self.front_offset += pre_len - len;
673                 Some((index, ch))
674             }
675         }
676     }
677
678     #[inline]
679     fn count(self) -> usize {
680         self.iter.count()
681     }
682
683     #[inline]
684     fn size_hint(&self) -> (usize, Option<usize>) {
685         self.iter.size_hint()
686     }
687
688     #[inline]
689     fn last(mut self) -> Option<(usize, char)> {
690         // No need to go through the entire string.
691         self.next_back()
692     }
693 }
694
695 #[stable(feature = "rust1", since = "1.0.0")]
696 impl<'a> DoubleEndedIterator for CharIndices<'a> {
697     #[inline]
698     fn next_back(&mut self) -> Option<(usize, char)> {
699         self.iter.next_back().map(|ch| {
700             let index = self.front_offset + self.iter.iter.len();
701             (index, ch)
702         })
703     }
704 }
705
706 #[stable(feature = "fused", since = "1.26.0")]
707 impl FusedIterator for CharIndices<'_> {}
708
709 impl<'a> CharIndices<'a> {
710     /// Views the underlying data as a subslice of the original data.
711     ///
712     /// This has the same lifetime as the original slice, and so the
713     /// iterator can continue to be used while this exists.
714     #[stable(feature = "iter_to_slice", since = "1.4.0")]
715     #[inline]
716     pub fn as_str(&self) -> &'a str {
717         self.iter.as_str()
718     }
719 }
720
721 /// An iterator over the bytes of a string slice.
722 ///
723 /// This struct is created by the [`bytes`] method on [`str`].
724 /// See its documentation for more.
725 ///
726 /// [`bytes`]: ../../std/primitive.str.html#method.bytes
727 /// [`str`]: ../../std/primitive.str.html
728 #[stable(feature = "rust1", since = "1.0.0")]
729 #[derive(Clone, Debug)]
730 pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>);
731
732 #[stable(feature = "rust1", since = "1.0.0")]
733 impl Iterator for Bytes<'_> {
734     type Item = u8;
735
736     #[inline]
737     fn next(&mut self) -> Option<u8> {
738         self.0.next()
739     }
740
741     #[inline]
742     fn size_hint(&self) -> (usize, Option<usize>) {
743         self.0.size_hint()
744     }
745
746     #[inline]
747     fn count(self) -> usize {
748         self.0.count()
749     }
750
751     #[inline]
752     fn last(self) -> Option<Self::Item> {
753         self.0.last()
754     }
755
756     #[inline]
757     fn nth(&mut self, n: usize) -> Option<Self::Item> {
758         self.0.nth(n)
759     }
760
761     #[inline]
762     fn all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
763         self.0.all(f)
764     }
765
766     #[inline]
767     fn any<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool {
768         self.0.any(f)
769     }
770
771     #[inline]
772     fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where
773         P: FnMut(&Self::Item) -> bool
774     {
775         self.0.find(predicate)
776     }
777
778     #[inline]
779     fn position<P>(&mut self, predicate: P) -> Option<usize> where
780         P: FnMut(Self::Item) -> bool
781     {
782         self.0.position(predicate)
783     }
784
785     #[inline]
786     fn rposition<P>(&mut self, predicate: P) -> Option<usize> where
787         P: FnMut(Self::Item) -> bool
788     {
789         self.0.rposition(predicate)
790     }
791 }
792
793 #[stable(feature = "rust1", since = "1.0.0")]
794 impl DoubleEndedIterator for Bytes<'_> {
795     #[inline]
796     fn next_back(&mut self) -> Option<u8> {
797         self.0.next_back()
798     }
799
800     #[inline]
801     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
802         self.0.nth_back(n)
803     }
804
805     #[inline]
806     fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> where
807         P: FnMut(&Self::Item) -> bool
808     {
809         self.0.rfind(predicate)
810     }
811 }
812
813 #[stable(feature = "rust1", since = "1.0.0")]
814 impl ExactSizeIterator for Bytes<'_> {
815     #[inline]
816     fn len(&self) -> usize {
817         self.0.len()
818     }
819
820     #[inline]
821     fn is_empty(&self) -> bool {
822         self.0.is_empty()
823     }
824 }
825
826 #[stable(feature = "fused", since = "1.26.0")]
827 impl FusedIterator for Bytes<'_> {}
828
829 #[unstable(feature = "trusted_len", issue = "37572")]
830 unsafe impl TrustedLen for Bytes<'_> {}
831
832 #[doc(hidden)]
833 unsafe impl TrustedRandomAccess for Bytes<'_> {
834     unsafe fn get_unchecked(&mut self, i: usize) -> u8 {
835         self.0.get_unchecked(i)
836     }
837     fn may_have_side_effect() -> bool { false }
838 }
839
840 /// This macro generates a Clone impl for string pattern API
841 /// wrapper types of the form X<'a, P>
842 macro_rules! derive_pattern_clone {
843     (clone $t:ident with |$s:ident| $e:expr) => {
844         impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
845             where P::Searcher: Clone
846         {
847             fn clone(&self) -> Self {
848                 let $s = self;
849                 $e
850             }
851         }
852     }
853 }
854
855 /// This macro generates two public iterator structs
856 /// wrapping a private internal one that makes use of the `Pattern` API.
857 ///
858 /// For all patterns `P: Pattern<'a>` the following items will be
859 /// generated (generics omitted):
860 ///
861 /// struct $forward_iterator($internal_iterator);
862 /// struct $reverse_iterator($internal_iterator);
863 ///
864 /// impl Iterator for $forward_iterator
865 /// { /* internal ends up calling Searcher::next_match() */ }
866 ///
867 /// impl DoubleEndedIterator for $forward_iterator
868 ///       where P::Searcher: DoubleEndedSearcher
869 /// { /* internal ends up calling Searcher::next_match_back() */ }
870 ///
871 /// impl Iterator for $reverse_iterator
872 ///       where P::Searcher: ReverseSearcher
873 /// { /* internal ends up calling Searcher::next_match_back() */ }
874 ///
875 /// impl DoubleEndedIterator for $reverse_iterator
876 ///       where P::Searcher: DoubleEndedSearcher
877 /// { /* internal ends up calling Searcher::next_match() */ }
878 ///
879 /// The internal one is defined outside the macro, and has almost the same
880 /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
881 /// `pattern::ReverseSearcher` for both forward and reverse iteration.
882 ///
883 /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
884 /// `Pattern` might not return the same elements, so actually implementing
885 /// `DoubleEndedIterator` for it would be incorrect.
886 /// (See the docs in `str::pattern` for more details)
887 ///
888 /// However, the internal struct still represents a single ended iterator from
889 /// either end, and depending on pattern is also a valid double ended iterator,
890 /// so the two wrapper structs implement `Iterator`
891 /// and `DoubleEndedIterator` depending on the concrete pattern type, leading
892 /// to the complex impls seen above.
893 macro_rules! generate_pattern_iterators {
894     {
895         // Forward iterator
896         forward:
897             $(#[$forward_iterator_attribute:meta])*
898             struct $forward_iterator:ident;
899
900         // Reverse iterator
901         reverse:
902             $(#[$reverse_iterator_attribute:meta])*
903             struct $reverse_iterator:ident;
904
905         // Stability of all generated items
906         stability:
907             $(#[$common_stability_attribute:meta])*
908
909         // Internal almost-iterator that is being delegated to
910         internal:
911             $internal_iterator:ident yielding ($iterty:ty);
912
913         // Kind of delegation - either single ended or double ended
914         delegate $($t:tt)*
915     } => {
916         $(#[$forward_iterator_attribute])*
917         $(#[$common_stability_attribute])*
918         pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
919
920         $(#[$common_stability_attribute])*
921         impl<'a, P: Pattern<'a>> fmt::Debug for $forward_iterator<'a, P>
922             where P::Searcher: fmt::Debug
923         {
924             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
925                 f.debug_tuple(stringify!($forward_iterator))
926                     .field(&self.0)
927                     .finish()
928             }
929         }
930
931         $(#[$common_stability_attribute])*
932         impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
933             type Item = $iterty;
934
935             #[inline]
936             fn next(&mut self) -> Option<$iterty> {
937                 self.0.next()
938             }
939         }
940
941         $(#[$common_stability_attribute])*
942         impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
943             where P::Searcher: Clone
944         {
945             fn clone(&self) -> Self {
946                 $forward_iterator(self.0.clone())
947             }
948         }
949
950         $(#[$reverse_iterator_attribute])*
951         $(#[$common_stability_attribute])*
952         pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);
953
954         $(#[$common_stability_attribute])*
955         impl<'a, P: Pattern<'a>> fmt::Debug for $reverse_iterator<'a, P>
956             where P::Searcher: fmt::Debug
957         {
958             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
959                 f.debug_tuple(stringify!($reverse_iterator))
960                     .field(&self.0)
961                     .finish()
962             }
963         }
964
965         $(#[$common_stability_attribute])*
966         impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
967             where P::Searcher: ReverseSearcher<'a>
968         {
969             type Item = $iterty;
970
971             #[inline]
972             fn next(&mut self) -> Option<$iterty> {
973                 self.0.next_back()
974             }
975         }
976
977         $(#[$common_stability_attribute])*
978         impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
979             where P::Searcher: Clone
980         {
981             fn clone(&self) -> Self {
982                 $reverse_iterator(self.0.clone())
983             }
984         }
985
986         #[stable(feature = "fused", since = "1.26.0")]
987         impl<'a, P: Pattern<'a>> FusedIterator for $forward_iterator<'a, P> {}
988
989         #[stable(feature = "fused", since = "1.26.0")]
990         impl<'a, P: Pattern<'a>> FusedIterator for $reverse_iterator<'a, P>
991             where P::Searcher: ReverseSearcher<'a> {}
992
993         generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
994                                                 $forward_iterator,
995                                                 $reverse_iterator, $iterty);
996     };
997     {
998         double ended; with $(#[$common_stability_attribute:meta])*,
999                            $forward_iterator:ident,
1000                            $reverse_iterator:ident, $iterty:ty
1001     } => {
1002         $(#[$common_stability_attribute])*
1003         impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
1004             where P::Searcher: DoubleEndedSearcher<'a>
1005         {
1006             #[inline]
1007             fn next_back(&mut self) -> Option<$iterty> {
1008                 self.0.next_back()
1009             }
1010         }
1011
1012         $(#[$common_stability_attribute])*
1013         impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
1014             where P::Searcher: DoubleEndedSearcher<'a>
1015         {
1016             #[inline]
1017             fn next_back(&mut self) -> Option<$iterty> {
1018                 self.0.next()
1019             }
1020         }
1021     };
1022     {
1023         single ended; with $(#[$common_stability_attribute:meta])*,
1024                            $forward_iterator:ident,
1025                            $reverse_iterator:ident, $iterty:ty
1026     } => {}
1027 }
1028
1029 derive_pattern_clone!{
1030     clone SplitInternal
1031     with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
1032 }
1033
1034 struct SplitInternal<'a, P: Pattern<'a>> {
1035     start: usize,
1036     end: usize,
1037     matcher: P::Searcher,
1038     allow_trailing_empty: bool,
1039     finished: bool,
1040 }
1041
1042 impl<'a, P: Pattern<'a>> fmt::Debug for SplitInternal<'a, P> where P::Searcher: fmt::Debug {
1043     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1044         f.debug_struct("SplitInternal")
1045             .field("start", &self.start)
1046             .field("end", &self.end)
1047             .field("matcher", &self.matcher)
1048             .field("allow_trailing_empty", &self.allow_trailing_empty)
1049             .field("finished", &self.finished)
1050             .finish()
1051     }
1052 }
1053
1054 impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
1055     #[inline]
1056     fn get_end(&mut self) -> Option<&'a str> {
1057         if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
1058             self.finished = true;
1059             unsafe {
1060                 let string = self.matcher.haystack().get_unchecked(self.start..self.end);
1061                 Some(string)
1062             }
1063         } else {
1064             None
1065         }
1066     }
1067
1068     #[inline]
1069     fn next(&mut self) -> Option<&'a str> {
1070         if self.finished { return None }
1071
1072         let haystack = self.matcher.haystack();
1073         match self.matcher.next_match() {
1074             Some((a, b)) => unsafe {
1075                 let elt = haystack.get_unchecked(self.start..a);
1076                 self.start = b;
1077                 Some(elt)
1078             },
1079             None => self.get_end(),
1080         }
1081     }
1082
1083     #[inline]
1084     fn next_back(&mut self) -> Option<&'a str>
1085         where P::Searcher: ReverseSearcher<'a>
1086     {
1087         if self.finished { return None }
1088
1089         if !self.allow_trailing_empty {
1090             self.allow_trailing_empty = true;
1091             match self.next_back() {
1092                 Some(elt) if !elt.is_empty() => return Some(elt),
1093                 _ => if self.finished { return None }
1094             }
1095         }
1096
1097         let haystack = self.matcher.haystack();
1098         match self.matcher.next_match_back() {
1099             Some((a, b)) => unsafe {
1100                 let elt = haystack.get_unchecked(b..self.end);
1101                 self.end = a;
1102                 Some(elt)
1103             },
1104             None => unsafe {
1105                 self.finished = true;
1106                 Some(haystack.get_unchecked(self.start..self.end))
1107             },
1108         }
1109     }
1110 }
1111
1112 generate_pattern_iterators! {
1113     forward:
1114         /// Created with the method [`split`].
1115         ///
1116         /// [`split`]: ../../std/primitive.str.html#method.split
1117         struct Split;
1118     reverse:
1119         /// Created with the method [`rsplit`].
1120         ///
1121         /// [`rsplit`]: ../../std/primitive.str.html#method.rsplit
1122         struct RSplit;
1123     stability:
1124         #[stable(feature = "rust1", since = "1.0.0")]
1125     internal:
1126         SplitInternal yielding (&'a str);
1127     delegate double ended;
1128 }
1129
1130 generate_pattern_iterators! {
1131     forward:
1132         /// Created with the method [`split_terminator`].
1133         ///
1134         /// [`split_terminator`]: ../../std/primitive.str.html#method.split_terminator
1135         struct SplitTerminator;
1136     reverse:
1137         /// Created with the method [`rsplit_terminator`].
1138         ///
1139         /// [`rsplit_terminator`]: ../../std/primitive.str.html#method.rsplit_terminator
1140         struct RSplitTerminator;
1141     stability:
1142         #[stable(feature = "rust1", since = "1.0.0")]
1143     internal:
1144         SplitInternal yielding (&'a str);
1145     delegate double ended;
1146 }
1147
1148 derive_pattern_clone!{
1149     clone SplitNInternal
1150     with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
1151 }
1152
1153 struct SplitNInternal<'a, P: Pattern<'a>> {
1154     iter: SplitInternal<'a, P>,
1155     /// The number of splits remaining
1156     count: usize,
1157 }
1158
1159 impl<'a, P: Pattern<'a>> fmt::Debug for SplitNInternal<'a, P> where P::Searcher: fmt::Debug {
1160     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1161         f.debug_struct("SplitNInternal")
1162             .field("iter", &self.iter)
1163             .field("count", &self.count)
1164             .finish()
1165     }
1166 }
1167
1168 impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
1169     #[inline]
1170     fn next(&mut self) -> Option<&'a str> {
1171         match self.count {
1172             0 => None,
1173             1 => { self.count = 0; self.iter.get_end() }
1174             _ => { self.count -= 1; self.iter.next() }
1175         }
1176     }
1177
1178     #[inline]
1179     fn next_back(&mut self) -> Option<&'a str>
1180         where P::Searcher: ReverseSearcher<'a>
1181     {
1182         match self.count {
1183             0 => None,
1184             1 => { self.count = 0; self.iter.get_end() }
1185             _ => { self.count -= 1; self.iter.next_back() }
1186         }
1187     }
1188 }
1189
1190 generate_pattern_iterators! {
1191     forward:
1192         /// Created with the method [`splitn`].
1193         ///
1194         /// [`splitn`]: ../../std/primitive.str.html#method.splitn
1195         struct SplitN;
1196     reverse:
1197         /// Created with the method [`rsplitn`].
1198         ///
1199         /// [`rsplitn`]: ../../std/primitive.str.html#method.rsplitn
1200         struct RSplitN;
1201     stability:
1202         #[stable(feature = "rust1", since = "1.0.0")]
1203     internal:
1204         SplitNInternal yielding (&'a str);
1205     delegate single ended;
1206 }
1207
1208 derive_pattern_clone!{
1209     clone MatchIndicesInternal
1210     with |s| MatchIndicesInternal(s.0.clone())
1211 }
1212
1213 struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);
1214
1215 impl<'a, P: Pattern<'a>> fmt::Debug for MatchIndicesInternal<'a, P> where P::Searcher: fmt::Debug {
1216     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1217         f.debug_tuple("MatchIndicesInternal")
1218             .field(&self.0)
1219             .finish()
1220     }
1221 }
1222
1223 impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
1224     #[inline]
1225     fn next(&mut self) -> Option<(usize, &'a str)> {
1226         self.0.next_match().map(|(start, end)| unsafe {
1227             (start, self.0.haystack().get_unchecked(start..end))
1228         })
1229     }
1230
1231     #[inline]
1232     fn next_back(&mut self) -> Option<(usize, &'a str)>
1233         where P::Searcher: ReverseSearcher<'a>
1234     {
1235         self.0.next_match_back().map(|(start, end)| unsafe {
1236             (start, self.0.haystack().get_unchecked(start..end))
1237         })
1238     }
1239 }
1240
1241 generate_pattern_iterators! {
1242     forward:
1243         /// Created with the method [`match_indices`].
1244         ///
1245         /// [`match_indices`]: ../../std/primitive.str.html#method.match_indices
1246         struct MatchIndices;
1247     reverse:
1248         /// Created with the method [`rmatch_indices`].
1249         ///
1250         /// [`rmatch_indices`]: ../../std/primitive.str.html#method.rmatch_indices
1251         struct RMatchIndices;
1252     stability:
1253         #[stable(feature = "str_match_indices", since = "1.5.0")]
1254     internal:
1255         MatchIndicesInternal yielding ((usize, &'a str));
1256     delegate double ended;
1257 }
1258
1259 derive_pattern_clone!{
1260     clone MatchesInternal
1261     with |s| MatchesInternal(s.0.clone())
1262 }
1263
1264 struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);
1265
1266 impl<'a, P: Pattern<'a>> fmt::Debug for MatchesInternal<'a, P> where P::Searcher: fmt::Debug {
1267     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1268         f.debug_tuple("MatchesInternal")
1269             .field(&self.0)
1270             .finish()
1271     }
1272 }
1273
1274 impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
1275     #[inline]
1276     fn next(&mut self) -> Option<&'a str> {
1277         self.0.next_match().map(|(a, b)| unsafe {
1278             // Indices are known to be on utf8 boundaries
1279             self.0.haystack().get_unchecked(a..b)
1280         })
1281     }
1282
1283     #[inline]
1284     fn next_back(&mut self) -> Option<&'a str>
1285         where P::Searcher: ReverseSearcher<'a>
1286     {
1287         self.0.next_match_back().map(|(a, b)| unsafe {
1288             // Indices are known to be on utf8 boundaries
1289             self.0.haystack().get_unchecked(a..b)
1290         })
1291     }
1292 }
1293
1294 generate_pattern_iterators! {
1295     forward:
1296         /// Created with the method [`matches`].
1297         ///
1298         /// [`matches`]: ../../std/primitive.str.html#method.matches
1299         struct Matches;
1300     reverse:
1301         /// Created with the method [`rmatches`].
1302         ///
1303         /// [`rmatches`]: ../../std/primitive.str.html#method.rmatches
1304         struct RMatches;
1305     stability:
1306         #[stable(feature = "str_matches", since = "1.2.0")]
1307     internal:
1308         MatchesInternal yielding (&'a str);
1309     delegate double ended;
1310 }
1311
1312 /// An iterator over the lines of a string, as string slices.
1313 ///
1314 /// This struct is created with the [`lines`] method on [`str`].
1315 /// See its documentation for more.
1316 ///
1317 /// [`lines`]: ../../std/primitive.str.html#method.lines
1318 /// [`str`]: ../../std/primitive.str.html
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 #[derive(Clone, Debug)]
1321 pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>);
1322
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 impl<'a> Iterator for Lines<'a> {
1325     type Item = &'a str;
1326
1327     #[inline]
1328     fn next(&mut self) -> Option<&'a str> {
1329         self.0.next()
1330     }
1331
1332     #[inline]
1333     fn size_hint(&self) -> (usize, Option<usize>) {
1334         self.0.size_hint()
1335     }
1336
1337     #[inline]
1338     fn last(mut self) -> Option<&'a str> {
1339         self.next_back()
1340     }
1341 }
1342
1343 #[stable(feature = "rust1", since = "1.0.0")]
1344 impl<'a> DoubleEndedIterator for Lines<'a> {
1345     #[inline]
1346     fn next_back(&mut self) -> Option<&'a str> {
1347         self.0.next_back()
1348     }
1349 }
1350
1351 #[stable(feature = "fused", since = "1.26.0")]
1352 impl FusedIterator for Lines<'_> {}
1353
1354 /// Created with the method [`lines_any`].
1355 ///
1356 /// [`lines_any`]: ../../std/primitive.str.html#method.lines_any
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 #[rustc_deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")]
1359 #[derive(Clone, Debug)]
1360 #[allow(deprecated)]
1361 pub struct LinesAny<'a>(Lines<'a>);
1362
1363 impl_fn_for_zst! {
1364     /// A nameable, cloneable fn type
1365     #[derive(Clone)]
1366     struct LinesAnyMap impl<'a> Fn = |line: &'a str| -> &'a str {
1367         let l = line.len();
1368         if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
1369         else { line }
1370     };
1371 }
1372
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 #[allow(deprecated)]
1375 impl<'a> Iterator for LinesAny<'a> {
1376     type Item = &'a str;
1377
1378     #[inline]
1379     fn next(&mut self) -> Option<&'a str> {
1380         self.0.next()
1381     }
1382
1383     #[inline]
1384     fn size_hint(&self) -> (usize, Option<usize>) {
1385         self.0.size_hint()
1386     }
1387 }
1388
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 #[allow(deprecated)]
1391 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1392     #[inline]
1393     fn next_back(&mut self) -> Option<&'a str> {
1394         self.0.next_back()
1395     }
1396 }
1397
1398 #[stable(feature = "fused", since = "1.26.0")]
1399 #[allow(deprecated)]
1400 impl FusedIterator for LinesAny<'_> {}
1401
1402 /*
1403 Section: UTF-8 validation
1404 */
1405
1406 // use truncation to fit u64 into usize
1407 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
1408
1409 /// Returns `true` if any byte in the word `x` is nonascii (>= 128).
1410 #[inline]
1411 fn contains_nonascii(x: usize) -> bool {
1412     (x & NONASCII_MASK) != 0
1413 }
1414
1415 /// Walks through `v` checking that it's a valid UTF-8 sequence,
1416 /// returning `Ok(())` in that case, or, if it is invalid, `Err(err)`.
1417 #[inline]
1418 fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
1419     let mut index = 0;
1420     let len = v.len();
1421
1422     let usize_bytes = mem::size_of::<usize>();
1423     let ascii_block_size = 2 * usize_bytes;
1424     let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
1425     let align = v.as_ptr().align_offset(usize_bytes);
1426
1427     while index < len {
1428         let old_offset = index;
1429         macro_rules! err {
1430             ($error_len: expr) => {
1431                 return Err(Utf8Error {
1432                     valid_up_to: old_offset,
1433                     error_len: $error_len,
1434                 })
1435             }
1436         }
1437
1438         macro_rules! next { () => {{
1439             index += 1;
1440             // we needed data, but there was none: error!
1441             if index >= len {
1442                 err!(None)
1443             }
1444             v[index]
1445         }}}
1446
1447         let first = v[index];
1448         if first >= 128 {
1449             let w = UTF8_CHAR_WIDTH[first as usize];
1450             // 2-byte encoding is for codepoints  \u{0080} to  \u{07ff}
1451             //        first  C2 80        last DF BF
1452             // 3-byte encoding is for codepoints  \u{0800} to  \u{ffff}
1453             //        first  E0 A0 80     last EF BF BF
1454             //   excluding surrogates codepoints  \u{d800} to  \u{dfff}
1455             //               ED A0 80 to       ED BF BF
1456             // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1457             //        first  F0 90 80 80  last F4 8F BF BF
1458             //
1459             // Use the UTF-8 syntax from the RFC
1460             //
1461             // https://tools.ietf.org/html/rfc3629
1462             // UTF8-1      = %x00-7F
1463             // UTF8-2      = %xC2-DF UTF8-tail
1464             // UTF8-3      = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1465             //               %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1466             // UTF8-4      = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1467             //               %xF4 %x80-8F 2( UTF8-tail )
1468             match w {
1469                 2 => if next!() & !CONT_MASK != TAG_CONT_U8 {
1470                     err!(Some(1))
1471                 },
1472                 3 => {
1473                     match (first, next!()) {
1474                         (0xE0         , 0xA0 ..= 0xBF) |
1475                         (0xE1 ..= 0xEC, 0x80 ..= 0xBF) |
1476                         (0xED         , 0x80 ..= 0x9F) |
1477                         (0xEE ..= 0xEF, 0x80 ..= 0xBF) => {}
1478                         _ => err!(Some(1))
1479                     }
1480                     if next!() & !CONT_MASK != TAG_CONT_U8 {
1481                         err!(Some(2))
1482                     }
1483                 }
1484                 4 => {
1485                     match (first, next!()) {
1486                         (0xF0         , 0x90 ..= 0xBF) |
1487                         (0xF1 ..= 0xF3, 0x80 ..= 0xBF) |
1488                         (0xF4         , 0x80 ..= 0x8F) => {}
1489                         _ => err!(Some(1))
1490                     }
1491                     if next!() & !CONT_MASK != TAG_CONT_U8 {
1492                         err!(Some(2))
1493                     }
1494                     if next!() & !CONT_MASK != TAG_CONT_U8 {
1495                         err!(Some(3))
1496                     }
1497                 }
1498                 _ => err!(Some(1))
1499             }
1500             index += 1;
1501         } else {
1502             // Ascii case, try to skip forward quickly.
1503             // When the pointer is aligned, read 2 words of data per iteration
1504             // until we find a word containing a non-ascii byte.
1505             if align != usize::max_value() && align.wrapping_sub(index) % usize_bytes == 0 {
1506                 let ptr = v.as_ptr();
1507                 while index < blocks_end {
1508                     unsafe {
1509                         let block = ptr.add(index) as *const usize;
1510                         // break if there is a nonascii byte
1511                         let zu = contains_nonascii(*block);
1512                         let zv = contains_nonascii(*block.offset(1));
1513                         if zu | zv {
1514                             break;
1515                         }
1516                     }
1517                     index += ascii_block_size;
1518                 }
1519                 // step from the point where the wordwise loop stopped
1520                 while index < len && v[index] < 128 {
1521                     index += 1;
1522                 }
1523             } else {
1524                 index += 1;
1525             }
1526         }
1527     }
1528
1529     Ok(())
1530 }
1531
1532 // https://tools.ietf.org/html/rfc3629
1533 static UTF8_CHAR_WIDTH: [u8; 256] = [
1534 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1535 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1536 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1537 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1538 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1539 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1540 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1541 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1542 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1543 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1544 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1545 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1546 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1547 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1548 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1549 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1550 ];
1551
1552 /// Given a first byte, determines how many bytes are in this UTF-8 character.
1553 #[unstable(feature = "str_internals", issue = "0")]
1554 #[inline]
1555 pub fn utf8_char_width(b: u8) -> usize {
1556     UTF8_CHAR_WIDTH[b as usize] as usize
1557 }
1558
1559 /// Mask of the value bits of a continuation byte.
1560 const CONT_MASK: u8 = 0b0011_1111;
1561 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte.
1562 const TAG_CONT_U8: u8 = 0b1000_0000;
1563
1564 /*
1565 Section: Trait implementations
1566 */
1567
1568 mod traits {
1569     use crate::cmp::Ordering;
1570     use crate::ops;
1571     use crate::slice::{self, SliceIndex};
1572
1573     /// Implements ordering of strings.
1574     ///
1575     /// Strings are ordered  lexicographically by their byte values. This orders Unicode code
1576     /// points based on their positions in the code charts. This is not necessarily the same as
1577     /// "alphabetical" order, which varies by language and locale. Sorting strings according to
1578     /// culturally-accepted standards requires locale-specific data that is outside the scope of
1579     /// the `str` type.
1580     #[stable(feature = "rust1", since = "1.0.0")]
1581     impl Ord for str {
1582         #[inline]
1583         fn cmp(&self, other: &str) -> Ordering {
1584             self.as_bytes().cmp(other.as_bytes())
1585         }
1586     }
1587
1588     #[stable(feature = "rust1", since = "1.0.0")]
1589     impl PartialEq for str {
1590         #[inline]
1591         fn eq(&self, other: &str) -> bool {
1592             self.as_bytes() == other.as_bytes()
1593         }
1594         #[inline]
1595         fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1596     }
1597
1598     #[stable(feature = "rust1", since = "1.0.0")]
1599     impl Eq for str {}
1600
1601     /// Implements comparison operations on strings.
1602     ///
1603     /// Strings are compared lexicographically by their byte values. This compares Unicode code
1604     /// points based on their positions in the code charts. This is not necessarily the same as
1605     /// "alphabetical" order, which varies by language and locale. Comparing strings according to
1606     /// culturally-accepted standards requires locale-specific data that is outside the scope of
1607     /// the `str` type.
1608     #[stable(feature = "rust1", since = "1.0.0")]
1609     impl PartialOrd for str {
1610         #[inline]
1611         fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1612             Some(self.cmp(other))
1613         }
1614     }
1615
1616     #[stable(feature = "rust1", since = "1.0.0")]
1617     impl<I> ops::Index<I> for str
1618     where
1619         I: SliceIndex<str>,
1620     {
1621         type Output = I::Output;
1622
1623         #[inline]
1624         fn index(&self, index: I) -> &I::Output {
1625             index.index(self)
1626         }
1627     }
1628
1629     #[stable(feature = "rust1", since = "1.0.0")]
1630     impl<I> ops::IndexMut<I> for str
1631     where
1632         I: SliceIndex<str>,
1633     {
1634         #[inline]
1635         fn index_mut(&mut self, index: I) -> &mut I::Output {
1636             index.index_mut(self)
1637         }
1638     }
1639
1640     #[inline(never)]
1641     #[cold]
1642     fn str_index_overflow_fail() -> ! {
1643         panic!("attempted to index str up to maximum usize");
1644     }
1645
1646     /// Implements substring slicing with syntax `&self[..]` or `&mut self[..]`.
1647     ///
1648     /// Returns a slice of the whole string, i.e., returns `&self` or `&mut
1649     /// self`. Equivalent to `&self[0 .. len]` or `&mut self[0 .. len]`. Unlike
1650     /// other indexing operations, this can never panic.
1651     ///
1652     /// This operation is `O(1)`.
1653     ///
1654     /// Prior to 1.20.0, these indexing operations were still supported by
1655     /// direct implementation of `Index` and `IndexMut`.
1656     ///
1657     /// Equivalent to `&self[0 .. len]` or `&mut self[0 .. len]`.
1658     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1659     impl SliceIndex<str> for ops::RangeFull {
1660         type Output = str;
1661         #[inline]
1662         fn get(self, slice: &str) -> Option<&Self::Output> {
1663             Some(slice)
1664         }
1665         #[inline]
1666         fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1667             Some(slice)
1668         }
1669         #[inline]
1670         unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1671             slice
1672         }
1673         #[inline]
1674         unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1675             slice
1676         }
1677         #[inline]
1678         fn index(self, slice: &str) -> &Self::Output {
1679             slice
1680         }
1681         #[inline]
1682         fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1683             slice
1684         }
1685     }
1686
1687     /// Implements substring slicing with syntax `&self[begin .. end]` or `&mut
1688     /// self[begin .. end]`.
1689     ///
1690     /// Returns a slice of the given string from the byte range
1691     /// [`begin`, `end`).
1692     ///
1693     /// This operation is `O(1)`.
1694     ///
1695     /// Prior to 1.20.0, these indexing operations were still supported by
1696     /// direct implementation of `Index` and `IndexMut`.
1697     ///
1698     /// # Panics
1699     ///
1700     /// Panics if `begin` or `end` does not point to the starting byte offset of
1701     /// a character (as defined by `is_char_boundary`), if `begin > end`, or if
1702     /// `end > len`.
1703     ///
1704     /// # Examples
1705     ///
1706     /// ```
1707     /// let s = "Löwe 老虎 Léopard";
1708     /// assert_eq!(&s[0 .. 1], "L");
1709     ///
1710     /// assert_eq!(&s[1 .. 9], "öwe 老");
1711     ///
1712     /// // these will panic:
1713     /// // byte 2 lies within `ö`:
1714     /// // &s[2 ..3];
1715     ///
1716     /// // byte 8 lies within `老`
1717     /// // &s[1 .. 8];
1718     ///
1719     /// // byte 100 is outside the string
1720     /// // &s[3 .. 100];
1721     /// ```
1722     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1723     impl SliceIndex<str> for ops::Range<usize> {
1724         type Output = str;
1725         #[inline]
1726         fn get(self, slice: &str) -> Option<&Self::Output> {
1727             if self.start <= self.end &&
1728                slice.is_char_boundary(self.start) &&
1729                slice.is_char_boundary(self.end) {
1730                 Some(unsafe { self.get_unchecked(slice) })
1731             } else {
1732                 None
1733             }
1734         }
1735         #[inline]
1736         fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1737             if self.start <= self.end &&
1738                slice.is_char_boundary(self.start) &&
1739                slice.is_char_boundary(self.end) {
1740                 Some(unsafe { self.get_unchecked_mut(slice) })
1741             } else {
1742                 None
1743             }
1744         }
1745         #[inline]
1746         unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1747             let ptr = slice.as_ptr().add(self.start);
1748             let len = self.end - self.start;
1749             super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1750         }
1751         #[inline]
1752         unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1753             let ptr = slice.as_mut_ptr().add(self.start);
1754             let len = self.end - self.start;
1755             super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, len))
1756         }
1757         #[inline]
1758         fn index(self, slice: &str) -> &Self::Output {
1759             let (start, end) = (self.start, self.end);
1760             self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1761         }
1762         #[inline]
1763         fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1764             // is_char_boundary checks that the index is in [0, .len()]
1765             // cannot reuse `get` as above, because of NLL trouble
1766             if self.start <= self.end &&
1767                slice.is_char_boundary(self.start) &&
1768                slice.is_char_boundary(self.end) {
1769                 unsafe { self.get_unchecked_mut(slice) }
1770             } else {
1771                 super::slice_error_fail(slice, self.start, self.end)
1772             }
1773         }
1774     }
1775
1776     /// Implements substring slicing with syntax `&self[.. end]` or `&mut
1777     /// self[.. end]`.
1778     ///
1779     /// Returns a slice of the given string from the byte range [`0`, `end`).
1780     /// Equivalent to `&self[0 .. end]` or `&mut self[0 .. end]`.
1781     ///
1782     /// This operation is `O(1)`.
1783     ///
1784     /// Prior to 1.20.0, these indexing operations were still supported by
1785     /// direct implementation of `Index` and `IndexMut`.
1786     ///
1787     /// # Panics
1788     ///
1789     /// Panics if `end` does not point to the starting byte offset of a
1790     /// character (as defined by `is_char_boundary`), or if `end > len`.
1791     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1792     impl SliceIndex<str> for ops::RangeTo<usize> {
1793         type Output = str;
1794         #[inline]
1795         fn get(self, slice: &str) -> Option<&Self::Output> {
1796             if slice.is_char_boundary(self.end) {
1797                 Some(unsafe { self.get_unchecked(slice) })
1798             } else {
1799                 None
1800             }
1801         }
1802         #[inline]
1803         fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1804             if slice.is_char_boundary(self.end) {
1805                 Some(unsafe { self.get_unchecked_mut(slice) })
1806             } else {
1807                 None
1808             }
1809         }
1810         #[inline]
1811         unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1812             let ptr = slice.as_ptr();
1813             super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end))
1814         }
1815         #[inline]
1816         unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1817             let ptr = slice.as_mut_ptr();
1818             super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, self.end))
1819         }
1820         #[inline]
1821         fn index(self, slice: &str) -> &Self::Output {
1822             let end = self.end;
1823             self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end))
1824         }
1825         #[inline]
1826         fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1827             // is_char_boundary checks that the index is in [0, .len()]
1828             if slice.is_char_boundary(self.end) {
1829                 unsafe { self.get_unchecked_mut(slice) }
1830             } else {
1831                 super::slice_error_fail(slice, 0, self.end)
1832             }
1833         }
1834     }
1835
1836     /// Implements substring slicing with syntax `&self[begin ..]` or `&mut
1837     /// self[begin ..]`.
1838     ///
1839     /// Returns a slice of the given string from the byte range [`begin`,
1840     /// `len`). Equivalent to `&self[begin .. len]` or `&mut self[begin ..
1841     /// len]`.
1842     ///
1843     /// This operation is `O(1)`.
1844     ///
1845     /// Prior to 1.20.0, these indexing operations were still supported by
1846     /// direct implementation of `Index` and `IndexMut`.
1847     ///
1848     /// # Panics
1849     ///
1850     /// Panics if `begin` does not point to the starting byte offset of
1851     /// a character (as defined by `is_char_boundary`), or if `begin >= len`.
1852     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
1853     impl SliceIndex<str> for ops::RangeFrom<usize> {
1854         type Output = str;
1855         #[inline]
1856         fn get(self, slice: &str) -> Option<&Self::Output> {
1857             if slice.is_char_boundary(self.start) {
1858                 Some(unsafe { self.get_unchecked(slice) })
1859             } else {
1860                 None
1861             }
1862         }
1863         #[inline]
1864         fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1865             if slice.is_char_boundary(self.start) {
1866                 Some(unsafe { self.get_unchecked_mut(slice) })
1867             } else {
1868                 None
1869             }
1870         }
1871         #[inline]
1872         unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1873             let ptr = slice.as_ptr().add(self.start);
1874             let len = slice.len() - self.start;
1875             super::from_utf8_unchecked(slice::from_raw_parts(ptr, len))
1876         }
1877         #[inline]
1878         unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1879             let ptr = slice.as_mut_ptr().add(self.start);
1880             let len = slice.len() - self.start;
1881             super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, len))
1882         }
1883         #[inline]
1884         fn index(self, slice: &str) -> &Self::Output {
1885             let (start, end) = (self.start, slice.len());
1886             self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, start, end))
1887         }
1888         #[inline]
1889         fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1890             // is_char_boundary checks that the index is in [0, .len()]
1891             if slice.is_char_boundary(self.start) {
1892                 unsafe { self.get_unchecked_mut(slice) }
1893             } else {
1894                 super::slice_error_fail(slice, self.start, slice.len())
1895             }
1896         }
1897     }
1898
1899     /// Implements substring slicing with syntax `&self[begin ..= end]` or `&mut
1900     /// self[begin ..= end]`.
1901     ///
1902     /// Returns a slice of the given string from the byte range
1903     /// [`begin`, `end`]. Equivalent to `&self [begin .. end + 1]` or `&mut
1904     /// self[begin .. end + 1]`, except if `end` has the maximum value for
1905     /// `usize`.
1906     ///
1907     /// This operation is `O(1)`.
1908     ///
1909     /// # Panics
1910     ///
1911     /// Panics if `begin` does not point to the starting byte offset of
1912     /// a character (as defined by `is_char_boundary`), if `end` does not point
1913     /// to the ending byte offset of a character (`end + 1` is either a starting
1914     /// byte offset or equal to `len`), if `begin > end`, or if `end >= len`.
1915     #[stable(feature = "inclusive_range", since = "1.26.0")]
1916     impl SliceIndex<str> for ops::RangeInclusive<usize> {
1917         type Output = str;
1918         #[inline]
1919         fn get(self, slice: &str) -> Option<&Self::Output> {
1920             if *self.end() == usize::max_value() { None }
1921             else { (*self.start()..self.end()+1).get(slice) }
1922         }
1923         #[inline]
1924         fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1925             if *self.end() == usize::max_value() { None }
1926             else { (*self.start()..self.end()+1).get_mut(slice) }
1927         }
1928         #[inline]
1929         unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1930             (*self.start()..self.end()+1).get_unchecked(slice)
1931         }
1932         #[inline]
1933         unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1934             (*self.start()..self.end()+1).get_unchecked_mut(slice)
1935         }
1936         #[inline]
1937         fn index(self, slice: &str) -> &Self::Output {
1938             if *self.end() == usize::max_value() { str_index_overflow_fail(); }
1939             (*self.start()..self.end()+1).index(slice)
1940         }
1941         #[inline]
1942         fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1943             if *self.end() == usize::max_value() { str_index_overflow_fail(); }
1944             (*self.start()..self.end()+1).index_mut(slice)
1945         }
1946     }
1947
1948     /// Implements substring slicing with syntax `&self[..= end]` or `&mut
1949     /// self[..= end]`.
1950     ///
1951     /// Returns a slice of the given string from the byte range [0, `end`].
1952     /// Equivalent to `&self [0 .. end + 1]`, except if `end` has the maximum
1953     /// value for `usize`.
1954     ///
1955     /// This operation is `O(1)`.
1956     ///
1957     /// # Panics
1958     ///
1959     /// Panics if `end` does not point to the ending byte offset of a character
1960     /// (`end + 1` is either a starting byte offset as defined by
1961     /// `is_char_boundary`, or equal to `len`), or if `end >= len`.
1962     #[stable(feature = "inclusive_range", since = "1.26.0")]
1963     impl SliceIndex<str> for ops::RangeToInclusive<usize> {
1964         type Output = str;
1965         #[inline]
1966         fn get(self, slice: &str) -> Option<&Self::Output> {
1967             if self.end == usize::max_value() { None }
1968             else { (..self.end+1).get(slice) }
1969         }
1970         #[inline]
1971         fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
1972             if self.end == usize::max_value() { None }
1973             else { (..self.end+1).get_mut(slice) }
1974         }
1975         #[inline]
1976         unsafe fn get_unchecked(self, slice: &str) -> &Self::Output {
1977             (..self.end+1).get_unchecked(slice)
1978         }
1979         #[inline]
1980         unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1981             (..self.end+1).get_unchecked_mut(slice)
1982         }
1983         #[inline]
1984         fn index(self, slice: &str) -> &Self::Output {
1985             if self.end == usize::max_value() { str_index_overflow_fail(); }
1986             (..self.end+1).index(slice)
1987         }
1988         #[inline]
1989         fn index_mut(self, slice: &mut str) -> &mut Self::Output {
1990             if self.end == usize::max_value() { str_index_overflow_fail(); }
1991             (..self.end+1).index_mut(slice)
1992         }
1993     }
1994 }
1995
1996 // truncate `&str` to length at most equal to `max`
1997 // return `true` if it were truncated, and the new str.
1998 fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
1999     if max >= s.len() {
2000         (false, s)
2001     } else {
2002         while !s.is_char_boundary(max) {
2003             max -= 1;
2004         }
2005         (true, &s[..max])
2006     }
2007 }
2008
2009 #[inline(never)]
2010 #[cold]
2011 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
2012     const MAX_DISPLAY_LENGTH: usize = 256;
2013     let (truncated, s_trunc) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
2014     let ellipsis = if truncated { "[...]" } else { "" };
2015
2016     // 1. out of bounds
2017     if begin > s.len() || end > s.len() {
2018         let oob_index = if begin > s.len() { begin } else { end };
2019         panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
2020     }
2021
2022     // 2. begin <= end
2023     assert!(begin <= end, "begin <= end ({} <= {}) when slicing `{}`{}",
2024             begin, end, s_trunc, ellipsis);
2025
2026     // 3. character boundary
2027     let index = if !s.is_char_boundary(begin) { begin } else { end };
2028     // find the character
2029     let mut char_start = index;
2030     while !s.is_char_boundary(char_start) {
2031         char_start -= 1;
2032     }
2033     // `char_start` must be less than len and a char boundary
2034     let ch = s[char_start..].chars().next().unwrap();
2035     let char_range = char_start .. char_start + ch.len_utf8();
2036     panic!("byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
2037            index, ch, char_range, s_trunc, ellipsis);
2038 }
2039
2040 #[lang = "str"]
2041 #[cfg(not(test))]
2042 impl str {
2043     /// Returns the length of `self`.
2044     ///
2045     /// This length is in bytes, not [`char`]s or graphemes. In other words,
2046     /// it may not be what a human considers the length of the string.
2047     ///
2048     /// # Examples
2049     ///
2050     /// Basic usage:
2051     ///
2052     /// ```
2053     /// let len = "foo".len();
2054     /// assert_eq!(3, len);
2055     ///
2056     /// let len = "ƒoo".len(); // fancy f!
2057     /// assert_eq!(4, len);
2058     /// ```
2059     #[stable(feature = "rust1", since = "1.0.0")]
2060     #[inline]
2061     #[rustc_const_unstable(feature = "const_str_len")]
2062     pub const fn len(&self) -> usize {
2063         self.as_bytes().len()
2064     }
2065
2066     /// Returns `true` if `self` has a length of zero bytes.
2067     ///
2068     /// # Examples
2069     ///
2070     /// Basic usage:
2071     ///
2072     /// ```
2073     /// let s = "";
2074     /// assert!(s.is_empty());
2075     ///
2076     /// let s = "not empty";
2077     /// assert!(!s.is_empty());
2078     /// ```
2079     #[inline]
2080     #[stable(feature = "rust1", since = "1.0.0")]
2081     #[rustc_const_unstable(feature = "const_str_len")]
2082     pub const fn is_empty(&self) -> bool {
2083         self.len() == 0
2084     }
2085
2086     /// Checks that `index`-th byte lies at the start and/or end of a
2087     /// UTF-8 code point sequence.
2088     ///
2089     /// The start and end of the string (when `index == self.len()`) are
2090     /// considered to be
2091     /// boundaries.
2092     ///
2093     /// Returns `false` if `index` is greater than `self.len()`.
2094     ///
2095     /// # Examples
2096     ///
2097     /// ```
2098     /// let s = "Löwe 老虎 Léopard";
2099     /// assert!(s.is_char_boundary(0));
2100     /// // start of `老`
2101     /// assert!(s.is_char_boundary(6));
2102     /// assert!(s.is_char_boundary(s.len()));
2103     ///
2104     /// // second byte of `ö`
2105     /// assert!(!s.is_char_boundary(2));
2106     ///
2107     /// // third byte of `老`
2108     /// assert!(!s.is_char_boundary(8));
2109     /// ```
2110     #[stable(feature = "is_char_boundary", since = "1.9.0")]
2111     #[inline]
2112     pub fn is_char_boundary(&self, index: usize) -> bool {
2113         // 0 and len are always ok.
2114         // Test for 0 explicitly so that it can optimize out the check
2115         // easily and skip reading string data for that case.
2116         if index == 0 || index == self.len() { return true; }
2117         match self.as_bytes().get(index) {
2118             None => false,
2119             // This is bit magic equivalent to: b < 128 || b >= 192
2120             Some(&b) => (b as i8) >= -0x40,
2121         }
2122     }
2123
2124     /// Converts a string slice to a byte slice. To convert the byte slice back
2125     /// into a string slice, use the [`str::from_utf8`] function.
2126     ///
2127     /// [`str::from_utf8`]: ./str/fn.from_utf8.html
2128     ///
2129     /// # Examples
2130     ///
2131     /// Basic usage:
2132     ///
2133     /// ```
2134     /// let bytes = "bors".as_bytes();
2135     /// assert_eq!(b"bors", bytes);
2136     /// ```
2137     #[stable(feature = "rust1", since = "1.0.0")]
2138     #[inline(always)]
2139     #[rustc_const_unstable(feature="const_str_as_bytes")]
2140     pub const fn as_bytes(&self) -> &[u8] {
2141         union Slices<'a> {
2142             str: &'a str,
2143             slice: &'a [u8],
2144         }
2145         unsafe { Slices { str: self }.slice }
2146     }
2147
2148     /// Converts a mutable string slice to a mutable byte slice. To convert the
2149     /// mutable byte slice back into a mutable string slice, use the
2150     /// [`str::from_utf8_mut`] function.
2151     ///
2152     /// [`str::from_utf8_mut`]: ./str/fn.from_utf8_mut.html
2153     ///
2154     /// # Examples
2155     ///
2156     /// Basic usage:
2157     ///
2158     /// ```
2159     /// let mut s = String::from("Hello");
2160     /// let bytes = unsafe { s.as_bytes_mut() };
2161     ///
2162     /// assert_eq!(b"Hello", bytes);
2163     /// ```
2164     ///
2165     /// Mutability:
2166     ///
2167     /// ```
2168     /// let mut s = String::from("🗻∈🌏");
2169     ///
2170     /// unsafe {
2171     ///     let bytes = s.as_bytes_mut();
2172     ///
2173     ///     bytes[0] = 0xF0;
2174     ///     bytes[1] = 0x9F;
2175     ///     bytes[2] = 0x8D;
2176     ///     bytes[3] = 0x94;
2177     /// }
2178     ///
2179     /// assert_eq!("🍔∈🌏", s);
2180     /// ```
2181     #[stable(feature = "str_mut_extras", since = "1.20.0")]
2182     #[inline(always)]
2183     pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
2184         &mut *(self as *mut str as *mut [u8])
2185     }
2186
2187     /// Converts a string slice to a raw pointer.
2188     ///
2189     /// As string slices are a slice of bytes, the raw pointer points to a
2190     /// [`u8`]. This pointer will be pointing to the first byte of the string
2191     /// slice.
2192     ///
2193     /// The caller must ensure that the returned pointer is never written to.
2194     /// If you need to mutate the contents of the string slice, use [`as_mut_ptr`].
2195     ///
2196     /// [`u8`]: primitive.u8.html
2197     /// [`as_mut_ptr`]: #method.as_mut_ptr
2198     ///
2199     /// # Examples
2200     ///
2201     /// Basic usage:
2202     ///
2203     /// ```
2204     /// let s = "Hello";
2205     /// let ptr = s.as_ptr();
2206     /// ```
2207     #[stable(feature = "rust1", since = "1.0.0")]
2208     #[inline]
2209     pub const fn as_ptr(&self) -> *const u8 {
2210         self as *const str as *const u8
2211     }
2212
2213     /// Converts a mutable string slice to a raw pointer.
2214     ///
2215     /// As string slices are a slice of bytes, the raw pointer points to a
2216     /// [`u8`]. This pointer will be pointing to the first byte of the string
2217     /// slice.
2218     ///
2219     /// It is your responsibility to make sure that the string slice only gets
2220     /// modified in a way that it remains valid UTF-8.
2221     ///
2222     /// [`u8`]: primitive.u8.html
2223     #[stable(feature = "str_as_mut_ptr", since = "1.36.0")]
2224     #[inline]
2225     pub fn as_mut_ptr(&mut self) -> *mut u8 {
2226         self as *mut str as *mut u8
2227     }
2228
2229     /// Returns a subslice of `str`.
2230     ///
2231     /// This is the non-panicking alternative to indexing the `str`. Returns
2232     /// [`None`] whenever equivalent indexing operation would panic.
2233     ///
2234     /// [`None`]: option/enum.Option.html#variant.None
2235     ///
2236     /// # Examples
2237     ///
2238     /// ```
2239     /// let v = String::from("🗻∈🌏");
2240     ///
2241     /// assert_eq!(Some("🗻"), v.get(0..4));
2242     ///
2243     /// // indices not on UTF-8 sequence boundaries
2244     /// assert!(v.get(1..).is_none());
2245     /// assert!(v.get(..8).is_none());
2246     ///
2247     /// // out of bounds
2248     /// assert!(v.get(..42).is_none());
2249     /// ```
2250     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2251     #[inline]
2252     pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
2253         i.get(self)
2254     }
2255
2256     /// Returns a mutable subslice of `str`.
2257     ///
2258     /// This is the non-panicking alternative to indexing the `str`. Returns
2259     /// [`None`] whenever equivalent indexing operation would panic.
2260     ///
2261     /// [`None`]: option/enum.Option.html#variant.None
2262     ///
2263     /// # Examples
2264     ///
2265     /// ```
2266     /// let mut v = String::from("hello");
2267     /// // correct length
2268     /// assert!(v.get_mut(0..5).is_some());
2269     /// // out of bounds
2270     /// assert!(v.get_mut(..42).is_none());
2271     /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
2272     ///
2273     /// assert_eq!("hello", v);
2274     /// {
2275     ///     let s = v.get_mut(0..2);
2276     ///     let s = s.map(|s| {
2277     ///         s.make_ascii_uppercase();
2278     ///         &*s
2279     ///     });
2280     ///     assert_eq!(Some("HE"), s);
2281     /// }
2282     /// assert_eq!("HEllo", v);
2283     /// ```
2284     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2285     #[inline]
2286     pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
2287         i.get_mut(self)
2288     }
2289
2290     /// Returns a unchecked subslice of `str`.
2291     ///
2292     /// This is the unchecked alternative to indexing the `str`.
2293     ///
2294     /// # Safety
2295     ///
2296     /// Callers of this function are responsible that these preconditions are
2297     /// satisfied:
2298     ///
2299     /// * The starting index must come before the ending index;
2300     /// * Indexes must be within bounds of the original slice;
2301     /// * Indexes must lie on UTF-8 sequence boundaries.
2302     ///
2303     /// Failing that, the returned string slice may reference invalid memory or
2304     /// violate the invariants communicated by the `str` type.
2305     ///
2306     /// # Examples
2307     ///
2308     /// ```
2309     /// let v = "🗻∈🌏";
2310     /// unsafe {
2311     ///     assert_eq!("🗻", v.get_unchecked(0..4));
2312     ///     assert_eq!("∈", v.get_unchecked(4..7));
2313     ///     assert_eq!("🌏", v.get_unchecked(7..11));
2314     /// }
2315     /// ```
2316     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2317     #[inline]
2318     pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
2319         i.get_unchecked(self)
2320     }
2321
2322     /// Returns a mutable, unchecked subslice of `str`.
2323     ///
2324     /// This is the unchecked alternative to indexing the `str`.
2325     ///
2326     /// # Safety
2327     ///
2328     /// Callers of this function are responsible that these preconditions are
2329     /// satisfied:
2330     ///
2331     /// * The starting index must come before the ending index;
2332     /// * Indexes must be within bounds of the original slice;
2333     /// * Indexes must lie on UTF-8 sequence boundaries.
2334     ///
2335     /// Failing that, the returned string slice may reference invalid memory or
2336     /// violate the invariants communicated by the `str` type.
2337     ///
2338     /// # Examples
2339     ///
2340     /// ```
2341     /// let mut v = String::from("🗻∈🌏");
2342     /// unsafe {
2343     ///     assert_eq!("🗻", v.get_unchecked_mut(0..4));
2344     ///     assert_eq!("∈", v.get_unchecked_mut(4..7));
2345     ///     assert_eq!("🌏", v.get_unchecked_mut(7..11));
2346     /// }
2347     /// ```
2348     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
2349     #[inline]
2350     pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
2351         i.get_unchecked_mut(self)
2352     }
2353
2354     /// Creates a string slice from another string slice, bypassing safety
2355     /// checks.
2356     ///
2357     /// This is generally not recommended, use with caution! For a safe
2358     /// alternative see [`str`] and [`Index`].
2359     ///
2360     /// [`str`]: primitive.str.html
2361     /// [`Index`]: ops/trait.Index.html
2362     ///
2363     /// This new slice goes from `begin` to `end`, including `begin` but
2364     /// excluding `end`.
2365     ///
2366     /// To get a mutable string slice instead, see the
2367     /// [`slice_mut_unchecked`] method.
2368     ///
2369     /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
2370     ///
2371     /// # Safety
2372     ///
2373     /// Callers of this function are responsible that three preconditions are
2374     /// satisfied:
2375     ///
2376     /// * `begin` must come before `end`.
2377     /// * `begin` and `end` must be byte positions within the string slice.
2378     /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2379     ///
2380     /// # Examples
2381     ///
2382     /// Basic usage:
2383     ///
2384     /// ```
2385     /// let s = "Löwe 老虎 Léopard";
2386     ///
2387     /// unsafe {
2388     ///     assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
2389     /// }
2390     ///
2391     /// let s = "Hello, world!";
2392     ///
2393     /// unsafe {
2394     ///     assert_eq!("world", s.slice_unchecked(7, 12));
2395     /// }
2396     /// ```
2397     #[stable(feature = "rust1", since = "1.0.0")]
2398     #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked(begin..end)` instead")]
2399     #[inline]
2400     pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
2401         (begin..end).get_unchecked(self)
2402     }
2403
2404     /// Creates a string slice from another string slice, bypassing safety
2405     /// checks.
2406     /// This is generally not recommended, use with caution! For a safe
2407     /// alternative see [`str`] and [`IndexMut`].
2408     ///
2409     /// [`str`]: primitive.str.html
2410     /// [`IndexMut`]: ops/trait.IndexMut.html
2411     ///
2412     /// This new slice goes from `begin` to `end`, including `begin` but
2413     /// excluding `end`.
2414     ///
2415     /// To get an immutable string slice instead, see the
2416     /// [`slice_unchecked`] method.
2417     ///
2418     /// [`slice_unchecked`]: #method.slice_unchecked
2419     ///
2420     /// # Safety
2421     ///
2422     /// Callers of this function are responsible that three preconditions are
2423     /// satisfied:
2424     ///
2425     /// * `begin` must come before `end`.
2426     /// * `begin` and `end` must be byte positions within the string slice.
2427     /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
2428     #[stable(feature = "str_slice_mut", since = "1.5.0")]
2429     #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked_mut(begin..end)` instead")]
2430     #[inline]
2431     pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
2432         (begin..end).get_unchecked_mut(self)
2433     }
2434
2435     /// Divide one string slice into two at an index.
2436     ///
2437     /// The argument, `mid`, should be a byte offset from the start of the
2438     /// string. It must also be on the boundary of a UTF-8 code point.
2439     ///
2440     /// The two slices returned go from the start of the string slice to `mid`,
2441     /// and from `mid` to the end of the string slice.
2442     ///
2443     /// To get mutable string slices instead, see the [`split_at_mut`]
2444     /// method.
2445     ///
2446     /// [`split_at_mut`]: #method.split_at_mut
2447     ///
2448     /// # Panics
2449     ///
2450     /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2451     /// beyond the last code point of the string slice.
2452     ///
2453     /// # Examples
2454     ///
2455     /// Basic usage:
2456     ///
2457     /// ```
2458     /// let s = "Per Martin-Löf";
2459     ///
2460     /// let (first, last) = s.split_at(3);
2461     ///
2462     /// assert_eq!("Per", first);
2463     /// assert_eq!(" Martin-Löf", last);
2464     /// ```
2465     #[inline]
2466     #[stable(feature = "str_split_at", since = "1.4.0")]
2467     pub fn split_at(&self, mid: usize) -> (&str, &str) {
2468         // is_char_boundary checks that the index is in [0, .len()]
2469         if self.is_char_boundary(mid) {
2470             unsafe {
2471                 (self.get_unchecked(0..mid),
2472                  self.get_unchecked(mid..self.len()))
2473             }
2474         } else {
2475             slice_error_fail(self, 0, mid)
2476         }
2477     }
2478
2479     /// Divide one mutable string slice into two at an index.
2480     ///
2481     /// The argument, `mid`, should be a byte offset from the start of the
2482     /// string. It must also be on the boundary of a UTF-8 code point.
2483     ///
2484     /// The two slices returned go from the start of the string slice to `mid`,
2485     /// and from `mid` to the end of the string slice.
2486     ///
2487     /// To get immutable string slices instead, see the [`split_at`] method.
2488     ///
2489     /// [`split_at`]: #method.split_at
2490     ///
2491     /// # Panics
2492     ///
2493     /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
2494     /// beyond the last code point of the string slice.
2495     ///
2496     /// # Examples
2497     ///
2498     /// Basic usage:
2499     ///
2500     /// ```
2501     /// let mut s = "Per Martin-Löf".to_string();
2502     /// {
2503     ///     let (first, last) = s.split_at_mut(3);
2504     ///     first.make_ascii_uppercase();
2505     ///     assert_eq!("PER", first);
2506     ///     assert_eq!(" Martin-Löf", last);
2507     /// }
2508     /// assert_eq!("PER Martin-Löf", s);
2509     /// ```
2510     #[inline]
2511     #[stable(feature = "str_split_at", since = "1.4.0")]
2512     pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
2513         // is_char_boundary checks that the index is in [0, .len()]
2514         if self.is_char_boundary(mid) {
2515             let len = self.len();
2516             let ptr = self.as_mut_ptr();
2517             unsafe {
2518                 (from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
2519                  from_utf8_unchecked_mut(slice::from_raw_parts_mut(
2520                     ptr.add(mid),
2521                     len - mid
2522                  )))
2523             }
2524         } else {
2525             slice_error_fail(self, 0, mid)
2526         }
2527     }
2528
2529     /// Returns an iterator over the [`char`]s of a string slice.
2530     ///
2531     /// As a string slice consists of valid UTF-8, we can iterate through a
2532     /// string slice by [`char`]. This method returns such an iterator.
2533     ///
2534     /// It's important to remember that [`char`] represents a Unicode Scalar
2535     /// Value, and may not match your idea of what a 'character' is. Iteration
2536     /// over grapheme clusters may be what you actually want.
2537     ///
2538     /// # Examples
2539     ///
2540     /// Basic usage:
2541     ///
2542     /// ```
2543     /// let word = "goodbye";
2544     ///
2545     /// let count = word.chars().count();
2546     /// assert_eq!(7, count);
2547     ///
2548     /// let mut chars = word.chars();
2549     ///
2550     /// assert_eq!(Some('g'), chars.next());
2551     /// assert_eq!(Some('o'), chars.next());
2552     /// assert_eq!(Some('o'), chars.next());
2553     /// assert_eq!(Some('d'), chars.next());
2554     /// assert_eq!(Some('b'), chars.next());
2555     /// assert_eq!(Some('y'), chars.next());
2556     /// assert_eq!(Some('e'), chars.next());
2557     ///
2558     /// assert_eq!(None, chars.next());
2559     /// ```
2560     ///
2561     /// Remember, [`char`]s may not match your human intuition about characters:
2562     ///
2563     /// ```
2564     /// let y = "y̆";
2565     ///
2566     /// let mut chars = y.chars();
2567     ///
2568     /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
2569     /// assert_eq!(Some('\u{0306}'), chars.next());
2570     ///
2571     /// assert_eq!(None, chars.next());
2572     /// ```
2573     #[stable(feature = "rust1", since = "1.0.0")]
2574     #[inline]
2575     pub fn chars(&self) -> Chars<'_> {
2576         Chars{iter: self.as_bytes().iter()}
2577     }
2578
2579     /// Returns an iterator over the [`char`]s of a string slice, and their
2580     /// positions.
2581     ///
2582     /// As a string slice consists of valid UTF-8, we can iterate through a
2583     /// string slice by [`char`]. This method returns an iterator of both
2584     /// these [`char`]s, as well as their byte positions.
2585     ///
2586     /// The iterator yields tuples. The position is first, the [`char`] is
2587     /// second.
2588     ///
2589     /// # Examples
2590     ///
2591     /// Basic usage:
2592     ///
2593     /// ```
2594     /// let word = "goodbye";
2595     ///
2596     /// let count = word.char_indices().count();
2597     /// assert_eq!(7, count);
2598     ///
2599     /// let mut char_indices = word.char_indices();
2600     ///
2601     /// assert_eq!(Some((0, 'g')), char_indices.next());
2602     /// assert_eq!(Some((1, 'o')), char_indices.next());
2603     /// assert_eq!(Some((2, 'o')), char_indices.next());
2604     /// assert_eq!(Some((3, 'd')), char_indices.next());
2605     /// assert_eq!(Some((4, 'b')), char_indices.next());
2606     /// assert_eq!(Some((5, 'y')), char_indices.next());
2607     /// assert_eq!(Some((6, 'e')), char_indices.next());
2608     ///
2609     /// assert_eq!(None, char_indices.next());
2610     /// ```
2611     ///
2612     /// Remember, [`char`]s may not match your human intuition about characters:
2613     ///
2614     /// ```
2615     /// let yes = "y̆es";
2616     ///
2617     /// let mut char_indices = yes.char_indices();
2618     ///
2619     /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
2620     /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
2621     ///
2622     /// // note the 3 here - the last character took up two bytes
2623     /// assert_eq!(Some((3, 'e')), char_indices.next());
2624     /// assert_eq!(Some((4, 's')), char_indices.next());
2625     ///
2626     /// assert_eq!(None, char_indices.next());
2627     /// ```
2628     #[stable(feature = "rust1", since = "1.0.0")]
2629     #[inline]
2630     pub fn char_indices(&self) -> CharIndices<'_> {
2631         CharIndices { front_offset: 0, iter: self.chars() }
2632     }
2633
2634     /// An iterator over the bytes of a string slice.
2635     ///
2636     /// As a string slice consists of a sequence of bytes, we can iterate
2637     /// through a string slice by byte. This method returns such an iterator.
2638     ///
2639     /// # Examples
2640     ///
2641     /// Basic usage:
2642     ///
2643     /// ```
2644     /// let mut bytes = "bors".bytes();
2645     ///
2646     /// assert_eq!(Some(b'b'), bytes.next());
2647     /// assert_eq!(Some(b'o'), bytes.next());
2648     /// assert_eq!(Some(b'r'), bytes.next());
2649     /// assert_eq!(Some(b's'), bytes.next());
2650     ///
2651     /// assert_eq!(None, bytes.next());
2652     /// ```
2653     #[stable(feature = "rust1", since = "1.0.0")]
2654     #[inline]
2655     pub fn bytes(&self) -> Bytes<'_> {
2656         Bytes(self.as_bytes().iter().cloned())
2657     }
2658
2659     /// Splits a string slice by whitespace.
2660     ///
2661     /// The iterator returned will return string slices that are sub-slices of
2662     /// the original string slice, separated by any amount of whitespace.
2663     ///
2664     /// 'Whitespace' is defined according to the terms of the Unicode Derived
2665     /// Core Property `White_Space`. If you only want to split on ASCII whitespace
2666     /// instead, use [`split_ascii_whitespace`].
2667     ///
2668     /// [`split_ascii_whitespace`]: #method.split_ascii_whitespace
2669     ///
2670     /// # Examples
2671     ///
2672     /// Basic usage:
2673     ///
2674     /// ```
2675     /// let mut iter = "A few words".split_whitespace();
2676     ///
2677     /// assert_eq!(Some("A"), iter.next());
2678     /// assert_eq!(Some("few"), iter.next());
2679     /// assert_eq!(Some("words"), iter.next());
2680     ///
2681     /// assert_eq!(None, iter.next());
2682     /// ```
2683     ///
2684     /// All kinds of whitespace are considered:
2685     ///
2686     /// ```
2687     /// let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
2688     /// assert_eq!(Some("Mary"), iter.next());
2689     /// assert_eq!(Some("had"), iter.next());
2690     /// assert_eq!(Some("a"), iter.next());
2691     /// assert_eq!(Some("little"), iter.next());
2692     /// assert_eq!(Some("lamb"), iter.next());
2693     ///
2694     /// assert_eq!(None, iter.next());
2695     /// ```
2696     #[stable(feature = "split_whitespace", since = "1.1.0")]
2697     #[inline]
2698     pub fn split_whitespace(&self) -> SplitWhitespace<'_> {
2699         SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
2700     }
2701
2702     /// Splits a string slice by ASCII whitespace.
2703     ///
2704     /// The iterator returned will return string slices that are sub-slices of
2705     /// the original string slice, separated by any amount of ASCII whitespace.
2706     ///
2707     /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
2708     ///
2709     /// [`split_whitespace`]: #method.split_whitespace
2710     ///
2711     /// # Examples
2712     ///
2713     /// Basic usage:
2714     ///
2715     /// ```
2716     /// let mut iter = "A few words".split_ascii_whitespace();
2717     ///
2718     /// assert_eq!(Some("A"), iter.next());
2719     /// assert_eq!(Some("few"), iter.next());
2720     /// assert_eq!(Some("words"), iter.next());
2721     ///
2722     /// assert_eq!(None, iter.next());
2723     /// ```
2724     ///
2725     /// All kinds of ASCII whitespace are considered:
2726     ///
2727     /// ```
2728     /// let mut iter = " Mary   had\ta little  \n\t lamb".split_ascii_whitespace();
2729     /// assert_eq!(Some("Mary"), iter.next());
2730     /// assert_eq!(Some("had"), iter.next());
2731     /// assert_eq!(Some("a"), iter.next());
2732     /// assert_eq!(Some("little"), iter.next());
2733     /// assert_eq!(Some("lamb"), iter.next());
2734     ///
2735     /// assert_eq!(None, iter.next());
2736     /// ```
2737     #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
2738     #[inline]
2739     pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> {
2740         let inner = self
2741             .as_bytes()
2742             .split(IsAsciiWhitespace)
2743             .filter(BytesIsNotEmpty)
2744             .map(UnsafeBytesToStr);
2745         SplitAsciiWhitespace { inner }
2746     }
2747
2748     /// An iterator over the lines of a string, as string slices.
2749     ///
2750     /// Lines are ended with either a newline (`\n`) or a carriage return with
2751     /// a line feed (`\r\n`).
2752     ///
2753     /// The final line ending is optional.
2754     ///
2755     /// # Examples
2756     ///
2757     /// Basic usage:
2758     ///
2759     /// ```
2760     /// let text = "foo\r\nbar\n\nbaz\n";
2761     /// let mut lines = text.lines();
2762     ///
2763     /// assert_eq!(Some("foo"), lines.next());
2764     /// assert_eq!(Some("bar"), lines.next());
2765     /// assert_eq!(Some(""), lines.next());
2766     /// assert_eq!(Some("baz"), lines.next());
2767     ///
2768     /// assert_eq!(None, lines.next());
2769     /// ```
2770     ///
2771     /// The final line ending isn't required:
2772     ///
2773     /// ```
2774     /// let text = "foo\nbar\n\r\nbaz";
2775     /// let mut lines = text.lines();
2776     ///
2777     /// assert_eq!(Some("foo"), lines.next());
2778     /// assert_eq!(Some("bar"), lines.next());
2779     /// assert_eq!(Some(""), lines.next());
2780     /// assert_eq!(Some("baz"), lines.next());
2781     ///
2782     /// assert_eq!(None, lines.next());
2783     /// ```
2784     #[stable(feature = "rust1", since = "1.0.0")]
2785     #[inline]
2786     pub fn lines(&self) -> Lines<'_> {
2787         Lines(self.split_terminator('\n').map(LinesAnyMap))
2788     }
2789
2790     /// An iterator over the lines of a string.
2791     #[stable(feature = "rust1", since = "1.0.0")]
2792     #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
2793     #[inline]
2794     #[allow(deprecated)]
2795     pub fn lines_any(&self) -> LinesAny<'_> {
2796         LinesAny(self.lines())
2797     }
2798
2799     /// Returns an iterator of `u16` over the string encoded as UTF-16.
2800     ///
2801     /// # Examples
2802     ///
2803     /// Basic usage:
2804     ///
2805     /// ```
2806     /// let text = "Zażółć gęślą jaźń";
2807     ///
2808     /// let utf8_len = text.len();
2809     /// let utf16_len = text.encode_utf16().count();
2810     ///
2811     /// assert!(utf16_len <= utf8_len);
2812     /// ```
2813     #[stable(feature = "encode_utf16", since = "1.8.0")]
2814     pub fn encode_utf16(&self) -> EncodeUtf16<'_> {
2815         EncodeUtf16 { chars: self.chars(), extra: 0 }
2816     }
2817
2818     /// Returns `true` if the given pattern matches a sub-slice of
2819     /// this string slice.
2820     ///
2821     /// Returns `false` if it does not.
2822     ///
2823     /// # Examples
2824     ///
2825     /// Basic usage:
2826     ///
2827     /// ```
2828     /// let bananas = "bananas";
2829     ///
2830     /// assert!(bananas.contains("nana"));
2831     /// assert!(!bananas.contains("apples"));
2832     /// ```
2833     #[stable(feature = "rust1", since = "1.0.0")]
2834     #[inline]
2835     pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2836         pat.is_contained_in(self)
2837     }
2838
2839     /// Returns `true` if the given pattern matches a prefix of this
2840     /// string slice.
2841     ///
2842     /// Returns `false` if it does not.
2843     ///
2844     /// # Examples
2845     ///
2846     /// Basic usage:
2847     ///
2848     /// ```
2849     /// let bananas = "bananas";
2850     ///
2851     /// assert!(bananas.starts_with("bana"));
2852     /// assert!(!bananas.starts_with("nana"));
2853     /// ```
2854     #[stable(feature = "rust1", since = "1.0.0")]
2855     pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
2856         pat.is_prefix_of(self)
2857     }
2858
2859     /// Returns `true` if the given pattern matches a suffix of this
2860     /// string slice.
2861     ///
2862     /// Returns `false` if it does not.
2863     ///
2864     /// # Examples
2865     ///
2866     /// Basic usage:
2867     ///
2868     /// ```
2869     /// let bananas = "bananas";
2870     ///
2871     /// assert!(bananas.ends_with("anas"));
2872     /// assert!(!bananas.ends_with("nana"));
2873     /// ```
2874     #[stable(feature = "rust1", since = "1.0.0")]
2875     pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
2876         where P::Searcher: ReverseSearcher<'a>
2877     {
2878         pat.is_suffix_of(self)
2879     }
2880
2881     /// Returns the byte index of the first character of this string slice that
2882     /// matches the pattern.
2883     ///
2884     /// Returns [`None`] if the pattern doesn't match.
2885     ///
2886     /// The pattern can be a `&str`, [`char`], or a closure that determines if
2887     /// a character matches.
2888     ///
2889     /// [`None`]: option/enum.Option.html#variant.None
2890     ///
2891     /// # Examples
2892     ///
2893     /// Simple patterns:
2894     ///
2895     /// ```
2896     /// let s = "Löwe 老虎 Léopard";
2897     ///
2898     /// assert_eq!(s.find('L'), Some(0));
2899     /// assert_eq!(s.find('é'), Some(14));
2900     /// assert_eq!(s.find("Léopard"), Some(13));
2901     /// ```
2902     ///
2903     /// More complex patterns using point-free style and closures:
2904     ///
2905     /// ```
2906     /// let s = "Löwe 老虎 Léopard";
2907     ///
2908     /// assert_eq!(s.find(char::is_whitespace), Some(5));
2909     /// assert_eq!(s.find(char::is_lowercase), Some(1));
2910     /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
2911     /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
2912     /// ```
2913     ///
2914     /// Not finding the pattern:
2915     ///
2916     /// ```
2917     /// let s = "Löwe 老虎 Léopard";
2918     /// let x: &[_] = &['1', '2'];
2919     ///
2920     /// assert_eq!(s.find(x), None);
2921     /// ```
2922     #[stable(feature = "rust1", since = "1.0.0")]
2923     #[inline]
2924     pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
2925         pat.into_searcher(self).next_match().map(|(i, _)| i)
2926     }
2927
2928     /// Returns the byte index of the last character of this string slice that
2929     /// matches the pattern.
2930     ///
2931     /// Returns [`None`] if the pattern doesn't match.
2932     ///
2933     /// The pattern can be a `&str`, [`char`], or a closure that determines if
2934     /// a character matches.
2935     ///
2936     /// [`None`]: option/enum.Option.html#variant.None
2937     ///
2938     /// # Examples
2939     ///
2940     /// Simple patterns:
2941     ///
2942     /// ```
2943     /// let s = "Löwe 老虎 Léopard";
2944     ///
2945     /// assert_eq!(s.rfind('L'), Some(13));
2946     /// assert_eq!(s.rfind('é'), Some(14));
2947     /// ```
2948     ///
2949     /// More complex patterns with closures:
2950     ///
2951     /// ```
2952     /// let s = "Löwe 老虎 Léopard";
2953     ///
2954     /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
2955     /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
2956     /// ```
2957     ///
2958     /// Not finding the pattern:
2959     ///
2960     /// ```
2961     /// let s = "Löwe 老虎 Léopard";
2962     /// let x: &[_] = &['1', '2'];
2963     ///
2964     /// assert_eq!(s.rfind(x), None);
2965     /// ```
2966     #[stable(feature = "rust1", since = "1.0.0")]
2967     #[inline]
2968     pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
2969         where P::Searcher: ReverseSearcher<'a>
2970     {
2971         pat.into_searcher(self).next_match_back().map(|(i, _)| i)
2972     }
2973
2974     /// An iterator over substrings of this string slice, separated by
2975     /// characters matched by a pattern.
2976     ///
2977     /// The pattern can be any type that implements the Pattern trait. Notable
2978     /// examples are `&str`, [`char`], and closures that determines the split.
2979     ///
2980     /// # Iterator behavior
2981     ///
2982     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
2983     /// allows a reverse search and forward/reverse search yields the same
2984     /// elements. This is true for, e.g., [`char`], but not for `&str`.
2985     ///
2986     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
2987     ///
2988     /// If the pattern allows a reverse search but its results might differ
2989     /// from a forward search, the [`rsplit`] method can be used.
2990     ///
2991     /// [`rsplit`]: #method.rsplit
2992     ///
2993     /// # Examples
2994     ///
2995     /// Simple patterns:
2996     ///
2997     /// ```
2998     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
2999     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
3000     ///
3001     /// let v: Vec<&str> = "".split('X').collect();
3002     /// assert_eq!(v, [""]);
3003     ///
3004     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
3005     /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
3006     ///
3007     /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
3008     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3009     ///
3010     /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
3011     /// assert_eq!(v, ["abc", "def", "ghi"]);
3012     ///
3013     /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
3014     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
3015     /// ```
3016     ///
3017     /// A more complex pattern, using a closure:
3018     ///
3019     /// ```
3020     /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
3021     /// assert_eq!(v, ["abc", "def", "ghi"]);
3022     /// ```
3023     ///
3024     /// If a string contains multiple contiguous separators, you will end up
3025     /// with empty strings in the output:
3026     ///
3027     /// ```
3028     /// let x = "||||a||b|c".to_string();
3029     /// let d: Vec<_> = x.split('|').collect();
3030     ///
3031     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3032     /// ```
3033     ///
3034     /// Contiguous separators are separated by the empty string.
3035     ///
3036     /// ```
3037     /// let x = "(///)".to_string();
3038     /// let d: Vec<_> = x.split('/').collect();
3039     ///
3040     /// assert_eq!(d, &["(", "", "", ")"]);
3041     /// ```
3042     ///
3043     /// Separators at the start or end of a string are neighbored
3044     /// by empty strings.
3045     ///
3046     /// ```
3047     /// let d: Vec<_> = "010".split("0").collect();
3048     /// assert_eq!(d, &["", "1", ""]);
3049     /// ```
3050     ///
3051     /// When the empty string is used as a separator, it separates
3052     /// every character in the string, along with the beginning
3053     /// and end of the string.
3054     ///
3055     /// ```
3056     /// let f: Vec<_> = "rust".split("").collect();
3057     /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
3058     /// ```
3059     ///
3060     /// Contiguous separators can lead to possibly surprising behavior
3061     /// when whitespace is used as the separator. This code is correct:
3062     ///
3063     /// ```
3064     /// let x = "    a  b c".to_string();
3065     /// let d: Vec<_> = x.split(' ').collect();
3066     ///
3067     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
3068     /// ```
3069     ///
3070     /// It does _not_ give you:
3071     ///
3072     /// ```,ignore
3073     /// assert_eq!(d, &["a", "b", "c"]);
3074     /// ```
3075     ///
3076     /// Use [`split_whitespace`] for this behavior.
3077     ///
3078     /// [`split_whitespace`]: #method.split_whitespace
3079     #[stable(feature = "rust1", since = "1.0.0")]
3080     #[inline]
3081     pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
3082         Split(SplitInternal {
3083             start: 0,
3084             end: self.len(),
3085             matcher: pat.into_searcher(self),
3086             allow_trailing_empty: true,
3087             finished: false,
3088         })
3089     }
3090
3091     /// An iterator over substrings of the given string slice, separated by
3092     /// characters matched by a pattern and yielded in reverse order.
3093     ///
3094     /// The pattern can be any type that implements the Pattern trait. Notable
3095     /// examples are `&str`, [`char`], and closures that determines the split.
3096     ///
3097     /// # Iterator behavior
3098     ///
3099     /// The returned iterator requires that the pattern supports a reverse
3100     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3101     /// search yields the same elements.
3102     ///
3103     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3104     ///
3105     /// For iterating from the front, the [`split`] method can be used.
3106     ///
3107     /// [`split`]: #method.split
3108     ///
3109     /// # Examples
3110     ///
3111     /// Simple patterns:
3112     ///
3113     /// ```
3114     /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
3115     /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
3116     ///
3117     /// let v: Vec<&str> = "".rsplit('X').collect();
3118     /// assert_eq!(v, [""]);
3119     ///
3120     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
3121     /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
3122     ///
3123     /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
3124     /// assert_eq!(v, ["leopard", "tiger", "lion"]);
3125     /// ```
3126     ///
3127     /// A more complex pattern, using a closure:
3128     ///
3129     /// ```
3130     /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
3131     /// assert_eq!(v, ["ghi", "def", "abc"]);
3132     /// ```
3133     #[stable(feature = "rust1", since = "1.0.0")]
3134     #[inline]
3135     pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
3136         where P::Searcher: ReverseSearcher<'a>
3137     {
3138         RSplit(self.split(pat).0)
3139     }
3140
3141     /// An iterator over substrings of the given string slice, separated by
3142     /// characters matched by a pattern.
3143     ///
3144     /// The pattern can be any type that implements the Pattern trait. Notable
3145     /// examples are `&str`, [`char`], and closures that determines the split.
3146     ///
3147     /// Equivalent to [`split`], except that the trailing substring
3148     /// is skipped if empty.
3149     ///
3150     /// [`split`]: #method.split
3151     ///
3152     /// This method can be used for string data that is _terminated_,
3153     /// rather than _separated_ by a pattern.
3154     ///
3155     /// # Iterator behavior
3156     ///
3157     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3158     /// allows a reverse search and forward/reverse search yields the same
3159     /// elements. This is true for, e.g., [`char`], but not for `&str`.
3160     ///
3161     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3162     ///
3163     /// If the pattern allows a reverse search but its results might differ
3164     /// from a forward search, the [`rsplit_terminator`] method can be used.
3165     ///
3166     /// [`rsplit_terminator`]: #method.rsplit_terminator
3167     ///
3168     /// # Examples
3169     ///
3170     /// Basic usage:
3171     ///
3172     /// ```
3173     /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
3174     /// assert_eq!(v, ["A", "B"]);
3175     ///
3176     /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
3177     /// assert_eq!(v, ["A", "", "B", ""]);
3178     /// ```
3179     #[stable(feature = "rust1", since = "1.0.0")]
3180     #[inline]
3181     pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
3182         SplitTerminator(SplitInternal {
3183             allow_trailing_empty: false,
3184             ..self.split(pat).0
3185         })
3186     }
3187
3188     /// An iterator over substrings of `self`, separated by characters
3189     /// matched by a pattern and yielded in reverse order.
3190     ///
3191     /// The pattern can be any type that implements the Pattern trait. Notable
3192     /// examples are `&str`, [`char`], and closures that determines the split.
3193     /// Additional libraries might provide more complex patterns like
3194     /// regular expressions.
3195     ///
3196     /// Equivalent to [`split`], except that the trailing substring is
3197     /// skipped if empty.
3198     ///
3199     /// [`split`]: #method.split
3200     ///
3201     /// This method can be used for string data that is _terminated_,
3202     /// rather than _separated_ by a pattern.
3203     ///
3204     /// # Iterator behavior
3205     ///
3206     /// The returned iterator requires that the pattern supports a
3207     /// reverse search, and it will be double ended if a forward/reverse
3208     /// search yields the same elements.
3209     ///
3210     /// For iterating from the front, the [`split_terminator`] method can be
3211     /// used.
3212     ///
3213     /// [`split_terminator`]: #method.split_terminator
3214     ///
3215     /// # Examples
3216     ///
3217     /// ```
3218     /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
3219     /// assert_eq!(v, ["B", "A"]);
3220     ///
3221     /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
3222     /// assert_eq!(v, ["", "B", "", "A"]);
3223     /// ```
3224     #[stable(feature = "rust1", since = "1.0.0")]
3225     #[inline]
3226     pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
3227         where P::Searcher: ReverseSearcher<'a>
3228     {
3229         RSplitTerminator(self.split_terminator(pat).0)
3230     }
3231
3232     /// An iterator over substrings of the given string slice, separated by a
3233     /// pattern, restricted to returning at most `n` items.
3234     ///
3235     /// If `n` substrings are returned, the last substring (the `n`th substring)
3236     /// will contain the remainder of the string.
3237     ///
3238     /// The pattern can be any type that implements the Pattern trait. Notable
3239     /// examples are `&str`, [`char`], and closures that determines the split.
3240     ///
3241     /// # Iterator behavior
3242     ///
3243     /// The returned iterator will not be double ended, because it is
3244     /// not efficient to support.
3245     ///
3246     /// If the pattern allows a reverse search, the [`rsplitn`] method can be
3247     /// used.
3248     ///
3249     /// [`rsplitn`]: #method.rsplitn
3250     ///
3251     /// # Examples
3252     ///
3253     /// Simple patterns:
3254     ///
3255     /// ```
3256     /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
3257     /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
3258     ///
3259     /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
3260     /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
3261     ///
3262     /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
3263     /// assert_eq!(v, ["abcXdef"]);
3264     ///
3265     /// let v: Vec<&str> = "".splitn(1, 'X').collect();
3266     /// assert_eq!(v, [""]);
3267     /// ```
3268     ///
3269     /// A more complex pattern, using a closure:
3270     ///
3271     /// ```
3272     /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
3273     /// assert_eq!(v, ["abc", "defXghi"]);
3274     /// ```
3275     #[stable(feature = "rust1", since = "1.0.0")]
3276     #[inline]
3277     pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
3278         SplitN(SplitNInternal {
3279             iter: self.split(pat).0,
3280             count: n,
3281         })
3282     }
3283
3284     /// An iterator over substrings of this string slice, separated by a
3285     /// pattern, starting from the end of the string, restricted to returning
3286     /// at most `n` items.
3287     ///
3288     /// If `n` substrings are returned, the last substring (the `n`th substring)
3289     /// will contain the remainder of the string.
3290     ///
3291     /// The pattern can be any type that implements the Pattern trait. Notable
3292     /// examples are `&str`, [`char`], and closures that determines the split.
3293     ///
3294     /// # Iterator behavior
3295     ///
3296     /// The returned iterator will not be double ended, because it is not
3297     /// efficient to support.
3298     ///
3299     /// For splitting from the front, the [`splitn`] method can be used.
3300     ///
3301     /// [`splitn`]: #method.splitn
3302     ///
3303     /// # Examples
3304     ///
3305     /// Simple patterns:
3306     ///
3307     /// ```
3308     /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
3309     /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
3310     ///
3311     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
3312     /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
3313     ///
3314     /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
3315     /// assert_eq!(v, ["leopard", "lion::tiger"]);
3316     /// ```
3317     ///
3318     /// A more complex pattern, using a closure:
3319     ///
3320     /// ```
3321     /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
3322     /// assert_eq!(v, ["ghi", "abc1def"]);
3323     /// ```
3324     #[stable(feature = "rust1", since = "1.0.0")]
3325     #[inline]
3326     pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
3327         where P::Searcher: ReverseSearcher<'a>
3328     {
3329         RSplitN(self.splitn(n, pat).0)
3330     }
3331
3332     /// An iterator over the disjoint matches of a pattern within the given string
3333     /// slice.
3334     ///
3335     /// The pattern can be any type that implements the Pattern trait. Notable
3336     /// examples are `&str`, [`char`], and closures that determines the split.
3337     ///
3338     /// # Iterator behavior
3339     ///
3340     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3341     /// allows a reverse search and forward/reverse search yields the same
3342     /// elements. This is true for, e.g., [`char`], but not for `&str`.
3343     ///
3344     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3345     ///
3346     /// If the pattern allows a reverse search but its results might differ
3347     /// from a forward search, the [`rmatches`] method can be used.
3348     ///
3349     /// [`rmatches`]: #method.rmatches
3350     ///
3351     /// # Examples
3352     ///
3353     /// Basic usage:
3354     ///
3355     /// ```
3356     /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
3357     /// assert_eq!(v, ["abc", "abc", "abc"]);
3358     ///
3359     /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
3360     /// assert_eq!(v, ["1", "2", "3"]);
3361     /// ```
3362     #[stable(feature = "str_matches", since = "1.2.0")]
3363     #[inline]
3364     pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
3365         Matches(MatchesInternal(pat.into_searcher(self)))
3366     }
3367
3368     /// An iterator over the disjoint matches of a pattern within this string slice,
3369     /// yielded in reverse order.
3370     ///
3371     /// The pattern can be a `&str`, [`char`], or a closure that determines if
3372     /// a character matches.
3373     ///
3374     /// # Iterator behavior
3375     ///
3376     /// The returned iterator requires that the pattern supports a reverse
3377     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3378     /// search yields the same elements.
3379     ///
3380     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3381     ///
3382     /// For iterating from the front, the [`matches`] method can be used.
3383     ///
3384     /// [`matches`]: #method.matches
3385     ///
3386     /// # Examples
3387     ///
3388     /// Basic usage:
3389     ///
3390     /// ```
3391     /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
3392     /// assert_eq!(v, ["abc", "abc", "abc"]);
3393     ///
3394     /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
3395     /// assert_eq!(v, ["3", "2", "1"]);
3396     /// ```
3397     #[stable(feature = "str_matches", since = "1.2.0")]
3398     #[inline]
3399     pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
3400         where P::Searcher: ReverseSearcher<'a>
3401     {
3402         RMatches(self.matches(pat).0)
3403     }
3404
3405     /// An iterator over the disjoint matches of a pattern within this string
3406     /// slice as well as the index that the match starts at.
3407     ///
3408     /// For matches of `pat` within `self` that overlap, only the indices
3409     /// corresponding to the first match are returned.
3410     ///
3411     /// The pattern can be a `&str`, [`char`], or a closure that determines
3412     /// if a character matches.
3413     ///
3414     /// # Iterator behavior
3415     ///
3416     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
3417     /// allows a reverse search and forward/reverse search yields the same
3418     /// elements. This is true for, e.g., [`char`], but not for `&str`.
3419     ///
3420     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3421     ///
3422     /// If the pattern allows a reverse search but its results might differ
3423     /// from a forward search, the [`rmatch_indices`] method can be used.
3424     ///
3425     /// [`rmatch_indices`]: #method.rmatch_indices
3426     ///
3427     /// # Examples
3428     ///
3429     /// Basic usage:
3430     ///
3431     /// ```
3432     /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
3433     /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
3434     ///
3435     /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
3436     /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
3437     ///
3438     /// let v: Vec<_> = "ababa".match_indices("aba").collect();
3439     /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
3440     /// ```
3441     #[stable(feature = "str_match_indices", since = "1.5.0")]
3442     #[inline]
3443     pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
3444         MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
3445     }
3446
3447     /// An iterator over the disjoint matches of a pattern within `self`,
3448     /// yielded in reverse order along with the index of the match.
3449     ///
3450     /// For matches of `pat` within `self` that overlap, only the indices
3451     /// corresponding to the last match are returned.
3452     ///
3453     /// The pattern can be a `&str`, [`char`], or a closure that determines if a
3454     /// character matches.
3455     ///
3456     /// # Iterator behavior
3457     ///
3458     /// The returned iterator requires that the pattern supports a reverse
3459     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
3460     /// search yields the same elements.
3461     ///
3462     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
3463     ///
3464     /// For iterating from the front, the [`match_indices`] method can be used.
3465     ///
3466     /// [`match_indices`]: #method.match_indices
3467     ///
3468     /// # Examples
3469     ///
3470     /// Basic usage:
3471     ///
3472     /// ```
3473     /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
3474     /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
3475     ///
3476     /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
3477     /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
3478     ///
3479     /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
3480     /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
3481     /// ```
3482     #[stable(feature = "str_match_indices", since = "1.5.0")]
3483     #[inline]
3484     pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
3485         where P::Searcher: ReverseSearcher<'a>
3486     {
3487         RMatchIndices(self.match_indices(pat).0)
3488     }
3489
3490     /// Returns a string slice with leading and trailing whitespace removed.
3491     ///
3492     /// 'Whitespace' is defined according to the terms of the Unicode Derived
3493     /// Core Property `White_Space`.
3494     ///
3495     /// # Examples
3496     ///
3497     /// Basic usage:
3498     ///
3499     /// ```
3500     /// let s = " Hello\tworld\t";
3501     ///
3502     /// assert_eq!("Hello\tworld", s.trim());
3503     /// ```
3504     #[must_use = "this returns the trimmed string as a slice, \
3505                   without modifying the original"]
3506     #[stable(feature = "rust1", since = "1.0.0")]
3507     pub fn trim(&self) -> &str {
3508         self.trim_matches(|c: char| c.is_whitespace())
3509     }
3510
3511     /// Returns a string slice with leading whitespace removed.
3512     ///
3513     /// 'Whitespace' is defined according to the terms of the Unicode Derived
3514     /// Core Property `White_Space`.
3515     ///
3516     /// # Text directionality
3517     ///
3518     /// A string is a sequence of bytes. `start` in this context means the first
3519     /// position of that byte string; for a left-to-right language like English or
3520     /// Russian, this will be left side, and for right-to-left languages like
3521     /// like Arabic or Hebrew, this will be the right side.
3522     ///
3523     /// # Examples
3524     ///
3525     /// Basic usage:
3526     ///
3527     /// ```
3528     /// let s = " Hello\tworld\t";
3529     /// assert_eq!("Hello\tworld\t", s.trim_start());
3530     /// ```
3531     ///
3532     /// Directionality:
3533     ///
3534     /// ```
3535     /// let s = "  English  ";
3536     /// assert!(Some('E') == s.trim_start().chars().next());
3537     ///
3538     /// let s = "  עברית  ";
3539     /// assert!(Some('ע') == s.trim_start().chars().next());
3540     /// ```
3541     #[must_use = "this returns the trimmed string as a new slice, \
3542                   without modifying the original"]
3543     #[stable(feature = "trim_direction", since = "1.30.0")]
3544     pub fn trim_start(&self) -> &str {
3545         self.trim_start_matches(|c: char| c.is_whitespace())
3546     }
3547
3548     /// Returns a string slice with trailing whitespace removed.
3549     ///
3550     /// 'Whitespace' is defined according to the terms of the Unicode Derived
3551     /// Core Property `White_Space`.
3552     ///
3553     /// # Text directionality
3554     ///
3555     /// A string is a sequence of bytes. `end` in this context means the last
3556     /// position of that byte string; for a left-to-right language like English or
3557     /// Russian, this will be right side, and for right-to-left languages like
3558     /// like Arabic or Hebrew, this will be the left side.
3559     ///
3560     /// # Examples
3561     ///
3562     /// Basic usage:
3563     ///
3564     /// ```
3565     /// let s = " Hello\tworld\t";
3566     /// assert_eq!(" Hello\tworld", s.trim_end());
3567     /// ```
3568     ///
3569     /// Directionality:
3570     ///
3571     /// ```
3572     /// let s = "  English  ";
3573     /// assert!(Some('h') == s.trim_end().chars().rev().next());
3574     ///
3575     /// let s = "  עברית  ";
3576     /// assert!(Some('ת') == s.trim_end().chars().rev().next());
3577     /// ```
3578     #[must_use = "this returns the trimmed string as a new slice, \
3579                   without modifying the original"]
3580     #[stable(feature = "trim_direction", since = "1.30.0")]
3581     pub fn trim_end(&self) -> &str {
3582         self.trim_end_matches(|c: char| c.is_whitespace())
3583     }
3584
3585     /// Returns a string slice with leading whitespace removed.
3586     ///
3587     /// 'Whitespace' is defined according to the terms of the Unicode Derived
3588     /// Core Property `White_Space`.
3589     ///
3590     /// # Text directionality
3591     ///
3592     /// A string is a sequence of bytes. 'Left' in this context means the first
3593     /// position of that byte string; for a language like Arabic or Hebrew
3594     /// which are 'right to left' rather than 'left to right', this will be
3595     /// the _right_ side, not the left.
3596     ///
3597     /// # Examples
3598     ///
3599     /// Basic usage:
3600     ///
3601     /// ```
3602     /// let s = " Hello\tworld\t";
3603     ///
3604     /// assert_eq!("Hello\tworld\t", s.trim_left());
3605     /// ```
3606     ///
3607     /// Directionality:
3608     ///
3609     /// ```
3610     /// let s = "  English";
3611     /// assert!(Some('E') == s.trim_left().chars().next());
3612     ///
3613     /// let s = "  עברית";
3614     /// assert!(Some('ע') == s.trim_left().chars().next());
3615     /// ```
3616     #[stable(feature = "rust1", since = "1.0.0")]
3617     #[rustc_deprecated(
3618         since = "1.33.0",
3619         reason = "superseded by `trim_start`",
3620         suggestion = "trim_start",
3621     )]
3622     pub fn trim_left(&self) -> &str {
3623         self.trim_start()
3624     }
3625
3626     /// Returns a string slice with trailing whitespace removed.
3627     ///
3628     /// 'Whitespace' is defined according to the terms of the Unicode Derived
3629     /// Core Property `White_Space`.
3630     ///
3631     /// # Text directionality
3632     ///
3633     /// A string is a sequence of bytes. 'Right' in this context means the last
3634     /// position of that byte string; for a language like Arabic or Hebrew
3635     /// which are 'right to left' rather than 'left to right', this will be
3636     /// the _left_ side, not the right.
3637     ///
3638     /// # Examples
3639     ///
3640     /// Basic usage:
3641     ///
3642     /// ```
3643     /// let s = " Hello\tworld\t";
3644     ///
3645     /// assert_eq!(" Hello\tworld", s.trim_right());
3646     /// ```
3647     ///
3648     /// Directionality:
3649     ///
3650     /// ```
3651     /// let s = "English  ";
3652     /// assert!(Some('h') == s.trim_right().chars().rev().next());
3653     ///
3654     /// let s = "עברית  ";
3655     /// assert!(Some('ת') == s.trim_right().chars().rev().next());
3656     /// ```
3657     #[stable(feature = "rust1", since = "1.0.0")]
3658     #[rustc_deprecated(
3659         since = "1.33.0",
3660         reason = "superseded by `trim_end`",
3661         suggestion = "trim_end",
3662     )]
3663     pub fn trim_right(&self) -> &str {
3664         self.trim_end()
3665     }
3666
3667     /// Returns a string slice with all prefixes and suffixes that match a
3668     /// pattern repeatedly removed.
3669     ///
3670     /// The pattern can be a [`char`] or a closure that determines if a
3671     /// character matches.
3672     ///
3673     /// # Examples
3674     ///
3675     /// Simple patterns:
3676     ///
3677     /// ```
3678     /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
3679     /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
3680     ///
3681     /// let x: &[_] = &['1', '2'];
3682     /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
3683     /// ```
3684     ///
3685     /// A more complex pattern, using a closure:
3686     ///
3687     /// ```
3688     /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
3689     /// ```
3690     #[must_use = "this returns the trimmed string as a new slice, \
3691                   without modifying the original"]
3692     #[stable(feature = "rust1", since = "1.0.0")]
3693     pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3694         where P::Searcher: DoubleEndedSearcher<'a>
3695     {
3696         let mut i = 0;
3697         let mut j = 0;
3698         let mut matcher = pat.into_searcher(self);
3699         if let Some((a, b)) = matcher.next_reject() {
3700             i = a;
3701             j = b; // Remember earliest known match, correct it below if
3702                    // last match is different
3703         }
3704         if let Some((_, b)) = matcher.next_reject_back() {
3705             j = b;
3706         }
3707         unsafe {
3708             // Searcher is known to return valid indices
3709             self.get_unchecked(i..j)
3710         }
3711     }
3712
3713     /// Returns a string slice with all prefixes that match a pattern
3714     /// repeatedly removed.
3715     ///
3716     /// The pattern can be a `&str`, [`char`], or a closure that determines if
3717     /// a character matches.
3718     ///
3719     /// # Text directionality
3720     ///
3721     /// A string is a sequence of bytes. `start` in this context means the first
3722     /// position of that byte string; for a left-to-right language like English or
3723     /// Russian, this will be left side, and for right-to-left languages like
3724     /// like Arabic or Hebrew, this will be the right side.
3725     ///
3726     /// # Examples
3727     ///
3728     /// Basic usage:
3729     ///
3730     /// ```
3731     /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
3732     /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
3733     ///
3734     /// let x: &[_] = &['1', '2'];
3735     /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
3736     /// ```
3737     #[must_use = "this returns the trimmed string as a new slice, \
3738                   without modifying the original"]
3739     #[stable(feature = "trim_direction", since = "1.30.0")]
3740     pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3741         let mut i = self.len();
3742         let mut matcher = pat.into_searcher(self);
3743         if let Some((a, _)) = matcher.next_reject() {
3744             i = a;
3745         }
3746         unsafe {
3747             // Searcher is known to return valid indices
3748             self.get_unchecked(i..self.len())
3749         }
3750     }
3751
3752     /// Returns a string slice with all suffixes that match a pattern
3753     /// repeatedly removed.
3754     ///
3755     /// The pattern can be a `&str`, [`char`], or a closure that
3756     /// determines if a character matches.
3757     ///
3758     /// # Text directionality
3759     ///
3760     /// A string is a sequence of bytes. `end` in this context means the last
3761     /// position of that byte string; for a left-to-right language like English or
3762     /// Russian, this will be right side, and for right-to-left languages like
3763     /// like Arabic or Hebrew, this will be the left side.
3764     ///
3765     /// # Examples
3766     ///
3767     /// Simple patterns:
3768     ///
3769     /// ```
3770     /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
3771     /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
3772     ///
3773     /// let x: &[_] = &['1', '2'];
3774     /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
3775     /// ```
3776     ///
3777     /// A more complex pattern, using a closure:
3778     ///
3779     /// ```
3780     /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
3781     /// ```
3782     #[must_use = "this returns the trimmed string as a new slice, \
3783                   without modifying the original"]
3784     #[stable(feature = "trim_direction", since = "1.30.0")]
3785     pub fn trim_end_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3786         where P::Searcher: ReverseSearcher<'a>
3787     {
3788         let mut j = 0;
3789         let mut matcher = pat.into_searcher(self);
3790         if let Some((_, b)) = matcher.next_reject_back() {
3791             j = b;
3792         }
3793         unsafe {
3794             // Searcher is known to return valid indices
3795             self.get_unchecked(0..j)
3796         }
3797     }
3798
3799     /// Returns a string slice with all prefixes that match a pattern
3800     /// repeatedly removed.
3801     ///
3802     /// The pattern can be a `&str`, [`char`], or a closure that determines if
3803     /// a character matches.
3804     ///
3805     /// [`char`]: primitive.char.html
3806     ///
3807     /// # Text directionality
3808     ///
3809     /// A string is a sequence of bytes. 'Left' in this context means the first
3810     /// position of that byte string; for a language like Arabic or Hebrew
3811     /// which are 'right to left' rather than 'left to right', this will be
3812     /// the _right_ side, not the left.
3813     ///
3814     /// # Examples
3815     ///
3816     /// Basic usage:
3817     ///
3818     /// ```
3819     /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
3820     /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
3821     ///
3822     /// let x: &[_] = &['1', '2'];
3823     /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
3824     /// ```
3825     #[stable(feature = "rust1", since = "1.0.0")]
3826     #[rustc_deprecated(
3827         since = "1.33.0",
3828         reason = "superseded by `trim_start_matches`",
3829         suggestion = "trim_start_matches",
3830     )]
3831     pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
3832         self.trim_start_matches(pat)
3833     }
3834
3835     /// Returns a string slice with all suffixes that match a pattern
3836     /// repeatedly removed.
3837     ///
3838     /// The pattern can be a `&str`, [`char`], or a closure that
3839     /// determines if a character matches.
3840     ///
3841     /// [`char`]: primitive.char.html
3842     ///
3843     /// # Text directionality
3844     ///
3845     /// A string is a sequence of bytes. 'Right' in this context means the last
3846     /// position of that byte string; for a language like Arabic or Hebrew
3847     /// which are 'right to left' rather than 'left to right', this will be
3848     /// the _left_ side, not the right.
3849     ///
3850     /// # Examples
3851     ///
3852     /// Simple patterns:
3853     ///
3854     /// ```
3855     /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
3856     /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
3857     ///
3858     /// let x: &[_] = &['1', '2'];
3859     /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
3860     /// ```
3861     ///
3862     /// A more complex pattern, using a closure:
3863     ///
3864     /// ```
3865     /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
3866     /// ```
3867     #[stable(feature = "rust1", since = "1.0.0")]
3868     #[rustc_deprecated(
3869         since = "1.33.0",
3870         reason = "superseded by `trim_end_matches`",
3871         suggestion = "trim_end_matches",
3872     )]
3873     pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
3874         where P::Searcher: ReverseSearcher<'a>
3875     {
3876         self.trim_end_matches(pat)
3877     }
3878
3879     /// Parses this string slice into another type.
3880     ///
3881     /// Because `parse` is so general, it can cause problems with type
3882     /// inference. As such, `parse` is one of the few times you'll see
3883     /// the syntax affectionately known as the 'turbofish': `::<>`. This
3884     /// helps the inference algorithm understand specifically which type
3885     /// you're trying to parse into.
3886     ///
3887     /// `parse` can parse any type that implements the [`FromStr`] trait.
3888     ///
3889     /// [`FromStr`]: str/trait.FromStr.html
3890     ///
3891     /// # Errors
3892     ///
3893     /// Will return [`Err`] if it's not possible to parse this string slice into
3894     /// the desired type.
3895     ///
3896     /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
3897     ///
3898     /// # Examples
3899     ///
3900     /// Basic usage
3901     ///
3902     /// ```
3903     /// let four: u32 = "4".parse().unwrap();
3904     ///
3905     /// assert_eq!(4, four);
3906     /// ```
3907     ///
3908     /// Using the 'turbofish' instead of annotating `four`:
3909     ///
3910     /// ```
3911     /// let four = "4".parse::<u32>();
3912     ///
3913     /// assert_eq!(Ok(4), four);
3914     /// ```
3915     ///
3916     /// Failing to parse:
3917     ///
3918     /// ```
3919     /// let nope = "j".parse::<u32>();
3920     ///
3921     /// assert!(nope.is_err());
3922     /// ```
3923     #[inline]
3924     #[stable(feature = "rust1", since = "1.0.0")]
3925     pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
3926         FromStr::from_str(self)
3927     }
3928
3929     /// Checks if all characters in this string are within the ASCII range.
3930     ///
3931     /// # Examples
3932     ///
3933     /// ```
3934     /// let ascii = "hello!\n";
3935     /// let non_ascii = "Grüße, Jürgen ❤";
3936     ///
3937     /// assert!(ascii.is_ascii());
3938     /// assert!(!non_ascii.is_ascii());
3939     /// ```
3940     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3941     #[inline]
3942     pub fn is_ascii(&self) -> bool {
3943         // We can treat each byte as character here: all multibyte characters
3944         // start with a byte that is not in the ascii range, so we will stop
3945         // there already.
3946         self.bytes().all(|b| b.is_ascii())
3947     }
3948
3949     /// Checks that two strings are an ASCII case-insensitive match.
3950     ///
3951     /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
3952     /// but without allocating and copying temporaries.
3953     ///
3954     /// # Examples
3955     ///
3956     /// ```
3957     /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
3958     /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
3959     /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
3960     /// ```
3961     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3962     #[inline]
3963     pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
3964         self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
3965     }
3966
3967     /// Converts this string to its ASCII upper case equivalent in-place.
3968     ///
3969     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3970     /// but non-ASCII letters are unchanged.
3971     ///
3972     /// To return a new uppercased value without modifying the existing one, use
3973     /// [`to_ascii_uppercase`].
3974     ///
3975     /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3976     ///
3977     /// # Examples
3978     ///
3979     /// ```
3980     /// let mut s = String::from("Grüße, Jürgen ❤");
3981     ///
3982     /// s.make_ascii_uppercase();
3983     ///
3984     /// assert_eq!("GRüßE, JüRGEN ❤", s);
3985     /// ```
3986     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3987     pub fn make_ascii_uppercase(&mut self) {
3988         let me = unsafe { self.as_bytes_mut() };
3989         me.make_ascii_uppercase()
3990     }
3991
3992     /// Converts this string to its ASCII lower case equivalent in-place.
3993     ///
3994     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3995     /// but non-ASCII letters are unchanged.
3996     ///
3997     /// To return a new lowercased value without modifying the existing one, use
3998     /// [`to_ascii_lowercase`].
3999     ///
4000     /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4001     ///
4002     /// # Examples
4003     ///
4004     /// ```
4005     /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
4006     ///
4007     /// s.make_ascii_lowercase();
4008     ///
4009     /// assert_eq!("grÜße, jÜrgen ❤", s);
4010     /// ```
4011     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4012     pub fn make_ascii_lowercase(&mut self) {
4013         let me = unsafe { self.as_bytes_mut() };
4014         me.make_ascii_lowercase()
4015     }
4016
4017     /// Return an iterator that escapes each char in `self` with [`char::escape_debug`].
4018     ///
4019     /// Note: only extended grapheme codepoints that begin the string will be
4020     /// escaped.
4021     ///
4022     /// [`char::escape_debug`]: ../std/primitive.char.html#method.escape_debug
4023     ///
4024     /// # Examples
4025     ///
4026     /// As an iterator:
4027     ///
4028     /// ```
4029     /// for c in "❤\n!".escape_debug() {
4030     ///     print!("{}", c);
4031     /// }
4032     /// println!();
4033     /// ```
4034     ///
4035     /// Using `println!` directly:
4036     ///
4037     /// ```
4038     /// println!("{}", "❤\n!".escape_debug());
4039     /// ```
4040     ///
4041     ///
4042     /// Both are equivalent to:
4043     ///
4044     /// ```
4045     /// println!("❤\\n!");
4046     /// ```
4047     ///
4048     /// Using `to_string`:
4049     ///
4050     /// ```
4051     /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
4052     /// ```
4053     #[stable(feature = "str_escape", since = "1.34.0")]
4054     pub fn escape_debug(&self) -> EscapeDebug<'_> {
4055         let mut chars = self.chars();
4056         EscapeDebug {
4057             inner: chars.next()
4058                 .map(|first| first.escape_debug_ext(true))
4059                 .into_iter()
4060                 .flatten()
4061                 .chain(chars.flat_map(CharEscapeDebugContinue))
4062         }
4063     }
4064
4065     /// Return an iterator that escapes each char in `self` with [`char::escape_default`].
4066     ///
4067     /// [`char::escape_default`]: ../std/primitive.char.html#method.escape_default
4068     ///
4069     /// # Examples
4070     ///
4071     /// As an iterator:
4072     ///
4073     /// ```
4074     /// for c in "❤\n!".escape_default() {
4075     ///     print!("{}", c);
4076     /// }
4077     /// println!();
4078     /// ```
4079     ///
4080     /// Using `println!` directly:
4081     ///
4082     /// ```
4083     /// println!("{}", "❤\n!".escape_default());
4084     /// ```
4085     ///
4086     ///
4087     /// Both are equivalent to:
4088     ///
4089     /// ```
4090     /// println!("\\u{{2764}}\\n!");
4091     /// ```
4092     ///
4093     /// Using `to_string`:
4094     ///
4095     /// ```
4096     /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
4097     /// ```
4098     #[stable(feature = "str_escape", since = "1.34.0")]
4099     pub fn escape_default(&self) -> EscapeDefault<'_> {
4100         EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
4101     }
4102
4103     /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`].
4104     ///
4105     /// [`char::escape_unicode`]: ../std/primitive.char.html#method.escape_unicode
4106     ///
4107     /// # Examples
4108     ///
4109     /// As an iterator:
4110     ///
4111     /// ```
4112     /// for c in "❤\n!".escape_unicode() {
4113     ///     print!("{}", c);
4114     /// }
4115     /// println!();
4116     /// ```
4117     ///
4118     /// Using `println!` directly:
4119     ///
4120     /// ```
4121     /// println!("{}", "❤\n!".escape_unicode());
4122     /// ```
4123     ///
4124     ///
4125     /// Both are equivalent to:
4126     ///
4127     /// ```
4128     /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
4129     /// ```
4130     ///
4131     /// Using `to_string`:
4132     ///
4133     /// ```
4134     /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
4135     /// ```
4136     #[stable(feature = "str_escape", since = "1.34.0")]
4137     pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
4138         EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
4139     }
4140 }
4141
4142 impl_fn_for_zst! {
4143     #[derive(Clone)]
4144     struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
4145         c.escape_debug_ext(false)
4146     };
4147
4148     #[derive(Clone)]
4149     struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
4150         c.escape_unicode()
4151     };
4152     #[derive(Clone)]
4153     struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
4154         c.escape_default()
4155     };
4156 }
4157
4158 #[stable(feature = "rust1", since = "1.0.0")]
4159 impl AsRef<[u8]> for str {
4160     #[inline]
4161     fn as_ref(&self) -> &[u8] {
4162         self.as_bytes()
4163     }
4164 }
4165
4166 #[stable(feature = "rust1", since = "1.0.0")]
4167 impl Default for &str {
4168     /// Creates an empty str
4169     fn default() -> Self { "" }
4170 }
4171
4172 #[stable(feature = "default_mut_str", since = "1.28.0")]
4173 impl Default for &mut str {
4174     /// Creates an empty mutable str
4175     fn default() -> Self { unsafe { from_utf8_unchecked_mut(&mut []) } }
4176 }
4177
4178 /// An iterator over the non-whitespace substrings of a string,
4179 /// separated by any amount of whitespace.
4180 ///
4181 /// This struct is created by the [`split_whitespace`] method on [`str`].
4182 /// See its documentation for more.
4183 ///
4184 /// [`split_whitespace`]: ../../std/primitive.str.html#method.split_whitespace
4185 /// [`str`]: ../../std/primitive.str.html
4186 #[stable(feature = "split_whitespace", since = "1.1.0")]
4187 #[derive(Clone, Debug)]
4188 pub struct SplitWhitespace<'a> {
4189     inner: Filter<Split<'a, IsWhitespace>, IsNotEmpty>,
4190 }
4191
4192 /// An iterator over the non-ASCII-whitespace substrings of a string,
4193 /// separated by any amount of ASCII whitespace.
4194 ///
4195 /// This struct is created by the [`split_ascii_whitespace`] method on [`str`].
4196 /// See its documentation for more.
4197 ///
4198 /// [`split_ascii_whitespace`]: ../../std/primitive.str.html#method.split_ascii_whitespace
4199 /// [`str`]: ../../std/primitive.str.html
4200 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4201 #[derive(Clone, Debug)]
4202 pub struct SplitAsciiWhitespace<'a> {
4203     inner: Map<Filter<SliceSplit<'a, u8, IsAsciiWhitespace>, BytesIsNotEmpty>, UnsafeBytesToStr>,
4204 }
4205
4206 impl_fn_for_zst! {
4207     #[derive(Clone)]
4208     struct IsWhitespace impl Fn = |c: char| -> bool {
4209         c.is_whitespace()
4210     };
4211
4212     #[derive(Clone)]
4213     struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
4214         byte.is_ascii_whitespace()
4215     };
4216
4217     #[derive(Clone)]
4218     struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
4219         !s.is_empty()
4220     };
4221
4222     #[derive(Clone)]
4223     struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
4224         !s.is_empty()
4225     };
4226
4227     #[derive(Clone)]
4228     struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
4229         unsafe { from_utf8_unchecked(bytes) }
4230     };
4231 }
4232
4233 #[stable(feature = "split_whitespace", since = "1.1.0")]
4234 impl<'a> Iterator for SplitWhitespace<'a> {
4235     type Item = &'a str;
4236
4237     #[inline]
4238     fn next(&mut self) -> Option<&'a str> {
4239         self.inner.next()
4240     }
4241
4242     #[inline]
4243     fn size_hint(&self) -> (usize, Option<usize>) {
4244         self.inner.size_hint()
4245     }
4246
4247     #[inline]
4248     fn last(mut self) -> Option<&'a str> {
4249         self.next_back()
4250     }
4251 }
4252
4253 #[stable(feature = "split_whitespace", since = "1.1.0")]
4254 impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
4255     #[inline]
4256     fn next_back(&mut self) -> Option<&'a str> {
4257         self.inner.next_back()
4258     }
4259 }
4260
4261 #[stable(feature = "fused", since = "1.26.0")]
4262 impl FusedIterator for SplitWhitespace<'_> {}
4263
4264 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4265 impl<'a> Iterator for SplitAsciiWhitespace<'a> {
4266     type Item = &'a str;
4267
4268     #[inline]
4269     fn next(&mut self) -> Option<&'a str> {
4270         self.inner.next()
4271     }
4272
4273     #[inline]
4274     fn size_hint(&self) -> (usize, Option<usize>) {
4275         self.inner.size_hint()
4276     }
4277
4278     #[inline]
4279     fn last(mut self) -> Option<&'a str> {
4280         self.next_back()
4281     }
4282 }
4283
4284 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4285 impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> {
4286     #[inline]
4287     fn next_back(&mut self) -> Option<&'a str> {
4288         self.inner.next_back()
4289     }
4290 }
4291
4292 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
4293 impl FusedIterator for SplitAsciiWhitespace<'_> {}
4294
4295 /// An iterator of [`u16`] over the string encoded as UTF-16.
4296 ///
4297 /// [`u16`]: ../../std/primitive.u16.html
4298 ///
4299 /// This struct is created by the [`encode_utf16`] method on [`str`].
4300 /// See its documentation for more.
4301 ///
4302 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
4303 /// [`str`]: ../../std/primitive.str.html
4304 #[derive(Clone)]
4305 #[stable(feature = "encode_utf16", since = "1.8.0")]
4306 pub struct EncodeUtf16<'a> {
4307     chars: Chars<'a>,
4308     extra: u16,
4309 }
4310
4311 #[stable(feature = "collection_debug", since = "1.17.0")]
4312 impl fmt::Debug for EncodeUtf16<'_> {
4313     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4314         f.pad("EncodeUtf16 { .. }")
4315     }
4316 }
4317
4318 #[stable(feature = "encode_utf16", since = "1.8.0")]
4319 impl<'a> Iterator for EncodeUtf16<'a> {
4320     type Item = u16;
4321
4322     #[inline]
4323     fn next(&mut self) -> Option<u16> {
4324         if self.extra != 0 {
4325             let tmp = self.extra;
4326             self.extra = 0;
4327             return Some(tmp);
4328         }
4329
4330         let mut buf = [0; 2];
4331         self.chars.next().map(|ch| {
4332             let n = ch.encode_utf16(&mut buf).len();
4333             if n == 2 {
4334                 self.extra = buf[1];
4335             }
4336             buf[0]
4337         })
4338     }
4339
4340     #[inline]
4341     fn size_hint(&self) -> (usize, Option<usize>) {
4342         let (low, high) = self.chars.size_hint();
4343         // every char gets either one u16 or two u16,
4344         // so this iterator is between 1 or 2 times as
4345         // long as the underlying iterator.
4346         (low, high.and_then(|n| n.checked_mul(2)))
4347     }
4348 }
4349
4350 #[stable(feature = "fused", since = "1.26.0")]
4351 impl FusedIterator for EncodeUtf16<'_> {}
4352
4353 /// The return type of [`str::escape_debug`].
4354 ///
4355 /// [`str::escape_debug`]: ../../std/primitive.str.html#method.escape_debug
4356 #[stable(feature = "str_escape", since = "1.34.0")]
4357 #[derive(Clone, Debug)]
4358 pub struct EscapeDebug<'a> {
4359     inner: Chain<
4360         Flatten<option::IntoIter<char::EscapeDebug>>,
4361         FlatMap<Chars<'a>, char::EscapeDebug, CharEscapeDebugContinue>
4362     >,
4363 }
4364
4365 /// The return type of [`str::escape_default`].
4366 ///
4367 /// [`str::escape_default`]: ../../std/primitive.str.html#method.escape_default
4368 #[stable(feature = "str_escape", since = "1.34.0")]
4369 #[derive(Clone, Debug)]
4370 pub struct EscapeDefault<'a> {
4371     inner: FlatMap<Chars<'a>, char::EscapeDefault, CharEscapeDefault>,
4372 }
4373
4374 /// The return type of [`str::escape_unicode`].
4375 ///
4376 /// [`str::escape_unicode`]: ../../std/primitive.str.html#method.escape_unicode
4377 #[stable(feature = "str_escape", since = "1.34.0")]
4378 #[derive(Clone, Debug)]
4379 pub struct EscapeUnicode<'a> {
4380     inner: FlatMap<Chars<'a>, char::EscapeUnicode, CharEscapeUnicode>,
4381 }
4382
4383 macro_rules! escape_types_impls {
4384     ($( $Name: ident ),+) => {$(
4385         #[stable(feature = "str_escape", since = "1.34.0")]
4386         impl<'a> fmt::Display for $Name<'a> {
4387             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4388                 self.clone().try_for_each(|c| f.write_char(c))
4389             }
4390         }
4391
4392         #[stable(feature = "str_escape", since = "1.34.0")]
4393         impl<'a> Iterator for $Name<'a> {
4394             type Item = char;
4395
4396             #[inline]
4397             fn next(&mut self) -> Option<char> { self.inner.next() }
4398
4399             #[inline]
4400             fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
4401
4402             #[inline]
4403             fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
4404                 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
4405             {
4406                 self.inner.try_fold(init, fold)
4407             }
4408
4409             #[inline]
4410             fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
4411                 where Fold: FnMut(Acc, Self::Item) -> Acc,
4412             {
4413                 self.inner.fold(init, fold)
4414             }
4415         }
4416
4417         #[stable(feature = "str_escape", since = "1.34.0")]
4418         impl<'a> FusedIterator for $Name<'a> {}
4419     )+}
4420 }
4421
4422 escape_types_impls!(EscapeDebug, EscapeDefault, EscapeUnicode);