Skip to main content

core/str/
mod.rs

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