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