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