core/str/
mod.rs

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