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