core/str/
mod.rs

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