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