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