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