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