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