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