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