Skip to main content

core/str/
mod.rs

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