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