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    #[must_use]
1028    #[unstable(feature = "str_split_at_unchecked", issue = "165545")]
1029    pub const unsafe fn split_at_unchecked(&self, mid: usize) -> (&str, &str) {
1030        let len = self.len();
1031        let ptr = self.as_ptr();
1032
1033        assert_unsafe_precondition!(
1034            check_library_ub,
1035            "str::split_at_unchecked requires the index to be on a UTF-8 boundary",
1036            (it: &str = self, mid: usize = mid) => it.is_char_boundary(mid),
1037        );
1038
1039        // SAFETY: caller guarantees `mid` is on a char boundary.
1040        unsafe {
1041            (
1042                from_utf8_unchecked(slice::from_raw_parts(ptr, mid)),
1043                from_utf8_unchecked(slice::from_raw_parts(ptr.add(mid), len - mid)),
1044            )
1045        }
1046    }
1047
1048    /// Divides one mutable string slice into two at a byte offset.
1049    ///
1050    /// # Safety
1051    ///
1052    /// The caller must ensure that `mid` is a valid byte offset from the start
1053    /// of the string and falls on the boundary of a UTF-8 code point.
1054    #[inline]
1055    #[must_use]
1056    #[unstable(feature = "str_split_at_unchecked", issue = "165545")]
1057    pub const unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut str, &mut str) {
1058        let len = self.len();
1059        let ptr = self.as_mut_ptr();
1060
1061        assert_unsafe_precondition!(
1062            check_library_ub,
1063            "str::split_at_mut_unchecked requires the index to be on a UTF-8 boundary",
1064            (it: &str = self, mid: usize = mid) => it.is_char_boundary(mid),
1065        );
1066
1067        // SAFETY: caller guarantees `mid` is on a char boundary.
1068        unsafe {
1069            (
1070                from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
1071                from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr.add(mid), len - mid)),
1072            )
1073        }
1074    }
1075
1076    /// Returns an iterator over the [`char`]s of a string slice.
1077    ///
1078    /// As a string slice consists of valid UTF-8, we can iterate through a
1079    /// string slice by [`char`]. This method returns such an iterator.
1080    ///
1081    /// It's important to remember that [`char`] represents a Unicode Scalar
1082    /// Value, and might not match your idea of what a 'character' is. Iteration
1083    /// over grapheme clusters may be what you actually want. This functionality
1084    /// is not provided by Rust's standard library, check crates.io instead.
1085    ///
1086    /// # Examples
1087    ///
1088    /// Basic usage:
1089    ///
1090    /// ```
1091    /// let word = "goodbye";
1092    ///
1093    /// let count = word.chars().count();
1094    /// assert_eq!(7, count);
1095    ///
1096    /// let mut chars = word.chars();
1097    ///
1098    /// assert_eq!(Some('g'), chars.next());
1099    /// assert_eq!(Some('o'), chars.next());
1100    /// assert_eq!(Some('o'), chars.next());
1101    /// assert_eq!(Some('d'), chars.next());
1102    /// assert_eq!(Some('b'), chars.next());
1103    /// assert_eq!(Some('y'), chars.next());
1104    /// assert_eq!(Some('e'), chars.next());
1105    ///
1106    /// assert_eq!(None, chars.next());
1107    /// ```
1108    ///
1109    /// Remember, [`char`]s might not match your intuition about characters:
1110    ///
1111    /// [`char`]: prim@char
1112    ///
1113    /// ```
1114    /// let y = "y̆";
1115    ///
1116    /// let mut chars = y.chars();
1117    ///
1118    /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
1119    /// assert_eq!(Some('\u{0306}'), chars.next());
1120    ///
1121    /// assert_eq!(None, chars.next());
1122    /// ```
1123    #[stable(feature = "rust1", since = "1.0.0")]
1124    #[inline]
1125    #[rustc_diagnostic_item = "str_chars"]
1126    #[ferrocene::prevalidated]
1127    pub fn chars(&self) -> Chars<'_> {
1128        Chars { iter: self.as_bytes().iter() }
1129    }
1130
1131    /// Returns an iterator over the [`char`]s of a string slice, and their
1132    /// positions.
1133    ///
1134    /// As a string slice consists of valid UTF-8, we can iterate through a
1135    /// string slice by [`char`]. This method returns an iterator of both
1136    /// these [`char`]s, as well as their byte positions.
1137    ///
1138    /// The iterator yields tuples. The position is first, the [`char`] is
1139    /// second.
1140    ///
1141    /// # Examples
1142    ///
1143    /// Basic usage:
1144    ///
1145    /// ```
1146    /// let word = "goodbye";
1147    ///
1148    /// let count = word.char_indices().count();
1149    /// assert_eq!(7, count);
1150    ///
1151    /// let mut char_indices = word.char_indices();
1152    ///
1153    /// assert_eq!(Some((0, 'g')), char_indices.next());
1154    /// assert_eq!(Some((1, 'o')), char_indices.next());
1155    /// assert_eq!(Some((2, 'o')), char_indices.next());
1156    /// assert_eq!(Some((3, 'd')), char_indices.next());
1157    /// assert_eq!(Some((4, 'b')), char_indices.next());
1158    /// assert_eq!(Some((5, 'y')), char_indices.next());
1159    /// assert_eq!(Some((6, 'e')), char_indices.next());
1160    ///
1161    /// assert_eq!(None, char_indices.next());
1162    /// ```
1163    ///
1164    /// Remember, [`char`]s might not match your intuition about characters:
1165    ///
1166    /// [`char`]: prim@char
1167    ///
1168    /// ```
1169    /// let yes = "y̆es";
1170    ///
1171    /// let mut char_indices = yes.char_indices();
1172    ///
1173    /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
1174    /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
1175    ///
1176    /// // note the 3 here - the previous character took up two bytes
1177    /// assert_eq!(Some((3, 'e')), char_indices.next());
1178    /// assert_eq!(Some((4, 's')), char_indices.next());
1179    ///
1180    /// assert_eq!(None, char_indices.next());
1181    /// ```
1182    #[stable(feature = "rust1", since = "1.0.0")]
1183    #[inline]
1184    #[ferrocene::prevalidated]
1185    pub fn char_indices(&self) -> CharIndices<'_> {
1186        CharIndices { front_offset: 0, iter: self.chars() }
1187    }
1188
1189    /// Returns an iterator over the bytes of a string slice.
1190    ///
1191    /// As a string slice consists of a sequence of bytes, we can iterate
1192    /// through a string slice by byte. This method returns such an iterator.
1193    ///
1194    /// # Examples
1195    ///
1196    /// ```
1197    /// let mut bytes = "bors".bytes();
1198    ///
1199    /// assert_eq!(Some(b'b'), bytes.next());
1200    /// assert_eq!(Some(b'o'), bytes.next());
1201    /// assert_eq!(Some(b'r'), bytes.next());
1202    /// assert_eq!(Some(b's'), bytes.next());
1203    ///
1204    /// assert_eq!(None, bytes.next());
1205    /// ```
1206    #[stable(feature = "rust1", since = "1.0.0")]
1207    #[inline]
1208    #[ferrocene::prevalidated]
1209    pub fn bytes(&self) -> Bytes<'_> {
1210        Bytes(self.as_bytes().iter().copied())
1211    }
1212
1213    /// Splits a string slice by whitespace.
1214    ///
1215    /// The iterator returned will return string slices that are sub-slices of
1216    /// the original string slice, separated by any amount of whitespace.
1217    ///
1218    /// 'Whitespace' is defined according to the terms of the Unicode Derived
1219    /// Core Property `White_Space`. If you only want to split on ASCII whitespace
1220    /// instead, use [`split_ascii_whitespace`].
1221    ///
1222    /// [`split_ascii_whitespace`]: str::split_ascii_whitespace
1223    ///
1224    /// # Examples
1225    ///
1226    /// Basic usage:
1227    ///
1228    /// ```
1229    /// let mut iter = "A few words".split_whitespace();
1230    ///
1231    /// assert_eq!(Some("A"), iter.next());
1232    /// assert_eq!(Some("few"), iter.next());
1233    /// assert_eq!(Some("words"), iter.next());
1234    ///
1235    /// assert_eq!(None, iter.next());
1236    /// ```
1237    ///
1238    /// All kinds of whitespace are considered:
1239    ///
1240    /// ```
1241    /// let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
1242    /// assert_eq!(Some("Mary"), iter.next());
1243    /// assert_eq!(Some("had"), iter.next());
1244    /// assert_eq!(Some("a"), iter.next());
1245    /// assert_eq!(Some("little"), iter.next());
1246    /// assert_eq!(Some("lamb"), iter.next());
1247    ///
1248    /// assert_eq!(None, iter.next());
1249    /// ```
1250    ///
1251    /// If the string is empty or all whitespace, the iterator yields no string slices:
1252    /// ```
1253    /// assert_eq!("".split_whitespace().next(), None);
1254    /// assert_eq!("   ".split_whitespace().next(), None);
1255    /// ```
1256    #[must_use = "this returns the split string as an iterator, \
1257                  without modifying the original"]
1258    #[stable(feature = "split_whitespace", since = "1.1.0")]
1259    #[rustc_diagnostic_item = "str_split_whitespace"]
1260    #[inline]
1261    pub fn split_whitespace(&self) -> SplitWhitespace<'_> {
1262        SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
1263    }
1264
1265    /// Splits a string slice by ASCII whitespace.
1266    ///
1267    /// The iterator returned will return string slices that are sub-slices of
1268    /// the original string slice, separated by any amount of ASCII whitespace.
1269    ///
1270    /// This uses the same definition as [`char::is_ascii_whitespace`].
1271    /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
1272    /// Note that because of this difference in definition, even if `s.is_ascii()`
1273    /// is `true`, `s.split_ascii_whitespace()` behavior will differ from `s.split_whitespace()`
1274    /// if `s` contains U+000B VERTICAL TAB.
1275    ///
1276    /// [`split_whitespace`]: str::split_whitespace
1277    ///
1278    /// # Examples
1279    ///
1280    /// Basic usage:
1281    ///
1282    /// ```
1283    /// let mut iter = "A few words".split_ascii_whitespace();
1284    ///
1285    /// assert_eq!(Some("A"), iter.next());
1286    /// assert_eq!(Some("few"), iter.next());
1287    /// assert_eq!(Some("words"), iter.next());
1288    ///
1289    /// assert_eq!(None, iter.next());
1290    /// ```
1291    ///
1292    /// Various kinds of ASCII whitespace are considered
1293    /// (see [`char::is_ascii_whitespace`]):
1294    ///
1295    /// ```
1296    /// let mut iter = " Mary   had\ta little  \n\t lamb".split_ascii_whitespace();
1297    /// assert_eq!(Some("Mary"), iter.next());
1298    /// assert_eq!(Some("had"), iter.next());
1299    /// assert_eq!(Some("a"), iter.next());
1300    /// assert_eq!(Some("little"), iter.next());
1301    /// assert_eq!(Some("lamb"), iter.next());
1302    ///
1303    /// assert_eq!(None, iter.next());
1304    /// ```
1305    ///
1306    /// If the string is empty or all ASCII whitespace, the iterator yields no string slices:
1307    /// ```
1308    /// assert_eq!("".split_ascii_whitespace().next(), None);
1309    /// assert_eq!("   ".split_ascii_whitespace().next(), None);
1310    /// ```
1311    #[must_use = "this returns the split string as an iterator, \
1312                  without modifying the original"]
1313    #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
1314    #[inline]
1315    pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> {
1316        let inner = self.as_bytes().split_ascii_whitespace().inner.map(UnsafeBytesToStr);
1317        SplitAsciiWhitespace { inner }
1318    }
1319
1320    /// Returns an iterator over the lines of a string, as string slices.
1321    ///
1322    /// Lines are split at line endings that are either newlines (`\n`) or
1323    /// sequences of a carriage return followed by a line feed (`\r\n`).
1324    ///
1325    /// Line terminators are not included in the lines returned by the iterator.
1326    ///
1327    /// Note that any carriage return (`\r`) not immediately followed by a
1328    /// line feed (`\n`) does not split a line. These carriage returns are
1329    /// thereby included in the produced lines.
1330    ///
1331    /// The final line ending is optional. A string that ends with a final line
1332    /// ending will return the same lines as an otherwise identical string
1333    /// without a final line ending.
1334    ///
1335    /// An empty string returns an empty iterator.
1336    ///
1337    /// # Examples
1338    ///
1339    /// Basic usage:
1340    ///
1341    /// ```
1342    /// let text = "foo\r\nbar\n\nbaz\r";
1343    /// let mut lines = text.lines();
1344    ///
1345    /// assert_eq!(Some("foo"), lines.next());
1346    /// assert_eq!(Some("bar"), lines.next());
1347    /// assert_eq!(Some(""), lines.next());
1348    /// // Trailing carriage return is included in the last line
1349    /// assert_eq!(Some("baz\r"), lines.next());
1350    ///
1351    /// assert_eq!(None, lines.next());
1352    /// ```
1353    ///
1354    /// The final line does not require any ending:
1355    ///
1356    /// ```
1357    /// let text = "foo\nbar\n\r\nbaz";
1358    /// let mut lines = text.lines();
1359    ///
1360    /// assert_eq!(Some("foo"), lines.next());
1361    /// assert_eq!(Some("bar"), lines.next());
1362    /// assert_eq!(Some(""), lines.next());
1363    /// assert_eq!(Some("baz"), lines.next());
1364    ///
1365    /// assert_eq!(None, lines.next());
1366    /// ```
1367    ///
1368    /// An empty string returns an empty iterator:
1369    ///
1370    /// ```
1371    /// let text = "";
1372    /// let mut lines = text.lines();
1373    ///
1374    /// assert_eq!(lines.next(), None);
1375    /// ```
1376    #[stable(feature = "rust1", since = "1.0.0")]
1377    #[inline]
1378    pub fn lines(&self) -> Lines<'_> {
1379        Lines(self.split_inclusive('\n').map(LinesMap))
1380    }
1381
1382    /// Returns an iterator over the lines of a string.
1383    #[stable(feature = "rust1", since = "1.0.0")]
1384    #[deprecated(since = "1.4.0", note = "use lines() instead now", suggestion = "lines")]
1385    #[inline]
1386    #[allow(deprecated)]
1387    pub fn lines_any(&self) -> LinesAny<'_> {
1388        LinesAny(self.lines())
1389    }
1390
1391    /// Returns an iterator of `u16` over the string encoded
1392    /// as native endian UTF-16 (without byte-order mark).
1393    ///
1394    /// # Examples
1395    ///
1396    /// ```
1397    /// let text = "Zażółć gęślą jaźń";
1398    ///
1399    /// let utf8_len = text.len();
1400    /// let utf16_len = text.encode_utf16().count();
1401    ///
1402    /// assert!(utf16_len <= utf8_len);
1403    /// ```
1404    #[must_use = "this returns the encoded string as an iterator, \
1405                  without modifying the original"]
1406    #[stable(feature = "encode_utf16", since = "1.8.0")]
1407    pub fn encode_utf16(&self) -> EncodeUtf16<'_> {
1408        EncodeUtf16 { chars: self.chars(), extra: 0 }
1409    }
1410
1411    /// Returns `true` if the given pattern matches a sub-slice of
1412    /// this string slice.
1413    ///
1414    /// Returns `false` if it does not.
1415    ///
1416    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1417    /// function or closure that determines if a character matches.
1418    ///
1419    /// [`char`]: prim@char
1420    /// [pattern]: self::pattern
1421    ///
1422    /// # Examples
1423    ///
1424    /// ```
1425    /// let bananas = "bananas";
1426    ///
1427    /// assert!(bananas.contains("nana"));
1428    /// assert!(!bananas.contains("apples"));
1429    /// ```
1430    #[stable(feature = "rust1", since = "1.0.0")]
1431    #[inline]
1432    pub fn contains<P: Pattern>(&self, pat: P) -> bool {
1433        pat.is_contained_in(self)
1434    }
1435
1436    /// Returns `true` if the given pattern matches a prefix of this
1437    /// string slice.
1438    ///
1439    /// Returns `false` if it does not.
1440    ///
1441    /// The [pattern] can be a `&str`, in which case this function will return true if
1442    /// the `&str` is a prefix of this string slice.
1443    ///
1444    /// The [pattern] can also be a [`char`], a slice of [`char`]s, or a
1445    /// function or closure that determines if a character matches.
1446    /// These will only be checked against the first character of this string slice.
1447    /// Look at the second example below regarding behavior for slices of [`char`]s.
1448    ///
1449    /// [`char`]: prim@char
1450    /// [pattern]: self::pattern
1451    ///
1452    /// # Examples
1453    ///
1454    /// ```
1455    /// let bananas = "bananas";
1456    ///
1457    /// assert!(bananas.starts_with("bana"));
1458    /// assert!(!bananas.starts_with("nana"));
1459    /// ```
1460    ///
1461    /// ```
1462    /// let bananas = "bananas";
1463    ///
1464    /// // Note that both of these assert successfully.
1465    /// assert!(bananas.starts_with(&['b', 'a', 'n', 'a']));
1466    /// assert!(bananas.starts_with(&['a', 'b', 'c', 'd']));
1467    /// ```
1468    #[stable(feature = "rust1", since = "1.0.0")]
1469    #[rustc_diagnostic_item = "str_starts_with"]
1470    #[ferrocene::prevalidated]
1471    pub fn starts_with<P: Pattern>(&self, pat: P) -> bool {
1472        pat.is_prefix_of(self)
1473    }
1474
1475    /// Returns `true` if the given pattern matches a suffix of this
1476    /// string slice.
1477    ///
1478    /// Returns `false` if it does not.
1479    ///
1480    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1481    /// function or closure that determines if a character matches.
1482    ///
1483    /// [`char`]: prim@char
1484    /// [pattern]: self::pattern
1485    ///
1486    /// # Examples
1487    ///
1488    /// ```
1489    /// let bananas = "bananas";
1490    ///
1491    /// assert!(bananas.ends_with("anas"));
1492    /// assert!(!bananas.ends_with("nana"));
1493    /// ```
1494    #[stable(feature = "rust1", since = "1.0.0")]
1495    #[rustc_diagnostic_item = "str_ends_with"]
1496    #[ferrocene::prevalidated]
1497    pub fn ends_with<P: Pattern>(&self, pat: P) -> bool
1498    where
1499        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
1500    {
1501        pat.is_suffix_of(self)
1502    }
1503
1504    /// Returns the byte index of the first character of this string slice that
1505    /// matches the pattern.
1506    ///
1507    /// Returns [`None`] if the pattern doesn't match.
1508    ///
1509    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1510    /// function or closure that determines if a character matches.
1511    ///
1512    /// [`char`]: prim@char
1513    /// [pattern]: self::pattern
1514    ///
1515    /// # Examples
1516    ///
1517    /// Simple patterns:
1518    ///
1519    /// ```
1520    /// let s = "Löwe 老虎 Léopard Gepardi";
1521    ///
1522    /// assert_eq!(s.find('L'), Some(0));
1523    /// assert_eq!(s.find('é'), Some(14));
1524    /// assert_eq!(s.find("pard"), Some(17));
1525    /// ```
1526    ///
1527    /// More complex patterns using point-free style and closures:
1528    ///
1529    /// ```
1530    /// let s = "Löwe 老虎 Léopard";
1531    ///
1532    /// assert_eq!(s.find(char::is_whitespace), Some(5));
1533    /// assert_eq!(s.find(char::is_lowercase), Some(1));
1534    /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
1535    /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
1536    /// ```
1537    ///
1538    /// Not finding the pattern:
1539    ///
1540    /// ```
1541    /// let s = "Löwe 老虎 Léopard";
1542    /// let x: &[_] = &['1', '2'];
1543    ///
1544    /// assert_eq!(s.find(x), None);
1545    /// ```
1546    #[stable(feature = "rust1", since = "1.0.0")]
1547    #[inline]
1548    #[ferrocene::prevalidated]
1549    pub fn find<P: Pattern>(&self, pat: P) -> Option<usize> {
1550        pat.into_searcher(self).next_match().map(|(i, _)| i)
1551    }
1552
1553    /// Returns the byte index for the first character of the last match of the pattern in
1554    /// this string slice.
1555    ///
1556    /// Returns [`None`] if the pattern doesn't match.
1557    ///
1558    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1559    /// function or closure that determines if a character matches.
1560    ///
1561    /// [`char`]: prim@char
1562    /// [pattern]: self::pattern
1563    ///
1564    /// # Examples
1565    ///
1566    /// Simple patterns:
1567    ///
1568    /// ```
1569    /// let s = "Löwe 老虎 Léopard Gepardi";
1570    ///
1571    /// assert_eq!(s.rfind('L'), Some(13));
1572    /// assert_eq!(s.rfind('é'), Some(14));
1573    /// assert_eq!(s.rfind("pard"), Some(24));
1574    /// ```
1575    ///
1576    /// More complex patterns with closures:
1577    ///
1578    /// ```
1579    /// let s = "Löwe 老虎 Léopard";
1580    ///
1581    /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1582    /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1583    /// ```
1584    ///
1585    /// Not finding the pattern:
1586    ///
1587    /// ```
1588    /// let s = "Löwe 老虎 Léopard";
1589    /// let x: &[_] = &['1', '2'];
1590    ///
1591    /// assert_eq!(s.rfind(x), None);
1592    /// ```
1593    #[stable(feature = "rust1", since = "1.0.0")]
1594    #[inline]
1595    pub fn rfind<P: Pattern>(&self, pat: P) -> Option<usize>
1596    where
1597        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
1598    {
1599        pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1600    }
1601
1602    /// Returns an iterator over substrings of this string slice, separated by
1603    /// characters matched by a pattern.
1604    ///
1605    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1606    /// function or closure that determines if a character matches.
1607    ///
1608    /// If there are no matches the full string slice is returned as the only
1609    /// item in the iterator.
1610    ///
1611    /// [`char`]: prim@char
1612    /// [pattern]: self::pattern
1613    ///
1614    /// # Iterator behavior
1615    ///
1616    /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1617    /// allows a reverse search and forward/reverse search yields the same
1618    /// elements. This is true for, e.g., [`char`], but not for `&str`.
1619    ///
1620    /// If the pattern allows a reverse search but its results might differ
1621    /// from a forward search, the [`rsplit`] method can be used.
1622    ///
1623    /// [`rsplit`]: str::rsplit
1624    ///
1625    /// # Examples
1626    ///
1627    /// Simple patterns:
1628    ///
1629    /// ```
1630    /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1631    /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1632    ///
1633    /// let v: Vec<&str> = "".split('X').collect();
1634    /// assert_eq!(v, [""]);
1635    ///
1636    /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1637    /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1638    ///
1639    /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1640    /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1641    ///
1642    /// let v: Vec<&str> = "AABBCC".split("DD").collect();
1643    /// assert_eq!(v, ["AABBCC"]);
1644    ///
1645    /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1646    /// assert_eq!(v, ["abc", "def", "ghi"]);
1647    ///
1648    /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1649    /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1650    /// ```
1651    ///
1652    /// If the pattern is a slice of chars, split on each occurrence of any of the characters:
1653    ///
1654    /// ```
1655    /// let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
1656    /// assert_eq!(v, ["2020", "11", "03", "23", "59"]);
1657    /// ```
1658    ///
1659    /// A more complex pattern, using a closure:
1660    ///
1661    /// ```
1662    /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1663    /// assert_eq!(v, ["abc", "def", "ghi"]);
1664    /// ```
1665    ///
1666    /// If a string contains multiple contiguous separators, you will end up
1667    /// with empty strings in the output:
1668    ///
1669    /// ```
1670    /// let x = "||||a||b|c".to_string();
1671    /// let d: Vec<_> = x.split('|').collect();
1672    ///
1673    /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1674    /// ```
1675    ///
1676    /// Contiguous separators are separated by the empty string.
1677    ///
1678    /// ```
1679    /// let x = "(///)".to_string();
1680    /// let d: Vec<_> = x.split('/').collect();
1681    ///
1682    /// assert_eq!(d, &["(", "", "", ")"]);
1683    /// ```
1684    ///
1685    /// Separators at the start or end of a string are neighbored
1686    /// by empty strings.
1687    ///
1688    /// ```
1689    /// let d: Vec<_> = "010".split("0").collect();
1690    /// assert_eq!(d, &["", "1", ""]);
1691    /// ```
1692    ///
1693    /// When the empty string is used as a separator, it separates
1694    /// every character in the string, along with the beginning
1695    /// and end of the string.
1696    ///
1697    /// ```
1698    /// let f: Vec<_> = "rust".split("").collect();
1699    /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1700    /// ```
1701    ///
1702    /// Contiguous separators can lead to possibly surprising behavior
1703    /// when whitespace is used as the separator. This code is correct:
1704    ///
1705    /// ```
1706    /// let x = "    a  b c".to_string();
1707    /// let d: Vec<_> = x.split(' ').collect();
1708    ///
1709    /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1710    /// ```
1711    ///
1712    /// It does _not_ give you:
1713    ///
1714    /// ```,ignore
1715    /// assert_eq!(d, &["a", "b", "c"]);
1716    /// ```
1717    ///
1718    /// Use [`split_whitespace`] for this behavior.
1719    ///
1720    /// [`split_whitespace`]: str::split_whitespace
1721    #[ferrocene::prevalidated]
1722    #[stable(feature = "rust1", since = "1.0.0")]
1723    #[inline]
1724    pub fn split<P: Pattern>(&self, pat: P) -> Split<'_, P> {
1725        Split(SplitInternal {
1726            start: 0,
1727            end: self.len(),
1728            matcher: pat.into_searcher(self),
1729            allow_trailing_empty: true,
1730            finished: false,
1731        })
1732    }
1733
1734    /// Returns an iterator over substrings of this string slice, separated by
1735    /// characters matched by a pattern.
1736    ///
1737    /// Differs from the iterator produced by `split` in that `split_inclusive`
1738    /// leaves the matched part as the terminator of the substring.
1739    ///
1740    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1741    /// function or closure that determines if a character matches.
1742    ///
1743    /// [`char`]: prim@char
1744    /// [pattern]: self::pattern
1745    ///
1746    /// # Examples
1747    ///
1748    /// ```
1749    /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
1750    ///     .split_inclusive('\n').collect();
1751    /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
1752    /// ```
1753    ///
1754    /// If the last element of the string is matched,
1755    /// that element will be considered the terminator of the preceding substring.
1756    /// That substring will be the last item returned by the iterator.
1757    ///
1758    /// ```
1759    /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
1760    ///     .split_inclusive('\n').collect();
1761    /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1762    /// ```
1763    #[stable(feature = "split_inclusive", since = "1.51.0")]
1764    #[inline]
1765    #[ferrocene::prevalidated]
1766    pub fn split_inclusive<P: Pattern>(&self, pat: P) -> SplitInclusive<'_, P> {
1767        SplitInclusive(SplitInternal {
1768            start: 0,
1769            end: self.len(),
1770            matcher: pat.into_searcher(self),
1771            allow_trailing_empty: false,
1772            finished: false,
1773        })
1774    }
1775
1776    /// Returns an iterator over substrings of the given string slice, separated
1777    /// by characters matched by a pattern and yielded in reverse order.
1778    ///
1779    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1780    /// function or closure that determines if a character matches.
1781    ///
1782    /// [`char`]: prim@char
1783    /// [pattern]: self::pattern
1784    ///
1785    /// # Iterator behavior
1786    ///
1787    /// The returned iterator requires that the pattern supports a reverse
1788    /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1789    /// search yields the same elements.
1790    ///
1791    /// For iterating from the front, the [`split`] method can be used.
1792    ///
1793    /// [`split`]: str::split
1794    ///
1795    /// # Examples
1796    ///
1797    /// Simple patterns:
1798    ///
1799    /// ```
1800    /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1801    /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1802    ///
1803    /// let v: Vec<&str> = "".rsplit('X').collect();
1804    /// assert_eq!(v, [""]);
1805    ///
1806    /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1807    /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1808    ///
1809    /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1810    /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1811    /// ```
1812    ///
1813    /// A more complex pattern, using a closure:
1814    ///
1815    /// ```
1816    /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1817    /// assert_eq!(v, ["ghi", "def", "abc"]);
1818    /// ```
1819    #[stable(feature = "rust1", since = "1.0.0")]
1820    #[inline]
1821    pub fn rsplit<P: Pattern>(&self, pat: P) -> RSplit<'_, P>
1822    where
1823        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
1824    {
1825        RSplit(self.split(pat).0)
1826    }
1827
1828    /// Returns an iterator over substrings of the given string slice, separated
1829    /// by characters matched by a pattern.
1830    ///
1831    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1832    /// function or closure that determines if a character matches.
1833    ///
1834    /// [`char`]: prim@char
1835    /// [pattern]: self::pattern
1836    ///
1837    /// Equivalent to [`split`], except that the trailing substring
1838    /// is skipped if empty.
1839    ///
1840    /// [`split`]: str::split
1841    ///
1842    /// This method can be used for string data that is _terminated_,
1843    /// rather than _separated_ by a pattern.
1844    ///
1845    /// # Iterator behavior
1846    ///
1847    /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1848    /// allows a reverse search and forward/reverse search yields the same
1849    /// elements. This is true for, e.g., [`char`], but not for `&str`.
1850    ///
1851    /// If the pattern allows a reverse search but its results might differ
1852    /// from a forward search, the [`rsplit_terminator`] method can be used.
1853    ///
1854    /// [`rsplit_terminator`]: str::rsplit_terminator
1855    ///
1856    /// # Examples
1857    ///
1858    /// ```
1859    /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1860    /// assert_eq!(v, ["A", "B"]);
1861    ///
1862    /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1863    /// assert_eq!(v, ["A", "", "B", ""]);
1864    ///
1865    /// let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
1866    /// assert_eq!(v, ["A", "B", "C", "D"]);
1867    /// ```
1868    #[stable(feature = "rust1", since = "1.0.0")]
1869    #[inline]
1870    pub fn split_terminator<P: Pattern>(&self, pat: P) -> SplitTerminator<'_, P> {
1871        SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 })
1872    }
1873
1874    /// Returns an iterator over substrings of `self`, separated by characters
1875    /// matched by a pattern and yielded in reverse order.
1876    ///
1877    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1878    /// function or closure that determines if a character matches.
1879    ///
1880    /// [`char`]: prim@char
1881    /// [pattern]: self::pattern
1882    ///
1883    /// Equivalent to [`split`], except that the trailing substring is
1884    /// skipped if empty.
1885    ///
1886    /// [`split`]: str::split
1887    ///
1888    /// This method can be used for string data that is _terminated_,
1889    /// rather than _separated_ by a pattern.
1890    ///
1891    /// # Iterator behavior
1892    ///
1893    /// The returned iterator requires that the pattern supports a
1894    /// reverse search, and it will be double ended if a forward/reverse
1895    /// search yields the same elements.
1896    ///
1897    /// For iterating from the front, the [`split_terminator`] method can be
1898    /// used.
1899    ///
1900    /// [`split_terminator`]: str::split_terminator
1901    ///
1902    /// # Examples
1903    ///
1904    /// ```
1905    /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1906    /// assert_eq!(v, ["B", "A"]);
1907    ///
1908    /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1909    /// assert_eq!(v, ["", "B", "", "A"]);
1910    ///
1911    /// let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
1912    /// assert_eq!(v, ["D", "C", "B", "A"]);
1913    /// ```
1914    #[stable(feature = "rust1", since = "1.0.0")]
1915    #[inline]
1916    pub fn rsplit_terminator<P: Pattern>(&self, pat: P) -> RSplitTerminator<'_, P>
1917    where
1918        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
1919    {
1920        RSplitTerminator(self.split_terminator(pat).0)
1921    }
1922
1923    /// Returns an iterator over substrings of the given string slice, separated
1924    /// by a pattern, restricted to returning at most `n` items.
1925    ///
1926    /// If `n` substrings are returned, the last substring (the `n`th substring)
1927    /// will contain the remainder of the string.
1928    ///
1929    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1930    /// function or closure that determines if a character matches.
1931    ///
1932    /// [`char`]: prim@char
1933    /// [pattern]: self::pattern
1934    ///
1935    /// # Iterator behavior
1936    ///
1937    /// The returned iterator will not be double ended, because it is
1938    /// not efficient to support.
1939    ///
1940    /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1941    /// used.
1942    ///
1943    /// [`rsplitn`]: str::rsplitn
1944    ///
1945    /// # Examples
1946    ///
1947    /// Simple patterns:
1948    ///
1949    /// ```
1950    /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1951    /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1952    ///
1953    /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1954    /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1955    ///
1956    /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1957    /// assert_eq!(v, ["abcXdef"]);
1958    ///
1959    /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1960    /// assert_eq!(v, [""]);
1961    /// ```
1962    ///
1963    /// A more complex pattern, using a closure:
1964    ///
1965    /// ```
1966    /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1967    /// assert_eq!(v, ["abc", "defXghi"]);
1968    /// ```
1969    #[stable(feature = "rust1", since = "1.0.0")]
1970    #[inline]
1971    pub fn splitn<P: Pattern>(&self, n: usize, pat: P) -> SplitN<'_, P> {
1972        SplitN(SplitNInternal { iter: self.split(pat).0, count: n })
1973    }
1974
1975    /// Returns an iterator over substrings of this string slice, separated by a
1976    /// pattern, starting from the end of the string, restricted to returning at
1977    /// most `n` items.
1978    ///
1979    /// If `n` substrings are returned, the last substring (the `n`th substring)
1980    /// will contain the remainder of the string.
1981    ///
1982    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1983    /// function or closure that determines if a character matches.
1984    ///
1985    /// [`char`]: prim@char
1986    /// [pattern]: self::pattern
1987    ///
1988    /// # Iterator behavior
1989    ///
1990    /// The returned iterator will not be double ended, because it is not
1991    /// efficient to support.
1992    ///
1993    /// For splitting from the front, the [`splitn`] method can be used.
1994    ///
1995    /// [`splitn`]: str::splitn
1996    ///
1997    /// # Examples
1998    ///
1999    /// Simple patterns:
2000    ///
2001    /// ```
2002    /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
2003    /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
2004    ///
2005    /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
2006    /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
2007    ///
2008    /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
2009    /// assert_eq!(v, ["leopard", "lion::tiger"]);
2010    /// ```
2011    ///
2012    /// A more complex pattern, using a closure:
2013    ///
2014    /// ```
2015    /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
2016    /// assert_eq!(v, ["ghi", "abc1def"]);
2017    /// ```
2018    #[stable(feature = "rust1", since = "1.0.0")]
2019    #[inline]
2020    pub fn rsplitn<P: Pattern>(&self, n: usize, pat: P) -> RSplitN<'_, P>
2021    where
2022        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2023    {
2024        RSplitN(self.splitn(n, pat).0)
2025    }
2026
2027    /// Splits the string on the first occurrence of the specified delimiter and
2028    /// returns prefix before delimiter and suffix after delimiter.
2029    ///
2030    /// # Examples
2031    ///
2032    /// ```
2033    /// assert_eq!("cfg".split_once('='), None);
2034    /// assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
2035    /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
2036    /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
2037    /// ```
2038    #[stable(feature = "str_split_once", since = "1.52.0")]
2039    #[inline]
2040    pub fn split_once<P: Pattern>(&self, delimiter: P) -> Option<(&'_ str, &'_ str)> {
2041        let (start, end) = delimiter.into_searcher(self).next_match()?;
2042        // SAFETY: `Searcher` is known to return valid indices.
2043        unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
2044    }
2045
2046    /// Splits the string on the last occurrence of the specified delimiter and
2047    /// returns prefix before delimiter and suffix after delimiter.
2048    ///
2049    /// # Examples
2050    ///
2051    /// ```
2052    /// assert_eq!("cfg".rsplit_once('='), None);
2053    /// assert_eq!("cfg=".rsplit_once('='), Some(("cfg", "")));
2054    /// assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
2055    /// assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
2056    /// ```
2057    #[stable(feature = "str_split_once", since = "1.52.0")]
2058    #[inline]
2059    pub fn rsplit_once<P: Pattern>(&self, delimiter: P) -> Option<(&'_ str, &'_ str)>
2060    where
2061        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2062    {
2063        let (start, end) = delimiter.into_searcher(self).next_match_back()?;
2064        // SAFETY: `Searcher` is known to return valid indices.
2065        unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
2066    }
2067
2068    /// Returns an iterator over the disjoint matches of a pattern within the
2069    /// given string slice.
2070    ///
2071    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2072    /// function or closure that determines if a character matches.
2073    ///
2074    /// [`char`]: prim@char
2075    /// [pattern]: self::pattern
2076    ///
2077    /// # Iterator behavior
2078    ///
2079    /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
2080    /// allows a reverse search and forward/reverse search yields the same
2081    /// elements. This is true for, e.g., [`char`], but not for `&str`.
2082    ///
2083    /// If the pattern allows a reverse search but its results might differ
2084    /// from a forward search, the [`rmatches`] method can be used.
2085    ///
2086    /// [`rmatches`]: str::rmatches
2087    ///
2088    /// # Examples
2089    ///
2090    /// ```
2091    /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
2092    /// assert_eq!(v, ["abc", "abc", "abc"]);
2093    ///
2094    /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
2095    /// assert_eq!(v, ["1", "2", "3"]);
2096    /// ```
2097    #[stable(feature = "str_matches", since = "1.2.0")]
2098    #[inline]
2099    pub fn matches<P: Pattern>(&self, pat: P) -> Matches<'_, P> {
2100        Matches(MatchesInternal(pat.into_searcher(self)))
2101    }
2102
2103    /// Returns an iterator over the disjoint matches of a pattern within this
2104    /// string slice, yielded in reverse order.
2105    ///
2106    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2107    /// function or closure that determines if a character matches.
2108    ///
2109    /// [`char`]: prim@char
2110    /// [pattern]: self::pattern
2111    ///
2112    /// # Iterator behavior
2113    ///
2114    /// The returned iterator requires that the pattern supports a reverse
2115    /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
2116    /// search yields the same elements.
2117    ///
2118    /// For iterating from the front, the [`matches`] method can be used.
2119    ///
2120    /// [`matches`]: str::matches
2121    ///
2122    /// # Examples
2123    ///
2124    /// ```
2125    /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
2126    /// assert_eq!(v, ["abc", "abc", "abc"]);
2127    ///
2128    /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
2129    /// assert_eq!(v, ["3", "2", "1"]);
2130    /// ```
2131    #[stable(feature = "str_matches", since = "1.2.0")]
2132    #[inline]
2133    pub fn rmatches<P: Pattern>(&self, pat: P) -> RMatches<'_, P>
2134    where
2135        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2136    {
2137        RMatches(self.matches(pat).0)
2138    }
2139
2140    /// Returns an iterator over the disjoint matches of a pattern within this string
2141    /// slice as well as the index that the match starts at.
2142    ///
2143    /// For matches of `pat` within `self` that overlap, only the indices
2144    /// corresponding to the first match are returned.
2145    ///
2146    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2147    /// function or closure that determines if a character matches.
2148    ///
2149    /// [`char`]: prim@char
2150    /// [pattern]: self::pattern
2151    ///
2152    /// # Iterator behavior
2153    ///
2154    /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
2155    /// allows a reverse search and forward/reverse search yields the same
2156    /// elements. This is true for, e.g., [`char`], but not for `&str`.
2157    ///
2158    /// If the pattern allows a reverse search but its results might differ
2159    /// from a forward search, the [`rmatch_indices`] method can be used.
2160    ///
2161    /// [`rmatch_indices`]: str::rmatch_indices
2162    ///
2163    /// # Examples
2164    ///
2165    /// ```
2166    /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
2167    /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
2168    ///
2169    /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
2170    /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
2171    ///
2172    /// let v: Vec<_> = "ababa".match_indices("aba").collect();
2173    /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
2174    /// ```
2175    #[stable(feature = "str_match_indices", since = "1.5.0")]
2176    #[inline]
2177    pub fn match_indices<P: Pattern>(&self, pat: P) -> MatchIndices<'_, P> {
2178        MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
2179    }
2180
2181    /// Returns an iterator over the disjoint matches of a pattern within `self`,
2182    /// yielded in reverse order along with the index of the match.
2183    ///
2184    /// For matches of `pat` within `self` that overlap, only the indices
2185    /// corresponding to the last match are returned.
2186    ///
2187    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2188    /// function or closure that determines if a character matches.
2189    ///
2190    /// [`char`]: prim@char
2191    /// [pattern]: self::pattern
2192    ///
2193    /// # Iterator behavior
2194    ///
2195    /// The returned iterator requires that the pattern supports a reverse
2196    /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
2197    /// search yields the same elements.
2198    ///
2199    /// For iterating from the front, the [`match_indices`] method can be used.
2200    ///
2201    /// [`match_indices`]: str::match_indices
2202    ///
2203    /// # Examples
2204    ///
2205    /// ```
2206    /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
2207    /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
2208    ///
2209    /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
2210    /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
2211    ///
2212    /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
2213    /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
2214    /// ```
2215    #[stable(feature = "str_match_indices", since = "1.5.0")]
2216    #[inline]
2217    pub fn rmatch_indices<P: Pattern>(&self, pat: P) -> RMatchIndices<'_, P>
2218    where
2219        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2220    {
2221        RMatchIndices(self.match_indices(pat).0)
2222    }
2223
2224    /// Returns a string slice with leading and trailing whitespace removed.
2225    ///
2226    /// 'Whitespace' is defined according to the terms of the Unicode Derived
2227    /// Core Property `White_Space`, which includes newlines.
2228    ///
2229    /// # Examples
2230    ///
2231    /// ```
2232    /// let s = "\n Hello\tworld\t\n";
2233    ///
2234    /// assert_eq!("Hello\tworld", s.trim());
2235    /// ```
2236    #[inline]
2237    #[must_use = "this returns the trimmed string as a slice, \
2238                  without modifying the original"]
2239    #[stable(feature = "rust1", since = "1.0.0")]
2240    #[rustc_diagnostic_item = "str_trim"]
2241    pub fn trim(&self) -> &str {
2242        self.trim_matches(char::is_whitespace)
2243    }
2244
2245    /// Returns a string slice with leading whitespace removed.
2246    ///
2247    /// 'Whitespace' is defined according to the terms of the Unicode Derived
2248    /// Core Property `White_Space`, which includes newlines.
2249    ///
2250    /// # Text directionality
2251    ///
2252    /// A string is a sequence of bytes. `start` in this context means the first
2253    /// position of that byte string; for a left-to-right language like English or
2254    /// Russian, this will be left side, and for right-to-left languages like
2255    /// Arabic or Hebrew, this will be the right side.
2256    ///
2257    /// # Examples
2258    ///
2259    /// Basic usage:
2260    ///
2261    /// ```
2262    /// let s = "\n Hello\tworld\t\n";
2263    /// assert_eq!("Hello\tworld\t\n", s.trim_start());
2264    /// ```
2265    ///
2266    /// Directionality:
2267    ///
2268    /// ```
2269    /// let s = "  English  ";
2270    /// assert!(Some('E') == s.trim_start().chars().next());
2271    ///
2272    /// let s = "  עברית  ";
2273    /// assert!(Some('ע') == s.trim_start().chars().next());
2274    /// ```
2275    #[inline]
2276    #[must_use = "this returns the trimmed string as a new slice, \
2277                  without modifying the original"]
2278    #[stable(feature = "trim_direction", since = "1.30.0")]
2279    #[rustc_diagnostic_item = "str_trim_start"]
2280    pub fn trim_start(&self) -> &str {
2281        self.trim_start_matches(char::is_whitespace)
2282    }
2283
2284    /// Returns a string slice with trailing whitespace removed.
2285    ///
2286    /// 'Whitespace' is defined according to the terms of the Unicode Derived
2287    /// Core Property `White_Space`, which includes newlines.
2288    ///
2289    /// # Text directionality
2290    ///
2291    /// A string is a sequence of bytes. `end` in this context means the last
2292    /// position of that byte string; for a left-to-right language like English or
2293    /// Russian, this will be right side, and for right-to-left languages like
2294    /// Arabic or Hebrew, this will be the left side.
2295    ///
2296    /// # Examples
2297    ///
2298    /// Basic usage:
2299    ///
2300    /// ```
2301    /// let s = "\n Hello\tworld\t\n";
2302    /// assert_eq!("\n Hello\tworld", s.trim_end());
2303    /// ```
2304    ///
2305    /// Directionality:
2306    ///
2307    /// ```
2308    /// let s = "  English  ";
2309    /// assert!(Some('h') == s.trim_end().chars().rev().next());
2310    ///
2311    /// let s = "  עברית  ";
2312    /// assert!(Some('ת') == s.trim_end().chars().rev().next());
2313    /// ```
2314    #[inline]
2315    #[must_use = "this returns the trimmed string as a new slice, \
2316                  without modifying the original"]
2317    #[stable(feature = "trim_direction", since = "1.30.0")]
2318    #[rustc_diagnostic_item = "str_trim_end"]
2319    pub fn trim_end(&self) -> &str {
2320        self.trim_end_matches(char::is_whitespace)
2321    }
2322
2323    /// Returns a string slice with leading whitespace removed.
2324    ///
2325    /// 'Whitespace' is defined according to the terms of the Unicode Derived
2326    /// Core Property `White_Space`.
2327    ///
2328    /// # Text directionality
2329    ///
2330    /// A string is a sequence of bytes. 'Left' in this context means the first
2331    /// position of that byte string; for a language like Arabic or Hebrew
2332    /// which are 'right to left' rather than 'left to right', this will be
2333    /// the _right_ side, not the left.
2334    ///
2335    /// # Examples
2336    ///
2337    /// Basic usage:
2338    ///
2339    /// ```
2340    /// let s = " Hello\tworld\t";
2341    ///
2342    /// assert_eq!("Hello\tworld\t", s.trim_left());
2343    /// ```
2344    ///
2345    /// Directionality:
2346    ///
2347    /// ```
2348    /// let s = "  English";
2349    /// assert!(Some('E') == s.trim_left().chars().next());
2350    ///
2351    /// let s = "  עברית";
2352    /// assert!(Some('ע') == s.trim_left().chars().next());
2353    /// ```
2354    #[must_use = "this returns the trimmed string as a new slice, \
2355                  without modifying the original"]
2356    #[inline]
2357    #[stable(feature = "rust1", since = "1.0.0")]
2358    #[deprecated(since = "1.33.0", note = "superseded by `trim_start`", suggestion = "trim_start")]
2359    pub fn trim_left(&self) -> &str {
2360        self.trim_start()
2361    }
2362
2363    /// Returns a string slice with trailing whitespace removed.
2364    ///
2365    /// 'Whitespace' is defined according to the terms of the Unicode Derived
2366    /// Core Property `White_Space`.
2367    ///
2368    /// # Text directionality
2369    ///
2370    /// A string is a sequence of bytes. 'Right' in this context means the last
2371    /// position of that byte string; for a language like Arabic or Hebrew
2372    /// which are 'right to left' rather than 'left to right', this will be
2373    /// the _left_ side, not the right.
2374    ///
2375    /// # Examples
2376    ///
2377    /// Basic usage:
2378    ///
2379    /// ```
2380    /// let s = " Hello\tworld\t";
2381    ///
2382    /// assert_eq!(" Hello\tworld", s.trim_right());
2383    /// ```
2384    ///
2385    /// Directionality:
2386    ///
2387    /// ```
2388    /// let s = "English  ";
2389    /// assert!(Some('h') == s.trim_right().chars().rev().next());
2390    ///
2391    /// let s = "עברית  ";
2392    /// assert!(Some('ת') == s.trim_right().chars().rev().next());
2393    /// ```
2394    #[must_use = "this returns the trimmed string as a new slice, \
2395                  without modifying the original"]
2396    #[inline]
2397    #[stable(feature = "rust1", since = "1.0.0")]
2398    #[deprecated(since = "1.33.0", note = "superseded by `trim_end`", suggestion = "trim_end")]
2399    pub fn trim_right(&self) -> &str {
2400        self.trim_end()
2401    }
2402
2403    /// Returns a string slice with all prefixes and suffixes that match a
2404    /// pattern repeatedly removed.
2405    ///
2406    /// The [pattern] can be a [`char`], a slice of [`char`]s, or a function
2407    /// or closure that determines if a character matches.
2408    ///
2409    /// [`char`]: prim@char
2410    /// [pattern]: self::pattern
2411    ///
2412    /// # Examples
2413    ///
2414    /// Simple patterns:
2415    ///
2416    /// ```
2417    /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
2418    /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
2419    ///
2420    /// let x: &[_] = &['1', '2'];
2421    /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
2422    /// ```
2423    ///
2424    /// A more complex pattern, using a closure:
2425    ///
2426    /// ```
2427    /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
2428    /// ```
2429    #[must_use = "this returns the trimmed string as a new slice, \
2430                  without modifying the original"]
2431    #[stable(feature = "rust1", since = "1.0.0")]
2432    pub fn trim_matches<P: Pattern>(&self, pat: P) -> &str
2433    where
2434        for<'a> P::Searcher<'a>: DoubleEndedSearcher<'a>,
2435    {
2436        let mut i = 0;
2437        let mut j = 0;
2438        let mut matcher = pat.into_searcher(self);
2439        if let Some((a, b)) = matcher.next_reject() {
2440            i = a;
2441            j = b; // Remember earliest known match, correct it below if
2442            // last match is different
2443        }
2444        if let Some((_, b)) = matcher.next_reject_back() {
2445            j = b;
2446        }
2447        // SAFETY: `Searcher` is known to return valid indices.
2448        unsafe { self.get_unchecked(i..j) }
2449    }
2450
2451    /// Returns a string slice with all prefixes that match a pattern
2452    /// repeatedly removed.
2453    ///
2454    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2455    /// function or closure that determines if a character matches.
2456    ///
2457    /// [`char`]: prim@char
2458    /// [pattern]: self::pattern
2459    ///
2460    /// # Text directionality
2461    ///
2462    /// A string is a sequence of bytes. `start` in this context means the first
2463    /// position of that byte string; for a left-to-right language like English or
2464    /// Russian, this will be left side, and for right-to-left languages like
2465    /// Arabic or Hebrew, this will be the right side.
2466    ///
2467    /// # Examples
2468    ///
2469    /// ```
2470    /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
2471    /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
2472    ///
2473    /// let x: &[_] = &['1', '2'];
2474    /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
2475    /// ```
2476    #[must_use = "this returns the trimmed string as a new slice, \
2477                  without modifying the original"]
2478    #[stable(feature = "trim_direction", since = "1.30.0")]
2479    pub fn trim_start_matches<P: Pattern>(&self, pat: P) -> &str {
2480        let mut i = self.len();
2481        let mut matcher = pat.into_searcher(self);
2482        if let Some((a, _)) = matcher.next_reject() {
2483            i = a;
2484        }
2485        // SAFETY: `Searcher` is known to return valid indices.
2486        unsafe { self.get_unchecked(i..self.len()) }
2487    }
2488
2489    /// Returns a string slice with the prefix removed.
2490    ///
2491    /// If the string starts with the pattern `prefix`, returns the substring after the prefix,
2492    /// wrapped in `Some`. Unlike [`trim_start_matches`], this method removes the prefix exactly once.
2493    ///
2494    /// If the string does not start with `prefix`, returns `None`.
2495    ///
2496    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2497    /// function or closure that determines if a character matches.
2498    ///
2499    /// [`char`]: prim@char
2500    /// [pattern]: self::pattern
2501    /// [`trim_start_matches`]: Self::trim_start_matches
2502    ///
2503    /// # Examples
2504    ///
2505    /// ```
2506    /// assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
2507    /// assert_eq!("foo:bar".strip_prefix("bar"), None);
2508    /// assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
2509    /// ```
2510    #[must_use = "this returns the remaining substring as a new slice, \
2511                  without modifying the original"]
2512    #[stable(feature = "str_strip", since = "1.45.0")]
2513    pub fn strip_prefix<P: Pattern>(&self, prefix: P) -> Option<&str> {
2514        prefix.strip_prefix_of(self)
2515    }
2516
2517    /// Returns a string slice with the suffix removed.
2518    ///
2519    /// If the string ends with the pattern `suffix`, returns the substring before the suffix,
2520    /// wrapped in `Some`.  Unlike [`trim_end_matches`], this method removes the suffix exactly once.
2521    ///
2522    /// If the string does not end with `suffix`, returns `None`.
2523    ///
2524    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2525    /// function or closure that determines if a character matches.
2526    ///
2527    /// [`char`]: prim@char
2528    /// [pattern]: self::pattern
2529    /// [`trim_end_matches`]: Self::trim_end_matches
2530    ///
2531    /// # Examples
2532    ///
2533    /// ```
2534    /// assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
2535    /// assert_eq!("bar:foo".strip_suffix("bar"), None);
2536    /// assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
2537    /// ```
2538    #[must_use = "this returns the remaining substring as a new slice, \
2539                  without modifying the original"]
2540    #[stable(feature = "str_strip", since = "1.45.0")]
2541    #[ferrocene::prevalidated]
2542    pub fn strip_suffix<P: Pattern>(&self, suffix: P) -> Option<&str>
2543    where
2544        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2545    {
2546        suffix.strip_suffix_of(self)
2547    }
2548
2549    /// Returns a string slice with the prefix and suffix removed.
2550    ///
2551    /// If the string starts with the pattern `prefix` and ends with
2552    /// the pattern `suffix`, and the prefix and suffix don't overlap, returns
2553    /// the substring after the prefix and before the suffix, wrapped in `Some`.
2554    /// Unlike [`trim_start_matches`] and [`trim_end_matches`], this method removes both the prefix
2555    /// and suffix exactly once.
2556    ///
2557    /// If the string does not start with `prefix`, does not end with `suffix`,
2558    /// or the prefix and suffix overlap in the string, returns `None`.
2559    ///
2560    /// Each [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2561    /// function or closure that determines if a character matches.
2562    ///
2563    /// [`char`]: prim@char
2564    /// [pattern]: self::pattern
2565    /// [`trim_start_matches`]: Self::trim_start_matches
2566    /// [`trim_end_matches`]: Self::trim_end_matches
2567    ///
2568    /// # Examples
2569    ///
2570    /// ```
2571    /// assert_eq!("bar:hello:foo".strip_circumfix("bar:", ":foo"), Some("hello"));
2572    /// assert_eq!("bar:foo".strip_circumfix("foo", "foo"), None);
2573    /// assert_eq!("foo:bar;".strip_circumfix("foo:", ';'), Some("bar"));
2574    /// assert_eq!("foo:bar:baz".strip_circumfix("foo:bar:", ":bar:baz"), None);
2575    /// ```
2576    #[must_use = "this returns the remaining substring as a new slice, \
2577                  without modifying the original"]
2578    #[stable(feature = "strip_circumfix", since = "1.98.0")]
2579    pub fn strip_circumfix<P: Pattern, S: Pattern>(&self, prefix: P, suffix: S) -> Option<&str>
2580    where
2581        for<'a> S::Searcher<'a>: ReverseSearcher<'a>,
2582    {
2583        self.strip_prefix(prefix)?.strip_suffix(suffix)
2584    }
2585
2586    /// Returns a string slice with the optional prefix removed.
2587    ///
2588    /// If the string starts with the pattern `prefix`, returns the substring after the prefix.
2589    /// Unlike [`strip_prefix`], this method always returns `&str` for easy method chaining,
2590    /// instead of returning [`Option<&str>`].
2591    ///
2592    /// If the string does not start with `prefix`, returns the original string unchanged.
2593    ///
2594    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2595    /// function or closure that determines if a character matches.
2596    ///
2597    /// [`char`]: prim@char
2598    /// [pattern]: self::pattern
2599    /// [`strip_prefix`]: Self::strip_prefix
2600    ///
2601    /// # Examples
2602    ///
2603    /// ```
2604    /// // Prefix present - removes it
2605    /// assert_eq!("foo:bar".trim_prefix("foo:"), "bar");
2606    /// assert_eq!("foofoo".trim_prefix("foo"), "foo");
2607    ///
2608    /// // Prefix absent - returns original string
2609    /// assert_eq!("foo:bar".trim_prefix("bar"), "foo:bar");
2610    ///
2611    /// // Method chaining example
2612    /// assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/");
2613    /// ```
2614    #[must_use = "this returns the remaining substring as a new slice, \
2615                  without modifying the original"]
2616    #[stable(feature = "trim_prefix_suffix", since = "1.100.0")]
2617    pub fn trim_prefix<P: Pattern>(&self, prefix: P) -> &str {
2618        prefix.strip_prefix_of(self).unwrap_or(self)
2619    }
2620
2621    /// Returns a string slice with the optional suffix removed.
2622    ///
2623    /// If the string ends with the pattern `suffix`, returns the substring before the suffix.
2624    /// Unlike [`strip_suffix`], this method always returns `&str` for easy method chaining,
2625    /// instead of returning [`Option<&str>`].
2626    ///
2627    /// If the string does not end with `suffix`, returns the original string unchanged.
2628    ///
2629    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2630    /// function or closure that determines if a character matches.
2631    ///
2632    /// [`char`]: prim@char
2633    /// [pattern]: self::pattern
2634    /// [`strip_suffix`]: Self::strip_suffix
2635    ///
2636    /// # Examples
2637    ///
2638    /// ```
2639    /// // Suffix present - removes it
2640    /// assert_eq!("bar:foo".trim_suffix(":foo"), "bar");
2641    /// assert_eq!("foofoo".trim_suffix("foo"), "foo");
2642    ///
2643    /// // Suffix absent - returns original string
2644    /// assert_eq!("bar:foo".trim_suffix("bar"), "bar:foo");
2645    ///
2646    /// // Method chaining example
2647    /// assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/");
2648    /// ```
2649    #[must_use = "this returns the remaining substring as a new slice, \
2650                  without modifying the original"]
2651    #[stable(feature = "trim_prefix_suffix", since = "1.100.0")]
2652    pub fn trim_suffix<P: Pattern>(&self, suffix: P) -> &str
2653    where
2654        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2655    {
2656        suffix.strip_suffix_of(self).unwrap_or(self)
2657    }
2658
2659    /// Returns a string slice with all suffixes that match a pattern
2660    /// repeatedly removed.
2661    ///
2662    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2663    /// function or closure that determines if a character matches.
2664    ///
2665    /// [`char`]: prim@char
2666    /// [pattern]: self::pattern
2667    ///
2668    /// # Text directionality
2669    ///
2670    /// A string is a sequence of bytes. `end` in this context means the last
2671    /// position of that byte string; for a left-to-right language like English or
2672    /// Russian, this will be right side, and for right-to-left languages like
2673    /// Arabic or Hebrew, this will be the left side.
2674    ///
2675    /// # Examples
2676    ///
2677    /// Simple patterns:
2678    ///
2679    /// ```
2680    /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
2681    /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
2682    ///
2683    /// let x: &[_] = &['1', '2'];
2684    /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
2685    /// ```
2686    ///
2687    /// A more complex pattern, using a closure:
2688    ///
2689    /// ```
2690    /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
2691    /// ```
2692    #[must_use = "this returns the trimmed string as a new slice, \
2693                  without modifying the original"]
2694    #[stable(feature = "trim_direction", since = "1.30.0")]
2695    pub fn trim_end_matches<P: Pattern>(&self, pat: P) -> &str
2696    where
2697        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2698    {
2699        let mut j = 0;
2700        let mut matcher = pat.into_searcher(self);
2701        if let Some((_, b)) = matcher.next_reject_back() {
2702            j = b;
2703        }
2704        // SAFETY: `Searcher` is known to return valid indices.
2705        unsafe { self.get_unchecked(0..j) }
2706    }
2707
2708    /// Returns a string slice with all prefixes that match a pattern
2709    /// repeatedly removed.
2710    ///
2711    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2712    /// function or closure that determines if a character matches.
2713    ///
2714    /// [`char`]: prim@char
2715    /// [pattern]: self::pattern
2716    ///
2717    /// # Text directionality
2718    ///
2719    /// A string is a sequence of bytes. 'Left' in this context means the first
2720    /// position of that byte string; for a language like Arabic or Hebrew
2721    /// which are 'right to left' rather than 'left to right', this will be
2722    /// the _right_ side, not the left.
2723    ///
2724    /// # Examples
2725    ///
2726    /// ```
2727    /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
2728    /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
2729    ///
2730    /// let x: &[_] = &['1', '2'];
2731    /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
2732    /// ```
2733    #[stable(feature = "rust1", since = "1.0.0")]
2734    #[deprecated(
2735        since = "1.33.0",
2736        note = "superseded by `trim_start_matches`",
2737        suggestion = "trim_start_matches"
2738    )]
2739    pub fn trim_left_matches<P: Pattern>(&self, pat: P) -> &str {
2740        self.trim_start_matches(pat)
2741    }
2742
2743    /// Returns a string slice with all suffixes that match a pattern
2744    /// repeatedly removed.
2745    ///
2746    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2747    /// function or closure that determines if a character matches.
2748    ///
2749    /// [`char`]: prim@char
2750    /// [pattern]: self::pattern
2751    ///
2752    /// # Text directionality
2753    ///
2754    /// A string is a sequence of bytes. 'Right' in this context means the last
2755    /// position of that byte string; for a language like Arabic or Hebrew
2756    /// which are 'right to left' rather than 'left to right', this will be
2757    /// the _left_ side, not the right.
2758    ///
2759    /// # Examples
2760    ///
2761    /// Simple patterns:
2762    ///
2763    /// ```
2764    /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
2765    /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
2766    ///
2767    /// let x: &[_] = &['1', '2'];
2768    /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
2769    /// ```
2770    ///
2771    /// A more complex pattern, using a closure:
2772    ///
2773    /// ```
2774    /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
2775    /// ```
2776    #[stable(feature = "rust1", since = "1.0.0")]
2777    #[deprecated(
2778        since = "1.33.0",
2779        note = "superseded by `trim_end_matches`",
2780        suggestion = "trim_end_matches"
2781    )]
2782    pub fn trim_right_matches<P: Pattern>(&self, pat: P) -> &str
2783    where
2784        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2785    {
2786        self.trim_end_matches(pat)
2787    }
2788
2789    /// Parses this string slice into another type.
2790    ///
2791    /// Because `parse` is so general, it can cause problems with type
2792    /// inference. As such, `parse` is one of the few times you'll see
2793    /// the syntax affectionately known as the 'turbofish': `::<>`. This
2794    /// helps the inference algorithm understand specifically which type
2795    /// you're trying to parse into.
2796    ///
2797    /// `parse` can parse into any type that implements the [`FromStr`] trait.
2798    ///
2799    /// # Errors
2800    ///
2801    /// Will return [`Err`] if it's not possible to parse this string slice into
2802    /// the desired type.
2803    ///
2804    /// [`Err`]: FromStr::Err
2805    ///
2806    /// # Examples
2807    ///
2808    /// Basic usage:
2809    ///
2810    /// ```
2811    /// let four: u32 = "4".parse().unwrap();
2812    ///
2813    /// assert_eq!(4, four);
2814    /// ```
2815    ///
2816    /// Using the 'turbofish' instead of annotating `four`:
2817    ///
2818    /// ```
2819    /// let four = "4".parse::<u32>();
2820    ///
2821    /// assert_eq!(Ok(4), four);
2822    /// ```
2823    ///
2824    /// Failing to parse:
2825    ///
2826    /// ```
2827    /// let nope = "j".parse::<u32>();
2828    ///
2829    /// assert!(nope.is_err());
2830    /// ```
2831    #[inline]
2832    #[stable(feature = "rust1", since = "1.0.0")]
2833    #[ferrocene::prevalidated]
2834    pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
2835        FromStr::from_str(self)
2836    }
2837
2838    /// Checks if all characters in this string are within the ASCII range.
2839    ///
2840    /// An empty string returns `true`.
2841    ///
2842    /// # Examples
2843    ///
2844    /// ```
2845    /// let ascii = "hello!\n";
2846    /// let non_ascii = "Grüße, Jürgen ❤";
2847    ///
2848    /// assert!(ascii.is_ascii());
2849    /// assert!(!non_ascii.is_ascii());
2850    /// ```
2851    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2852    #[rustc_const_stable(feature = "const_slice_is_ascii", since = "1.74.0")]
2853    #[must_use]
2854    #[inline]
2855    #[ferrocene::prevalidated]
2856    pub const fn is_ascii(&self) -> bool {
2857        // We can treat each byte as character here: all multibyte characters
2858        // start with a byte that is not in the ASCII range, so we will stop
2859        // there already.
2860        self.as_bytes().is_ascii()
2861    }
2862
2863    /// If this string slice [`is_ascii`](Self::is_ascii), returns it as a slice
2864    /// of [ASCII characters](`ascii::Char`), otherwise returns `None`.
2865    #[unstable(feature = "ascii_char", issue = "110998")]
2866    #[must_use]
2867    #[inline]
2868    pub const fn as_ascii(&self) -> Option<&[ascii::Char]> {
2869        // Like in `is_ascii`, we can work on the bytes directly.
2870        self.as_bytes().as_ascii()
2871    }
2872
2873    /// Converts this string slice into a slice of [ASCII characters](ascii::Char),
2874    /// without checking whether they are valid.
2875    ///
2876    /// # Safety
2877    ///
2878    /// Every character in this string must be ASCII, or else this is UB.
2879    #[unstable(feature = "ascii_char", issue = "110998")]
2880    #[must_use]
2881    #[inline]
2882    pub const unsafe fn as_ascii_unchecked(&self) -> &[ascii::Char] {
2883        assert_unsafe_precondition!(
2884            check_library_ub,
2885            "as_ascii_unchecked requires that the string is valid ASCII",
2886            (it: &str = self) => it.is_ascii()
2887        );
2888
2889        // SAFETY: the caller promised that every byte of this string slice
2890        // is ASCII.
2891        unsafe { self.as_bytes().as_ascii_unchecked() }
2892    }
2893
2894    /// Checks that two strings are an ASCII case-insensitive match.
2895    ///
2896    /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2897    /// but without allocating and copying temporaries.
2898    ///
2899    /// For Unicode-aware case-insensitive matching, consider
2900    /// [`str::eq_ignore_case_unnormalized`].
2901    ///
2902    /// # Examples
2903    ///
2904    /// ```
2905    /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2906    /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2907    /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2908    /// ```
2909    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2910    #[rustc_const_stable(feature = "const_eq_ignore_ascii_case", since = "1.89.0")]
2911    #[must_use]
2912    #[inline]
2913    #[ferrocene::prevalidated]
2914    pub const fn eq_ignore_ascii_case(&self, other: &str) -> bool {
2915        self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
2916    }
2917
2918    /// Checks that two strings are a caseless match, according to
2919    /// [Definition 144] in Chapter 3 of the Unicode Standard.
2920    ///
2921    /// [Definition 144]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G53513
2922    ///
2923    /// Same as `a.to_casefold_unnormalized() == b.to_casefold_unnormalized()`,
2924    /// but without allocating. See that method's documentation,
2925    /// as well as [`char::to_casefold_unnormalized()`],
2926    /// for more information about case folding.
2927    ///
2928    /// No [normalization] (e.g. NFC) is performed, so visually and semantically identical strings
2929    /// might still compare unequal. For example, `"Å"` (U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE)
2930    /// is considered distinct from `"Å"` (A followed by U+030A COMBINING RING ABOVE),
2931    /// even though Unicode considers them canonically equivalent.
2932    ///
2933    /// In addition, this method is independent of language/locale,
2934    /// so the special behavior of I/ı/İ/i in Turkish and Azeri is not handled.
2935    ///
2936    /// # Examples
2937    ///
2938    /// ```
2939    /// #![feature(casefold)]
2940    /// assert!("Ferris".eq_ignore_case_unnormalized("FERRIS"));
2941    /// assert!("Ferrös".eq_ignore_case_unnormalized("FERRÖS"));
2942    /// assert!("ẞ".eq_ignore_case_unnormalized("ss"));
2943    /// ```
2944    ///
2945    /// No NFC [normalization] is performed:
2946    ///
2947    /// ```rust
2948    /// #![feature(casefold)]
2949    /// // These two strings are visually and semantically identical...
2950    /// let comp = "Å";
2951    /// let decomp = "Å";
2952    ///
2953    /// // ... but not codepoint-for-codepoint equal.
2954    /// assert_eq!(comp, "\u{C5}");
2955    /// assert_eq!(decomp, "A\u{030A}");
2956    ///
2957    /// // Their case-foldings are likewise unequal:
2958    /// assert!(!comp.eq_ignore_case_unnormalized(decomp));
2959    /// ```
2960    ///
2961    /// [normalization]: https://www.unicode.org/faq/normalization.html
2962    #[unstable(feature = "casefold", issue = "157000")]
2963    #[must_use]
2964    #[inline]
2965    pub fn eq_ignore_case_unnormalized(&self, other: &str) -> bool {
2966        self.chars()
2967            .flat_map(char::to_casefold_unnormalized)
2968            .eq(other.chars().flat_map(char::to_casefold_unnormalized))
2969    }
2970
2971    /// Converts this string to its ASCII upper case equivalent in-place.
2972    ///
2973    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2974    /// but all other characters are unchanged.
2975    ///
2976    /// To return a new uppercased value without modifying the existing one, use
2977    /// [`to_ascii_uppercase()`].
2978    ///
2979    /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
2980    ///
2981    /// # Examples
2982    ///
2983    /// ```
2984    /// let mut s = String::from("Grüße, Jürgen ❤");
2985    ///
2986    /// s.make_ascii_uppercase();
2987    ///
2988    /// assert_eq!("GRüßE, JüRGEN ❤", s);
2989    /// ```
2990    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2991    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
2992    #[inline]
2993    pub const fn make_ascii_uppercase(&mut self) {
2994        // SAFETY: changing ASCII letters only does not invalidate UTF-8.
2995        let me = unsafe { self.as_bytes_mut() };
2996        me.make_ascii_uppercase()
2997    }
2998
2999    /// Converts this string to its ASCII lower case equivalent in-place.
3000    ///
3001    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3002    /// but all other characters are unchanged.
3003    ///
3004    /// To return a new lowercased value without modifying the existing one, use
3005    /// [`to_ascii_lowercase()`].
3006    ///
3007    /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
3008    ///
3009    /// # Examples
3010    ///
3011    /// ```
3012    /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
3013    ///
3014    /// s.make_ascii_lowercase();
3015    ///
3016    /// assert_eq!("grÜße, jÜrgen ❤", s);
3017    /// ```
3018    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3019    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
3020    #[inline]
3021    pub const fn make_ascii_lowercase(&mut self) {
3022        // SAFETY: changing ASCII letters only does not invalidate UTF-8.
3023        let me = unsafe { self.as_bytes_mut() };
3024        me.make_ascii_lowercase()
3025    }
3026
3027    /// Copies the string from `src` into `self`, using a memcpy.
3028    ///
3029    /// The length of `src` must be the same as `self`.
3030    ///
3031    /// # Panics
3032    ///
3033    /// This function will panic if the two strings have different lengths.
3034    ///
3035    /// # Examples
3036    ///
3037    /// ```
3038    /// #![feature(str_copy_from_str)]
3039    /// let src = "Saludos";
3040    /// let mut dst = String::from("Grüße, Jürgen");
3041    ///
3042    /// // Because the strings have to be the same length,
3043    /// // we slice the destination slice from sixteen bytes
3044    /// // to seven. It will panic if we don't do this.
3045    /// dst[..7].copy_from_str(src);
3046    ///
3047    /// assert_eq!(src, "Saludos");
3048    /// assert_eq!(dst, "Saludos, Jürgen");
3049    /// ```
3050    ///
3051    /// Rust enforces that there can only be one mutable reference with no
3052    /// immutable references to a particular piece of data in a particular
3053    /// scope. Because of this, attempting to use `copy_from_str` on a
3054    /// single string will result in a compile failure:
3055    ///
3056    /// ```compile_fail
3057    /// #![feature(str_copy_from_str)]
3058    /// let mut string = String::from("Abcde");
3059    ///
3060    /// string[..2].copy_from_str(&string[3..]); // compile fail!
3061    /// ```
3062    ///
3063    /// To work around this, we can use [`split_at_mut`] to create two distinct
3064    /// sub-slices from a string:
3065    ///
3066    /// ```
3067    /// #![feature(str_copy_from_str)]
3068    /// let mut string = String::from("Abcde");
3069    ///
3070    /// {
3071    ///     let (left, right) = string.split_at_mut(2);
3072    ///     left.copy_from_str(&right[1..]);
3073    /// }
3074    ///
3075    /// assert_eq!(string, "decde");
3076    /// ```
3077    ///
3078    /// [`split_at_mut`]: str::split_at_mut
3079    #[doc(alias = "memcpy")]
3080    #[inline]
3081    #[unstable(feature = "str_copy_from_str", issue = "159841")]
3082    #[track_caller]
3083    pub fn copy_from_str(&mut self, src: &str) {
3084        // SAFETY: `copy_from_slice` panics unless the lengths are equal, and copying same-length
3085        // UTF-8 into a `str` keeps it valid UTF-8.
3086        let me = unsafe { self.as_bytes_mut() };
3087        me.copy_from_slice(src.as_bytes());
3088    }
3089
3090    /// Returns a string slice with leading ASCII whitespace removed.
3091    ///
3092    /// 'Whitespace' refers to the definition used by
3093    /// [`u8::is_ascii_whitespace`]. Importantly, this definition excludes
3094    /// the U+000B code point even though it has the Unicode [`White_Space`] property
3095    /// and is removed by [`str::trim_start`].
3096    ///
3097    /// [`u8::is_ascii_whitespace`]: u8::is_ascii_whitespace
3098    /// [`White_Space`]: https://www.unicode.org/reports/tr44/#White_Space
3099    ///
3100    /// # Examples
3101    ///
3102    /// ```
3103    /// assert_eq!(" \t \u{3000}hello world\n".trim_ascii_start(), "\u{3000}hello world\n");
3104    /// assert_eq!("  ".trim_ascii_start(), "");
3105    /// assert_eq!("".trim_ascii_start(), "");
3106    /// ```
3107    #[must_use = "this returns the trimmed string as a new slice, \
3108                  without modifying the original"]
3109    #[stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
3110    #[rustc_const_stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
3111    #[inline]
3112    pub const fn trim_ascii_start(&self) -> &str {
3113        // SAFETY: Removing ASCII characters from a `&str` does not invalidate
3114        // UTF-8.
3115        unsafe { core::str::from_utf8_unchecked(self.as_bytes().trim_ascii_start()) }
3116    }
3117
3118    /// Returns a string slice with trailing ASCII whitespace removed.
3119    ///
3120    /// 'Whitespace' refers to the definition used by
3121    /// [`u8::is_ascii_whitespace`]. Importantly, this definition excludes
3122    /// the U+000B code point even though it has the Unicode [`White_Space`] property
3123    /// and is removed by [`str::trim_end`].
3124    ///
3125    /// [`u8::is_ascii_whitespace`]: u8::is_ascii_whitespace
3126    /// [`White_Space`]: https://www.unicode.org/reports/tr44/#White_Space
3127    ///
3128    /// # Examples
3129    ///
3130    /// ```
3131    /// assert_eq!("\r hello world\u{3000}\n ".trim_ascii_end(), "\r hello world\u{3000}");
3132    /// assert_eq!("  ".trim_ascii_end(), "");
3133    /// assert_eq!("".trim_ascii_end(), "");
3134    /// ```
3135    #[must_use = "this returns the trimmed string as a new slice, \
3136                  without modifying the original"]
3137    #[stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
3138    #[rustc_const_stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
3139    #[inline]
3140    pub const fn trim_ascii_end(&self) -> &str {
3141        // SAFETY: Removing ASCII characters from a `&str` does not invalidate
3142        // UTF-8.
3143        unsafe { core::str::from_utf8_unchecked(self.as_bytes().trim_ascii_end()) }
3144    }
3145
3146    /// Returns a string slice with leading and trailing ASCII whitespace
3147    /// removed.
3148    ///
3149    /// 'Whitespace' refers to the definition used by
3150    /// [`u8::is_ascii_whitespace`]. Importantly, this definition excludes
3151    /// the U+000B code point even though it has the Unicode [`White_Space`] property
3152    /// and is removed by [`str::trim`].
3153    ///
3154    /// [`u8::is_ascii_whitespace`]: u8::is_ascii_whitespace
3155    /// [`White_Space`]: https://www.unicode.org/reports/tr44/#White_Space
3156    ///
3157    /// # Examples
3158    ///
3159    /// ```
3160    /// assert_eq!("\r hello world\n ".trim_ascii(), "hello world");
3161    /// assert_eq!("  ".trim_ascii(), "");
3162    /// assert_eq!("".trim_ascii(), "");
3163    /// ```
3164    #[must_use = "this returns the trimmed string as a new slice, \
3165                  without modifying the original"]
3166    #[stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
3167    #[rustc_const_stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
3168    #[inline]
3169    pub const fn trim_ascii(&self) -> &str {
3170        // SAFETY: Removing ASCII characters from a `&str` does not invalidate
3171        // UTF-8.
3172        unsafe { core::str::from_utf8_unchecked(self.as_bytes().trim_ascii()) }
3173    }
3174
3175    /// Returns an iterator that escapes each char in `self` with [`char::escape_debug`].
3176    ///
3177    /// # Examples
3178    ///
3179    /// As an iterator:
3180    ///
3181    /// ```
3182    /// for c in "❤\n!".escape_debug() {
3183    ///     print!("{c}");
3184    /// }
3185    /// println!();
3186    /// ```
3187    ///
3188    /// Using `println!` directly:
3189    ///
3190    /// ```
3191    /// println!("{}", "❤\n!".escape_debug());
3192    /// ```
3193    ///
3194    ///
3195    /// Both are equivalent to:
3196    ///
3197    /// ```
3198    /// println!("❤\\n!");
3199    /// ```
3200    ///
3201    /// Using `to_string`:
3202    ///
3203    /// ```
3204    /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
3205    /// ```
3206    #[must_use = "this returns the escaped string as an iterator, \
3207                  without modifying the original"]
3208    #[stable(feature = "str_escape", since = "1.34.0")]
3209    pub fn escape_debug(&self) -> EscapeDebug<'_> {
3210        EscapeDebug { inner: self.chars().flat_map(CharEscapeDebug) }
3211    }
3212
3213    /// Returns an iterator that escapes each char in `self` with [`char::escape_default`].
3214    ///
3215    /// # Examples
3216    ///
3217    /// As an iterator:
3218    ///
3219    /// ```
3220    /// for c in "❤\n!".escape_default() {
3221    ///     print!("{c}");
3222    /// }
3223    /// println!();
3224    /// ```
3225    ///
3226    /// Using `println!` directly:
3227    ///
3228    /// ```
3229    /// println!("{}", "❤\n!".escape_default());
3230    /// ```
3231    ///
3232    ///
3233    /// Both are equivalent to:
3234    ///
3235    /// ```
3236    /// println!("\\u{{2764}}\\n!");
3237    /// ```
3238    ///
3239    /// Using `to_string`:
3240    ///
3241    /// ```
3242    /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
3243    /// ```
3244    #[must_use = "this returns the escaped string as an iterator, \
3245                  without modifying the original"]
3246    #[stable(feature = "str_escape", since = "1.34.0")]
3247    pub fn escape_default(&self) -> EscapeDefault<'_> {
3248        EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
3249    }
3250
3251    /// Returns an iterator that escapes each char in `self` with [`char::escape_unicode`].
3252    ///
3253    /// # Examples
3254    ///
3255    /// As an iterator:
3256    ///
3257    /// ```
3258    /// for c in "❤\n!".escape_unicode() {
3259    ///     print!("{c}");
3260    /// }
3261    /// println!();
3262    /// ```
3263    ///
3264    /// Using `println!` directly:
3265    ///
3266    /// ```
3267    /// println!("{}", "❤\n!".escape_unicode());
3268    /// ```
3269    ///
3270    ///
3271    /// Both are equivalent to:
3272    ///
3273    /// ```
3274    /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
3275    /// ```
3276    ///
3277    /// Using `to_string`:
3278    ///
3279    /// ```
3280    /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
3281    /// ```
3282    #[must_use = "this returns the escaped string as an iterator, \
3283                  without modifying the original"]
3284    #[stable(feature = "str_escape", since = "1.34.0")]
3285    pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
3286        EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
3287    }
3288
3289    /// Returns the range that a substring points to.
3290    ///
3291    /// Returns `None` if `substr` does not point within `self`.
3292    ///
3293    /// Unlike [`str::find`], **this does not search through the string**.
3294    /// Instead, it uses pointer arithmetic to find where in the string
3295    /// `substr` is derived from.
3296    ///
3297    /// This is useful for extending [`str::split`] and similar methods.
3298    ///
3299    /// Note that this method may return false positives (typically either
3300    /// `Some(0..0)` or `Some(self.len()..self.len())`) if `substr` is a
3301    /// zero-length `str` that points at the beginning or end of another,
3302    /// independent, `str`.
3303    ///
3304    /// # Examples
3305    /// ```
3306    /// use core::range::Range;
3307    ///
3308    /// let data = "a, b, b, a";
3309    /// let mut iter = data.split(", ").map(|s| data.substr_range(s).unwrap());
3310    ///
3311    /// assert_eq!(iter.next(), Some(Range { start: 0, end: 1 }));
3312    /// assert_eq!(iter.next(), Some(Range { start: 3, end: 4 }));
3313    /// assert_eq!(iter.next(), Some(Range { start: 6, end: 7 }));
3314    /// assert_eq!(iter.next(), Some(Range { start: 9, end: 10 }));
3315    /// ```
3316    #[must_use]
3317    #[stable(feature = "substr_range", since = "1.98.0")]
3318    pub fn substr_range(&self, substr: &str) -> Option<Range<usize>> {
3319        self.as_bytes().subslice_range(substr.as_bytes())
3320    }
3321
3322    /// Returns the same string as a string slice `&str`.
3323    ///
3324    /// This method is redundant when used directly on `&str`, but
3325    /// it helps dereferencing other string-like types to string slices,
3326    /// for example references to `Box<str>` or `Arc<str>`.
3327    #[inline]
3328    #[unstable(feature = "str_as_str", issue = "130366")]
3329    #[ferrocene::prevalidated]
3330    pub const fn as_str(&self) -> &str {
3331        self
3332    }
3333}
3334
3335#[stable(feature = "rust1", since = "1.0.0")]
3336#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
3337const impl AsRef<[u8]> for str {
3338    #[inline]
3339    #[ferrocene::prevalidated]
3340    fn as_ref(&self) -> &[u8] {
3341        self.as_bytes()
3342    }
3343}
3344
3345#[stable(feature = "rust1", since = "1.0.0")]
3346#[rustc_const_unstable(feature = "const_default", issue = "143894")]
3347const impl Default for &str {
3348    /// Creates an empty str
3349    #[inline]
3350    #[ferrocene::prevalidated]
3351    fn default() -> Self {
3352        ""
3353    }
3354}
3355
3356#[stable(feature = "default_mut_str", since = "1.28.0")]
3357#[rustc_const_unstable(feature = "const_default", issue = "143894")]
3358const impl Default for &mut str {
3359    /// Creates an empty mutable str
3360    #[inline]
3361    fn default() -> Self {
3362        // SAFETY: The empty string is valid UTF-8.
3363        unsafe { from_utf8_unchecked_mut(&mut []) }
3364    }
3365}
3366
3367impl_fn_for_zst! {
3368    /// A nameable, cloneable fn type
3369    #[derive(Clone)]
3370    struct LinesMap impl<'a> Fn = |line: &'a str| -> &'a str {
3371        let Some(line) = line.strip_suffix('\n') else { return line };
3372        let Some(line) = line.strip_suffix('\r') else { return line };
3373        line
3374    };
3375
3376    #[derive(Clone)]
3377    struct CharEscapeDebug impl Fn = |c: char| -> char::EscapeDebug {
3378        c.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL)
3379    };
3380
3381    #[derive(Clone)]
3382    struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
3383        c.escape_unicode()
3384    };
3385    #[derive(Clone)]
3386    struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
3387        c.escape_default()
3388    };
3389
3390    #[derive(Clone)]
3391    struct IsWhitespace impl Fn = |c: char| -> bool {
3392        c.is_whitespace()
3393    };
3394
3395    #[derive(Clone)]
3396    pub(crate) struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
3397        byte.is_ascii_whitespace()
3398    };
3399
3400    #[derive(Clone)]
3401    struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
3402        !s.is_empty()
3403    };
3404
3405    #[derive(Clone)]
3406    pub(crate) struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
3407        !s.is_empty()
3408    };
3409
3410    #[derive(Clone)]
3411    struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
3412        // SAFETY: not safe
3413        unsafe { from_utf8_unchecked(bytes) }
3414    };
3415}
3416
3417// This is required to make `impl From<&str> for Box<dyn Error>` and `impl<E> From<E> for Box<dyn Error>` not overlap.
3418#[stable(feature = "error_in_core_neg_impl", since = "1.65.0")]
3419impl !crate::error::Error for &str {}