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