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=foo".rsplit_once('='), Some(("cfg", "foo")));
2032    /// assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
2033    /// ```
2034    #[stable(feature = "str_split_once", since = "1.52.0")]
2035    #[inline]
2036    #[cfg(not(feature = "ferrocene_certified"))]
2037    pub fn rsplit_once<P: Pattern>(&self, delimiter: P) -> Option<(&'_ str, &'_ str)>
2038    where
2039        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2040    {
2041        let (start, end) = delimiter.into_searcher(self).next_match_back()?;
2042        // SAFETY: `Searcher` is known to return valid indices.
2043        unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
2044    }
2045
2046    /// Returns an iterator over the disjoint matches of a pattern within the
2047    /// given string slice.
2048    ///
2049    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2050    /// function or closure that determines if a character matches.
2051    ///
2052    /// [`char`]: prim@char
2053    /// [pattern]: self::pattern
2054    ///
2055    /// # Iterator behavior
2056    ///
2057    /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
2058    /// allows a reverse search and forward/reverse search yields the same
2059    /// elements. This is true for, e.g., [`char`], but not for `&str`.
2060    ///
2061    /// If the pattern allows a reverse search but its results might differ
2062    /// from a forward search, the [`rmatches`] method can be used.
2063    ///
2064    /// [`rmatches`]: str::rmatches
2065    ///
2066    /// # Examples
2067    ///
2068    /// ```
2069    /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
2070    /// assert_eq!(v, ["abc", "abc", "abc"]);
2071    ///
2072    /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
2073    /// assert_eq!(v, ["1", "2", "3"]);
2074    /// ```
2075    #[stable(feature = "str_matches", since = "1.2.0")]
2076    #[inline]
2077    #[cfg(not(feature = "ferrocene_certified"))]
2078    pub fn matches<P: Pattern>(&self, pat: P) -> Matches<'_, P> {
2079        Matches(MatchesInternal(pat.into_searcher(self)))
2080    }
2081
2082    /// Returns an iterator over the disjoint matches of a pattern within this
2083    /// string slice, yielded in reverse order.
2084    ///
2085    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2086    /// function or closure that determines if a character matches.
2087    ///
2088    /// [`char`]: prim@char
2089    /// [pattern]: self::pattern
2090    ///
2091    /// # Iterator behavior
2092    ///
2093    /// The returned iterator requires that the pattern supports a reverse
2094    /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
2095    /// search yields the same elements.
2096    ///
2097    /// For iterating from the front, the [`matches`] method can be used.
2098    ///
2099    /// [`matches`]: str::matches
2100    ///
2101    /// # Examples
2102    ///
2103    /// ```
2104    /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
2105    /// assert_eq!(v, ["abc", "abc", "abc"]);
2106    ///
2107    /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
2108    /// assert_eq!(v, ["3", "2", "1"]);
2109    /// ```
2110    #[stable(feature = "str_matches", since = "1.2.0")]
2111    #[inline]
2112    #[cfg(not(feature = "ferrocene_certified"))]
2113    pub fn rmatches<P: Pattern>(&self, pat: P) -> RMatches<'_, P>
2114    where
2115        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2116    {
2117        RMatches(self.matches(pat).0)
2118    }
2119
2120    /// Returns an iterator over the disjoint matches of a pattern within this string
2121    /// slice as well as the index that the match starts at.
2122    ///
2123    /// For matches of `pat` within `self` that overlap, only the indices
2124    /// corresponding to the first match are returned.
2125    ///
2126    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2127    /// function or closure that determines if a character matches.
2128    ///
2129    /// [`char`]: prim@char
2130    /// [pattern]: self::pattern
2131    ///
2132    /// # Iterator behavior
2133    ///
2134    /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
2135    /// allows a reverse search and forward/reverse search yields the same
2136    /// elements. This is true for, e.g., [`char`], but not for `&str`.
2137    ///
2138    /// If the pattern allows a reverse search but its results might differ
2139    /// from a forward search, the [`rmatch_indices`] method can be used.
2140    ///
2141    /// [`rmatch_indices`]: str::rmatch_indices
2142    ///
2143    /// # Examples
2144    ///
2145    /// ```
2146    /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
2147    /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
2148    ///
2149    /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
2150    /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
2151    ///
2152    /// let v: Vec<_> = "ababa".match_indices("aba").collect();
2153    /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
2154    /// ```
2155    #[stable(feature = "str_match_indices", since = "1.5.0")]
2156    #[inline]
2157    #[cfg(not(feature = "ferrocene_certified"))]
2158    pub fn match_indices<P: Pattern>(&self, pat: P) -> MatchIndices<'_, P> {
2159        MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
2160    }
2161
2162    /// Returns an iterator over the disjoint matches of a pattern within `self`,
2163    /// yielded in reverse order along with the index of the match.
2164    ///
2165    /// For matches of `pat` within `self` that overlap, only the indices
2166    /// corresponding to the last match are returned.
2167    ///
2168    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2169    /// function or closure that determines if a character matches.
2170    ///
2171    /// [`char`]: prim@char
2172    /// [pattern]: self::pattern
2173    ///
2174    /// # Iterator behavior
2175    ///
2176    /// The returned iterator requires that the pattern supports a reverse
2177    /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
2178    /// search yields the same elements.
2179    ///
2180    /// For iterating from the front, the [`match_indices`] method can be used.
2181    ///
2182    /// [`match_indices`]: str::match_indices
2183    ///
2184    /// # Examples
2185    ///
2186    /// ```
2187    /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
2188    /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
2189    ///
2190    /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
2191    /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
2192    ///
2193    /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
2194    /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
2195    /// ```
2196    #[stable(feature = "str_match_indices", since = "1.5.0")]
2197    #[inline]
2198    #[cfg(not(feature = "ferrocene_certified"))]
2199    pub fn rmatch_indices<P: Pattern>(&self, pat: P) -> RMatchIndices<'_, P>
2200    where
2201        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2202    {
2203        RMatchIndices(self.match_indices(pat).0)
2204    }
2205
2206    /// Returns a string slice with leading and trailing whitespace removed.
2207    ///
2208    /// 'Whitespace' is defined according to the terms of the Unicode Derived
2209    /// Core Property `White_Space`, which includes newlines.
2210    ///
2211    /// # Examples
2212    ///
2213    /// ```
2214    /// let s = "\n Hello\tworld\t\n";
2215    ///
2216    /// assert_eq!("Hello\tworld", s.trim());
2217    /// ```
2218    #[inline]
2219    #[must_use = "this returns the trimmed string as a slice, \
2220                  without modifying the original"]
2221    #[stable(feature = "rust1", since = "1.0.0")]
2222    #[rustc_diagnostic_item = "str_trim"]
2223    #[cfg(not(feature = "ferrocene_certified"))]
2224    pub fn trim(&self) -> &str {
2225        self.trim_matches(char::is_whitespace)
2226    }
2227
2228    /// Returns a string slice with leading whitespace removed.
2229    ///
2230    /// 'Whitespace' is defined according to the terms of the Unicode Derived
2231    /// Core Property `White_Space`, which includes newlines.
2232    ///
2233    /// # Text directionality
2234    ///
2235    /// A string is a sequence of bytes. `start` in this context means the first
2236    /// position of that byte string; for a left-to-right language like English or
2237    /// Russian, this will be left side, and for right-to-left languages like
2238    /// Arabic or Hebrew, this will be the right side.
2239    ///
2240    /// # Examples
2241    ///
2242    /// Basic usage:
2243    ///
2244    /// ```
2245    /// let s = "\n Hello\tworld\t\n";
2246    /// assert_eq!("Hello\tworld\t\n", s.trim_start());
2247    /// ```
2248    ///
2249    /// Directionality:
2250    ///
2251    /// ```
2252    /// let s = "  English  ";
2253    /// assert!(Some('E') == s.trim_start().chars().next());
2254    ///
2255    /// let s = "  עברית  ";
2256    /// assert!(Some('ע') == s.trim_start().chars().next());
2257    /// ```
2258    #[inline]
2259    #[must_use = "this returns the trimmed string as a new slice, \
2260                  without modifying the original"]
2261    #[stable(feature = "trim_direction", since = "1.30.0")]
2262    #[rustc_diagnostic_item = "str_trim_start"]
2263    #[cfg(not(feature = "ferrocene_certified"))]
2264    pub fn trim_start(&self) -> &str {
2265        self.trim_start_matches(char::is_whitespace)
2266    }
2267
2268    /// Returns a string slice with trailing whitespace removed.
2269    ///
2270    /// 'Whitespace' is defined according to the terms of the Unicode Derived
2271    /// Core Property `White_Space`, which includes newlines.
2272    ///
2273    /// # Text directionality
2274    ///
2275    /// A string is a sequence of bytes. `end` in this context means the last
2276    /// position of that byte string; for a left-to-right language like English or
2277    /// Russian, this will be right side, and for right-to-left languages like
2278    /// Arabic or Hebrew, this will be the left side.
2279    ///
2280    /// # Examples
2281    ///
2282    /// Basic usage:
2283    ///
2284    /// ```
2285    /// let s = "\n Hello\tworld\t\n";
2286    /// assert_eq!("\n Hello\tworld", s.trim_end());
2287    /// ```
2288    ///
2289    /// Directionality:
2290    ///
2291    /// ```
2292    /// let s = "  English  ";
2293    /// assert!(Some('h') == s.trim_end().chars().rev().next());
2294    ///
2295    /// let s = "  עברית  ";
2296    /// assert!(Some('ת') == s.trim_end().chars().rev().next());
2297    /// ```
2298    #[inline]
2299    #[must_use = "this returns the trimmed string as a new slice, \
2300                  without modifying the original"]
2301    #[stable(feature = "trim_direction", since = "1.30.0")]
2302    #[rustc_diagnostic_item = "str_trim_end"]
2303    #[cfg(not(feature = "ferrocene_certified"))]
2304    pub fn trim_end(&self) -> &str {
2305        self.trim_end_matches(char::is_whitespace)
2306    }
2307
2308    /// Returns a string slice with leading whitespace removed.
2309    ///
2310    /// 'Whitespace' is defined according to the terms of the Unicode Derived
2311    /// Core Property `White_Space`.
2312    ///
2313    /// # Text directionality
2314    ///
2315    /// A string is a sequence of bytes. 'Left' in this context means the first
2316    /// position of that byte string; for a language like Arabic or Hebrew
2317    /// which are 'right to left' rather than 'left to right', this will be
2318    /// the _right_ side, not the left.
2319    ///
2320    /// # Examples
2321    ///
2322    /// Basic usage:
2323    ///
2324    /// ```
2325    /// let s = " Hello\tworld\t";
2326    ///
2327    /// assert_eq!("Hello\tworld\t", s.trim_left());
2328    /// ```
2329    ///
2330    /// Directionality:
2331    ///
2332    /// ```
2333    /// let s = "  English";
2334    /// assert!(Some('E') == s.trim_left().chars().next());
2335    ///
2336    /// let s = "  עברית";
2337    /// assert!(Some('ע') == s.trim_left().chars().next());
2338    /// ```
2339    #[must_use = "this returns the trimmed string as a new slice, \
2340                  without modifying the original"]
2341    #[inline]
2342    #[stable(feature = "rust1", since = "1.0.0")]
2343    #[deprecated(since = "1.33.0", note = "superseded by `trim_start`", suggestion = "trim_start")]
2344    #[cfg(not(feature = "ferrocene_certified"))]
2345    pub fn trim_left(&self) -> &str {
2346        self.trim_start()
2347    }
2348
2349    /// Returns a string slice with trailing whitespace removed.
2350    ///
2351    /// 'Whitespace' is defined according to the terms of the Unicode Derived
2352    /// Core Property `White_Space`.
2353    ///
2354    /// # Text directionality
2355    ///
2356    /// A string is a sequence of bytes. 'Right' in this context means the last
2357    /// position of that byte string; for a language like Arabic or Hebrew
2358    /// which are 'right to left' rather than 'left to right', this will be
2359    /// the _left_ side, not the right.
2360    ///
2361    /// # Examples
2362    ///
2363    /// Basic usage:
2364    ///
2365    /// ```
2366    /// let s = " Hello\tworld\t";
2367    ///
2368    /// assert_eq!(" Hello\tworld", s.trim_right());
2369    /// ```
2370    ///
2371    /// Directionality:
2372    ///
2373    /// ```
2374    /// let s = "English  ";
2375    /// assert!(Some('h') == s.trim_right().chars().rev().next());
2376    ///
2377    /// let s = "עברית  ";
2378    /// assert!(Some('ת') == s.trim_right().chars().rev().next());
2379    /// ```
2380    #[must_use = "this returns the trimmed string as a new slice, \
2381                  without modifying the original"]
2382    #[inline]
2383    #[stable(feature = "rust1", since = "1.0.0")]
2384    #[deprecated(since = "1.33.0", note = "superseded by `trim_end`", suggestion = "trim_end")]
2385    #[cfg(not(feature = "ferrocene_certified"))]
2386    pub fn trim_right(&self) -> &str {
2387        self.trim_end()
2388    }
2389
2390    /// Returns a string slice with all prefixes and suffixes that match a
2391    /// pattern repeatedly removed.
2392    ///
2393    /// The [pattern] can be a [`char`], a slice of [`char`]s, or a function
2394    /// or closure that determines if a character matches.
2395    ///
2396    /// [`char`]: prim@char
2397    /// [pattern]: self::pattern
2398    ///
2399    /// # Examples
2400    ///
2401    /// Simple patterns:
2402    ///
2403    /// ```
2404    /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
2405    /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
2406    ///
2407    /// let x: &[_] = &['1', '2'];
2408    /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
2409    /// ```
2410    ///
2411    /// A more complex pattern, using a closure:
2412    ///
2413    /// ```
2414    /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
2415    /// ```
2416    #[must_use = "this returns the trimmed string as a new slice, \
2417                  without modifying the original"]
2418    #[stable(feature = "rust1", since = "1.0.0")]
2419    #[cfg(not(feature = "ferrocene_certified"))]
2420    pub fn trim_matches<P: Pattern>(&self, pat: P) -> &str
2421    where
2422        for<'a> P::Searcher<'a>: DoubleEndedSearcher<'a>,
2423    {
2424        let mut i = 0;
2425        let mut j = 0;
2426        let mut matcher = pat.into_searcher(self);
2427        if let Some((a, b)) = matcher.next_reject() {
2428            i = a;
2429            j = b; // Remember earliest known match, correct it below if
2430            // last match is different
2431        }
2432        if let Some((_, b)) = matcher.next_reject_back() {
2433            j = b;
2434        }
2435        // SAFETY: `Searcher` is known to return valid indices.
2436        unsafe { self.get_unchecked(i..j) }
2437    }
2438
2439    /// Returns a string slice with all prefixes that match a pattern
2440    /// repeatedly removed.
2441    ///
2442    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2443    /// function or closure that determines if a character matches.
2444    ///
2445    /// [`char`]: prim@char
2446    /// [pattern]: self::pattern
2447    ///
2448    /// # Text directionality
2449    ///
2450    /// A string is a sequence of bytes. `start` in this context means the first
2451    /// position of that byte string; for a left-to-right language like English or
2452    /// Russian, this will be left side, and for right-to-left languages like
2453    /// Arabic or Hebrew, this will be the right side.
2454    ///
2455    /// # Examples
2456    ///
2457    /// ```
2458    /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
2459    /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
2460    ///
2461    /// let x: &[_] = &['1', '2'];
2462    /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
2463    /// ```
2464    #[must_use = "this returns the trimmed string as a new slice, \
2465                  without modifying the original"]
2466    #[stable(feature = "trim_direction", since = "1.30.0")]
2467    #[cfg(not(feature = "ferrocene_certified"))]
2468    pub fn trim_start_matches<P: Pattern>(&self, pat: P) -> &str {
2469        let mut i = self.len();
2470        let mut matcher = pat.into_searcher(self);
2471        if let Some((a, _)) = matcher.next_reject() {
2472            i = a;
2473        }
2474        // SAFETY: `Searcher` is known to return valid indices.
2475        unsafe { self.get_unchecked(i..self.len()) }
2476    }
2477
2478    /// Returns a string slice with the prefix removed.
2479    ///
2480    /// If the string starts with the pattern `prefix`, returns the substring after the prefix,
2481    /// wrapped in `Some`. Unlike [`trim_start_matches`], this method removes the prefix exactly once.
2482    ///
2483    /// If the string does not start with `prefix`, returns `None`.
2484    ///
2485    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2486    /// function or closure that determines if a character matches.
2487    ///
2488    /// [`char`]: prim@char
2489    /// [pattern]: self::pattern
2490    /// [`trim_start_matches`]: Self::trim_start_matches
2491    ///
2492    /// # Examples
2493    ///
2494    /// ```
2495    /// assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
2496    /// assert_eq!("foo:bar".strip_prefix("bar"), None);
2497    /// assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
2498    /// ```
2499    #[must_use = "this returns the remaining substring as a new slice, \
2500                  without modifying the original"]
2501    #[stable(feature = "str_strip", since = "1.45.0")]
2502    #[cfg(not(feature = "ferrocene_certified"))]
2503    pub fn strip_prefix<P: Pattern>(&self, prefix: P) -> Option<&str> {
2504        prefix.strip_prefix_of(self)
2505    }
2506
2507    /// Returns a string slice with the suffix removed.
2508    ///
2509    /// If the string ends with the pattern `suffix`, returns the substring before the suffix,
2510    /// wrapped in `Some`.  Unlike [`trim_end_matches`], this method removes the suffix exactly once.
2511    ///
2512    /// If the string does not end with `suffix`, returns `None`.
2513    ///
2514    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2515    /// function or closure that determines if a character matches.
2516    ///
2517    /// [`char`]: prim@char
2518    /// [pattern]: self::pattern
2519    /// [`trim_end_matches`]: Self::trim_end_matches
2520    ///
2521    /// # Examples
2522    ///
2523    /// ```
2524    /// assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
2525    /// assert_eq!("bar:foo".strip_suffix("bar"), None);
2526    /// assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
2527    /// ```
2528    #[must_use = "this returns the remaining substring as a new slice, \
2529                  without modifying the original"]
2530    #[stable(feature = "str_strip", since = "1.45.0")]
2531    #[cfg(not(feature = "ferrocene_certified"))]
2532    pub fn strip_suffix<P: Pattern>(&self, suffix: P) -> Option<&str>
2533    where
2534        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2535    {
2536        suffix.strip_suffix_of(self)
2537    }
2538
2539    /// Returns a string slice with the prefix and suffix removed.
2540    ///
2541    /// If the string starts with the pattern `prefix` and ends with the pattern `suffix`, returns
2542    /// the substring after the prefix and before the suffix, wrapped in `Some`.
2543    /// Unlike [`trim_start_matches`] and [`trim_end_matches`], this method removes both the prefix
2544    /// and suffix exactly once.
2545    ///
2546    /// If the string does not start with `prefix` or does not end with `suffix`, returns `None`.
2547    ///
2548    /// Each [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2549    /// function or closure that determines if a character matches.
2550    ///
2551    /// [`char`]: prim@char
2552    /// [pattern]: self::pattern
2553    /// [`trim_start_matches`]: Self::trim_start_matches
2554    /// [`trim_end_matches`]: Self::trim_end_matches
2555    ///
2556    /// # Examples
2557    ///
2558    /// ```
2559    /// #![feature(strip_circumfix)]
2560    ///
2561    /// assert_eq!("bar:hello:foo".strip_circumfix("bar:", ":foo"), Some("hello"));
2562    /// assert_eq!("bar:foo".strip_circumfix("foo", "foo"), None);
2563    /// assert_eq!("foo:bar;".strip_circumfix("foo:", ';'), Some("bar"));
2564    /// ```
2565    #[must_use = "this returns the remaining substring as a new slice, \
2566                  without modifying the original"]
2567    #[unstable(feature = "strip_circumfix", issue = "147946")]
2568    #[cfg(not(feature = "ferrocene_certified"))]
2569    pub fn strip_circumfix<P: Pattern, S: Pattern>(&self, prefix: P, suffix: S) -> Option<&str>
2570    where
2571        for<'a> S::Searcher<'a>: ReverseSearcher<'a>,
2572    {
2573        self.strip_prefix(prefix)?.strip_suffix(suffix)
2574    }
2575
2576    /// Returns a string slice with the optional prefix removed.
2577    ///
2578    /// If the string starts with the pattern `prefix`, returns the substring after the prefix.
2579    /// Unlike [`strip_prefix`], this method always returns `&str` for easy method chaining,
2580    /// instead of returning [`Option<&str>`].
2581    ///
2582    /// If the string does not start with `prefix`, returns the original string unchanged.
2583    ///
2584    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2585    /// function or closure that determines if a character matches.
2586    ///
2587    /// [`char`]: prim@char
2588    /// [pattern]: self::pattern
2589    /// [`strip_prefix`]: Self::strip_prefix
2590    ///
2591    /// # Examples
2592    ///
2593    /// ```
2594    /// #![feature(trim_prefix_suffix)]
2595    ///
2596    /// // Prefix present - removes it
2597    /// assert_eq!("foo:bar".trim_prefix("foo:"), "bar");
2598    /// assert_eq!("foofoo".trim_prefix("foo"), "foo");
2599    ///
2600    /// // Prefix absent - returns original string
2601    /// assert_eq!("foo:bar".trim_prefix("bar"), "foo:bar");
2602    ///
2603    /// // Method chaining example
2604    /// assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/");
2605    /// ```
2606    #[must_use = "this returns the remaining substring as a new slice, \
2607                  without modifying the original"]
2608    #[unstable(feature = "trim_prefix_suffix", issue = "142312")]
2609    #[cfg(not(feature = "ferrocene_certified"))]
2610    pub fn trim_prefix<P: Pattern>(&self, prefix: P) -> &str {
2611        prefix.strip_prefix_of(self).unwrap_or(self)
2612    }
2613
2614    /// Returns a string slice with the optional suffix removed.
2615    ///
2616    /// If the string ends with the pattern `suffix`, returns the substring before the suffix.
2617    /// Unlike [`strip_suffix`], this method always returns `&str` for easy method chaining,
2618    /// instead of returning [`Option<&str>`].
2619    ///
2620    /// If the string does not end with `suffix`, returns the original string unchanged.
2621    ///
2622    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2623    /// function or closure that determines if a character matches.
2624    ///
2625    /// [`char`]: prim@char
2626    /// [pattern]: self::pattern
2627    /// [`strip_suffix`]: Self::strip_suffix
2628    ///
2629    /// # Examples
2630    ///
2631    /// ```
2632    /// #![feature(trim_prefix_suffix)]
2633    ///
2634    /// // Suffix present - removes it
2635    /// assert_eq!("bar:foo".trim_suffix(":foo"), "bar");
2636    /// assert_eq!("foofoo".trim_suffix("foo"), "foo");
2637    ///
2638    /// // Suffix absent - returns original string
2639    /// assert_eq!("bar:foo".trim_suffix("bar"), "bar:foo");
2640    ///
2641    /// // Method chaining example
2642    /// assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/");
2643    /// ```
2644    #[must_use = "this returns the remaining substring as a new slice, \
2645                  without modifying the original"]
2646    #[unstable(feature = "trim_prefix_suffix", issue = "142312")]
2647    #[cfg(not(feature = "ferrocene_certified"))]
2648    pub fn trim_suffix<P: Pattern>(&self, suffix: P) -> &str
2649    where
2650        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2651    {
2652        suffix.strip_suffix_of(self).unwrap_or(self)
2653    }
2654
2655    /// Returns a string slice with all suffixes that match a pattern
2656    /// repeatedly removed.
2657    ///
2658    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2659    /// function or closure that determines if a character matches.
2660    ///
2661    /// [`char`]: prim@char
2662    /// [pattern]: self::pattern
2663    ///
2664    /// # Text directionality
2665    ///
2666    /// A string is a sequence of bytes. `end` in this context means the last
2667    /// position of that byte string; for a left-to-right language like English or
2668    /// Russian, this will be right side, and for right-to-left languages like
2669    /// Arabic or Hebrew, this will be the left side.
2670    ///
2671    /// # Examples
2672    ///
2673    /// Simple patterns:
2674    ///
2675    /// ```
2676    /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
2677    /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
2678    ///
2679    /// let x: &[_] = &['1', '2'];
2680    /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
2681    /// ```
2682    ///
2683    /// A more complex pattern, using a closure:
2684    ///
2685    /// ```
2686    /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
2687    /// ```
2688    #[must_use = "this returns the trimmed string as a new slice, \
2689                  without modifying the original"]
2690    #[stable(feature = "trim_direction", since = "1.30.0")]
2691    #[cfg(not(feature = "ferrocene_certified"))]
2692    pub fn trim_end_matches<P: Pattern>(&self, pat: P) -> &str
2693    where
2694        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2695    {
2696        let mut j = 0;
2697        let mut matcher = pat.into_searcher(self);
2698        if let Some((_, b)) = matcher.next_reject_back() {
2699            j = b;
2700        }
2701        // SAFETY: `Searcher` is known to return valid indices.
2702        unsafe { self.get_unchecked(0..j) }
2703    }
2704
2705    /// Returns a string slice with all prefixes that match a pattern
2706    /// repeatedly removed.
2707    ///
2708    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2709    /// function or closure that determines if a character matches.
2710    ///
2711    /// [`char`]: prim@char
2712    /// [pattern]: self::pattern
2713    ///
2714    /// # Text directionality
2715    ///
2716    /// A string is a sequence of bytes. 'Left' in this context means the first
2717    /// position of that byte string; for a language like Arabic or Hebrew
2718    /// which are 'right to left' rather than 'left to right', this will be
2719    /// the _right_ side, not the left.
2720    ///
2721    /// # Examples
2722    ///
2723    /// ```
2724    /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
2725    /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
2726    ///
2727    /// let x: &[_] = &['1', '2'];
2728    /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
2729    /// ```
2730    #[stable(feature = "rust1", since = "1.0.0")]
2731    #[deprecated(
2732        since = "1.33.0",
2733        note = "superseded by `trim_start_matches`",
2734        suggestion = "trim_start_matches"
2735    )]
2736    #[cfg(not(feature = "ferrocene_certified"))]
2737    pub fn trim_left_matches<P: Pattern>(&self, pat: P) -> &str {
2738        self.trim_start_matches(pat)
2739    }
2740
2741    /// Returns a string slice with all suffixes that match a pattern
2742    /// repeatedly removed.
2743    ///
2744    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2745    /// function or closure that determines if a character matches.
2746    ///
2747    /// [`char`]: prim@char
2748    /// [pattern]: self::pattern
2749    ///
2750    /// # Text directionality
2751    ///
2752    /// A string is a sequence of bytes. 'Right' in this context means the last
2753    /// position of that byte string; for a language like Arabic or Hebrew
2754    /// which are 'right to left' rather than 'left to right', this will be
2755    /// the _left_ side, not the right.
2756    ///
2757    /// # Examples
2758    ///
2759    /// Simple patterns:
2760    ///
2761    /// ```
2762    /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
2763    /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
2764    ///
2765    /// let x: &[_] = &['1', '2'];
2766    /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
2767    /// ```
2768    ///
2769    /// A more complex pattern, using a closure:
2770    ///
2771    /// ```
2772    /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
2773    /// ```
2774    #[stable(feature = "rust1", since = "1.0.0")]
2775    #[deprecated(
2776        since = "1.33.0",
2777        note = "superseded by `trim_end_matches`",
2778        suggestion = "trim_end_matches"
2779    )]
2780    #[cfg(not(feature = "ferrocene_certified"))]
2781    pub fn trim_right_matches<P: Pattern>(&self, pat: P) -> &str
2782    where
2783        for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2784    {
2785        self.trim_end_matches(pat)
2786    }
2787
2788    /// Parses this string slice into another type.
2789    ///
2790    /// Because `parse` is so general, it can cause problems with type
2791    /// inference. As such, `parse` is one of the few times you'll see
2792    /// the syntax affectionately known as the 'turbofish': `::<>`. This
2793    /// helps the inference algorithm understand specifically which type
2794    /// you're trying to parse into.
2795    ///
2796    /// `parse` can parse into any type that implements the [`FromStr`] trait.
2797    ///
2798    /// # Errors
2799    ///
2800    /// Will return [`Err`] if it's not possible to parse this string slice into
2801    /// the desired type.
2802    ///
2803    /// [`Err`]: FromStr::Err
2804    ///
2805    /// # Examples
2806    ///
2807    /// Basic usage:
2808    ///
2809    /// ```
2810    /// let four: u32 = "4".parse().unwrap();
2811    ///
2812    /// assert_eq!(4, four);
2813    /// ```
2814    ///
2815    /// Using the 'turbofish' instead of annotating `four`:
2816    ///
2817    /// ```
2818    /// let four = "4".parse::<u32>();
2819    ///
2820    /// assert_eq!(Ok(4), four);
2821    /// ```
2822    ///
2823    /// Failing to parse:
2824    ///
2825    /// ```
2826    /// let nope = "j".parse::<u32>();
2827    ///
2828    /// assert!(nope.is_err());
2829    /// ```
2830    #[inline]
2831    #[stable(feature = "rust1", since = "1.0.0")]
2832    pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
2833        FromStr::from_str(self)
2834    }
2835
2836    /// Checks if all characters in this string are within the ASCII range.
2837    ///
2838    /// An empty string returns `true`.
2839    ///
2840    /// # Examples
2841    ///
2842    /// ```
2843    /// let ascii = "hello!\n";
2844    /// let non_ascii = "Grüße, Jürgen ❤";
2845    ///
2846    /// assert!(ascii.is_ascii());
2847    /// assert!(!non_ascii.is_ascii());
2848    /// ```
2849    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2850    #[rustc_const_stable(feature = "const_slice_is_ascii", since = "1.74.0")]
2851    #[must_use]
2852    #[inline]
2853    #[cfg(not(feature = "ferrocene_certified"))]
2854    pub const fn is_ascii(&self) -> bool {
2855        // We can treat each byte as character here: all multibyte characters
2856        // start with a byte that is not in the ASCII range, so we will stop
2857        // there already.
2858        self.as_bytes().is_ascii()
2859    }
2860
2861    /// If this string slice [`is_ascii`](Self::is_ascii), returns it as a slice
2862    /// of [ASCII characters](`ascii::Char`), otherwise returns `None`.
2863    #[unstable(feature = "ascii_char", issue = "110998")]
2864    #[must_use]
2865    #[inline]
2866    #[cfg(not(feature = "ferrocene_certified"))]
2867    pub const fn as_ascii(&self) -> Option<&[ascii::Char]> {
2868        // Like in `is_ascii`, we can work on the bytes directly.
2869        self.as_bytes().as_ascii()
2870    }
2871
2872    /// Converts this string slice into a slice of [ASCII characters](ascii::Char),
2873    /// without checking whether they are valid.
2874    ///
2875    /// # Safety
2876    ///
2877    /// Every character in this string must be ASCII, or else this is UB.
2878    #[unstable(feature = "ascii_char", issue = "110998")]
2879    #[must_use]
2880    #[inline]
2881    #[cfg(not(feature = "ferrocene_certified"))]
2882    pub const unsafe fn as_ascii_unchecked(&self) -> &[ascii::Char] {
2883        assert_unsafe_precondition!(
2884            check_library_ub,
2885            "as_ascii_unchecked requires that the string is valid ASCII",
2886            (it: &str = self) => it.is_ascii()
2887        );
2888
2889        // SAFETY: the caller promised that every byte of this string slice
2890        // is ASCII.
2891        unsafe { self.as_bytes().as_ascii_unchecked() }
2892    }
2893
2894    /// Checks that two strings are an ASCII case-insensitive match.
2895    ///
2896    /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2897    /// but without allocating and copying temporaries.
2898    ///
2899    /// # Examples
2900    ///
2901    /// ```
2902    /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2903    /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2904    /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2905    /// ```
2906    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2907    #[rustc_const_stable(feature = "const_eq_ignore_ascii_case", since = "1.89.0")]
2908    #[must_use]
2909    #[inline]
2910    #[cfg(not(feature = "ferrocene_certified"))]
2911    pub const fn eq_ignore_ascii_case(&self, other: &str) -> bool {
2912        self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
2913    }
2914
2915    /// Converts this string to its ASCII upper case equivalent in-place.
2916    ///
2917    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2918    /// but non-ASCII letters are unchanged.
2919    ///
2920    /// To return a new uppercased value without modifying the existing one, use
2921    /// [`to_ascii_uppercase()`].
2922    ///
2923    /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
2924    ///
2925    /// # Examples
2926    ///
2927    /// ```
2928    /// let mut s = String::from("Grüße, Jürgen ❤");
2929    ///
2930    /// s.make_ascii_uppercase();
2931    ///
2932    /// assert_eq!("GRüßE, JüRGEN ❤", s);
2933    /// ```
2934    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2935    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
2936    #[inline]
2937    #[cfg(not(feature = "ferrocene_certified"))]
2938    pub const fn make_ascii_uppercase(&mut self) {
2939        // SAFETY: changing ASCII letters only does not invalidate UTF-8.
2940        let me = unsafe { self.as_bytes_mut() };
2941        me.make_ascii_uppercase()
2942    }
2943
2944    /// Converts this string to its ASCII lower case equivalent in-place.
2945    ///
2946    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2947    /// but non-ASCII letters are unchanged.
2948    ///
2949    /// To return a new lowercased value without modifying the existing one, use
2950    /// [`to_ascii_lowercase()`].
2951    ///
2952    /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
2953    ///
2954    /// # Examples
2955    ///
2956    /// ```
2957    /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
2958    ///
2959    /// s.make_ascii_lowercase();
2960    ///
2961    /// assert_eq!("grÜße, jÜrgen ❤", s);
2962    /// ```
2963    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2964    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
2965    #[inline]
2966    #[cfg(not(feature = "ferrocene_certified"))]
2967    pub const fn make_ascii_lowercase(&mut self) {
2968        // SAFETY: changing ASCII letters only does not invalidate UTF-8.
2969        let me = unsafe { self.as_bytes_mut() };
2970        me.make_ascii_lowercase()
2971    }
2972
2973    /// Returns a string slice with leading ASCII whitespace removed.
2974    ///
2975    /// 'Whitespace' refers to the definition used by
2976    /// [`u8::is_ascii_whitespace`].
2977    ///
2978    /// [`u8::is_ascii_whitespace`]: u8::is_ascii_whitespace
2979    ///
2980    /// # Examples
2981    ///
2982    /// ```
2983    /// assert_eq!(" \t \u{3000}hello world\n".trim_ascii_start(), "\u{3000}hello world\n");
2984    /// assert_eq!("  ".trim_ascii_start(), "");
2985    /// assert_eq!("".trim_ascii_start(), "");
2986    /// ```
2987    #[must_use = "this returns the trimmed string as a new slice, \
2988                  without modifying the original"]
2989    #[stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
2990    #[rustc_const_stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
2991    #[inline]
2992    #[cfg(not(feature = "ferrocene_certified"))]
2993    pub const fn trim_ascii_start(&self) -> &str {
2994        // SAFETY: Removing ASCII characters from a `&str` does not invalidate
2995        // UTF-8.
2996        unsafe { core::str::from_utf8_unchecked(self.as_bytes().trim_ascii_start()) }
2997    }
2998
2999    /// Returns a string slice with trailing ASCII whitespace removed.
3000    ///
3001    /// 'Whitespace' refers to the definition used by
3002    /// [`u8::is_ascii_whitespace`].
3003    ///
3004    /// [`u8::is_ascii_whitespace`]: u8::is_ascii_whitespace
3005    ///
3006    /// # Examples
3007    ///
3008    /// ```
3009    /// assert_eq!("\r hello world\u{3000}\n ".trim_ascii_end(), "\r hello world\u{3000}");
3010    /// assert_eq!("  ".trim_ascii_end(), "");
3011    /// assert_eq!("".trim_ascii_end(), "");
3012    /// ```
3013    #[must_use = "this returns the trimmed string as a new slice, \
3014                  without modifying the original"]
3015    #[stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
3016    #[rustc_const_stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
3017    #[inline]
3018    #[cfg(not(feature = "ferrocene_certified"))]
3019    pub const fn trim_ascii_end(&self) -> &str {
3020        // SAFETY: Removing ASCII characters from a `&str` does not invalidate
3021        // UTF-8.
3022        unsafe { core::str::from_utf8_unchecked(self.as_bytes().trim_ascii_end()) }
3023    }
3024
3025    /// Returns a string slice with leading and trailing ASCII whitespace
3026    /// removed.
3027    ///
3028    /// 'Whitespace' refers to the definition used by
3029    /// [`u8::is_ascii_whitespace`].
3030    ///
3031    /// [`u8::is_ascii_whitespace`]: u8::is_ascii_whitespace
3032    ///
3033    /// # Examples
3034    ///
3035    /// ```
3036    /// assert_eq!("\r hello world\n ".trim_ascii(), "hello world");
3037    /// assert_eq!("  ".trim_ascii(), "");
3038    /// assert_eq!("".trim_ascii(), "");
3039    /// ```
3040    #[must_use = "this returns the trimmed string as a new slice, \
3041                  without modifying the original"]
3042    #[stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
3043    #[rustc_const_stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
3044    #[inline]
3045    #[cfg(not(feature = "ferrocene_certified"))]
3046    pub const fn trim_ascii(&self) -> &str {
3047        // SAFETY: Removing ASCII characters from a `&str` does not invalidate
3048        // UTF-8.
3049        unsafe { core::str::from_utf8_unchecked(self.as_bytes().trim_ascii()) }
3050    }
3051
3052    /// Returns an iterator that escapes each char in `self` with [`char::escape_debug`].
3053    ///
3054    /// Note: only extended grapheme codepoints that begin the string will be
3055    /// escaped.
3056    ///
3057    /// # Examples
3058    ///
3059    /// As an iterator:
3060    ///
3061    /// ```
3062    /// for c in "❤\n!".escape_debug() {
3063    ///     print!("{c}");
3064    /// }
3065    /// println!();
3066    /// ```
3067    ///
3068    /// Using `println!` directly:
3069    ///
3070    /// ```
3071    /// println!("{}", "❤\n!".escape_debug());
3072    /// ```
3073    ///
3074    ///
3075    /// Both are equivalent to:
3076    ///
3077    /// ```
3078    /// println!("❤\\n!");
3079    /// ```
3080    ///
3081    /// Using `to_string`:
3082    ///
3083    /// ```
3084    /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
3085    /// ```
3086    #[must_use = "this returns the escaped string as an iterator, \
3087                  without modifying the original"]
3088    #[stable(feature = "str_escape", since = "1.34.0")]
3089    #[cfg(not(feature = "ferrocene_certified"))]
3090    pub fn escape_debug(&self) -> EscapeDebug<'_> {
3091        let mut chars = self.chars();
3092        EscapeDebug {
3093            inner: chars
3094                .next()
3095                .map(|first| first.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL))
3096                .into_iter()
3097                .flatten()
3098                .chain(chars.flat_map(CharEscapeDebugContinue)),
3099        }
3100    }
3101
3102    /// Returns an iterator that escapes each char in `self` with [`char::escape_default`].
3103    ///
3104    /// # Examples
3105    ///
3106    /// As an iterator:
3107    ///
3108    /// ```
3109    /// for c in "❤\n!".escape_default() {
3110    ///     print!("{c}");
3111    /// }
3112    /// println!();
3113    /// ```
3114    ///
3115    /// Using `println!` directly:
3116    ///
3117    /// ```
3118    /// println!("{}", "❤\n!".escape_default());
3119    /// ```
3120    ///
3121    ///
3122    /// Both are equivalent to:
3123    ///
3124    /// ```
3125    /// println!("\\u{{2764}}\\n!");
3126    /// ```
3127    ///
3128    /// Using `to_string`:
3129    ///
3130    /// ```
3131    /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
3132    /// ```
3133    #[must_use = "this returns the escaped string as an iterator, \
3134                  without modifying the original"]
3135    #[stable(feature = "str_escape", since = "1.34.0")]
3136    #[cfg(not(feature = "ferrocene_certified"))]
3137    pub fn escape_default(&self) -> EscapeDefault<'_> {
3138        EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
3139    }
3140
3141    /// Returns an iterator that escapes each char in `self` with [`char::escape_unicode`].
3142    ///
3143    /// # Examples
3144    ///
3145    /// As an iterator:
3146    ///
3147    /// ```
3148    /// for c in "❤\n!".escape_unicode() {
3149    ///     print!("{c}");
3150    /// }
3151    /// println!();
3152    /// ```
3153    ///
3154    /// Using `println!` directly:
3155    ///
3156    /// ```
3157    /// println!("{}", "❤\n!".escape_unicode());
3158    /// ```
3159    ///
3160    ///
3161    /// Both are equivalent to:
3162    ///
3163    /// ```
3164    /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
3165    /// ```
3166    ///
3167    /// Using `to_string`:
3168    ///
3169    /// ```
3170    /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
3171    /// ```
3172    #[must_use = "this returns the escaped string as an iterator, \
3173                  without modifying the original"]
3174    #[stable(feature = "str_escape", since = "1.34.0")]
3175    #[cfg(not(feature = "ferrocene_certified"))]
3176    pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
3177        EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
3178    }
3179
3180    /// Returns the range that a substring points to.
3181    ///
3182    /// Returns `None` if `substr` does not point within `self`.
3183    ///
3184    /// Unlike [`str::find`], **this does not search through the string**.
3185    /// Instead, it uses pointer arithmetic to find where in the string
3186    /// `substr` is derived from.
3187    ///
3188    /// This is useful for extending [`str::split`] and similar methods.
3189    ///
3190    /// Note that this method may return false positives (typically either
3191    /// `Some(0..0)` or `Some(self.len()..self.len())`) if `substr` is a
3192    /// zero-length `str` that points at the beginning or end of another,
3193    /// independent, `str`.
3194    ///
3195    /// # Examples
3196    /// ```
3197    /// #![feature(substr_range)]
3198    ///
3199    /// let data = "a, b, b, a";
3200    /// let mut iter = data.split(", ").map(|s| data.substr_range(s).unwrap());
3201    ///
3202    /// assert_eq!(iter.next(), Some(0..1));
3203    /// assert_eq!(iter.next(), Some(3..4));
3204    /// assert_eq!(iter.next(), Some(6..7));
3205    /// assert_eq!(iter.next(), Some(9..10));
3206    /// ```
3207    #[must_use]
3208    #[unstable(feature = "substr_range", issue = "126769")]
3209    #[cfg(not(feature = "ferrocene_certified"))]
3210    pub fn substr_range(&self, substr: &str) -> Option<Range<usize>> {
3211        self.as_bytes().subslice_range(substr.as_bytes())
3212    }
3213
3214    /// Returns the same string as a string slice `&str`.
3215    ///
3216    /// This method is redundant when used directly on `&str`, but
3217    /// it helps dereferencing other string-like types to string slices,
3218    /// for example references to `Box<str>` or `Arc<str>`.
3219    #[inline]
3220    #[unstable(feature = "str_as_str", issue = "130366")]
3221    pub const fn as_str(&self) -> &str {
3222        self
3223    }
3224}
3225
3226#[stable(feature = "rust1", since = "1.0.0")]
3227#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
3228impl const AsRef<[u8]> for str {
3229    #[inline]
3230    fn as_ref(&self) -> &[u8] {
3231        self.as_bytes()
3232    }
3233}
3234
3235#[stable(feature = "rust1", since = "1.0.0")]
3236#[rustc_const_unstable(feature = "const_default", issue = "143894")]
3237impl const Default for &str {
3238    /// Creates an empty str
3239    #[inline]
3240    fn default() -> Self {
3241        ""
3242    }
3243}
3244
3245#[stable(feature = "default_mut_str", since = "1.28.0")]
3246#[rustc_const_unstable(feature = "const_default", issue = "143894")]
3247#[cfg(not(feature = "ferrocene_certified"))]
3248impl const Default for &mut str {
3249    /// Creates an empty mutable str
3250    #[inline]
3251    fn default() -> Self {
3252        // SAFETY: The empty string is valid UTF-8.
3253        unsafe { from_utf8_unchecked_mut(&mut []) }
3254    }
3255}
3256
3257#[cfg(not(feature = "ferrocene_certified"))]
3258impl_fn_for_zst! {
3259    /// A nameable, cloneable fn type
3260    #[derive(Clone)]
3261    struct LinesMap impl<'a> Fn = |line: &'a str| -> &'a str {
3262        let Some(line) = line.strip_suffix('\n') else { return line };
3263        let Some(line) = line.strip_suffix('\r') else { return line };
3264        line
3265    };
3266
3267    #[derive(Clone)]
3268    struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
3269        c.escape_debug_ext(EscapeDebugExtArgs {
3270            escape_grapheme_extended: false,
3271            escape_single_quote: true,
3272            escape_double_quote: true
3273        })
3274    };
3275
3276    #[derive(Clone)]
3277    struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
3278        c.escape_unicode()
3279    };
3280    #[derive(Clone)]
3281    struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
3282        c.escape_default()
3283    };
3284
3285    #[derive(Clone)]
3286    struct IsWhitespace impl Fn = |c: char| -> bool {
3287        c.is_whitespace()
3288    };
3289
3290    #[derive(Clone)]
3291    struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
3292        byte.is_ascii_whitespace()
3293    };
3294
3295    #[derive(Clone)]
3296    struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
3297        !s.is_empty()
3298    };
3299
3300    #[derive(Clone)]
3301    struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
3302        !s.is_empty()
3303    };
3304
3305    #[derive(Clone)]
3306    struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
3307        // SAFETY: not safe
3308        unsafe { from_utf8_unchecked(bytes) }
3309    };
3310}
3311
3312// This is required to make `impl From<&str> for Box<dyn Error>` and `impl<E> From<E> for Box<dyn Error>` not overlap.
3313#[stable(feature = "error_in_core_neg_impl", since = "1.65.0")]
3314#[cfg(not(feature = "ferrocene_certified"))]
3315impl !crate::error::Error for &str {}