]> git.lizzy.rs Git - rust.git/blob - library/core/src/str/mod.rs
Auto merge of #99292 - Aaron1011:stability-use-tree, r=cjgillot
[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 libstd 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]
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]
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     #[must_use = "this returns the split string as an iterator, \
906                   without modifying the original"]
907     #[stable(feature = "split_whitespace", since = "1.1.0")]
908     #[cfg_attr(not(test), rustc_diagnostic_item = "str_split_whitespace")]
909     #[inline]
910     pub fn split_whitespace(&self) -> SplitWhitespace<'_> {
911         SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
912     }
913
914     /// Splits a string slice by ASCII whitespace.
915     ///
916     /// The iterator returned will return string slices that are sub-slices of
917     /// the original string slice, separated by any amount of ASCII whitespace.
918     ///
919     /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
920     ///
921     /// [`split_whitespace`]: str::split_whitespace
922     ///
923     /// # Examples
924     ///
925     /// Basic usage:
926     ///
927     /// ```
928     /// let mut iter = "A few words".split_ascii_whitespace();
929     ///
930     /// assert_eq!(Some("A"), iter.next());
931     /// assert_eq!(Some("few"), iter.next());
932     /// assert_eq!(Some("words"), iter.next());
933     ///
934     /// assert_eq!(None, iter.next());
935     /// ```
936     ///
937     /// All kinds of ASCII whitespace are considered:
938     ///
939     /// ```
940     /// let mut iter = " Mary   had\ta little  \n\t lamb".split_ascii_whitespace();
941     /// assert_eq!(Some("Mary"), iter.next());
942     /// assert_eq!(Some("had"), iter.next());
943     /// assert_eq!(Some("a"), iter.next());
944     /// assert_eq!(Some("little"), iter.next());
945     /// assert_eq!(Some("lamb"), iter.next());
946     ///
947     /// assert_eq!(None, iter.next());
948     /// ```
949     #[must_use = "this returns the split string as an iterator, \
950                   without modifying the original"]
951     #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
952     #[inline]
953     pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> {
954         let inner =
955             self.as_bytes().split(IsAsciiWhitespace).filter(BytesIsNotEmpty).map(UnsafeBytesToStr);
956         SplitAsciiWhitespace { inner }
957     }
958
959     /// An iterator over the lines of a string, as string slices.
960     ///
961     /// Lines are ended with either a newline (`\n`) or a carriage return with
962     /// a line feed (`\r\n`).
963     ///
964     /// The final line ending is optional. A string that ends with a final line
965     /// ending will return the same lines as an otherwise identical string
966     /// without a final line ending.
967     ///
968     /// # Examples
969     ///
970     /// Basic usage:
971     ///
972     /// ```
973     /// let text = "foo\r\nbar\n\nbaz\n";
974     /// let mut lines = text.lines();
975     ///
976     /// assert_eq!(Some("foo"), lines.next());
977     /// assert_eq!(Some("bar"), lines.next());
978     /// assert_eq!(Some(""), lines.next());
979     /// assert_eq!(Some("baz"), lines.next());
980     ///
981     /// assert_eq!(None, lines.next());
982     /// ```
983     ///
984     /// The final line ending isn't required:
985     ///
986     /// ```
987     /// let text = "foo\nbar\n\r\nbaz";
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     #[stable(feature = "rust1", since = "1.0.0")]
998     #[inline]
999     pub fn lines(&self) -> Lines<'_> {
1000         Lines(self.split_terminator('\n').map(LinesAnyMap))
1001     }
1002
1003     /// An iterator over the lines of a string.
1004     #[stable(feature = "rust1", since = "1.0.0")]
1005     #[deprecated(since = "1.4.0", note = "use lines() instead now")]
1006     #[inline]
1007     #[allow(deprecated)]
1008     pub fn lines_any(&self) -> LinesAny<'_> {
1009         LinesAny(self.lines())
1010     }
1011
1012     /// Returns an iterator of `u16` over the string encoded as UTF-16.
1013     ///
1014     /// # Examples
1015     ///
1016     /// Basic usage:
1017     ///
1018     /// ```
1019     /// let text = "Zażółć gęślą jaźń";
1020     ///
1021     /// let utf8_len = text.len();
1022     /// let utf16_len = text.encode_utf16().count();
1023     ///
1024     /// assert!(utf16_len <= utf8_len);
1025     /// ```
1026     #[must_use = "this returns the encoded string as an iterator, \
1027                   without modifying the original"]
1028     #[stable(feature = "encode_utf16", since = "1.8.0")]
1029     pub fn encode_utf16(&self) -> EncodeUtf16<'_> {
1030         EncodeUtf16 { chars: self.chars(), extra: 0 }
1031     }
1032
1033     /// Returns `true` if the given pattern matches a sub-slice of
1034     /// this string slice.
1035     ///
1036     /// Returns `false` if it does not.
1037     ///
1038     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1039     /// function or closure that determines if a character matches.
1040     ///
1041     /// [`char`]: prim@char
1042     /// [pattern]: self::pattern
1043     ///
1044     /// # Examples
1045     ///
1046     /// Basic usage:
1047     ///
1048     /// ```
1049     /// let bananas = "bananas";
1050     ///
1051     /// assert!(bananas.contains("nana"));
1052     /// assert!(!bananas.contains("apples"));
1053     /// ```
1054     #[stable(feature = "rust1", since = "1.0.0")]
1055     #[inline]
1056     pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1057         pat.is_contained_in(self)
1058     }
1059
1060     /// Returns `true` if the given pattern matches a prefix of this
1061     /// string slice.
1062     ///
1063     /// Returns `false` if it does not.
1064     ///
1065     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1066     /// function or closure that determines if a character matches.
1067     ///
1068     /// [`char`]: prim@char
1069     /// [pattern]: self::pattern
1070     ///
1071     /// # Examples
1072     ///
1073     /// Basic usage:
1074     ///
1075     /// ```
1076     /// let bananas = "bananas";
1077     ///
1078     /// assert!(bananas.starts_with("bana"));
1079     /// assert!(!bananas.starts_with("nana"));
1080     /// ```
1081     #[stable(feature = "rust1", since = "1.0.0")]
1082     pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1083         pat.is_prefix_of(self)
1084     }
1085
1086     /// Returns `true` if the given pattern matches a suffix of this
1087     /// string slice.
1088     ///
1089     /// Returns `false` if it does not.
1090     ///
1091     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1092     /// function or closure that determines if a character matches.
1093     ///
1094     /// [`char`]: prim@char
1095     /// [pattern]: self::pattern
1096     ///
1097     /// # Examples
1098     ///
1099     /// Basic usage:
1100     ///
1101     /// ```
1102     /// let bananas = "bananas";
1103     ///
1104     /// assert!(bananas.ends_with("anas"));
1105     /// assert!(!bananas.ends_with("nana"));
1106     /// ```
1107     #[stable(feature = "rust1", since = "1.0.0")]
1108     pub fn ends_with<'a, P>(&'a self, pat: P) -> bool
1109     where
1110         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1111     {
1112         pat.is_suffix_of(self)
1113     }
1114
1115     /// Returns the byte index of the first character of this string slice that
1116     /// matches the pattern.
1117     ///
1118     /// Returns [`None`] if the pattern doesn't match.
1119     ///
1120     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1121     /// function or closure that determines if a character matches.
1122     ///
1123     /// [`char`]: prim@char
1124     /// [pattern]: self::pattern
1125     ///
1126     /// # Examples
1127     ///
1128     /// Simple patterns:
1129     ///
1130     /// ```
1131     /// let s = "Löwe 老虎 Léopard Gepardi";
1132     ///
1133     /// assert_eq!(s.find('L'), Some(0));
1134     /// assert_eq!(s.find('é'), Some(14));
1135     /// assert_eq!(s.find("pard"), Some(17));
1136     /// ```
1137     ///
1138     /// More complex patterns using point-free style and closures:
1139     ///
1140     /// ```
1141     /// let s = "Löwe 老虎 Léopard";
1142     ///
1143     /// assert_eq!(s.find(char::is_whitespace), Some(5));
1144     /// assert_eq!(s.find(char::is_lowercase), Some(1));
1145     /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
1146     /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
1147     /// ```
1148     ///
1149     /// Not finding the pattern:
1150     ///
1151     /// ```
1152     /// let s = "Löwe 老虎 Léopard";
1153     /// let x: &[_] = &['1', '2'];
1154     ///
1155     /// assert_eq!(s.find(x), None);
1156     /// ```
1157     #[stable(feature = "rust1", since = "1.0.0")]
1158     #[inline]
1159     pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1160         pat.into_searcher(self).next_match().map(|(i, _)| i)
1161     }
1162
1163     /// Returns the byte index for the first character of the last match of the pattern in
1164     /// this string slice.
1165     ///
1166     /// Returns [`None`] if the pattern doesn't match.
1167     ///
1168     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1169     /// function or closure that determines if a character matches.
1170     ///
1171     /// [`char`]: prim@char
1172     /// [pattern]: self::pattern
1173     ///
1174     /// # Examples
1175     ///
1176     /// Simple patterns:
1177     ///
1178     /// ```
1179     /// let s = "Löwe 老虎 Léopard Gepardi";
1180     ///
1181     /// assert_eq!(s.rfind('L'), Some(13));
1182     /// assert_eq!(s.rfind('é'), Some(14));
1183     /// assert_eq!(s.rfind("pard"), Some(24));
1184     /// ```
1185     ///
1186     /// More complex patterns with closures:
1187     ///
1188     /// ```
1189     /// let s = "Löwe 老虎 Léopard";
1190     ///
1191     /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1192     /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1193     /// ```
1194     ///
1195     /// Not finding the pattern:
1196     ///
1197     /// ```
1198     /// let s = "Löwe 老虎 Léopard";
1199     /// let x: &[_] = &['1', '2'];
1200     ///
1201     /// assert_eq!(s.rfind(x), None);
1202     /// ```
1203     #[stable(feature = "rust1", since = "1.0.0")]
1204     #[inline]
1205     pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>
1206     where
1207         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1208     {
1209         pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1210     }
1211
1212     /// An iterator over substrings of this string slice, separated by
1213     /// characters matched by a pattern.
1214     ///
1215     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1216     /// function or closure that determines if a character matches.
1217     ///
1218     /// [`char`]: prim@char
1219     /// [pattern]: self::pattern
1220     ///
1221     /// # Iterator behavior
1222     ///
1223     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1224     /// allows a reverse search and forward/reverse search yields the same
1225     /// elements. This is true for, e.g., [`char`], but not for `&str`.
1226     ///
1227     /// If the pattern allows a reverse search but its results might differ
1228     /// from a forward search, the [`rsplit`] method can be used.
1229     ///
1230     /// [`rsplit`]: str::rsplit
1231     ///
1232     /// # Examples
1233     ///
1234     /// Simple patterns:
1235     ///
1236     /// ```
1237     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1238     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1239     ///
1240     /// let v: Vec<&str> = "".split('X').collect();
1241     /// assert_eq!(v, [""]);
1242     ///
1243     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1244     /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1245     ///
1246     /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1247     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1248     ///
1249     /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1250     /// assert_eq!(v, ["abc", "def", "ghi"]);
1251     ///
1252     /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1253     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1254     /// ```
1255     ///
1256     /// If the pattern is a slice of chars, split on each occurrence of any of the characters:
1257     ///
1258     /// ```
1259     /// let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
1260     /// assert_eq!(v, ["2020", "11", "03", "23", "59"]);
1261     /// ```
1262     ///
1263     /// A more complex pattern, using a closure:
1264     ///
1265     /// ```
1266     /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1267     /// assert_eq!(v, ["abc", "def", "ghi"]);
1268     /// ```
1269     ///
1270     /// If a string contains multiple contiguous separators, you will end up
1271     /// with empty strings in the output:
1272     ///
1273     /// ```
1274     /// let x = "||||a||b|c".to_string();
1275     /// let d: Vec<_> = x.split('|').collect();
1276     ///
1277     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1278     /// ```
1279     ///
1280     /// Contiguous separators are separated by the empty string.
1281     ///
1282     /// ```
1283     /// let x = "(///)".to_string();
1284     /// let d: Vec<_> = x.split('/').collect();
1285     ///
1286     /// assert_eq!(d, &["(", "", "", ")"]);
1287     /// ```
1288     ///
1289     /// Separators at the start or end of a string are neighbored
1290     /// by empty strings.
1291     ///
1292     /// ```
1293     /// let d: Vec<_> = "010".split("0").collect();
1294     /// assert_eq!(d, &["", "1", ""]);
1295     /// ```
1296     ///
1297     /// When the empty string is used as a separator, it separates
1298     /// every character in the string, along with the beginning
1299     /// and end of the string.
1300     ///
1301     /// ```
1302     /// let f: Vec<_> = "rust".split("").collect();
1303     /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1304     /// ```
1305     ///
1306     /// Contiguous separators can lead to possibly surprising behavior
1307     /// when whitespace is used as the separator. This code is correct:
1308     ///
1309     /// ```
1310     /// let x = "    a  b c".to_string();
1311     /// let d: Vec<_> = x.split(' ').collect();
1312     ///
1313     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1314     /// ```
1315     ///
1316     /// It does _not_ give you:
1317     ///
1318     /// ```,ignore
1319     /// assert_eq!(d, &["a", "b", "c"]);
1320     /// ```
1321     ///
1322     /// Use [`split_whitespace`] for this behavior.
1323     ///
1324     /// [`split_whitespace`]: str::split_whitespace
1325     #[stable(feature = "rust1", since = "1.0.0")]
1326     #[inline]
1327     pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1328         Split(SplitInternal {
1329             start: 0,
1330             end: self.len(),
1331             matcher: pat.into_searcher(self),
1332             allow_trailing_empty: true,
1333             finished: false,
1334         })
1335     }
1336
1337     /// An iterator over substrings of this string slice, separated by
1338     /// characters matched by a pattern. Differs from the iterator produced by
1339     /// `split` in that `split_inclusive` leaves the matched part as the
1340     /// terminator of the substring.
1341     ///
1342     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1343     /// function or closure that determines if a character matches.
1344     ///
1345     /// [`char`]: prim@char
1346     /// [pattern]: self::pattern
1347     ///
1348     /// # Examples
1349     ///
1350     /// ```
1351     /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
1352     ///     .split_inclusive('\n').collect();
1353     /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
1354     /// ```
1355     ///
1356     /// If the last element of the string is matched,
1357     /// that element will be considered the terminator of the preceding substring.
1358     /// That substring will be the last item returned by the iterator.
1359     ///
1360     /// ```
1361     /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
1362     ///     .split_inclusive('\n').collect();
1363     /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1364     /// ```
1365     #[stable(feature = "split_inclusive", since = "1.51.0")]
1366     #[inline]
1367     pub fn split_inclusive<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitInclusive<'a, P> {
1368         SplitInclusive(SplitInternal {
1369             start: 0,
1370             end: self.len(),
1371             matcher: pat.into_searcher(self),
1372             allow_trailing_empty: false,
1373             finished: false,
1374         })
1375     }
1376
1377     /// An iterator over substrings of the given string slice, separated by
1378     /// characters matched by a pattern and yielded in reverse order.
1379     ///
1380     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1381     /// function or closure that determines if a character matches.
1382     ///
1383     /// [`char`]: prim@char
1384     /// [pattern]: self::pattern
1385     ///
1386     /// # Iterator behavior
1387     ///
1388     /// The returned iterator requires that the pattern supports a reverse
1389     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1390     /// search yields the same elements.
1391     ///
1392     /// For iterating from the front, the [`split`] method can be used.
1393     ///
1394     /// [`split`]: str::split
1395     ///
1396     /// # Examples
1397     ///
1398     /// Simple patterns:
1399     ///
1400     /// ```
1401     /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1402     /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1403     ///
1404     /// let v: Vec<&str> = "".rsplit('X').collect();
1405     /// assert_eq!(v, [""]);
1406     ///
1407     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1408     /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1409     ///
1410     /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1411     /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1412     /// ```
1413     ///
1414     /// A more complex pattern, using a closure:
1415     ///
1416     /// ```
1417     /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1418     /// assert_eq!(v, ["ghi", "def", "abc"]);
1419     /// ```
1420     #[stable(feature = "rust1", since = "1.0.0")]
1421     #[inline]
1422     pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P>
1423     where
1424         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1425     {
1426         RSplit(self.split(pat).0)
1427     }
1428
1429     /// An iterator over substrings of the given string slice, separated by
1430     /// characters matched by a pattern.
1431     ///
1432     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1433     /// function or closure that determines if a character matches.
1434     ///
1435     /// [`char`]: prim@char
1436     /// [pattern]: self::pattern
1437     ///
1438     /// Equivalent to [`split`], except that the trailing substring
1439     /// is skipped if empty.
1440     ///
1441     /// [`split`]: str::split
1442     ///
1443     /// This method can be used for string data that is _terminated_,
1444     /// rather than _separated_ by a pattern.
1445     ///
1446     /// # Iterator behavior
1447     ///
1448     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1449     /// allows a reverse search and forward/reverse search yields the same
1450     /// elements. This is true for, e.g., [`char`], but not for `&str`.
1451     ///
1452     /// If the pattern allows a reverse search but its results might differ
1453     /// from a forward search, the [`rsplit_terminator`] method can be used.
1454     ///
1455     /// [`rsplit_terminator`]: str::rsplit_terminator
1456     ///
1457     /// # Examples
1458     ///
1459     /// Basic usage:
1460     ///
1461     /// ```
1462     /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1463     /// assert_eq!(v, ["A", "B"]);
1464     ///
1465     /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1466     /// assert_eq!(v, ["A", "", "B", ""]);
1467     ///
1468     /// let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
1469     /// assert_eq!(v, ["A", "B", "C", "D"]);
1470     /// ```
1471     #[stable(feature = "rust1", since = "1.0.0")]
1472     #[inline]
1473     pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1474         SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 })
1475     }
1476
1477     /// An iterator over substrings of `self`, separated by characters
1478     /// matched by a pattern and yielded in reverse order.
1479     ///
1480     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1481     /// function or closure that determines if a character matches.
1482     ///
1483     /// [`char`]: prim@char
1484     /// [pattern]: self::pattern
1485     ///
1486     /// Equivalent to [`split`], except that the trailing substring is
1487     /// skipped if empty.
1488     ///
1489     /// [`split`]: str::split
1490     ///
1491     /// This method can be used for string data that is _terminated_,
1492     /// rather than _separated_ by a pattern.
1493     ///
1494     /// # Iterator behavior
1495     ///
1496     /// The returned iterator requires that the pattern supports a
1497     /// reverse search, and it will be double ended if a forward/reverse
1498     /// search yields the same elements.
1499     ///
1500     /// For iterating from the front, the [`split_terminator`] method can be
1501     /// used.
1502     ///
1503     /// [`split_terminator`]: str::split_terminator
1504     ///
1505     /// # Examples
1506     ///
1507     /// ```
1508     /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1509     /// assert_eq!(v, ["B", "A"]);
1510     ///
1511     /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1512     /// assert_eq!(v, ["", "B", "", "A"]);
1513     ///
1514     /// let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
1515     /// assert_eq!(v, ["D", "C", "B", "A"]);
1516     /// ```
1517     #[stable(feature = "rust1", since = "1.0.0")]
1518     #[inline]
1519     pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1520     where
1521         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1522     {
1523         RSplitTerminator(self.split_terminator(pat).0)
1524     }
1525
1526     /// An iterator over substrings of the given string slice, separated by a
1527     /// pattern, restricted to returning at most `n` items.
1528     ///
1529     /// If `n` substrings are returned, the last substring (the `n`th substring)
1530     /// will contain the remainder of the string.
1531     ///
1532     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1533     /// function or closure that determines if a character matches.
1534     ///
1535     /// [`char`]: prim@char
1536     /// [pattern]: self::pattern
1537     ///
1538     /// # Iterator behavior
1539     ///
1540     /// The returned iterator will not be double ended, because it is
1541     /// not efficient to support.
1542     ///
1543     /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1544     /// used.
1545     ///
1546     /// [`rsplitn`]: str::rsplitn
1547     ///
1548     /// # Examples
1549     ///
1550     /// Simple patterns:
1551     ///
1552     /// ```
1553     /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1554     /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1555     ///
1556     /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1557     /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1558     ///
1559     /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1560     /// assert_eq!(v, ["abcXdef"]);
1561     ///
1562     /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1563     /// assert_eq!(v, [""]);
1564     /// ```
1565     ///
1566     /// A more complex pattern, using a closure:
1567     ///
1568     /// ```
1569     /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1570     /// assert_eq!(v, ["abc", "defXghi"]);
1571     /// ```
1572     #[stable(feature = "rust1", since = "1.0.0")]
1573     #[inline]
1574     pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1575         SplitN(SplitNInternal { iter: self.split(pat).0, count: n })
1576     }
1577
1578     /// An iterator over substrings of this string slice, separated by a
1579     /// pattern, starting from the end of the string, restricted to returning
1580     /// at most `n` items.
1581     ///
1582     /// If `n` substrings are returned, the last substring (the `n`th substring)
1583     /// will contain the remainder of the string.
1584     ///
1585     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1586     /// function or closure that determines if a character matches.
1587     ///
1588     /// [`char`]: prim@char
1589     /// [pattern]: self::pattern
1590     ///
1591     /// # Iterator behavior
1592     ///
1593     /// The returned iterator will not be double ended, because it is not
1594     /// efficient to support.
1595     ///
1596     /// For splitting from the front, the [`splitn`] method can be used.
1597     ///
1598     /// [`splitn`]: str::splitn
1599     ///
1600     /// # Examples
1601     ///
1602     /// Simple patterns:
1603     ///
1604     /// ```
1605     /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1606     /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1607     ///
1608     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1609     /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1610     ///
1611     /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1612     /// assert_eq!(v, ["leopard", "lion::tiger"]);
1613     /// ```
1614     ///
1615     /// A more complex pattern, using a closure:
1616     ///
1617     /// ```
1618     /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1619     /// assert_eq!(v, ["ghi", "abc1def"]);
1620     /// ```
1621     #[stable(feature = "rust1", since = "1.0.0")]
1622     #[inline]
1623     pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1624     where
1625         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1626     {
1627         RSplitN(self.splitn(n, pat).0)
1628     }
1629
1630     /// Splits the string on the first occurrence of the specified delimiter and
1631     /// returns prefix before delimiter and suffix after delimiter.
1632     ///
1633     /// # Examples
1634     ///
1635     /// ```
1636     /// assert_eq!("cfg".split_once('='), None);
1637     /// assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
1638     /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
1639     /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
1640     /// ```
1641     #[stable(feature = "str_split_once", since = "1.52.0")]
1642     #[inline]
1643     pub fn split_once<'a, P: Pattern<'a>>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)> {
1644         let (start, end) = delimiter.into_searcher(self).next_match()?;
1645         // SAFETY: `Searcher` is known to return valid indices.
1646         unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
1647     }
1648
1649     /// Splits the string on the last occurrence of the specified delimiter and
1650     /// returns prefix before delimiter and suffix after delimiter.
1651     ///
1652     /// # Examples
1653     ///
1654     /// ```
1655     /// assert_eq!("cfg".rsplit_once('='), None);
1656     /// assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
1657     /// assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
1658     /// ```
1659     #[stable(feature = "str_split_once", since = "1.52.0")]
1660     #[inline]
1661     pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>
1662     where
1663         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1664     {
1665         let (start, end) = delimiter.into_searcher(self).next_match_back()?;
1666         // SAFETY: `Searcher` is known to return valid indices.
1667         unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
1668     }
1669
1670     /// An iterator over the disjoint matches of a pattern within the given string
1671     /// slice.
1672     ///
1673     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1674     /// function or closure that determines if a character matches.
1675     ///
1676     /// [`char`]: prim@char
1677     /// [pattern]: self::pattern
1678     ///
1679     /// # Iterator behavior
1680     ///
1681     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1682     /// allows a reverse search and forward/reverse search yields the same
1683     /// elements. This is true for, e.g., [`char`], but not for `&str`.
1684     ///
1685     /// If the pattern allows a reverse search but its results might differ
1686     /// from a forward search, the [`rmatches`] method can be used.
1687     ///
1688     /// [`rmatches`]: str::matches
1689     ///
1690     /// # Examples
1691     ///
1692     /// Basic usage:
1693     ///
1694     /// ```
1695     /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1696     /// assert_eq!(v, ["abc", "abc", "abc"]);
1697     ///
1698     /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1699     /// assert_eq!(v, ["1", "2", "3"]);
1700     /// ```
1701     #[stable(feature = "str_matches", since = "1.2.0")]
1702     #[inline]
1703     pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1704         Matches(MatchesInternal(pat.into_searcher(self)))
1705     }
1706
1707     /// An iterator over the disjoint matches of a pattern within this string slice,
1708     /// yielded in reverse order.
1709     ///
1710     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1711     /// function or closure that determines if a character matches.
1712     ///
1713     /// [`char`]: prim@char
1714     /// [pattern]: self::pattern
1715     ///
1716     /// # Iterator behavior
1717     ///
1718     /// The returned iterator requires that the pattern supports a reverse
1719     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1720     /// search yields the same elements.
1721     ///
1722     /// For iterating from the front, the [`matches`] method can be used.
1723     ///
1724     /// [`matches`]: str::matches
1725     ///
1726     /// # Examples
1727     ///
1728     /// Basic usage:
1729     ///
1730     /// ```
1731     /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1732     /// assert_eq!(v, ["abc", "abc", "abc"]);
1733     ///
1734     /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1735     /// assert_eq!(v, ["3", "2", "1"]);
1736     /// ```
1737     #[stable(feature = "str_matches", since = "1.2.0")]
1738     #[inline]
1739     pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P>
1740     where
1741         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1742     {
1743         RMatches(self.matches(pat).0)
1744     }
1745
1746     /// An iterator over the disjoint matches of a pattern within this string
1747     /// slice as well as the index that the match starts at.
1748     ///
1749     /// For matches of `pat` within `self` that overlap, only the indices
1750     /// corresponding to the first match are returned.
1751     ///
1752     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1753     /// function or closure that determines if a character matches.
1754     ///
1755     /// [`char`]: prim@char
1756     /// [pattern]: self::pattern
1757     ///
1758     /// # Iterator behavior
1759     ///
1760     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1761     /// allows a reverse search and forward/reverse search yields the same
1762     /// elements. This is true for, e.g., [`char`], but not for `&str`.
1763     ///
1764     /// If the pattern allows a reverse search but its results might differ
1765     /// from a forward search, the [`rmatch_indices`] method can be used.
1766     ///
1767     /// [`rmatch_indices`]: str::rmatch_indices
1768     ///
1769     /// # Examples
1770     ///
1771     /// Basic usage:
1772     ///
1773     /// ```
1774     /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1775     /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1776     ///
1777     /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1778     /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1779     ///
1780     /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1781     /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1782     /// ```
1783     #[stable(feature = "str_match_indices", since = "1.5.0")]
1784     #[inline]
1785     pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1786         MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
1787     }
1788
1789     /// An iterator over the disjoint matches of a pattern within `self`,
1790     /// yielded in reverse order along with the index of the match.
1791     ///
1792     /// For matches of `pat` within `self` that overlap, only the indices
1793     /// corresponding to the last match are returned.
1794     ///
1795     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1796     /// function or closure that determines if a character matches.
1797     ///
1798     /// [`char`]: prim@char
1799     /// [pattern]: self::pattern
1800     ///
1801     /// # Iterator behavior
1802     ///
1803     /// The returned iterator requires that the pattern supports a reverse
1804     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1805     /// search yields the same elements.
1806     ///
1807     /// For iterating from the front, the [`match_indices`] method can be used.
1808     ///
1809     /// [`match_indices`]: str::match_indices
1810     ///
1811     /// # Examples
1812     ///
1813     /// Basic usage:
1814     ///
1815     /// ```
1816     /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1817     /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1818     ///
1819     /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1820     /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1821     ///
1822     /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1823     /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1824     /// ```
1825     #[stable(feature = "str_match_indices", since = "1.5.0")]
1826     #[inline]
1827     pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P>
1828     where
1829         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1830     {
1831         RMatchIndices(self.match_indices(pat).0)
1832     }
1833
1834     /// Returns a string slice with leading and trailing whitespace removed.
1835     ///
1836     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1837     /// Core Property `White_Space`, which includes newlines.
1838     ///
1839     /// # Examples
1840     ///
1841     /// Basic usage:
1842     ///
1843     /// ```
1844     /// let s = "\n Hello\tworld\t\n";
1845     ///
1846     /// assert_eq!("Hello\tworld", s.trim());
1847     /// ```
1848     #[inline]
1849     #[must_use = "this returns the trimmed string as a slice, \
1850                   without modifying the original"]
1851     #[stable(feature = "rust1", since = "1.0.0")]
1852     #[cfg_attr(not(test), rustc_diagnostic_item = "str_trim")]
1853     pub fn trim(&self) -> &str {
1854         self.trim_matches(|c: char| c.is_whitespace())
1855     }
1856
1857     /// Returns a string slice with leading whitespace removed.
1858     ///
1859     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1860     /// Core Property `White_Space`, which includes newlines.
1861     ///
1862     /// # Text directionality
1863     ///
1864     /// A string is a sequence of bytes. `start` in this context means the first
1865     /// position of that byte string; for a left-to-right language like English or
1866     /// Russian, this will be left side, and for right-to-left languages like
1867     /// Arabic or Hebrew, this will be the right side.
1868     ///
1869     /// # Examples
1870     ///
1871     /// Basic usage:
1872     ///
1873     /// ```
1874     /// let s = "\n Hello\tworld\t\n";
1875     /// assert_eq!("Hello\tworld\t\n", s.trim_start());
1876     /// ```
1877     ///
1878     /// Directionality:
1879     ///
1880     /// ```
1881     /// let s = "  English  ";
1882     /// assert!(Some('E') == s.trim_start().chars().next());
1883     ///
1884     /// let s = "  עברית  ";
1885     /// assert!(Some('ע') == s.trim_start().chars().next());
1886     /// ```
1887     #[inline]
1888     #[must_use = "this returns the trimmed string as a new slice, \
1889                   without modifying the original"]
1890     #[stable(feature = "trim_direction", since = "1.30.0")]
1891     #[cfg_attr(not(test), rustc_diagnostic_item = "str_trim_start")]
1892     pub fn trim_start(&self) -> &str {
1893         self.trim_start_matches(|c: char| c.is_whitespace())
1894     }
1895
1896     /// Returns a string slice with trailing whitespace removed.
1897     ///
1898     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1899     /// Core Property `White_Space`, which includes newlines.
1900     ///
1901     /// # Text directionality
1902     ///
1903     /// A string is a sequence of bytes. `end` in this context means the last
1904     /// position of that byte string; for a left-to-right language like English or
1905     /// Russian, this will be right side, and for right-to-left languages like
1906     /// Arabic or Hebrew, this will be the left side.
1907     ///
1908     /// # Examples
1909     ///
1910     /// Basic usage:
1911     ///
1912     /// ```
1913     /// let s = "\n Hello\tworld\t\n";
1914     /// assert_eq!("\n Hello\tworld", s.trim_end());
1915     /// ```
1916     ///
1917     /// Directionality:
1918     ///
1919     /// ```
1920     /// let s = "  English  ";
1921     /// assert!(Some('h') == s.trim_end().chars().rev().next());
1922     ///
1923     /// let s = "  עברית  ";
1924     /// assert!(Some('ת') == s.trim_end().chars().rev().next());
1925     /// ```
1926     #[inline]
1927     #[must_use = "this returns the trimmed string as a new slice, \
1928                   without modifying the original"]
1929     #[stable(feature = "trim_direction", since = "1.30.0")]
1930     #[cfg_attr(not(test), rustc_diagnostic_item = "str_trim_end")]
1931     pub fn trim_end(&self) -> &str {
1932         self.trim_end_matches(|c: char| c.is_whitespace())
1933     }
1934
1935     /// Returns a string slice with leading whitespace removed.
1936     ///
1937     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1938     /// Core Property `White_Space`.
1939     ///
1940     /// # Text directionality
1941     ///
1942     /// A string is a sequence of bytes. 'Left' in this context means the first
1943     /// position of that byte string; for a language like Arabic or Hebrew
1944     /// which are 'right to left' rather than 'left to right', this will be
1945     /// the _right_ side, not the left.
1946     ///
1947     /// # Examples
1948     ///
1949     /// Basic usage:
1950     ///
1951     /// ```
1952     /// let s = " Hello\tworld\t";
1953     ///
1954     /// assert_eq!("Hello\tworld\t", s.trim_left());
1955     /// ```
1956     ///
1957     /// Directionality:
1958     ///
1959     /// ```
1960     /// let s = "  English";
1961     /// assert!(Some('E') == s.trim_left().chars().next());
1962     ///
1963     /// let s = "  עברית";
1964     /// assert!(Some('ע') == s.trim_left().chars().next());
1965     /// ```
1966     #[must_use = "this returns the trimmed string as a new slice, \
1967                   without modifying the original"]
1968     #[inline]
1969     #[stable(feature = "rust1", since = "1.0.0")]
1970     #[deprecated(since = "1.33.0", note = "superseded by `trim_start`", suggestion = "trim_start")]
1971     pub fn trim_left(&self) -> &str {
1972         self.trim_start()
1973     }
1974
1975     /// Returns a string slice with trailing whitespace removed.
1976     ///
1977     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1978     /// Core Property `White_Space`.
1979     ///
1980     /// # Text directionality
1981     ///
1982     /// A string is a sequence of bytes. 'Right' in this context means the last
1983     /// position of that byte string; for a language like Arabic or Hebrew
1984     /// which are 'right to left' rather than 'left to right', this will be
1985     /// the _left_ side, not the right.
1986     ///
1987     /// # Examples
1988     ///
1989     /// Basic usage:
1990     ///
1991     /// ```
1992     /// let s = " Hello\tworld\t";
1993     ///
1994     /// assert_eq!(" Hello\tworld", s.trim_right());
1995     /// ```
1996     ///
1997     /// Directionality:
1998     ///
1999     /// ```
2000     /// let s = "English  ";
2001     /// assert!(Some('h') == s.trim_right().chars().rev().next());
2002     ///
2003     /// let s = "עברית  ";
2004     /// assert!(Some('ת') == s.trim_right().chars().rev().next());
2005     /// ```
2006     #[must_use = "this returns the trimmed string as a new slice, \
2007                   without modifying the original"]
2008     #[inline]
2009     #[stable(feature = "rust1", since = "1.0.0")]
2010     #[deprecated(since = "1.33.0", note = "superseded by `trim_end`", suggestion = "trim_end")]
2011     pub fn trim_right(&self) -> &str {
2012         self.trim_end()
2013     }
2014
2015     /// Returns a string slice with all prefixes and suffixes that match a
2016     /// pattern repeatedly removed.
2017     ///
2018     /// The [pattern] can be a [`char`], a slice of [`char`]s, or a function
2019     /// or closure that determines if a character matches.
2020     ///
2021     /// [`char`]: prim@char
2022     /// [pattern]: self::pattern
2023     ///
2024     /// # Examples
2025     ///
2026     /// Simple patterns:
2027     ///
2028     /// ```
2029     /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
2030     /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
2031     ///
2032     /// let x: &[_] = &['1', '2'];
2033     /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
2034     /// ```
2035     ///
2036     /// A more complex pattern, using a closure:
2037     ///
2038     /// ```
2039     /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
2040     /// ```
2041     #[must_use = "this returns the trimmed string as a new slice, \
2042                   without modifying the original"]
2043     #[stable(feature = "rust1", since = "1.0.0")]
2044     pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str
2045     where
2046         P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>,
2047     {
2048         let mut i = 0;
2049         let mut j = 0;
2050         let mut matcher = pat.into_searcher(self);
2051         if let Some((a, b)) = matcher.next_reject() {
2052             i = a;
2053             j = b; // Remember earliest known match, correct it below if
2054             // last match is different
2055         }
2056         if let Some((_, b)) = matcher.next_reject_back() {
2057             j = b;
2058         }
2059         // SAFETY: `Searcher` is known to return valid indices.
2060         unsafe { self.get_unchecked(i..j) }
2061     }
2062
2063     /// Returns a string slice with all prefixes that match a pattern
2064     /// repeatedly removed.
2065     ///
2066     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2067     /// function or closure that determines if a character matches.
2068     ///
2069     /// [`char`]: prim@char
2070     /// [pattern]: self::pattern
2071     ///
2072     /// # Text directionality
2073     ///
2074     /// A string is a sequence of bytes. `start` in this context means the first
2075     /// position of that byte string; for a left-to-right language like English or
2076     /// Russian, this will be left side, and for right-to-left languages like
2077     /// Arabic or Hebrew, this will be the right side.
2078     ///
2079     /// # Examples
2080     ///
2081     /// Basic usage:
2082     ///
2083     /// ```
2084     /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
2085     /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
2086     ///
2087     /// let x: &[_] = &['1', '2'];
2088     /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
2089     /// ```
2090     #[must_use = "this returns the trimmed string as a new slice, \
2091                   without modifying the original"]
2092     #[stable(feature = "trim_direction", since = "1.30.0")]
2093     pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2094         let mut i = self.len();
2095         let mut matcher = pat.into_searcher(self);
2096         if let Some((a, _)) = matcher.next_reject() {
2097             i = a;
2098         }
2099         // SAFETY: `Searcher` is known to return valid indices.
2100         unsafe { self.get_unchecked(i..self.len()) }
2101     }
2102
2103     /// Returns a string slice with the prefix removed.
2104     ///
2105     /// If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped
2106     /// in `Some`.  Unlike `trim_start_matches`, this method removes the prefix exactly once.
2107     ///
2108     /// If the string does not start with `prefix`, returns `None`.
2109     ///
2110     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2111     /// function or closure that determines if a character matches.
2112     ///
2113     /// [`char`]: prim@char
2114     /// [pattern]: self::pattern
2115     ///
2116     /// # Examples
2117     ///
2118     /// ```
2119     /// assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
2120     /// assert_eq!("foo:bar".strip_prefix("bar"), None);
2121     /// assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
2122     /// ```
2123     #[must_use = "this returns the remaining substring as a new slice, \
2124                   without modifying the original"]
2125     #[stable(feature = "str_strip", since = "1.45.0")]
2126     pub fn strip_prefix<'a, P: Pattern<'a>>(&'a self, prefix: P) -> Option<&'a str> {
2127         prefix.strip_prefix_of(self)
2128     }
2129
2130     /// Returns a string slice with the suffix removed.
2131     ///
2132     /// If the string ends with the pattern `suffix`, returns the substring before the suffix,
2133     /// wrapped in `Some`.  Unlike `trim_end_matches`, this method removes the suffix exactly once.
2134     ///
2135     /// If the string does not end with `suffix`, returns `None`.
2136     ///
2137     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2138     /// function or closure that determines if a character matches.
2139     ///
2140     /// [`char`]: prim@char
2141     /// [pattern]: self::pattern
2142     ///
2143     /// # Examples
2144     ///
2145     /// ```
2146     /// assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
2147     /// assert_eq!("bar:foo".strip_suffix("bar"), None);
2148     /// assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
2149     /// ```
2150     #[must_use = "this returns the remaining substring as a new slice, \
2151                   without modifying the original"]
2152     #[stable(feature = "str_strip", since = "1.45.0")]
2153     pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>
2154     where
2155         P: Pattern<'a>,
2156         <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
2157     {
2158         suffix.strip_suffix_of(self)
2159     }
2160
2161     /// Returns a string slice with all suffixes that match a pattern
2162     /// repeatedly removed.
2163     ///
2164     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2165     /// function or closure that determines if a character matches.
2166     ///
2167     /// [`char`]: prim@char
2168     /// [pattern]: self::pattern
2169     ///
2170     /// # Text directionality
2171     ///
2172     /// A string is a sequence of bytes. `end` in this context means the last
2173     /// position of that byte string; for a left-to-right language like English or
2174     /// Russian, this will be right side, and for right-to-left languages like
2175     /// Arabic or Hebrew, this will be the left side.
2176     ///
2177     /// # Examples
2178     ///
2179     /// Simple patterns:
2180     ///
2181     /// ```
2182     /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
2183     /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
2184     ///
2185     /// let x: &[_] = &['1', '2'];
2186     /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
2187     /// ```
2188     ///
2189     /// A more complex pattern, using a closure:
2190     ///
2191     /// ```
2192     /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
2193     /// ```
2194     #[must_use = "this returns the trimmed string as a new slice, \
2195                   without modifying the original"]
2196     #[stable(feature = "trim_direction", since = "1.30.0")]
2197     pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str
2198     where
2199         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2200     {
2201         let mut j = 0;
2202         let mut matcher = pat.into_searcher(self);
2203         if let Some((_, b)) = matcher.next_reject_back() {
2204             j = b;
2205         }
2206         // SAFETY: `Searcher` is known to return valid indices.
2207         unsafe { self.get_unchecked(0..j) }
2208     }
2209
2210     /// Returns a string slice with all prefixes that match a pattern
2211     /// repeatedly removed.
2212     ///
2213     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2214     /// function or closure that determines if a character matches.
2215     ///
2216     /// [`char`]: prim@char
2217     /// [pattern]: self::pattern
2218     ///
2219     /// # Text directionality
2220     ///
2221     /// A string is a sequence of bytes. 'Left' in this context means the first
2222     /// position of that byte string; for a language like Arabic or Hebrew
2223     /// which are 'right to left' rather than 'left to right', this will be
2224     /// the _right_ side, not the left.
2225     ///
2226     /// # Examples
2227     ///
2228     /// Basic usage:
2229     ///
2230     /// ```
2231     /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
2232     /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
2233     ///
2234     /// let x: &[_] = &['1', '2'];
2235     /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
2236     /// ```
2237     #[stable(feature = "rust1", since = "1.0.0")]
2238     #[deprecated(
2239         since = "1.33.0",
2240         note = "superseded by `trim_start_matches`",
2241         suggestion = "trim_start_matches"
2242     )]
2243     pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2244         self.trim_start_matches(pat)
2245     }
2246
2247     /// Returns a string slice with all suffixes that match a pattern
2248     /// repeatedly removed.
2249     ///
2250     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2251     /// function or closure that determines if a character matches.
2252     ///
2253     /// [`char`]: prim@char
2254     /// [pattern]: self::pattern
2255     ///
2256     /// # Text directionality
2257     ///
2258     /// A string is a sequence of bytes. 'Right' in this context means the last
2259     /// position of that byte string; for a language like Arabic or Hebrew
2260     /// which are 'right to left' rather than 'left to right', this will be
2261     /// the _left_ side, not the right.
2262     ///
2263     /// # Examples
2264     ///
2265     /// Simple patterns:
2266     ///
2267     /// ```
2268     /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
2269     /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
2270     ///
2271     /// let x: &[_] = &['1', '2'];
2272     /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
2273     /// ```
2274     ///
2275     /// A more complex pattern, using a closure:
2276     ///
2277     /// ```
2278     /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
2279     /// ```
2280     #[stable(feature = "rust1", since = "1.0.0")]
2281     #[deprecated(
2282         since = "1.33.0",
2283         note = "superseded by `trim_end_matches`",
2284         suggestion = "trim_end_matches"
2285     )]
2286     pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str
2287     where
2288         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2289     {
2290         self.trim_end_matches(pat)
2291     }
2292
2293     /// Parses this string slice into another type.
2294     ///
2295     /// Because `parse` is so general, it can cause problems with type
2296     /// inference. As such, `parse` is one of the few times you'll see
2297     /// the syntax affectionately known as the 'turbofish': `::<>`. This
2298     /// helps the inference algorithm understand specifically which type
2299     /// you're trying to parse into.
2300     ///
2301     /// `parse` can parse into any type that implements the [`FromStr`] trait.
2302
2303     ///
2304     /// # Errors
2305     ///
2306     /// Will return [`Err`] if it's not possible to parse this string slice into
2307     /// the desired type.
2308     ///
2309     /// [`Err`]: FromStr::Err
2310     ///
2311     /// # Examples
2312     ///
2313     /// Basic usage
2314     ///
2315     /// ```
2316     /// let four: u32 = "4".parse().unwrap();
2317     ///
2318     /// assert_eq!(4, four);
2319     /// ```
2320     ///
2321     /// Using the 'turbofish' instead of annotating `four`:
2322     ///
2323     /// ```
2324     /// let four = "4".parse::<u32>();
2325     ///
2326     /// assert_eq!(Ok(4), four);
2327     /// ```
2328     ///
2329     /// Failing to parse:
2330     ///
2331     /// ```
2332     /// let nope = "j".parse::<u32>();
2333     ///
2334     /// assert!(nope.is_err());
2335     /// ```
2336     #[inline]
2337     #[stable(feature = "rust1", since = "1.0.0")]
2338     pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
2339         FromStr::from_str(self)
2340     }
2341
2342     /// Checks if all characters in this string are within the ASCII range.
2343     ///
2344     /// # Examples
2345     ///
2346     /// ```
2347     /// let ascii = "hello!\n";
2348     /// let non_ascii = "Grüße, Jürgen ❤";
2349     ///
2350     /// assert!(ascii.is_ascii());
2351     /// assert!(!non_ascii.is_ascii());
2352     /// ```
2353     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2354     #[must_use]
2355     #[inline]
2356     pub fn is_ascii(&self) -> bool {
2357         // We can treat each byte as character here: all multibyte characters
2358         // start with a byte that is not in the ASCII range, so we will stop
2359         // there already.
2360         self.as_bytes().is_ascii()
2361     }
2362
2363     /// Checks that two strings are an ASCII case-insensitive match.
2364     ///
2365     /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2366     /// but without allocating and copying temporaries.
2367     ///
2368     /// # Examples
2369     ///
2370     /// ```
2371     /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2372     /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2373     /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2374     /// ```
2375     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2376     #[must_use]
2377     #[inline]
2378     pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
2379         self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
2380     }
2381
2382     /// Converts this string to its ASCII upper case equivalent in-place.
2383     ///
2384     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2385     /// but non-ASCII letters are unchanged.
2386     ///
2387     /// To return a new uppercased value without modifying the existing one, use
2388     /// [`to_ascii_uppercase()`].
2389     ///
2390     /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
2391     ///
2392     /// # Examples
2393     ///
2394     /// ```
2395     /// let mut s = String::from("Grüße, Jürgen ❤");
2396     ///
2397     /// s.make_ascii_uppercase();
2398     ///
2399     /// assert_eq!("GRüßE, JüRGEN ❤", s);
2400     /// ```
2401     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2402     #[inline]
2403     pub fn make_ascii_uppercase(&mut self) {
2404         // SAFETY: changing ASCII letters only does not invalidate UTF-8.
2405         let me = unsafe { self.as_bytes_mut() };
2406         me.make_ascii_uppercase()
2407     }
2408
2409     /// Converts this string to its ASCII lower case equivalent in-place.
2410     ///
2411     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2412     /// but non-ASCII letters are unchanged.
2413     ///
2414     /// To return a new lowercased value without modifying the existing one, use
2415     /// [`to_ascii_lowercase()`].
2416     ///
2417     /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
2418     ///
2419     /// # Examples
2420     ///
2421     /// ```
2422     /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
2423     ///
2424     /// s.make_ascii_lowercase();
2425     ///
2426     /// assert_eq!("grÜße, jÜrgen ❤", s);
2427     /// ```
2428     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2429     #[inline]
2430     pub fn make_ascii_lowercase(&mut self) {
2431         // SAFETY: changing ASCII letters only does not invalidate UTF-8.
2432         let me = unsafe { self.as_bytes_mut() };
2433         me.make_ascii_lowercase()
2434     }
2435
2436     /// Return an iterator that escapes each char in `self` with [`char::escape_debug`].
2437     ///
2438     /// Note: only extended grapheme codepoints that begin the string will be
2439     /// escaped.
2440     ///
2441     /// # Examples
2442     ///
2443     /// As an iterator:
2444     ///
2445     /// ```
2446     /// for c in "❤\n!".escape_debug() {
2447     ///     print!("{c}");
2448     /// }
2449     /// println!();
2450     /// ```
2451     ///
2452     /// Using `println!` directly:
2453     ///
2454     /// ```
2455     /// println!("{}", "❤\n!".escape_debug());
2456     /// ```
2457     ///
2458     ///
2459     /// Both are equivalent to:
2460     ///
2461     /// ```
2462     /// println!("❤\\n!");
2463     /// ```
2464     ///
2465     /// Using `to_string`:
2466     ///
2467     /// ```
2468     /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
2469     /// ```
2470     #[must_use = "this returns the escaped string as an iterator, \
2471                   without modifying the original"]
2472     #[stable(feature = "str_escape", since = "1.34.0")]
2473     pub fn escape_debug(&self) -> EscapeDebug<'_> {
2474         let mut chars = self.chars();
2475         EscapeDebug {
2476             inner: chars
2477                 .next()
2478                 .map(|first| first.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL))
2479                 .into_iter()
2480                 .flatten()
2481                 .chain(chars.flat_map(CharEscapeDebugContinue)),
2482         }
2483     }
2484
2485     /// Return an iterator that escapes each char in `self` with [`char::escape_default`].
2486     ///
2487     /// # Examples
2488     ///
2489     /// As an iterator:
2490     ///
2491     /// ```
2492     /// for c in "❤\n!".escape_default() {
2493     ///     print!("{c}");
2494     /// }
2495     /// println!();
2496     /// ```
2497     ///
2498     /// Using `println!` directly:
2499     ///
2500     /// ```
2501     /// println!("{}", "❤\n!".escape_default());
2502     /// ```
2503     ///
2504     ///
2505     /// Both are equivalent to:
2506     ///
2507     /// ```
2508     /// println!("\\u{{2764}}\\n!");
2509     /// ```
2510     ///
2511     /// Using `to_string`:
2512     ///
2513     /// ```
2514     /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
2515     /// ```
2516     #[must_use = "this returns the escaped string as an iterator, \
2517                   without modifying the original"]
2518     #[stable(feature = "str_escape", since = "1.34.0")]
2519     pub fn escape_default(&self) -> EscapeDefault<'_> {
2520         EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
2521     }
2522
2523     /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`].
2524     ///
2525     /// # Examples
2526     ///
2527     /// As an iterator:
2528     ///
2529     /// ```
2530     /// for c in "❤\n!".escape_unicode() {
2531     ///     print!("{c}");
2532     /// }
2533     /// println!();
2534     /// ```
2535     ///
2536     /// Using `println!` directly:
2537     ///
2538     /// ```
2539     /// println!("{}", "❤\n!".escape_unicode());
2540     /// ```
2541     ///
2542     ///
2543     /// Both are equivalent to:
2544     ///
2545     /// ```
2546     /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
2547     /// ```
2548     ///
2549     /// Using `to_string`:
2550     ///
2551     /// ```
2552     /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
2553     /// ```
2554     #[must_use = "this returns the escaped string as an iterator, \
2555                   without modifying the original"]
2556     #[stable(feature = "str_escape", since = "1.34.0")]
2557     pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
2558         EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
2559     }
2560 }
2561
2562 #[stable(feature = "rust1", since = "1.0.0")]
2563 impl AsRef<[u8]> for str {
2564     #[inline]
2565     fn as_ref(&self) -> &[u8] {
2566         self.as_bytes()
2567     }
2568 }
2569
2570 #[stable(feature = "rust1", since = "1.0.0")]
2571 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
2572 impl const Default for &str {
2573     /// Creates an empty str
2574     #[inline]
2575     fn default() -> Self {
2576         ""
2577     }
2578 }
2579
2580 #[stable(feature = "default_mut_str", since = "1.28.0")]
2581 impl Default for &mut str {
2582     /// Creates an empty mutable str
2583     #[inline]
2584     fn default() -> Self {
2585         // SAFETY: The empty string is valid UTF-8.
2586         unsafe { from_utf8_unchecked_mut(&mut []) }
2587     }
2588 }
2589
2590 impl_fn_for_zst! {
2591     /// A nameable, cloneable fn type
2592     #[derive(Clone)]
2593     struct LinesAnyMap impl<'a> Fn = |line: &'a str| -> &'a str {
2594         let l = line.len();
2595         if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
2596         else { line }
2597     };
2598
2599     #[derive(Clone)]
2600     struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
2601         c.escape_debug_ext(EscapeDebugExtArgs {
2602             escape_grapheme_extended: false,
2603             escape_single_quote: true,
2604             escape_double_quote: true
2605         })
2606     };
2607
2608     #[derive(Clone)]
2609     struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
2610         c.escape_unicode()
2611     };
2612     #[derive(Clone)]
2613     struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
2614         c.escape_default()
2615     };
2616
2617     #[derive(Clone)]
2618     struct IsWhitespace impl Fn = |c: char| -> bool {
2619         c.is_whitespace()
2620     };
2621
2622     #[derive(Clone)]
2623     struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
2624         byte.is_ascii_whitespace()
2625     };
2626
2627     #[derive(Clone)]
2628     struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
2629         !s.is_empty()
2630     };
2631
2632     #[derive(Clone)]
2633     struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
2634         !s.is_empty()
2635     };
2636
2637     #[derive(Clone)]
2638     struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
2639         // SAFETY: not safe
2640         unsafe { from_utf8_unchecked(bytes) }
2641     };
2642 }
2643
2644 #[stable(feature = "rust1", since = "1.0.0")]
2645 impl !crate::error::Error for &str {}