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