Skip to main content

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