]> git.lizzy.rs Git - rust.git/blob - library/core/src/str/mod.rs
Auto merge of #79780 - camelid:use-summary_opts, r=GuillaumeGomez
[rust.git] / library / core / src / 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
9 mod converts;
10 mod error;
11 mod iter;
12 mod traits;
13 mod validations;
14
15 use self::pattern::Pattern;
16 use self::pattern::{DoubleEndedSearcher, ReverseSearcher, Searcher};
17
18 use crate::char;
19 use crate::mem;
20 use crate::slice::{self, SliceIndex};
21
22 pub mod pattern;
23
24 #[unstable(feature = "str_internals", issue = "none")]
25 #[allow(missing_docs)]
26 pub mod lossy;
27
28 #[stable(feature = "rust1", since = "1.0.0")]
29 pub use converts::{from_utf8, from_utf8_unchecked};
30
31 #[stable(feature = "str_mut_extras", since = "1.20.0")]
32 pub use converts::{from_utf8_mut, from_utf8_unchecked_mut};
33
34 #[stable(feature = "rust1", since = "1.0.0")]
35 pub use error::{ParseBoolError, Utf8Error};
36
37 #[stable(feature = "rust1", since = "1.0.0")]
38 pub use traits::FromStr;
39
40 #[stable(feature = "rust1", since = "1.0.0")]
41 pub use iter::{Bytes, CharIndices, Chars, Lines, SplitWhitespace};
42
43 #[stable(feature = "rust1", since = "1.0.0")]
44 #[allow(deprecated)]
45 pub use iter::LinesAny;
46
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub use iter::{RSplit, RSplitTerminator, Split, SplitTerminator};
49
50 #[stable(feature = "rust1", since = "1.0.0")]
51 pub use iter::{RSplitN, SplitN};
52
53 #[stable(feature = "str_matches", since = "1.2.0")]
54 pub use iter::{Matches, RMatches};
55
56 #[stable(feature = "str_match_indices", since = "1.5.0")]
57 pub use iter::{MatchIndices, RMatchIndices};
58
59 #[stable(feature = "encode_utf16", since = "1.8.0")]
60 pub use iter::EncodeUtf16;
61
62 #[stable(feature = "str_escape", since = "1.34.0")]
63 pub use iter::{EscapeDebug, EscapeDefault, EscapeUnicode};
64
65 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
66 pub use iter::SplitAsciiWhitespace;
67
68 #[unstable(feature = "split_inclusive", issue = "72360")]
69 use iter::SplitInclusive;
70
71 #[unstable(feature = "str_internals", issue = "none")]
72 pub use validations::next_code_point;
73
74 use iter::MatchIndicesInternal;
75 use iter::SplitInternal;
76 use iter::{MatchesInternal, SplitNInternal};
77
78 use validations::truncate_to_char_boundary;
79
80 #[inline(never)]
81 #[cold]
82 #[track_caller]
83 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
84     const MAX_DISPLAY_LENGTH: usize = 256;
85     let (truncated, s_trunc) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
86     let ellipsis = if truncated { "[...]" } else { "" };
87
88     // 1. out of bounds
89     if begin > s.len() || end > s.len() {
90         let oob_index = if begin > s.len() { begin } else { end };
91         panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
92     }
93
94     // 2. begin <= end
95     assert!(
96         begin <= end,
97         "begin <= end ({} <= {}) when slicing `{}`{}",
98         begin,
99         end,
100         s_trunc,
101         ellipsis
102     );
103
104     // 3. character boundary
105     let index = if !s.is_char_boundary(begin) { begin } else { end };
106     // find the character
107     let mut char_start = index;
108     while !s.is_char_boundary(char_start) {
109         char_start -= 1;
110     }
111     // `char_start` must be less than len and a char boundary
112     let ch = s[char_start..].chars().next().unwrap();
113     let char_range = char_start..char_start + ch.len_utf8();
114     panic!(
115         "byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
116         index, ch, char_range, s_trunc, ellipsis
117     );
118 }
119
120 #[lang = "str"]
121 #[cfg(not(test))]
122 impl str {
123     /// Returns the length of `self`.
124     ///
125     /// This length is in bytes, not [`char`]s or graphemes. In other words,
126     /// it may not be what a human considers the length of the string.
127     ///
128     /// [`char`]: prim@char
129     ///
130     /// # Examples
131     ///
132     /// Basic usage:
133     ///
134     /// ```
135     /// let len = "foo".len();
136     /// assert_eq!(3, len);
137     ///
138     /// assert_eq!("ƒoo".len(), 4); // fancy f!
139     /// assert_eq!("ƒoo".chars().count(), 3);
140     /// ```
141     #[stable(feature = "rust1", since = "1.0.0")]
142     #[rustc_const_stable(feature = "const_str_len", since = "1.32.0")]
143     #[inline]
144     pub const fn len(&self) -> usize {
145         self.as_bytes().len()
146     }
147
148     /// Returns `true` if `self` has a length of zero bytes.
149     ///
150     /// # Examples
151     ///
152     /// Basic usage:
153     ///
154     /// ```
155     /// let s = "";
156     /// assert!(s.is_empty());
157     ///
158     /// let s = "not empty";
159     /// assert!(!s.is_empty());
160     /// ```
161     #[inline]
162     #[stable(feature = "rust1", since = "1.0.0")]
163     #[rustc_const_stable(feature = "const_str_is_empty", since = "1.32.0")]
164     pub const fn is_empty(&self) -> bool {
165         self.len() == 0
166     }
167
168     /// Checks that `index`-th byte is the first byte in a UTF-8 code point
169     /// sequence or the end of the string.
170     ///
171     /// The start and end of the string (when `index == self.len()`) are
172     /// considered to be boundaries.
173     ///
174     /// Returns `false` if `index` is greater than `self.len()`.
175     ///
176     /// # Examples
177     ///
178     /// ```
179     /// let s = "Löwe 老虎 Léopard";
180     /// assert!(s.is_char_boundary(0));
181     /// // start of `老`
182     /// assert!(s.is_char_boundary(6));
183     /// assert!(s.is_char_boundary(s.len()));
184     ///
185     /// // second byte of `ö`
186     /// assert!(!s.is_char_boundary(2));
187     ///
188     /// // third byte of `老`
189     /// assert!(!s.is_char_boundary(8));
190     /// ```
191     #[stable(feature = "is_char_boundary", since = "1.9.0")]
192     #[inline]
193     pub fn is_char_boundary(&self, index: usize) -> bool {
194         // 0 and len are always ok.
195         // Test for 0 explicitly so that it can optimize out the check
196         // easily and skip reading string data for that case.
197         if index == 0 || index == self.len() {
198             return true;
199         }
200         match self.as_bytes().get(index) {
201             None => false,
202             // This is bit magic equivalent to: b < 128 || b >= 192
203             Some(&b) => (b as i8) >= -0x40,
204         }
205     }
206
207     /// Converts a string slice to a byte slice. To convert the byte slice back
208     /// into a string slice, use the [`from_utf8`] function.
209     ///
210     /// # Examples
211     ///
212     /// Basic usage:
213     ///
214     /// ```
215     /// let bytes = "bors".as_bytes();
216     /// assert_eq!(b"bors", bytes);
217     /// ```
218     #[stable(feature = "rust1", since = "1.0.0")]
219     #[rustc_const_stable(feature = "str_as_bytes", since = "1.32.0")]
220     #[inline(always)]
221     #[allow(unused_attributes)]
222     #[rustc_allow_const_fn_unstable(const_fn_transmute)]
223     pub const fn as_bytes(&self) -> &[u8] {
224         // SAFETY: const sound because we transmute two types with the same layout
225         unsafe { mem::transmute(self) }
226     }
227
228     /// Converts a mutable string slice to a mutable byte slice.
229     ///
230     /// # Safety
231     ///
232     /// The caller must ensure that the content of the slice is valid UTF-8
233     /// before the borrow ends and the underlying `str` is used.
234     ///
235     /// Use of a `str` whose contents are not valid UTF-8 is undefined behavior.
236     ///
237     /// # Examples
238     ///
239     /// Basic usage:
240     ///
241     /// ```
242     /// let mut s = String::from("Hello");
243     /// let bytes = unsafe { s.as_bytes_mut() };
244     ///
245     /// assert_eq!(b"Hello", bytes);
246     /// ```
247     ///
248     /// Mutability:
249     ///
250     /// ```
251     /// let mut s = String::from("🗻∈🌏");
252     ///
253     /// unsafe {
254     ///     let bytes = s.as_bytes_mut();
255     ///
256     ///     bytes[0] = 0xF0;
257     ///     bytes[1] = 0x9F;
258     ///     bytes[2] = 0x8D;
259     ///     bytes[3] = 0x94;
260     /// }
261     ///
262     /// assert_eq!("🍔∈🌏", s);
263     /// ```
264     #[stable(feature = "str_mut_extras", since = "1.20.0")]
265     #[inline(always)]
266     pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
267         // SAFETY: the cast from `&str` to `&[u8]` is safe since `str`
268         // has the same layout as `&[u8]` (only libstd can make this guarantee).
269         // The pointer dereference is safe since it comes from a mutable reference which
270         // is guaranteed to be valid for writes.
271         unsafe { &mut *(self as *mut str as *mut [u8]) }
272     }
273
274     /// Converts a string slice to a raw pointer.
275     ///
276     /// As string slices are a slice of bytes, the raw pointer points to a
277     /// [`u8`]. This pointer will be pointing to the first byte of the string
278     /// slice.
279     ///
280     /// The caller must ensure that the returned pointer is never written to.
281     /// If you need to mutate the contents of the string slice, use [`as_mut_ptr`].
282     ///
283     /// [`as_mut_ptr`]: str::as_mut_ptr
284     ///
285     /// # Examples
286     ///
287     /// Basic usage:
288     ///
289     /// ```
290     /// let s = "Hello";
291     /// let ptr = s.as_ptr();
292     /// ```
293     #[stable(feature = "rust1", since = "1.0.0")]
294     #[rustc_const_stable(feature = "rustc_str_as_ptr", since = "1.32.0")]
295     #[inline]
296     pub const fn as_ptr(&self) -> *const u8 {
297         self as *const str as *const u8
298     }
299
300     /// Converts a mutable string slice to a raw pointer.
301     ///
302     /// As string slices are a slice of bytes, the raw pointer points to a
303     /// [`u8`]. This pointer will be pointing to the first byte of the string
304     /// slice.
305     ///
306     /// It is your responsibility to make sure that the string slice only gets
307     /// modified in a way that it remains valid UTF-8.
308     #[stable(feature = "str_as_mut_ptr", since = "1.36.0")]
309     #[inline]
310     pub fn as_mut_ptr(&mut self) -> *mut u8 {
311         self as *mut str as *mut u8
312     }
313
314     /// Returns a subslice of `str`.
315     ///
316     /// This is the non-panicking alternative to indexing the `str`. Returns
317     /// [`None`] whenever equivalent indexing operation would panic.
318     ///
319     /// # Examples
320     ///
321     /// ```
322     /// let v = String::from("🗻∈🌏");
323     ///
324     /// assert_eq!(Some("🗻"), v.get(0..4));
325     ///
326     /// // indices not on UTF-8 sequence boundaries
327     /// assert!(v.get(1..).is_none());
328     /// assert!(v.get(..8).is_none());
329     ///
330     /// // out of bounds
331     /// assert!(v.get(..42).is_none());
332     /// ```
333     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
334     #[inline]
335     pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
336         i.get(self)
337     }
338
339     /// Returns a mutable subslice of `str`.
340     ///
341     /// This is the non-panicking alternative to indexing the `str`. Returns
342     /// [`None`] whenever equivalent indexing operation would panic.
343     ///
344     /// # Examples
345     ///
346     /// ```
347     /// let mut v = String::from("hello");
348     /// // correct length
349     /// assert!(v.get_mut(0..5).is_some());
350     /// // out of bounds
351     /// assert!(v.get_mut(..42).is_none());
352     /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
353     ///
354     /// assert_eq!("hello", v);
355     /// {
356     ///     let s = v.get_mut(0..2);
357     ///     let s = s.map(|s| {
358     ///         s.make_ascii_uppercase();
359     ///         &*s
360     ///     });
361     ///     assert_eq!(Some("HE"), s);
362     /// }
363     /// assert_eq!("HEllo", v);
364     /// ```
365     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
366     #[inline]
367     pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
368         i.get_mut(self)
369     }
370
371     /// Returns an unchecked subslice of `str`.
372     ///
373     /// This is the unchecked alternative to indexing the `str`.
374     ///
375     /// # Safety
376     ///
377     /// Callers of this function are responsible that these preconditions are
378     /// satisfied:
379     ///
380     /// * The starting index must not exceed the ending index;
381     /// * Indexes must be within bounds of the original slice;
382     /// * Indexes must lie on UTF-8 sequence boundaries.
383     ///
384     /// Failing that, the returned string slice may reference invalid memory or
385     /// violate the invariants communicated by the `str` type.
386     ///
387     /// # Examples
388     ///
389     /// ```
390     /// let v = "🗻∈🌏";
391     /// unsafe {
392     ///     assert_eq!("🗻", v.get_unchecked(0..4));
393     ///     assert_eq!("∈", v.get_unchecked(4..7));
394     ///     assert_eq!("🌏", v.get_unchecked(7..11));
395     /// }
396     /// ```
397     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
398     #[inline]
399     pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
400         // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
401         // the slice is dereferencable because `self` is a safe reference.
402         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
403         unsafe { &*i.get_unchecked(self) }
404     }
405
406     /// Returns a mutable, unchecked subslice of `str`.
407     ///
408     /// This is the unchecked alternative to indexing the `str`.
409     ///
410     /// # Safety
411     ///
412     /// Callers of this function are responsible that these preconditions are
413     /// satisfied:
414     ///
415     /// * The starting index must not exceed the ending index;
416     /// * Indexes must be within bounds of the original slice;
417     /// * Indexes must lie on UTF-8 sequence boundaries.
418     ///
419     /// Failing that, the returned string slice may reference invalid memory or
420     /// violate the invariants communicated by the `str` type.
421     ///
422     /// # Examples
423     ///
424     /// ```
425     /// let mut v = String::from("🗻∈🌏");
426     /// unsafe {
427     ///     assert_eq!("🗻", v.get_unchecked_mut(0..4));
428     ///     assert_eq!("∈", v.get_unchecked_mut(4..7));
429     ///     assert_eq!("🌏", v.get_unchecked_mut(7..11));
430     /// }
431     /// ```
432     #[stable(feature = "str_checked_slicing", since = "1.20.0")]
433     #[inline]
434     pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
435         // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
436         // the slice is dereferencable because `self` is a safe reference.
437         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
438         unsafe { &mut *i.get_unchecked_mut(self) }
439     }
440
441     /// Creates a string slice from another string slice, bypassing safety
442     /// checks.
443     ///
444     /// This is generally not recommended, use with caution! For a safe
445     /// alternative see [`str`] and [`Index`].
446     ///
447     /// [`Index`]: crate::ops::Index
448     ///
449     /// This new slice goes from `begin` to `end`, including `begin` but
450     /// excluding `end`.
451     ///
452     /// To get a mutable string slice instead, see the
453     /// [`slice_mut_unchecked`] method.
454     ///
455     /// [`slice_mut_unchecked`]: str::slice_mut_unchecked
456     ///
457     /// # Safety
458     ///
459     /// Callers of this function are responsible that three preconditions are
460     /// satisfied:
461     ///
462     /// * `begin` must not exceed `end`.
463     /// * `begin` and `end` must be byte positions within the string slice.
464     /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
465     ///
466     /// # Examples
467     ///
468     /// Basic usage:
469     ///
470     /// ```
471     /// let s = "Löwe 老虎 Léopard";
472     ///
473     /// unsafe {
474     ///     assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
475     /// }
476     ///
477     /// let s = "Hello, world!";
478     ///
479     /// unsafe {
480     ///     assert_eq!("world", s.slice_unchecked(7, 12));
481     /// }
482     /// ```
483     #[stable(feature = "rust1", since = "1.0.0")]
484     #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked(begin..end)` instead")]
485     #[inline]
486     pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
487         // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
488         // the slice is dereferencable because `self` is a safe reference.
489         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
490         unsafe { &*(begin..end).get_unchecked(self) }
491     }
492
493     /// Creates a string slice from another string slice, bypassing safety
494     /// checks.
495     /// This is generally not recommended, use with caution! For a safe
496     /// alternative see [`str`] and [`IndexMut`].
497     ///
498     /// [`IndexMut`]: crate::ops::IndexMut
499     ///
500     /// This new slice goes from `begin` to `end`, including `begin` but
501     /// excluding `end`.
502     ///
503     /// To get an immutable string slice instead, see the
504     /// [`slice_unchecked`] method.
505     ///
506     /// [`slice_unchecked`]: str::slice_unchecked
507     ///
508     /// # Safety
509     ///
510     /// Callers of this function are responsible that three preconditions are
511     /// satisfied:
512     ///
513     /// * `begin` must not exceed `end`.
514     /// * `begin` and `end` must be byte positions within the string slice.
515     /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
516     #[stable(feature = "str_slice_mut", since = "1.5.0")]
517     #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked_mut(begin..end)` instead")]
518     #[inline]
519     pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
520         // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
521         // the slice is dereferencable because `self` is a safe reference.
522         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
523         unsafe { &mut *(begin..end).get_unchecked_mut(self) }
524     }
525
526     /// Divide one string slice into two at an index.
527     ///
528     /// The argument, `mid`, should be a byte offset from the start of the
529     /// string. It must also be on the boundary of a UTF-8 code point.
530     ///
531     /// The two slices returned go from the start of the string slice to `mid`,
532     /// and from `mid` to the end of the string slice.
533     ///
534     /// To get mutable string slices instead, see the [`split_at_mut`]
535     /// method.
536     ///
537     /// [`split_at_mut`]: str::split_at_mut
538     ///
539     /// # Panics
540     ///
541     /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
542     /// past the end of the last code point of the string slice.
543     ///
544     /// # Examples
545     ///
546     /// Basic usage:
547     ///
548     /// ```
549     /// let s = "Per Martin-Löf";
550     ///
551     /// let (first, last) = s.split_at(3);
552     ///
553     /// assert_eq!("Per", first);
554     /// assert_eq!(" Martin-Löf", last);
555     /// ```
556     #[inline]
557     #[stable(feature = "str_split_at", since = "1.4.0")]
558     pub fn split_at(&self, mid: usize) -> (&str, &str) {
559         // is_char_boundary checks that the index is in [0, .len()]
560         if self.is_char_boundary(mid) {
561             // SAFETY: just checked that `mid` is on a char boundary.
562             unsafe { (self.get_unchecked(0..mid), self.get_unchecked(mid..self.len())) }
563         } else {
564             slice_error_fail(self, 0, mid)
565         }
566     }
567
568     /// Divide one mutable string slice into two at an index.
569     ///
570     /// The argument, `mid`, should be a byte offset from the start of the
571     /// string. It must also be on the boundary of a UTF-8 code point.
572     ///
573     /// The two slices returned go from the start of the string slice to `mid`,
574     /// and from `mid` to the end of the string slice.
575     ///
576     /// To get immutable string slices instead, see the [`split_at`] method.
577     ///
578     /// [`split_at`]: str::split_at
579     ///
580     /// # Panics
581     ///
582     /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
583     /// past the end of the last code point of the string slice.
584     ///
585     /// # Examples
586     ///
587     /// Basic usage:
588     ///
589     /// ```
590     /// let mut s = "Per Martin-Löf".to_string();
591     /// {
592     ///     let (first, last) = s.split_at_mut(3);
593     ///     first.make_ascii_uppercase();
594     ///     assert_eq!("PER", first);
595     ///     assert_eq!(" Martin-Löf", last);
596     /// }
597     /// assert_eq!("PER Martin-Löf", s);
598     /// ```
599     #[inline]
600     #[stable(feature = "str_split_at", since = "1.4.0")]
601     pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
602         // is_char_boundary checks that the index is in [0, .len()]
603         if self.is_char_boundary(mid) {
604             let len = self.len();
605             let ptr = self.as_mut_ptr();
606             // SAFETY: just checked that `mid` is on a char boundary.
607             unsafe {
608                 (
609                     from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
610                     from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr.add(mid), len - mid)),
611                 )
612             }
613         } else {
614             slice_error_fail(self, 0, mid)
615         }
616     }
617
618     /// Returns an iterator over the [`char`]s of a string slice.
619     ///
620     /// As a string slice consists of valid UTF-8, we can iterate through a
621     /// string slice by [`char`]. This method returns such an iterator.
622     ///
623     /// It's important to remember that [`char`] represents a Unicode Scalar
624     /// Value, and may not match your idea of what a 'character' is. Iteration
625     /// over grapheme clusters may be what you actually want. This functionality
626     /// is not provided by Rust's standard library, check crates.io instead.
627     ///
628     /// # Examples
629     ///
630     /// Basic usage:
631     ///
632     /// ```
633     /// let word = "goodbye";
634     ///
635     /// let count = word.chars().count();
636     /// assert_eq!(7, count);
637     ///
638     /// let mut chars = word.chars();
639     ///
640     /// assert_eq!(Some('g'), chars.next());
641     /// assert_eq!(Some('o'), chars.next());
642     /// assert_eq!(Some('o'), chars.next());
643     /// assert_eq!(Some('d'), chars.next());
644     /// assert_eq!(Some('b'), chars.next());
645     /// assert_eq!(Some('y'), chars.next());
646     /// assert_eq!(Some('e'), chars.next());
647     ///
648     /// assert_eq!(None, chars.next());
649     /// ```
650     ///
651     /// Remember, [`char`]s may not match your intuition about characters:
652     ///
653     /// [`char`]: prim@char
654     ///
655     /// ```
656     /// let y = "y̆";
657     ///
658     /// let mut chars = y.chars();
659     ///
660     /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
661     /// assert_eq!(Some('\u{0306}'), chars.next());
662     ///
663     /// assert_eq!(None, chars.next());
664     /// ```
665     #[stable(feature = "rust1", since = "1.0.0")]
666     #[inline]
667     pub fn chars(&self) -> Chars<'_> {
668         Chars { iter: self.as_bytes().iter() }
669     }
670
671     /// Returns an iterator over the [`char`]s of a string slice, and their
672     /// positions.
673     ///
674     /// As a string slice consists of valid UTF-8, we can iterate through a
675     /// string slice by [`char`]. This method returns an iterator of both
676     /// these [`char`]s, as well as their byte positions.
677     ///
678     /// The iterator yields tuples. The position is first, the [`char`] is
679     /// second.
680     ///
681     /// # Examples
682     ///
683     /// Basic usage:
684     ///
685     /// ```
686     /// let word = "goodbye";
687     ///
688     /// let count = word.char_indices().count();
689     /// assert_eq!(7, count);
690     ///
691     /// let mut char_indices = word.char_indices();
692     ///
693     /// assert_eq!(Some((0, 'g')), char_indices.next());
694     /// assert_eq!(Some((1, 'o')), char_indices.next());
695     /// assert_eq!(Some((2, 'o')), char_indices.next());
696     /// assert_eq!(Some((3, 'd')), char_indices.next());
697     /// assert_eq!(Some((4, 'b')), char_indices.next());
698     /// assert_eq!(Some((5, 'y')), char_indices.next());
699     /// assert_eq!(Some((6, 'e')), char_indices.next());
700     ///
701     /// assert_eq!(None, char_indices.next());
702     /// ```
703     ///
704     /// Remember, [`char`]s may not match your intuition about characters:
705     ///
706     /// [`char`]: prim@char
707     ///
708     /// ```
709     /// let yes = "y̆es";
710     ///
711     /// let mut char_indices = yes.char_indices();
712     ///
713     /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
714     /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
715     ///
716     /// // note the 3 here - the last character took up two bytes
717     /// assert_eq!(Some((3, 'e')), char_indices.next());
718     /// assert_eq!(Some((4, 's')), char_indices.next());
719     ///
720     /// assert_eq!(None, char_indices.next());
721     /// ```
722     #[stable(feature = "rust1", since = "1.0.0")]
723     #[inline]
724     pub fn char_indices(&self) -> CharIndices<'_> {
725         CharIndices { front_offset: 0, iter: self.chars() }
726     }
727
728     /// An iterator over the bytes of a string slice.
729     ///
730     /// As a string slice consists of a sequence of bytes, we can iterate
731     /// through a string slice by byte. This method returns such an iterator.
732     ///
733     /// # Examples
734     ///
735     /// Basic usage:
736     ///
737     /// ```
738     /// let mut bytes = "bors".bytes();
739     ///
740     /// assert_eq!(Some(b'b'), bytes.next());
741     /// assert_eq!(Some(b'o'), bytes.next());
742     /// assert_eq!(Some(b'r'), bytes.next());
743     /// assert_eq!(Some(b's'), bytes.next());
744     ///
745     /// assert_eq!(None, bytes.next());
746     /// ```
747     #[stable(feature = "rust1", since = "1.0.0")]
748     #[inline]
749     pub fn bytes(&self) -> Bytes<'_> {
750         Bytes(self.as_bytes().iter().copied())
751     }
752
753     /// Splits a string slice by whitespace.
754     ///
755     /// The iterator returned will return string slices that are sub-slices of
756     /// the original string slice, separated by any amount of whitespace.
757     ///
758     /// 'Whitespace' is defined according to the terms of the Unicode Derived
759     /// Core Property `White_Space`. If you only want to split on ASCII whitespace
760     /// instead, use [`split_ascii_whitespace`].
761     ///
762     /// [`split_ascii_whitespace`]: str::split_ascii_whitespace
763     ///
764     /// # Examples
765     ///
766     /// Basic usage:
767     ///
768     /// ```
769     /// let mut iter = "A few words".split_whitespace();
770     ///
771     /// assert_eq!(Some("A"), iter.next());
772     /// assert_eq!(Some("few"), iter.next());
773     /// assert_eq!(Some("words"), iter.next());
774     ///
775     /// assert_eq!(None, iter.next());
776     /// ```
777     ///
778     /// All kinds of whitespace are considered:
779     ///
780     /// ```
781     /// let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
782     /// assert_eq!(Some("Mary"), iter.next());
783     /// assert_eq!(Some("had"), iter.next());
784     /// assert_eq!(Some("a"), iter.next());
785     /// assert_eq!(Some("little"), iter.next());
786     /// assert_eq!(Some("lamb"), iter.next());
787     ///
788     /// assert_eq!(None, iter.next());
789     /// ```
790     #[stable(feature = "split_whitespace", since = "1.1.0")]
791     #[inline]
792     pub fn split_whitespace(&self) -> SplitWhitespace<'_> {
793         SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
794     }
795
796     /// Splits a string slice by ASCII whitespace.
797     ///
798     /// The iterator returned will return string slices that are sub-slices of
799     /// the original string slice, separated by any amount of ASCII whitespace.
800     ///
801     /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
802     ///
803     /// [`split_whitespace`]: str::split_whitespace
804     ///
805     /// # Examples
806     ///
807     /// Basic usage:
808     ///
809     /// ```
810     /// let mut iter = "A few words".split_ascii_whitespace();
811     ///
812     /// assert_eq!(Some("A"), iter.next());
813     /// assert_eq!(Some("few"), iter.next());
814     /// assert_eq!(Some("words"), iter.next());
815     ///
816     /// assert_eq!(None, iter.next());
817     /// ```
818     ///
819     /// All kinds of ASCII whitespace are considered:
820     ///
821     /// ```
822     /// let mut iter = " Mary   had\ta little  \n\t lamb".split_ascii_whitespace();
823     /// assert_eq!(Some("Mary"), iter.next());
824     /// assert_eq!(Some("had"), iter.next());
825     /// assert_eq!(Some("a"), iter.next());
826     /// assert_eq!(Some("little"), iter.next());
827     /// assert_eq!(Some("lamb"), iter.next());
828     ///
829     /// assert_eq!(None, iter.next());
830     /// ```
831     #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
832     #[inline]
833     pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> {
834         let inner =
835             self.as_bytes().split(IsAsciiWhitespace).filter(BytesIsNotEmpty).map(UnsafeBytesToStr);
836         SplitAsciiWhitespace { inner }
837     }
838
839     /// An iterator over the lines of a string, as string slices.
840     ///
841     /// Lines are ended with either a newline (`\n`) or a carriage return with
842     /// a line feed (`\r\n`).
843     ///
844     /// The final line ending is optional. A string that ends with a final line
845     /// ending will return the same lines as an otherwise identical string
846     /// without a final line ending.
847     ///
848     /// # Examples
849     ///
850     /// Basic usage:
851     ///
852     /// ```
853     /// let text = "foo\r\nbar\n\nbaz\n";
854     /// let mut lines = text.lines();
855     ///
856     /// assert_eq!(Some("foo"), lines.next());
857     /// assert_eq!(Some("bar"), lines.next());
858     /// assert_eq!(Some(""), lines.next());
859     /// assert_eq!(Some("baz"), lines.next());
860     ///
861     /// assert_eq!(None, lines.next());
862     /// ```
863     ///
864     /// The final line ending isn't required:
865     ///
866     /// ```
867     /// let text = "foo\nbar\n\r\nbaz";
868     /// let mut lines = text.lines();
869     ///
870     /// assert_eq!(Some("foo"), lines.next());
871     /// assert_eq!(Some("bar"), lines.next());
872     /// assert_eq!(Some(""), lines.next());
873     /// assert_eq!(Some("baz"), lines.next());
874     ///
875     /// assert_eq!(None, lines.next());
876     /// ```
877     #[stable(feature = "rust1", since = "1.0.0")]
878     #[inline]
879     pub fn lines(&self) -> Lines<'_> {
880         Lines(self.split_terminator('\n').map(LinesAnyMap))
881     }
882
883     /// An iterator over the lines of a string.
884     #[stable(feature = "rust1", since = "1.0.0")]
885     #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
886     #[inline]
887     #[allow(deprecated)]
888     pub fn lines_any(&self) -> LinesAny<'_> {
889         LinesAny(self.lines())
890     }
891
892     /// Returns an iterator of `u16` over the string encoded as UTF-16.
893     ///
894     /// # Examples
895     ///
896     /// Basic usage:
897     ///
898     /// ```
899     /// let text = "Zażółć gęślą jaźń";
900     ///
901     /// let utf8_len = text.len();
902     /// let utf16_len = text.encode_utf16().count();
903     ///
904     /// assert!(utf16_len <= utf8_len);
905     /// ```
906     #[stable(feature = "encode_utf16", since = "1.8.0")]
907     pub fn encode_utf16(&self) -> EncodeUtf16<'_> {
908         EncodeUtf16 { chars: self.chars(), extra: 0 }
909     }
910
911     /// Returns `true` if the given pattern matches a sub-slice of
912     /// this string slice.
913     ///
914     /// Returns `false` if it does not.
915     ///
916     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
917     /// function or closure that determines if a character matches.
918     ///
919     /// [`char`]: prim@char
920     /// [pattern]: self::pattern
921     ///
922     /// # Examples
923     ///
924     /// Basic usage:
925     ///
926     /// ```
927     /// let bananas = "bananas";
928     ///
929     /// assert!(bananas.contains("nana"));
930     /// assert!(!bananas.contains("apples"));
931     /// ```
932     #[stable(feature = "rust1", since = "1.0.0")]
933     #[inline]
934     pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
935         pat.is_contained_in(self)
936     }
937
938     /// Returns `true` if the given pattern matches a prefix of this
939     /// string slice.
940     ///
941     /// Returns `false` if it does not.
942     ///
943     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
944     /// function or closure that determines if a character matches.
945     ///
946     /// [`char`]: prim@char
947     /// [pattern]: self::pattern
948     ///
949     /// # Examples
950     ///
951     /// Basic usage:
952     ///
953     /// ```
954     /// let bananas = "bananas";
955     ///
956     /// assert!(bananas.starts_with("bana"));
957     /// assert!(!bananas.starts_with("nana"));
958     /// ```
959     #[stable(feature = "rust1", since = "1.0.0")]
960     pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
961         pat.is_prefix_of(self)
962     }
963
964     /// Returns `true` if the given pattern matches a suffix of this
965     /// string slice.
966     ///
967     /// Returns `false` if it does not.
968     ///
969     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
970     /// function or closure that determines if a character matches.
971     ///
972     /// [`char`]: prim@char
973     /// [pattern]: self::pattern
974     ///
975     /// # Examples
976     ///
977     /// Basic usage:
978     ///
979     /// ```
980     /// let bananas = "bananas";
981     ///
982     /// assert!(bananas.ends_with("anas"));
983     /// assert!(!bananas.ends_with("nana"));
984     /// ```
985     #[stable(feature = "rust1", since = "1.0.0")]
986     pub fn ends_with<'a, P>(&'a self, pat: P) -> bool
987     where
988         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
989     {
990         pat.is_suffix_of(self)
991     }
992
993     /// Returns the byte index of the first character of this string slice that
994     /// matches the pattern.
995     ///
996     /// Returns [`None`] if the pattern doesn't match.
997     ///
998     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
999     /// function or closure that determines if a character matches.
1000     ///
1001     /// [`char`]: prim@char
1002     /// [pattern]: self::pattern
1003     ///
1004     /// # Examples
1005     ///
1006     /// Simple patterns:
1007     ///
1008     /// ```
1009     /// let s = "Löwe 老虎 Léopard Gepardi";
1010     ///
1011     /// assert_eq!(s.find('L'), Some(0));
1012     /// assert_eq!(s.find('é'), Some(14));
1013     /// assert_eq!(s.find("pard"), Some(17));
1014     /// ```
1015     ///
1016     /// More complex patterns using point-free style and closures:
1017     ///
1018     /// ```
1019     /// let s = "Löwe 老虎 Léopard";
1020     ///
1021     /// assert_eq!(s.find(char::is_whitespace), Some(5));
1022     /// assert_eq!(s.find(char::is_lowercase), Some(1));
1023     /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
1024     /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
1025     /// ```
1026     ///
1027     /// Not finding the pattern:
1028     ///
1029     /// ```
1030     /// let s = "Löwe 老虎 Léopard";
1031     /// let x: &[_] = &['1', '2'];
1032     ///
1033     /// assert_eq!(s.find(x), None);
1034     /// ```
1035     #[stable(feature = "rust1", since = "1.0.0")]
1036     #[inline]
1037     pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1038         pat.into_searcher(self).next_match().map(|(i, _)| i)
1039     }
1040
1041     /// Returns the byte index for the first character of the rightmost match of the pattern in
1042     /// this string slice.
1043     ///
1044     /// Returns [`None`] if the pattern doesn't match.
1045     ///
1046     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1047     /// function or closure that determines if a character matches.
1048     ///
1049     /// [`char`]: prim@char
1050     /// [pattern]: self::pattern
1051     ///
1052     /// # Examples
1053     ///
1054     /// Simple patterns:
1055     ///
1056     /// ```
1057     /// let s = "Löwe 老虎 Léopard Gepardi";
1058     ///
1059     /// assert_eq!(s.rfind('L'), Some(13));
1060     /// assert_eq!(s.rfind('é'), Some(14));
1061     /// assert_eq!(s.rfind("pard"), Some(24));
1062     /// ```
1063     ///
1064     /// More complex patterns with closures:
1065     ///
1066     /// ```
1067     /// let s = "Löwe 老虎 Léopard";
1068     ///
1069     /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1070     /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1071     /// ```
1072     ///
1073     /// Not finding the pattern:
1074     ///
1075     /// ```
1076     /// let s = "Löwe 老虎 Léopard";
1077     /// let x: &[_] = &['1', '2'];
1078     ///
1079     /// assert_eq!(s.rfind(x), None);
1080     /// ```
1081     #[stable(feature = "rust1", since = "1.0.0")]
1082     #[inline]
1083     pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>
1084     where
1085         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1086     {
1087         pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1088     }
1089
1090     /// An iterator over substrings of this string slice, separated by
1091     /// characters matched by a pattern.
1092     ///
1093     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1094     /// function or closure that determines if a character matches.
1095     ///
1096     /// [`char`]: prim@char
1097     /// [pattern]: self::pattern
1098     ///
1099     /// # Iterator behavior
1100     ///
1101     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1102     /// allows a reverse search and forward/reverse search yields the same
1103     /// elements. This is true for, e.g., [`char`], but not for `&str`.
1104     ///
1105     /// If the pattern allows a reverse search but its results might differ
1106     /// from a forward search, the [`rsplit`] method can be used.
1107     ///
1108     /// [`rsplit`]: str::rsplit
1109     ///
1110     /// # Examples
1111     ///
1112     /// Simple patterns:
1113     ///
1114     /// ```
1115     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1116     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1117     ///
1118     /// let v: Vec<&str> = "".split('X').collect();
1119     /// assert_eq!(v, [""]);
1120     ///
1121     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1122     /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1123     ///
1124     /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1125     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1126     ///
1127     /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1128     /// assert_eq!(v, ["abc", "def", "ghi"]);
1129     ///
1130     /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1131     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1132     /// ```
1133     ///
1134     /// If the pattern is a slice of chars, split on each occurrence of any of the characters:
1135     ///
1136     /// ```
1137     /// let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
1138     /// assert_eq!(v, ["2020", "11", "03", "23", "59"]);
1139     /// ```
1140     ///
1141     /// A more complex pattern, using a closure:
1142     ///
1143     /// ```
1144     /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1145     /// assert_eq!(v, ["abc", "def", "ghi"]);
1146     /// ```
1147     ///
1148     /// If a string contains multiple contiguous separators, you will end up
1149     /// with empty strings in the output:
1150     ///
1151     /// ```
1152     /// let x = "||||a||b|c".to_string();
1153     /// let d: Vec<_> = x.split('|').collect();
1154     ///
1155     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1156     /// ```
1157     ///
1158     /// Contiguous separators are separated by the empty string.
1159     ///
1160     /// ```
1161     /// let x = "(///)".to_string();
1162     /// let d: Vec<_> = x.split('/').collect();
1163     ///
1164     /// assert_eq!(d, &["(", "", "", ")"]);
1165     /// ```
1166     ///
1167     /// Separators at the start or end of a string are neighbored
1168     /// by empty strings.
1169     ///
1170     /// ```
1171     /// let d: Vec<_> = "010".split("0").collect();
1172     /// assert_eq!(d, &["", "1", ""]);
1173     /// ```
1174     ///
1175     /// When the empty string is used as a separator, it separates
1176     /// every character in the string, along with the beginning
1177     /// and end of the string.
1178     ///
1179     /// ```
1180     /// let f: Vec<_> = "rust".split("").collect();
1181     /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1182     /// ```
1183     ///
1184     /// Contiguous separators can lead to possibly surprising behavior
1185     /// when whitespace is used as the separator. This code is correct:
1186     ///
1187     /// ```
1188     /// let x = "    a  b c".to_string();
1189     /// let d: Vec<_> = x.split(' ').collect();
1190     ///
1191     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1192     /// ```
1193     ///
1194     /// It does _not_ give you:
1195     ///
1196     /// ```,ignore
1197     /// assert_eq!(d, &["a", "b", "c"]);
1198     /// ```
1199     ///
1200     /// Use [`split_whitespace`] for this behavior.
1201     ///
1202     /// [`split_whitespace`]: str::split_whitespace
1203     #[stable(feature = "rust1", since = "1.0.0")]
1204     #[inline]
1205     pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1206         Split(SplitInternal {
1207             start: 0,
1208             end: self.len(),
1209             matcher: pat.into_searcher(self),
1210             allow_trailing_empty: true,
1211             finished: false,
1212         })
1213     }
1214
1215     /// An iterator over substrings of this string slice, separated by
1216     /// characters matched by a pattern. Differs from the iterator produced by
1217     /// `split` in that `split_inclusive` leaves the matched part as the
1218     /// terminator of the substring.
1219     ///
1220     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1221     /// function or closure that determines if a character matches.
1222     ///
1223     /// [`char`]: prim@char
1224     /// [pattern]: self::pattern
1225     ///
1226     /// # Examples
1227     ///
1228     /// ```
1229     /// #![feature(split_inclusive)]
1230     /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
1231     ///     .split_inclusive('\n').collect();
1232     /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
1233     /// ```
1234     ///
1235     /// If the last element of the string is matched,
1236     /// that element will be considered the terminator of the preceding substring.
1237     /// That substring will be the last item returned by the iterator.
1238     ///
1239     /// ```
1240     /// #![feature(split_inclusive)]
1241     /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
1242     ///     .split_inclusive('\n').collect();
1243     /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1244     /// ```
1245     #[unstable(feature = "split_inclusive", issue = "72360")]
1246     #[inline]
1247     pub fn split_inclusive<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitInclusive<'a, P> {
1248         SplitInclusive(SplitInternal {
1249             start: 0,
1250             end: self.len(),
1251             matcher: pat.into_searcher(self),
1252             allow_trailing_empty: false,
1253             finished: false,
1254         })
1255     }
1256
1257     /// An iterator over substrings of the given string slice, separated by
1258     /// characters matched by a pattern and yielded in reverse order.
1259     ///
1260     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1261     /// function or closure that determines if a character matches.
1262     ///
1263     /// [`char`]: prim@char
1264     /// [pattern]: self::pattern
1265     ///
1266     /// # Iterator behavior
1267     ///
1268     /// The returned iterator requires that the pattern supports a reverse
1269     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1270     /// search yields the same elements.
1271     ///
1272     /// For iterating from the front, the [`split`] method can be used.
1273     ///
1274     /// [`split`]: str::split
1275     ///
1276     /// # Examples
1277     ///
1278     /// Simple patterns:
1279     ///
1280     /// ```
1281     /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1282     /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1283     ///
1284     /// let v: Vec<&str> = "".rsplit('X').collect();
1285     /// assert_eq!(v, [""]);
1286     ///
1287     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1288     /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1289     ///
1290     /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1291     /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1292     /// ```
1293     ///
1294     /// A more complex pattern, using a closure:
1295     ///
1296     /// ```
1297     /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1298     /// assert_eq!(v, ["ghi", "def", "abc"]);
1299     /// ```
1300     #[stable(feature = "rust1", since = "1.0.0")]
1301     #[inline]
1302     pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P>
1303     where
1304         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1305     {
1306         RSplit(self.split(pat).0)
1307     }
1308
1309     /// An iterator over substrings of the given string slice, separated by
1310     /// characters matched by a pattern.
1311     ///
1312     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1313     /// function or closure that determines if a character matches.
1314     ///
1315     /// [`char`]: prim@char
1316     /// [pattern]: self::pattern
1317     ///
1318     /// Equivalent to [`split`], except that the trailing substring
1319     /// is skipped if empty.
1320     ///
1321     /// [`split`]: str::split
1322     ///
1323     /// This method can be used for string data that is _terminated_,
1324     /// rather than _separated_ by a pattern.
1325     ///
1326     /// # Iterator behavior
1327     ///
1328     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1329     /// allows a reverse search and forward/reverse search yields the same
1330     /// elements. This is true for, e.g., [`char`], but not for `&str`.
1331     ///
1332     /// If the pattern allows a reverse search but its results might differ
1333     /// from a forward search, the [`rsplit_terminator`] method can be used.
1334     ///
1335     /// [`rsplit_terminator`]: str::rsplit_terminator
1336     ///
1337     /// # Examples
1338     ///
1339     /// Basic usage:
1340     ///
1341     /// ```
1342     /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1343     /// assert_eq!(v, ["A", "B"]);
1344     ///
1345     /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1346     /// assert_eq!(v, ["A", "", "B", ""]);
1347     /// ```
1348     #[stable(feature = "rust1", since = "1.0.0")]
1349     #[inline]
1350     pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1351         SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 })
1352     }
1353
1354     /// An iterator over substrings of `self`, separated by characters
1355     /// matched by a pattern and yielded in reverse order.
1356     ///
1357     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1358     /// function or closure that determines if a character matches.
1359     ///
1360     /// [`char`]: prim@char
1361     /// [pattern]: self::pattern
1362     ///
1363     /// Equivalent to [`split`], except that the trailing substring is
1364     /// skipped if empty.
1365     ///
1366     /// [`split`]: str::split
1367     ///
1368     /// This method can be used for string data that is _terminated_,
1369     /// rather than _separated_ by a pattern.
1370     ///
1371     /// # Iterator behavior
1372     ///
1373     /// The returned iterator requires that the pattern supports a
1374     /// reverse search, and it will be double ended if a forward/reverse
1375     /// search yields the same elements.
1376     ///
1377     /// For iterating from the front, the [`split_terminator`] method can be
1378     /// used.
1379     ///
1380     /// [`split_terminator`]: str::split_terminator
1381     ///
1382     /// # Examples
1383     ///
1384     /// ```
1385     /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1386     /// assert_eq!(v, ["B", "A"]);
1387     ///
1388     /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1389     /// assert_eq!(v, ["", "B", "", "A"]);
1390     /// ```
1391     #[stable(feature = "rust1", since = "1.0.0")]
1392     #[inline]
1393     pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1394     where
1395         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1396     {
1397         RSplitTerminator(self.split_terminator(pat).0)
1398     }
1399
1400     /// An iterator over substrings of the given string slice, separated by a
1401     /// pattern, restricted to returning at most `n` items.
1402     ///
1403     /// If `n` substrings are returned, the last substring (the `n`th substring)
1404     /// will contain the remainder of the string.
1405     ///
1406     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1407     /// function or closure that determines if a character matches.
1408     ///
1409     /// [`char`]: prim@char
1410     /// [pattern]: self::pattern
1411     ///
1412     /// # Iterator behavior
1413     ///
1414     /// The returned iterator will not be double ended, because it is
1415     /// not efficient to support.
1416     ///
1417     /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1418     /// used.
1419     ///
1420     /// [`rsplitn`]: str::rsplitn
1421     ///
1422     /// # Examples
1423     ///
1424     /// Simple patterns:
1425     ///
1426     /// ```
1427     /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1428     /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1429     ///
1430     /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1431     /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1432     ///
1433     /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1434     /// assert_eq!(v, ["abcXdef"]);
1435     ///
1436     /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1437     /// assert_eq!(v, [""]);
1438     /// ```
1439     ///
1440     /// A more complex pattern, using a closure:
1441     ///
1442     /// ```
1443     /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1444     /// assert_eq!(v, ["abc", "defXghi"]);
1445     /// ```
1446     #[stable(feature = "rust1", since = "1.0.0")]
1447     #[inline]
1448     pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1449         SplitN(SplitNInternal { iter: self.split(pat).0, count: n })
1450     }
1451
1452     /// An iterator over substrings of this string slice, separated by a
1453     /// pattern, starting from the end of the string, restricted to returning
1454     /// at most `n` items.
1455     ///
1456     /// If `n` substrings are returned, the last substring (the `n`th substring)
1457     /// will contain the remainder of the string.
1458     ///
1459     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1460     /// function or closure that determines if a character matches.
1461     ///
1462     /// [`char`]: prim@char
1463     /// [pattern]: self::pattern
1464     ///
1465     /// # Iterator behavior
1466     ///
1467     /// The returned iterator will not be double ended, because it is not
1468     /// efficient to support.
1469     ///
1470     /// For splitting from the front, the [`splitn`] method can be used.
1471     ///
1472     /// [`splitn`]: str::splitn
1473     ///
1474     /// # Examples
1475     ///
1476     /// Simple patterns:
1477     ///
1478     /// ```
1479     /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1480     /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1481     ///
1482     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1483     /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1484     ///
1485     /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1486     /// assert_eq!(v, ["leopard", "lion::tiger"]);
1487     /// ```
1488     ///
1489     /// A more complex pattern, using a closure:
1490     ///
1491     /// ```
1492     /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1493     /// assert_eq!(v, ["ghi", "abc1def"]);
1494     /// ```
1495     #[stable(feature = "rust1", since = "1.0.0")]
1496     #[inline]
1497     pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1498     where
1499         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1500     {
1501         RSplitN(self.splitn(n, pat).0)
1502     }
1503
1504     /// Splits the string on the first occurrence of the specified delimiter and
1505     /// returns prefix before delimiter and suffix after delimiter.
1506     ///
1507     /// # Examples
1508     ///
1509     /// ```
1510     /// #![feature(str_split_once)]
1511     ///
1512     /// assert_eq!("cfg".split_once('='), None);
1513     /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
1514     /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
1515     /// ```
1516     #[unstable(feature = "str_split_once", reason = "newly added", issue = "74773")]
1517     #[inline]
1518     pub fn split_once<'a, P: Pattern<'a>>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)> {
1519         let (start, end) = delimiter.into_searcher(self).next_match()?;
1520         Some((&self[..start], &self[end..]))
1521     }
1522
1523     /// Splits the string on the last occurrence of the specified delimiter and
1524     /// returns prefix before delimiter and suffix after delimiter.
1525     ///
1526     /// # Examples
1527     ///
1528     /// ```
1529     /// #![feature(str_split_once)]
1530     ///
1531     /// assert_eq!("cfg".rsplit_once('='), None);
1532     /// assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
1533     /// assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
1534     /// ```
1535     #[unstable(feature = "str_split_once", reason = "newly added", issue = "74773")]
1536     #[inline]
1537     pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>
1538     where
1539         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1540     {
1541         let (start, end) = delimiter.into_searcher(self).next_match_back()?;
1542         Some((&self[..start], &self[end..]))
1543     }
1544
1545     /// An iterator over the disjoint matches of a pattern within the given string
1546     /// slice.
1547     ///
1548     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1549     /// function or closure that determines if a character matches.
1550     ///
1551     /// [`char`]: prim@char
1552     /// [pattern]: self::pattern
1553     ///
1554     /// # Iterator behavior
1555     ///
1556     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1557     /// allows a reverse search and forward/reverse search yields the same
1558     /// elements. This is true for, e.g., [`char`], but not for `&str`.
1559     ///
1560     /// If the pattern allows a reverse search but its results might differ
1561     /// from a forward search, the [`rmatches`] method can be used.
1562     ///
1563     /// [`rmatches`]: str::matches
1564     ///
1565     /// # Examples
1566     ///
1567     /// Basic usage:
1568     ///
1569     /// ```
1570     /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1571     /// assert_eq!(v, ["abc", "abc", "abc"]);
1572     ///
1573     /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1574     /// assert_eq!(v, ["1", "2", "3"]);
1575     /// ```
1576     #[stable(feature = "str_matches", since = "1.2.0")]
1577     #[inline]
1578     pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1579         Matches(MatchesInternal(pat.into_searcher(self)))
1580     }
1581
1582     /// An iterator over the disjoint matches of a pattern within this string slice,
1583     /// yielded in reverse order.
1584     ///
1585     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1586     /// function or closure that determines if a character matches.
1587     ///
1588     /// [`char`]: prim@char
1589     /// [pattern]: self::pattern
1590     ///
1591     /// # Iterator behavior
1592     ///
1593     /// The returned iterator requires that the pattern supports a reverse
1594     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1595     /// search yields the same elements.
1596     ///
1597     /// For iterating from the front, the [`matches`] method can be used.
1598     ///
1599     /// [`matches`]: str::matches
1600     ///
1601     /// # Examples
1602     ///
1603     /// Basic usage:
1604     ///
1605     /// ```
1606     /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1607     /// assert_eq!(v, ["abc", "abc", "abc"]);
1608     ///
1609     /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1610     /// assert_eq!(v, ["3", "2", "1"]);
1611     /// ```
1612     #[stable(feature = "str_matches", since = "1.2.0")]
1613     #[inline]
1614     pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P>
1615     where
1616         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1617     {
1618         RMatches(self.matches(pat).0)
1619     }
1620
1621     /// An iterator over the disjoint matches of a pattern within this string
1622     /// slice as well as the index that the match starts at.
1623     ///
1624     /// For matches of `pat` within `self` that overlap, only the indices
1625     /// corresponding to the first match are returned.
1626     ///
1627     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1628     /// function or closure that determines if a character matches.
1629     ///
1630     /// [`char`]: prim@char
1631     /// [pattern]: self::pattern
1632     ///
1633     /// # Iterator behavior
1634     ///
1635     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1636     /// allows a reverse search and forward/reverse search yields the same
1637     /// elements. This is true for, e.g., [`char`], but not for `&str`.
1638     ///
1639     /// If the pattern allows a reverse search but its results might differ
1640     /// from a forward search, the [`rmatch_indices`] method can be used.
1641     ///
1642     /// [`rmatch_indices`]: str::match_indices
1643     ///
1644     /// # Examples
1645     ///
1646     /// Basic usage:
1647     ///
1648     /// ```
1649     /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1650     /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1651     ///
1652     /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1653     /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1654     ///
1655     /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1656     /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1657     /// ```
1658     #[stable(feature = "str_match_indices", since = "1.5.0")]
1659     #[inline]
1660     pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1661         MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
1662     }
1663
1664     /// An iterator over the disjoint matches of a pattern within `self`,
1665     /// yielded in reverse order along with the index of the match.
1666     ///
1667     /// For matches of `pat` within `self` that overlap, only the indices
1668     /// corresponding to the last match are returned.
1669     ///
1670     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1671     /// function or closure that determines if a character matches.
1672     ///
1673     /// [`char`]: prim@char
1674     /// [pattern]: self::pattern
1675     ///
1676     /// # Iterator behavior
1677     ///
1678     /// The returned iterator requires that the pattern supports a reverse
1679     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1680     /// search yields the same elements.
1681     ///
1682     /// For iterating from the front, the [`match_indices`] method can be used.
1683     ///
1684     /// [`match_indices`]: str::match_indices
1685     ///
1686     /// # Examples
1687     ///
1688     /// Basic usage:
1689     ///
1690     /// ```
1691     /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1692     /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1693     ///
1694     /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1695     /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1696     ///
1697     /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1698     /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1699     /// ```
1700     #[stable(feature = "str_match_indices", since = "1.5.0")]
1701     #[inline]
1702     pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P>
1703     where
1704         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1705     {
1706         RMatchIndices(self.match_indices(pat).0)
1707     }
1708
1709     /// Returns a string slice with leading and trailing whitespace removed.
1710     ///
1711     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1712     /// Core Property `White_Space`.
1713     ///
1714     /// # Examples
1715     ///
1716     /// Basic usage:
1717     ///
1718     /// ```
1719     /// let s = " Hello\tworld\t";
1720     ///
1721     /// assert_eq!("Hello\tworld", s.trim());
1722     /// ```
1723     #[inline]
1724     #[must_use = "this returns the trimmed string as a slice, \
1725                   without modifying the original"]
1726     #[stable(feature = "rust1", since = "1.0.0")]
1727     pub fn trim(&self) -> &str {
1728         self.trim_matches(|c: char| c.is_whitespace())
1729     }
1730
1731     /// Returns a string slice with leading whitespace removed.
1732     ///
1733     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1734     /// Core Property `White_Space`.
1735     ///
1736     /// # Text directionality
1737     ///
1738     /// A string is a sequence of bytes. `start` in this context means the first
1739     /// position of that byte string; for a left-to-right language like English or
1740     /// Russian, this will be left side, and for right-to-left languages like
1741     /// Arabic or Hebrew, this will be the right side.
1742     ///
1743     /// # Examples
1744     ///
1745     /// Basic usage:
1746     ///
1747     /// ```
1748     /// let s = " Hello\tworld\t";
1749     /// assert_eq!("Hello\tworld\t", s.trim_start());
1750     /// ```
1751     ///
1752     /// Directionality:
1753     ///
1754     /// ```
1755     /// let s = "  English  ";
1756     /// assert!(Some('E') == s.trim_start().chars().next());
1757     ///
1758     /// let s = "  עברית  ";
1759     /// assert!(Some('ע') == s.trim_start().chars().next());
1760     /// ```
1761     #[inline]
1762     #[must_use = "this returns the trimmed string as a new slice, \
1763                   without modifying the original"]
1764     #[stable(feature = "trim_direction", since = "1.30.0")]
1765     pub fn trim_start(&self) -> &str {
1766         self.trim_start_matches(|c: char| c.is_whitespace())
1767     }
1768
1769     /// Returns a string slice with trailing whitespace removed.
1770     ///
1771     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1772     /// Core Property `White_Space`.
1773     ///
1774     /// # Text directionality
1775     ///
1776     /// A string is a sequence of bytes. `end` in this context means the last
1777     /// position of that byte string; for a left-to-right language like English or
1778     /// Russian, this will be right side, and for right-to-left languages like
1779     /// Arabic or Hebrew, this will be the left side.
1780     ///
1781     /// # Examples
1782     ///
1783     /// Basic usage:
1784     ///
1785     /// ```
1786     /// let s = " Hello\tworld\t";
1787     /// assert_eq!(" Hello\tworld", s.trim_end());
1788     /// ```
1789     ///
1790     /// Directionality:
1791     ///
1792     /// ```
1793     /// let s = "  English  ";
1794     /// assert!(Some('h') == s.trim_end().chars().rev().next());
1795     ///
1796     /// let s = "  עברית  ";
1797     /// assert!(Some('ת') == s.trim_end().chars().rev().next());
1798     /// ```
1799     #[inline]
1800     #[must_use = "this returns the trimmed string as a new slice, \
1801                   without modifying the original"]
1802     #[stable(feature = "trim_direction", since = "1.30.0")]
1803     pub fn trim_end(&self) -> &str {
1804         self.trim_end_matches(|c: char| c.is_whitespace())
1805     }
1806
1807     /// Returns a string slice with leading whitespace removed.
1808     ///
1809     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1810     /// Core Property `White_Space`.
1811     ///
1812     /// # Text directionality
1813     ///
1814     /// A string is a sequence of bytes. 'Left' in this context means the first
1815     /// position of that byte string; for a language like Arabic or Hebrew
1816     /// which are 'right to left' rather than 'left to right', this will be
1817     /// the _right_ side, not the left.
1818     ///
1819     /// # Examples
1820     ///
1821     /// Basic usage:
1822     ///
1823     /// ```
1824     /// let s = " Hello\tworld\t";
1825     ///
1826     /// assert_eq!("Hello\tworld\t", s.trim_left());
1827     /// ```
1828     ///
1829     /// Directionality:
1830     ///
1831     /// ```
1832     /// let s = "  English";
1833     /// assert!(Some('E') == s.trim_left().chars().next());
1834     ///
1835     /// let s = "  עברית";
1836     /// assert!(Some('ע') == s.trim_left().chars().next());
1837     /// ```
1838     #[inline]
1839     #[stable(feature = "rust1", since = "1.0.0")]
1840     #[rustc_deprecated(
1841         since = "1.33.0",
1842         reason = "superseded by `trim_start`",
1843         suggestion = "trim_start"
1844     )]
1845     pub fn trim_left(&self) -> &str {
1846         self.trim_start()
1847     }
1848
1849     /// Returns a string slice with trailing whitespace removed.
1850     ///
1851     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1852     /// Core Property `White_Space`.
1853     ///
1854     /// # Text directionality
1855     ///
1856     /// A string is a sequence of bytes. 'Right' in this context means the last
1857     /// position of that byte string; for a language like Arabic or Hebrew
1858     /// which are 'right to left' rather than 'left to right', this will be
1859     /// the _left_ side, not the right.
1860     ///
1861     /// # Examples
1862     ///
1863     /// Basic usage:
1864     ///
1865     /// ```
1866     /// let s = " Hello\tworld\t";
1867     ///
1868     /// assert_eq!(" Hello\tworld", s.trim_right());
1869     /// ```
1870     ///
1871     /// Directionality:
1872     ///
1873     /// ```
1874     /// let s = "English  ";
1875     /// assert!(Some('h') == s.trim_right().chars().rev().next());
1876     ///
1877     /// let s = "עברית  ";
1878     /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1879     /// ```
1880     #[inline]
1881     #[stable(feature = "rust1", since = "1.0.0")]
1882     #[rustc_deprecated(
1883         since = "1.33.0",
1884         reason = "superseded by `trim_end`",
1885         suggestion = "trim_end"
1886     )]
1887     pub fn trim_right(&self) -> &str {
1888         self.trim_end()
1889     }
1890
1891     /// Returns a string slice with all prefixes and suffixes that match a
1892     /// pattern repeatedly removed.
1893     ///
1894     /// The [pattern] can be a [`char`], a slice of [`char`]s, or a function
1895     /// or closure that determines if a character matches.
1896     ///
1897     /// [`char`]: prim@char
1898     /// [pattern]: self::pattern
1899     ///
1900     /// # Examples
1901     ///
1902     /// Simple patterns:
1903     ///
1904     /// ```
1905     /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1906     /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1907     ///
1908     /// let x: &[_] = &['1', '2'];
1909     /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1910     /// ```
1911     ///
1912     /// A more complex pattern, using a closure:
1913     ///
1914     /// ```
1915     /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1916     /// ```
1917     #[must_use = "this returns the trimmed string as a new slice, \
1918                   without modifying the original"]
1919     #[stable(feature = "rust1", since = "1.0.0")]
1920     pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str
1921     where
1922         P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>,
1923     {
1924         let mut i = 0;
1925         let mut j = 0;
1926         let mut matcher = pat.into_searcher(self);
1927         if let Some((a, b)) = matcher.next_reject() {
1928             i = a;
1929             j = b; // Remember earliest known match, correct it below if
1930             // last match is different
1931         }
1932         if let Some((_, b)) = matcher.next_reject_back() {
1933             j = b;
1934         }
1935         // SAFETY: `Searcher` is known to return valid indices.
1936         unsafe { self.get_unchecked(i..j) }
1937     }
1938
1939     /// Returns a string slice with all prefixes that match a pattern
1940     /// repeatedly removed.
1941     ///
1942     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1943     /// function or closure that determines if a character matches.
1944     ///
1945     /// [`char`]: prim@char
1946     /// [pattern]: self::pattern
1947     ///
1948     /// # Text directionality
1949     ///
1950     /// A string is a sequence of bytes. `start` in this context means the first
1951     /// position of that byte string; for a left-to-right language like English or
1952     /// Russian, this will be left side, and for right-to-left languages like
1953     /// Arabic or Hebrew, this will be the right side.
1954     ///
1955     /// # Examples
1956     ///
1957     /// Basic usage:
1958     ///
1959     /// ```
1960     /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
1961     /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
1962     ///
1963     /// let x: &[_] = &['1', '2'];
1964     /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
1965     /// ```
1966     #[must_use = "this returns the trimmed string as a new slice, \
1967                   without modifying the original"]
1968     #[stable(feature = "trim_direction", since = "1.30.0")]
1969     pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1970         let mut i = self.len();
1971         let mut matcher = pat.into_searcher(self);
1972         if let Some((a, _)) = matcher.next_reject() {
1973             i = a;
1974         }
1975         // SAFETY: `Searcher` is known to return valid indices.
1976         unsafe { self.get_unchecked(i..self.len()) }
1977     }
1978
1979     /// Returns a string slice with the prefix removed.
1980     ///
1981     /// If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped
1982     /// in `Some`.  Unlike `trim_start_matches`, this method removes the prefix exactly once.
1983     ///
1984     /// If the string does not start with `prefix`, returns `None`.
1985     ///
1986     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1987     /// function or closure that determines if a character matches.
1988     ///
1989     /// [`char`]: prim@char
1990     /// [pattern]: self::pattern
1991     ///
1992     /// # Examples
1993     ///
1994     /// ```
1995     /// assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
1996     /// assert_eq!("foo:bar".strip_prefix("bar"), None);
1997     /// assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
1998     /// ```
1999     #[must_use = "this returns the remaining substring as a new slice, \
2000                   without modifying the original"]
2001     #[stable(feature = "str_strip", since = "1.45.0")]
2002     pub fn strip_prefix<'a, P: Pattern<'a>>(&'a self, prefix: P) -> Option<&'a str> {
2003         prefix.strip_prefix_of(self)
2004     }
2005
2006     /// Returns a string slice with the suffix removed.
2007     ///
2008     /// If the string ends with the pattern `suffix`, returns the substring before the suffix,
2009     /// wrapped in `Some`.  Unlike `trim_end_matches`, this method removes the suffix exactly once.
2010     ///
2011     /// If the string does not end with `suffix`, returns `None`.
2012     ///
2013     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2014     /// function or closure that determines if a character matches.
2015     ///
2016     /// [`char`]: prim@char
2017     /// [pattern]: self::pattern
2018     ///
2019     /// # Examples
2020     ///
2021     /// ```
2022     /// assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
2023     /// assert_eq!("bar:foo".strip_suffix("bar"), None);
2024     /// assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
2025     /// ```
2026     #[must_use = "this returns the remaining substring as a new slice, \
2027                   without modifying the original"]
2028     #[stable(feature = "str_strip", since = "1.45.0")]
2029     pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>
2030     where
2031         P: Pattern<'a>,
2032         <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
2033     {
2034         suffix.strip_suffix_of(self)
2035     }
2036
2037     /// Returns a string slice with all suffixes that match a pattern
2038     /// repeatedly removed.
2039     ///
2040     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2041     /// function or closure that determines if a character matches.
2042     ///
2043     /// [`char`]: prim@char
2044     /// [pattern]: self::pattern
2045     ///
2046     /// # Text directionality
2047     ///
2048     /// A string is a sequence of bytes. `end` in this context means the last
2049     /// position of that byte string; for a left-to-right language like English or
2050     /// Russian, this will be right side, and for right-to-left languages like
2051     /// Arabic or Hebrew, this will be the left side.
2052     ///
2053     /// # Examples
2054     ///
2055     /// Simple patterns:
2056     ///
2057     /// ```
2058     /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
2059     /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
2060     ///
2061     /// let x: &[_] = &['1', '2'];
2062     /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
2063     /// ```
2064     ///
2065     /// A more complex pattern, using a closure:
2066     ///
2067     /// ```
2068     /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
2069     /// ```
2070     #[must_use = "this returns the trimmed string as a new slice, \
2071                   without modifying the original"]
2072     #[stable(feature = "trim_direction", since = "1.30.0")]
2073     pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str
2074     where
2075         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2076     {
2077         let mut j = 0;
2078         let mut matcher = pat.into_searcher(self);
2079         if let Some((_, b)) = matcher.next_reject_back() {
2080             j = b;
2081         }
2082         // SAFETY: `Searcher` is known to return valid indices.
2083         unsafe { self.get_unchecked(0..j) }
2084     }
2085
2086     /// Returns a string slice with all prefixes that match a pattern
2087     /// repeatedly removed.
2088     ///
2089     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2090     /// function or closure that determines if a character matches.
2091     ///
2092     /// [`char`]: prim@char
2093     /// [pattern]: self::pattern
2094     ///
2095     /// # Text directionality
2096     ///
2097     /// A string is a sequence of bytes. 'Left' in this context means the first
2098     /// position of that byte string; for a language like Arabic or Hebrew
2099     /// which are 'right to left' rather than 'left to right', this will be
2100     /// the _right_ side, not the left.
2101     ///
2102     /// # Examples
2103     ///
2104     /// Basic usage:
2105     ///
2106     /// ```
2107     /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
2108     /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
2109     ///
2110     /// let x: &[_] = &['1', '2'];
2111     /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
2112     /// ```
2113     #[stable(feature = "rust1", since = "1.0.0")]
2114     #[rustc_deprecated(
2115         since = "1.33.0",
2116         reason = "superseded by `trim_start_matches`",
2117         suggestion = "trim_start_matches"
2118     )]
2119     pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2120         self.trim_start_matches(pat)
2121     }
2122
2123     /// Returns a string slice with all suffixes that match a pattern
2124     /// repeatedly removed.
2125     ///
2126     /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2127     /// function or closure that determines if a character matches.
2128     ///
2129     /// [`char`]: prim@char
2130     /// [pattern]: self::pattern
2131     ///
2132     /// # Text directionality
2133     ///
2134     /// A string is a sequence of bytes. 'Right' in this context means the last
2135     /// position of that byte string; for a language like Arabic or Hebrew
2136     /// which are 'right to left' rather than 'left to right', this will be
2137     /// the _left_ side, not the right.
2138     ///
2139     /// # Examples
2140     ///
2141     /// Simple patterns:
2142     ///
2143     /// ```
2144     /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
2145     /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
2146     ///
2147     /// let x: &[_] = &['1', '2'];
2148     /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
2149     /// ```
2150     ///
2151     /// A more complex pattern, using a closure:
2152     ///
2153     /// ```
2154     /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
2155     /// ```
2156     #[stable(feature = "rust1", since = "1.0.0")]
2157     #[rustc_deprecated(
2158         since = "1.33.0",
2159         reason = "superseded by `trim_end_matches`",
2160         suggestion = "trim_end_matches"
2161     )]
2162     pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str
2163     where
2164         P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2165     {
2166         self.trim_end_matches(pat)
2167     }
2168
2169     /// Parses this string slice into another type.
2170     ///
2171     /// Because `parse` is so general, it can cause problems with type
2172     /// inference. As such, `parse` is one of the few times you'll see
2173     /// the syntax affectionately known as the 'turbofish': `::<>`. This
2174     /// helps the inference algorithm understand specifically which type
2175     /// you're trying to parse into.
2176     ///
2177     /// `parse` can parse any type that implements the [`FromStr`] trait.
2178
2179     ///
2180     /// # Errors
2181     ///
2182     /// Will return [`Err`] if it's not possible to parse this string slice into
2183     /// the desired type.
2184     ///
2185     /// [`Err`]: FromStr::Err
2186     ///
2187     /// # Examples
2188     ///
2189     /// Basic usage
2190     ///
2191     /// ```
2192     /// let four: u32 = "4".parse().unwrap();
2193     ///
2194     /// assert_eq!(4, four);
2195     /// ```
2196     ///
2197     /// Using the 'turbofish' instead of annotating `four`:
2198     ///
2199     /// ```
2200     /// let four = "4".parse::<u32>();
2201     ///
2202     /// assert_eq!(Ok(4), four);
2203     /// ```
2204     ///
2205     /// Failing to parse:
2206     ///
2207     /// ```
2208     /// let nope = "j".parse::<u32>();
2209     ///
2210     /// assert!(nope.is_err());
2211     /// ```
2212     #[inline]
2213     #[stable(feature = "rust1", since = "1.0.0")]
2214     pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
2215         FromStr::from_str(self)
2216     }
2217
2218     /// Checks if all characters in this string are within the ASCII range.
2219     ///
2220     /// # Examples
2221     ///
2222     /// ```
2223     /// let ascii = "hello!\n";
2224     /// let non_ascii = "Grüße, Jürgen ❤";
2225     ///
2226     /// assert!(ascii.is_ascii());
2227     /// assert!(!non_ascii.is_ascii());
2228     /// ```
2229     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2230     #[inline]
2231     pub fn is_ascii(&self) -> bool {
2232         // We can treat each byte as character here: all multibyte characters
2233         // start with a byte that is not in the ascii range, so we will stop
2234         // there already.
2235         self.as_bytes().is_ascii()
2236     }
2237
2238     /// Checks that two strings are an ASCII case-insensitive match.
2239     ///
2240     /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2241     /// but without allocating and copying temporaries.
2242     ///
2243     /// # Examples
2244     ///
2245     /// ```
2246     /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2247     /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2248     /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2249     /// ```
2250     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2251     #[inline]
2252     pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
2253         self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
2254     }
2255
2256     /// Converts this string to its ASCII upper case equivalent in-place.
2257     ///
2258     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2259     /// but non-ASCII letters are unchanged.
2260     ///
2261     /// To return a new uppercased value without modifying the existing one, use
2262     /// [`to_ascii_uppercase()`].
2263     ///
2264     /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
2265     ///
2266     /// # Examples
2267     ///
2268     /// ```
2269     /// let mut s = String::from("Grüße, Jürgen ❤");
2270     ///
2271     /// s.make_ascii_uppercase();
2272     ///
2273     /// assert_eq!("GRüßE, JüRGEN ❤", s);
2274     /// ```
2275     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2276     #[inline]
2277     pub fn make_ascii_uppercase(&mut self) {
2278         // SAFETY: safe because we transmute two types with the same layout.
2279         let me = unsafe { self.as_bytes_mut() };
2280         me.make_ascii_uppercase()
2281     }
2282
2283     /// Converts this string to its ASCII lower case equivalent in-place.
2284     ///
2285     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2286     /// but non-ASCII letters are unchanged.
2287     ///
2288     /// To return a new lowercased value without modifying the existing one, use
2289     /// [`to_ascii_lowercase()`].
2290     ///
2291     /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
2292     ///
2293     /// # Examples
2294     ///
2295     /// ```
2296     /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
2297     ///
2298     /// s.make_ascii_lowercase();
2299     ///
2300     /// assert_eq!("grÜße, jÜrgen ❤", s);
2301     /// ```
2302     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2303     #[inline]
2304     pub fn make_ascii_lowercase(&mut self) {
2305         // SAFETY: safe because we transmute two types with the same layout.
2306         let me = unsafe { self.as_bytes_mut() };
2307         me.make_ascii_lowercase()
2308     }
2309
2310     /// Return an iterator that escapes each char in `self` with [`char::escape_debug`].
2311     ///
2312     /// Note: only extended grapheme codepoints that begin the string will be
2313     /// escaped.
2314     ///
2315     /// # Examples
2316     ///
2317     /// As an iterator:
2318     ///
2319     /// ```
2320     /// for c in "❤\n!".escape_debug() {
2321     ///     print!("{}", c);
2322     /// }
2323     /// println!();
2324     /// ```
2325     ///
2326     /// Using `println!` directly:
2327     ///
2328     /// ```
2329     /// println!("{}", "❤\n!".escape_debug());
2330     /// ```
2331     ///
2332     ///
2333     /// Both are equivalent to:
2334     ///
2335     /// ```
2336     /// println!("❤\\n!");
2337     /// ```
2338     ///
2339     /// Using `to_string`:
2340     ///
2341     /// ```
2342     /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
2343     /// ```
2344     #[stable(feature = "str_escape", since = "1.34.0")]
2345     pub fn escape_debug(&self) -> EscapeDebug<'_> {
2346         let mut chars = self.chars();
2347         EscapeDebug {
2348             inner: chars
2349                 .next()
2350                 .map(|first| first.escape_debug_ext(true))
2351                 .into_iter()
2352                 .flatten()
2353                 .chain(chars.flat_map(CharEscapeDebugContinue)),
2354         }
2355     }
2356
2357     /// Return an iterator that escapes each char in `self` with [`char::escape_default`].
2358     ///
2359     /// # Examples
2360     ///
2361     /// As an iterator:
2362     ///
2363     /// ```
2364     /// for c in "❤\n!".escape_default() {
2365     ///     print!("{}", c);
2366     /// }
2367     /// println!();
2368     /// ```
2369     ///
2370     /// Using `println!` directly:
2371     ///
2372     /// ```
2373     /// println!("{}", "❤\n!".escape_default());
2374     /// ```
2375     ///
2376     ///
2377     /// Both are equivalent to:
2378     ///
2379     /// ```
2380     /// println!("\\u{{2764}}\\n!");
2381     /// ```
2382     ///
2383     /// Using `to_string`:
2384     ///
2385     /// ```
2386     /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
2387     /// ```
2388     #[stable(feature = "str_escape", since = "1.34.0")]
2389     pub fn escape_default(&self) -> EscapeDefault<'_> {
2390         EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
2391     }
2392
2393     /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`].
2394     ///
2395     /// # Examples
2396     ///
2397     /// As an iterator:
2398     ///
2399     /// ```
2400     /// for c in "❤\n!".escape_unicode() {
2401     ///     print!("{}", c);
2402     /// }
2403     /// println!();
2404     /// ```
2405     ///
2406     /// Using `println!` directly:
2407     ///
2408     /// ```
2409     /// println!("{}", "❤\n!".escape_unicode());
2410     /// ```
2411     ///
2412     ///
2413     /// Both are equivalent to:
2414     ///
2415     /// ```
2416     /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
2417     /// ```
2418     ///
2419     /// Using `to_string`:
2420     ///
2421     /// ```
2422     /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
2423     /// ```
2424     #[stable(feature = "str_escape", since = "1.34.0")]
2425     pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
2426         EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
2427     }
2428 }
2429
2430 #[stable(feature = "rust1", since = "1.0.0")]
2431 impl AsRef<[u8]> for str {
2432     #[inline]
2433     fn as_ref(&self) -> &[u8] {
2434         self.as_bytes()
2435     }
2436 }
2437
2438 #[stable(feature = "rust1", since = "1.0.0")]
2439 impl Default for &str {
2440     /// Creates an empty str
2441     #[inline]
2442     fn default() -> Self {
2443         ""
2444     }
2445 }
2446
2447 #[stable(feature = "default_mut_str", since = "1.28.0")]
2448 impl Default for &mut str {
2449     /// Creates an empty mutable str
2450     #[inline]
2451     fn default() -> Self {
2452         // SAFETY: The empty string is valid UTF-8.
2453         unsafe { from_utf8_unchecked_mut(&mut []) }
2454     }
2455 }
2456
2457 impl_fn_for_zst! {
2458     /// A nameable, cloneable fn type
2459     #[derive(Clone)]
2460     struct LinesAnyMap impl<'a> Fn = |line: &'a str| -> &'a str {
2461         let l = line.len();
2462         if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
2463         else { line }
2464     };
2465
2466     #[derive(Clone)]
2467     struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
2468         c.escape_debug_ext(false)
2469     };
2470
2471     #[derive(Clone)]
2472     struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
2473         c.escape_unicode()
2474     };
2475     #[derive(Clone)]
2476     struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
2477         c.escape_default()
2478     };
2479
2480     #[derive(Clone)]
2481     struct IsWhitespace impl Fn = |c: char| -> bool {
2482         c.is_whitespace()
2483     };
2484
2485     #[derive(Clone)]
2486     struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
2487         byte.is_ascii_whitespace()
2488     };
2489
2490     #[derive(Clone)]
2491     struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
2492         !s.is_empty()
2493     };
2494
2495     #[derive(Clone)]
2496     struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
2497         !s.is_empty()
2498     };
2499
2500     #[derive(Clone)]
2501     struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
2502         // SAFETY: not safe
2503         unsafe { from_utf8_unchecked(bytes) }
2504     };
2505 }