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