]> git.lizzy.rs Git - rust.git/blob - library/core/src/str/mod.rs
Auto merge of #95678 - pietroalbini:pa-1.62.0-bootstrap, r=Mark-Simulacrum
[rust.git] / library / core / src / str / mod.rs
1 //! String manipulation.
2 //!
3 //! For more details, see the [`std::str`] module.
4 //!
5 //! [`std::str`]: ../../std/str/index.html
6
7 #![stable(feature = "rust1", since = "1.0.0")]
8
9 mod converts;
10 mod count;
11 mod error;
12 mod iter;
13 mod traits;
14 mod validations;
15
16 use self::pattern::Pattern;
17 use self::pattern::{DoubleEndedSearcher, ReverseSearcher, Searcher};
18
19 use crate::char::{self, EscapeDebugExtArgs};
20 use crate::mem;
21 use crate::slice::{self, SliceIndex};
22
23 pub mod pattern;
24
25 #[unstable(feature = "str_internals", issue = "none")]
26 #[allow(missing_docs)]
27 pub mod lossy;
28
29 #[stable(feature = "rust1", since = "1.0.0")]
30 pub use converts::{from_utf8, from_utf8_unchecked};
31
32 #[stable(feature = "str_mut_extras", since = "1.20.0")]
33 pub use converts::{from_utf8_mut, from_utf8_unchecked_mut};
34
35 #[stable(feature = "rust1", since = "1.0.0")]
36 pub use error::{ParseBoolError, Utf8Error};
37
38 #[stable(feature = "rust1", since = "1.0.0")]
39 pub use traits::FromStr;
40
41 #[stable(feature = "rust1", since = "1.0.0")]
42 pub use iter::{Bytes, CharIndices, Chars, Lines, SplitWhitespace};
43
44 #[stable(feature = "rust1", since = "1.0.0")]
45 #[allow(deprecated)]
46 pub use iter::LinesAny;
47
48 #[stable(feature = "rust1", since = "1.0.0")]
49 pub use iter::{RSplit, RSplitTerminator, Split, SplitTerminator};
50
51 #[stable(feature = "rust1", since = "1.0.0")]
52 pub use iter::{RSplitN, SplitN};
53
54 #[stable(feature = "str_matches", since = "1.2.0")]
55 pub use iter::{Matches, RMatches};
56
57 #[stable(feature = "str_match_indices", since = "1.5.0")]
58 pub use iter::{MatchIndices, RMatchIndices};
59
60 #[stable(feature = "encode_utf16", since = "1.8.0")]
61 pub use iter::EncodeUtf16;
62
63 #[stable(feature = "str_escape", since = "1.34.0")]
64 pub use iter::{EscapeDebug, EscapeDefault, EscapeUnicode};
65
66 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
67 pub use iter::SplitAsciiWhitespace;
68
69 #[stable(feature = "split_inclusive", since = "1.51.0")]
70 pub use iter::SplitInclusive;
71
72 #[unstable(feature = "str_internals", issue = "none")]
73 pub use validations::{next_code_point, utf8_char_width};
74
75 use iter::MatchIndicesInternal;
76 use iter::SplitInternal;
77 use iter::{MatchesInternal, SplitNInternal};
78
79 #[inline(never)]
80 #[cold]
81 #[track_caller]
82 #[rustc_allow_const_fn_unstable(const_eval_select)]
83 const fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
84     // SAFETY: panics for both branches
85     unsafe {
86         crate::intrinsics::const_eval_select(
87             (s, begin, end),
88             slice_error_fail_ct,
89             slice_error_fail_rt,
90         )
91     }
92 }
93
94 const fn slice_error_fail_ct(_: &str, _: usize, _: usize) -> ! {
95     panic!("failed to slice string");
96 }
97
98 fn slice_error_fail_rt(s: &str, begin: usize, end: usize) -> ! {
99     const MAX_DISPLAY_LENGTH: usize = 256;
100     let trunc_len = s.floor_char_boundary(MAX_DISPLAY_LENGTH);
101     let s_trunc = &s[..trunc_len];
102     let ellipsis = if trunc_len < s.len() { "[...]" } else { "" };
103
104     // 1. out of bounds
105     if begin > s.len() || end > s.len() {
106         let oob_index = if begin > s.len() { begin } else { end };
107         panic!("byte index {oob_index} is out of bounds of `{s_trunc}`{ellipsis}");
108     }
109
110     // 2. begin <= end
111     assert!(
112         begin <= end,
113         "begin <= end ({} <= {}) when slicing `{}`{}",
114         begin,
115         end,
116         s_trunc,
117         ellipsis
118     );
119
120     // 3. character boundary
121     let index = if !s.is_char_boundary(begin) { begin } else { end };
122     // find the character
123     let char_start = s.floor_char_boundary(index);
124     // `char_start` must be less than len and a char boundary
125     let ch = s[char_start..].chars().next().unwrap();
126     let char_range = char_start..char_start + ch.len_utf8();
127     panic!(
128         "byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
129         index, ch, char_range, s_trunc, ellipsis
130     );
131 }
132
133 #[cfg(not(test))]
134 impl str {
135     /// Returns the length of `self`.
136     ///
137     /// This length is in bytes, not [`char`]s or graphemes. In other words,
138     /// it might not be what a human considers the length of the string.
139     ///
140     /// [`char`]: prim@char
141     ///
142     /// # Examples
143     ///
144     /// Basic usage:
145     ///
146     /// ```
147     /// let len = "foo".len();
148     /// assert_eq!(3, len);
149     ///
150     /// assert_eq!("ƒoo".len(), 4); // fancy f!
151     /// assert_eq!("ƒoo".chars().count(), 3);
152     /// ```
153     #[stable(feature = "rust1", since = "1.0.0")]
154     #[rustc_const_stable(feature = "const_str_len", since = "1.39.0")]
155     #[must_use]
156     #[inline]
157     pub const fn len(&self) -> usize {
158         self.as_bytes().len()
159     }
160
161     /// Returns `true` if `self` has a length of zero bytes.
162     ///
163     /// # Examples
164     ///
165     /// Basic usage:
166     ///
167     /// ```
168     /// let s = "";
169     /// assert!(s.is_empty());
170     ///
171     /// let s = "not empty";
172     /// assert!(!s.is_empty());
173     /// ```
174     #[stable(feature = "rust1", since = "1.0.0")]
175     #[rustc_const_stable(feature = "const_str_is_empty", since = "1.39.0")]
176     #[must_use]
177     #[inline]
178     pub const fn is_empty(&self) -> bool {
179         self.len() == 0
180     }
181
182     /// Checks that `index`-th byte is the first byte in a UTF-8 code point
183     /// sequence or the end of the string.
184     ///
185     /// The start and end of the string (when `index == self.len()`) are
186     /// considered to be boundaries.
187     ///
188     /// Returns `false` if `index` is greater than `self.len()`.
189     ///
190     /// # Examples
191     ///
192     /// ```
193     /// let s = "Löwe 老虎 Léopard";
194     /// assert!(s.is_char_boundary(0));
195     /// // start of `老`
196     /// assert!(s.is_char_boundary(6));
197     /// assert!(s.is_char_boundary(s.len()));
198     ///
199     /// // second byte of `ö`
200     /// assert!(!s.is_char_boundary(2));
201     ///
202     /// // third byte of `老`
203     /// assert!(!s.is_char_boundary(8));
204     /// ```
205     #[must_use]
206     #[stable(feature = "is_char_boundary", since = "1.9.0")]
207     #[rustc_const_unstable(feature = "const_is_char_boundary", issue = "none")]
208     #[inline]
209     pub const fn is_char_boundary(&self, index: usize) -> bool {
210         // 0 is always ok.
211         // Test for 0 explicitly so that it can optimize out the check
212         // easily and skip reading string data for that case.
213         // Note that optimizing `self.get(..index)` relies on this.
214         if index == 0 {
215             return true;
216         }
217
218         match self.as_bytes().get(index) {
219             // For `None` we have two options:
220             //
221             // - index == self.len()
222             //   Empty strings are valid, so return true
223             // - index > self.len()
224             //   In this case return false
225             //
226             // The check is placed exactly here, because it improves generated
227             // code on higher opt-levels. See PR #84751 for more details.
228             None => index == self.len(),
229
230             Some(&b) => b.is_utf8_char_boundary(),
231         }
232     }
233
234     /// Finds the closest `x` not exceeding `index` where `is_char_boundary(x)` is `true`.
235     ///
236     /// This method can help you truncate a string so that it's still valid UTF-8, but doesn't
237     /// exceed a given number of bytes. Note that this is done purely at the character level
238     /// and can still visually split graphemes, even though the underlying characters aren't
239     /// split. For example, the emoji 🧑‍🔬 (scientist) could be split so that the string only
240     /// includes 🧑 (person) instead.
241     ///
242     /// # Examples
243     ///
244     /// ```
245     /// #![feature(round_char_boundary)]
246     /// let s = "❤️🧡💛💚💙💜";
247     /// assert_eq!(s.len(), 26);
248     /// assert!(!s.is_char_boundary(13));
249     ///
250     /// let closest = s.floor_char_boundary(13);
251     /// assert_eq!(closest, 10);
252     /// assert_eq!(&s[..closest], "❤️🧡");
253     /// ```
254     #[unstable(feature = "round_char_boundary", issue = "93743")]
255     #[inline]
256     pub fn floor_char_boundary(&self, index: usize) -> usize {
257         if index >= self.len() {
258             self.len()
259         } else {
260             let lower_bound = index.saturating_sub(3);
261             let new_index = self.as_bytes()[lower_bound..=index]
262                 .iter()
263                 .rposition(|b| b.is_utf8_char_boundary());
264
265             // SAFETY: we know that the character boundary will be within four bytes
266             unsafe { lower_bound + new_index.unwrap_unchecked() }
267         }
268     }
269
270     /// Finds the closest `x` not below `index` where `is_char_boundary(x)` is `true`.
271     ///
272     /// This method is the natural complement to [`floor_char_boundary`]. See that method
273     /// for more details.
274     ///
275     /// [`floor_char_boundary`]: str::floor_char_boundary
276     ///
277     /// # Panics
278     ///
279     /// Panics if `index > self.len()`.
280     ///
281     /// # Examples
282     ///
283     /// ```
284     /// #![feature(round_char_boundary)]
285     /// let s = "❤️🧡💛💚💙💜";
286     /// assert_eq!(s.len(), 26);
287     /// assert!(!s.is_char_boundary(13));
288     ///
289     /// let closest = s.ceil_char_boundary(13);
290     /// assert_eq!(closest, 14);
291     /// assert_eq!(&s[..closest], "❤️🧡💛");
292     /// ```
293     #[unstable(feature = "round_char_boundary", issue = "93743")]
294     #[inline]
295     pub fn ceil_char_boundary(&self, index: usize) -> usize {
296         if index > self.len() {
297             slice_error_fail(self, index, index)
298         } else {
299             let upper_bound = Ord::min(index + 4, self.len());
300             self.as_bytes()[index..upper_bound]
301                 .iter()
302                 .position(|b| b.is_utf8_char_boundary())
303                 .map_or(upper_bound, |pos| pos + index)
304         }
305     }
306
307     /// Converts a string slice to a byte slice. To convert the byte slice back
308     /// into a string slice, use the [`from_utf8`] function.
309     ///
310     /// # Examples
311     ///
312     /// Basic usage:
313     ///
314     /// ```
315     /// let bytes = "bors".as_bytes();
316     /// assert_eq!(b"bors", bytes);
317     /// ```
318     #[stable(feature = "rust1", since = "1.0.0")]
319     #[rustc_const_stable(feature = "str_as_bytes", since = "1.39.0")]
320     #[must_use]
321     #[inline(always)]
322     #[allow(unused_attributes)]
323     pub const fn as_bytes(&self) -> &[u8] {
324         // SAFETY: const sound because we transmute two types with the same layout
325         unsafe { mem::transmute(self) }
326     }
327
328     /// Converts a mutable string slice to a mutable byte slice.
329     ///
330     /// # Safety
331     ///
332     /// The caller must ensure that the content of the slice is valid UTF-8
333     /// before the borrow ends and the underlying `str` is used.
334     ///
335     /// Use of a `str` whose contents are not valid UTF-8 is undefined behavior.
336     ///
337     /// # Examples
338     ///
339     /// Basic usage:
340     ///
341     /// ```
342     /// let mut s = String::from("Hello");
343     /// let bytes = unsafe { s.as_bytes_mut() };
344     ///
345     /// assert_eq!(b"Hello", bytes);
346     /// ```
347     ///
348     /// Mutability:
349     ///
350     /// ```
351     /// let mut s = String::from("🗻∈🌏");
352     ///
353     /// unsafe {
354     ///     let bytes = s.as_bytes_mut();
355     ///
356     ///     bytes[0] = 0xF0;
357     ///     bytes[1] = 0x9F;
358     ///     bytes[2] = 0x8D;
359     ///     bytes[3] = 0x94;
360     /// }
361     ///
362     /// assert_eq!("🍔∈🌏", s);
363     /// ```
364     #[stable(feature = "str_mut_extras", since = "1.20.0")]
365     #[must_use]
366     #[inline(always)]
367     pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
368         // SAFETY: the cast from `&str` to `&[u8]` is safe since `str`
369         // has the same layout as `&[u8]` (only libstd can make this guarantee).
370         // The pointer dereference is safe since it comes from a mutable reference which
371         // is guaranteed to be valid for writes.
372         unsafe { &mut *(self as *mut str as *mut [u8]) }
373     }
374
375     /// Converts a string slice to a raw pointer.
376     ///
377     /// As string slices are a slice of bytes, the raw pointer points to a
378     /// [`u8`]. This pointer will be pointing to the first byte of the string
379     /// slice.
380     ///
381     /// The caller must ensure that the returned pointer is never written to.
382     /// If you need to mutate the contents of the string slice, use [`as_mut_ptr`].
383     ///
384     /// [`as_mut_ptr`]: str::as_mut_ptr
385     ///
386     /// # Examples
387     ///
388     /// Basic usage:
389     ///
390     /// ```
391     /// let s = "Hello";
392     /// let ptr = s.as_ptr();
393     /// ```
394     #[stable(feature = "rust1", since = "1.0.0")]
395     #[rustc_const_stable(feature = "rustc_str_as_ptr", since = "1.32.0")]
396     #[must_use]
397     #[inline]
398     pub const fn as_ptr(&self) -> *const u8 {
399         self as *const str as *const u8
400     }
401
402     /// Converts a mutable string slice to a raw pointer.
403     ///
404     /// As string slices are a slice of bytes, the raw pointer points to a
405     /// [`u8`]. This pointer will be pointing to the first byte of the string
406     /// slice.
407     ///
408     /// It is your responsibility to make sure that the string slice only gets
409     /// modified in a way that it remains valid UTF-8.
410     #[stable(feature = "str_as_mut_ptr", since = "1.36.0")]
411     #[must_use]
412     #[inline]
413     pub fn as_mut_ptr(&mut self) -> *mut u8 {
414         self as *mut str as *mut u8
415     }
416
417     /// Returns a subslice of `str`.
418     ///
419     /// This is the non-panicking alternative to indexing the `str`. Returns
420     /// [`None`] whenever equivalent indexing operation would panic.
421     ///
422     /// # Examples
423     ///
424     /// ```
425     /// let v = String::from("🗻∈🌏");
426     ///
427     /// assert_eq!(Some("🗻"), v.get(0..4));
428     ///
429     /// // indices not on UTF-8 sequence boundaries
430     /// assert!(v.get(1..).is_none());
431     /// assert!(v.get(..8).is_none());
432     ///
433     /// // out of bounds
434     /// assert!(v.get(..42).is_none());
435     /// ```
436     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
437     #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
438     #[inline]
439     pub const fn get<I: ~const SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
440         i.get(self)
441     }
442
443     /// Returns a mutable subslice of `str`.
444     ///
445     /// This is the non-panicking alternative to indexing the `str`. Returns
446     /// [`None`] whenever equivalent indexing operation would panic.
447     ///
448     /// # Examples
449     ///
450     /// ```
451     /// let mut v = String::from("hello");
452     /// // correct length
453     /// assert!(v.get_mut(0..5).is_some());
454     /// // out of bounds
455     /// assert!(v.get_mut(..42).is_none());
456     /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
457     ///
458     /// assert_eq!("hello", v);
459     /// {
460     ///     let s = v.get_mut(0..2);
461     ///     let s = s.map(|s| {
462     ///         s.make_ascii_uppercase();
463     ///         &*s
464     ///     });
465     ///     assert_eq!(Some("HE"), s);
466     /// }
467     /// assert_eq!("HEllo", v);
468     /// ```
469     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
470     #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
471     #[inline]
472     pub const fn get_mut<I: ~const SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
473         i.get_mut(self)
474     }
475
476     /// Returns an unchecked subslice of `str`.
477     ///
478     /// This is the unchecked alternative to indexing the `str`.
479     ///
480     /// # Safety
481     ///
482     /// Callers of this function are responsible that these preconditions are
483     /// satisfied:
484     ///
485     /// * The starting index must not exceed the ending index;
486     /// * Indexes must be within bounds of the original slice;
487     /// * Indexes must lie on UTF-8 sequence boundaries.
488     ///
489     /// Failing that, the returned string slice may reference invalid memory or
490     /// violate the invariants communicated by the `str` type.
491     ///
492     /// # Examples
493     ///
494     /// ```
495     /// let v = "🗻∈🌏";
496     /// unsafe {
497     ///     assert_eq!("🗻", v.get_unchecked(0..4));
498     ///     assert_eq!("∈", v.get_unchecked(4..7));
499     ///     assert_eq!("🌏", v.get_unchecked(7..11));
500     /// }
501     /// ```
502     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
503     #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
504     #[inline]
505     pub const unsafe fn get_unchecked<I: ~const SliceIndex<str>>(&self, i: I) -> &I::Output {
506         // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
507         // the slice is dereferenceable because `self` is a safe reference.
508         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
509         unsafe { &*i.get_unchecked(self) }
510     }
511
512     /// Returns a mutable, unchecked subslice of `str`.
513     ///
514     /// This is the unchecked alternative to indexing the `str`.
515     ///
516     /// # Safety
517     ///
518     /// Callers of this function are responsible that these preconditions are
519     /// satisfied:
520     ///
521     /// * The starting index must not exceed the ending index;
522     /// * Indexes must be within bounds of the original slice;
523     /// * Indexes must lie on UTF-8 sequence boundaries.
524     ///
525     /// Failing that, the returned string slice may reference invalid memory or
526     /// violate the invariants communicated by the `str` type.
527     ///
528     /// # Examples
529     ///
530     /// ```
531     /// let mut v = String::from("🗻∈🌏");
532     /// unsafe {
533     ///     assert_eq!("🗻", v.get_unchecked_mut(0..4));
534     ///     assert_eq!("∈", v.get_unchecked_mut(4..7));
535     ///     assert_eq!("🌏", v.get_unchecked_mut(7..11));
536     /// }
537     /// ```
538     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
539     #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
540     #[inline]
541     pub const unsafe fn get_unchecked_mut<I: ~const SliceIndex<str>>(
542         &mut self,
543         i: I,
544     ) -> &mut I::Output {
545         // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
546         // the slice is dereferenceable because `self` is a safe reference.
547         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
548         unsafe { &mut *i.get_unchecked_mut(self) }
549     }
550
551     /// Creates a string slice from another string slice, bypassing safety
552     /// checks.
553     ///
554     /// This is generally not recommended, use with caution! For a safe
555     /// alternative see [`str`] and [`Index`].
556     ///
557     /// [`Index`]: crate::ops::Index
558     ///
559     /// This new slice goes from `begin` to `end`, including `begin` but
560     /// excluding `end`.
561     ///
562     /// To get a mutable string slice instead, see the
563     /// [`slice_mut_unchecked`] method.
564     ///
565     /// [`slice_mut_unchecked`]: str::slice_mut_unchecked
566     ///
567     /// # Safety
568     ///
569     /// Callers of this function are responsible that three preconditions are
570     /// satisfied:
571     ///
572     /// * `begin` must not exceed `end`.
573     /// * `begin` and `end` must be byte positions within the string slice.
574     /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
575     ///
576     /// # Examples
577     ///
578     /// Basic usage:
579     ///
580     /// ```
581     /// let s = "Löwe 老虎 Léopard";
582     ///
583     /// unsafe {
584     ///     assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
585     /// }
586     ///
587     /// let s = "Hello, world!";
588     ///
589     /// unsafe {
590     ///     assert_eq!("world", s.slice_unchecked(7, 12));
591     /// }
592     /// ```
593     #[stable(feature = "rust1", since = "1.0.0")]
594     #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked(begin..end)` instead")]
595     #[must_use]
596     #[inline]
597     pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
598         // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
599         // the slice is dereferenceable because `self` is a safe reference.
600         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
601         unsafe { &*(begin..end).get_unchecked(self) }
602     }
603
604     /// Creates a string slice from another string slice, bypassing safety
605     /// checks.
606     /// This is generally not recommended, use with caution! For a safe
607     /// alternative see [`str`] and [`IndexMut`].
608     ///
609     /// [`IndexMut`]: crate::ops::IndexMut
610     ///
611     /// This new slice goes from `begin` to `end`, including `begin` but
612     /// excluding `end`.
613     ///
614     /// To get an immutable string slice instead, see the
615     /// [`slice_unchecked`] method.
616     ///
617     /// [`slice_unchecked`]: str::slice_unchecked
618     ///
619     /// # Safety
620     ///
621     /// Callers of this function are responsible that three preconditions are
622     /// satisfied:
623     ///
624     /// * `begin` must not exceed `end`.
625     /// * `begin` and `end` must be byte positions within the string slice.
626     /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
627     #[stable(feature = "str_slice_mut", since = "1.5.0")]
628     #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked_mut(begin..end)` instead")]
629     #[inline]
630     pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
631         // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
632         // the slice is dereferenceable because `self` is a safe reference.
633         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
634         unsafe { &mut *(begin..end).get_unchecked_mut(self) }
635     }
636
637     /// Divide one string slice into two at an index.
638     ///
639     /// The argument, `mid`, should be a byte offset from the start of the
640     /// string. It must also be on the boundary of a UTF-8 code point.
641     ///
642     /// The two slices returned go from the start of the string slice to `mid`,
643     /// and from `mid` to the end of the string slice.
644     ///
645     /// To get mutable string slices instead, see the [`split_at_mut`]
646     /// method.
647     ///
648     /// [`split_at_mut`]: str::split_at_mut
649     ///
650     /// # Panics
651     ///
652     /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
653     /// past the end of the last code point of the string slice.
654     ///
655     /// # Examples
656     ///
657     /// Basic usage:
658     ///
659     /// ```
660     /// let s = "Per Martin-Löf";
661     ///
662     /// let (first, last) = s.split_at(3);
663     ///
664     /// assert_eq!("Per", first);
665     /// assert_eq!(" Martin-Löf", last);
666     /// ```
667     #[inline]
668     #[must_use]
669     #[stable(feature = "str_split_at", since = "1.4.0")]
670     pub fn split_at(&self, mid: usize) -> (&str, &str) {
671         // is_char_boundary checks that the index is in [0, .len()]
672         if self.is_char_boundary(mid) {
673             // SAFETY: just checked that `mid` is on a char boundary.
674             unsafe { (self.get_unchecked(0..mid), self.get_unchecked(mid..self.len())) }
675         } else {
676             slice_error_fail(self, 0, mid)
677         }
678     }
679
680     /// Divide one mutable string slice into two at an index.
681     ///
682     /// The argument, `mid`, should be a byte offset from the start of the
683     /// string. It must also be on the boundary of a UTF-8 code point.
684     ///
685     /// The two slices returned go from the start of the string slice to `mid`,
686     /// and from `mid` to the end of the string slice.
687     ///
688     /// To get immutable string slices instead, see the [`split_at`] method.
689     ///
690     /// [`split_at`]: str::split_at
691     ///
692     /// # Panics
693     ///
694     /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
695     /// past the end of the last code point of the string slice.
696     ///
697     /// # Examples
698     ///
699     /// Basic usage:
700     ///
701     /// ```
702     /// let mut s = "Per Martin-Löf".to_string();
703     /// {
704     ///     let (first, last) = s.split_at_mut(3);
705     ///     first.make_ascii_uppercase();
706     ///     assert_eq!("PER", first);
707     ///     assert_eq!(" Martin-Löf", last);
708     /// }
709     /// assert_eq!("PER Martin-Löf", s);
710     /// ```
711     #[inline]
712     #[must_use]
713     #[stable(feature = "str_split_at", since = "1.4.0")]
714     pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
715         // is_char_boundary checks that the index is in [0, .len()]
716         if self.is_char_boundary(mid) {
717             let len = self.len();
718             let ptr = self.as_mut_ptr();
719             // SAFETY: just checked that `mid` is on a char boundary.
720             unsafe {
721                 (
722                     from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
723                     from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr.add(mid), len - mid)),
724                 )
725             }
726         } else {
727             slice_error_fail(self, 0, mid)
728         }
729     }
730
731     /// Returns an iterator over the [`char`]s of a string slice.
732     ///
733     /// As a string slice consists of valid UTF-8, we can iterate through a
734     /// string slice by [`char`]. This method returns such an iterator.
735     ///
736     /// It's important to remember that [`char`] represents a Unicode Scalar
737     /// Value, and might not match your idea of what a 'character' is. Iteration
738     /// over grapheme clusters may be what you actually want. This functionality
739     /// is not provided by Rust's standard library, check crates.io instead.
740     ///
741     /// # Examples
742     ///
743     /// Basic usage:
744     ///
745     /// ```
746     /// let word = "goodbye";
747     ///
748     /// let count = word.chars().count();
749     /// assert_eq!(7, count);
750     ///
751     /// let mut chars = word.chars();
752     ///
753     /// assert_eq!(Some('g'), chars.next());
754     /// assert_eq!(Some('o'), chars.next());
755     /// assert_eq!(Some('o'), chars.next());
756     /// assert_eq!(Some('d'), chars.next());
757     /// assert_eq!(Some('b'), chars.next());
758     /// assert_eq!(Some('y'), chars.next());
759     /// assert_eq!(Some('e'), chars.next());
760     ///
761     /// assert_eq!(None, chars.next());
762     /// ```
763     ///
764     /// Remember, [`char`]s might not match your intuition about characters:
765     ///
766     /// [`char`]: prim@char
767     ///
768     /// ```
769     /// let y = "y̆";
770     ///
771     /// let mut chars = y.chars();
772     ///
773     /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
774     /// assert_eq!(Some('\u{0306}'), chars.next());
775     ///
776     /// assert_eq!(None, chars.next());
777     /// ```
778     #[stable(feature = "rust1", since = "1.0.0")]
779     #[inline]
780     pub fn chars(&self) -> Chars<'_> {
781         Chars { iter: self.as_bytes().iter() }
782     }
783
784     /// Returns an iterator over the [`char`]s of a string slice, and their
785     /// positions.
786     ///
787     /// As a string slice consists of valid UTF-8, we can iterate through a
788     /// string slice by [`char`]. This method returns an iterator of both
789     /// these [`char`]s, as well as their byte positions.
790     ///
791     /// The iterator yields tuples. The position is first, the [`char`] is
792     /// second.
793     ///
794     /// # Examples
795     ///
796     /// Basic usage:
797     ///
798     /// ```
799     /// let word = "goodbye";
800     ///
801     /// let count = word.char_indices().count();
802     /// assert_eq!(7, count);
803     ///
804     /// let mut char_indices = word.char_indices();
805     ///
806     /// assert_eq!(Some((0, 'g')), char_indices.next());
807     /// assert_eq!(Some((1, 'o')), char_indices.next());
808     /// assert_eq!(Some((2, 'o')), char_indices.next());
809     /// assert_eq!(Some((3, 'd')), char_indices.next());
810     /// assert_eq!(Some((4, 'b')), char_indices.next());
811     /// assert_eq!(Some((5, 'y')), char_indices.next());
812     /// assert_eq!(Some((6, 'e')), char_indices.next());
813     ///
814     /// assert_eq!(None, char_indices.next());
815     /// ```
816     ///
817     /// Remember, [`char`]s might not match your intuition about characters:
818     ///
819     /// [`char`]: prim@char
820     ///
821     /// ```
822     /// let yes = "y̆es";
823     ///
824     /// let mut char_indices = yes.char_indices();
825     ///
826     /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
827     /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
828     ///
829     /// // note the 3 here - the last character took up two bytes
830     /// assert_eq!(Some((3, 'e')), char_indices.next());
831     /// assert_eq!(Some((4, 's')), char_indices.next());
832     ///
833     /// assert_eq!(None, char_indices.next());
834     /// ```
835     #[stable(feature = "rust1", since = "1.0.0")]
836     #[inline]
837     pub fn char_indices(&self) -> CharIndices<'_> {
838         CharIndices { front_offset: 0, iter: self.chars() }
839     }
840
841     /// An iterator over the bytes of a string slice.
842     ///
843     /// As a string slice consists of a sequence of bytes, we can iterate
844     /// through a string slice by byte. This method returns such an iterator.
845     ///
846     /// # Examples
847     ///
848     /// Basic usage:
849     ///
850     /// ```
851     /// let mut bytes = "bors".bytes();
852     ///
853     /// assert_eq!(Some(b'b'), bytes.next());
854     /// assert_eq!(Some(b'o'), bytes.next());
855     /// assert_eq!(Some(b'r'), bytes.next());
856     /// assert_eq!(Some(b's'), bytes.next());
857     ///
858     /// assert_eq!(None, bytes.next());
859     /// ```
860     #[stable(feature = "rust1", since = "1.0.0")]
861     #[inline]
862     pub fn bytes(&self) -> Bytes<'_> {
863         Bytes(self.as_bytes().iter().copied())
864     }
865
866     /// Splits a string slice by whitespace.
867     ///
868     /// The iterator returned will return string slices that are sub-slices of
869     /// the original string slice, separated by any amount of whitespace.
870     ///
871     /// 'Whitespace' is defined according to the terms of the Unicode Derived
872     /// Core Property `White_Space`. If you only want to split on ASCII whitespace
873     /// instead, use [`split_ascii_whitespace`].
874     ///
875     /// [`split_ascii_whitespace`]: str::split_ascii_whitespace
876     ///
877     /// # Examples
878     ///
879     /// Basic usage:
880     ///
881     /// ```
882     /// let mut iter = "A few words".split_whitespace();
883     ///
884     /// assert_eq!(Some("A"), iter.next());
885     /// assert_eq!(Some("few"), iter.next());
886     /// assert_eq!(Some("words"), iter.next());
887     ///
888     /// assert_eq!(None, iter.next());
889     /// ```
890     ///
891     /// All kinds of whitespace are considered:
892     ///
893     /// ```
894     /// let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
895     /// assert_eq!(Some("Mary"), iter.next());
896     /// assert_eq!(Some("had"), iter.next());
897     /// assert_eq!(Some("a"), iter.next());
898     /// assert_eq!(Some("little"), iter.next());
899     /// assert_eq!(Some("lamb"), iter.next());
900     ///
901     /// assert_eq!(None, iter.next());
902     /// ```
903     #[must_use = "this returns the split string as an iterator, \
904                   without modifying the original"]
905     #[stable(feature = "split_whitespace", since = "1.1.0")]
906     #[cfg_attr(not(test), rustc_diagnostic_item = "str_split_whitespace")]
907     #[inline]
908     pub fn split_whitespace(&self) -> SplitWhitespace<'_> {
909         SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
910     }
911
912     /// Splits a string slice by ASCII whitespace.
913     ///
914     /// The iterator returned will return string slices that are sub-slices of
915     /// the original string slice, separated by any amount of ASCII whitespace.
916     ///
917     /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
918     ///
919     /// [`split_whitespace`]: str::split_whitespace
920     ///
921     /// # Examples
922     ///
923     /// Basic usage:
924     ///
925     /// ```
926     /// let mut iter = "A few words".split_ascii_whitespace();
927     ///
928     /// assert_eq!(Some("A"), iter.next());
929     /// assert_eq!(Some("few"), iter.next());
930     /// assert_eq!(Some("words"), iter.next());
931     ///
932     /// assert_eq!(None, iter.next());
933     /// ```
934     ///
935     /// All kinds of ASCII whitespace are considered:
936     ///
937     /// ```
938     /// let mut iter = " Mary   had\ta little  \n\t lamb".split_ascii_whitespace();
939     /// assert_eq!(Some("Mary"), iter.next());
940     /// assert_eq!(Some("had"), iter.next());
941     /// assert_eq!(Some("a"), iter.next());
942     /// assert_eq!(Some("little"), iter.next());
943     /// assert_eq!(Some("lamb"), iter.next());
944     ///
945     /// assert_eq!(None, iter.next());
946     /// ```
947     #[must_use = "this returns the split string as an iterator, \
948                   without modifying the original"]
949     #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
950     #[inline]
951     pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> {
952         let inner =
953             self.as_bytes().split(IsAsciiWhitespace).filter(BytesIsNotEmpty).map(UnsafeBytesToStr);
954         SplitAsciiWhitespace { inner }
955     }
956
957     /// An iterator over the lines of a string, as string slices.
958     ///
959     /// Lines are ended with either a newline (`\n`) or a carriage return with
960     /// a line feed (`\r\n`).
961     ///
962     /// The final line ending is optional. A string that ends with a final line
963     /// ending will return the same lines as an otherwise identical string
964     /// without a final line ending.
965     ///
966     /// # Examples
967     ///
968     /// Basic usage:
969     ///
970     /// ```
971     /// let text = "foo\r\nbar\n\nbaz\n";
972     /// let mut lines = text.lines();
973     ///
974     /// assert_eq!(Some("foo"), lines.next());
975     /// assert_eq!(Some("bar"), lines.next());
976     /// assert_eq!(Some(""), lines.next());
977     /// assert_eq!(Some("baz"), lines.next());
978     ///
979     /// assert_eq!(None, lines.next());
980     /// ```
981     ///
982     /// The final line ending isn't required:
983     ///
984     /// ```
985     /// let text = "foo\nbar\n\r\nbaz";
986     /// let mut lines = text.lines();
987     ///
988     /// assert_eq!(Some("foo"), lines.next());
989     /// assert_eq!(Some("bar"), lines.next());
990     /// assert_eq!(Some(""), lines.next());
991     /// assert_eq!(Some("baz"), lines.next());
992     ///
993     /// assert_eq!(None, lines.next());
994     /// ```
995     #[stable(feature = "rust1", since = "1.0.0")]
996     #[inline]
997     pub fn lines(&self) -> Lines<'_> {
998         Lines(self.split_terminator('\n').map(LinesAnyMap))
999     }
1000
1001     /// An iterator over the lines of a string.
1002     #[stable(feature = "rust1", since = "1.0.0")]
1003     #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
1004     #[inline]
1005     #[allow(deprecated)]
1006     pub fn lines_any(&self) -> LinesAny<'_> {
1007         LinesAny(self.lines())
1008     }
1009
1010     /// Returns an iterator of `u16` over the string encoded as UTF-16.
1011     ///
1012     /// # Examples
1013     ///
1014     /// Basic usage:
1015     ///
1016     /// ```
1017     /// let text = "Zażółć gęślą jaźń";
1018     ///
1019     /// let utf8_len = text.len();
1020     /// let utf16_len = text.encode_utf16().count();
1021     ///
1022     /// assert!(utf16_len <= utf8_len);
1023     /// ```
1024     #[must_use = "this returns the encoded string as an iterator, \
1025                   without modifying the original"]
1026     #[stable(feature = "encode_utf16", since = "1.8.0")]
1027     pub fn encode_utf16(&self) -> EncodeUtf16<'_> {
1028         EncodeUtf16 { chars: self.chars(), extra: 0 }
1029     }
1030
1031     /// Returns `true` if the given pattern matches a sub-slice of
1032     /// this string slice.
1033     ///
1034     /// Returns `false` if it does not.
1035     ///
1036     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1037     /// function or closure that determines if a character matches.
1038     ///
1039     /// [`char`]: prim@char
1040     /// [pattern]: self::pattern
1041     ///
1042     /// # Examples
1043     ///
1044     /// Basic usage:
1045     ///
1046     /// ```
1047     /// let bananas = "bananas";
1048     ///
1049     /// assert!(bananas.contains("nana"));
1050     /// assert!(!bananas.contains("apples"));
1051     /// ```
1052     #[stable(feature = "rust1", since = "1.0.0")]
1053     #[inline]
1054     pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1055         pat.is_contained_in(self)
1056     }
1057
1058     /// Returns `true` if the given pattern matches a prefix of this
1059     /// string slice.
1060     ///
1061     /// Returns `false` if it does not.
1062     ///
1063     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1064     /// function or closure that determines if a character matches.
1065     ///
1066     /// [`char`]: prim@char
1067     /// [pattern]: self::pattern
1068     ///
1069     /// # Examples
1070     ///
1071     /// Basic usage:
1072     ///
1073     /// ```
1074     /// let bananas = "bananas";
1075     ///
1076     /// assert!(bananas.starts_with("bana"));
1077     /// assert!(!bananas.starts_with("nana"));
1078     /// ```
1079     #[stable(feature = "rust1", since = "1.0.0")]
1080     pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1081         pat.is_prefix_of(self)
1082     }
1083
1084     /// Returns `true` if the given pattern matches a suffix of this
1085     /// string slice.
1086     ///
1087     /// Returns `false` if it does not.
1088     ///
1089     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1090     /// function or closure that determines if a character matches.
1091     ///
1092     /// [`char`]: prim@char
1093     /// [pattern]: self::pattern
1094     ///
1095     /// # Examples
1096     ///
1097     /// Basic usage:
1098     ///
1099     /// ```
1100     /// let bananas = "bananas";
1101     ///
1102     /// assert!(bananas.ends_with("anas"));
1103     /// assert!(!bananas.ends_with("nana"));
1104     /// ```
1105     #[stable(feature = "rust1", since = "1.0.0")]
1106     pub fn ends_with<'a, P>(&'a self, pat: P) -> bool
1107     where
1108         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1109     {
1110         pat.is_suffix_of(self)
1111     }
1112
1113     /// Returns the byte index of the first character of this string slice that
1114     /// matches the pattern.
1115     ///
1116     /// Returns [`None`] if the pattern doesn't match.
1117     ///
1118     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1119     /// function or closure that determines if a character matches.
1120     ///
1121     /// [`char`]: prim@char
1122     /// [pattern]: self::pattern
1123     ///
1124     /// # Examples
1125     ///
1126     /// Simple patterns:
1127     ///
1128     /// ```
1129     /// let s = "Löwe 老虎 Léopard Gepardi";
1130     ///
1131     /// assert_eq!(s.find('L'), Some(0));
1132     /// assert_eq!(s.find('é'), Some(14));
1133     /// assert_eq!(s.find("pard"), Some(17));
1134     /// ```
1135     ///
1136     /// More complex patterns using point-free style and closures:
1137     ///
1138     /// ```
1139     /// let s = "Löwe 老虎 Léopard";
1140     ///
1141     /// assert_eq!(s.find(char::is_whitespace), Some(5));
1142     /// assert_eq!(s.find(char::is_lowercase), Some(1));
1143     /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
1144     /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
1145     /// ```
1146     ///
1147     /// Not finding the pattern:
1148     ///
1149     /// ```
1150     /// let s = "Löwe 老虎 Léopard";
1151     /// let x: &[_] = &['1', '2'];
1152     ///
1153     /// assert_eq!(s.find(x), None);
1154     /// ```
1155     #[stable(feature = "rust1", since = "1.0.0")]
1156     #[inline]
1157     pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1158         pat.into_searcher(self).next_match().map(|(i, _)| i)
1159     }
1160
1161     /// Returns the byte index for the first character of the rightmost match of the pattern in
1162     /// this string slice.
1163     ///
1164     /// Returns [`None`] if the pattern doesn't match.
1165     ///
1166     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1167     /// function or closure that determines if a character matches.
1168     ///
1169     /// [`char`]: prim@char
1170     /// [pattern]: self::pattern
1171     ///
1172     /// # Examples
1173     ///
1174     /// Simple patterns:
1175     ///
1176     /// ```
1177     /// let s = "Löwe 老虎 Léopard Gepardi";
1178     ///
1179     /// assert_eq!(s.rfind('L'), Some(13));
1180     /// assert_eq!(s.rfind('é'), Some(14));
1181     /// assert_eq!(s.rfind("pard"), Some(24));
1182     /// ```
1183     ///
1184     /// More complex patterns with closures:
1185     ///
1186     /// ```
1187     /// let s = "Löwe 老虎 Léopard";
1188     ///
1189     /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1190     /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1191     /// ```
1192     ///
1193     /// Not finding the pattern:
1194     ///
1195     /// ```
1196     /// let s = "Löwe 老虎 Léopard";
1197     /// let x: &[_] = &['1', '2'];
1198     ///
1199     /// assert_eq!(s.rfind(x), None);
1200     /// ```
1201     #[stable(feature = "rust1", since = "1.0.0")]
1202     #[inline]
1203     pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>
1204     where
1205         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1206     {
1207         pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1208     }
1209
1210     /// An iterator over substrings of this string slice, separated by
1211     /// characters matched by a pattern.
1212     ///
1213     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1214     /// function or closure that determines if a character matches.
1215     ///
1216     /// [`char`]: prim@char
1217     /// [pattern]: self::pattern
1218     ///
1219     /// # Iterator behavior
1220     ///
1221     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1222     /// allows a reverse search and forward/reverse search yields the same
1223     /// elements. This is true for, e.g., [`char`], but not for `&str`.
1224     ///
1225     /// If the pattern allows a reverse search but its results might differ
1226     /// from a forward search, the [`rsplit`] method can be used.
1227     ///
1228     /// [`rsplit`]: str::rsplit
1229     ///
1230     /// # Examples
1231     ///
1232     /// Simple patterns:
1233     ///
1234     /// ```
1235     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1236     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1237     ///
1238     /// let v: Vec<&str> = "".split('X').collect();
1239     /// assert_eq!(v, [""]);
1240     ///
1241     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1242     /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1243     ///
1244     /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1245     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1246     ///
1247     /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1248     /// assert_eq!(v, ["abc", "def", "ghi"]);
1249     ///
1250     /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1251     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1252     /// ```
1253     ///
1254     /// If the pattern is a slice of chars, split on each occurrence of any of the characters:
1255     ///
1256     /// ```
1257     /// let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
1258     /// assert_eq!(v, ["2020", "11", "03", "23", "59"]);
1259     /// ```
1260     ///
1261     /// A more complex pattern, using a closure:
1262     ///
1263     /// ```
1264     /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1265     /// assert_eq!(v, ["abc", "def", "ghi"]);
1266     /// ```
1267     ///
1268     /// If a string contains multiple contiguous separators, you will end up
1269     /// with empty strings in the output:
1270     ///
1271     /// ```
1272     /// let x = "||||a||b|c".to_string();
1273     /// let d: Vec<_> = x.split('|').collect();
1274     ///
1275     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1276     /// ```
1277     ///
1278     /// Contiguous separators are separated by the empty string.
1279     ///
1280     /// ```
1281     /// let x = "(///)".to_string();
1282     /// let d: Vec<_> = x.split('/').collect();
1283     ///
1284     /// assert_eq!(d, &["(", "", "", ")"]);
1285     /// ```
1286     ///
1287     /// Separators at the start or end of a string are neighbored
1288     /// by empty strings.
1289     ///
1290     /// ```
1291     /// let d: Vec<_> = "010".split("0").collect();
1292     /// assert_eq!(d, &["", "1", ""]);
1293     /// ```
1294     ///
1295     /// When the empty string is used as a separator, it separates
1296     /// every character in the string, along with the beginning
1297     /// and end of the string.
1298     ///
1299     /// ```
1300     /// let f: Vec<_> = "rust".split("").collect();
1301     /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1302     /// ```
1303     ///
1304     /// Contiguous separators can lead to possibly surprising behavior
1305     /// when whitespace is used as the separator. This code is correct:
1306     ///
1307     /// ```
1308     /// let x = "    a  b c".to_string();
1309     /// let d: Vec<_> = x.split(' ').collect();
1310     ///
1311     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1312     /// ```
1313     ///
1314     /// It does _not_ give you:
1315     ///
1316     /// ```,ignore
1317     /// assert_eq!(d, &["a", "b", "c"]);
1318     /// ```
1319     ///
1320     /// Use [`split_whitespace`] for this behavior.
1321     ///
1322     /// [`split_whitespace`]: str::split_whitespace
1323     #[stable(feature = "rust1", since = "1.0.0")]
1324     #[inline]
1325     pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1326         Split(SplitInternal {
1327             start: 0,
1328             end: self.len(),
1329             matcher: pat.into_searcher(self),
1330             allow_trailing_empty: true,
1331             finished: false,
1332         })
1333     }
1334
1335     /// An iterator over substrings of this string slice, separated by
1336     /// characters matched by a pattern. Differs from the iterator produced by
1337     /// `split` in that `split_inclusive` leaves the matched part as the
1338     /// terminator of the substring.
1339     ///
1340     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1341     /// function or closure that determines if a character matches.
1342     ///
1343     /// [`char`]: prim@char
1344     /// [pattern]: self::pattern
1345     ///
1346     /// # Examples
1347     ///
1348     /// ```
1349     /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
1350     ///     .split_inclusive('\n').collect();
1351     /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
1352     /// ```
1353     ///
1354     /// If the last element of the string is matched,
1355     /// that element will be considered the terminator of the preceding substring.
1356     /// That substring will be the last item returned by the iterator.
1357     ///
1358     /// ```
1359     /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
1360     ///     .split_inclusive('\n').collect();
1361     /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1362     /// ```
1363     #[stable(feature = "split_inclusive", since = "1.51.0")]
1364     #[inline]
1365     pub fn split_inclusive<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitInclusive<'a, P> {
1366         SplitInclusive(SplitInternal {
1367             start: 0,
1368             end: self.len(),
1369             matcher: pat.into_searcher(self),
1370             allow_trailing_empty: false,
1371             finished: false,
1372         })
1373     }
1374
1375     /// An iterator over substrings of the given string slice, separated by
1376     /// characters matched by a pattern and yielded in reverse order.
1377     ///
1378     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1379     /// function or closure that determines if a character matches.
1380     ///
1381     /// [`char`]: prim@char
1382     /// [pattern]: self::pattern
1383     ///
1384     /// # Iterator behavior
1385     ///
1386     /// The returned iterator requires that the pattern supports a reverse
1387     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1388     /// search yields the same elements.
1389     ///
1390     /// For iterating from the front, the [`split`] method can be used.
1391     ///
1392     /// [`split`]: str::split
1393     ///
1394     /// # Examples
1395     ///
1396     /// Simple patterns:
1397     ///
1398     /// ```
1399     /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1400     /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1401     ///
1402     /// let v: Vec<&str> = "".rsplit('X').collect();
1403     /// assert_eq!(v, [""]);
1404     ///
1405     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1406     /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1407     ///
1408     /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1409     /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1410     /// ```
1411     ///
1412     /// A more complex pattern, using a closure:
1413     ///
1414     /// ```
1415     /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1416     /// assert_eq!(v, ["ghi", "def", "abc"]);
1417     /// ```
1418     #[stable(feature = "rust1", since = "1.0.0")]
1419     #[inline]
1420     pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P>
1421     where
1422         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1423     {
1424         RSplit(self.split(pat).0)
1425     }
1426
1427     /// An iterator over substrings of the given string slice, separated by
1428     /// characters matched by a pattern.
1429     ///
1430     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1431     /// function or closure that determines if a character matches.
1432     ///
1433     /// [`char`]: prim@char
1434     /// [pattern]: self::pattern
1435     ///
1436     /// Equivalent to [`split`], except that the trailing substring
1437     /// is skipped if empty.
1438     ///
1439     /// [`split`]: str::split
1440     ///
1441     /// This method can be used for string data that is _terminated_,
1442     /// rather than _separated_ by a pattern.
1443     ///
1444     /// # Iterator behavior
1445     ///
1446     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1447     /// allows a reverse search and forward/reverse search yields the same
1448     /// elements. This is true for, e.g., [`char`], but not for `&str`.
1449     ///
1450     /// If the pattern allows a reverse search but its results might differ
1451     /// from a forward search, the [`rsplit_terminator`] method can be used.
1452     ///
1453     /// [`rsplit_terminator`]: str::rsplit_terminator
1454     ///
1455     /// # Examples
1456     ///
1457     /// Basic usage:
1458     ///
1459     /// ```
1460     /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1461     /// assert_eq!(v, ["A", "B"]);
1462     ///
1463     /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1464     /// assert_eq!(v, ["A", "", "B", ""]);
1465     ///
1466     /// let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
1467     /// assert_eq!(v, ["A", "B", "C", "D"]);
1468     /// ```
1469     #[stable(feature = "rust1", since = "1.0.0")]
1470     #[inline]
1471     pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1472         SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 })
1473     }
1474
1475     /// An iterator over substrings of `self`, separated by characters
1476     /// matched by a pattern and yielded in reverse order.
1477     ///
1478     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1479     /// function or closure that determines if a character matches.
1480     ///
1481     /// [`char`]: prim@char
1482     /// [pattern]: self::pattern
1483     ///
1484     /// Equivalent to [`split`], except that the trailing substring is
1485     /// skipped if empty.
1486     ///
1487     /// [`split`]: str::split
1488     ///
1489     /// This method can be used for string data that is _terminated_,
1490     /// rather than _separated_ by a pattern.
1491     ///
1492     /// # Iterator behavior
1493     ///
1494     /// The returned iterator requires that the pattern supports a
1495     /// reverse search, and it will be double ended if a forward/reverse
1496     /// search yields the same elements.
1497     ///
1498     /// For iterating from the front, the [`split_terminator`] method can be
1499     /// used.
1500     ///
1501     /// [`split_terminator`]: str::split_terminator
1502     ///
1503     /// # Examples
1504     ///
1505     /// ```
1506     /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1507     /// assert_eq!(v, ["B", "A"]);
1508     ///
1509     /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1510     /// assert_eq!(v, ["", "B", "", "A"]);
1511     ///
1512     /// let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
1513     /// assert_eq!(v, ["D", "C", "B", "A"]);
1514     /// ```
1515     #[stable(feature = "rust1", since = "1.0.0")]
1516     #[inline]
1517     pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1518     where
1519         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1520     {
1521         RSplitTerminator(self.split_terminator(pat).0)
1522     }
1523
1524     /// An iterator over substrings of the given string slice, separated by a
1525     /// pattern, restricted to returning at most `n` items.
1526     ///
1527     /// If `n` substrings are returned, the last substring (the `n`th substring)
1528     /// will contain the remainder of the string.
1529     ///
1530     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1531     /// function or closure that determines if a character matches.
1532     ///
1533     /// [`char`]: prim@char
1534     /// [pattern]: self::pattern
1535     ///
1536     /// # Iterator behavior
1537     ///
1538     /// The returned iterator will not be double ended, because it is
1539     /// not efficient to support.
1540     ///
1541     /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1542     /// used.
1543     ///
1544     /// [`rsplitn`]: str::rsplitn
1545     ///
1546     /// # Examples
1547     ///
1548     /// Simple patterns:
1549     ///
1550     /// ```
1551     /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1552     /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1553     ///
1554     /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1555     /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1556     ///
1557     /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1558     /// assert_eq!(v, ["abcXdef"]);
1559     ///
1560     /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1561     /// assert_eq!(v, [""]);
1562     /// ```
1563     ///
1564     /// A more complex pattern, using a closure:
1565     ///
1566     /// ```
1567     /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1568     /// assert_eq!(v, ["abc", "defXghi"]);
1569     /// ```
1570     #[stable(feature = "rust1", since = "1.0.0")]
1571     #[inline]
1572     pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1573         SplitN(SplitNInternal { iter: self.split(pat).0, count: n })
1574     }
1575
1576     /// An iterator over substrings of this string slice, separated by a
1577     /// pattern, starting from the end of the string, restricted to returning
1578     /// at most `n` items.
1579     ///
1580     /// If `n` substrings are returned, the last substring (the `n`th substring)
1581     /// will contain the remainder of the string.
1582     ///
1583     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1584     /// function or closure that determines if a character matches.
1585     ///
1586     /// [`char`]: prim@char
1587     /// [pattern]: self::pattern
1588     ///
1589     /// # Iterator behavior
1590     ///
1591     /// The returned iterator will not be double ended, because it is not
1592     /// efficient to support.
1593     ///
1594     /// For splitting from the front, the [`splitn`] method can be used.
1595     ///
1596     /// [`splitn`]: str::splitn
1597     ///
1598     /// # Examples
1599     ///
1600     /// Simple patterns:
1601     ///
1602     /// ```
1603     /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1604     /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1605     ///
1606     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1607     /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1608     ///
1609     /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1610     /// assert_eq!(v, ["leopard", "lion::tiger"]);
1611     /// ```
1612     ///
1613     /// A more complex pattern, using a closure:
1614     ///
1615     /// ```
1616     /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1617     /// assert_eq!(v, ["ghi", "abc1def"]);
1618     /// ```
1619     #[stable(feature = "rust1", since = "1.0.0")]
1620     #[inline]
1621     pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1622     where
1623         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1624     {
1625         RSplitN(self.splitn(n, pat).0)
1626     }
1627
1628     /// Splits the string on the first occurrence of the specified delimiter and
1629     /// returns prefix before delimiter and suffix after delimiter.
1630     ///
1631     /// # Examples
1632     ///
1633     /// ```
1634     /// assert_eq!("cfg".split_once('='), None);
1635     /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
1636     /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
1637     /// ```
1638     #[stable(feature = "str_split_once", since = "1.52.0")]
1639     #[inline]
1640     pub fn split_once<'a, P: Pattern<'a>>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)> {
1641         let (start, end) = delimiter.into_searcher(self).next_match()?;
1642         // SAFETY: `Searcher` is known to return valid indices.
1643         unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
1644     }
1645
1646     /// Splits the string on the last occurrence of the specified delimiter and
1647     /// returns prefix before delimiter and suffix after delimiter.
1648     ///
1649     /// # Examples
1650     ///
1651     /// ```
1652     /// assert_eq!("cfg".rsplit_once('='), None);
1653     /// assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
1654     /// assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
1655     /// ```
1656     #[stable(feature = "str_split_once", since = "1.52.0")]
1657     #[inline]
1658     pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>
1659     where
1660         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1661     {
1662         let (start, end) = delimiter.into_searcher(self).next_match_back()?;
1663         // SAFETY: `Searcher` is known to return valid indices.
1664         unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
1665     }
1666
1667     /// An iterator over the disjoint matches of a pattern within the given string
1668     /// slice.
1669     ///
1670     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1671     /// function or closure that determines if a character matches.
1672     ///
1673     /// [`char`]: prim@char
1674     /// [pattern]: self::pattern
1675     ///
1676     /// # Iterator behavior
1677     ///
1678     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1679     /// allows a reverse search and forward/reverse search yields the same
1680     /// elements. This is true for, e.g., [`char`], but not for `&str`.
1681     ///
1682     /// If the pattern allows a reverse search but its results might differ
1683     /// from a forward search, the [`rmatches`] method can be used.
1684     ///
1685     /// [`rmatches`]: str::matches
1686     ///
1687     /// # Examples
1688     ///
1689     /// Basic usage:
1690     ///
1691     /// ```
1692     /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1693     /// assert_eq!(v, ["abc", "abc", "abc"]);
1694     ///
1695     /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1696     /// assert_eq!(v, ["1", "2", "3"]);
1697     /// ```
1698     #[stable(feature = "str_matches", since = "1.2.0")]
1699     #[inline]
1700     pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1701         Matches(MatchesInternal(pat.into_searcher(self)))
1702     }
1703
1704     /// An iterator over the disjoint matches of a pattern within this string slice,
1705     /// yielded in reverse order.
1706     ///
1707     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1708     /// function or closure that determines if a character matches.
1709     ///
1710     /// [`char`]: prim@char
1711     /// [pattern]: self::pattern
1712     ///
1713     /// # Iterator behavior
1714     ///
1715     /// The returned iterator requires that the pattern supports a reverse
1716     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1717     /// search yields the same elements.
1718     ///
1719     /// For iterating from the front, the [`matches`] method can be used.
1720     ///
1721     /// [`matches`]: str::matches
1722     ///
1723     /// # Examples
1724     ///
1725     /// Basic usage:
1726     ///
1727     /// ```
1728     /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1729     /// assert_eq!(v, ["abc", "abc", "abc"]);
1730     ///
1731     /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1732     /// assert_eq!(v, ["3", "2", "1"]);
1733     /// ```
1734     #[stable(feature = "str_matches", since = "1.2.0")]
1735     #[inline]
1736     pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P>
1737     where
1738         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1739     {
1740         RMatches(self.matches(pat).0)
1741     }
1742
1743     /// An iterator over the disjoint matches of a pattern within this string
1744     /// slice as well as the index that the match starts at.
1745     ///
1746     /// For matches of `pat` within `self` that overlap, only the indices
1747     /// corresponding to the first match are returned.
1748     ///
1749     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1750     /// function or closure that determines if a character matches.
1751     ///
1752     /// [`char`]: prim@char
1753     /// [pattern]: self::pattern
1754     ///
1755     /// # Iterator behavior
1756     ///
1757     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1758     /// allows a reverse search and forward/reverse search yields the same
1759     /// elements. This is true for, e.g., [`char`], but not for `&str`.
1760     ///
1761     /// If the pattern allows a reverse search but its results might differ
1762     /// from a forward search, the [`rmatch_indices`] method can be used.
1763     ///
1764     /// [`rmatch_indices`]: str::rmatch_indices
1765     ///
1766     /// # Examples
1767     ///
1768     /// Basic usage:
1769     ///
1770     /// ```
1771     /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1772     /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1773     ///
1774     /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1775     /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1776     ///
1777     /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1778     /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1779     /// ```
1780     #[stable(feature = "str_match_indices", since = "1.5.0")]
1781     #[inline]
1782     pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1783         MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
1784     }
1785
1786     /// An iterator over the disjoint matches of a pattern within `self`,
1787     /// yielded in reverse order along with the index of the match.
1788     ///
1789     /// For matches of `pat` within `self` that overlap, only the indices
1790     /// corresponding to the last match are returned.
1791     ///
1792     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1793     /// function or closure that determines if a character matches.
1794     ///
1795     /// [`char`]: prim@char
1796     /// [pattern]: self::pattern
1797     ///
1798     /// # Iterator behavior
1799     ///
1800     /// The returned iterator requires that the pattern supports a reverse
1801     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1802     /// search yields the same elements.
1803     ///
1804     /// For iterating from the front, the [`match_indices`] method can be used.
1805     ///
1806     /// [`match_indices`]: str::match_indices
1807     ///
1808     /// # Examples
1809     ///
1810     /// Basic usage:
1811     ///
1812     /// ```
1813     /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1814     /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1815     ///
1816     /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1817     /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1818     ///
1819     /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1820     /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1821     /// ```
1822     #[stable(feature = "str_match_indices", since = "1.5.0")]
1823     #[inline]
1824     pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P>
1825     where
1826         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1827     {
1828         RMatchIndices(self.match_indices(pat).0)
1829     }
1830
1831     /// Returns a string slice with leading and trailing whitespace removed.
1832     ///
1833     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1834     /// Core Property `White_Space`, which includes newlines.
1835     ///
1836     /// # Examples
1837     ///
1838     /// Basic usage:
1839     ///
1840     /// ```
1841     /// let s = "\n Hello\tworld\t\n";
1842     ///
1843     /// assert_eq!("Hello\tworld", s.trim());
1844     /// ```
1845     #[inline]
1846     #[must_use = "this returns the trimmed string as a slice, \
1847                   without modifying the original"]
1848     #[stable(feature = "rust1", since = "1.0.0")]
1849     #[cfg_attr(not(test), rustc_diagnostic_item = "str_trim")]
1850     pub fn trim(&self) -> &str {
1851         self.trim_matches(|c: char| c.is_whitespace())
1852     }
1853
1854     /// Returns a string slice with leading whitespace removed.
1855     ///
1856     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1857     /// Core Property `White_Space`, which includes newlines.
1858     ///
1859     /// # Text directionality
1860     ///
1861     /// A string is a sequence of bytes. `start` in this context means the first
1862     /// position of that byte string; for a left-to-right language like English or
1863     /// Russian, this will be left side, and for right-to-left languages like
1864     /// Arabic or Hebrew, this will be the right side.
1865     ///
1866     /// # Examples
1867     ///
1868     /// Basic usage:
1869     ///
1870     /// ```
1871     /// let s = "\n Hello\tworld\t\n";
1872     /// assert_eq!("Hello\tworld\t\n", s.trim_start());
1873     /// ```
1874     ///
1875     /// Directionality:
1876     ///
1877     /// ```
1878     /// let s = "  English  ";
1879     /// assert!(Some('E') == s.trim_start().chars().next());
1880     ///
1881     /// let s = "  עברית  ";
1882     /// assert!(Some('ע') == s.trim_start().chars().next());
1883     /// ```
1884     #[inline]
1885     #[must_use = "this returns the trimmed string as a new slice, \
1886                   without modifying the original"]
1887     #[stable(feature = "trim_direction", since = "1.30.0")]
1888     #[cfg_attr(not(test), rustc_diagnostic_item = "str_trim_start")]
1889     pub fn trim_start(&self) -> &str {
1890         self.trim_start_matches(|c: char| c.is_whitespace())
1891     }
1892
1893     /// Returns a string slice with trailing whitespace removed.
1894     ///
1895     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1896     /// Core Property `White_Space`, which includes newlines.
1897     ///
1898     /// # Text directionality
1899     ///
1900     /// A string is a sequence of bytes. `end` in this context means the last
1901     /// position of that byte string; for a left-to-right language like English or
1902     /// Russian, this will be right side, and for right-to-left languages like
1903     /// Arabic or Hebrew, this will be the left side.
1904     ///
1905     /// # Examples
1906     ///
1907     /// Basic usage:
1908     ///
1909     /// ```
1910     /// let s = "\n Hello\tworld\t\n";
1911     /// assert_eq!("\n Hello\tworld", s.trim_end());
1912     /// ```
1913     ///
1914     /// Directionality:
1915     ///
1916     /// ```
1917     /// let s = "  English  ";
1918     /// assert!(Some('h') == s.trim_end().chars().rev().next());
1919     ///
1920     /// let s = "  עברית  ";
1921     /// assert!(Some('ת') == s.trim_end().chars().rev().next());
1922     /// ```
1923     #[inline]
1924     #[must_use = "this returns the trimmed string as a new slice, \
1925                   without modifying the original"]
1926     #[stable(feature = "trim_direction", since = "1.30.0")]
1927     #[cfg_attr(not(test), rustc_diagnostic_item = "str_trim_end")]
1928     pub fn trim_end(&self) -> &str {
1929         self.trim_end_matches(|c: char| c.is_whitespace())
1930     }
1931
1932     /// Returns a string slice with leading whitespace removed.
1933     ///
1934     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1935     /// Core Property `White_Space`.
1936     ///
1937     /// # Text directionality
1938     ///
1939     /// A string is a sequence of bytes. 'Left' in this context means the first
1940     /// position of that byte string; for a language like Arabic or Hebrew
1941     /// which are 'right to left' rather than 'left to right', this will be
1942     /// the _right_ side, not the left.
1943     ///
1944     /// # Examples
1945     ///
1946     /// Basic usage:
1947     ///
1948     /// ```
1949     /// let s = " Hello\tworld\t";
1950     ///
1951     /// assert_eq!("Hello\tworld\t", s.trim_left());
1952     /// ```
1953     ///
1954     /// Directionality:
1955     ///
1956     /// ```
1957     /// let s = "  English";
1958     /// assert!(Some('E') == s.trim_left().chars().next());
1959     ///
1960     /// let s = "  עברית";
1961     /// assert!(Some('ע') == s.trim_left().chars().next());
1962     /// ```
1963     #[must_use = "this returns the trimmed string as a new slice, \
1964                   without modifying the original"]
1965     #[inline]
1966     #[stable(feature = "rust1", since = "1.0.0")]
1967     #[rustc_deprecated(
1968         since = "1.33.0",
1969         reason = "superseded by `trim_start`",
1970         suggestion = "trim_start"
1971     )]
1972     pub fn trim_left(&self) -> &str {
1973         self.trim_start()
1974     }
1975
1976     /// Returns a string slice with trailing whitespace removed.
1977     ///
1978     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1979     /// Core Property `White_Space`.
1980     ///
1981     /// # Text directionality
1982     ///
1983     /// A string is a sequence of bytes. 'Right' in this context means the last
1984     /// position of that byte string; for a language like Arabic or Hebrew
1985     /// which are 'right to left' rather than 'left to right', this will be
1986     /// the _left_ side, not the right.
1987     ///
1988     /// # Examples
1989     ///
1990     /// Basic usage:
1991     ///
1992     /// ```
1993     /// let s = " Hello\tworld\t";
1994     ///
1995     /// assert_eq!(" Hello\tworld", s.trim_right());
1996     /// ```
1997     ///
1998     /// Directionality:
1999     ///
2000     /// ```
2001     /// let s = "English  ";
2002     /// assert!(Some('h') == s.trim_right().chars().rev().next());
2003     ///
2004     /// let s = "עברית  ";
2005     /// assert!(Some('ת') == s.trim_right().chars().rev().next());
2006     /// ```
2007     #[must_use = "this returns the trimmed string as a new slice, \
2008                   without modifying the original"]
2009     #[inline]
2010     #[stable(feature = "rust1", since = "1.0.0")]
2011     #[rustc_deprecated(
2012         since = "1.33.0",
2013         reason = "superseded by `trim_end`",
2014         suggestion = "trim_end"
2015     )]
2016     pub fn trim_right(&self) -> &str {
2017         self.trim_end()
2018     }
2019
2020     /// Returns a string slice with all prefixes and suffixes that match a
2021     /// pattern repeatedly removed.
2022     ///
2023     /// The [pattern] can be a [`char`], a slice of [`char`]s, or a function
2024     /// or closure that determines if a character matches.
2025     ///
2026     /// [`char`]: prim@char
2027     /// [pattern]: self::pattern
2028     ///
2029     /// # Examples
2030     ///
2031     /// Simple patterns:
2032     ///
2033     /// ```
2034     /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
2035     /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
2036     ///
2037     /// let x: &[_] = &['1', '2'];
2038     /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
2039     /// ```
2040     ///
2041     /// A more complex pattern, using a closure:
2042     ///
2043     /// ```
2044     /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
2045     /// ```
2046     #[must_use = "this returns the trimmed string as a new slice, \
2047                   without modifying the original"]
2048     #[stable(feature = "rust1", since = "1.0.0")]
2049     pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str
2050     where
2051         P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>,
2052     {
2053         let mut i = 0;
2054         let mut j = 0;
2055         let mut matcher = pat.into_searcher(self);
2056         if let Some((a, b)) = matcher.next_reject() {
2057             i = a;
2058             j = b; // Remember earliest known match, correct it below if
2059             // last match is different
2060         }
2061         if let Some((_, b)) = matcher.next_reject_back() {
2062             j = b;
2063         }
2064         // SAFETY: `Searcher` is known to return valid indices.
2065         unsafe { self.get_unchecked(i..j) }
2066     }
2067
2068     /// Returns a string slice with all prefixes that match a pattern
2069     /// repeatedly removed.
2070     ///
2071     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2072     /// function or closure that determines if a character matches.
2073     ///
2074     /// [`char`]: prim@char
2075     /// [pattern]: self::pattern
2076     ///
2077     /// # Text directionality
2078     ///
2079     /// A string is a sequence of bytes. `start` in this context means the first
2080     /// position of that byte string; for a left-to-right language like English or
2081     /// Russian, this will be left side, and for right-to-left languages like
2082     /// Arabic or Hebrew, this will be the right side.
2083     ///
2084     /// # Examples
2085     ///
2086     /// Basic usage:
2087     ///
2088     /// ```
2089     /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
2090     /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
2091     ///
2092     /// let x: &[_] = &['1', '2'];
2093     /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
2094     /// ```
2095     #[must_use = "this returns the trimmed string as a new slice, \
2096                   without modifying the original"]
2097     #[stable(feature = "trim_direction", since = "1.30.0")]
2098     pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2099         let mut i = self.len();
2100         let mut matcher = pat.into_searcher(self);
2101         if let Some((a, _)) = matcher.next_reject() {
2102             i = a;
2103         }
2104         // SAFETY: `Searcher` is known to return valid indices.
2105         unsafe { self.get_unchecked(i..self.len()) }
2106     }
2107
2108     /// Returns a string slice with the prefix removed.
2109     ///
2110     /// If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped
2111     /// in `Some`.  Unlike `trim_start_matches`, this method removes the prefix exactly once.
2112     ///
2113     /// If the string does not start with `prefix`, returns `None`.
2114     ///
2115     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2116     /// function or closure that determines if a character matches.
2117     ///
2118     /// [`char`]: prim@char
2119     /// [pattern]: self::pattern
2120     ///
2121     /// # Examples
2122     ///
2123     /// ```
2124     /// assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
2125     /// assert_eq!("foo:bar".strip_prefix("bar"), None);
2126     /// assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
2127     /// ```
2128     #[must_use = "this returns the remaining substring as a new slice, \
2129                   without modifying the original"]
2130     #[stable(feature = "str_strip", since = "1.45.0")]
2131     pub fn strip_prefix<'a, P: Pattern<'a>>(&'a self, prefix: P) -> Option<&'a str> {
2132         prefix.strip_prefix_of(self)
2133     }
2134
2135     /// Returns a string slice with the suffix removed.
2136     ///
2137     /// If the string ends with the pattern `suffix`, returns the substring before the suffix,
2138     /// wrapped in `Some`.  Unlike `trim_end_matches`, this method removes the suffix exactly once.
2139     ///
2140     /// If the string does not end with `suffix`, returns `None`.
2141     ///
2142     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2143     /// function or closure that determines if a character matches.
2144     ///
2145     /// [`char`]: prim@char
2146     /// [pattern]: self::pattern
2147     ///
2148     /// # Examples
2149     ///
2150     /// ```
2151     /// assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
2152     /// assert_eq!("bar:foo".strip_suffix("bar"), None);
2153     /// assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
2154     /// ```
2155     #[must_use = "this returns the remaining substring as a new slice, \
2156                   without modifying the original"]
2157     #[stable(feature = "str_strip", since = "1.45.0")]
2158     pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>
2159     where
2160         P: Pattern<'a>,
2161         <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
2162     {
2163         suffix.strip_suffix_of(self)
2164     }
2165
2166     /// Returns a string slice with all suffixes that match a pattern
2167     /// repeatedly removed.
2168     ///
2169     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2170     /// function or closure that determines if a character matches.
2171     ///
2172     /// [`char`]: prim@char
2173     /// [pattern]: self::pattern
2174     ///
2175     /// # Text directionality
2176     ///
2177     /// A string is a sequence of bytes. `end` in this context means the last
2178     /// position of that byte string; for a left-to-right language like English or
2179     /// Russian, this will be right side, and for right-to-left languages like
2180     /// Arabic or Hebrew, this will be the left side.
2181     ///
2182     /// # Examples
2183     ///
2184     /// Simple patterns:
2185     ///
2186     /// ```
2187     /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
2188     /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
2189     ///
2190     /// let x: &[_] = &['1', '2'];
2191     /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
2192     /// ```
2193     ///
2194     /// A more complex pattern, using a closure:
2195     ///
2196     /// ```
2197     /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
2198     /// ```
2199     #[must_use = "this returns the trimmed string as a new slice, \
2200                   without modifying the original"]
2201     #[stable(feature = "trim_direction", since = "1.30.0")]
2202     pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str
2203     where
2204         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2205     {
2206         let mut j = 0;
2207         let mut matcher = pat.into_searcher(self);
2208         if let Some((_, b)) = matcher.next_reject_back() {
2209             j = b;
2210         }
2211         // SAFETY: `Searcher` is known to return valid indices.
2212         unsafe { self.get_unchecked(0..j) }
2213     }
2214
2215     /// Returns a string slice with all prefixes that match a pattern
2216     /// repeatedly removed.
2217     ///
2218     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2219     /// function or closure that determines if a character matches.
2220     ///
2221     /// [`char`]: prim@char
2222     /// [pattern]: self::pattern
2223     ///
2224     /// # Text directionality
2225     ///
2226     /// A string is a sequence of bytes. 'Left' in this context means the first
2227     /// position of that byte string; for a language like Arabic or Hebrew
2228     /// which are 'right to left' rather than 'left to right', this will be
2229     /// the _right_ side, not the left.
2230     ///
2231     /// # Examples
2232     ///
2233     /// Basic usage:
2234     ///
2235     /// ```
2236     /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
2237     /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
2238     ///
2239     /// let x: &[_] = &['1', '2'];
2240     /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
2241     /// ```
2242     #[stable(feature = "rust1", since = "1.0.0")]
2243     #[rustc_deprecated(
2244         since = "1.33.0",
2245         reason = "superseded by `trim_start_matches`",
2246         suggestion = "trim_start_matches"
2247     )]
2248     pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2249         self.trim_start_matches(pat)
2250     }
2251
2252     /// Returns a string slice with all suffixes that match a pattern
2253     /// repeatedly removed.
2254     ///
2255     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2256     /// function or closure that determines if a character matches.
2257     ///
2258     /// [`char`]: prim@char
2259     /// [pattern]: self::pattern
2260     ///
2261     /// # Text directionality
2262     ///
2263     /// A string is a sequence of bytes. 'Right' in this context means the last
2264     /// position of that byte string; for a language like Arabic or Hebrew
2265     /// which are 'right to left' rather than 'left to right', this will be
2266     /// the _left_ side, not the right.
2267     ///
2268     /// # Examples
2269     ///
2270     /// Simple patterns:
2271     ///
2272     /// ```
2273     /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
2274     /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
2275     ///
2276     /// let x: &[_] = &['1', '2'];
2277     /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
2278     /// ```
2279     ///
2280     /// A more complex pattern, using a closure:
2281     ///
2282     /// ```
2283     /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
2284     /// ```
2285     #[stable(feature = "rust1", since = "1.0.0")]
2286     #[rustc_deprecated(
2287         since = "1.33.0",
2288         reason = "superseded by `trim_end_matches`",
2289         suggestion = "trim_end_matches"
2290     )]
2291     pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str
2292     where
2293         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2294     {
2295         self.trim_end_matches(pat)
2296     }
2297
2298     /// Parses this string slice into another type.
2299     ///
2300     /// Because `parse` is so general, it can cause problems with type
2301     /// inference. As such, `parse` is one of the few times you'll see
2302     /// the syntax affectionately known as the 'turbofish': `::<>`. This
2303     /// helps the inference algorithm understand specifically which type
2304     /// you're trying to parse into.
2305     ///
2306     /// `parse` can parse into any type that implements the [`FromStr`] trait.
2307
2308     ///
2309     /// # Errors
2310     ///
2311     /// Will return [`Err`] if it's not possible to parse this string slice into
2312     /// the desired type.
2313     ///
2314     /// [`Err`]: FromStr::Err
2315     ///
2316     /// # Examples
2317     ///
2318     /// Basic usage
2319     ///
2320     /// ```
2321     /// let four: u32 = "4".parse().unwrap();
2322     ///
2323     /// assert_eq!(4, four);
2324     /// ```
2325     ///
2326     /// Using the 'turbofish' instead of annotating `four`:
2327     ///
2328     /// ```
2329     /// let four = "4".parse::<u32>();
2330     ///
2331     /// assert_eq!(Ok(4), four);
2332     /// ```
2333     ///
2334     /// Failing to parse:
2335     ///
2336     /// ```
2337     /// let nope = "j".parse::<u32>();
2338     ///
2339     /// assert!(nope.is_err());
2340     /// ```
2341     #[inline]
2342     #[stable(feature = "rust1", since = "1.0.0")]
2343     pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
2344         FromStr::from_str(self)
2345     }
2346
2347     /// Checks if all characters in this string are within the ASCII range.
2348     ///
2349     /// # Examples
2350     ///
2351     /// ```
2352     /// let ascii = "hello!\n";
2353     /// let non_ascii = "Grüße, Jürgen ❤";
2354     ///
2355     /// assert!(ascii.is_ascii());
2356     /// assert!(!non_ascii.is_ascii());
2357     /// ```
2358     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2359     #[must_use]
2360     #[inline]
2361     pub fn is_ascii(&self) -> bool {
2362         // We can treat each byte as character here: all multibyte characters
2363         // start with a byte that is not in the ascii range, so we will stop
2364         // there already.
2365         self.as_bytes().is_ascii()
2366     }
2367
2368     /// Checks that two strings are an ASCII case-insensitive match.
2369     ///
2370     /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2371     /// but without allocating and copying temporaries.
2372     ///
2373     /// # Examples
2374     ///
2375     /// ```
2376     /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2377     /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2378     /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2379     /// ```
2380     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2381     #[must_use]
2382     #[inline]
2383     pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
2384         self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
2385     }
2386
2387     /// Converts this string to its ASCII upper case equivalent in-place.
2388     ///
2389     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2390     /// but non-ASCII letters are unchanged.
2391     ///
2392     /// To return a new uppercased value without modifying the existing one, use
2393     /// [`to_ascii_uppercase()`].
2394     ///
2395     /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
2396     ///
2397     /// # Examples
2398     ///
2399     /// ```
2400     /// let mut s = String::from("Grüße, Jürgen ❤");
2401     ///
2402     /// s.make_ascii_uppercase();
2403     ///
2404     /// assert_eq!("GRüßE, JüRGEN ❤", s);
2405     /// ```
2406     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2407     #[inline]
2408     pub fn make_ascii_uppercase(&mut self) {
2409         // SAFETY: safe because we transmute two types with the same layout.
2410         let me = unsafe { self.as_bytes_mut() };
2411         me.make_ascii_uppercase()
2412     }
2413
2414     /// Converts this string to its ASCII lower case equivalent in-place.
2415     ///
2416     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2417     /// but non-ASCII letters are unchanged.
2418     ///
2419     /// To return a new lowercased value without modifying the existing one, use
2420     /// [`to_ascii_lowercase()`].
2421     ///
2422     /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
2423     ///
2424     /// # Examples
2425     ///
2426     /// ```
2427     /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
2428     ///
2429     /// s.make_ascii_lowercase();
2430     ///
2431     /// assert_eq!("grÜße, jÜrgen ❤", s);
2432     /// ```
2433     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2434     #[inline]
2435     pub fn make_ascii_lowercase(&mut self) {
2436         // SAFETY: safe because we transmute two types with the same layout.
2437         let me = unsafe { self.as_bytes_mut() };
2438         me.make_ascii_lowercase()
2439     }
2440
2441     /// Return an iterator that escapes each char in `self` with [`char::escape_debug`].
2442     ///
2443     /// Note: only extended grapheme codepoints that begin the string will be
2444     /// escaped.
2445     ///
2446     /// # Examples
2447     ///
2448     /// As an iterator:
2449     ///
2450     /// ```
2451     /// for c in "❤\n!".escape_debug() {
2452     ///     print!("{c}");
2453     /// }
2454     /// println!();
2455     /// ```
2456     ///
2457     /// Using `println!` directly:
2458     ///
2459     /// ```
2460     /// println!("{}", "❤\n!".escape_debug());
2461     /// ```
2462     ///
2463     ///
2464     /// Both are equivalent to:
2465     ///
2466     /// ```
2467     /// println!("❤\\n!");
2468     /// ```
2469     ///
2470     /// Using `to_string`:
2471     ///
2472     /// ```
2473     /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
2474     /// ```
2475     #[must_use = "this returns the escaped string as an iterator, \
2476                   without modifying the original"]
2477     #[stable(feature = "str_escape", since = "1.34.0")]
2478     pub fn escape_debug(&self) -> EscapeDebug<'_> {
2479         let mut chars = self.chars();
2480         EscapeDebug {
2481             inner: chars
2482                 .next()
2483                 .map(|first| first.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL))
2484                 .into_iter()
2485                 .flatten()
2486                 .chain(chars.flat_map(CharEscapeDebugContinue)),
2487         }
2488     }
2489
2490     /// Return an iterator that escapes each char in `self` with [`char::escape_default`].
2491     ///
2492     /// # Examples
2493     ///
2494     /// As an iterator:
2495     ///
2496     /// ```
2497     /// for c in "❤\n!".escape_default() {
2498     ///     print!("{c}");
2499     /// }
2500     /// println!();
2501     /// ```
2502     ///
2503     /// Using `println!` directly:
2504     ///
2505     /// ```
2506     /// println!("{}", "❤\n!".escape_default());
2507     /// ```
2508     ///
2509     ///
2510     /// Both are equivalent to:
2511     ///
2512     /// ```
2513     /// println!("\\u{{2764}}\\n!");
2514     /// ```
2515     ///
2516     /// Using `to_string`:
2517     ///
2518     /// ```
2519     /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
2520     /// ```
2521     #[must_use = "this returns the escaped string as an iterator, \
2522                   without modifying the original"]
2523     #[stable(feature = "str_escape", since = "1.34.0")]
2524     pub fn escape_default(&self) -> EscapeDefault<'_> {
2525         EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
2526     }
2527
2528     /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`].
2529     ///
2530     /// # Examples
2531     ///
2532     /// As an iterator:
2533     ///
2534     /// ```
2535     /// for c in "❤\n!".escape_unicode() {
2536     ///     print!("{c}");
2537     /// }
2538     /// println!();
2539     /// ```
2540     ///
2541     /// Using `println!` directly:
2542     ///
2543     /// ```
2544     /// println!("{}", "❤\n!".escape_unicode());
2545     /// ```
2546     ///
2547     ///
2548     /// Both are equivalent to:
2549     ///
2550     /// ```
2551     /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
2552     /// ```
2553     ///
2554     /// Using `to_string`:
2555     ///
2556     /// ```
2557     /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
2558     /// ```
2559     #[must_use = "this returns the escaped string as an iterator, \
2560                   without modifying the original"]
2561     #[stable(feature = "str_escape", since = "1.34.0")]
2562     pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
2563         EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
2564     }
2565 }
2566
2567 #[stable(feature = "rust1", since = "1.0.0")]
2568 impl AsRef<[u8]> for str {
2569     #[inline]
2570     fn as_ref(&self) -> &[u8] {
2571         self.as_bytes()
2572     }
2573 }
2574
2575 #[stable(feature = "rust1", since = "1.0.0")]
2576 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
2577 impl const Default for &str {
2578     /// Creates an empty str
2579     #[inline]
2580     fn default() -> Self {
2581         ""
2582     }
2583 }
2584
2585 #[stable(feature = "default_mut_str", since = "1.28.0")]
2586 impl Default for &mut str {
2587     /// Creates an empty mutable str
2588     #[inline]
2589     fn default() -> Self {
2590         // SAFETY: The empty string is valid UTF-8.
2591         unsafe { from_utf8_unchecked_mut(&mut []) }
2592     }
2593 }
2594
2595 impl_fn_for_zst! {
2596     /// A nameable, cloneable fn type
2597     #[derive(Clone)]
2598     struct LinesAnyMap impl<'a> Fn = |line: &'a str| -> &'a str {
2599         let l = line.len();
2600         if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
2601         else { line }
2602     };
2603
2604     #[derive(Clone)]
2605     struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
2606         c.escape_debug_ext(EscapeDebugExtArgs {
2607             escape_grapheme_extended: false,
2608             escape_single_quote: true,
2609             escape_double_quote: true
2610         })
2611     };
2612
2613     #[derive(Clone)]
2614     struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
2615         c.escape_unicode()
2616     };
2617     #[derive(Clone)]
2618     struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
2619         c.escape_default()
2620     };
2621
2622     #[derive(Clone)]
2623     struct IsWhitespace impl Fn = |c: char| -> bool {
2624         c.is_whitespace()
2625     };
2626
2627     #[derive(Clone)]
2628     struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
2629         byte.is_ascii_whitespace()
2630     };
2631
2632     #[derive(Clone)]
2633     struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
2634         !s.is_empty()
2635     };
2636
2637     #[derive(Clone)]
2638     struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
2639         !s.is_empty()
2640     };
2641
2642     #[derive(Clone)]
2643     struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
2644         // SAFETY: not safe
2645         unsafe { from_utf8_unchecked(bytes) }
2646     };
2647 }