Skip to main content

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