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