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