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